bun-query-builder 0.3.7 → 0.3.8

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.
@@ -3,5 +3,5 @@ class At{config;entityMappings=new Map;constructor(t){if(this.config=t,t.entityM
3
3
  `)+`
4
4
  `,A=g.map((T)=>T.toLowerCase()).join(";"),k=await w(n),M=[t,y,d,D,A,k].join(`
5
5
  `),K=await w(M),P="AWS4-HMAC-SHA256",_=`${c}/${a}/${s}/aws4_request`,L=[P,l,_,K].join(`
6
- `),O=await G(r.secretAccessKey,c,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class z{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await W("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let c=JSON.parse(o);l=c.message??c.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function x(t){return new z(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,N=null;function Nt(t){p={...p,...t},B=null,N=null}function h(){if(!B)B=x({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!N)N=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return N}class Ye{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=h(),n=b(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=h(),n=b(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let c=new e(l);return c._exists=!0,c}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=h(),n=b(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let c=[],y={},d={},m=0;for(let[g,D]of Object.entries(l)){let A=`#attr${m}`,k=`:val${m}`;y[A]=g,d[k]=n.marshall({v:D}).v,c.push(`${A} = ${k}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:d});for(let[g,D]of Object.entries(l))this._attributes[g]=D,this[g]=D;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=h(),i=b(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=b(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let c=o.values.map((y,d)=>`:flt${r}_${d}`);o.values.forEach((y,d)=>{n[`:flt${r}_${d}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${c.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let c=`:flt${r}a`,y=`:flt${r}b`;n[c]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${c} AND ${y}`)}else if(o.operator==="begins_with"){let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${c})`)}else{let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${c}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=h(),e=b(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=h(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=b();if(e)this._startKey=e;this._limitValue=t;let n=h(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let c=i.unmarshall(l),y=new this.ModelClass(c);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function v(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function Ne(t){let e=Xe(t);return Ze(e)}function Xe(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Ze(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Me(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),c=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!c.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,d=e.streamSpecification?.enabled;if(y!==d)if(d)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:v(e)}}function Mt(t,e){return v(t)===v(e)}var f="_qb_migrations",E="MIGRATION",C="VERSION";class Y{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(f),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${f}`),await this.client.createTable({TableName:f,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(f),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${E}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:v(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:f,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:f,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${E}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${E}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:f,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Oe{client;tracker;config;constructor(t){this.config=t,this.client=x({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new Y(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=Ne(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Me(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function et(t){return new Oe(t)}async function Ot(t,e){return et(e).migrateModels(t)}class tt{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((c,y)=>`:flt${r}_${y}`);s.values.forEach((c,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:c}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=u(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new tt(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[c,y]of Object.entries(i.update.set)){let d=`#set${o}`,m=`:set${o}`;a[d]=c,s[m]=this.driver.marshall({v:y}).v,l.push(`${d} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[c,y]of Object.entries(i.update.add)){let d=`#add${o}`,m=`:add${o}`;a[d]=c,s[m]={N:String(y)},l.push(`${d} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let c of i.update.remove){let y=`#rem${o}`;a[y]=c,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var tn=new I;function nn(){return new I}
7
- export{At,u,z,x,Nt,Ye,v,Ne,Xe,Ze,Me,Mt,f,Y,Oe,et,Ot,tt,tn,nn};
6
+ `),O=await G(r.secretAccessKey,c,a,s),U=await S(O,L),j=Array.from(new Uint8Array(U)).map((T)=>T.toString(16).padStart(2,"0")).join(""),V=`${P} Credential=${r.accessKeyId}/${_}, SignedHeaders=${A}, Signature=${j}`;return{...m,authorization:V}}class z{config;endpoint;credentials;constructor(t){if(this.config=t,this.endpoint=t.endpoint??`https://dynamodb.${t.region}.amazonaws.com`,this.credentials=t.credentials??{accessKeyId:process.env.AWS_ACCESS_KEY_ID??"",secretAccessKey:process.env.AWS_SECRET_ACCESS_KEY??"",sessionToken:process.env.AWS_SESSION_TOKEN},!this.credentials.accessKeyId||!this.credentials.secretAccessKey)throw Error("AWS credentials not provided. Set credentials in config or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY environment variables.")}async execute(t,e){let i=new URL(this.endpoint),n=JSON.stringify(e),r={"content-type":"application/x-amz-json-1.0","x-amz-target":`DynamoDB_20120810.${t}`},a=await W("POST",i,r,n,this.credentials,this.config.region,"dynamodb"),s=await fetch(i.toString(),{method:"POST",headers:a,body:n});if(!s.ok){let o=await s.text(),l;try{let c=JSON.parse(o);l=c.message??c.Message??o}catch{l=o}throw Error(`DynamoDB ${t} failed: ${s.status} - ${l}`)}return s.json()}async query(t){return this.execute("Query",t)}async scan(t){return this.execute("Scan",t)}async getItem(t){return this.execute("GetItem",t)}async putItem(t){return this.execute("PutItem",t)}async updateItem(t){return this.execute("UpdateItem",t)}async deleteItem(t){return this.execute("DeleteItem",t)}async batchGetItem(t){return this.execute("BatchGetItem",t)}async batchWriteItem(t){return this.execute("BatchWriteItem",t)}async transactWriteItems(t){return this.execute("TransactWriteItems",t)}async describeTable(t){return this.execute("DescribeTable",{TableName:t})}async createTable(t){return this.execute("CreateTable",t)}async deleteTable(t){return this.execute("DeleteTable",{TableName:t})}async listTables(t){return this.execute("ListTables",t??{})}async updateTable(t){return this.execute("UpdateTable",t)}async updateTimeToLive(t){return this.execute("UpdateTimeToLive",t)}async describeTimeToLive(t){return this.execute("DescribeTimeToLive",{TableName:t})}}function x(t){return new z(t)}var p={region:process.env.AWS_REGION??"us-east-1"},B=null,N=null;function Mt(t){p={...p,...t},B=null,N=null}function h(){if(!B)B=x({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return B}function b(){if(!N)N=u({region:p.region??"us-east-1",endpoint:p.endpoint,credentials:p.credentials});return N}class Ye{static tableName="";static pkAttribute="pk";static skAttribute="sk";static pkPrefix="";static skPrefix="METADATA";static entityTypeAttribute="_et";static keyDelimiter="#";static primaryKey="id";static timestamps=!0;static createdAtField="createdAt";static updatedAtField="updatedAt";_attributes={};_original={};_exists=!1;constructor(t={}){this._attributes={...t},this._original={...t};for(let[e,i]of Object.entries(t))this[e]=i}static query(){return new R(this)}static async find(t){let e=this,i=h(),n=b(),r=`${e.pkPrefix}${e.keyDelimiter}${t}`,a=e.skPrefix;try{let s=await i.getItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:r,[e.skAttribute]:a})});if(!s.Item)return null;let o=n.unmarshall(s.Item),l=new e(o);return l._exists=!0,l}catch(s){return console.error("Find error:",s),null}}static async findOrFail(t){let e=await this.find(t);if(!e)throw Error(`${this.name} not found with id: ${t}`);return e}static async all(){return this.query().get()}static async create(t){let e=this,i=h(),n=b(),r=t[e.primaryKey];if(!r)throw Error(`${e.primaryKey} is required`);let a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t,[e.pkAttribute]:a,[e.skAttribute]:s,[e.entityTypeAttribute]:e.name};if(e.timestamps)l[e.createdAtField]=o,l[e.updatedAtField]=o;await i.putItem({TableName:e.tableName,Item:n.marshall(l),ConditionExpression:`attribute_not_exists(${e.pkAttribute})`});let c=new e(l);return c._exists=!0,c}static async updateOrCreate(t,e){let i=this,n=t[i.primaryKey],r=await i.find(n);if(r)return await r.update(e),r;return i.create({...t,...e})}static where(t,e,i){return this.query().where(t,e,i)}static wherePk(t){return this.query().wherePk(t)}getKey(){let t=this.constructor;return this[t.primaryKey]}getAttribute(t){return this._attributes[t]}setAttribute(t,e){return this._attributes[t]=e,this[t]=e,this}getAttributes(){return{...this._attributes}}isDirty(t){if(t)return this._attributes[t]!==this._original[t];return JSON.stringify(this._attributes)!==JSON.stringify(this._original)}getDirty(){let t={};for(let[e,i]of Object.entries(this._attributes))if(i!==this._original[e])t[e]=i;return t}async save(){if(this._exists){let t=this.getDirty();if(Object.keys(t).length>0)await this.update(t)}else{let e=await this.constructor.create(this._attributes);this._attributes=e._attributes,this._original={...this._attributes},this._exists=!0}return this}async update(t){let e=this.constructor,i=h(),n=b(),r=this.getKey(),a=`${e.pkPrefix}${e.keyDelimiter}${r}`,s=e.skPrefix,o=new Date().toISOString(),l={...t};if(e.timestamps)l[e.updatedAtField]=o;let c=[],y={},d={},m=0;for(let[g,D]of Object.entries(l)){let A=`#attr${m}`,k=`:val${m}`;y[A]=g,d[k]=n.marshall({v:D}).v,c.push(`${A} = ${k}`),m++}await i.updateItem({TableName:e.tableName,Key:n.marshall({[e.pkAttribute]:a,[e.skAttribute]:s}),UpdateExpression:`SET ${c.join(", ")}`,ExpressionAttributeNames:y,ExpressionAttributeValues:d});for(let[g,D]of Object.entries(l))this._attributes[g]=D,this[g]=D;return this._original={...this._attributes},this}async delete(){let t=this.constructor,e=h(),i=b(),n=this.getKey(),r=`${t.pkPrefix}${t.keyDelimiter}${n}`,a=t.skPrefix;return await e.deleteItem({TableName:t.tableName,Key:i.marshall({[t.pkAttribute]:r,[t.skAttribute]:a})}),this._exists=!1,!0}async refresh(){let e=await this.constructor.find(this.getKey());if(e){this._attributes=e._attributes,this._original={...this._attributes};for(let[i,n]of Object.entries(this._attributes))this[i]=n}return this}toObject(){let t=this.constructor,e={...this._attributes};return delete e[t.pkAttribute],delete e[t.skAttribute],delete e[t.entityTypeAttribute],e}toJSON(){return this.toObject()}}class R{ModelClass;_pkValue;_skCondition;_indexName;_filterConditions=[];_projectionAttrs=[];_limitValue;_scanForward=!0;_consistentReadValue=!1;_startKey;constructor(t){this.ModelClass=t}wherePk(t){return this._pkValue=`${this.ModelClass.pkPrefix}${this.ModelClass.keyDelimiter}${t}`,this}where(t,e,i){if(i===void 0)this._filterConditions.push({attribute:t,operator:"=",value:e});else this._filterConditions.push({attribute:t,operator:e,value:i});return this}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}whereBetween(t,e,i){return this._filterConditions.push({attribute:t,operator:"BETWEEN",value:e,values:[e,i]}),this}whereBeginsWith(t,e){return this._filterConditions.push({attribute:t,operator:"begins_with",value:e}),this}whereExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_exists"}),this}whereNotExists(t){return this._filterConditions.push({attribute:t,operator:"attribute_not_exists"}),this}orderBy(t){return this._scanForward=t==="asc",this}limit(t){return this._limitValue=t,this}select(...t){return this._projectionAttrs.push(...t),this}index(t){return this._indexName=t,this}consistentRead(){return this._consistentReadValue=!0,this}startFrom(t){return this._startKey=t,this}buildRequest(){let t=b(),e={TableName:this.ModelClass.tableName};if(this._indexName)e.IndexName=this._indexName;let i={},n={},r=0,a=[];if(this._pkValue){let s=`#pk${r}`,o=`:pk${r}`;i[s]=this.ModelClass.pkAttribute,n[o]={S:this._pkValue},a.push(`${s} = ${o}`),r++}if(this._skCondition){let s=`#sk${r}`;switch(i[s]=this.ModelClass.skAttribute,this._skCondition.type){case"eq":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`${s} = ${o}`);break}case"begins_with":{let o=`:sk${r}`;n[o]={S:this._skCondition.value},a.push(`begins_with(${s}, ${o})`);break}}r++}if(a.length>0)e.KeyConditionExpression=a.join(" AND ");if(this._filterConditions.length>0){let s=[];for(let o of this._filterConditions){let l=`#flt${r}`;if(i[l]=o.attribute,o.operator==="attribute_exists")s.push(`attribute_exists(${l})`);else if(o.operator==="attribute_not_exists")s.push(`attribute_not_exists(${l})`);else if(o.operator==="IN"&&o.values){let c=o.values.map((y,d)=>`:flt${r}_${d}`);o.values.forEach((y,d)=>{n[`:flt${r}_${d}`]=t.marshall({v:y}).v}),s.push(`${l} IN (${c.join(", ")})`)}else if(o.operator==="BETWEEN"&&o.values){let c=`:flt${r}a`,y=`:flt${r}b`;n[c]=t.marshall({v:o.values[0]}).v,n[y]=t.marshall({v:o.values[1]}).v,s.push(`${l} BETWEEN ${c} AND ${y}`)}else if(o.operator==="begins_with"){let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`begins_with(${l}, ${c})`)}else{let c=`:flt${r}`;n[c]=t.marshall({v:o.value}).v,s.push(`${l} ${o.operator} ${c}`)}r++}e.FilterExpression=s.join(" AND ")}if(this._projectionAttrs.length>0){let s=[];for(let o of this._projectionAttrs){let l=`#proj${r}`;i[l]=o,s.push(l),r++}e.ProjectionExpression=s.join(", ")}if(Object.keys(i).length>0)e.ExpressionAttributeNames=i;if(Object.keys(n).length>0)e.ExpressionAttributeValues=n;if(this._limitValue!==void 0)e.Limit=this._limitValue;if(e.ScanIndexForward=this._scanForward,this._consistentReadValue)e.ConsistentRead=!0;if(this._startKey)e.ExclusiveStartKey=t.marshall(this._startKey);return e}async get(){let t=h(),e=b(),i=this.buildRequest();return((this._pkValue!==void 0?await t.query(i):await t.scan(i)).Items??[]).map((s)=>{let o=e.unmarshall(s),l=new this.ModelClass(o);return l._exists=!0,l})}async first(){return this._limitValue=1,(await this.get())[0]??null}async count(){let t=h(),e=this.buildRequest();return e.Select="COUNT",(this._pkValue!==void 0?await t.query(e):await t.scan(e)).Count??0}async paginate(t,e){let i=b();if(e)this._startKey=e;this._limitValue=t;let n=h(),r=this.buildRequest(),s=this._pkValue!==void 0?await n.query(r):await n.scan(r);return{items:(s.Items??[]).map((l)=>{let c=i.unmarshall(l),y=new this.ModelClass(c);return y._exists=!0,y}),lastKey:s.LastEvaluatedKey?i.unmarshall(s.LastEvaluatedKey):void 0}}}function v(t){let e=JSON.stringify({tableName:t.tableName,keySchema:t.keySchema,attributeDefinitions:[...t.attributeDefinitions||[]].sort((n,r)=>n.name.localeCompare(r.name)),globalSecondaryIndexes:[...t.globalSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),localSecondaryIndexes:[...t.localSecondaryIndexes||[]].sort((n,r)=>n.indexName.localeCompare(r.indexName)),billingMode:t.billingMode,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamSpecification}),i=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return Math.abs(i).toString(16).padStart(8,"0")}function Me(t){let e=Xe(t);return Ze(e)}function Xe(t){return{tableName:t.tableName||"",pkAttribute:t.pkAttribute||"pk",skAttribute:t.skAttribute||"sk",pkPrefix:t.pkPrefix||"",skPrefix:t.skPrefix||"METADATA",entityTypeAttribute:t.entityTypeAttribute||"_et",timestamps:t.timestamps!==!1,ttlAttribute:t.ttlAttribute,gsis:t.gsis,lsis:t.lsis,billingMode:t.billingMode||"PAY_PER_REQUEST",provisionedThroughput:t.provisionedThroughput,streamEnabled:t.streamEnabled,streamViewType:t.streamViewType}}function Ze(t){let e=[{name:t.pkAttribute,type:"S"},{name:t.skAttribute,type:"S"}],i=[];if(t.gsis)for(let n of t.gsis){if(!e.some((r)=>r.name===n.pkAttribute))e.push({name:n.pkAttribute,type:"S"});if(n.skAttribute&&!e.some((r)=>r.name===n.skAttribute))e.push({name:n.skAttribute,type:"S"});i.push({indexName:n.indexName,keySchema:{partitionKey:n.pkAttribute,sortKey:n.skAttribute},projection:{type:Array.isArray(n.projection)?"INCLUDE":n.projection||"ALL",nonKeyAttributes:Array.isArray(n.projection)?n.projection:void 0},provisionedThroughput:n.provisionedThroughput})}return{tableName:t.tableName,keySchema:{partitionKey:t.pkAttribute,sortKey:t.skAttribute},attributeDefinitions:e,globalSecondaryIndexes:i.length>0?i:void 0,billingMode:t.billingMode,provisionedThroughput:t.provisionedThroughput,ttlAttribute:t.ttlAttribute,streamSpecification:t.streamEnabled?{enabled:!0,viewType:t.streamViewType||"NEW_AND_OLD_IMAGES"}:void 0}}function Ne(t,e){let i=[],n=e.tableName;if(!t)i.push({type:"CREATE_TABLE",tableName:n,details:{definition:e}});else{let r=t.keySchema.partitionKey!==e.keySchema.partitionKey,a=t.keySchema.sortKey!==e.keySchema.sortKey;if(r||a)console.warn(`[Migration] Table ${n}: Key schema changes require table recreation. Current: pk=${t.keySchema.partitionKey}, sk=${t.keySchema.sortKey}. Target: pk=${e.keySchema.partitionKey}, sk=${e.keySchema.sortKey}. This operation is not supported automatically.`);let s=t.globalSecondaryIndexes||[],o=e.globalSecondaryIndexes||[],l=new Set(s.map((m)=>m.indexName)),c=new Set(o.map((m)=>m.indexName));for(let m of o)if(!l.has(m.indexName))i.push({type:"ADD_GSI",tableName:n,details:{gsi:m}});for(let m of s)if(!c.has(m.indexName))i.push({type:"DELETE_GSI",tableName:n,details:{indexName:m.indexName}});if(t.billingMode!==e.billingMode&&e.billingMode)i.push({type:"UPDATE_BILLING_MODE",tableName:n,details:{billingMode:e.billingMode,provisionedThroughput:e.provisionedThroughput}});if(t.ttlAttribute!==e.ttlAttribute)i.push({type:"UPDATE_TTL",tableName:n,details:{ttlAttribute:e.ttlAttribute||null,enabled:!!e.ttlAttribute}});let y=t.streamSpecification?.enabled,d=e.streamSpecification?.enabled;if(y!==d)if(d)i.push({type:"ENABLE_STREAM",tableName:n,details:{viewType:e.streamSpecification?.viewType||"NEW_AND_OLD_IMAGES"}});else i.push({type:"DISABLE_STREAM",tableName:n,details:{}})}return{tableName:n,operations:i,timestamp:new Date().toISOString(),hash:v(e)}}function Nt(t,e){return v(t)===v(e)}var f="_qb_migrations",E="MIGRATION",C="VERSION";class Y{client;initialized=!1;constructor(t){this.client=t}async ensureMigrationsTable(){if(this.initialized)return;try{await this.client.describeTable(f),this.initialized=!0}catch(t){if(t.message?.includes("ResourceNotFoundException")||t.message?.includes("not found"))console.log(`[Migration] Creating migrations table: ${f}`),await this.client.createTable({TableName:f,KeySchema:[{AttributeName:"pk",KeyType:"HASH"},{AttributeName:"sk",KeyType:"RANGE"}],AttributeDefinitions:[{AttributeName:"pk",AttributeType:"S"},{AttributeName:"sk",AttributeType:"S"}],BillingMode:"PAY_PER_REQUEST"}),await this.waitForTableActive(f),this.initialized=!0;else throw t}}async waitForTableActive(t,e=30){for(let i=0;i<e;i++){try{if((await this.client.describeTable(t)).Table?.TableStatus==="ACTIVE")return}catch{}await new Promise((n)=>setTimeout(n,1000))}throw Error(`Table ${t} did not become active within ${e} seconds`)}async getLatestState(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1,Limit:1});if(!i.Items||i.Items.length===0)return null;return this.unmarshallState(i.Items[0])}async getHistory(t){await this.ensureMigrationsTable();let e=`${E}#${t}`,i=await this.client.query({TableName:f,KeyConditionExpression:"pk = :pk",ExpressionAttributeValues:{":pk":{S:e}},ScanIndexForward:!1});if(!i.Items)return[];return i.Items.map((n)=>this.unmarshallState(n))}async recordMigration(t,e,i){await this.ensureMigrationsTable();let n=await this.getLatestState(t),r=i??(n?n.version+1:1),a=`${E}#${t}`,s=`${C}#${String(r).padStart(6,"0")}`,o={tableName:t,hash:v(e),definition:e,appliedAt:new Date().toISOString(),version:r};return await this.client.putItem({TableName:f,Item:this.marshallState(o,a,s)}),console.log(`[Migration] Recorded migration for ${t} (version ${r})`),o}async listTrackedTables(){await this.ensureMigrationsTable();let t=await this.client.scan({TableName:f,ProjectionExpression:"pk"});if(!t.Items)return[];let e=new Set;for(let i of t.Items){let r=(i.pk?.S||"").replace(`${E}#`,"");if(r)e.add(r)}return Array.from(e)}async hasMigrations(t){return await this.getLatestState(t)!==null}async deleteMigrationHistory(t){await this.ensureMigrationsTable();let e=await this.getHistory(t),i=`${E}#${t}`;for(let n of e){let r=`${C}#${String(n.version).padStart(6,"0")}`;await this.client.deleteItem({TableName:f,Key:{pk:{S:i},sk:{S:r}}})}console.log(`[Migration] Deleted migration history for ${t}`)}marshallState(t,e,i){return{pk:{S:e},sk:{S:i},tableName:{S:t.tableName},hash:{S:t.hash},definition:{S:JSON.stringify(t.definition)},appliedAt:{S:t.appliedAt},version:{N:String(t.version)}}}unmarshallState(t){return{tableName:t.tableName?.S||"",hash:t.hash?.S||"",definition:JSON.parse(t.definition?.S||"{}"),appliedAt:t.appliedAt?.S||"",version:Number(t.version?.N||0)}}}class Oe{client;tracker;config;constructor(t){this.config=t,this.client=x({region:t.region,endpoint:t.endpoint,credentials:t.credentials}),this.tracker=new Y(this.client)}async execute(t){let e={tableName:t.tableName,success:!0,operations:[]};if(t.operations.length===0)return this.log(`[Migration] No changes needed for ${t.tableName}`),e;this.log(`[Migration] Executing ${t.operations.length} operations for ${t.tableName}`);try{for(let i of t.operations)await this.executeOperation(i),e.operations.push(i.type);this.log(`[Migration] Successfully applied ${e.operations.length} operations to ${t.tableName}`)}catch(i){e.success=!1,e.error=i.message,console.error(`[Migration] Failed to execute migration for ${t.tableName}:`,i)}return e}async executeOperation(t){if(this.log(`[Migration] Executing ${t.type} on ${t.tableName}`),this.config.dryRun){this.log(`[Migration] DRY RUN: Would execute ${t.type}`,t.details);return}switch(t.type){case"CREATE_TABLE":await this.createTable(t.details.definition);break;case"DELETE_TABLE":await this.deleteTable(t.tableName);break;case"ADD_GSI":await this.addGSI(t.tableName,t.details.gsi);break;case"DELETE_GSI":await this.deleteGSI(t.tableName,t.details.indexName);break;case"UPDATE_TTL":await this.updateTTL(t.tableName,t.details.ttlAttribute,t.details.enabled);break;case"UPDATE_BILLING_MODE":await this.updateBillingMode(t.tableName,t.details.billingMode,t.details.provisionedThroughput);break;case"ENABLE_STREAM":await this.enableStream(t.tableName,t.details.viewType);break;case"DISABLE_STREAM":await this.disableStream(t.tableName);break;default:throw Error(`Unknown migration operation type: ${t.type}`)}}async createTable(t){let e={TableName:t.tableName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"}],AttributeDefinitions:t.attributeDefinitions.map((i)=>({AttributeName:i.name,AttributeType:i.type})),BillingMode:t.billingMode||"PAY_PER_REQUEST"};if(t.keySchema.sortKey)e.KeySchema.push({AttributeName:t.keySchema.sortKey,KeyType:"RANGE"});if(t.billingMode==="PROVISIONED"&&t.provisionedThroughput)e.ProvisionedThroughput={ReadCapacityUnits:t.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:t.provisionedThroughput.writeCapacityUnits};if(t.globalSecondaryIndexes&&t.globalSecondaryIndexes.length>0)e.GlobalSecondaryIndexes=t.globalSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:i.keySchema.partitionKey,KeyType:"HASH"},...i.keySchema.sortKey?[{AttributeName:i.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}},...i.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:i.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:i.provisionedThroughput.writeCapacityUnits}}:{}}));if(t.localSecondaryIndexes&&t.localSecondaryIndexes.length>0)e.LocalSecondaryIndexes=t.localSecondaryIndexes.map((i)=>({IndexName:i.indexName,KeySchema:[{AttributeName:t.keySchema.partitionKey,KeyType:"HASH"},{AttributeName:i.sortKey,KeyType:"RANGE"}],Projection:{ProjectionType:i.projection.type,...i.projection.nonKeyAttributes?{NonKeyAttributes:i.projection.nonKeyAttributes}:{}}}));if(t.streamSpecification?.enabled)e.StreamSpecification={StreamEnabled:!0,StreamViewType:t.streamSpecification.viewType||"NEW_AND_OLD_IMAGES"};if(this.log(`[Migration] Creating table: ${t.tableName}`),await this.client.createTable(e),await this.waitForTableActive(t.tableName),t.ttlAttribute)await this.updateTTL(t.tableName,t.ttlAttribute,!0);this.log(`[Migration] Table created: ${t.tableName}`)}async deleteTable(t){this.log(`[Migration] Deleting table: ${t}`),await this.client.deleteTable(t),this.log(`[Migration] Table deleted: ${t}`)}async addGSI(t,e){this.log(`[Migration] Adding GSI ${e.indexName} to ${t}`);let i=await this.client.describeTable(t),n=new Set(i.Table?.AttributeDefinitions?.map((s)=>s.AttributeName)||[]),r=[];if(!n.has(e.keySchema.partitionKey))r.push({AttributeName:e.keySchema.partitionKey,AttributeType:"S"});if(e.keySchema.sortKey&&!n.has(e.keySchema.sortKey))r.push({AttributeName:e.keySchema.sortKey,AttributeType:"S"});let a={TableName:t,AttributeDefinitions:r.length>0?r:void 0,GlobalSecondaryIndexUpdates:[{Create:{IndexName:e.indexName,KeySchema:[{AttributeName:e.keySchema.partitionKey,KeyType:"HASH"},...e.keySchema.sortKey?[{AttributeName:e.keySchema.sortKey,KeyType:"RANGE"}]:[]],Projection:{ProjectionType:e.projection.type,...e.projection.nonKeyAttributes?{NonKeyAttributes:e.projection.nonKeyAttributes}:{}},...e.provisionedThroughput?{ProvisionedThroughput:{ReadCapacityUnits:e.provisionedThroughput.readCapacityUnits,WriteCapacityUnits:e.provisionedThroughput.writeCapacityUnits}}:{}}}]};await this.executeUpdateTable(a),await this.waitForGSIActive(t,e.indexName),this.log(`[Migration] GSI ${e.indexName} added to ${t}`)}async deleteGSI(t,e){this.log(`[Migration] Deleting GSI ${e} from ${t}`);let i={TableName:t,GlobalSecondaryIndexUpdates:[{Delete:{IndexName:e}}]};await this.executeUpdateTable(i),this.log(`[Migration] GSI ${e} deleted from ${t}`)}async updateTTL(t,e,i){this.log(`[Migration] Updating TTL on ${t}: ${i?e:"disabled"}`);let n={TableName:t,TimeToLiveSpecification:{Enabled:i,AttributeName:e||"ttl"}};await this.executeUpdateTimeToLive(n),this.log(`[Migration] TTL updated on ${t}`)}async updateBillingMode(t,e,i){this.log(`[Migration] Updating billing mode on ${t} to ${e}`);let n={TableName:t,BillingMode:e};if(e==="PROVISIONED"&&i)n.ProvisionedThroughput={ReadCapacityUnits:i.readCapacityUnits,WriteCapacityUnits:i.writeCapacityUnits};await this.executeUpdateTable(n),await this.waitForTableActive(t),this.log(`[Migration] Billing mode updated on ${t}`)}async enableStream(t,e){this.log(`[Migration] Enabling stream on ${t} with view type ${e}`);let i={TableName:t,StreamSpecification:{StreamEnabled:!0,StreamViewType:e}};await this.executeUpdateTable(i),await this.waitForTableActive(t),this.log(`[Migration] Stream enabled on ${t}`)}async disableStream(t){this.log(`[Migration] Disabling stream on ${t}`);let e={TableName:t,StreamSpecification:{StreamEnabled:!1}};await this.executeUpdateTable(e),await this.waitForTableActive(t),this.log(`[Migration] Stream disabled on ${t}`)}async executeUpdateTable(t){await this.client.updateTable(t)}async executeUpdateTimeToLive(t){await this.client.updateTimeToLive(t)}async waitForTableActive(t,e=60){this.log(`[Migration] Waiting for table ${t} to become active...`);for(let i=0;i<e;i++){try{let r=(await this.client.describeTable(t)).Table?.TableStatus;if(r==="ACTIVE")return;this.log(`[Migration] Table status: ${r}, waiting...`)}catch{}await new Promise((n)=>setTimeout(n,2000))}throw Error(`Table ${t} did not become active within ${e*2} seconds`)}async waitForGSIActive(t,e,i=120){this.log(`[Migration] Waiting for GSI ${e} to become active...`);for(let n=0;n<i;n++){try{let a=(await this.client.describeTable(t)).Table?.GlobalSecondaryIndexes?.find((o)=>o.IndexName===e);if(a?.IndexStatus==="ACTIVE")return;let s=a?.IndexStatus||"CREATING";this.log(`[Migration] GSI status: ${s}, waiting...`)}catch{}await new Promise((r)=>setTimeout(r,5000))}throw Error(`GSI ${e} did not become active within ${i*5} seconds`)}async migrateModel(t){let e=Me(t),i=null;try{let a=await this.client.describeTable(e.tableName);if(a.Table)i=this.tableInfoToDefinition(a.Table)}catch(a){if(!a.message?.includes("ResourceNotFoundException")&&!a.message?.includes("not found"))throw a}let n=Ne(i,e),r=await this.execute(n);if(r.success&&!this.config.dryRun)r.state=await this.tracker.recordMigration(e.tableName,e);return r}async migrateModels(t){let e=[];for(let i of t)try{let n=await this.migrateModel(i);e.push(n)}catch(n){e.push({tableName:i.tableName||"unknown",success:!1,operations:[],error:n.message})}return e}async getStatus(){let t=new Map,e=await this.tracker.listTrackedTables();for(let i of e){let n=await this.tracker.getLatestState(i);t.set(i,n)}return t}tableInfoToDefinition(t){let e={partitionKey:"",sortKey:void 0};for(let r of t.KeySchema||[])if(r.KeyType==="HASH")e.partitionKey=r.AttributeName;else if(r.KeyType==="RANGE")e.sortKey=r.AttributeName;let i=(t.AttributeDefinitions||[]).map((r)=>({name:r.AttributeName,type:r.AttributeType})),n=(t.GlobalSecondaryIndexes||[]).map((r)=>{let a={partitionKey:"",sortKey:void 0};for(let s of r.KeySchema||[])if(s.KeyType==="HASH")a.partitionKey=s.AttributeName;else if(s.KeyType==="RANGE")a.sortKey=s.AttributeName;return{indexName:r.IndexName,keySchema:a,projection:{type:r.Projection?.ProjectionType||"ALL",nonKeyAttributes:r.Projection?.NonKeyAttributes},provisionedThroughput:r.ProvisionedThroughput?{readCapacityUnits:r.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:r.ProvisionedThroughput.WriteCapacityUnits}:void 0}});return{tableName:t.TableName,keySchema:e,attributeDefinitions:i,globalSecondaryIndexes:n.length>0?n:void 0,billingMode:t.BillingModeSummary?.BillingMode||"PAY_PER_REQUEST",provisionedThroughput:t.ProvisionedThroughput?{readCapacityUnits:t.ProvisionedThroughput.ReadCapacityUnits,writeCapacityUnits:t.ProvisionedThroughput.WriteCapacityUnits}:void 0,ttlAttribute:t.TimeToLiveDescription?.AttributeName,streamSpecification:t.StreamSpecification?{enabled:t.StreamSpecification.StreamEnabled,viewType:t.StreamSpecification.StreamViewType}:void 0}}log(...t){if(this.config.verbose||this.config.dryRun)console.log(...t)}}function et(t){return new Oe(t)}async function Ot(t,e){return et(e).migrateModels(t)}class tt{driver;client;tableName;pkAttribute;skAttribute;entityTypeAttr;delimiter;_entityType;_pkValue;_skCondition;_indexName;_projectionAttrs=[];_filterConditions=[];_limitValue;_scanForward=!0;_consistentRead=!1;_startKey;constructor(t,e,i,n){this.driver=t,this.client=e,this.tableName=i,this.pkAttribute=n.pkAttribute,this.skAttribute=n.skAttribute,this.entityTypeAttr=n.entityTypeAttribute,this.delimiter=n.keyDelimiter}entity(t){return this._entityType=t,this}pk(t){return this._pkValue=t,this}get sk(){let t=this;return{equals(e){return t._skCondition={type:"eq",value:e},t},beginsWith(e){return t._skCondition={type:"begins_with",value:e},t},between(e,i){return t._skCondition={type:"between",value:e,value2:i},t},lt(e){return t._skCondition={type:"lt",value:e},t},lte(e){return t._skCondition={type:"lte",value:e},t},gt(e){return t._skCondition={type:"gt",value:e},t},gte(e){return t._skCondition={type:"gte",value:e},t}}}index(t){return this._indexName=t,this}project(...t){return this._projectionAttrs.push(...t),this}filter(t,e,i){return this._filterConditions.push({attribute:t,operator:e,value:i}),this}where(t,e){return this.filter(t,"=",e)}whereIn(t,e){return this._filterConditions.push({attribute:t,operator:"IN",values:e}),this}limit(t){return this._limitValue=t,this}asc(){return this._scanForward=!0,this}desc(){return this._scanForward=!1,this}consistent(){return this._consistentRead=!0,this}startFrom(t){return this._startKey=t,this}toRequest(){let t={TableName:this.tableName};if(this._indexName)t.IndexName=this._indexName;let e=[],i={},n={},r=0;if(this._pkValue){let a=`#pk${r}`,s=`:pk${r}`;i[a]=this.pkAttribute,n[s]={S:this._pkValue},e.push(`${a} = ${s}`),r++}if(this._skCondition){let a=`#sk${r}`;switch(i[a]=this.skAttribute,this._skCondition.type){case"eq":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} = ${s}`);break}case"begins_with":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`begins_with(${a}, ${s})`);break}case"between":{let s=`:sk${r}a`,o=`:sk${r}b`;n[s]={S:this._skCondition.value},n[o]={S:this._skCondition.value2},e.push(`${a} BETWEEN ${s} AND ${o}`);break}case"lt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} < ${s}`);break}case"lte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} <= ${s}`);break}case"gt":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} > ${s}`);break}case"gte":{let s=`:sk${r}`;n[s]={S:this._skCondition.value},e.push(`${a} >= ${s}`);break}}r++}if(e.length>0)t.KeyConditionExpression=e.join(" AND ");if(this._filterConditions.length>0){let a=[];for(let s of this._filterConditions){let o=`#flt${r}`;if(i[o]=s.attribute,s.operator==="IN"&&s.values){let l=s.values.map((c,y)=>`:flt${r}_${y}`);s.values.forEach((c,y)=>{n[`:flt${r}_${y}`]=this.driver.marshall({v:c}).v}),a.push(`${o} IN (${l.join(", ")})`)}else{let l=`:flt${r}`;n[l]=this.driver.marshall({v:s.value}).v,a.push(`${o} ${s.operator} ${l}`)}r++}t.FilterExpression=a.join(" AND ")}if(this._projectionAttrs.length>0){let a=[];for(let s of this._projectionAttrs){let o=`#proj${r}`;i[o]=s,a.push(o),r++}t.ProjectionExpression=a.join(", ")}if(Object.keys(i).length>0)t.ExpressionAttributeNames=i;if(Object.keys(n).length>0)t.ExpressionAttributeValues=n;if(this._limitValue!==void 0)t.Limit=this._limitValue;if(t.ScanIndexForward=this._scanForward,this._consistentRead)t.ConsistentRead=!0;if(this._startKey)t.ExclusiveStartKey=this.driver.marshall(this._startKey);return t}async get(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return((this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Items??[]).map((n)=>this.driver.unmarshall(n))}async first(){return this._limitValue=1,(await this.get())[0]}async getAll(){let t=[],e;do{if(e)this._startKey=e;let i=this.toRequest(),r=this._pkValue!==void 0?await this.client.query(i):await this.client.scan(i),a=(r.Items??[]).map((s)=>this.driver.unmarshall(s));t.push(...a),e=r.LastEvaluatedKey?this.driver.unmarshall(r.LastEvaluatedKey):void 0}while(e);return t}async count(){if(!this.client)throw Error("DynamoDB client not configured. Call dynamo.connection() first.");let t=this.toRequest();return t.Select="COUNT",(this._pkValue!==void 0?await this.client.query(t):await this.client.scan(t)).Count??0}}class I{driver;client;tableName="";pkAttribute="pk";skAttribute="sk";entityTypeAttr="_et";delimiter="#";entityMappings=new Map;connection(t){let e={region:t.region,tableName:t.table,endpoint:t.endpoint,credentials:t.credentials};return this.driver=u(e),this.tableName=t.table,this.pkAttribute=t.pkAttribute??"pk",this.skAttribute=t.skAttribute??"sk",this.entityTypeAttr=t.entityTypeAttribute??"_et",this.delimiter=t.keyDelimiter??"#",this}setClient(t){return this.client=t,this}registerEntity(t){if(this.entityMappings.set(t.entityType,t),this.driver)this.driver.registerEntity(t);return this}entity(t){if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");return new tt(this.driver,this.client,this.tableName,{pkAttribute:this.pkAttribute,skAttribute:this.skAttribute,entityTypeAttribute:this.entityTypeAttr,keyDelimiter:this.delimiter}).entity(t)}async batchWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity};e.push({PutRequest:{Item:this.driver.marshall(n)}})}else if(i.delete)e.push({DeleteRequest:{Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}});if(e.length>0)await this.client.batchWriteItem({RequestItems:{[this.tableName]:e}})}async transactWrite(t){if(!this.client)throw Error("DynamoDB client not configured. Call setClient() first.");if(!this.driver)throw Error("DynamoDB not configured. Call dynamo.connection() first.");let e=[];for(let i of t)if(i.put){let n={...i.put.item,[this.entityTypeAttr]:i.put.entity},r={Put:{TableName:this.tableName,Item:this.driver.marshall(n)}};if(i.put.condition)r.Put.ConditionExpression=i.put.condition;e.push(r)}else if(i.update){let n={[this.pkAttribute]:i.update.pk};if(i.update.sk)n[this.skAttribute]=i.update.sk;let r=[],a={},s={},o=0;if(i.update.set){let l=[];for(let[c,y]of Object.entries(i.update.set)){let d=`#set${o}`,m=`:set${o}`;a[d]=c,s[m]=this.driver.marshall({v:y}).v,l.push(`${d} = ${m}`),o++}if(l.length>0)r.push(`SET ${l.join(", ")}`)}if(i.update.add){let l=[];for(let[c,y]of Object.entries(i.update.add)){let d=`#add${o}`,m=`:add${o}`;a[d]=c,s[m]={N:String(y)},l.push(`${d} ${m}`),o++}if(l.length>0)r.push(`ADD ${l.join(", ")}`)}if(i.update.remove&&i.update.remove.length>0){let l=[];for(let c of i.update.remove){let y=`#rem${o}`;a[y]=c,l.push(y),o++}r.push(`REMOVE ${l.join(", ")}`)}e.push({Update:{TableName:this.tableName,Key:this.driver.marshall(n),UpdateExpression:r.join(" "),ExpressionAttributeNames:a,ExpressionAttributeValues:s}})}else if(i.delete){let n={Delete:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.delete.pk,[this.skAttribute]:i.delete.sk})}};if(i.delete.condition)n.Delete.ConditionExpression=i.delete.condition;e.push(n)}else if(i.conditionCheck)e.push({ConditionCheck:{TableName:this.tableName,Key:this.driver.marshall({[this.pkAttribute]:i.conditionCheck.pk,[this.skAttribute]:i.conditionCheck.sk}),ConditionExpression:i.conditionCheck.condition}});if(e.length>0)await this.client.transactWriteItems({TransactItems:e})}getDriver(){return this.driver}}var tn=new I;function nn(){return new I}
7
+ export{At,u,z,x,Mt,Ye,v,Me,Xe,Ze,Ne,Nt,f,Y,Oe,et,Ot,tt,tn,nn};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ht,w,R,Qe,A}from"./chunk-3htakbmy.js";import"./chunk-b5fh1hw4.js";import"./chunk-7dxm19yj.js";import"./chunk-vmptnnff.js";import"./chunk-bpwg9p8b.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
2
+ import{ht,w,R,Qe,A}from"./chunk-3b13fc8j.js";import"./chunk-vyqr0w2z.js";import"./chunk-9wck98bv.js";import"./chunk-rzfnhh9f.js";import"./chunk-bpwg9p8b.js";import"./chunk-93ny6tvm.js";export{R as executeMigration,Qe as executeMigrationWithReport,w as generateMigration,A as resetDatabase,ht as saveMigrationSnapshot};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-bpwg9p8b.js";function M(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Pe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Ue(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[Ue(s)];if(Le(a))return a.bind(o);return}})}function Pt(t){let r=(f)=>{let g=Array.isArray(f)?f:[],x=Math.floor(Math.random()*g.length);return g[x]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let x=[...Array.isArray(f)?f:[]],K=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*x.length));for(let A=x.length-1;A>0;A-=1){let E=Math.floor(Math.random()*(A+1));[x[A],x[E]]=[x[E],x[A]]}return x.slice(0,Math.min(K,x.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let x=g.length-1;x>0;x-=1){let K=Math.floor(Math.random()*(x+1));[g[x],g[K]]=[g[K],g[x]]}return g},maybe:(f,g)=>{let x=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<x?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let x=f[g];if(x&&typeof x==="object")return z(x);return x}})}function Be(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var $e=/^[A-Z_][A-Z0-9_]*$/i;function H(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!$e.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Se(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!$e.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&X(t)===0)return[];return r}var ae=null,we=new Map;function qe(t,r){we.set(t,r),re.clear()}function Bt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-baxpnvev.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Ke(t){let r=le.get(t);if(r!==void 0)return r;let o=at(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function _t(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function It(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}text(t){return this.dialect==="postgres"?Ke(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:_t(o),lastInsertId:It(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Ke(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=It(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:_t(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function Ln(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Kn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var Re=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!Re)Re=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Fn(){let t=S();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,_e=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function ze(t,r){return typeof r==="bigint"?r.toString():r}function xe(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ae=500,ye="__btm_rel__";function ee(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ee=new WeakMap;function Ge(t){let r=Ee.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ee.set(t,o),o}function Oe(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Oe(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Xe({...r}),this._original=null;let s=Ge(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=Ie(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Lt(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=C(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[C(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[C(r)]=o(this._attributes)}async save(){let t=S(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),ee(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var ve=new Map,Ne=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=ve.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ve.set(t,r),r}function G(t){let r=Ne.get(t);if(r!==void 0)return r;return r=Fe(t),Ne.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ce(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>Ce(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>Ce(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function Ie(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let R=typeof h==="string"?h:h?.model||"";if(R&&R.toLowerCase()===r.toLowerCase())return R}return null}if(typeof w==="object"){for(let[h,R]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof R==="string"?R:R?.model||R?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),R=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=R(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return R(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof w==="object"){for(let[h,R]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:R}}return null}function c(w){let h=t[w];if(!h)return null;let R=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==R)continue;let N=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(N??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let N=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==R&&N.toLowerCase()!==R)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:N,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),R=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:R,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),R=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:R,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),R=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:R,foreignKey:y,localKey:p}}let x=u();if(x){let w=typeof x.entry==="object",h=w?x.entry.model:x.entry,p=j(h)?.getTable?.()||G(h),y=w?x.entry:null,N,P;if(y?.table)N=y.table;else if(y?.through){P=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);N=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);N=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},je=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===je)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:N,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let K=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let R=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!R||typeof R!=="object")return null;let{through:p,target:y}=R;if(!p||!y)return null;let N=j(p),P=N?.getDefinition?.()||N?.definition,F=N?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},A=K(t.hasManyThrough,"hasManyThrough");if(A)return A;let E=K(t.hasOneThrough,"hasOneThrough");if(E)return E;return null}function ge(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ie(t){return m(e.relations?.singularizeStrategy)(t)}class Lt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ye}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ye))i[u.slice(ye.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=S(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=S(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=S(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((x)=>u[x]);await o.run(f,g),a++}return a}async detach(t){let r=S(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=S(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class v{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new v(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return H(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){H(t,"whereNotBetween(column)");let o=W(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=W(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:W(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${W(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=Ie(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),x=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let K=new Map;for(let A of f){let E=A[a.foreignKey];if(!K.has(E))K.set(E,[]);K.get(E).push(A)}for(let A of r){let E=K.get(A.get(s))||[];A.setRelation(t,E.map((w)=>new I(x,w,!0)))}}else{let K=new Map;for(let A of f){let E=A[a.foreignKey];if(!K.has(E))K.set(E,A)}for(let A of r){let E=K.get(A.get(s));A.setRelation(t,E?new I(x,E,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let A of r){let E=A._attributes[a.foreignKey];if(E!=null)u.add(E)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),x=g?.getDefinition?.()||g?.definition||this._definition,K=new Map;for(let A of f)K.set(A[a.localKey],A);for(let A of r){let E=A._attributes[a.foreignKey],w=K.get(E);A.setRelation(t,w?new I(x,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],x=j(a.relatedModelName),K=x?.getDefinition?.()||x?.definition||this._definition,A=K?.primaryKey||"id",E=[];if(g.length>0){let p=g.map(()=>"?").join(", ");E=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${A} IN (${p})`,g)}let w=new Map;for(let p of E)w.set(p[A],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let R=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(K,J,!0),B={};for(let[q,he]of Object.entries(F))if(!R.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let R of r)R.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let R of f)g.set(R[c],R[a.throughForeignKey]);let x=[...new Set(f.map((R)=>R[c]))],K=x.map(()=>"?").join(", "),A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${K})`,x),E=j(a.relatedModelName),w=E?.getDefinition?.()||E?.definition||this._definition,h=new Map;for(let R of A){let p=g.get(R[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,R,!0))}for(let R of r){let p=h.get(R.get(s))||[];R.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=S(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new v(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){H(t,"pluck(column)");let r=S(),o=[],s=W(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${W(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((K)=>new I(this._definition,K,!0)),g=f.map((K)=>K._attributes[c]);if(g.some((K)=>K==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let K of f)await s.beforeDelete?.(K);let x=0;for(let K=0;K<g.length;K+=Ae){let A=g.slice(K,K+Ae),E=`${c} IN (${A.map(()=>"?").join(", ")})`;x+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${E}`,[u,...A])).changes:(await r.run(`DELETE FROM ${o} WHERE ${E}`,A)).changes}for(let K of f){if(t)K._attributes[L]=u;await s.afterDelete?.(K)}return x}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function tt(t){let r={query:()=>new v(t),where(o,s,i){return new v(t).where(o,s,i)},orWhere(o,s,i){return new v(t).orWhere(o,s,i)},whereIn(o,s){return new v(t).whereIn(o,s)},whereNotIn(o,s){return new v(t).whereNotIn(o,s)},whereNull(o){return new v(t).whereNull(o)},whereNotNull(o){return new v(t).whereNotNull(o)},whereLike(o,s){return new v(t).whereLike(o,s)},orderBy(o,s="asc"){return new v(t).orderBy(o,s)},orderByDesc(o){return new v(t).orderByDesc(o)},select(...o){return new v(t).select(...o)},with(...o){return new v(t).with(...o)},limit:(o)=>new v(t).limit(o),take:(o)=>new v(t).take(o),skip:(o)=>new v(t).skip(o),withTrashed:()=>new v(t).withTrashed(),onlyTrashed:()=>new v(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new v(t).get(),first:()=>new v(t).first(),firstOrFail:()=>new v(t).firstOrFail(),last:()=>new v(t).last(),count:()=>new v(t).count(),exists:()=>new v(t).exists(),doesntExist:()=>new v(t).doesntExist(),paginate:(o,s)=>new v(t).paginate(o,s),whereBetween(o,s){return new v(t).whereBetween(o,s)},whereNotBetween(o,s){return new v(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let K of T){let A=d[K],E=Object.keys(A),w=await i.insert(E.length?`INSERT INTO ${t.table} (${E.join(", ")}) VALUES (${E.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(A),a);await s[K]._markInserted(A,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((K)=>d[K]))){let K=t.table,A=f.join(", "),E=`INSERT INTO ${K} (${A}) SELECT ${A} FROM jsonb_populate_recordset(NULL::${K}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),R=JSON.stringify(h.map((N)=>Object.fromEntries(f.map((P)=>[P,d[N][P]??null]))),ze);if(!g){await i.run(E,[R]);for(let N of h)await s[N]._markInserted(d[N]);continue}let p=(await i.all(`${E} RETURNING ${a}`,[R])).map((N)=>N[a]),y=p.every((N)=>typeof N==="number"||typeof N==="bigint")?[...p].sort((N,P)=>N<P?-1:N>P?1:0):p;for(let N=0;N<h.length;N++)await s[h[N]]._markInserted(d[h[N]],y[N])}continue}let x=xe(Math.max(1,Math.floor(Qe/f.length)));for(let K=0;K<T.length;){let A=Math.min(x,xe(T.length-K)),E=T.slice(K,K+A);K+=A;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${E.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=E.flatMap((y)=>f.map((N)=>d[y][N]));if(!g){await i.run(w,h);for(let y of E)await s[y]._markInserted(d[y]);continue}let R=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=R.every((y)=>typeof y==="number"||typeof y==="bigint")?[...R].sort((y,N)=>y<N?-1:y>N?1:0):R;for(let y=0;y<E.length;y++)await s[E[y]]._markInserted(d[E[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new v(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new v(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new v(t).orderByDesc(o),oldest:(o="created_at")=>new v(t).orderBy(o,"asc"),max:(o)=>new v(t).max(o),min:(o)=>new v(t).min(o),avg:(o)=>new v(t).avg(o),sum:(o)=>new v(t).sum(o),pluck(o){return new v(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new v(t).where(a,d)}return Reflect.get(o,s)}})}function Kt(t){let r=tt(t);if(t?.name)qe(t.name,r);return r}async function jn(t){let r=S(),o=C(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Pe(c);if(u.endsWith("_id")&&(c===void 0||M(c)))T="INTEGER";let f=`${u} ${T}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of O(t.belongsTo)){let d=a.foreignKey??`${C(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ee(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function qn(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=Pt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=Y();u.created_at=T,u.updated_at=T}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var oe=new Map;function rn(t){return oe.get(t)}function sn(){return[...oe.values()]}function an(){return Object.fromEntries(oe)}function on(t){return oe.has(t)}function ln(){oe.clear(),Bt()}function Ft(t,r){return oe.set(t,r),r}function nt(){return typeof window<"u"&&typeof document<"u"}function cn(t){let r;if(nt())r=We(t);else{let o=Kt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Ft(t.name,r),r}function un(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
- export{M,Pe,Pt,Be,O,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un};
2
+ import{We}from"./chunk-93ny6tvm.js";import{n,e,k,_,b,Fe,m,D,l,at,X}from"./chunk-bpwg9p8b.js";function N(t){return t==="integer"||t==="bigint"||t==="float"||t==="double"||t==="decimal"}function De(t){if(typeof t!=="string")return;switch(t.toLowerCase()){case"string":return"string";case"text":return"text";case"integer":case"int":return"integer";case"number":return"integer";case"bigint":return"bigint";case"float":return"float";case"double":return"double";case"decimal":return"decimal";case"boolean":case"bool":return"boolean";case"date":return"date";case"datetime":case"timestamp":return"datetime";case"timestamptz":case"timestamp_tz":return"timestamptz";case"json":return"json";case"enum":return"enum";default:return}}function Pe(t){switch(t){case"boolean":case"integer":case"bigint":return"INTEGER";case"float":case"double":case"decimal":return"REAL";default:return"TEXT"}}import{Database as Te}from"bun:sqlite";function te(t){if(typeof t==="number")return{length:t};return t}function me(t){if(typeof t==="number")return{max:t};return t}function Le(t){return typeof t==="function"}function Ue(t){return t.replace(/[A-Z]/g,(r)=>r.toLowerCase())}function ke(t,r){if(!r||typeof r.fractionDigits!=="number")return t;return Number(t.toFixed(r.fractionDigits))}function z(t,r={}){if(!t)return r;return new Proxy(t,{get(o,s){if(s in r)return r[s];let i=o[s];if(i!==void 0)return i;let a=o[Ue(s)];if(Le(a))return a.bind(o);return}})}function Pt(t){let r=(f)=>{let g=Array.isArray(f)?f:[],R=Math.floor(Math.random()*g.length);return g[R]},o=()=>t.string,s=()=>t.number,i=()=>t.random,a=z(t.string,{alpha:(f)=>o()?.alpha?.(te(f)),alphanumeric:(f)=>o()?.alphanumeric?.(te(f)),numeric:(f)=>o()?.numeric?.(te(f)),sample:(f)=>o()?.sample?.(te(f)),hexadecimal:(f)=>o()?.hexadecimal?.(te(f))}),d=z(t.number,{int:(f)=>s()?.int?.(me(f)),float:(f)=>{let g=me(f);return ke(Number(s()?.float?.(g)??0),g)}}),u=z(t.helpers,{arrayElement:r,arrayElements:(f,g)=>{let R=[...Array.isArray(f)?f:[]],M=typeof g==="number"?g:Math.max(1,Math.floor(Math.random()*R.length));for(let x=R.length-1;x>0;x-=1){let A=Math.floor(Math.random()*(x+1));[R[x],R[A]]=[R[A],R[x]]}return R.slice(0,Math.min(M,R.length))},shuffle:(f)=>{let g=[...Array.isArray(f)?f:[]];for(let R=g.length-1;R>0;R-=1){let M=Math.floor(Math.random()*(R+1));[g[R],g[M]]=[g[M],g[R]]}return g},maybe:(f,g)=>{let R=typeof g?.probability==="number"?g.probability:0.5;return Math.random()<R?f():void 0},slugify:(f)=>String(f??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}),T={string:a,number:d,helpers:u,datatype:{boolean:(f)=>{let g=typeof f==="number"?f:f?.probability;if(typeof g==="number")return Math.random()<g;return Boolean(i()?.boolean?.())},number:(f)=>Number(s()?.int?.(me(f))??0),float:(f)=>ke(Number(s()?.float?.(f)??0),f),uuid:()=>crypto.randomUUID(),string:(f)=>String(o()?.alphanumeric?.({length:f??10})??""),hexadecimal:(f)=>String(o()?.hexadecimal?.(te(f))??""),array:(f)=>Array.from({length:f??3},()=>o()?.alphanumeric?.({length:8})),json:()=>JSON.stringify({value:o()?.alphanumeric?.({length:8})})},location:z(t.address),address:z(t.address),vehicle:z(t.vehicle,{vrm:()=>t.vehicle?.registration?.()}),company:z(t.company,{catchPhrase:()=>t.company?.catchphrase?.(),buzzPhrase:()=>t.company?.bs?.()??t.company?.buzzword?.()})};return new Proxy(t,{get(f,g){if(g in T)return T[g];let R=f[g];if(R&&typeof R==="object")return z(R);return R}})}function Be(t){if(typeof t==="string")return{model:t};if(t&&typeof t==="object"&&typeof t.model==="string"){let r=t;return{model:r.model,foreignKey:r.foreignKey,onDelete:r.onDelete}}return null}function O(t){if(!t)return[];return(Array.isArray(t)?t:typeof t==="object"?Object.values(t):[]).map(Be).filter((o)=>o!==null)}function Y(){let t=new Date().toISOString();return n(e.dialect)?t.slice(0,19).replace("T"," "):t}var $e=/^[A-Z_][A-Z0-9_]*$/i;function H(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);if(t.length>64)throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' exceeds 64 chars`);if(!$e.test(t))throw TypeError(`[bun-query-builder] ${r}: identifier '${t}' contains characters outside [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Se(t,r){if(typeof t!=="string"||t.length===0)throw TypeError(`[bun-query-builder] ${r}: identifier must be a non-empty string, got ${typeof t}`);let o=t.split(".");if(o.length>2||o.some((s)=>s.length===0||s.length>64||!$e.test(s)))throw TypeError(`[bun-query-builder] ${r}: invalid ORDER BY column '${t}' \u2014 expected 'column' or 'table.column' of [A-Za-z0-9_] \u2014 refusing to interpolate into SQL`)}function Me(t,r){if(r.length!==1)return r;let o=r[0];if(Array.isArray(o))return[...o];if(o===void 0&&X(t)===0)return[];return r}var ae=null,we=new Map;function qe(t,r){we.set(t,r),re.clear()}function Bt(){we.clear(),re.clear()}function j(t){if(!ae)try{ae=import.meta.require("./chunk-82w0fmx3.js").getModel}catch{ae=()=>{return}}return ae(t)??we.get(t)}var le=new Map,He=500;function Ke(t){let r=le.get(t);if(r!==void 0)return r;let o=at(t,"postgres");if(le.size>=He)le.clear();return le.set(t,o),o}function _t(t){if(t==null)return 0;if(typeof t.affectedRows==="number")return t.affectedRows;if(typeof t.count==="number")return t.count;if(Array.isArray(t))return t.length;return 0}function It(t){if(t==null||typeof t!=="object")return null;if("insertId"in t&&t.insertId!=null)return t.insertId;if("lastInsertRowid"in t&&t.lastInsertRowid!=null)return t.lastInsertRowid;return null}class pe{sqliteDb;dialect="sqlite";constructor(t){this.sqliteDb=t}all(t,r){return Promise.resolve(this.sqliteDb.query(t).all(...r))}get(t,r){return Promise.resolve(this.sqliteDb.query(t).get(...r)??void 0)}run(t,r){let o=this.sqliteDb.run(t,r);return Promise.resolve({changes:o.changes,lastInsertId:o.lastInsertRowid})}insert(t,r){return this.run(t,r)}}class be{dialect;constructor(t){this.dialect=t}conn(){return b()}text(t){return this.dialect==="postgres"?Ke(t):t}async all(t,r){let o=await this.conn().unsafe(this.text(t),r);return Array.isArray(o)?o:[]}async get(t,r){let o=await this.conn().unsafe(this.text(t),r);if(Array.isArray(o))return o[0]??void 0;return o??void 0}async run(t,r){let o=await this.conn().unsafe(this.text(t),r);return{changes:_t(o),lastInsertId:It(o)}}async insert(t,r,o){if(this.dialect==="postgres"){let a=await this.conn().unsafe(`${Ke(t)} RETURNING ${o}`,r),d=Array.isArray(a)?a[0]:a;return{changes:1,lastInsertId:d?d[o]??null:null}}let s=await this.conn().unsafe(t,r),i=It(s);if(i==null&&this.dialect!=="sqlite"){let a=await this.conn().unsafe("SELECT LAST_INSERT_ID() as id",[]);i=(Array.isArray(a)?a[0]:a)?.id??null}return{changes:_t(s)||1,lastInsertId:i}}}var Q=null,ce=!1,U=null,ne=null,ue=null,de=null;function Ln(t){if(t.database instanceof Te)Q=t.database,ce=!1;else Q=new Te(t.database||":memory:",{create:!0}),ce=!0,k(Q);U=null,ne=null}function Kn(){let t=ce,r=Q;if(Q=null,ce=!1,U=null,ne=null,ue=null,de=null,t&&r)try{r.close()}catch{}}var Re=!1;function S(){if(Q){if(!U||ne!==Q)U=new pe(Q),ne=Q,ue="sqlite",de=null;return U}let t=e.dialect,r=e.database?.database??null,o=`${r??""}|${_()?.url??""}`;if(U&&ne===null&&ue===t&&de===o)return U;if(ne=null,ue=t,de=o,t==="sqlite"&&_())U=new be(t);else if(t==="sqlite"){if(!r&&!Re)Re=!0,console.warn("[bun-query-builder] The model layer has no database configured, so it is using an in-memory SQLite database and nothing it writes will persist. Configure one with setConfig({ dialect, database }) or configureOrm({ database }), or name ':memory:' explicitly to silence this.");let s=new Te(r||":memory:",{create:!0});k(s),U=new pe(s)}else U=new be(t);return U}function Fn(){let t=S();if(t.sqliteDb)return t.sqliteDb;throw Error(`[bun-query-builder] getDatabase() is only available for the sqlite dialect; the configured dialect is '${t.dialect}'. Use the async model API instead.`)}var Qe=4096,_e=1000;function Ve(t,r,o){let s=t.attributes,i=new Map(Object.entries(s).map(([a,d])=>[C(a),d]));for(let a of r){let d=String(i.get(a)?.type??"").toLowerCase();if(d==="json"||d==="jsonb")return!1}for(let a of o)for(let d of r){let u=a[d];if(u===null||u===void 0||u instanceof Date)continue;let c=typeof u;if(c!=="string"&&c!=="number"&&c!=="boolean"&&c!=="bigint")return!1}return!0}function ze(t,r){return typeof r==="bigint"?r.toString():r}function xe(t){return 2**Math.floor(Math.log2(t))}var L="deleted_at",Ae=500,ye="__btm_rel__";function ee(t){let r=t.traits;return Boolean(r?.useSoftDeletes||r?.softDeletable)}function Z(t){let r=t.traits;return Boolean(r?.useTimestamps||r?.timestampable)}var Ee=new WeakMap;function Ge(t){let r=Ee.get(t);if(r)return r;let o=new Set,s=t.belongsToMany;if(s){if(Array.isArray(s)){for(let i of s)if(typeof i==="string")o.add(i.toLowerCase());else if(i&&typeof i==="object"&&i.model)o.add(i.model.toLowerCase())}else if(typeof s==="object")for(let i of Object.keys(s))o.add(i)}return Ee.set(t,o),o}function Oe(t){let r={};for(let[o,s]of Object.entries(t))r[C(o)]=s;return r}function Xe(t){for(let r in t)if(C(r)!==r)return Oe(t);return t}function Ye(t,r){if(t[r])return t[r];let o=C(r);if(t[o])return t[o];for(let s of Object.keys(t))if(C(s)===o)return t[s];return}class I{_attributes;_original;_forced=new Set;_definition;_hasSaved=!1;_exists;_relations={};constructor(t,r,o){this._definition=t,this._exists=o,this._attributes=Xe({...r}),this._original=null;let s=Ge(t);if(s.size===0)return;let i=this;return new Proxy(this,{get(a,d,u){if(typeof d==="string"&&s.has(d)&&!(d in a))return()=>{let c=Ie(t,d);if(!c||c.type!=="belongsToMany")throw Error(`[orm] relation '${d}' did not resolve to a belongsToMany on '${t.name}'`);let T=j(c.relatedModelName),f=T?.getDefinition?.()||T?.definition;if(!f)throw Error(`[orm] related model '${c.relatedModelName}' is not registered`);return new Lt(i,t,c,f)};return Reflect.get(a,d,u)}})}getOriginalAttributes(){if(this._original===null)this._original={...this._attributes};return this._original}get(t){let r=this._definition.get?.[t];if(r)try{let o=r(this._attributes);if(o!==void 0)return o}catch{}return this._attributes[C(t)]}getAttribute(t){return this._attributes[C(t)]}getAttributes(){return{...this._attributes}}set(t,r){if(this._original===null)this._original={...this._attributes};this._attributes[C(t)]=r}only(t){let r={};for(let o of t)r[o]=this._attributes[C(o)];return r}except(t){let r=new Set(t.map((s)=>C(s))),o={};for(let s of Object.keys(this._attributes))if(!r.has(s))o[s]=this._attributes[s];return o}getRelation(t){return this._relations[t]}setRelation(t,r){this._relations[t]=r}getLoadedRelations(){return{...this._relations}}get attributes(){return{...this._attributes}}get id(){let t=this._definition.primaryKey||"id";return this._attributes[t]}isDirty(t){if(this._original===null)return!1;if(t){let r=C(t);return this._attributes[r]!==this._original[r]}return Object.keys(this._attributes).some((r)=>this._attributes[r]!==this._original[r])}isClean(t){return!this.isDirty(t)}getOriginal(t){return this.getOriginalAttributes()[C(t)]}getChanges(){if(this._original===null)return{};let t={};for(let r of Object.keys(this._attributes))if(this._attributes[r]!==this._original[r])t[r]=this._attributes[r];return t}fill(t){let r=this._definition.attributes;for(let[o,s]of Object.entries(t)){let i=Ye(r,o),a=!i&&C(o).endsWith("_id");if(i?.fillable&&!i?.guarded||a){if(this._original===null)this._original={...this._attributes};this._attributes[C(o)]=s}}return this}forceFill(t){if(this._original===null)this._original={...this._attributes};let r=Oe(t);Object.assign(this._attributes,r);for(let o of Object.keys(r))this._forced.add(o);return this}async _prepareInsert(){this._applySetters();let t=this._definition.primaryKey||"id",r=this._definition.hooks,o=this._definition.attributes,s={};for(let[u,c]of Object.entries(o)){if(c.guarded&&!this._forced.has(C(u)))continue;let T=C(u);if(this._attributes[T]!==void 0)s[T]=this._attributes[T]}for(let u of Object.keys(this._attributes))if(u.endsWith("_id")&&u!==t&&!(u in s))s[u]=this._attributes[u];let i=this._attributes[t],d=o[t]?.guarded&&!this._forced.has(t);if(i!=null&&!(t in s)&&!d)s[t]=i;if(Z(this._definition)){let u=Y(),c=this._attributes.created_at;s.created_at=c===void 0||c===null?u:c,s.updated_at=u}if(this._definition.traits?.useUuid&&!s.uuid)s.uuid=crypto.randomUUID();return await r?.beforeCreate?.(s),s}async _markInserted(t,r){let o=this._definition.primaryKey||"id";for(let[s,i]of Object.entries(t))this._attributes[s]=i;if(!(o in t)&&r!=null)this._attributes[o]=r;this._exists=!0,await this._definition.hooks?.afterCreate?.(this),this._original={...this._attributes},this._hasSaved=!0}_applySetters(){let t=this._definition.set||{};for(let[r,o]of Object.entries(t))if(this.isDirty(r))this._attributes[C(r)]=o(this._attributes)}async save(){let t=S(),r=this._definition.primaryKey||"id",o=this._definition.hooks;if(this._exists){this._applySetters(),await o?.beforeUpdate?.(this,this.getChanges());let s=this.getChanges(),i=Object.keys(s);if(i.length>0){if(this._attributes[r]==null)throw Error(`Cannot save a model without a primary key: '${r}' was not selected`);let a=i.map((u)=>`${u} = ?`).join(", "),d=[...Object.values(s),this._attributes[r]];if(Z(this._definition)){let u=Y();await t.run(`UPDATE ${this._definition.table} SET ${a}, updated_at = ? WHERE ${r} = ?`,[...Object.values(s),u,this._attributes[r]])}else await t.run(`UPDATE ${this._definition.table} SET ${a} WHERE ${r} = ?`,d)}await o?.afterUpdate?.(this)}else{let s=await this._prepareInsert(),i=Object.keys(s),a=i.map(()=>"?").join(", "),d=await t.insert(`INSERT INTO ${this._definition.table} (${i.join(", ")}) VALUES (${a})`,Object.values(s),r);return await this._markInserted(s,r in s?void 0:d.lastInsertId),this}return this._original={...this._attributes},this._hasSaved=!0,this}async update(t){return this.fill(t),this.save()}async fresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(o==null)return null;let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return new I(this._definition,s,!0)}async delete(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r],s=this._definition.hooks;if(o==null)throw Error("Cannot delete a model without a primary key");if(await s?.beforeDelete?.(this),ee(this._definition)){let i=Y();await t.run(`UPDATE ${this._definition.table} SET deleted_at = ? WHERE ${r} = ?`,[i,o]),this._attributes[L]=i}else await t.run(`DELETE FROM ${this._definition.table} WHERE ${r} = ?`,[o]);return await s?.afterDelete?.(this),!0}async forceDelete(){let t=this._definition.primaryKey||"id",r=this._attributes[t],o=this._definition.hooks;if(r==null)throw Error("Cannot delete a model without a primary key");return await o?.beforeDelete?.(this),await S().run(`DELETE FROM ${this._definition.table} WHERE ${t} = ?`,[r]),await o?.afterDelete?.(this),!0}async restore(){if(!ee(this._definition))throw Error(`[orm] restore() requires soft deletes on '${this._definition.name}'`);let t=this._definition.primaryKey||"id",r=this._attributes[t];if(!r)throw Error("Cannot restore a model without a primary key");return await S().run(`UPDATE ${this._definition.table} SET ${L} = ? WHERE ${t} = ?`,[null,r]),this._attributes[L]=null,this._original=null,this}trashed(){return this._attributes[L]!=null}async refresh(){let t=S(),r=this._definition.primaryKey||"id",o=this._attributes[r];if(!o)throw Error("Cannot refresh a model without a primary key");let s=await t.get(`SELECT * FROM ${this._definition.table} WHERE ${r} = ?`,[o]);if(!s)return null;return this._attributes=s,this._original=null,this}replicate(){let t=this._definition.primaryKey||"id",r={...this._attributes};return delete r[t],delete r.uuid,delete r.created_at,delete r.updated_at,new I(this._definition,r,!1)}toArray(){let t={...this._attributes};for(let[r,o]of Object.entries(this._relations))if(Array.isArray(o))t[r]=o.map((s)=>s.toArray());else if(o)t[r]=o.toArray();else t[r]=null;return t}toJSON(){let t=new Set;for(let[o,s]of Object.entries(this._definition.attributes))if(s.hidden)t.add(o);let r={};for(let[o,s]of Object.entries(this._attributes))if(!t.has(o))r[o]=s;for(let[o,s]of Object.entries(this._relations))if(Array.isArray(s))r[o]=s.map((i)=>i.toJSON());else if(s)r[o]=s.toJSON();else r[o]=null;return r}}var ve=new Map,Ne=new Map,re=new Map,Je=1000;function W(t){return C(t)}function C(t){let r=ve.get(t);if(r!==void 0)return r;return r=t.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""),ve.set(t,r),r}function G(t){let r=Ne.get(t);if(r!==void 0)return r;return r=Fe(t),Ne.set(t,r),r}var fe=["hasMany","hasOne","belongsTo","belongsToMany","morphMany","morphOne"],Ze=[...fe,"hasOneThrough","hasManyThrough","morphOne","morphMany","morphTo","morphToMany","morphedByMany"];function Ce(t,r){let o=t[r];if(!o)return[];if(Array.isArray(o))return o.map((s)=>typeof s==="string"?s:String(s?.model??"")).filter(Boolean);if(typeof o==="object")return Object.keys(o);if(typeof o==="string")return[o];return[]}function et(t,r){let o=t.name??t.table??"model",i=Ze.filter((d)=>Ce(t,d).some((u)=>u.toLowerCase()===r.toLowerCase())).filter((d)=>!fe.includes(d));if(i.length>0)return`[orm] '${o}' declares '${r}' as ${i.join("/")}, which eager loading does not support yet. Supported kinds: ${fe.join(", ")}. `+"Load it with a manual query for now \u2014 see stacksjs/bun-query-builder#1068.";let a=fe.flatMap((d)=>Ce(t,d));return a.length>0?`[orm] '${o}' has no relation '${r}'. Available: ${a.join(", ")}.`:`[orm] '${o}' has no relation '${r}' \u2014 it declares no relations at all.`}function Ie(t,r){let{name:o,table:s}=t,i=t.primaryKey||"id";function a(w){if(!w)return null;if(Array.isArray(w)){for(let h of w){let K=typeof h==="string"?h:h?.model||"";if(K&&K.toLowerCase()===r.toLowerCase())return K}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return typeof K==="string"?K:K?.model||K?.target||h}return null}function d(){let w=t.belongsTo;if(!w)return null;let h=r.toLowerCase(),K=(p)=>{if(typeof p==="string")return{model:p};if(p&&typeof p==="object"&&typeof p.model==="string")return{model:p.model,foreignKey:p.foreignKey};return null};if(Array.isArray(w)){for(let p of w){let y=K(p);if(y&&y.model.toLowerCase()===h)return y}return null}if(typeof w==="object"){for(let[p,y]of Object.entries(w))if(p===r||p.toLowerCase()===h)return K(y)}return null}function u(){let w=t.belongsToMany;if(!w)return null;if(Array.isArray(w)){for(let h of w)if(typeof h==="string"){if(h.toLowerCase()===r.toLowerCase())return{entry:h}}else if(h&&typeof h==="object"&&h.model){if(h.model.toLowerCase()===r.toLowerCase())return{entry:h}}return null}if(typeof w==="object"){for(let[h,K]of Object.entries(w))if(h===r||h.toLowerCase()===r.toLowerCase())return{entry:K}}return null}function c(w){let h=t[w];if(!h)return null;let K=r.toLowerCase();if(Array.isArray(h)){for(let p of h){let y=typeof p==="string"?p:String(p?.model??"");if(!y||y.toLowerCase()!==K)continue;let v=typeof p==="object"?p?.morphName:void 0;return{model:y,morphName:String(v??`${C(o)}able`)}}return null}if(typeof h==="object")for(let[p,y]of Object.entries(h)){let v=typeof y==="string"?y:String(y?.model??"");if(p.toLowerCase()!==K&&v.toLowerCase()!==K)continue;let P=typeof y==="object"?y?.morphName:void 0;return{model:v,morphName:String(P??p)}}return null}for(let w of["morphMany","morphOne"]){let h=c(w);if(!h)continue;let p=j(h.model)?.getTable?.()||G(h.model);return{type:w,relatedModelName:h.model,relatedTable:p,foreignKey:`${h.morphName}_id`,localKey:i,morphTypeColumn:`${h.morphName}_type`,morphTypeValue:s}}let T=a(t.hasMany);if(T){let h=j(T)?.getTable?.()||G(T),K=C(o)+"_id";return{type:"hasMany",relatedModelName:T,relatedTable:h,foreignKey:K,localKey:i}}let f=a(t.hasOne);if(f){let h=j(f)?.getTable?.()||G(f),K=C(o)+"_id";return{type:"hasOne",relatedModelName:f,relatedTable:h,foreignKey:K,localKey:i}}let g=d();if(g){let w=g.model,h=j(w),K=h?.getTable?.()||G(w),p=h?.getDefinition?.()?.primaryKey||"id",y=g.foreignKey||`${C(w)}_id`;return{type:"belongsTo",relatedModelName:w,relatedTable:K,foreignKey:y,localKey:p}}let R=u();if(R){let w=typeof R.entry==="object",h=w?R.entry.model:R.entry,p=j(h)?.getTable?.()||G(h),y=w?R.entry:null,v,P;if(y?.table)v=y.table;else if(y?.through){P=y.through;let B=j(y.through);if(!B)throw Error(`[orm] belongsToMany relation '${r}' on '${o}' references unknown through model '${y.through}'. Make sure '${y.through}' is registered.`);v=B.getTable?.()||B.getDefinition?.()?.table||G(y.through)}else{let B=ie(s),q=ie(p);v=[B,q].sort().join("_")}let F=y?.foreignKey||`${ie(s)}_id`,J=y?.relatedKey||`${ie(p)}_id`,V=[];if(y?.pivot?.columns)for(let B of Object.keys(y.pivot.columns))V.push(B);if(P){let B=j(P),q=B?.getDefinition?.()||B?.definition,he=q?.attributes??{},je=q?.primaryKey??"id";for(let se of Object.keys(he)){if(se===F||se===J||se===je)continue;if(!V.includes(se))V.push(se)}}return{type:"belongsToMany",relatedModelName:h,relatedTable:p,foreignKey:F,localKey:i,pivotTable:v,pivotFkParent:F,pivotFkRelated:J,pivotColumns:V,pivotModelName:P,pivotTimestamps:Boolean(y?.pivot?.timestamps)}}let M=(w,h)=>{if(!w||typeof w!=="object"||Array.isArray(w))return null;let K=w[r]??w[Object.keys(w).find((q)=>q.toLowerCase()===r.toLowerCase())??""];if(!K||typeof K!=="object")return null;let{through:p,target:y}=K;if(!p||!y)return null;let v=j(p),P=v?.getDefinition?.()||v?.definition,F=v?.getTable?.()||P?.table||G(p),J=P?.primaryKey||"id",B=j(y)?.getTable?.()||G(y);return{type:h,relatedModelName:y,relatedTable:B,foreignKey:`${C(o)}_id`,localKey:i,throughTable:F,throughForeignKey:`${C(o)}_id`,throughLocalKey:J,targetForeignKey:`${ie(F)}_id`}},x=M(t.hasManyThrough,"hasManyThrough");if(x)return x;let A=M(t.hasOneThrough,"hasOneThrough");if(A)return A;return null}function ge(t,r){let o=new Set;for(let s of t){let i=s.get(r);if(i!=null)o.add(i)}return[...o]}function ie(t){return m(e.relations?.singularizeStrategy)(t)}class Lt{_parent;_parentDef;_resolved;_relatedDef;_wheres=[];_pivotWheres=[];_orderBy=[];_limit;_offset;constructor(t,r,o,s){this._parent=t,this._parentDef=r,this._resolved=o,this._relatedDef=s}get parentId(){let t=this._parentDef.primaryKey||"id";return this._parent.get(t)}get pivotTable(){return this._resolved.pivotTable}get fkParent(){return this._resolved.pivotFkParent}get fkRelated(){return this._resolved.pivotFkRelated}get relatedTable(){return this._resolved.relatedTable}get relatedPk(){return this._relatedDef.primaryKey||"id"}where(t,r,o){if(o===void 0)this._wheres.push({sql:`${this.relatedTable}.${t} = ?`,params:[r]});else this._wheres.push({sql:`${this.relatedTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivot(t,r,o){if(o===void 0)this._pivotWheres.push({sql:`${this.pivotTable}.${t} = ?`,params:[r]});else this._pivotWheres.push({sql:`${this.pivotTable}.${t} ${String(r)} ?`,params:[o]});return this}wherePivotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IN (${o})`,params:[...r]}),this}wherePivotNotIn(t,r){if(!r.length)return this;let o=r.map(()=>"?").join(", ");return this._pivotWheres.push({sql:`${this.pivotTable}.${t} NOT IN (${o})`,params:[...r]}),this}wherePivotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NULL`,params:[]}),this}wherePivotNotNull(t){return this._pivotWheres.push({sql:`${this.pivotTable}.${t} IS NOT NULL`,params:[]}),this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push(`${t} ${r.toUpperCase()}`),this}limit(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] limit(n): expected non-negative integer, got ${t}`);return this._limit=t,this}offset(t){if(!Number.isFinite(t)||t<0||!Number.isInteger(t))throw TypeError(`[bun-query-builder] offset(n): expected non-negative integer, got ${t}`);return this._offset=t,this}relatedSelectColumns(){let t=new Set([this.relatedPk,...Object.keys(this._relatedDef.attributes??{})]),r=this._relatedDef.traits;if(r?.useTimestamps||r?.timestampable)t.add("created_at"),t.add("updated_at");if(r?.useSoftDeletes||r?.softDeletable)t.add("deleted_at");if(r?.useUuid)t.add("uuid");return[...t]}buildSelect(){let t=[],o=`SELECT ${this.relatedSelectColumns().map((s)=>`${this.relatedTable}.${s} AS ${ye}${s}`).join(", ")}, ${this.pivotTable}.* FROM ${this.relatedTable}`;o+=` INNER JOIN ${this.pivotTable} ON ${this.pivotTable}.${this.fkRelated} = ${this.relatedTable}.${this.relatedPk}`,o+=` WHERE ${this.pivotTable}.${this.fkParent} = ?`,t.push(this.parentId);for(let s of this._pivotWheres)o+=` AND ${s.sql}`,t.push(...s.params);for(let s of this._wheres)o+=` AND ${s.sql}`,t.push(...s.params);if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}hydrateRows(t){let r=this.fkParent,o=this.fkRelated;return t.map((s)=>{let i={},a={};for(let[u,c]of Object.entries(s))if(u.startsWith(ye))i[u.slice(ye.length)]=c;else if(u!==r&&u!==o)a[u]=c;let d=new I(this._relatedDef,i,!0);return d.pivot=a,d})}async get(){let t=S(),{sql:r,params:o}=this.buildSelect(),s=await t.all(r,o);return this.hydrateRows(s)}async first(){return this._limit=1,(await this.get())[0]}async count(){let t=S(),r=`SELECT COUNT(*) as count FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,o=[this.parentId];for(let i of this._pivotWheres)r+=` AND ${i.sql}`,o.push(...i.params);let s=await t.get(r,o);return Number(s?.count??0)}async exists(){return await this.count()>0}now(){return Y()}async attach(t,r={}){let o=S(),s=Array.isArray(t)?t:[t];if(s.length===0)return 0;let i=this._resolved.pivotTimestamps?this.now():null,a=0;for(let d of s){let u={[this.fkParent]:this.parentId,[this.fkRelated]:d,...r};if(i){if(u.created_at===void 0)u.created_at=i;if(u.updated_at===void 0)u.updated_at=i}let c=Object.keys(u),T=c.map(()=>"?").join(", "),f=`INSERT INTO ${this.pivotTable} (${c.join(", ")}) VALUES (${T})`,g=c.map((R)=>u[R]);await o.run(f,g),a++}return a}async detach(t){let r=S(),o=`DELETE FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,s=[this.parentId];if(t!==void 0&&t!==null){let i=Array.isArray(t)?t:[t];if(i.length===0)return 0;let a=i.map(()=>"?").join(", ");o+=` AND ${this.fkRelated} IN (${a})`,s.push(...i)}return(await r.run(o,s)).changes}async updateExistingPivot(t,r){let o=S(),s={...r};if(this._resolved.pivotTimestamps&&s.updated_at===void 0)s.updated_at=this.now();let i=Object.keys(s);if(i.length===0)return 0;let a=i.map((c)=>`${c} = ?`).join(", "),d=`UPDATE ${this.pivotTable} SET ${a} WHERE ${this.fkParent} = ? AND ${this.fkRelated} = ?`,u=[...i.map((c)=>s[c]),this.parentId,t];return(await o.run(d,u)).changes}async sync(t){let r=S(),o=new Map;for(let T of t)if(T!=null&&typeof T==="object"&&"id"in T){let{id:f,...g}=T;o.set(f,g)}else o.set(T,{});let s=await r.all(`SELECT * FROM ${this.pivotTable} WHERE ${this.fkParent} = ?`,[this.parentId]),i=new Set(s.map((T)=>T[this.fkRelated])),a=[],d=[],u=[],c=[...i].filter((T)=>!o.has(T));if(c.length>0)await this.detach(c),d.push(...c);for(let[T,f]of o)if(!i.has(T))await this.attach(T,f),a.push(T);else if(Object.keys(f).length>0)await this.updateExistingPivot(T,f),u.push(T);return{attached:a,detached:d,updated:u}}async toggle(t){let r=S(),o=Array.isArray(t)?t:[t];if(o.length===0)return{attached:[],detached:[]};let s=o.map(()=>"?").join(", "),i=await r.all(`SELECT ${this.fkRelated} FROM ${this.pivotTable} WHERE ${this.fkParent} = ? AND ${this.fkRelated} IN (${s})`,[this.parentId,...o]),a=new Set(i.map((c)=>c[this.fkRelated])),d=o.filter((c)=>!a.has(c)),u=o.filter((c)=>a.has(c));if(d.length>0)await this.attach(d);if(u.length>0)await this.detach(u);return{attached:d,detached:u}}}class E{_definition;_wheres=[];_orderBy=[];_limit;_offset;_select=["*"];_withRelations=[];_trashed="exclude";constructor(t){this._definition=t}withTrashed(){return this._trashed="include",this}onlyTrashed(){return this._trashed="only",this}where(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"and"});else this._wheres.push({column:t,operator:r,value:o,boolean:"and"});return this}orWhere(t,r,o){if(o===void 0)this._wheres.push({column:t,operator:"=",value:r,boolean:"or"});else this._wheres.push({column:t,operator:r,value:o,boolean:"or"});return this}whereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"and"}),this}orWhereIn(t,r){return this._wheres.push({column:t,operator:"in",value:r,boolean:"or"}),this}whereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"and"}),this}orWhereNotIn(t,r){return this._wheres.push({column:t,operator:"not in",value:r,boolean:"or"}),this}whereNull(t){return H(t,"whereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"and"}),this}orWhereNull(t){return H(t,"orWhereNull(column)"),this._wheres.push({column:t,operator:"=",value:null,boolean:"or"}),this}whereNotNull(t){return H(t,"whereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"and"}),this}orWhereNotNull(t){return H(t,"orWhereNotNull(column)"),this._wheres.push({column:t,operator:"!=",value:null,boolean:"or"}),this}whereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"and"}),this}orWhereLike(t,r){return this._wheres.push({column:t,operator:"like",value:r,boolean:"or"}),this}whereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"and"}),this}orWhereNotLike(t,r){return this._wheres.push({column:t,operator:"not like",value:r,boolean:"or"}),this}whereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"and"}),this}orWhereRaw(t,...r){return this._wheres.push({raw:t,rawParams:Me(t,r),boolean:"or"}),this}whereGroup(t){return this._addGroup("and",t)}orWhereGroup(t){return this._addGroup("or",t)}_addGroup(t,r){let o=new E(this._definition);if(r(o),o._wheres.length===0)return this;let s=[],i=o.buildWhereClauses(s);if(!i)return this;return this._wheres.push({raw:`(${i})`,rawParams:s,boolean:t}),this}whereBetween(t,r){return H(t,"whereBetween(column)"),this._wheres.push({column:t,operator:">=",value:r[0],boolean:"and"}),this._wheres.push({column:t,operator:"<=",value:r[1],boolean:"and"}),this}whereNotBetween(t,r){H(t,"whereNotBetween(column)");let o=W(t);return this._wheres.push({raw:`(${o} < ? OR ${o} > ?)`,rawParams:[r[0],r[1]],boolean:"and"}),this}when(t,r){if(t)return r(this);return this}orderBy(t,r="asc"){if(Se(t,"orderBy(column)"),r!=="asc"&&r!=="desc")throw TypeError(`[bun-query-builder] orderBy(direction): expected 'asc' or 'desc', got '${r}'`);return this._orderBy.push({column:t,direction:r}),this}orderByDesc(t){return this.orderBy(t,"desc")}orderByAsc(t){return this.orderBy(t,"asc")}latest(t="created_at"){return this.orderBy(t,"desc")}oldest(t="created_at"){return this.orderBy(t,"asc")}limit(t){return this._limit=t,this}take(t){return this.limit(t)}offset(t){return this._offset=t,this}skip(t){return this.offset(t)}select(...t){return this._select=t,this}with(...t){for(let r of t)if(!this._withRelations.includes(r))this._withRelations.push(r);return this}getWithRelations(){return this._withRelations}buildWhereClauses(t){let r=[];for(let o of this._wheres){let s;if(o.raw){if(s=o.raw,o.rawParams&&o.rawParams.length>0)t.push(...o.rawParams)}else if(o.value===null){let i=W(o.column);s=o.operator==="="?`${i} IS NULL`:`${i} IS NOT NULL`}else if(o.operator==="in"||o.operator==="not in"){let i=o.value;s=l(W(o.column),i,o.operator==="not in",i.map(()=>"?").join(", ")),t.push(...i)}else s=`${W(o.column)} ${o.operator} ?`,t.push(o.value);r.push({conn:o.boolean==="or"?"OR":"AND",sql:s})}return D(r)}softDeleteClause(){if(this._trashed==="include"||!ee(this._definition))return"";return this._trashed==="only"?`${L} IS NOT NULL`:`${L} IS NULL`}assertNoUnappliedClauses(t){let r=[];if(this._limit!==void 0)r.push("limit()");if(this._offset!==void 0)r.push("offset()");if(this._orderBy.length>0)r.push("orderBy()");if(r.length>0)throw TypeError(`[orm] ${t}() cannot apply ${r.join(", ")} \u2014 an UPDATE/DELETE takes no ORDER BY or LIMIT on every supported dialect. `+"Previously these were ignored, so the statement affected every matching row. Narrow it with where() instead.")}composeWhere(t){let r=this._wheres.length>0?this.buildWhereClauses(t):"",o=this.softDeleteClause();if(r&&o)return`(${r}) AND ${o}`;return r||o}buildQuery(){let t=[],o=`SELECT ${this._select.map((i)=>i==="*"?i:W(i)).join(", ")} FROM ${this._definition.table}`,s=this.composeWhere(t);if(s)o+=` WHERE ${s}`;if(this._orderBy.length>0)o+=` ORDER BY ${this._orderBy.map((i)=>`${W(i.column)} ${i.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)o+=` LIMIT ${this._limit}`;if(this._offset!==void 0)o+=` OFFSET ${this._offset}`;return{sql:o,params:t}}toSql(){return this.buildQuery()}async eagerLoadRelations(t){if(t.length===0||this._withRelations.length===0)return;await Promise.all(this._withRelations.map((r)=>this.eagerLoadRelation(r,t)))}async eagerLoadRelation(t,r){let o=S(),s=this._definition.primaryKey||"id",i=`${this._definition.name}:${t}`,a=re.get(i);if(a===void 0){if(a=Ie(this._definition,t),re.size>=Je)re.clear();re.set(i,a)}if(!a)throw Error(et(this._definition,t));let d=a.type==="hasOne"||a.type==="morphOne";if(a.type==="hasMany"||a.type==="hasOne"||a.type==="morphMany"||a.type==="morphOne"){let u=ge(r,s);if(u.length===0)return;let c=u.map(()=>"?").join(", "),T=a.morphTypeColumn?` AND ${a.morphTypeColumn} = ?`:"",f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.foreignKey} IN (${c})${T}`,a.morphTypeColumn?[...u,a.morphTypeValue]:u),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition;if(!d){let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,[]);M.get(A).push(x)}for(let x of r){let A=M.get(x.get(s))||[];x.setRelation(t,A.map((w)=>new I(R,w,!0)))}}else{let M=new Map;for(let x of f){let A=x[a.foreignKey];if(!M.has(A))M.set(A,x)}for(let x of r){let A=M.get(x.get(s));x.setRelation(t,A?new I(R,A,!0):null)}}}if(a.type==="belongsTo"){let u=new Set;for(let x of r){let A=x._attributes[a.foreignKey];if(A!=null)u.add(A)}let c=[...u];if(c.length===0)return;let T=c.map(()=>"?").join(", "),f=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.localKey} IN (${T})`,c),g=j(a.relatedModelName),R=g?.getDefinition?.()||g?.definition||this._definition,M=new Map;for(let x of f)M.set(x[a.localKey],x);for(let x of r){let A=x._attributes[a.foreignKey],w=M.get(A);x.setRelation(t,w?new I(R,w,!0):null)}}if(a.type==="belongsToMany"){let u=ge(r,s);if(u.length===0)return;if(!a.pivotTable||!a.pivotFkParent||!a.pivotFkRelated)return;let c=u.map(()=>"?").join(", "),T=await o.all(`SELECT * FROM ${a.pivotTable} WHERE ${a.pivotFkParent} IN (${c})`,u);if(T.length===0){for(let p of r)p.setRelation(t,[]);return}let f=new Set;for(let p of T){let y=p[a.pivotFkRelated];if(y!=null)f.add(y)}let g=[...f],R=j(a.relatedModelName),M=R?.getDefinition?.()||R?.definition||this._definition,x=M?.primaryKey||"id",A=[];if(g.length>0){let p=g.map(()=>"?").join(", ");A=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${x} IN (${p})`,g)}let w=new Map;for(let p of A)w.set(p[x],p);let h=new Map;for(let p of T){let y=p[a.pivotFkParent];if(!h.has(y))h.set(y,[]);h.get(y).push(p)}let K=new Set([a.pivotFkParent,a.pivotFkRelated]);for(let p of r){let y=p.get(s),P=(h.get(y)||[]).map((F)=>{let J=w.get(F[a.pivotFkRelated]);if(!J)return null;let V=new I(M,J,!0),B={};for(let[q,he]of Object.entries(F))if(!K.has(q))B[q]=he;return V.pivot=B,V}).filter((F)=>F!==null);p.setRelation(t,P)}}if(a.type==="hasManyThrough"||a.type==="hasOneThrough"){let u=ge(r,s);if(u.length===0)return;let c=a.throughLocalKey||"id",T=u.map(()=>"?").join(", "),f=await o.all(`SELECT ${c}, ${a.throughForeignKey} FROM ${a.throughTable} WHERE ${a.throughForeignKey} IN (${T})`,u);if(f.length===0){for(let K of r)K.setRelation(t,a.type==="hasManyThrough"?[]:null);return}let g=new Map;for(let K of f)g.set(K[c],K[a.throughForeignKey]);let R=[...new Set(f.map((K)=>K[c]))],M=R.map(()=>"?").join(", "),x=await o.all(`SELECT * FROM ${a.relatedTable} WHERE ${a.targetForeignKey} IN (${M})`,R),A=j(a.relatedModelName),w=A?.getDefinition?.()||A?.definition||this._definition,h=new Map;for(let K of x){let p=g.get(K[a.targetForeignKey]);if(p==null)continue;if(!h.has(p))h.set(p,[]);h.get(p).push(new I(w,K,!0))}for(let K of r){let p=h.get(K.get(s))||[];K.setRelation(t,a.type==="hasManyThrough"?p:p[0]??null)}}}async get(){let t=S(),{sql:r,params:o}=this.buildQuery(),i=(await t.all(r,o)).map((a)=>new I(this._definition,a,!0));if(this._withRelations.length>0)await this.eagerLoadRelations(i);return i}async first(){return this._limit=1,(await this.get())[0]}async firstOrFail(){let t=await this.first();if(!t)throw Error(`No ${this._definition.name} found`);return t}async find(t){let r=this._definition.primaryKey||"id";return this.where(r,t).first()}async findOrFail(t){let r=await this.find(t);if(!r)throw Error(`${this._definition.name} with id ${t} not found`);return r}async last(){let t=this._definition.primaryKey||"id";return this._orderBy=[{column:t,direction:"desc"}],this._limit=1,(await this.get())[0]}async count(){let t=S(),r=[],o=`SELECT COUNT(*) as count FROM ${this._definition.table}`,s=this.composeWhere(r);if(s)o+=` WHERE ${s}`;let i=await t.get(o,r);return Number(i?.count??0)}async exists(){return await this.count()>0}async doesntExist(){return await this.count()===0}async sole(){this._limit=2;let t=await this.get();if(t.length===0)throw Error(`No ${this._definition.name} found`);if(t.length>1)throw Error(`Expected one ${this._definition.name}, found multiple`);return t[0]}async increment(t,r=1){H(t,"increment(column)"),this.assertNoUnappliedClauses("increment");let o=S(),s=[r],i=W(t),a=`UPDATE ${this._definition.table} SET ${i} = ${i} + ?`;if(Z(this._definition))a+=", updated_at = ?",s.push(Y());let d=this.composeWhere(s);if(d)a+=` WHERE ${d}`;return(await o.run(a,s)).changes}decrement(t,r=1){return this.increment(t,-r)}async chunk(t,r){let o=0;while(!0){let s=new E(this._definition);s._wheres=[...this._wheres],s._orderBy=[...this._orderBy],s._select=[...this._select],s._withRelations=[...this._withRelations],s._trashed=this._trashed,s._limit=t,s._offset=o*t;let i=await s.get();if(i.length===0)break;if(await r(i)===!1)break;if(i.length<t)break;o++}}async paginate(t=1,r=15){if(typeof t==="object"&&t!==null){let a=t;r=a.perPage??15,t=a.page??1}let o=await this.count(),s=Math.ceil(o/r);this._limit=r,this._offset=(t-1)*r;let i=await this.get();return{data:i,total:o,page:t,perPage:r,lastPage:s,hasMorePages:t<s,isEmpty:i.length===0,from:i.length>0?(t-1)*r+1:null,to:i.length>0?(t-1)*r+i.length:null,meta:{perPage:r,page:t,total:o,lastPage:s}}}async pluck(t){H(t,"pluck(column)");let r=S(),o=[],s=W(t),i=`SELECT ${s} FROM ${this._definition.table}`,a=this.composeWhere(o);if(a)i+=` WHERE ${a}`;if(this._orderBy.length>0)i+=` ORDER BY ${this._orderBy.map((u)=>`${W(u.column)} ${u.direction.toUpperCase()}`).join(", ")}`;if(this._limit!==void 0)i+=` LIMIT ${this._limit}`;if(this._offset!==void 0)i+=` OFFSET ${this._offset}`;return(await r.all(i,o)).map((u)=>u[s])}async aggregate(t,r){H(r,`${t}(column)`);let o=S(),s=[],i=`SELECT ${t}(${W(r)}) as v FROM ${this._definition.table}`,a=this.composeWhere(s);if(a)i+=` WHERE ${a}`;let u=(await o.get(i,s))?.v;if(u==null)return null;if(typeof u==="string"){let c=Number(u);return u.trim()!==""&&!Number.isNaN(c)?c:u}return u}max(t){return this.aggregate("MAX",t)}min(t){return this.aggregate("MIN",t)}async avg(t){return Number(await this.aggregate("AVG",t)??0)||0}async sum(t){return Number(await this.aggregate("SUM",t)??0)||0}async delete(){this.assertNoUnappliedClauses("delete");let t=ee(this._definition)&&this._trashed!=="only";return this.deleteMatching(t)}async forceDelete(){return this.assertNoUnappliedClauses("forceDelete"),this.deleteMatching(!1)}async deleteMatching(t){let r=S(),o=this._definition.table,s=this._definition.hooks,i=[],a=this.composeWhere(i);if(t&&this._trashed==="include")a=a?`(${a}) AND ${L} IS NULL`:`${L} IS NULL`;let d=a?` WHERE ${a}`:"",u=t?Y():void 0;if(!s?.beforeDelete&&!s?.afterDelete)return t?(await r.run(`UPDATE ${o} SET ${L} = ?${d}`,[u,...i])).changes:(await r.run(`DELETE FROM ${o}${d}`,i)).changes;let c=this._definition.primaryKey||"id",f=(await r.all(`SELECT * FROM ${o}${d}`,i)).map((M)=>new I(this._definition,M,!0)),g=f.map((M)=>M._attributes[c]);if(g.some((M)=>M==null))throw Error(`Cannot delete a model without a primary key: '${c}' is missing from a matching row`);for(let M of f)await s.beforeDelete?.(M);let R=0;for(let M=0;M<g.length;M+=Ae){let x=g.slice(M,M+Ae),A=`${c} IN (${x.map(()=>"?").join(", ")})`;R+=t?(await r.run(`UPDATE ${o} SET ${L} = ? WHERE ${A}`,[u,...x])).changes:(await r.run(`DELETE FROM ${o} WHERE ${A}`,x)).changes}for(let M of f){if(t)M._attributes[L]=u;await s.afterDelete?.(M)}return R}async update(t){this.assertNoUnappliedClauses("update");let r=S(),o=Object.entries(t),s=o.map(([u])=>`${W(u)} = ?`).join(", "),i=o.map(([,u])=>u);if(Z(this._definition))i.push(Y());let a=`UPDATE ${this._definition.table} SET ${s}${Z(this._definition)?", updated_at = ?":""}`,d=this.composeWhere(i);if(d)a+=` WHERE ${d}`;return(await r.run(a,i)).changes}}function tt(t){let r={query:()=>new E(t),where(o,s,i){return new E(t).where(o,s,i)},orWhere(o,s,i){return new E(t).orWhere(o,s,i)},whereIn(o,s){return new E(t).whereIn(o,s)},whereNotIn(o,s){return new E(t).whereNotIn(o,s)},whereNull(o){return new E(t).whereNull(o)},whereNotNull(o){return new E(t).whereNotNull(o)},whereLike(o,s){return new E(t).whereLike(o,s)},orderBy(o,s="asc"){return new E(t).orderBy(o,s)},orderByDesc(o){return new E(t).orderByDesc(o)},select(...o){return new E(t).select(...o)},with(...o){return new E(t).with(...o)},limit:(o)=>new E(t).limit(o),take:(o)=>new E(t).take(o),skip:(o)=>new E(t).skip(o),withTrashed:()=>new E(t).withTrashed(),onlyTrashed:()=>new E(t).onlyTrashed(),async find(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"",d=await s.get(`SELECT * FROM ${t.table} WHERE ${i} = ?${a}`,[o]);return d?new I(t,d,!0):void 0},async findOrFail(o){let s=await r.find(o);if(!s)throw Error(`${t.name} with id ${o} not found`);return s},async findMany(o){let s=S(),i=t.primaryKey||"id",a=ee(t)?` AND ${L} IS NULL`:"";return(await s.all(`SELECT * FROM ${t.table} WHERE ${i} IN (${o.map(()=>"?").join(", ")})${a}`,o)).map((u)=>new I(t,u,!0))},all:()=>new E(t).get(),first:()=>new E(t).first(),firstOrFail:()=>new E(t).firstOrFail(),last:()=>new E(t).last(),count:()=>new E(t).count(),exists:()=>new E(t).exists(),doesntExist:()=>new E(t).doesntExist(),paginate:(o,s)=>new E(t).paginate(o,s),whereBetween(o,s){return new E(t).whereBetween(o,s)},whereNotBetween(o,s){return new E(t).whereNotBetween(o,s)},async create(o){let s=new I(t,o,!1);return await s.save(),s},async createMany(o){let s=o.map((c)=>new I(t,c,!1));if(!s.length)return[];let i=S(),a=t.primaryKey||"id",d=[];for(let c of s)d.push(await c._prepareInsert());let u=new Map;d.forEach((c,T)=>{let f=Object.keys(c).join("\x00"),g=u.get(f);if(g)g.push(T);else u.set(f,[T])});for(let[c,T]of u){let f=c?c.split("\x00"):[],g=!f.includes(a);if(!f.length||g&&i.dialect==="mysql"){for(let M of T){let x=d[M],A=Object.keys(x),w=await i.insert(A.length?`INSERT INTO ${t.table} (${A.join(", ")}) VALUES (${A.map(()=>"?").join(", ")})`:`INSERT INTO ${t.table} DEFAULT VALUES`,Object.values(x),a);await s[M]._markInserted(x,g?w.lastInsertId:void 0)}continue}if(i.dialect==="postgres"&&Ve(t,f,T.map((M)=>d[M]))){let M=t.table,x=f.join(", "),A=`INSERT INTO ${M} (${x}) SELECT ${x} FROM jsonb_populate_recordset(NULL::${M}, (?::text)::jsonb)`;for(let w=0;w<T.length;w+=_e){let h=T.slice(w,w+_e),K=JSON.stringify(h.map((v)=>Object.fromEntries(f.map((P)=>[P,d[v][P]??null]))),ze);if(!g){await i.run(A,[K]);for(let v of h)await s[v]._markInserted(d[v]);continue}let p=(await i.all(`${A} RETURNING ${a}`,[K])).map((v)=>v[a]),y=p.every((v)=>typeof v==="number"||typeof v==="bigint")?[...p].sort((v,P)=>v<P?-1:v>P?1:0):p;for(let v=0;v<h.length;v++)await s[h[v]]._markInserted(d[h[v]],y[v])}continue}let R=xe(Math.max(1,Math.floor(Qe/f.length)));for(let M=0;M<T.length;){let x=Math.min(R,xe(T.length-M)),A=T.slice(M,M+x);M+=x;let w=`INSERT INTO ${t.table} (${f.join(", ")}) VALUES ${A.map(()=>`(${f.map(()=>"?").join(", ")})`).join(", ")}`,h=A.flatMap((y)=>f.map((v)=>d[y][v]));if(!g){await i.run(w,h);for(let y of A)await s[y]._markInserted(d[y]);continue}let K=(await i.all(`${w} RETURNING ${a}`,h)).map((y)=>y[a]),p=K.every((y)=>typeof y==="number"||typeof y==="bigint")?[...K].sort((y,v)=>y<v?-1:y>v?1:0):K;for(let y=0;y<A.length;y++)await s[A[y]]._markInserted(d[A[y]],p[y])}}return s},async updateOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);let a=await i.first();if(a)return await a.update(s),a;return this.create({...o,...s})},async firstOrCreate(o,s){let i=new E(t);for(let[d,u]of Object.entries(o))i=i.where(d,u);return await i.first()||this.create({...o,...s})},async update(o,s){let i=await r.findOrFail(o);return await i.update(s),i},async delete(o){let s=await r.find(o);return s?s.delete():!1},destroy(o){return r.delete(o)},async forceDelete(o){let s=await r.withTrashed().find(o);return s?s.forceDelete():!1},remove(o){return r.forceDelete(o)},async truncate(){await S().run(`DELETE FROM ${t.table}`,[])},getDefinition:()=>t,getTable:()=>t.table,make(o={}){return new I(t,o,!1)},latest:(o="created_at")=>new E(t).orderByDesc(o),oldest:(o="created_at")=>new E(t).orderBy(o,"asc"),max:(o)=>new E(t).max(o),min:(o)=>new E(t).min(o),avg:(o)=>new E(t).avg(o),sum:(o)=>new E(t).sum(o),pluck(o){return new E(t).pluck(o)}};return new Proxy(r,{get(o,s){if(typeof s==="string"&&s.startsWith("where")&&s.length>5){let i=s.slice(5),a=i.charAt(0).toLowerCase()+i.slice(1);if(a in t.attributes||a==="id"||a===t.primaryKey)return(d)=>new E(t).where(a,d)}return Reflect.get(o,s)}})}function Kt(t){let r=tt(t);if(t?.name)qe(t.name,r);return r}async function jn(t){let r=S(),o=C(t.primaryKey||"id"),s=[],i=new Set([o]);if(s.push(t.autoIncrement!==!1?`${o} INTEGER PRIMARY KEY AUTOINCREMENT`:`${o} INTEGER PRIMARY KEY`),t.traits?.useUuid)s.push("uuid TEXT UNIQUE"),i.add("uuid");for(let[a,d]of Object.entries(t.attributes)){let u=C(a);if(i.has(u))continue;i.add(u);let c=De(d.type),T=Pe(c);if(u.endsWith("_id")&&(c===void 0||N(c)))T="INTEGER";let f=`${u} ${T}`;if(d.unique)f+=" UNIQUE";if(typeof d.foreignKey==="object"&&d.foreignKey!==null){let g=d.foreignKey;if(f+=` REFERENCES ${g.table}(${g.column??"id"})`,g.onDelete)f+=` ON DELETE ${g.onDelete.toUpperCase()}`;if(g.onUpdate)f+=` ON UPDATE ${g.onUpdate.toUpperCase()}`}s.push(f)}for(let a of O(t.belongsTo)){let d=a.foreignKey??`${C(a.model)}_id`;if(i.has(d))continue;i.add(d),s.push(`${d} INTEGER`)}if(Z(t))for(let a of["created_at","updated_at"]){if(i.has(a))continue;i.add(a),s.push(`${a} TEXT`)}if(ee(t)&&!i.has("deleted_at"))i.add("deleted_at"),s.push("deleted_at TEXT");await r.run(`CREATE TABLE IF NOT EXISTS ${t.table} (${s.join(", ")})`,[])}async function qn(t,r,o){let s=S(),i=t.traits?.useSeeder,a=r??(typeof i==="object"&&i?i.count:10);if(!o)try{let d=await import("./chunk-r2ta1rnj.js");o=Pt(d.faker)}catch{console.warn("@stacksjs/ts-faker not found. Install it for seeding support.");return}for(let d=0;d<a;d++){let u={};for(let[T,f]of Object.entries(t.attributes))if(f.factory)u[C(T)]=f.factory(o);if(Z(t)){let T=Y();u.created_at=T,u.updated_at=T}if(t.traits?.useUuid)u.uuid=crypto.randomUUID();let c=Object.keys(u);await s.run(`INSERT INTO ${t.table} (${c.join(", ")}) VALUES (${c.map(()=>"?").join(", ")})`,Object.values(u))}}var oe=new Map;function rn(t){return oe.get(t)}function sn(){return[...oe.values()]}function an(){return Object.fromEntries(oe)}function on(t){return oe.has(t)}function ln(){oe.clear(),Bt()}function Ft(t,r){return oe.set(t,r),r}function nt(){return typeof window<"u"&&typeof document<"u"}function cn(t){let r;if(nt())r=We(t);else{let o=Kt(t);r=Object.assign(o,{definition:t,getDefinition:()=>t,getTable:()=>t.table,getName:()=>t.name})}return Ft(t.name,r),r}function un(t){if(typeof window>"u")return;window.StacksBrowser={...window.StacksBrowser,...t}}
3
+ export{N,Pe,Pt,Be,O,Bt,_t,It,Ln,Kn,Fn,Lt,Kt,jn,qn,rn,sn,an,on,ln,Ft,cn,un};