@shumai-one/shumai 0.4.6 → 0.4.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/{chunk-1bgsphyz.js → chunk-05tnmf8h.js} +2 -2
- package/bin/chunk-0xsgx9ep.js +1 -0
- package/bin/{chunk-3d5rm1d1.js → chunk-0ygtayqf.js} +1 -1
- package/bin/{chunk-crja7whq.js → chunk-11c93g1m.js} +2 -2
- package/bin/chunk-1ajgdv26.js +1 -0
- package/bin/{chunk-ba33nf0q.js → chunk-1ntn42d2.js} +3 -3
- package/bin/chunk-2kxhdnma.js +3 -0
- package/bin/chunk-30dsxm8s.js +1 -0
- package/bin/chunk-3b6h719s.js +3 -0
- package/bin/{chunk-pdh9bnyj.js → chunk-3g5pyw2e.js} +2 -2
- package/bin/{chunk-p75f5pgq.js → chunk-3h9c5ak3.js} +2 -2
- package/bin/{chunk-2qjfpmcf.js → chunk-3m5kwcj7.js} +1 -1
- package/bin/{chunk-w1wxzqqb.js → chunk-3p1bb08a.js} +2 -2
- package/bin/{chunk-6vxzkrsj.js → chunk-3r5yc5wm.js} +4 -4
- package/bin/{chunk-sab7tjxw.js → chunk-3tyk9xgf.js} +3 -3
- package/bin/{chunk-h9mka9br.js → chunk-4a88wwg2.js} +1 -1
- package/bin/{chunk-z08bqvkc.js → chunk-4f5pnnah.js} +14 -14
- package/bin/{chunk-dpc11hpd.js → chunk-4jgq9m51.js} +7 -7
- package/bin/{chunk-d7fwggt6.js → chunk-4m8gk79m.js} +1 -1
- package/bin/{chunk-b9hyc0a1.js → chunk-53vtc74g.js} +2 -2
- package/bin/{chunk-1kt5dzjv.js → chunk-58e1a3re.js} +2 -2
- package/bin/{chunk-dmvvt8va.js → chunk-5qkwpy8c.js} +2 -2
- package/bin/{chunk-07jszkhj.js → chunk-5rk7dyx9.js} +58 -58
- package/bin/{chunk-ga3pahzf.js → chunk-5v4s2kp4.js} +1 -1
- package/bin/{chunk-v8v8vdf7.js → chunk-5wp37g6w.js} +4 -4
- package/bin/{chunk-hs2r9qaw.js → chunk-628k58ek.js} +2 -2
- package/bin/{chunk-rp4pc6kz.js → chunk-6kdf411z.js} +1 -1
- package/bin/chunk-6ksrrayx.css +1 -0
- package/bin/chunk-6rjkbwz6.js +14 -0
- package/bin/{chunk-md5pcq46.js → chunk-781990k7.js} +4 -4
- package/bin/{chunk-ey3h4sct.js → chunk-887pj9xd.js} +2 -2
- package/bin/{chunk-1jybg56e.js → chunk-8b1w6bj9.js} +1 -1
- package/bin/{chunk-0wvhahzh.js → chunk-8gna37dd.js} +1 -1
- package/bin/{chunk-rmzcarv9.js → chunk-8sf106rq.js} +1 -1
- package/bin/{chunk-2jrjwaqr.js → chunk-8ystwvdt.js} +1 -1
- package/bin/{chunk-3j5njrpr.js → chunk-9v6eqa3n.js} +2 -2
- package/bin/{chunk-rsd164d9.js → chunk-9va1mzeq.js} +1 -1
- package/bin/{chunk-kmbjp5kp.js → chunk-an6nsq1t.js} +1 -1
- package/bin/{chunk-vzj2j11x.js → chunk-ayq8dskd.js} +1 -1
- package/bin/{chunk-y20sbaz5.js → chunk-b0rjvx5g.js} +1 -1
- package/bin/chunk-bgm76rzj.js +1 -0
- package/bin/chunk-btmxr226.js +1 -0
- package/bin/chunk-camzbwqh.js +2 -0
- package/bin/{chunk-t350k3s1.js → chunk-ccvjwhqq.js} +1 -1
- package/bin/{chunk-pgj2kjnn.js → chunk-dkzyv61a.js} +2 -2
- package/bin/{chunk-y56yvezn.js → chunk-dyq6h9ha.js} +1 -1
- package/bin/{chunk-teqprbd8.js → chunk-e17daz1x.js} +1 -1
- package/bin/{chunk-dbw8c1jj.js → chunk-ebf1r872.js} +4 -4
- package/bin/{chunk-2vzzd0q6.js → chunk-ebx3bd4c.js} +1 -1
- package/bin/{chunk-161rxeq2.js → chunk-ee3mrvqp.js} +1 -1
- package/bin/chunk-fg6zf2gb.js +2 -0
- package/bin/{chunk-6y4xkcte.js → chunk-fhazy8f9.js} +1 -1
- package/bin/{chunk-gqr5hxhj.js → chunk-fk712d68.js} +1 -1
- package/bin/{chunk-afnzb9ne.js → chunk-fvgb6rps.js} +2 -2
- package/bin/chunk-g9gmht89.js +2 -0
- package/bin/{chunk-1t51fp6n.js → chunk-gf4n4ahk.js} +1 -1
- package/bin/{chunk-gcjsw9yp.js → chunk-h3wr8nnk.js} +1 -1
- package/bin/chunk-htpjtarr.js +2 -0
- package/bin/{chunk-kg8eg9z3.js → chunk-hye75kp0.js} +2 -2
- package/bin/{chunk-3tg39jx7.js → chunk-j41mya13.js} +2 -2
- package/bin/chunk-j547gtag.js +2 -0
- package/bin/{chunk-a4056d0r.js → chunk-jde9r5mj.js} +1 -1
- package/bin/chunk-jf4kcad0.js +1 -0
- package/bin/{chunk-tgr86ac4.js → chunk-jt04mf5s.js} +1 -1
- package/bin/{chunk-hnhdq2wd.js → chunk-k3qypq3x.js} +1 -1
- package/bin/chunk-k5hnrtrt.js +1 -0
- package/bin/{chunk-mtb9fpj2.js → chunk-k810fstm.js} +1 -1
- package/bin/{chunk-3n4224c0.js → chunk-kg2c445x.js} +1 -1
- package/bin/{chunk-edqd8evk.js → chunk-kq2qbwx1.js} +1 -1
- package/bin/{chunk-7nvk7waw.js → chunk-m2h7a172.js} +1 -1
- package/bin/{chunk-brwbhbmc.js → chunk-m638fg4n.js} +5 -5
- package/bin/{chunk-3dgahs95.js → chunk-mm1a0zja.js} +1 -1
- package/bin/{chunk-hxyg5q2a.js → chunk-njabdtvb.js} +2 -2
- package/bin/{chunk-b6q287d1.js → chunk-njqf50vw.js} +1 -1
- package/bin/{chunk-47tn3vtg.js → chunk-nn5hyf6f.js} +1 -1
- package/bin/{chunk-t7bvde99.js → chunk-nnq8g9yy.js} +3 -3
- package/bin/{chunk-8cn7fx40.js → chunk-ny7qjn6s.js} +1 -1
- package/bin/{chunk-3d9tfxp4.js → chunk-p5fwjk5c.js} +1 -1
- package/bin/{chunk-s05cdax2.js → chunk-pa1fmskf.js} +1 -1
- package/bin/{chunk-a796sgcw.js → chunk-pcspeqwq.js} +2 -2
- package/bin/{chunk-yfr0hzb7.js → chunk-q1d7x1cc.js} +1 -1
- package/bin/{chunk-y1b3ck7m.js → chunk-q45n02fs.js} +1 -1
- package/bin/chunk-q6jsw0rr.js +211 -0
- package/bin/chunk-qjzyze00.js +1 -0
- package/bin/{chunk-2yr5k567.js → chunk-r55htzxr.js} +1 -1
- package/bin/{chunk-46wfxyd7.js → chunk-r7e2fmmx.js} +2 -2
- package/bin/{chunk-5kvc1gp2.js → chunk-rbagbd0e.js} +1 -1
- package/bin/{chunk-dz076sh7.js → chunk-rdscv38p.js} +1 -1
- package/bin/chunk-rfhmk32e.js +1 -0
- package/bin/{chunk-qs7855cz.js → chunk-rkafv27g.js} +2 -2
- package/bin/{chunk-hd6dnnyg.js → chunk-rkqpnyzx.js} +1 -1
- package/bin/{chunk-z6jpt0h6.js → chunk-s30fjvzs.js} +3 -3
- package/bin/{chunk-dj5a6kkh.js → chunk-s41mgkse.js} +1 -1
- package/bin/{chunk-988casfy.js → chunk-s63vj79f.js} +1 -1
- package/bin/{chunk-9d0thqcy.js → chunk-t3t7dcfq.js} +1 -1
- package/bin/{chunk-gsfcpcye.js → chunk-twyxs4z2.js} +1 -1
- package/bin/{chunk-1dqsf5qj.js → chunk-typ46eqd.js} +5 -5
- package/bin/chunk-v1sgrg0r.js +1 -0
- package/bin/{chunk-j9ks8bd7.js → chunk-vdnmq163.js} +1 -1
- package/bin/{chunk-jg2v25d2.js → chunk-vx66rms0.js} +2 -2
- package/bin/{chunk-9nvymwqj.js → chunk-wvq717b5.js} +2 -2
- package/bin/chunk-xbge27m4.js +1 -0
- package/bin/{chunk-ysv80zyb.js → chunk-xca338dw.js} +3 -3
- package/bin/chunk-xcsz1wp7.js +1 -0
- package/bin/{chunk-ehpfg3km.js → chunk-xznabrt2.js} +1 -1
- package/bin/{chunk-pvg3msgw.js → chunk-xzyfnfck.js} +3 -3
- package/bin/{chunk-9trnkbtr.js → chunk-ycw3rwhx.js} +3 -3
- package/bin/{chunk-qbqym9m6.js → chunk-yqvhgtez.js} +2 -2
- package/bin/{chunk-4syt6rn0.js → chunk-yr03tf5r.js} +2 -2
- package/bin/{chunk-n3xjwszr.js → chunk-z9jpgxf1.js} +1 -1
- package/bin/chunk-zb0az2tq.js +2 -0
- package/bin/{chunk-pwkby9h7.js → chunk-zbt4h7n0.js} +1 -1
- package/bin/{chunk-kk42xhgz.js → chunk-zcdqsp1e.js} +1 -1
- package/bin/chunk-zej27b5c.js +2 -0
- package/bin/{chunk-axmd242s.js → chunk-zmjtv19e.js} +1 -1
- package/bin/{chunk-7e5z637e.js → chunk-zr11zfwc.js} +1 -1
- package/bin/{chunk-k6avge95.js → chunk-zz0522zr.js} +4 -4
- package/bin/shumai-app.html +1 -1
- package/bin/shumai-app.js +294 -293
- package/package.json +7 -7
- package/bin/chunk-0c67210c.js +0 -1
- package/bin/chunk-2z1pnt7h.js +0 -2
- package/bin/chunk-3vmapyk9.js +0 -1
- package/bin/chunk-886pnknh.js +0 -3
- package/bin/chunk-908pypkr.js +0 -1
- package/bin/chunk-952qwf17.js +0 -2
- package/bin/chunk-9a2tf0mh.js +0 -2
- package/bin/chunk-apfrw0wd.js +0 -3
- package/bin/chunk-batadmvr.js +0 -2
- package/bin/chunk-bvdvp192.js +0 -1
- package/bin/chunk-db1msmdh.js +0 -2
- package/bin/chunk-dkx3pmdz.js +0 -1
- package/bin/chunk-hacyjx1s.js +0 -1
- package/bin/chunk-he5nvmqw.js +0 -1
- package/bin/chunk-hyr1vtfp.js +0 -1
- package/bin/chunk-jh8q3885.js +0 -211
- package/bin/chunk-jzbrt2vk.js +0 -1
- package/bin/chunk-nqym3zbs.js +0 -1
- package/bin/chunk-sebbjvgv.css +0 -1
- package/bin/chunk-t8gv2ekj.js +0 -14
- package/bin/chunk-vm5tn0zm.js +0 -2
- package/bin/chunk-wmjp8dcm.js +0 -1
- package/bin/chunk-wy8dkyxj.js +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ts}from"./chunk-dbw8c1jj.js";import{ur,Lt,Ji,lf,Mo,cf,Xi,za,jr,or,fe,Gt,Su,Ye,mc,as,ja,Eu,hc,Cs,Cu,ko,gc,is,ho,uf,zt,De,dr}from"./chunk-9nvymwqj.js";import{ra,el,tl}from"./chunk-b9hyc0a1.js";import{On,Qt,jo,Is,na,Iu,oa,cm,Kt,Ir,f,Kn,ze,um,Ln,Sn,Zt,ls,cs,Zn,Jr,En}from"./chunk-hxyg5q2a.js";var _=f({is(e){return e.kind==="AlterTableNode"},create(e){return f({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,t){return f({...e,...t})},cloneWithColumnAlteration(e,t){return f({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}});var M=f({is(e){return e.kind==="CreateIndexNode"},create(e){return f({kind:"CreateIndexNode",name:ze.create(e)})},cloneWith(e,t){return f({...e,...t})},cloneWithColumns(e,t){return f({...e,columns:[...e.columns||[],...t]})}});var Oe=f({is(e){return e.kind==="CreateSchemaNode"},create(e,t){return f({kind:"CreateSchemaNode",schema:ze.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var H=f({is(e){return e.kind==="DropIndexNode"},create(e,t){return f({kind:"DropIndexNode",name:Sn.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var Ce=f({is(e){return e.kind==="DropSchemaNode"},create(e,t){return f({kind:"DropSchemaNode",schema:ze.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var Te=f({is(e){return e.kind==="DropTableNode"},create(e,t){return f({kind:"DropTableNode",table:e,...t})},cloneWith(e,t){return f({...e,...t})}});var Ke=f({is(e){return e.kind==="AddColumnNode"},create(e){return f({kind:"AddColumnNode",column:e})}});var b=f({is(e){return e.kind==="ColumnDefinitionNode"},create(e,t){return f({kind:"ColumnDefinitionNode",column:Lt.create(e),dataType:t})},cloneWithFrontModifier(e,t){return f({...e,frontModifiers:e.frontModifiers?f([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return f({...e,endModifiers:e.endModifiers?f([...e.endModifiers,t]):[t]})},cloneWith(e,t){return f({...e,...t})}});var Ge=f({is(e){return e.kind==="DropColumnNode"},create(e){return f({kind:"DropColumnNode",column:Lt.create(e)})}});var Je=f({is(e){return e.kind==="RenameColumnNode"},create(e,t){return f({kind:"RenameColumnNode",column:Lt.create(e),renameTo:Lt.create(t)})}});var ie=f({is(e){return e.kind==="CheckConstraintNode"},create(e,t){return f({kind:"CheckConstraintNode",expression:e,name:t?ze.create(t):void 0})}});var vt=["no action","restrict","cascade","set null","set default"],se=f({is(e){return e.kind==="ReferencesNode"},create(e,t){return f({kind:"ReferencesNode",table:e,columns:f([...t])})},cloneWithOnDelete(e,t){return f({...e,onDelete:t})},cloneWithOnUpdate(e,t){return f({...e,onUpdate:t})}});function Se(e){return ur(e)?e.toOperationNode():jr.createImmediate(e)}var ge=f({is(e){return e.kind==="GeneratedNode"},create(e){return f({kind:"GeneratedNode",...e})},createWithExpression(e){return f({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,t){return f({...e,...t})}});var qt=f({is(e){return e.kind==="DefaultValueNode"},create(e){return f({kind:"DefaultValueNode",defaultValue:e})}});function ae(e){if(vt.includes(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}class I{#e;constructor(e){this.#e=e}autoIncrement(){return new I(b.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new I(b.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new I(b.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=Mo(e);if(!t.table||Ji.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new I(b.cloneWith(this.#e,{references:se.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error("on delete constraint can only be added for foreign keys");return new I(b.cloneWith(this.#e,{references:se.cloneWithOnDelete(this.#e.references,ae(e))}))}onUpdate(e){if(!this.#e.references)throw Error("on update constraint can only be added for foreign keys");return new I(b.cloneWith(this.#e,{references:se.cloneWithOnUpdate(this.#e.references,ae(e))}))}unique(){return new I(b.cloneWith(this.#e,{unique:!0}))}notNull(){return new I(b.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new I(b.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new I(b.cloneWith(this.#e,{defaultTo:qt.create(Se(e))}))}check(e){return new I(b.cloneWith(this.#e,{check:ie.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new I(b.cloneWith(this.#e,{generated:ge.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new I(b.cloneWith(this.#e,{generated:ge.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new I(b.cloneWith(this.#e,{generated:ge.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new I(b.cloneWith(this.#e,{generated:ge.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new I(b.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new I(b.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new I(b.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new I(b.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}var He=f({is(e){return e.kind==="ModifyColumnNode"},create(e){return f({kind:"ModifyColumnNode",column:e})}});var W=f({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,t,r,n){return f({kind:"ForeignKeyConstraintNode",columns:e,references:se.create(t,r),name:n?ze.create(n):void 0})},cloneWith(e,t){return f({...e,...t})}});class P{#e;constructor(e){this.#e=e}onDelete(e){return new P(W.cloneWith(this.#e,{onDelete:ae(e)}))}onUpdate(e){return new P(W.cloneWith(this.#e,{onUpdate:ae(e)}))}deferrable(){return new P(W.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new P(W.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new P(W.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new P(W.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}var ce=f({is(e){return e.kind==="AddConstraintNode"},create(e){return f({kind:"AddConstraintNode",constraint:e})}});var R=f({is(e){return e.kind==="UniqueConstraintNode"},create(e,t,r){return f({kind:"UniqueConstraintNode",columns:f(e.map(Lt.create)),name:t?ze.create(t):void 0,nullsNotDistinct:r})},cloneWith(e,t){return f({...e,...t})}});var ue=f({is(e){return e.kind==="DropConstraintNode"},create(e){return f({kind:"DropConstraintNode",constraintName:ze.create(e)})},cloneWith(e,t){return f({...e,...t})}});var le=f({is(e){return e.kind==="AlterColumnNode"},create(e,t,r){return f({kind:"AlterColumnNode",column:Lt.create(e),[t]:r})}});class ke{#e;constructor(e){this.#e=e}setDataType(e){return new me(le.create(this.#e,"dataType",is(e)))}setDefault(e){return new me(le.create(this.#e,"setDefault",Se(e)))}dropDefault(){return new me(le.create(this.#e,"dropDefault",!0))}setNotNull(){return new me(le.create(this.#e,"setNotNull",!0))}dropNotNull(){return new me(le.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class me{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class Y{#e;constructor(e){this.#e=f(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class j{#e;constructor(e){this.#e=f(e)}onDelete(e){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class re{#e;constructor(e){this.#e=f(e)}ifExists(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{modifier:"restrict"})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var V=f({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,t){return f({kind:"PrimaryKeyConstraintNode",columns:f(e.map(Lt.create)),name:t?ze.create(t):void 0})},cloneWith(e,t){return f({...e,...t})}});var X=f({is(e){return e.kind==="AddIndexNode"},create(e){return f({kind:"AddIndexNode",name:ze.create(e)})},cloneWith(e,t){return f({...e,...t})},cloneWithColumns(e,t){return f({...e,columns:[...e.columns||[],...t]})}});class Z{#e;constructor(e){this.#e=f(e)}unique(){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,[Xi(e)])})})}columns(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,e.map(Xi))})})}expression(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWith(this.#e.node.addIndex,{using:Zt.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Q{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new Q(R.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new Q(R.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new Q(R.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new Q(R.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new Q(R.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class U{#e;constructor(e){this.#e=e}deferrable(){return new U(V.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new U(V.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new U(V.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new U(V.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class Ee{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}var Dt=f({is(e){return e.kind==="RenameConstraintNode"},create(e,t){return f({kind:"RenameConstraintNode",oldName:ze.create(e),newName:ze.create(t)})}});class Xe{#e;constructor(e){this.#e=f(e)}renameTo(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{renameTo:zt(e)})})}setSchema(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{setSchema:ze.create(e)})})}alterColumn(e,t){let r=t(new ke(e));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ge.create(e))})}renameColumn(e,t){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Je.create(e,t))})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,is(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ke.create(n.toOperationNode()))})}modifyColumn(e,t,r=Kn){let n=r(new I(b.create(e,is(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,He.create(n.toOperationNode()))})}addUniqueConstraint(e,t,r=Kn){let n=r(new Q(R.create(t,e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}addCheckConstraint(e,t,r=Kn){let n=r(new Ee(ie.create(t.toOperationNode(),e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}addForeignKeyConstraint(e,t,r,n,o=Kn){let d=o(new P(W.create(t.map(Lt.create),zt(r),n.map(Lt.create),e)));return new j({...this.#e,constraintBuilder:d})}addPrimaryKeyConstraint(e,t,r=Kn){let n=r(new U(V.create(t,e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}dropConstraint(e){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.create(e)})})}renameConstraint(e,t){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{renameConstraint:Dt.create(e,t)})})}addIndex(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.create(e)})})}dropIndex(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropIndex:H.create(e)})})}$call(e){return e(this)}}class L{#e;constructor(e){this.#e=f(e)}alterColumn(e,t){let r=t(new ke(e));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ge.create(e))})}renameColumn(e,t){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Je.create(e,t))})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,is(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ke.create(n.toOperationNode()))})}modifyColumn(e,t,r=Kn){let n=r(new I(b.create(e,is(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,He.create(n.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class be extends mc{transformPrimitiveValueList(e){return za.create(e.values.map(jr.createImmediate))}transformValue(e){return jr.createImmediate(e.value)}}class S{#e;constructor(e){this.#e=f(e)}ifNotExists(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new S({...this.#e,node:M.cloneWith(this.#e.node,{table:zt(e)})})}column(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,[Xi(e)])})}columns(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,e.map(Xi))})}expression(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new S({...this.#e,node:M.cloneWith(this.#e.node,{using:Zt.createWithSql(e)})})}where(...e){let t=new be;return new S({...this.#e,node:fe.cloneWithWhere(this.#e.node,t.transformNode(or(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Me{#e;constructor(e){this.#e=f(e)}ifNotExists(){return new Me({...this.#e,node:Oe.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function Ot(e){if(um.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}class O{#e;constructor(e){this.#e=f(e)}temporary(){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{onCommit:Ot(e)})})}ifNotExists(){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,is(t))));return new O({...this.#e,node:Ln.cloneWithColumn(this.#e.node,n.toOperationNode())})}addPrimaryKeyConstraint(e,t,r=Kn){let n=r(new U(V.create(t,e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addUniqueConstraint(e,t,r=Kn){let n=r(new Q(R.create(t,e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addCheckConstraint(e,t,r=Kn){let n=r(new Ee(ie.create(t.toOperationNode(),e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addForeignKeyConstraint(e,t,r,n,o=Kn){let d=o(new P(W.create(t.map(Lt.create),zt(r),n.map(Lt.create),e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,d.toOperationNode())})}modifyFront(e){return new O({...this.#e,node:Ln.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new O({...this.#e,node:Ln.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{selectQuery:ho(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class de{#e;constructor(e){this.#e=f(e)}on(e){return new de({...this.#e,node:H.cloneWith(this.#e.node,{table:zt(e)})})}ifExists(){return new de({...this.#e,node:H.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new de({...this.#e,node:H.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ie{#e;constructor(e){this.#e=f(e)}ifExists(){return new Ie({...this.#e,node:Ce.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ie({...this.#e,node:Ce.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ae{#e;constructor(e){this.#e=f(e)}ifExists(){return new Ae({...this.#e,node:Te.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ae({...this.#e,node:Te.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ze{#e=new be;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class B{#e;constructor(e){this.#e=f(e)}temporary(){return new B({...this.#e,node:cs.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new B({...this.#e,node:cs.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new B({...this.#e,node:cs.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new B({...this.#e,node:cs.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new B({...this.#e,node:cs.cloneWith(this.#e.node,{columns:e.map(cf)})})}as(e){let t=e.withPlugin(new Ze).toOperationNode();return new B({...this.#e,node:cs.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var he=f({is(e){return e.kind==="DropViewNode"},create(e){return f({kind:"DropViewNode",name:Sn.create(e)})},cloneWith(e,t){return f({...e,...t})}});class pe{#e;constructor(e){this.#e=f(e)}materialized(){return new pe({...this.#e,node:he.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new pe({...this.#e,node:he.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new pe({...this.#e,node:he.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var We=f({is(e){return e.kind==="CreateTypeNode"},create(e){return f({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,t){return f({...e,enum:za.create(t.map(jr.createImmediate))})}});class Pe{#e;constructor(e){this.#e=f(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new Pe({...this.#e,node:We.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var Le=f({is(e){return e.kind==="DropTypeNode"},create(e){return f({kind:"DropTypeNode",name:e})},cloneWith(e,t){return f({...e,...t})}});class Re{#e;constructor(e){this.#e=f(e)}ifExists(){return new Re({...this.#e,node:Le.cloneWith(this.#e.node,{ifExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function et(e){if(e.includes(".")){let r=e.split(".").map(Xt);if(r.length===2)return Sn.createWithSchema(r[0],r[1]);else throw Error(`invalid schemable identifier ${e}`)}else return Sn.create(e)}function Xt(e){return e.trim()}var ye=f({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return f({kind:"RefreshMaterializedViewNode",name:Sn.create(e)})},cloneWith(e,t){return f({...e,...t})}});class we{#e;constructor(e){this.#e=f(e)}concurrently(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class xe{#e;constructor(e){this.#e=e}createTable(e){return new O({queryId:Ye(),executor:this.#e,node:Ln.create(zt(e))})}dropTable(e){return new Ae({queryId:Ye(),executor:this.#e,node:Te.create(zt(e))})}createIndex(e){return new S({queryId:Ye(),executor:this.#e,node:M.create(e)})}dropIndex(e){return new de({queryId:Ye(),executor:this.#e,node:H.create(e)})}createSchema(e){return new Me({queryId:Ye(),executor:this.#e,node:Oe.create(e)})}dropSchema(e){return new Ie({queryId:Ye(),executor:this.#e,node:Ce.create(e)})}alterTable(e){return new Xe({queryId:Ye(),executor:this.#e,node:_.create(zt(e))})}createView(e){return new B({queryId:Ye(),executor:this.#e,node:cs.create(e)})}refreshMaterializedView(e){return new we({queryId:Ye(),executor:this.#e,node:ye.create(e)})}dropView(e){return new pe({queryId:Ye(),executor:this.#e,node:he.create(e)})}createType(e){return new Pe({queryId:Ye(),executor:this.#e,node:We.create(et(e))})}dropType(e){return new Re({queryId:Ye(),executor:this.#e,node:Le.create(et(e))})}withPlugin(e){return new xe(this.#e.withPlugin(e))}withoutPlugins(){return new xe(this.#e.withoutPlugins())}withSchema(e){return new xe(this.#e.withPluginAtFront(new as(e)))}}class tt{ref(e){return new lf(e)}table(e){return new uf(e)}}class rt{#e;constructor(e){this.#e=e}async provideConnection(e){let t=await this.#e.acquireConnection();try{return await e(t)}finally{await this.#e.releaseConnection(t)}}}class ee extends hc{#e;#t;#r;constructor(e,t,r,n=[]){super(n);this.#e=e,this.#t=t,this.#r=r}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#r.provideConnection(e)}withPlugins(e){return new ee(this.#e,this.#t,this.#r,[...this.plugins,...e])}withPlugin(e){return new ee(this.#e,this.#t,this.#r,[...this.plugins,e])}withPluginAtFront(e){return new ee(this.#e,this.#t,this.#r,[e,...this.plugins])}withConnectionProvider(e){return new ee(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new ee(this.#e,this.#t,this.#r,[])}}function Qe(){if(typeof performance<"u"&&Kt(performance.now))return performance.now();else return Date.now()}class nt{#e;#t;#r;#n;#o;#i=new WeakSet;constructor(e,t){this.#n=!1,this.#e=e,this.#t=t}async init(){if(this.#o)throw Error("driver has already been destroyed");if(!this.#r)this.#r=this.#e.init().then(()=>{this.#n=!0}).catch((e)=>(this.#r=void 0,Promise.reject(e)));await this.#r}async acquireConnection(){if(this.#o)throw Error("driver has already been destroyed");if(!this.#n)await this.init();let e=await this.#e.acquireConnection();if(!this.#i.has(e)){if(this.#a())this.#c(e);this.#i.add(e)}return e}async releaseConnection(e){await this.#e.releaseConnection(e)}beginTransaction(e,t){return this.#e.beginTransaction(e,t)}commitTransaction(e){return this.#e.commitTransaction(e)}rollbackTransaction(e){return this.#e.rollbackTransaction(e)}savepoint(e,t,r){if(this.#e.savepoint)return this.#e.savepoint(e,t,r);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(e,t,r){if(this.#e.rollbackToSavepoint)return this.#e.rollbackToSavepoint(e,t,r);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(e,t,r){if(this.#e.releaseSavepoint)return this.#e.releaseSavepoint(e,t,r);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#r)return;if(await this.#r,!this.#o)this.#o=this.#e.destroy().catch((e)=>(this.#o=void 0,Promise.reject(e)));await this.#o}#a(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#c(e){let{executeQuery:t,streamQuery:r}=e,n=this;e.executeQuery=async(o)=>{let d,l=Qe();try{return await t.call(e,o)}catch(g){throw d=g,await n.#s(g,o,l),g}finally{if(!d)await n.#u(o,l)}},e.streamQuery=async function*(o,d){let l,g=Qe();try{for await(let A of r.call(e,o,d))yield A}catch(A){throw l=A,await n.#s(A,o,g),A}finally{if(!l)await n.#u(o,g,!0)}}}async#s(e,t,r){await this.#t.error(()=>({level:"error",error:e,query:t,queryDurationMillis:this.#l(r)}))}async#u(e,t,r=!1){await this.#t.query(()=>({level:"query",isStream:r,query:e,queryDurationMillis:this.#l(t)}))}#l(e){return Qe()-e}}var er=()=>{};class ve{#e;#t;constructor(e){this.#e=e}async provideConnection(e){while(this.#t)await this.#t.catch(er);return this.#t=this.#r(e).finally(()=>{this.#t=void 0}),this.#t}async#r(e){return await e(this.#e)}}var tr=["read only","read write"],rr=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function ot(e){if(e.accessMode&&!tr.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!rr.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}var nr=["query","error"],Ra=f(nr);class it{#e;#t;constructor(e){if(Kt(e))this.#t=e,this.#e=f({query:!0,error:!0});else this.#t=ir,this.#e=f({query:e.includes("query"),error:e.includes("error")})}isLevelEnabled(e){return this.#e[e]}async query(e){if(this.#e.query)await this.#t(e())}async error(e){if(this.#e.error)await this.#t(e())}}function ir(e){if(e.level==="query"){let t=`kysely:query:${e.isStream?"stream:":""}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else if(e.level==="error")if(e.error instanceof Error)console.error(`kysely:error: ${e.error.stack??e.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`)}function St(e){return Ir(e)&&Kt(e.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class F extends Cs{#e;constructor(e){let t,r;if(sr(e))t={executor:e.executor},r={...e};else{let n=e.dialect,o=n.createDriver(),d=n.createQueryCompiler(),l=n.createAdapter(),g=new it(e.log??[]),A=new nt(o,g),D=new rt(A),z=new ee(d,l,D,e.plugins??[]);t={executor:z},r={config:e,executor:z,dialect:n,driver:A}}super(t);this.#e=f(r)}get schema(){return new xe(this.#e.executor)}get dynamic(){return new tt}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new gc({node:ko.create(On(e)?void 0:ho(e))})}get fn(){return Cu()}transaction(){return new $e({...this.#e})}startTransaction(){return new Fe({...this.#e})}connection(){return new kt({...this.#e})}withPlugin(e){return new F({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new F({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new F({...this.#e,executor:this.#e.executor.withPluginAtFront(new as(e))})}withTables(){return new F({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,t){if(t!==void 0)ls("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let r=St(e)?e.compile():e;return this.getExecutor().executeQuery(r)}async[Symbol.asyncDispose](){await this.destroy()}}class oe extends F{#e;constructor(e){super(e);this.#e=e}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(e){return new oe({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new oe({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new oe({...this.#e,executor:this.#e.executor.withPluginAtFront(new as(e))})}withTables(){return new oe({...this.#e})}}function sr(e){return Ir(e)&&Ir(e.config)&&Ir(e.driver)&&Ir(e.executor)&&Ir(e.dialect)}class kt{#e;constructor(e){this.#e=f(e)}async execute(e){return this.#e.executor.provideConnection(async(t)=>{let r=this.#e.executor.withConnectionProvider(new ve(t)),n=new F({...this.#e,executor:r});return await e(n)})}}class $e{#e;constructor(e){this.#e=f(e)}setAccessMode(e){return new $e({...this.#e,accessMode:e})}setIsolationLevel(e){return new $e({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:r,...n}=this.#e,o={isolationLevel:t,accessMode:r};return ot(o),this.#e.executor.provideConnection(async(d)=>{let l={isCommitted:!1,isRolledBack:!1},g=new G(this.#e.executor.withConnectionProvider(new ve(d)),l),A=new oe({...n,executor:g}),D=!1;try{await this.#e.driver.beginTransaction(d,o),D=!0;let z=await e(A);return await this.#e.driver.commitTransaction(d),l.isCommitted=!0,z}catch(z){if(D)await this.#e.driver.rollbackTransaction(d),l.isRolledBack=!0;throw z}})}}class Fe{#e;constructor(e){this.#e=f(e)}setAccessMode(e){return new Fe({...this.#e,accessMode:e})}setIsolationLevel(e){return new Fe({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...r}=this.#e,n={isolationLevel:e,accessMode:t};ot(n);let o=await Eu(this.#e.executor);return await this.#e.driver.beginTransaction(o.connection,n),new K({...r,connection:o,executor:this.#e.executor.withConnectionProvider(new ve(o.connection))})}}class K extends oe{#e;#t;#r;constructor(e){let t={isCommitted:!1,isRolledBack:!1};e={...e,executor:new G(e.executor,t)};let{connection:r,...n}=e;super(n);this.#e=f(e),this.#r=t;let o=Ye();this.#t=(d)=>e.executor.compileQuery(d,o)}get isCommitted(){return this.#r.isCommitted}get isRolledBack(){return this.#r.isRolledBack}commit(){return ne(this.#r),new Ne(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#r.isCommitted=!0,this.#e.connection.release()})}rollback(){return ne(this.#r),new Ne(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#r.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}rollbackToSavepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}releaseSavepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}withPlugin(e){return new K({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new K({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new K({...this.#e,executor:this.#e.executor.withPluginAtFront(new as(e))})}withTables(){return new K({...this.#e})}}class Ne{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function ne(e){if(e.isCommitted)throw Error("Transaction is already committed");if(e.isRolledBack)throw Error("Transaction is already rolled back")}class G{#e;#t;constructor(e,t){if(e instanceof G)this.#e=e.#e;else this.#e=e;this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#e.provideConnection(e)}executeQuery(e){return ne(this.#t),this.#e.executeQuery(e)}stream(e,t){return ne(this.#t),this.#e.stream(e,t)}withConnectionProvider(e){return new G(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new G(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new G(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new G(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new G(this.#e.withoutPlugins(),this.#t)}}function k(e,t){return Zt.createWithChildren([Zt.createWithSql(`${e} `),ze.create(t)])}class st{#e;#t=new Wt;#r;#n;constructor(e){this.#e=f({...e})}async init(){if(this.#r=Kt(this.#e.database)?await this.#e.database():this.#e.database,this.#n=new Mt(this.#r),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#n)}async acquireConnection(){return await this.#t.lock(),this.#n}async beginTransaction(e){await e.executeQuery(dr.raw("begin"))}async commitTransaction(e){await e.executeQuery(dr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(dr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release",t),Ye()))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#r?.close()}}class Mt{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:r}=e,n=this.#e.prepare(t);if(n.reader)return Promise.resolve({rows:n.all(r)});let{changes:o,lastInsertRowid:d}=n.run(r);return Promise.resolve({numAffectedRows:o!==void 0&&o!==null?BigInt(o):void 0,insertId:d!==void 0&&d!==null?BigInt(d):void 0,rows:[]})}async*streamQuery(e,t){let{sql:r,parameters:n,query:o}=e,d=this.#e.prepare(r);if(Gt.is(o)){let l=d.iterate(n);for(let g of l)yield{rows:[g]}}else throw Error("Sqlite driver only supports streaming of select queries")}}class Wt{#e;#t;async lock(){while(this.#e)await this.#e;this.#e=new Promise((e)=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}}class at{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#r(e)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e,t){let r=e.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!t.withInternalKyselyTables)r=r.where("name","!=",Jr).where("name","!=",En);return r}async#r(e){let t=await this.#t(this.#e,e).execute(),r=await this.#e.with("table_list",(o)=>this.#t(o,e)).selectFrom(["table_list as tl",De`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),n={};for(let o of r)n[o.table]??=[],n[o.table].push(o);return t.map(({name:o,sql:d,type:l})=>{let g=d?.split(/[\(\),]/)?.find((D)=>D.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),A=n[o]??[];if(!g){let D=A.filter((z)=>z.pk>0);if(D.length===1&&D[0].type.toLowerCase()==="integer")g=D[0].name}return{name:o,isView:l==="view",columns:A.map((D)=>({name:D.name,dataType:D.type,isNullable:!D.notnull,isAutoIncrementing:D.name===g,hasDefaultValue:D.dflt_value!=null,comment:void 0}))}})}}class je{#e;constructor(e){this.#e=f({...e})}createDriver(){return new st(this.#e)}createQueryCompiler(){return new el}createAdapter(){return new tl}createIntrospector(e){return new at(e)}}var ar=/"/g;class ct extends Zn{sanitizeIdentifier(e){return e.replace(ar,'""')}}class ut{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((t)=>({name:t.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",De`col_description(a.attrelid, a.attnum)`.as("column_description"),De`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(De`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!e.withInternalKyselyTables)t=t.where("c.relname","!=",Jr).where("c.relname","!=",En);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){let t=new Map;for(let r=0,n=e.length;r<n;r++){let o=e[r],{schema:d,table:l}=o,g=`schema:${d};table:${l}`;if(!t.has(g))t.set(g,f({columns:[],isView:o.table_type==="v",name:l,schema:d}));t.get(g).columns.push(f({comment:o.column_description??void 0,dataType:o.type,dataTypeSchema:o.type_schema,hasDefaultValue:o.has_default,isAutoIncrementing:o.auto_incrementing!==null,isNullable:!o.not_null,name:o.column}))}return Array.from(t.values())}}var cr=BigInt("3853314791062309107");class lt extends ra{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await De`select pg_advisory_xact_lock(${De.lit(cr)})`.execute(e)}async releaseMigrationLock(e,t){}}function _e(e,t){if(lr(e)&&t.stack){let r=t.stack.split(`
|
|
2
|
+
import{Ms}from"./chunk-ebf1r872.js";import{dr,Lt,Ji,uf,Mo,df,Xi,za,jr,sr,de,Gt,Eu,Ye,mc,is,ja,Cu,hc,Is,Iu,ko,gc,ls,ho,ff,zt,De,fr}from"./chunk-wvq717b5.js";import{na,el,tl}from"./chunk-53vtc74g.js";import{On,Qt,qo,Ts,oa,Tu,sa,um,Kt,Ir,f,Kn,ze,dm,Ln,Sn,Zt,cs,us,Zn,Jr,En}from"./chunk-njabdtvb.js";var _=f({is(e){return e.kind==="AlterTableNode"},create(e){return f({kind:"AlterTableNode",table:e})},cloneWithTableProps(e,t){return f({...e,...t})},cloneWithColumnAlteration(e,t){return f({...e,columnAlterations:e.columnAlterations?[...e.columnAlterations,t]:[t]})}});var M=f({is(e){return e.kind==="CreateIndexNode"},create(e){return f({kind:"CreateIndexNode",name:ze.create(e)})},cloneWith(e,t){return f({...e,...t})},cloneWithColumns(e,t){return f({...e,columns:[...e.columns||[],...t]})}});var Oe=f({is(e){return e.kind==="CreateSchemaNode"},create(e,t){return f({kind:"CreateSchemaNode",schema:ze.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var H=f({is(e){return e.kind==="DropIndexNode"},create(e,t){return f({kind:"DropIndexNode",name:Sn.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var Ce=f({is(e){return e.kind==="DropSchemaNode"},create(e,t){return f({kind:"DropSchemaNode",schema:ze.create(e),...t})},cloneWith(e,t){return f({...e,...t})}});var Te=f({is(e){return e.kind==="DropTableNode"},create(e,t){return f({kind:"DropTableNode",table:e,...t})},cloneWith(e,t){return f({...e,...t})}});var Ke=f({is(e){return e.kind==="AddColumnNode"},create(e){return f({kind:"AddColumnNode",column:e})}});var b=f({is(e){return e.kind==="ColumnDefinitionNode"},create(e,t){return f({kind:"ColumnDefinitionNode",column:Lt.create(e),dataType:t})},cloneWithFrontModifier(e,t){return f({...e,frontModifiers:e.frontModifiers?f([...e.frontModifiers,t]):[t]})},cloneWithEndModifier(e,t){return f({...e,endModifiers:e.endModifiers?f([...e.endModifiers,t]):[t]})},cloneWith(e,t){return f({...e,...t})}});var Ge=f({is(e){return e.kind==="DropColumnNode"},create(e){return f({kind:"DropColumnNode",column:Lt.create(e)})}});var Je=f({is(e){return e.kind==="RenameColumnNode"},create(e,t){return f({kind:"RenameColumnNode",column:Lt.create(e),renameTo:Lt.create(t)})}});var ie=f({is(e){return e.kind==="CheckConstraintNode"},create(e,t){return f({kind:"CheckConstraintNode",expression:e,name:t?ze.create(t):void 0})}});var vt=["no action","restrict","cascade","set null","set default"],se=f({is(e){return e.kind==="ReferencesNode"},create(e,t){return f({kind:"ReferencesNode",table:e,columns:f([...t])})},cloneWithOnDelete(e,t){return f({...e,onDelete:t})},cloneWithOnUpdate(e,t){return f({...e,onUpdate:t})}});function Se(e){return dr(e)?e.toOperationNode():jr.createImmediate(e)}var ge=f({is(e){return e.kind==="GeneratedNode"},create(e){return f({kind:"GeneratedNode",...e})},createWithExpression(e){return f({kind:"GeneratedNode",always:!0,expression:e})},cloneWith(e,t){return f({...e,...t})}});var qt=f({is(e){return e.kind==="DefaultValueNode"},create(e){return f({kind:"DefaultValueNode",defaultValue:e})}});function ae(e){if(vt.includes(e))return e;throw Error(`invalid OnModifyForeignAction ${e}`)}class I{#e;constructor(e){this.#e=e}autoIncrement(){return new I(b.cloneWith(this.#e,{autoIncrement:!0}))}identity(){return new I(b.cloneWith(this.#e,{identity:!0}))}primaryKey(){return new I(b.cloneWith(this.#e,{primaryKey:!0}))}references(e){let t=Mo(e);if(!t.table||Ji.is(t.column))throw Error(`invalid call references('${e}'). The reference must have format table.column or schema.table.column`);return new I(b.cloneWith(this.#e,{references:se.create(t.table,[t.column])}))}onDelete(e){if(!this.#e.references)throw Error("on delete constraint can only be added for foreign keys");return new I(b.cloneWith(this.#e,{references:se.cloneWithOnDelete(this.#e.references,ae(e))}))}onUpdate(e){if(!this.#e.references)throw Error("on update constraint can only be added for foreign keys");return new I(b.cloneWith(this.#e,{references:se.cloneWithOnUpdate(this.#e.references,ae(e))}))}unique(){return new I(b.cloneWith(this.#e,{unique:!0}))}notNull(){return new I(b.cloneWith(this.#e,{notNull:!0}))}unsigned(){return new I(b.cloneWith(this.#e,{unsigned:!0}))}defaultTo(e){return new I(b.cloneWith(this.#e,{defaultTo:qt.create(Se(e))}))}check(e){return new I(b.cloneWith(this.#e,{check:ie.create(e.toOperationNode())}))}generatedAlwaysAs(e){return new I(b.cloneWith(this.#e,{generated:ge.createWithExpression(e.toOperationNode())}))}generatedAlwaysAsIdentity(){return new I(b.cloneWith(this.#e,{generated:ge.create({identity:!0,always:!0})}))}generatedByDefaultAsIdentity(){return new I(b.cloneWith(this.#e,{generated:ge.create({identity:!0,byDefault:!0})}))}stored(){if(!this.#e.generated)throw Error("stored() can only be called after generatedAlwaysAs");return new I(b.cloneWith(this.#e,{generated:ge.cloneWith(this.#e.generated,{stored:!0})}))}modifyFront(e){return new I(b.cloneWithFrontModifier(this.#e,e.toOperationNode()))}nullsNotDistinct(){return new I(b.cloneWith(this.#e,{nullsNotDistinct:!0}))}ifNotExists(){return new I(b.cloneWith(this.#e,{ifNotExists:!0}))}modifyEnd(e){return new I(b.cloneWithEndModifier(this.#e,e.toOperationNode()))}$call(e){return e(this)}toOperationNode(){return this.#e}}var He=f({is(e){return e.kind==="ModifyColumnNode"},create(e){return f({kind:"ModifyColumnNode",column:e})}});var W=f({is(e){return e.kind==="ForeignKeyConstraintNode"},create(e,t,r,n){return f({kind:"ForeignKeyConstraintNode",columns:e,references:se.create(t,r),name:n?ze.create(n):void 0})},cloneWith(e,t){return f({...e,...t})}});class P{#e;constructor(e){this.#e=e}onDelete(e){return new P(W.cloneWith(this.#e,{onDelete:ae(e)}))}onUpdate(e){return new P(W.cloneWith(this.#e,{onUpdate:ae(e)}))}deferrable(){return new P(W.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new P(W.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new P(W.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new P(W.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}var ce=f({is(e){return e.kind==="AddConstraintNode"},create(e){return f({kind:"AddConstraintNode",constraint:e})}});var R=f({is(e){return e.kind==="UniqueConstraintNode"},create(e,t,r){return f({kind:"UniqueConstraintNode",columns:f(e.map(Lt.create)),name:t?ze.create(t):void 0,nullsNotDistinct:r})},cloneWith(e,t){return f({...e,...t})}});var ue=f({is(e){return e.kind==="DropConstraintNode"},create(e){return f({kind:"DropConstraintNode",constraintName:ze.create(e)})},cloneWith(e,t){return f({...e,...t})}});var le=f({is(e){return e.kind==="AlterColumnNode"},create(e,t,r){return f({kind:"AlterColumnNode",column:Lt.create(e),[t]:r})}});class ke{#e;constructor(e){this.#e=e}setDataType(e){return new me(le.create(this.#e,"dataType",ls(e)))}setDefault(e){return new me(le.create(this.#e,"setDefault",Se(e)))}dropDefault(){return new me(le.create(this.#e,"dropDefault",!0))}setNotNull(){return new me(le.create(this.#e,"setNotNull",!0))}dropNotNull(){return new me(le.create(this.#e,"dropNotNull",!0))}$call(e){return e(this)}}class me{#e;constructor(e){this.#e=e}toOperationNode(){return this.#e}}class Y{#e;constructor(e){this.#e=f(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class j{#e;constructor(e){this.#e=f(e)}onDelete(e){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.onDelete(e)})}onUpdate(e){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.onUpdate(e)})}deferrable(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.deferrable()})}notDeferrable(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.notDeferrable()})}initiallyDeferred(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyDeferred()})}initiallyImmediate(){return new j({...this.#e,constraintBuilder:this.#e.constraintBuilder.initiallyImmediate()})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(this.#e.constraintBuilder.toOperationNode())}),this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class re{#e;constructor(e){this.#e=f(e)}ifExists(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{ifExists:!0})})})}cascade(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{modifier:"cascade"})})})}restrict(){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.cloneWith(this.#e.node.dropConstraint,{modifier:"restrict"})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var V=f({is(e){return e.kind==="PrimaryKeyConstraintNode"},create(e,t){return f({kind:"PrimaryKeyConstraintNode",columns:f(e.map(Lt.create)),name:t?ze.create(t):void 0})},cloneWith(e,t){return f({...e,...t})}});var X=f({is(e){return e.kind==="AddIndexNode"},create(e){return f({kind:"AddIndexNode",name:ze.create(e)})},cloneWith(e,t){return f({...e,...t})},cloneWithColumns(e,t){return f({...e,columns:[...e.columns||[],...t]})}});class Z{#e;constructor(e){this.#e=f(e)}unique(){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWith(this.#e.node.addIndex,{unique:!0})})})}column(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,[Xi(e)])})})}columns(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,e.map(Xi))})})}expression(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWithColumns(this.#e.node.addIndex,[e.toOperationNode()])})})}using(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.cloneWith(this.#e.node.addIndex,{using:Zt.createWithSql(e)})})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Q{#e;constructor(e){this.#e=e}nullsNotDistinct(){return new Q(R.cloneWith(this.#e,{nullsNotDistinct:!0}))}deferrable(){return new Q(R.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new Q(R.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new Q(R.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new Q(R.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class U{#e;constructor(e){this.#e=e}deferrable(){return new U(V.cloneWith(this.#e,{deferrable:!0}))}notDeferrable(){return new U(V.cloneWith(this.#e,{deferrable:!1}))}initiallyDeferred(){return new U(V.cloneWith(this.#e,{initiallyDeferred:!0}))}initiallyImmediate(){return new U(V.cloneWith(this.#e,{initiallyDeferred:!1}))}$call(e){return e(this)}toOperationNode(){return this.#e}}class Ee{#e;constructor(e){this.#e=e}$call(e){return e(this)}toOperationNode(){return this.#e}}var Dt=f({is(e){return e.kind==="RenameConstraintNode"},create(e,t){return f({kind:"RenameConstraintNode",oldName:ze.create(e),newName:ze.create(t)})}});class Xe{#e;constructor(e){this.#e=f(e)}renameTo(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{renameTo:zt(e)})})}setSchema(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{setSchema:ze.create(e)})})}alterColumn(e,t){let r=t(new ke(e));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ge.create(e))})}renameColumn(e,t){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Je.create(e,t))})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,ls(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ke.create(n.toOperationNode()))})}modifyColumn(e,t,r=Kn){let n=r(new I(b.create(e,ls(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,He.create(n.toOperationNode()))})}addUniqueConstraint(e,t,r=Kn){let n=r(new Q(R.create(t,e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}addCheckConstraint(e,t,r=Kn){let n=r(new Ee(ie.create(t.toOperationNode(),e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}addForeignKeyConstraint(e,t,r,n,o=Kn){let d=o(new P(W.create(t.map(Lt.create),zt(r),n.map(Lt.create),e)));return new j({...this.#e,constraintBuilder:d})}addPrimaryKeyConstraint(e,t,r=Kn){let n=r(new U(V.create(t,e)));return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addConstraint:ce.create(n.toOperationNode())})})}dropConstraint(e){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropConstraint:ue.create(e)})})}renameConstraint(e,t){return new re({...this.#e,node:_.cloneWithTableProps(this.#e.node,{renameConstraint:Dt.create(e,t)})})}addIndex(e){return new Z({...this.#e,node:_.cloneWithTableProps(this.#e.node,{addIndex:X.create(e)})})}dropIndex(e){return new Y({...this.#e,node:_.cloneWithTableProps(this.#e.node,{dropIndex:H.create(e)})})}$call(e){return e(this)}}class L{#e;constructor(e){this.#e=f(e)}alterColumn(e,t){let r=t(new ke(e));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,r.toOperationNode())})}dropColumn(e){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ge.create(e))})}renameColumn(e,t){return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Je.create(e,t))})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,ls(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,Ke.create(n.toOperationNode()))})}modifyColumn(e,t,r=Kn){let n=r(new I(b.create(e,ls(t))));return new L({...this.#e,node:_.cloneWithColumnAlteration(this.#e.node,He.create(n.toOperationNode()))})}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class be extends mc{transformPrimitiveValueList(e){return za.create(e.values.map(jr.createImmediate))}transformValue(e){return jr.createImmediate(e.value)}}class S{#e;constructor(e){this.#e=f(e)}ifNotExists(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{ifNotExists:!0})})}unique(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{unique:!0})})}nullsNotDistinct(){return new S({...this.#e,node:M.cloneWith(this.#e.node,{nullsNotDistinct:!0})})}on(e){return new S({...this.#e,node:M.cloneWith(this.#e.node,{table:zt(e)})})}column(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,[Xi(e)])})}columns(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,e.map(Xi))})}expression(e){return new S({...this.#e,node:M.cloneWithColumns(this.#e.node,[e.toOperationNode()])})}using(e){return new S({...this.#e,node:M.cloneWith(this.#e.node,{using:Zt.createWithSql(e)})})}where(...e){let t=new be;return new S({...this.#e,node:de.cloneWithWhere(this.#e.node,t.transformNode(sr(e),this.#e.queryId))})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Me{#e;constructor(e){this.#e=f(e)}ifNotExists(){return new Me({...this.#e,node:Oe.cloneWith(this.#e.node,{ifNotExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function Ot(e){if(dm.includes(e))return e;throw Error(`invalid OnCommitAction ${e}`)}class O{#e;constructor(e){this.#e=f(e)}temporary(){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{temporary:!0})})}onCommit(e){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{onCommit:Ot(e)})})}ifNotExists(){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{ifNotExists:!0})})}addColumn(e,t,r=Kn){let n=r(new I(b.create(e,ls(t))));return new O({...this.#e,node:Ln.cloneWithColumn(this.#e.node,n.toOperationNode())})}addPrimaryKeyConstraint(e,t,r=Kn){let n=r(new U(V.create(t,e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addUniqueConstraint(e,t,r=Kn){let n=r(new Q(R.create(t,e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addCheckConstraint(e,t,r=Kn){let n=r(new Ee(ie.create(t.toOperationNode(),e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,n.toOperationNode())})}addForeignKeyConstraint(e,t,r,n,o=Kn){let d=o(new P(W.create(t.map(Lt.create),zt(r),n.map(Lt.create),e)));return new O({...this.#e,node:Ln.cloneWithConstraint(this.#e.node,d.toOperationNode())})}modifyFront(e){return new O({...this.#e,node:Ln.cloneWithFrontModifier(this.#e.node,e.toOperationNode())})}modifyEnd(e){return new O({...this.#e,node:Ln.cloneWithEndModifier(this.#e.node,e.toOperationNode())})}as(e){return new O({...this.#e,node:Ln.cloneWith(this.#e.node,{selectQuery:ho(e)})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class he{#e;constructor(e){this.#e=f(e)}on(e){return new he({...this.#e,node:H.cloneWith(this.#e.node,{table:zt(e)})})}ifExists(){return new he({...this.#e,node:H.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new he({...this.#e,node:H.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ie{#e;constructor(e){this.#e=f(e)}ifExists(){return new Ie({...this.#e,node:Ce.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ie({...this.#e,node:Ce.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ae{#e;constructor(e){this.#e=f(e)}ifExists(){return new Ae({...this.#e,node:Te.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new Ae({...this.#e,node:Te.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class Ze{#e=new be;transformQuery(e){return this.#e.transformNode(e.node,e.queryId)}transformResult(e){return Promise.resolve(e.result)}}class B{#e;constructor(e){this.#e=f(e)}temporary(){return new B({...this.#e,node:us.cloneWith(this.#e.node,{temporary:!0})})}materialized(){return new B({...this.#e,node:us.cloneWith(this.#e.node,{materialized:!0})})}ifNotExists(){return new B({...this.#e,node:us.cloneWith(this.#e.node,{ifNotExists:!0})})}orReplace(){return new B({...this.#e,node:us.cloneWith(this.#e.node,{orReplace:!0})})}columns(e){return new B({...this.#e,node:us.cloneWith(this.#e.node,{columns:e.map(df)})})}as(e){let t=e.withPlugin(new Ze).toOperationNode();return new B({...this.#e,node:us.cloneWith(this.#e.node,{as:t})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var pe=f({is(e){return e.kind==="DropViewNode"},create(e){return f({kind:"DropViewNode",name:Sn.create(e)})},cloneWith(e,t){return f({...e,...t})}});class fe{#e;constructor(e){this.#e=f(e)}materialized(){return new fe({...this.#e,node:pe.cloneWith(this.#e.node,{materialized:!0})})}ifExists(){return new fe({...this.#e,node:pe.cloneWith(this.#e.node,{ifExists:!0})})}cascade(){return new fe({...this.#e,node:pe.cloneWith(this.#e.node,{cascade:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var We=f({is(e){return e.kind==="CreateTypeNode"},create(e){return f({kind:"CreateTypeNode",name:e})},cloneWithEnum(e,t){return f({...e,enum:za.create(t.map(jr.createImmediate))})}});class Pe{#e;constructor(e){this.#e=f(e)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}asEnum(e){return new Pe({...this.#e,node:We.cloneWithEnum(this.#e.node,e)})}$call(e){return e(this)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}var Le=f({is(e){return e.kind==="DropTypeNode"},create(e){return f({kind:"DropTypeNode",name:e})},cloneWith(e,t){return f({...e,...t})}});class Re{#e;constructor(e){this.#e=f(e)}ifExists(){return new Re({...this.#e,node:Le.cloneWith(this.#e.node,{ifExists:!0})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}function et(e){if(e.includes(".")){let r=e.split(".").map(Xt);if(r.length===2)return Sn.createWithSchema(r[0],r[1]);else throw Error(`invalid schemable identifier ${e}`)}else return Sn.create(e)}function Xt(e){return e.trim()}var ye=f({is(e){return e.kind==="RefreshMaterializedViewNode"},create(e){return f({kind:"RefreshMaterializedViewNode",name:Sn.create(e)})},cloneWith(e,t){return f({...e,...t})}});class we{#e;constructor(e){this.#e=f(e)}concurrently(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{concurrently:!0,withNoData:!1})})}withData(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{withNoData:!1})})}withNoData(){return new we({...this.#e,node:ye.cloneWith(this.#e.node,{withNoData:!0,concurrently:!1})})}$call(e){return e(this)}toOperationNode(){return this.#e.executor.transformQuery(this.#e.node,this.#e.queryId)}compile(){return this.#e.executor.compileQuery(this.toOperationNode(),this.#e.queryId)}async execute(){await this.#e.executor.executeQuery(this.compile())}}class xe{#e;constructor(e){this.#e=e}createTable(e){return new O({queryId:Ye(),executor:this.#e,node:Ln.create(zt(e))})}dropTable(e){return new Ae({queryId:Ye(),executor:this.#e,node:Te.create(zt(e))})}createIndex(e){return new S({queryId:Ye(),executor:this.#e,node:M.create(e)})}dropIndex(e){return new he({queryId:Ye(),executor:this.#e,node:H.create(e)})}createSchema(e){return new Me({queryId:Ye(),executor:this.#e,node:Oe.create(e)})}dropSchema(e){return new Ie({queryId:Ye(),executor:this.#e,node:Ce.create(e)})}alterTable(e){return new Xe({queryId:Ye(),executor:this.#e,node:_.create(zt(e))})}createView(e){return new B({queryId:Ye(),executor:this.#e,node:us.create(e)})}refreshMaterializedView(e){return new we({queryId:Ye(),executor:this.#e,node:ye.create(e)})}dropView(e){return new fe({queryId:Ye(),executor:this.#e,node:pe.create(e)})}createType(e){return new Pe({queryId:Ye(),executor:this.#e,node:We.create(et(e))})}dropType(e){return new Re({queryId:Ye(),executor:this.#e,node:Le.create(et(e))})}withPlugin(e){return new xe(this.#e.withPlugin(e))}withoutPlugins(){return new xe(this.#e.withoutPlugins())}withSchema(e){return new xe(this.#e.withPluginAtFront(new is(e)))}}class tt{ref(e){return new uf(e)}table(e){return new ff(e)}}class rt{#e;constructor(e){this.#e=e}async provideConnection(e){let t=await this.#e.acquireConnection();try{return await e(t)}finally{await this.#e.releaseConnection(t)}}}class ee extends hc{#e;#t;#r;constructor(e,t,r,n=[]){super(n);this.#e=e,this.#t=t,this.#r=r}get adapter(){return this.#t}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#r.provideConnection(e)}withPlugins(e){return new ee(this.#e,this.#t,this.#r,[...this.plugins,...e])}withPlugin(e){return new ee(this.#e,this.#t,this.#r,[...this.plugins,e])}withPluginAtFront(e){return new ee(this.#e,this.#t,this.#r,[e,...this.plugins])}withConnectionProvider(e){return new ee(this.#e,this.#t,e,[...this.plugins])}withoutPlugins(){return new ee(this.#e,this.#t,this.#r,[])}}function Qe(){if(typeof performance<"u"&&Kt(performance.now))return performance.now();else return Date.now()}class nt{#e;#t;#r;#n;#o;#i=new WeakSet;constructor(e,t){this.#n=!1,this.#e=e,this.#t=t}async init(){if(this.#o)throw Error("driver has already been destroyed");if(!this.#r)this.#r=this.#e.init().then(()=>{this.#n=!0}).catch((e)=>(this.#r=void 0,Promise.reject(e)));await this.#r}async acquireConnection(){if(this.#o)throw Error("driver has already been destroyed");if(!this.#n)await this.init();let e=await this.#e.acquireConnection();if(!this.#i.has(e)){if(this.#a())this.#c(e);this.#i.add(e)}return e}async releaseConnection(e){await this.#e.releaseConnection(e)}beginTransaction(e,t){return this.#e.beginTransaction(e,t)}commitTransaction(e){return this.#e.commitTransaction(e)}rollbackTransaction(e){return this.#e.rollbackTransaction(e)}savepoint(e,t,r){if(this.#e.savepoint)return this.#e.savepoint(e,t,r);throw Error("The `savepoint` method is not supported by this driver")}rollbackToSavepoint(e,t,r){if(this.#e.rollbackToSavepoint)return this.#e.rollbackToSavepoint(e,t,r);throw Error("The `rollbackToSavepoint` method is not supported by this driver")}releaseSavepoint(e,t,r){if(this.#e.releaseSavepoint)return this.#e.releaseSavepoint(e,t,r);throw Error("The `releaseSavepoint` method is not supported by this driver")}async destroy(){if(!this.#r)return;if(await this.#r,!this.#o)this.#o=this.#e.destroy().catch((e)=>(this.#o=void 0,Promise.reject(e)));await this.#o}#a(){return this.#t.isLevelEnabled("query")||this.#t.isLevelEnabled("error")}#c(e){let{executeQuery:t,streamQuery:r}=e,n=this;e.executeQuery=async(o)=>{let d,l=Qe();try{return await t.call(e,o)}catch(g){throw d=g,await n.#s(g,o,l),g}finally{if(!d)await n.#u(o,l)}},e.streamQuery=async function*(o,d){let l,g=Qe();try{for await(let A of r.call(e,o,d))yield A}catch(A){throw l=A,await n.#s(A,o,g),A}finally{if(!l)await n.#u(o,g,!0)}}}async#s(e,t,r){await this.#t.error(()=>({level:"error",error:e,query:t,queryDurationMillis:this.#l(r)}))}async#u(e,t,r=!1){await this.#t.query(()=>({level:"query",isStream:r,query:e,queryDurationMillis:this.#l(t)}))}#l(e){return Qe()-e}}var er=()=>{};class ve{#e;#t;constructor(e){this.#e=e}async provideConnection(e){while(this.#t)await this.#t.catch(er);return this.#t=this.#r(e).finally(()=>{this.#t=void 0}),this.#t}async#r(e){return await e(this.#e)}}var tr=["read only","read write"],rr=["read uncommitted","read committed","repeatable read","serializable","snapshot"];function ot(e){if(e.accessMode&&!tr.includes(e.accessMode))throw Error(`invalid transaction access mode ${e.accessMode}`);if(e.isolationLevel&&!rr.includes(e.isolationLevel))throw Error(`invalid transaction isolation level ${e.isolationLevel}`)}var nr=["query","error"],Ra=f(nr);class it{#e;#t;constructor(e){if(Kt(e))this.#t=e,this.#e=f({query:!0,error:!0});else this.#t=or,this.#e=f({query:e.includes("query"),error:e.includes("error")})}isLevelEnabled(e){return this.#e[e]}async query(e){if(this.#e.query)await this.#t(e())}async error(e){if(this.#e.error)await this.#t(e())}}function or(e){if(e.level==="query"){let t=`kysely:query:${e.isStream?"stream:":""}`;console.log(`${t} ${e.query.sql}`),console.log(`${t} duration: ${e.queryDurationMillis.toFixed(1)}ms`)}else if(e.level==="error")if(e.error instanceof Error)console.error(`kysely:error: ${e.error.stack??e.error.message}`);else console.error(`kysely:error: ${JSON.stringify({error:e.error,query:e.query.sql,queryDurationMillis:e.queryDurationMillis})}`)}function St(e){return Ir(e)&&Kt(e.compile)}Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");class F extends Is{#e;constructor(e){let t,r;if(ir(e))t={executor:e.executor},r={...e};else{let n=e.dialect,o=n.createDriver(),d=n.createQueryCompiler(),l=n.createAdapter(),g=new it(e.log??[]),A=new nt(o,g),D=new rt(A),z=new ee(d,l,D,e.plugins??[]);t={executor:z},r={config:e,executor:z,dialect:n,driver:A}}super(t);this.#e=f(r)}get schema(){return new xe(this.#e.executor)}get dynamic(){return new tt}get introspection(){return this.#e.dialect.createIntrospector(this.withoutPlugins())}case(e){return new gc({node:ko.create(On(e)?void 0:ho(e))})}get fn(){return Iu()}transaction(){return new $e({...this.#e})}startTransaction(){return new Fe({...this.#e})}connection(){return new kt({...this.#e})}withPlugin(e){return new F({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new F({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new F({...this.#e,executor:this.#e.executor.withPluginAtFront(new is(e))})}withTables(){return new F({...this.#e})}async destroy(){await this.#e.driver.destroy()}get isTransaction(){return!1}getExecutor(){return this.#e.executor}executeQuery(e,t){if(t!==void 0)cs("Passing `queryId` in `db.executeQuery` is deprecated and will result in a compile-time error in the future.");let r=St(e)?e.compile():e;return this.getExecutor().executeQuery(r)}async[Symbol.asyncDispose](){await this.destroy()}}class oe extends F{#e;constructor(e){super(e);this.#e=e}get isTransaction(){return!0}transaction(){throw Error("calling the transaction method for a Transaction is not supported")}connection(){throw Error("calling the connection method for a Transaction is not supported")}async destroy(){throw Error("calling the destroy method for a Transaction is not supported")}withPlugin(e){return new oe({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new oe({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new oe({...this.#e,executor:this.#e.executor.withPluginAtFront(new is(e))})}withTables(){return new oe({...this.#e})}}function ir(e){return Ir(e)&&Ir(e.config)&&Ir(e.driver)&&Ir(e.executor)&&Ir(e.dialect)}class kt{#e;constructor(e){this.#e=f(e)}async execute(e){return this.#e.executor.provideConnection(async(t)=>{let r=this.#e.executor.withConnectionProvider(new ve(t)),n=new F({...this.#e,executor:r});return await e(n)})}}class $e{#e;constructor(e){this.#e=f(e)}setAccessMode(e){return new $e({...this.#e,accessMode:e})}setIsolationLevel(e){return new $e({...this.#e,isolationLevel:e})}async execute(e){let{isolationLevel:t,accessMode:r,...n}=this.#e,o={isolationLevel:t,accessMode:r};return ot(o),this.#e.executor.provideConnection(async(d)=>{let l={isCommitted:!1,isRolledBack:!1},g=new G(this.#e.executor.withConnectionProvider(new ve(d)),l),A=new oe({...n,executor:g}),D=!1;try{await this.#e.driver.beginTransaction(d,o),D=!0;let z=await e(A);return await this.#e.driver.commitTransaction(d),l.isCommitted=!0,z}catch(z){if(D)await this.#e.driver.rollbackTransaction(d),l.isRolledBack=!0;throw z}})}}class Fe{#e;constructor(e){this.#e=f(e)}setAccessMode(e){return new Fe({...this.#e,accessMode:e})}setIsolationLevel(e){return new Fe({...this.#e,isolationLevel:e})}async execute(){let{isolationLevel:e,accessMode:t,...r}=this.#e,n={isolationLevel:e,accessMode:t};ot(n);let o=await Cu(this.#e.executor);return await this.#e.driver.beginTransaction(o.connection,n),new K({...r,connection:o,executor:this.#e.executor.withConnectionProvider(new ve(o.connection))})}}class K extends oe{#e;#t;#r;constructor(e){let t={isCommitted:!1,isRolledBack:!1};e={...e,executor:new G(e.executor,t)};let{connection:r,...n}=e;super(n);this.#e=f(e),this.#r=t;let o=Ye();this.#t=(d)=>e.executor.compileQuery(d,o)}get isCommitted(){return this.#r.isCommitted}get isRolledBack(){return this.#r.isRolledBack}commit(){return ne(this.#r),new Ne(async()=>{await this.#e.driver.commitTransaction(this.#e.connection.connection),this.#r.isCommitted=!0,this.#e.connection.release()})}rollback(){return ne(this.#r),new Ne(async()=>{await this.#e.driver.rollbackTransaction(this.#e.connection.connection),this.#r.isRolledBack=!0,this.#e.connection.release()})}savepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.savepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}rollbackToSavepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.rollbackToSavepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}releaseSavepoint(e){return ne(this.#r),new Ne(async()=>(await this.#e.driver.releaseSavepoint?.(this.#e.connection.connection,e,this.#t),new K({...this.#e})))}withPlugin(e){return new K({...this.#e,executor:this.#e.executor.withPlugin(e)})}withoutPlugins(){return new K({...this.#e,executor:this.#e.executor.withoutPlugins()})}withSchema(e){return new K({...this.#e,executor:this.#e.executor.withPluginAtFront(new is(e))})}withTables(){return new K({...this.#e})}}class Ne{#e;constructor(e){this.#e=e}async execute(){return await this.#e()}}function ne(e){if(e.isCommitted)throw Error("Transaction is already committed");if(e.isRolledBack)throw Error("Transaction is already rolled back")}class G{#e;#t;constructor(e,t){if(e instanceof G)this.#e=e.#e;else this.#e=e;this.#t=t}get adapter(){return this.#e.adapter}get plugins(){return this.#e.plugins}transformQuery(e,t){return this.#e.transformQuery(e,t)}compileQuery(e,t){return this.#e.compileQuery(e,t)}provideConnection(e){return this.#e.provideConnection(e)}executeQuery(e){return ne(this.#t),this.#e.executeQuery(e)}stream(e,t){return ne(this.#t),this.#e.stream(e,t)}withConnectionProvider(e){return new G(this.#e.withConnectionProvider(e),this.#t)}withPlugin(e){return new G(this.#e.withPlugin(e),this.#t)}withPlugins(e){return new G(this.#e.withPlugins(e),this.#t)}withPluginAtFront(e){return new G(this.#e.withPluginAtFront(e),this.#t)}withoutPlugins(){return new G(this.#e.withoutPlugins(),this.#t)}}function k(e,t){return Zt.createWithChildren([Zt.createWithSql(`${e} `),ze.create(t)])}class st{#e;#t=new Wt;#r;#n;constructor(e){this.#e=f({...e})}async init(){if(this.#r=Kt(this.#e.database)?await this.#e.database():this.#e.database,this.#n=new Mt(this.#r),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#n)}async acquireConnection(){return await this.#t.lock(),this.#n}async beginTransaction(e){await e.executeQuery(fr.raw("begin"))}async commitTransaction(e){await e.executeQuery(fr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(fr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release",t),Ye()))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#r?.close()}}class Mt{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:t,parameters:r}=e,n=this.#e.prepare(t);if(n.reader)return Promise.resolve({rows:n.all(r)});let{changes:o,lastInsertRowid:d}=n.run(r);return Promise.resolve({numAffectedRows:o!==void 0&&o!==null?BigInt(o):void 0,insertId:d!==void 0&&d!==null?BigInt(d):void 0,rows:[]})}async*streamQuery(e,t){let{sql:r,parameters:n,query:o}=e,d=this.#e.prepare(r);if(Gt.is(o)){let l=d.iterate(n);for(let g of l)yield{rows:[g]}}else throw Error("Sqlite driver only supports streaming of select queries")}}class Wt{#e;#t;async lock(){while(this.#e)await this.#e;this.#e=new Promise((e)=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}}class at{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){return await this.#r(e)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e,t){let r=e.selectFrom("sqlite_master").where("type","in",["table","view"]).where("name","not like","sqlite_%").select(["name","sql","type"]).orderBy("name");if(!t.withInternalKyselyTables)r=r.where("name","!=",Jr).where("name","!=",En);return r}async#r(e){let t=await this.#t(this.#e,e).execute(),r=await this.#e.with("table_list",(o)=>this.#t(o,e)).selectFrom(["table_list as tl",De`pragma_table_info(tl.name)`.as("p")]).select(["tl.name as table","p.cid","p.name","p.type","p.notnull","p.dflt_value","p.pk"]).orderBy("tl.name").orderBy("p.cid").execute(),n={};for(let o of r)n[o.table]??=[],n[o.table].push(o);return t.map(({name:o,sql:d,type:l})=>{let g=d?.split(/[\(\),]/)?.find((D)=>D.toLowerCase().includes("autoincrement"))?.trimStart()?.split(/\s+/)?.[0]?.replace(/["`]/g,""),A=n[o]??[];if(!g){let D=A.filter((z)=>z.pk>0);if(D.length===1&&D[0].type.toLowerCase()==="integer")g=D[0].name}return{name:o,isView:l==="view",columns:A.map((D)=>({name:D.name,dataType:D.type,isNullable:!D.notnull,isAutoIncrementing:D.name===g,hasDefaultValue:D.dflt_value!=null,comment:void 0}))}})}}class je{#e;constructor(e){this.#e=f({...e})}createDriver(){return new st(this.#e)}createQueryCompiler(){return new el}createAdapter(){return new tl}createIntrospector(e){return new at(e)}}var ar=/"/g;class ct extends Zn{sanitizeIdentifier(e){return e.replace(ar,'""')}}class ut{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("pg_catalog.pg_namespace").select("nspname").$castTo().execute()).map((t)=>({name:t.nspname}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("pg_catalog.pg_attribute as a").innerJoin("pg_catalog.pg_class as c","a.attrelid","c.oid").innerJoin("pg_catalog.pg_namespace as ns","c.relnamespace","ns.oid").innerJoin("pg_catalog.pg_type as typ","a.atttypid","typ.oid").innerJoin("pg_catalog.pg_namespace as dtns","typ.typnamespace","dtns.oid").select(["a.attname as column","a.attnotnull as not_null","a.atthasdef as has_default","c.relname as table","c.relkind as table_type","ns.nspname as schema","typ.typname as type","dtns.nspname as type_schema",De`col_description(a.attrelid, a.attnum)`.as("column_description"),De`pg_get_serial_sequence(quote_ident(ns.nspname) || '.' || quote_ident(c.relname), a.attname)`.as("auto_incrementing")]).where("c.relkind","in",["r","v","p"]).where("ns.nspname","!~","^pg_").where("ns.nspname","!=","information_schema").where("ns.nspname","!=","crdb_internal").where(De`has_schema_privilege(ns.nspname, 'USAGE')`).where("a.attnum",">=",0).where("a.attisdropped","!=",!0).orderBy("ns.nspname").orderBy("c.relname").orderBy("a.attnum").$castTo();if(!e.withInternalKyselyTables)t=t.where("c.relname","!=",Jr).where("c.relname","!=",En);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){let t=new Map;for(let r=0,n=e.length;r<n;r++){let o=e[r],{schema:d,table:l}=o,g=`schema:${d};table:${l}`;if(!t.has(g))t.set(g,f({columns:[],isView:o.table_type==="v",name:l,schema:d}));t.get(g).columns.push(f({comment:o.column_description??void 0,dataType:o.type,dataTypeSchema:o.type_schema,hasDefaultValue:o.has_default,isAutoIncrementing:o.auto_incrementing!==null,isNullable:!o.not_null,name:o.column}))}return Array.from(t.values())}}var cr=BigInt("3853314791062309107");class lt extends na{get supportsTransactionalDdl(){return!0}get supportsReturning(){return!0}async acquireMigrationLock(e,t){await De`select pg_advisory_xact_lock(${De.lit(cr)})`.execute(e)}async releaseMigrationLock(e,t){}}function _e(e,t){if(ur(e)&&t.stack){let r=t.stack.split(`
|
|
3
3
|
`).slice(1).join(`
|
|
4
4
|
`);return e.stack+=`
|
|
5
|
-
${r}`,e}return e}function lr(e){return Ir(e)&&Qt(e.stack)}var Pt=Symbol();class mt{#e;#t=new WeakMap;#r;constructor(e){this.#e=f({...e})}async init(){this.#r=Kt(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#n(),t=this.#t.get(e);if(!t){if(t=new Rt(e),this.#t.set(e,t),this.#e?.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e?.onReserveConnection)await this.#e.onReserveConnection(t);return t}async#n(){return new Promise((e,t)=>{this.#r.getConnection(async(r,n)=>{if(r)t(r);else e(n)})})}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r=[];if(t.isolationLevel)r.push(`isolation level ${t.isolationLevel}`);if(t.accessMode)r.push(t.accessMode);let n=`set transaction ${r.join(", ")}`;await e.executeQuery(dr.raw(n))}await e.executeQuery(dr.raw("begin"))}async commitTransaction(e){await e.executeQuery(dr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(dr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release savepoint",t),Ye()))}async releaseConnection(e){e[Pt]()}async destroy(){return new Promise((e,t)=>{this.#r.end((r)=>{if(r)t(r);else e()})})}}function mr(e){return Ir(e)&&"insertId"in e&&"affectedRows"in e}class Rt{#e;constructor(e){this.#e=e}async executeQuery(e){try{let t=await this.#t(e);if(mr(t)){let{insertId:r,affectedRows:n,changedRows:o}=t;return{insertId:r!==void 0&&r!==null&&r.toString()!=="0"?BigInt(r):void 0,numAffectedRows:n!==void 0&&n!==null?BigInt(n):void 0,numChangedRows:o!==void 0&&o!==null?BigInt(o):void 0,rows:[]}}else if(Array.isArray(t))return{rows:t};return{rows:[]}}catch(t){throw _e(t,Error())}}#t(e){return new Promise((t,r)=>{this.#e.query(e.sql,e.parameters,(n,o)=>{if(n)r(n);else t(o)})})}async*streamQuery(e,t){let r=this.#e.query(e.sql,e.parameters).stream({objectMode:!0});try{for await(let n of r)yield{rows:[n]}}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw n}}[Pt](){this.#e.release()}}var hr=/[\\']/g,dt=/`/g,pr=/[\\'"]/g;class ht extends Zn{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return dt.source}getRightIdentifierWrapper(){return dt.source}sanitizeIdentifier(e){return e.replace(dt,"``")}sanitizeStringLiteral(e){return e.replace(hr,(t)=>t==="\\"?"\\\\":"''")}sanitizeJSONPathMemberValue(e){return e.replace(pr,(t)=>t==="\\"?"\\\\\\\\":t==="'"?"''":'\\\\"')}visitCreateIndex(e){if(this.append("create "),e.unique)this.append("unique ");if(this.append("index "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.name),e.using)this.append(" using "),this.visitNode(e.using);if(e.table)this.append(" on "),this.visitNode(e.table);if(e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.where)this.append(" "),this.visitNode(e.where)}}class pt{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((t)=>({name:t.SCHEMA_NAME}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(n)=>n.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",De`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!e.withInternalKyselyTables)t=t.where("columns.TABLE_NAME","!=",Jr).where("columns.TABLE_NAME","!=",En);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){return e.reduce((t,r)=>{let n=t.find((o)=>o.name===r.TABLE_NAME);if(!n)n=f({name:r.TABLE_NAME,isView:r.TABLE_TYPE==="VIEW",schema:r.TABLE_SCHEMA,columns:[]}),t.push(n);return n.columns.push(f({name:r.COLUMN_NAME,dataType:r.DATA_TYPE,isNullable:r.IS_NULLABLE==="YES",isAutoIncrementing:r.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:r.COLUMN_DEFAULT!==null,comment:r.COLUMN_COMMENT===""?void 0:r.COLUMN_COMMENT})),t},[])}}var $t="ea586330-2c93-47c8-908d-981d9d270f9d",fr=3600;class ft extends ra{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(e,t){await De`select get_lock(${De.lit($t)}, ${De.lit(fr)})`.execute(e)}async releaseMigrationLock(e,t){await De`select release_lock(${De.lit($t)})`.execute(e)}}class Ve{#e;constructor(e){this.#e=e}createDriver(){return new mt(this.#e)}createQueryCompiler(){return new ht}createAdapter(){return new ft}createIntrospector(e){return new pt(e)}}var Ft=Symbol();class yt{#e;#t=new WeakMap;#r;constructor(e){this.#e=f({...e})}async init(){this.#r=Kt(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#r.connect(),t=this.#t.get(e);if(!t){if(t=new jt(e,{cursor:this.#e.cursor??null}),this.#t.set(e,t),this.#e.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e.onReserveConnection)await this.#e.onReserveConnection(t);return t}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r="start transaction";if(t.isolationLevel)r+=` isolation level ${t.isolationLevel}`;if(t.accessMode)r+=` ${t.accessMode}`;await e.executeQuery(dr.raw(r))}else await e.executeQuery(dr.raw("begin"))}async commitTransaction(e){await e.executeQuery(dr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(dr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release",t),Ye()))}async releaseConnection(e){e[Ft]()}async destroy(){if(this.#r){let e=this.#r;this.#r=void 0,await e.end()}}}class jt{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async executeQuery(e){try{let{command:t,rowCount:r,rows:n}=await this.#e.query(e.sql,[...e.parameters]);return{numAffectedRows:t==="INSERT"||t==="UPDATE"||t==="DELETE"||t==="MERGE"?BigInt(r):void 0,rows:n??[]}}catch(t){throw _e(t,Error())}}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{while(!0){let n=await r.read(t);if(n.length===0)break;yield{rows:n}}}finally{await r.close()}}[Ft](){this.#e.release()}}class Ue{#e;constructor(e){this.#e=e}createDriver(){return new yt(this.#e)}createQueryCompiler(){return new ct}createAdapter(){return new lt}createIntrospector(e){return new ut(e)}}class wt extends ra{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(e){await De`exec sp_getapplock @DbPrincipal = ${De.lit("dbo")}, @Resource = ${De.lit(Jr)}, @LockMode = ${De.lit("Exclusive")}`.execute(e)}async releaseMigrationLock(){}}var Vt=Symbol(),Ut=Symbol(),Bt=Symbol();class xt{#e;#t;constructor(e){this.#e=f({...e});let{tarn:t,tedious:r,validateConnections:n}=this.#e,{validateConnections:o,...d}=t.options;this.#t=new t.Pool({...d,create:async()=>{let l=await r.connectionFactory();return await new Jt(l,r).connect()},destroy:async(l)=>{await l[Ut]()},validate:n===!1||o===!1?void 0:(l)=>l[Bt]()})}async init(){}async acquireConnection(){return await this.#t.acquire().promise}async beginTransaction(e,t){await e.beginTransaction(t)}async commitTransaction(e){await e.commitTransaction()}async rollbackTransaction(e){await e.rollbackTransaction()}async savepoint(e,t){await e.savepoint(t)}async rollbackToSavepoint(e,t){await e.rollbackTransaction(t)}async releaseConnection(e){if(this.#e.resetConnectionsOnRelease||this.#e.tedious.resetConnectionOnRelease)await e[Vt]();this.#t.release(e)}async destroy(){await this.#t.destroy()}}class Jt{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=!1,this.#r=t}async beginTransaction(e){let{isolationLevel:t}=e;await new Promise((r,n)=>this.#e.beginTransaction((o)=>{if(o)n(o);else r(void 0)},t?Su(8):void 0,t?this.#n(t):void 0))}async commitTransaction(){await new Promise((e,t)=>this.#e.commitTransaction((r)=>{if(r)t(r);else e(void 0)}))}async connect(){let{promise:e,reject:t,resolve:r}=new ja;this.#e.connect((o)=>{if(o)return t(o);r()}),this.#e.on("error",(o)=>{if(o instanceof Error&&"code"in o&&o.code==="ESOCKET")this.#t=!0;console.error(o),t(o)});function n(){t(Error("The connection ended without ever completing the connection"))}return this.#e.once("end",n),await e,this.#e.off("end",n),this}async executeQuery(e){try{let t=new ja,r=new Be({compiledQuery:e,tedious:this.#r,onDone:t});this.#e.execSql(r.request);let{rowCount:n,rows:o}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:o}}catch(t){throw _e(t,Error())}}async rollbackTransaction(e){await new Promise((t,r)=>this.#e.rollbackTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async savepoint(e){await new Promise((t,r)=>this.#e.saveTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async*streamQuery(e,t){if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=new Be({compiledQuery:e,streamChunkSize:t,tedious:this.#r});this.#e.execSql(r.request);try{while(!0){let n=await r.readChunk();if(n.length===0)break;if(yield{rows:n},n.length<t)break}}finally{await this.#o(r)}}#n(e){let{ISOLATION_LEVEL:t}=this.#r,n={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[e];if(n===void 0)throw Error(`Unknown isolation level: ${e}`);return n}#o(e){return new Promise((t)=>{if(e.request.once("requestCompleted",t),!this.#e.cancel())e.request.off("requestCompleted",t),t()})}[Ut](){if("closed"in this.#e&&this.#e.closed)return Promise.resolve();return new Promise((e)=>{this.#e.once("end",e),this.#e.close()})}async[Vt](){await new Promise((e,t)=>{this.#e.reset((r)=>{if(r)return t(r);e()})})}async[Bt](){if(this.#t||this.#i())return!1;try{let e=new ja,t=new Be({compiledQuery:dr.raw("select 1"),onDone:e,tedious:this.#r});return this.#e.execSql(t.request),await e.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&Boolean(this.#e.closed)}}class Be{#e;#t;#r;#n;#o;#i;constructor(e){let{compiledQuery:t,onDone:r,streamChunkSize:n,tedious:o}=e;if(this.#t=[],this.#r=n,this.#n={},this.#o=o,r)this.#n.onDone=(l,g)=>{if(l==="chunkReady")return;if(delete this.#n.onDone,l==="error")return r.reject(g);r.resolve({rowCount:this.#i,rows:this.#t})};this.#e=new this.#o.Request(t.sql,(d,l)=>{if(d)return Object.values(this.#n).forEach((g)=>g("error",d instanceof AggregateError?d.errors:d));this.#i=l}),this.#a(t.parameters),this.#c()}get request(){return this.#e}readChunk(){let e=this.readChunk.name;return new Promise((t,r)=>{this.#n[e]=(n,o)=>{if(delete this.#n[e],n==="error")return r(o);t(this.#t.splice(0,this.#r))},this.#e.resume()})}#a(e){for(let t=0;t<e.length;t++){let r=e[t];this.#e.addParameter(String(t+1),this.#s(r),r)}}#c(){let e=this.#r?()=>{if(this.#r<=this.#t.length)this.#e.pause(),Object.values(this.#n).forEach((r)=>r("chunkReady"))}:()=>{},t=(r)=>{let n={};for(let o of r)n[o.metadata.colName]=o.value;this.#t.push(n),e()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#n).forEach((r)=>r("completed")),this.#e.off("row",t)})}#s(e){if(na(e)||On(e)||Qt(e))return this.#o.TYPES.NVarChar;if(oa(e)||jo(e)&&e%1===0)if(e<-2147483648||e>2147483647)return this.#o.TYPES.BigInt;else return this.#o.TYPES.Int;if(jo(e))return this.#o.TYPES.Float;if(Is(e))return this.#o.TYPES.Bit;if(Iu(e))return this.#o.TYPES.DateTime;if(cm(e))return this.#o.TYPES.VarBinary;return this.#o.TYPES.NVarChar}}class Nt{#e;constructor(e){this.#e=e}async getSchemas(){return await this.#e.selectFrom("sys.schemas").select("name").execute()}async getTables(e={withInternalKyselyTables:!1}){let t=await this.#e.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!e.withInternalKyselyTables,(n)=>n.where("tables.name","!=",Jr).where("tables.name","!=",En)).select(["tables.name as table_name",(n)=>n.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#e.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),r={};for(let n of t){let o=`${n.table_schema_name}.${n.table_name}`;(r[o]=r[o]||f({columns:[],isView:n.table_type==="V ",name:n.table_name,schema:n.table_schema_name??void 0})).columns.push(f({dataType:n.type_name,dataTypeSchema:n.type_schema_name??void 0,hasDefaultValue:n.column_default_object_id>0||n.column_generated_always_type!=="NOT_APPLICABLE"||n.column_is_identity||n.column_is_computed||n.column_is_rowguidcol,isAutoIncrementing:n.column_is_identity,isNullable:n.column_is_nullable&&n.type_is_nullable,name:n.column_name,comment:n.column_comment??void 0}))}return Object.values(r)}async getMetadata(e){return{tables:await this.getTables(e)}}}var yr=/^[a-z0-9_]$/i;class _t extends Zn{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(e){super.visitOffset(e),this.append(" rows")}compileColumnAlterations(e){let t={};for(let n of e){if(!t[n.kind])t[n.kind]=[];t[n.kind].push(n)}let r=!0;if(t.AddColumnNode)this.append("add "),this.compileList(t.AddColumnNode),r=!1;if(t.AlterColumnNode){if(!r)this.append(", ");this.compileList(t.AlterColumnNode)}if(t.DropColumnNode){if(!r)this.append(", ");this.append("drop column "),this.compileList(t.DropColumnNode)}if(t.ModifyColumnNode){if(!r)this.append(", ");this.compileList(t.ModifyColumnNode)}if(t.RenameColumnNode){if(!r)this.append(", ");this.compileList(t.RenameColumnNode)}}visitAddColumn(e){this.visitNode(e.column)}visitDropColumn(e){this.visitNode(e.column)}visitMergeQuery(e){super.visitMergeQuery(e),this.append(";")}visitCollate(e){this.append("collate ");let{name:t}=e.collation;for(let r of t)if(!yr.test(r))throw Error(`Invalid collation: ${t}`);this.append(t)}announcesNewColumnDataType(){return!1}}class Ct{#e;constructor(e){this.#e=e}createDriver(){return new xt(this.#e)}createQueryCompiler(){return new _t}createAdapter(){return new wt}createIntrospector(e){return new Nt(e)}}function Tt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function xu(e){if(!e)return null;if("dialect"in e)return xu(e.dialect);if("createDriver"in e){if(e instanceof je)return"sqlite";if(e instanceof Ve)return"mysql";if(e instanceof Ue)return"postgres";if(e instanceof Ct)return"mssql"}if("aggregate"in e)return"sqlite";if("getConnection"in e)return"mysql";if("connect"in e)return"postgres";if("fileControl"in e)return"sqlite";if("open"in e&&"close"in e&&"prepare"in e)return"sqlite";if("batch"in e&&"exec"in e&&"prepare"in e)return"sqlite";return null}var af=async(e)=>{let t=e.database;if(!t)return{kysely:null,databaseType:null,transaction:void 0};if("db"in t)return{kysely:t.db,databaseType:t.type,transaction:t.transaction};if("dialect"in t)return{kysely:new F({dialect:t.dialect}),databaseType:t.type,transaction:t.transaction};let r=void 0,n=xu(t);if("createDriver"in t)r=t;if("aggregate"in t&&!("createSession"in t))r=new je({database:t});if("getConnection"in t)r=new Ve(t);if("connect"in t)r=new Ue({pool:t});if("fileControl"in t){let{BunSqliteDialect:o}=await import("./chunk-3d9tfxp4.js");r=new o({database:t})}if("createSession"in t){let o=void 0;try{({DatabaseSync:o}=await import("node:sqlite"))}catch(d){if(d!==null&&typeof d==="object"&&"code"in d&&d.code!=="ERR_UNKNOWN_BUILTIN_MODULE")throw d}if(o&&t instanceof o){let{NodeSqliteDialect:d}=await import("./chunk-mtb9fpj2.js");r=new d({database:t})}}if("batch"in t&&"exec"in t&&"prepare"in t){let{D1SqliteDialect:o}=await import("./chunk-dj5a6kkh.js");r=new o({database:t})}return{kysely:r?new F({dialect:r}):null,databaseType:n,transaction:void 0}};function gt(e,t,r){return r==="postgres"?De`${De.ref(e)} ILIKE ${t}`:De`LOWER(${De.ref(e)}) LIKE LOWER(${t})`}function wr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function xr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function Nr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,value:t.toLowerCase()}}function _r(e,t){return{lhs:De`LOWER(${De.ref(e)})`,value:t.toLowerCase()}}var vI=(e,t)=>{let r=null,n=(l,g=!1)=>({getFieldName:A,schema:D,getDefaultFieldName:z,getDefaultModelName:Ht,getFieldAttributes:Cr,getModelName:te})=>{let Et=(u)=>{let x=[],y=[];if(u)for(let[h,m]of Object.entries(u)){let a=D[Ht(h)]?.fields,[c,w]=h.includes(".")?h.split("."):[void 0,h];if(!a)continue;a.id={type:"string"};for(let[v,i]of Object.entries(a))x.push(De`${De.ref(`join_${w}`)}.${De.ref(i.fieldName||v)} as ${De.ref(`_joined_${w}_${i.fieldName||v}`)}`),y.push({joinModel:h,joinModelRef:w,fieldName:i.fieldName||v})}return{allSelectsStr:y,allSelects:x}},bt=async(u,x,y,h)=>{let m;if(t?.type==="mysql"){await x.execute();let a=u.id?"id":h.length>0&&h[0]?.field?h[0].field:"id";if(!u.id&&h.length===0)return m=await l.selectFrom(y).selectAll().orderBy(A({model:y,field:a}),"desc").limit(1).executeTakeFirst(),m;let c=u[a]!==void 0?u[a]:h[0]?.value;return m=await l.selectFrom(y).selectAll().orderBy(A({model:y,field:a}),"desc").where(A({model:y,field:a}),c===null?"is":"=",c).limit(1).executeTakeFirst(),m}if(t?.type==="mssql")return m=await x.outputAll("inserted").executeTakeFirst(),m;return m=await x.returningAll().executeTakeFirst(),m};function J(u,x){if(!x)return{and:null,or:null};let y={and:[],or:[]};return x.forEach((h)=>{let{field:m,value:a,operator:c="eq",connector:w="AND",mode:v="sensitive"}=h,i=a,C=A({model:u,field:m}),N=v==="insensitive"&&(typeof i==="string"||Array.isArray(i)&&i.every((p)=>typeof p==="string")),T=(p)=>{let s=`${u}.${C}`;if(c.toLowerCase()==="in"){if(N){let{lhs:q,values:E}=wr(s,Array.isArray(i)?i:[i]);return p(q,"in",E)}return p(s,"in",Array.isArray(i)?i:[i])}if(c.toLowerCase()==="not_in"){if(N){let{lhs:q,values:E}=xr(s,Array.isArray(i)?i:[i]);return p(q,"not in",E)}return p(s,"not in",Array.isArray(i)?i:[i])}if(c==="contains"){if(N&&typeof i==="string")return gt(s,`%${i}%`,t?.type);return p(s,"like",`%${i}%`)}if(c==="starts_with"){if(N&&typeof i==="string")return gt(s,`${i}%`,t?.type);return p(s,"like",`${i}%`)}if(c==="ends_with"){if(N&&typeof i==="string")return gt(s,`%${i}`,t?.type);return p(s,"like",`%${i}`)}if(c==="eq"){if(i===null)return p(s,"is",null);if(N&&typeof i==="string"){let{lhs:q,value:E}=Nr(s,i);return p(q,"=",E)}return p(s,"=",i)}if(c==="ne"){if(i===null)return p(s,"is not",null);if(N&&typeof i==="string"){let{lhs:q,value:E}=_r(s,i);return p(q,"<>",E)}return p(s,"<>",i)}if(c==="gt")return p(s,">",i);if(c==="gte")return p(s,">=",i);if(c==="lt")return p(s,"<",i);if(c==="lte")return p(s,"<=",i);return p(s,c,i)};if(w==="OR")y.or.push(T);else y.and.push(T)}),{and:y.and.length?y.and:null,or:y.or.length?y.or:null}}function It(u,x,y){if(!x||!u.length)return u;let h=new Map;for(let a of u){let c={},w={};for(let[C]of Object.entries(x))w[te(C)]={};for(let[C,N]of Object.entries(a)){let T=String(C),p=!1;for(let{joinModel:s,fieldName:q,joinModelRef:E}of y)if(T===`_joined_${E}_${q}`||T===`_Joined${Tt(E)}${Tt(q)}`){w[te(s)][A({model:s,field:q})]=N,p=!0;break}if(!p)c[C]=N}let v=c.id;if(!v)continue;if(!h.has(v)){let C={...c};for(let[N,T]of Object.entries(x))C[te(N)]=T.relation==="one-to-one"?null:[];h.set(v,C)}let i=h.get(v);for(let[C,N]of Object.entries(x)){let T=N.relation==="one-to-one",p=N.limit??100,s=w[te(C)],q=s&&Object.keys(s).length>0&&Object.values(s).some((E)=>E!==null&&E!==void 0);if(T)i[te(C)]=q?s:null;else{let E=te(C);if(Array.isArray(i[E])&&q){if(i[E].length>=p)continue;let qe=A({model:C,field:"id"}),At=s[qe];if(At){if(!i[E].some((Yt)=>Yt[qe]===At)&&i[E].length<p)i[E].push(s)}else if(i[E].length<p)i[E].push(s)}}}}let m=Array.from(h.values());for(let a of m)for(let[c,w]of Object.entries(x))if(w.relation!=="one-to-one"){let v=te(c);if(Array.isArray(a[v])){let i=w.limit??100;if(a[v].length>i)a[v]=a[v].slice(0,i)}}return m}return{async create({data:u,model:x}){return await bt(u,l.insertInto(x).values(u),x,[])},async findOne({model:u,where:x,select:y,join:h}){let{and:m,or:a}=J(u,x),c=l.selectFrom((N)=>{let T=N.selectFrom(u);if(m)T=T.where((p)=>p.and(m.map((s)=>s(p))));if(a)T=T.where((p)=>p.or(a.map((s)=>s(p))));if(y?.length&&y.length>0)T=T.select(y.map((p)=>A({model:u,field:p})));else T=T.selectAll();return T.as("primary")}).selectAll("primary");if(h)for(let[N,T]of Object.entries(h)){let[p,s]=N.includes(".")?N.split("."):[void 0,N];c=c.leftJoin(`${N} as join_${s}`,(q)=>q.onRef(`join_${s}.${T.on.to}`,"=",`primary.${T.on.from}`))}let{allSelectsStr:w,allSelects:v}=Et(h);c=c.select(v);let i=await c.execute();if(!i||!Array.isArray(i)||i.length===0)return null;let C=i[0];if(h)return It(i,h,w)[0];return C},async findMany({model:u,where:x,limit:y,select:h,offset:m,sortBy:a,join:c}){let{and:w,or:v}=J(u,x),i=l.selectFrom((p)=>{let s=p.selectFrom(u);if(t?.type==="mssql"){if(m!==void 0){if(!a)s=s.orderBy(A({model:u,field:"id"}));s=s.offset(m).fetch(y||100)}else if(y!==void 0)s=s.top(y)}else{if(y!==void 0)s=s.limit(y);if(m!==void 0)s=s.offset(m)}if(a?.field)s=s.orderBy(`${A({model:u,field:a.field})}`,a.direction);if(w)s=s.where((q)=>q.and(w.map((E)=>E(q))));if(v)s=s.where((q)=>q.or(v.map((E)=>E(q))));if(h?.length&&h.length>0)s=s.select(h.map((q)=>A({model:u,field:q})));else s=s.selectAll();return s.as("primary")}).selectAll("primary");if(c)for(let[p,s]of Object.entries(c)){let[q,E]=p.includes(".")?p.split("."):[void 0,p];i=i.leftJoin(`${p} as join_${E}`,(qe)=>qe.onRef(`join_${E}.${s.on.to}`,"=",`primary.${s.on.from}`))}let{allSelectsStr:C,allSelects:N}=Et(c);if(i=i.select(N),a?.field)i=i.orderBy(`${A({model:u,field:a.field})}`,a.direction);let T=await i.execute();if(!T)return[];if(c)return It(T,c,C);return T},async update({model:u,where:x,update:y}){let{and:h,or:m}=J(u,x),a=l.updateTable(u).set(y);if(h)a=a.where((c)=>c.and(h.map((w)=>w(c))));if(m)a=a.where((c)=>c.or(m.map((w)=>w(c))));return await bt(y,a,u,x)},async updateMany({model:u,where:x,update:y}){let{and:h,or:m}=J(u,x),a=l.updateTable(u).set(y);if(h)a=a.where((w)=>w.and(h.map((v)=>v(w))));if(m)a=a.where((w)=>w.or(m.map((v)=>v(w))));let c=(await a.executeTakeFirst()).numUpdatedRows;return c>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(c)},async count({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.selectFrom(u).select(l.fn.count("id").as("count"));if(y)m=m.where((c)=>c.and(y.map((w)=>w(c))));if(h)m=m.where((c)=>c.or(h.map((w)=>w(c))));let a=await m.execute();if(typeof a[0].count==="number")return a[0].count;if(typeof a[0].count==="bigint")return Number(a[0].count);return parseInt(a[0].count)},async delete({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.deleteFrom(u);if(y)m=m.where((a)=>a.and(y.map((c)=>c(a))));if(h)m=m.where((a)=>a.or(h.map((c)=>c(a))));await m.execute()},async deleteMany({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.deleteFrom(u);if(y)m=m.where((c)=>c.and(y.map((w)=>w(c))));if(h)m=m.where((c)=>c.or(h.map((w)=>w(c))));let a=(await m.executeTakeFirst()).numDeletedRows;return a>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(a)},async consumeOne({model:u,where:x}){let{and:y,or:h}=J(u,x),m=(i)=>{if(y)i=i.where((C)=>C.and(y.map((N)=>N(C))));if(h)i=i.where((C)=>C.or(h.map((N)=>N(C))));return i},a=A({model:u,field:"id"}),c=async(i,C)=>{let N=C[a]??C.id;if(N===void 0||N===null)return null;let T=i.deleteFrom(u).where(`${u}.${a}`,"=",N);if(t?.type==="mysql"){let p=await T.executeTakeFirst();return Number(p.numDeletedRows)>0?C:null}if(t?.type==="mssql")return await T.outputAll("deleted").executeTakeFirst()??null;return await T.returningAll().executeTakeFirst()??null},w=async(i)=>{if(t?.type==="mssql")return await i.outputAll("deleted").executeTakeFirst()??null;return await i.returningAll().executeTakeFirst()??null};if(t?.type==="mysql"){let i=async(C)=>{let N=await m(C.selectFrom(u).selectAll().forUpdate()).limit(1).executeTakeFirst();if(!N)return null;return c(C,N)};return g?i(l):l.transaction().execute(i)}let v=m(l.selectFrom(u).select(`${u}.${a}`)).limit(1);return w(l.deleteFrom(u).where(`${u}.${a}`,"in",v))},options:t}},o=null;o={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:t?.usePlural,debugLogs:t?.debugLogs,supportsBooleans:t?.type==="sqlite"||t?.type==="mssql"||t?.type==="mysql"||!t?.type?!1:!0,supportsDates:t?.type==="sqlite"||t?.type==="mssql"||!t?.type?!1:!0,supportsJSON:t?.type==="postgres"?!0:!1,supportsArrays:!1,supportsUUIDs:t?.type==="postgres"?!0:!1,transaction:t?.transaction?(l)=>e.transaction().execute((g)=>l(Ts({config:{...o.config,transaction:!1},adapter:n(g,!0)})(r))):!1},adapter:n(e)};let d=Ts(o);return(l)=>(r=l,d(l))};
|
|
6
|
-
export{
|
|
5
|
+
${r}`,e}return e}function ur(e){return Ir(e)&&Qt(e.stack)}var Pt=Symbol();class mt{#e;#t=new WeakMap;#r;constructor(e){this.#e=f({...e})}async init(){this.#r=Kt(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#n(),t=this.#t.get(e);if(!t){if(t=new Rt(e),this.#t.set(e,t),this.#e?.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e?.onReserveConnection)await this.#e.onReserveConnection(t);return t}async#n(){return new Promise((e,t)=>{this.#r.getConnection(async(r,n)=>{if(r)t(r);else e(n)})})}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r=[];if(t.isolationLevel)r.push(`isolation level ${t.isolationLevel}`);if(t.accessMode)r.push(t.accessMode);let n=`set transaction ${r.join(", ")}`;await e.executeQuery(fr.raw(n))}await e.executeQuery(fr.raw("begin"))}async commitTransaction(e){await e.executeQuery(fr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(fr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release savepoint",t),Ye()))}async releaseConnection(e){e[Pt]()}async destroy(){return new Promise((e,t)=>{this.#r.end((r)=>{if(r)t(r);else e()})})}}function lr(e){return Ir(e)&&"insertId"in e&&"affectedRows"in e}class Rt{#e;constructor(e){this.#e=e}async executeQuery(e){try{let t=await this.#t(e);if(lr(t)){let{insertId:r,affectedRows:n,changedRows:o}=t;return{insertId:r!==void 0&&r!==null&&r.toString()!=="0"?BigInt(r):void 0,numAffectedRows:n!==void 0&&n!==null?BigInt(n):void 0,numChangedRows:o!==void 0&&o!==null?BigInt(o):void 0,rows:[]}}else if(Array.isArray(t))return{rows:t};return{rows:[]}}catch(t){throw _e(t,Error())}}#t(e){return new Promise((t,r)=>{this.#e.query(e.sql,e.parameters,(n,o)=>{if(n)r(n);else t(o)})})}async*streamQuery(e,t){let r=this.#e.query(e.sql,e.parameters).stream({objectMode:!0});try{for await(let n of r)yield{rows:[n]}}catch(n){if(n&&typeof n==="object"&&"code"in n&&n.code==="ERR_STREAM_PREMATURE_CLOSE")return;throw n}}[Pt](){this.#e.release()}}var mr=/[\\']/g,dt=/`/g,hr=/[\\'"]/g;class ht extends Zn{getCurrentParameterPlaceholder(){return"?"}getLeftExplainOptionsWrapper(){return""}getExplainOptionAssignment(){return"="}getExplainOptionsDelimiter(){return" "}getRightExplainOptionsWrapper(){return""}getLeftIdentifierWrapper(){return dt.source}getRightIdentifierWrapper(){return dt.source}sanitizeIdentifier(e){return e.replace(dt,"``")}sanitizeStringLiteral(e){return e.replace(mr,(t)=>t==="\\"?"\\\\":"''")}sanitizeJSONPathMemberValue(e){return e.replace(hr,(t)=>t==="\\"?"\\\\\\\\":t==="'"?"''":'\\\\"')}visitCreateIndex(e){if(this.append("create "),e.unique)this.append("unique ");if(this.append("index "),e.ifNotExists)this.append("if not exists ");if(this.visitNode(e.name),e.using)this.append(" using "),this.visitNode(e.using);if(e.table)this.append(" on "),this.visitNode(e.table);if(e.columns)this.append(" ("),this.compileList(e.columns),this.append(")");if(e.where)this.append(" "),this.visitNode(e.where)}}class pt{#e;constructor(e){this.#e=e}async getSchemas(){return(await this.#e.selectFrom("information_schema.schemata").select("schema_name").$castTo().execute()).map((t)=>({name:t.SCHEMA_NAME}))}async getTables(e={withInternalKyselyTables:!1}){let t=this.#e.selectFrom("information_schema.columns as columns").innerJoin("information_schema.tables as tables",(n)=>n.onRef("columns.TABLE_CATALOG","=","tables.TABLE_CATALOG").onRef("columns.TABLE_SCHEMA","=","tables.TABLE_SCHEMA").onRef("columns.TABLE_NAME","=","tables.TABLE_NAME")).select(["columns.COLUMN_NAME","columns.COLUMN_DEFAULT","columns.TABLE_NAME","columns.TABLE_SCHEMA","tables.TABLE_TYPE","columns.IS_NULLABLE","columns.DATA_TYPE","columns.EXTRA","columns.COLUMN_COMMENT"]).where("columns.TABLE_SCHEMA","=",De`database()`).orderBy("columns.TABLE_NAME").orderBy("columns.ORDINAL_POSITION").$castTo();if(!e.withInternalKyselyTables)t=t.where("columns.TABLE_NAME","!=",Jr).where("columns.TABLE_NAME","!=",En);let r=await t.execute();return this.#t(r)}async getMetadata(e){return{tables:await this.getTables(e)}}#t(e){return e.reduce((t,r)=>{let n=t.find((o)=>o.name===r.TABLE_NAME);if(!n)n=f({name:r.TABLE_NAME,isView:r.TABLE_TYPE==="VIEW",schema:r.TABLE_SCHEMA,columns:[]}),t.push(n);return n.columns.push(f({name:r.COLUMN_NAME,dataType:r.DATA_TYPE,isNullable:r.IS_NULLABLE==="YES",isAutoIncrementing:r.EXTRA.toLowerCase().includes("auto_increment"),hasDefaultValue:r.COLUMN_DEFAULT!==null,comment:r.COLUMN_COMMENT===""?void 0:r.COLUMN_COMMENT})),t},[])}}var $t="ea586330-2c93-47c8-908d-981d9d270f9d",pr=3600;class ft extends na{get supportsTransactionalDdl(){return!1}get supportsReturning(){return!1}async acquireMigrationLock(e,t){await De`select get_lock(${De.lit($t)}, ${De.lit(pr)})`.execute(e)}async releaseMigrationLock(e,t){await De`select release_lock(${De.lit($t)})`.execute(e)}}class Ve{#e;constructor(e){this.#e=e}createDriver(){return new mt(this.#e)}createQueryCompiler(){return new ht}createAdapter(){return new ft}createIntrospector(e){return new pt(e)}}var Ft=Symbol();class yt{#e;#t=new WeakMap;#r;constructor(e){this.#e=f({...e})}async init(){this.#r=Kt(this.#e.pool)?await this.#e.pool():this.#e.pool}async acquireConnection(){let e=await this.#r.connect(),t=this.#t.get(e);if(!t){if(t=new jt(e,{cursor:this.#e.cursor??null}),this.#t.set(e,t),this.#e.onCreateConnection)await this.#e.onCreateConnection(t)}if(this.#e.onReserveConnection)await this.#e.onReserveConnection(t);return t}async beginTransaction(e,t){if(t.isolationLevel||t.accessMode){let r="start transaction";if(t.isolationLevel)r+=` isolation level ${t.isolationLevel}`;if(t.accessMode)r+=` ${t.accessMode}`;await e.executeQuery(fr.raw(r))}else await e.executeQuery(fr.raw("begin"))}async commitTransaction(e){await e.executeQuery(fr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(fr.raw("rollback"))}async savepoint(e,t,r){await e.executeQuery(r(k("savepoint",t),Ye()))}async rollbackToSavepoint(e,t,r){await e.executeQuery(r(k("rollback to",t),Ye()))}async releaseSavepoint(e,t,r){await e.executeQuery(r(k("release",t),Ye()))}async releaseConnection(e){e[Ft]()}async destroy(){if(this.#r){let e=this.#r;this.#r=void 0,await e.end()}}}class jt{#e;#t;constructor(e,t){this.#e=e,this.#t=t}async executeQuery(e){try{let{command:t,rowCount:r,rows:n}=await this.#e.query(e.sql,[...e.parameters]);return{numAffectedRows:t==="INSERT"||t==="UPDATE"||t==="DELETE"||t==="MERGE"?BigInt(r):void 0,rows:n??[]}}catch(t){throw _e(t,Error())}}async*streamQuery(e,t){if(!this.#t.cursor)throw Error("'cursor' is not present in your postgres dialect config. It's required to make streaming work in postgres.");if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=this.#e.query(new this.#t.cursor(e.sql,e.parameters.slice()));try{while(!0){let n=await r.read(t);if(n.length===0)break;yield{rows:n}}}finally{await r.close()}}[Ft](){this.#e.release()}}class Ue{#e;constructor(e){this.#e=e}createDriver(){return new yt(this.#e)}createQueryCompiler(){return new ct}createAdapter(){return new lt}createIntrospector(e){return new ut(e)}}class wt extends na{get supportsCreateIfNotExists(){return!1}get supportsTransactionalDdl(){return!0}get supportsOutput(){return!0}async acquireMigrationLock(e){await De`exec sp_getapplock @DbPrincipal = ${De.lit("dbo")}, @Resource = ${De.lit(Jr)}, @LockMode = ${De.lit("Exclusive")}`.execute(e)}async releaseMigrationLock(){}}var Vt=Symbol(),Ut=Symbol(),Bt=Symbol();class xt{#e;#t;constructor(e){this.#e=f({...e});let{tarn:t,tedious:r,validateConnections:n}=this.#e,{validateConnections:o,...d}=t.options;this.#t=new t.Pool({...d,create:async()=>{let l=await r.connectionFactory();return await new Jt(l,r).connect()},destroy:async(l)=>{await l[Ut]()},validate:n===!1||o===!1?void 0:(l)=>l[Bt]()})}async init(){}async acquireConnection(){return await this.#t.acquire().promise}async beginTransaction(e,t){await e.beginTransaction(t)}async commitTransaction(e){await e.commitTransaction()}async rollbackTransaction(e){await e.rollbackTransaction()}async savepoint(e,t){await e.savepoint(t)}async rollbackToSavepoint(e,t){await e.rollbackTransaction(t)}async releaseConnection(e){if(this.#e.resetConnectionsOnRelease||this.#e.tedious.resetConnectionOnRelease)await e[Vt]();this.#t.release(e)}async destroy(){await this.#t.destroy()}}class Jt{#e;#t;#r;constructor(e,t){this.#e=e,this.#t=!1,this.#r=t}async beginTransaction(e){let{isolationLevel:t}=e;await new Promise((r,n)=>this.#e.beginTransaction((o)=>{if(o)n(o);else r(void 0)},t?Eu(8):void 0,t?this.#n(t):void 0))}async commitTransaction(){await new Promise((e,t)=>this.#e.commitTransaction((r)=>{if(r)t(r);else e(void 0)}))}async connect(){let{promise:e,reject:t,resolve:r}=new ja;this.#e.connect((o)=>{if(o)return t(o);r()}),this.#e.on("error",(o)=>{if(o instanceof Error&&"code"in o&&o.code==="ESOCKET")this.#t=!0;console.error(o),t(o)});function n(){t(Error("The connection ended without ever completing the connection"))}return this.#e.once("end",n),await e,this.#e.off("end",n),this}async executeQuery(e){try{let t=new ja,r=new Be({compiledQuery:e,tedious:this.#r,onDone:t});this.#e.execSql(r.request);let{rowCount:n,rows:o}=await t.promise;return{numAffectedRows:n!==void 0?BigInt(n):void 0,rows:o}}catch(t){throw _e(t,Error())}}async rollbackTransaction(e){await new Promise((t,r)=>this.#e.rollbackTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async savepoint(e){await new Promise((t,r)=>this.#e.saveTransaction((n)=>{if(n)r(n);else t(void 0)},e))}async*streamQuery(e,t){if(!Number.isInteger(t)||t<=0)throw Error("chunkSize must be a positive integer");let r=new Be({compiledQuery:e,streamChunkSize:t,tedious:this.#r});this.#e.execSql(r.request);try{while(!0){let n=await r.readChunk();if(n.length===0)break;if(yield{rows:n},n.length<t)break}}finally{await this.#o(r)}}#n(e){let{ISOLATION_LEVEL:t}=this.#r,n={"read committed":t.READ_COMMITTED,"read uncommitted":t.READ_UNCOMMITTED,"repeatable read":t.REPEATABLE_READ,serializable:t.SERIALIZABLE,snapshot:t.SNAPSHOT}[e];if(n===void 0)throw Error(`Unknown isolation level: ${e}`);return n}#o(e){return new Promise((t)=>{if(e.request.once("requestCompleted",t),!this.#e.cancel())e.request.off("requestCompleted",t),t()})}[Ut](){if("closed"in this.#e&&this.#e.closed)return Promise.resolve();return new Promise((e)=>{this.#e.once("end",e),this.#e.close()})}async[Vt](){await new Promise((e,t)=>{this.#e.reset((r)=>{if(r)return t(r);e()})})}async[Bt](){if(this.#t||this.#i())return!1;try{let e=new ja,t=new Be({compiledQuery:fr.raw("select 1"),onDone:e,tedious:this.#r});return this.#e.execSql(t.request),await e.promise,!0}catch{return!1}}#i(){return"closed"in this.#e&&Boolean(this.#e.closed)}}class Be{#e;#t;#r;#n;#o;#i;constructor(e){let{compiledQuery:t,onDone:r,streamChunkSize:n,tedious:o}=e;if(this.#t=[],this.#r=n,this.#n={},this.#o=o,r)this.#n.onDone=(l,g)=>{if(l==="chunkReady")return;if(delete this.#n.onDone,l==="error")return r.reject(g);r.resolve({rowCount:this.#i,rows:this.#t})};this.#e=new this.#o.Request(t.sql,(d,l)=>{if(d)return Object.values(this.#n).forEach((g)=>g("error",d instanceof AggregateError?d.errors:d));this.#i=l}),this.#a(t.parameters),this.#c()}get request(){return this.#e}readChunk(){let e=this.readChunk.name;return new Promise((t,r)=>{this.#n[e]=(n,o)=>{if(delete this.#n[e],n==="error")return r(o);t(this.#t.splice(0,this.#r))},this.#e.resume()})}#a(e){for(let t=0;t<e.length;t++){let r=e[t];this.#e.addParameter(String(t+1),this.#s(r),r)}}#c(){let e=this.#r?()=>{if(this.#r<=this.#t.length)this.#e.pause(),Object.values(this.#n).forEach((r)=>r("chunkReady"))}:()=>{},t=(r)=>{let n={};for(let o of r)n[o.metadata.colName]=o.value;this.#t.push(n),e()};this.#e.on("row",t),this.#e.once("requestCompleted",()=>{Object.values(this.#n).forEach((r)=>r("completed")),this.#e.off("row",t)})}#s(e){if(oa(e)||On(e)||Qt(e))return this.#o.TYPES.NVarChar;if(sa(e)||qo(e)&&e%1===0)if(e<-2147483648||e>2147483647)return this.#o.TYPES.BigInt;else return this.#o.TYPES.Int;if(qo(e))return this.#o.TYPES.Float;if(Ts(e))return this.#o.TYPES.Bit;if(Tu(e))return this.#o.TYPES.DateTime;if(um(e))return this.#o.TYPES.VarBinary;return this.#o.TYPES.NVarChar}}class Nt{#e;constructor(e){this.#e=e}async getSchemas(){return await this.#e.selectFrom("sys.schemas").select("name").execute()}async getTables(e={withInternalKyselyTables:!1}){let t=await this.#e.selectFrom("sys.tables as tables").leftJoin("sys.schemas as table_schemas","table_schemas.schema_id","tables.schema_id").innerJoin("sys.columns as columns","columns.object_id","tables.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","tables.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).$if(!e.withInternalKyselyTables,(n)=>n.where("tables.name","!=",Jr).where("tables.name","!=",En)).select(["tables.name as table_name",(n)=>n.ref("tables.type").$castTo().as("table_type"),"table_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"]).unionAll(this.#e.selectFrom("sys.views as views").leftJoin("sys.schemas as view_schemas","view_schemas.schema_id","views.schema_id").innerJoin("sys.columns as columns","columns.object_id","views.object_id").innerJoin("sys.types as types","types.user_type_id","columns.user_type_id").leftJoin("sys.schemas as type_schemas","type_schemas.schema_id","types.schema_id").leftJoin("sys.extended_properties as comments",(n)=>n.onRef("comments.major_id","=","views.object_id").onRef("comments.minor_id","=","columns.column_id").on("comments.name","=","MS_Description")).select(["views.name as table_name","views.type as table_type","view_schemas.name as table_schema_name","columns.default_object_id as column_default_object_id","columns.generated_always_type_desc as column_generated_always_type","columns.is_computed as column_is_computed","columns.is_identity as column_is_identity","columns.is_nullable as column_is_nullable","columns.is_rowguidcol as column_is_rowguidcol","columns.name as column_name","types.is_nullable as type_is_nullable","types.name as type_name","type_schemas.name as type_schema_name","comments.value as column_comment"])).orderBy("table_schema_name").orderBy("table_name").orderBy("column_name").execute(),r={};for(let n of t){let o=`${n.table_schema_name}.${n.table_name}`;(r[o]=r[o]||f({columns:[],isView:n.table_type==="V ",name:n.table_name,schema:n.table_schema_name??void 0})).columns.push(f({dataType:n.type_name,dataTypeSchema:n.type_schema_name??void 0,hasDefaultValue:n.column_default_object_id>0||n.column_generated_always_type!=="NOT_APPLICABLE"||n.column_is_identity||n.column_is_computed||n.column_is_rowguidcol,isAutoIncrementing:n.column_is_identity,isNullable:n.column_is_nullable&&n.type_is_nullable,name:n.column_name,comment:n.column_comment??void 0}))}return Object.values(r)}async getMetadata(e){return{tables:await this.getTables(e)}}}var yr=/^[a-z0-9_]$/i;class _t extends Zn{getCurrentParameterPlaceholder(){return`@${this.numParameters}`}visitOffset(e){super.visitOffset(e),this.append(" rows")}compileColumnAlterations(e){let t={};for(let n of e){if(!t[n.kind])t[n.kind]=[];t[n.kind].push(n)}let r=!0;if(t.AddColumnNode)this.append("add "),this.compileList(t.AddColumnNode),r=!1;if(t.AlterColumnNode){if(!r)this.append(", ");this.compileList(t.AlterColumnNode)}if(t.DropColumnNode){if(!r)this.append(", ");this.append("drop column "),this.compileList(t.DropColumnNode)}if(t.ModifyColumnNode){if(!r)this.append(", ");this.compileList(t.ModifyColumnNode)}if(t.RenameColumnNode){if(!r)this.append(", ");this.compileList(t.RenameColumnNode)}}visitAddColumn(e){this.visitNode(e.column)}visitDropColumn(e){this.visitNode(e.column)}visitMergeQuery(e){super.visitMergeQuery(e),this.append(";")}visitCollate(e){this.append("collate ");let{name:t}=e.collation;for(let r of t)if(!yr.test(r))throw Error(`Invalid collation: ${t}`);this.append(t)}announcesNewColumnDataType(){return!1}}class Ct{#e;constructor(e){this.#e=e}createDriver(){return new xt(this.#e)}createQueryCompiler(){return new _t}createAdapter(){return new wt}createIntrospector(e){return new Nt(e)}}function Tt(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Su(e){if(!e)return null;if("dialect"in e)return Su(e.dialect);if("createDriver"in e){if(e instanceof je)return"sqlite";if(e instanceof Ve)return"mysql";if(e instanceof Ue)return"postgres";if(e instanceof Ct)return"mssql"}if("aggregate"in e)return"sqlite";if("getConnection"in e)return"mysql";if("connect"in e)return"postgres";if("fileControl"in e)return"sqlite";if("open"in e&&"close"in e&&"prepare"in e)return"sqlite";if("batch"in e&&"exec"in e&&"prepare"in e)return"sqlite";return null}var cf=async(e)=>{let t=e.database;if(!t)return{kysely:null,databaseType:null,transaction:void 0};if("db"in t)return{kysely:t.db,databaseType:t.type,transaction:t.transaction};if("dialect"in t)return{kysely:new F({dialect:t.dialect}),databaseType:t.type,transaction:t.transaction};let r=void 0,n=Su(t);if("createDriver"in t)r=t;if("aggregate"in t&&!("createSession"in t))r=new je({database:t});if("getConnection"in t)r=new Ve(t);if("connect"in t)r=new Ue({pool:t});if("fileControl"in t){let{BunSqliteDialect:o}=await import("./chunk-p5fwjk5c.js");r=new o({database:t})}if("createSession"in t){let o=void 0;try{({DatabaseSync:o}=await import("node:sqlite"))}catch(d){if(d!==null&&typeof d==="object"&&"code"in d&&d.code!=="ERR_UNKNOWN_BUILTIN_MODULE")throw d}if(o&&t instanceof o){let{NodeSqliteDialect:d}=await import("./chunk-k810fstm.js");r=new d({database:t})}}if("batch"in t&&"exec"in t&&"prepare"in t){let{D1SqliteDialect:o}=await import("./chunk-s41mgkse.js");r=new o({database:t})}return{kysely:r?new F({dialect:r}):null,databaseType:n,transaction:void 0}};function gt(e,t,r){return r==="postgres"?De`${De.ref(e)} ILIKE ${t}`:De`LOWER(${De.ref(e)}) LIKE LOWER(${t})`}function wr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function xr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,values:t.map((r)=>r.toLowerCase())}}function Nr(e,t){return{lhs:De`LOWER(${De.ref(e)})`,value:t.toLowerCase()}}function _r(e,t){return{lhs:De`LOWER(${De.ref(e)})`,value:t.toLowerCase()}}var RI=(e,t)=>{let r=null,n=(l,g=!1)=>({getFieldName:A,schema:D,getDefaultFieldName:z,getDefaultModelName:Ht,getFieldAttributes:Cr,getModelName:te})=>{let Et=(u)=>{let x=[],y=[];if(u)for(let[h,m]of Object.entries(u)){let a=D[Ht(h)]?.fields,[c,w]=h.includes(".")?h.split("."):[void 0,h];if(!a)continue;a.id={type:"string"};for(let[v,i]of Object.entries(a))x.push(De`${De.ref(`join_${w}`)}.${De.ref(i.fieldName||v)} as ${De.ref(`_joined_${w}_${i.fieldName||v}`)}`),y.push({joinModel:h,joinModelRef:w,fieldName:i.fieldName||v})}return{allSelectsStr:y,allSelects:x}},bt=async(u,x,y,h)=>{let m;if(t?.type==="mysql"){await x.execute();let a=u.id?"id":h.length>0&&h[0]?.field?h[0].field:"id";if(!u.id&&h.length===0)return m=await l.selectFrom(y).selectAll().orderBy(A({model:y,field:a}),"desc").limit(1).executeTakeFirst(),m;let c=u[a]!==void 0?u[a]:h[0]?.value;return m=await l.selectFrom(y).selectAll().orderBy(A({model:y,field:a}),"desc").where(A({model:y,field:a}),c===null?"is":"=",c).limit(1).executeTakeFirst(),m}if(t?.type==="mssql")return m=await x.outputAll("inserted").executeTakeFirst(),m;return m=await x.returningAll().executeTakeFirst(),m};function J(u,x){if(!x)return{and:null,or:null};let y={and:[],or:[]};return x.forEach((h)=>{let{field:m,value:a,operator:c="eq",connector:w="AND",mode:v="sensitive"}=h,i=a,C=A({model:u,field:m}),N=v==="insensitive"&&(typeof i==="string"||Array.isArray(i)&&i.every((p)=>typeof p==="string")),T=(p)=>{let s=`${u}.${C}`;if(c.toLowerCase()==="in"){if(N){let{lhs:q,values:E}=wr(s,Array.isArray(i)?i:[i]);return p(q,"in",E)}return p(s,"in",Array.isArray(i)?i:[i])}if(c.toLowerCase()==="not_in"){if(N){let{lhs:q,values:E}=xr(s,Array.isArray(i)?i:[i]);return p(q,"not in",E)}return p(s,"not in",Array.isArray(i)?i:[i])}if(c==="contains"){if(N&&typeof i==="string")return gt(s,`%${i}%`,t?.type);return p(s,"like",`%${i}%`)}if(c==="starts_with"){if(N&&typeof i==="string")return gt(s,`${i}%`,t?.type);return p(s,"like",`${i}%`)}if(c==="ends_with"){if(N&&typeof i==="string")return gt(s,`%${i}`,t?.type);return p(s,"like",`%${i}`)}if(c==="eq"){if(i===null)return p(s,"is",null);if(N&&typeof i==="string"){let{lhs:q,value:E}=Nr(s,i);return p(q,"=",E)}return p(s,"=",i)}if(c==="ne"){if(i===null)return p(s,"is not",null);if(N&&typeof i==="string"){let{lhs:q,value:E}=_r(s,i);return p(q,"<>",E)}return p(s,"<>",i)}if(c==="gt")return p(s,">",i);if(c==="gte")return p(s,">=",i);if(c==="lt")return p(s,"<",i);if(c==="lte")return p(s,"<=",i);return p(s,c,i)};if(w==="OR")y.or.push(T);else y.and.push(T)}),{and:y.and.length?y.and:null,or:y.or.length?y.or:null}}function It(u,x,y){if(!x||!u.length)return u;let h=new Map;for(let a of u){let c={},w={};for(let[C]of Object.entries(x))w[te(C)]={};for(let[C,N]of Object.entries(a)){let T=String(C),p=!1;for(let{joinModel:s,fieldName:q,joinModelRef:E}of y)if(T===`_joined_${E}_${q}`||T===`_Joined${Tt(E)}${Tt(q)}`){w[te(s)][A({model:s,field:q})]=N,p=!0;break}if(!p)c[C]=N}let v=c.id;if(!v)continue;if(!h.has(v)){let C={...c};for(let[N,T]of Object.entries(x))C[te(N)]=T.relation==="one-to-one"?null:[];h.set(v,C)}let i=h.get(v);for(let[C,N]of Object.entries(x)){let T=N.relation==="one-to-one",p=N.limit??100,s=w[te(C)],q=s&&Object.keys(s).length>0&&Object.values(s).some((E)=>E!==null&&E!==void 0);if(T)i[te(C)]=q?s:null;else{let E=te(C);if(Array.isArray(i[E])&&q){if(i[E].length>=p)continue;let qe=A({model:C,field:"id"}),At=s[qe];if(At){if(!i[E].some((Yt)=>Yt[qe]===At)&&i[E].length<p)i[E].push(s)}else if(i[E].length<p)i[E].push(s)}}}}let m=Array.from(h.values());for(let a of m)for(let[c,w]of Object.entries(x))if(w.relation!=="one-to-one"){let v=te(c);if(Array.isArray(a[v])){let i=w.limit??100;if(a[v].length>i)a[v]=a[v].slice(0,i)}}return m}return{async create({data:u,model:x}){return await bt(u,l.insertInto(x).values(u),x,[])},async findOne({model:u,where:x,select:y,join:h}){let{and:m,or:a}=J(u,x),c=l.selectFrom((N)=>{let T=N.selectFrom(u);if(m)T=T.where((p)=>p.and(m.map((s)=>s(p))));if(a)T=T.where((p)=>p.or(a.map((s)=>s(p))));if(y?.length&&y.length>0)T=T.select(y.map((p)=>A({model:u,field:p})));else T=T.selectAll();return T.as("primary")}).selectAll("primary");if(h)for(let[N,T]of Object.entries(h)){let[p,s]=N.includes(".")?N.split("."):[void 0,N];c=c.leftJoin(`${N} as join_${s}`,(q)=>q.onRef(`join_${s}.${T.on.to}`,"=",`primary.${T.on.from}`))}let{allSelectsStr:w,allSelects:v}=Et(h);c=c.select(v);let i=await c.execute();if(!i||!Array.isArray(i)||i.length===0)return null;let C=i[0];if(h)return It(i,h,w)[0];return C},async findMany({model:u,where:x,limit:y,select:h,offset:m,sortBy:a,join:c}){let{and:w,or:v}=J(u,x),i=l.selectFrom((p)=>{let s=p.selectFrom(u);if(t?.type==="mssql"){if(m!==void 0){if(!a)s=s.orderBy(A({model:u,field:"id"}));s=s.offset(m).fetch(y||100)}else if(y!==void 0)s=s.top(y)}else{if(y!==void 0)s=s.limit(y);if(m!==void 0)s=s.offset(m)}if(a?.field)s=s.orderBy(`${A({model:u,field:a.field})}`,a.direction);if(w)s=s.where((q)=>q.and(w.map((E)=>E(q))));if(v)s=s.where((q)=>q.or(v.map((E)=>E(q))));if(h?.length&&h.length>0)s=s.select(h.map((q)=>A({model:u,field:q})));else s=s.selectAll();return s.as("primary")}).selectAll("primary");if(c)for(let[p,s]of Object.entries(c)){let[q,E]=p.includes(".")?p.split("."):[void 0,p];i=i.leftJoin(`${p} as join_${E}`,(qe)=>qe.onRef(`join_${E}.${s.on.to}`,"=",`primary.${s.on.from}`))}let{allSelectsStr:C,allSelects:N}=Et(c);if(i=i.select(N),a?.field)i=i.orderBy(`${A({model:u,field:a.field})}`,a.direction);let T=await i.execute();if(!T)return[];if(c)return It(T,c,C);return T},async update({model:u,where:x,update:y}){let{and:h,or:m}=J(u,x),a=l.updateTable(u).set(y);if(h)a=a.where((c)=>c.and(h.map((w)=>w(c))));if(m)a=a.where((c)=>c.or(m.map((w)=>w(c))));return await bt(y,a,u,x)},async updateMany({model:u,where:x,update:y}){let{and:h,or:m}=J(u,x),a=l.updateTable(u).set(y);if(h)a=a.where((w)=>w.and(h.map((v)=>v(w))));if(m)a=a.where((w)=>w.or(m.map((v)=>v(w))));let c=(await a.executeTakeFirst()).numUpdatedRows;return c>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(c)},async count({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.selectFrom(u).select(l.fn.count("id").as("count"));if(y)m=m.where((c)=>c.and(y.map((w)=>w(c))));if(h)m=m.where((c)=>c.or(h.map((w)=>w(c))));let a=await m.execute();if(typeof a[0].count==="number")return a[0].count;if(typeof a[0].count==="bigint")return Number(a[0].count);return parseInt(a[0].count)},async delete({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.deleteFrom(u);if(y)m=m.where((a)=>a.and(y.map((c)=>c(a))));if(h)m=m.where((a)=>a.or(h.map((c)=>c(a))));await m.execute()},async deleteMany({model:u,where:x}){let{and:y,or:h}=J(u,x),m=l.deleteFrom(u);if(y)m=m.where((c)=>c.and(y.map((w)=>w(c))));if(h)m=m.where((c)=>c.or(h.map((w)=>w(c))));let a=(await m.executeTakeFirst()).numDeletedRows;return a>Number.MAX_SAFE_INTEGER?Number.MAX_SAFE_INTEGER:Number(a)},async consumeOne({model:u,where:x}){let{and:y,or:h}=J(u,x),m=(i)=>{if(y)i=i.where((C)=>C.and(y.map((N)=>N(C))));if(h)i=i.where((C)=>C.or(h.map((N)=>N(C))));return i},a=A({model:u,field:"id"}),c=async(i,C)=>{let N=C[a]??C.id;if(N===void 0||N===null)return null;let T=i.deleteFrom(u).where(`${u}.${a}`,"=",N);if(t?.type==="mysql"){let p=await T.executeTakeFirst();return Number(p.numDeletedRows)>0?C:null}if(t?.type==="mssql")return await T.outputAll("deleted").executeTakeFirst()??null;return await T.returningAll().executeTakeFirst()??null},w=async(i)=>{if(t?.type==="mssql")return await i.outputAll("deleted").executeTakeFirst()??null;return await i.returningAll().executeTakeFirst()??null};if(t?.type==="mysql"){let i=async(C)=>{let N=await m(C.selectFrom(u).selectAll().forUpdate()).limit(1).executeTakeFirst();if(!N)return null;return c(C,N)};return g?i(l):l.transaction().execute(i)}let v=m(l.selectFrom(u).select(`${u}.${a}`)).limit(1);return w(l.deleteFrom(u).where(`${u}.${a}`,"in",v))},options:t}},o=null;o={config:{adapterId:"kysely",adapterName:"Kysely Adapter",usePlural:t?.usePlural,debugLogs:t?.debugLogs,supportsBooleans:t?.type==="sqlite"||t?.type==="mssql"||t?.type==="mysql"||!t?.type?!1:!0,supportsDates:t?.type==="sqlite"||t?.type==="mssql"||!t?.type?!1:!0,supportsJSON:t?.type==="postgres"?!0:!1,supportsArrays:!1,supportsUUIDs:t?.type==="postgres"?!0:!1,transaction:t?.transaction?(l)=>e.transaction().execute((g)=>l(Ms({config:{...o.config,transaction:!1},adapter:n(g,!0)})(r))):!1},adapter:n(e)};let d=Ms(o);return(l)=>(r=l,d(l))};
|
|
6
|
+
export{Su,cf,RI};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$e,qt}from"./chunk-
|
|
2
|
+
import{$e,qt}from"./chunk-781990k7.js";import{z}from"./chunk-yqvhgtez.js";var _=z($e());var N=(e)=>Boolean(e)&&typeof e==="object"&&typeof e.AccessKeyId==="string"&&typeof e.SecretAccessKey==="string"&&typeof e.Token==="string"&&typeof e.Expiration==="string",h=(e)=>({accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,sessionToken:e.Token,expiration:new Date(e.Expiration),...e.AccountId&&{accountId:e.AccountId}});var C=({maxRetries:e=0,timeout:t=1000})=>({maxRetries:e,timeout:t});var v=z($e());import R from"http";function E(e){return new Promise((t,n)=>{let o=R.request({method:"GET",...e,hostname:e.hostname?.replace(/^\[(.+)\]$/,"$1")});o.on("error",(r)=>{n(Object.assign(new v.ProviderError("Unable to connect to instance metadata service"),r)),o.destroy()}),o.on("timeout",()=>{n(new v.ProviderError("TimeoutError from instance metadata service")),o.destroy()}),o.on("response",(r)=>{let{statusCode:a=400}=r;if(a<200||300<=a)n(Object.assign(new v.ProviderError("Error response received from instance metadata service"),{statusCode:a})),o.destroy();let p=[];r.on("data",(s)=>{p.push(s)}),r.on("end",()=>{t(Buffer.concat(p)),o.destroy()})}),o.end()})}var T=(e,t)=>{let n=e();for(let o=0;o<t;o++)n=n.catch(e);return n};var A="AWS_CONTAINER_CREDENTIALS_FULL_URI",g="AWS_CONTAINER_CREDENTIALS_RELATIVE_URI",D="AWS_CONTAINER_AUTHORIZATION_TOKEN",G=(e={})=>{let{timeout:t,maxRetries:n}=C(e);return()=>T(async()=>{let o=await J({logger:e.logger}),r=JSON.parse(await H(t,o));if(!N(r))throw new _.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:e.logger});return h(r)},n)},H=async(e,t)=>{if(process.env[D])t.headers={...t.headers,Authorization:process.env[D]};return(await E({...t,timeout:e})).toString()},q="169.254.170.2",Y=new Set(["localhost","127.0.0.1"]),j=new Set(["http:","https:"]),J=async({logger:e})=>{if(process.env[g])return{hostname:q,path:process.env[g]};if(process.env[A]){let t;try{t=new URL(process.env[A])}catch{throw new _.CredentialsProviderError(`${process.env[A]} is not a valid container metadata service URL`,{tryNextLink:!1,logger:e})}if(!t.hostname||!Y.has(t.hostname))throw new _.CredentialsProviderError(`${t.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:e});if(!t.protocol||!j.has(t.protocol))throw new _.CredentialsProviderError(`${t.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:e});return{protocol:t.protocol,hostname:t.hostname,path:t.pathname+t.search,port:t.port?parseInt(t.port,10):void 0}}throw new _.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${g} or ${A} environment variable is set`,{tryNextLink:!1,logger:e})};var u=z($e());var y=z($e());class O extends y.CredentialsProviderError{tryNextLink;name="InstanceMetadataV1FallbackError";constructor(e,t=!0){super(e,t);this.tryNextLink=t,Object.setPrototypeOf(this,O.prototype)}}var w=z($e()),F=z(qt());var S;(function(e){e.IPv4="http://169.254.169.254",e.IPv6="http://[fd00:ec2::254]"})(S||(S={}));var P={environmentVariableSelector:(e)=>e.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:(e)=>e.ec2_metadata_service_endpoint,default:void 0};var l;(function(e){e.IPv4="IPv4",e.IPv6="IPv6"})(l||(l={}));var X="AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE",Z="ec2_metadata_service_endpoint_mode",L={environmentVariableSelector:(e)=>e[X],configFileSelector:(e)=>e[Z],default:l.IPv4};var b=async()=>F.parseUrl(await Q()||await ee()),Q=async()=>w.loadConfig(P)(),ee=async()=>{let e=await w.loadConfig(L)();switch(e){case l.IPv4:return S.IPv4;case l.IPv6:return S.IPv6;default:throw Error(`Unsupported endpoint mode: ${e}. Select from ${Object.values(l)}`)}};var M=(e,t)=>{let n=300+Math.floor(Math.random()*300),o=new Date(Date.now()+n*1000);t.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(o)}.
|
|
3
3
|
For more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let r=e.originalExpiration??e.expiration;return{...e,...r?{originalExpiration:r}:{},expiration:o}};var V=(e,t={})=>{let n=t?.logger||console,o;return async()=>{let r;try{if(r=await e(),r.expiration&&r.expiration.getTime()<Date.now())r=M(r,n)}catch(a){if(o)n.warn("Credential renew failed: ",a),r=M(o,n);else throw a}return o=r,r}};var W="/latest/meta-data/iam/security-credentials/",te="/latest/api/token",x="AWS_EC2_METADATA_V1_DISABLED",k="ec2_metadata_v1_disabled",U="x-aws-ec2-metadata-token",oe=(e={})=>V(re(e),{logger:e.logger}),re=(e={})=>{let t=!1,{logger:n,profile:o}=e,{timeout:r,maxRetries:a}=C(e),p=async(s,m)=>{if(t||m.headers?.[U]==null){let i=!1,c=!1,B=await u.loadConfig({environmentVariableSelector:(d)=>{let f=d[x];if(c=!!f&&f!=="false",f===void 0)throw new u.CredentialsProviderError(`${x} not set in env, checking config file next.`,{logger:e.logger});return c},configFileSelector:(d)=>{let f=d[k];return i=!!f&&f!=="false",i},default:!1},{profile:o})();if(e.ec2MetadataV1Disabled||B){let d=[];if(e.ec2MetadataV1Disabled)d.push("credential provider initialization (runtime option ec2MetadataV1Disabled)");if(i)d.push(`config file profile (${k})`);if(c)d.push(`process environment variable (${x})`);throw new O(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${d.join(", ")}].`)}}let K=(await T(async()=>{let i;try{i=await ae(m)}catch(c){if(c.statusCode===401)t=!1;throw c}return i},s)).trim();return T(async()=>{let i;try{i=await se(K,m,e)}catch(c){if(c.statusCode===401)t=!1;throw c}return i},s)};return async()=>{let s=await b();if(t)return n?.debug("AWS SDK Instance Metadata","using v1 fallback (no token fetch)"),p(a,{...s,timeout:r});else{let m;try{m=(await ne({...s,timeout:r})).toString()}catch(I){if(I?.statusCode===400)throw Object.assign(I,{message:"EC2 Metadata token request returned error"});else if(I.message==="TimeoutError"||[403,404,405].includes(I.statusCode))t=!0;return n?.debug("AWS SDK Instance Metadata","using v1 fallback (initial)"),p(a,{...s,timeout:r})}return p(a,{...s,headers:{[U]:m},timeout:r})}}},ne=async(e)=>E({...e,path:te,method:"PUT",headers:{"x-aws-ec2-metadata-token-ttl-seconds":"21600"}}),ae=async(e)=>(await E({...e,path:W})).toString(),se=async(e,t,n)=>{let o=JSON.parse((await E({...t,path:W+e})).toString());if(!N(o))throw new u.CredentialsProviderError("Invalid response received from instance metadata service.",{logger:n.logger});return h(o)};export{A as ENV_CMDS_FULL_URI,g as ENV_CMDS_RELATIVE_URI,G as fromContainerMetadata,oe as fromInstanceMetadata};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{De,
|
|
2
|
+
import{De,fr}from"./chunk-wvq717b5.js";import{Zn,Jr,En}from"./chunk-njabdtvb.js";var n=class{get supportsCreateIfNotExists(){return!0}get supportsTransactionalDdl(){return!1}get supportsReturning(){return!0}async acquireMigrationLock(){}async releaseMigrationLock(){}get supportsOutput(){return!0}},s=class{#e;#t=new o;#r;#a;constructor(e){this.#e={...e}}async init(){if(this.#r=this.#e.database,this.#a=new i(this.#r),this.#e.onCreateConnection)await this.#e.onCreateConnection(this.#a)}async acquireConnection(){return await this.#t.lock(),this.#a}async beginTransaction(e){await e.executeQuery(fr.raw("begin"))}async commitTransaction(e){await e.executeQuery(fr.raw("commit"))}async rollbackTransaction(e){await e.executeQuery(fr.raw("rollback"))}async releaseConnection(){this.#t.unlock()}async destroy(){this.#r?.close()}},i=class{#e;constructor(e){this.#e=e}executeQuery(e){let{sql:r,parameters:a}=e,t=this.#e.prepare(r);return Promise.resolve({rows:t.all(a)})}async*streamQuery(){throw Error("Streaming query is not supported by SQLite driver.")}},o=class{#e;#t;async lock(){while(this.#e!==void 0)await this.#e;this.#e=new Promise((e)=>{this.#t=e})}unlock(){let e=this.#t;this.#e=void 0,this.#t=void 0,e?.()}},c=class{#e;constructor(e){this.#e=e}async getSchemas(){return[]}async getTables(e={withInternalKyselyTables:!1}){let r=this.#e.selectFrom("sqlite_schema").where("type","=","table").where("name","not like","sqlite_%").select("name").$castTo();if(!e.withInternalKyselyTables)r=r.where("name","!=",Jr).where("name","!=",En);let a=await r.execute();return Promise.all(a.map(({name:t})=>this.#t(t)))}async getMetadata(e){return{tables:await this.getTables(e)}}async#t(e){let r=this.#e,a=(await r.selectFrom("sqlite_master").where("name","=",e).select("sql").$castTo().execute())[0]?.sql?.split(/[\(\),]/)?.find((t)=>t.toLowerCase().includes("autoincrement"))?.split(/\s+/)?.[0]?.replace(/["`]/g,"");return{name:e,columns:(await r.selectFrom(De`pragma_table_info(${e})`.as("table_info")).select(["name","type","notnull","dflt_value"]).execute()).map((t)=>({name:t.name,dataType:t.type,isNullable:!t.notnull,isAutoIncrementing:t.name===a,hasDefaultValue:t.dflt_value!=null})),isView:!0}}},l=class extends Zn{getCurrentParameterPlaceholder(){return"?"}getLeftIdentifierWrapper(){return'"'}getRightIdentifierWrapper(){return'"'}getAutoIncrement(){return"autoincrement"}},m=class{#e;constructor(e){this.#e={...e}}createDriver(){return new s(this.#e)}createQueryCompiler(){return new l}createAdapter(){return new n}createIntrospector(e){return new c(e)}};export{m as BunSqliteDialect};
|
|
@@ -21,4 +21,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
21
21
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
22
|
|
|
23
23
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
24
|
-
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>pt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=We,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};We.OpenAI=Ps;We.DEFAULT_TIMEOUT=600000;We.OpenAIError=m;We.APIError=O;We.APIConnectionError=xe;We.APIConnectionTimeoutError=Ae;We.APIUserAbortError=F;We.NotFoundError=yt;We.ConflictError=bt;We.RateLimitError=xt;We.BadRequestError=mt;We.AuthenticationError=_t;We.InternalServerError=At;We.PermissionDeniedError=gt;We.UnprocessableEntityError=wt;We.InvalidWebhookSignatureError=se;We.toFile=Ir;We.Completions=Qe;We.Chat=Re;We.Embeddings=Ze;We.Files=tt;We.Images=ot;We.Audio=ce;We.Moderations=at;We.Models=it;We.FineTuning=te;We.Graders=Me;We.VectorStores=we;We.Webhooks=ht;We.Beta=ee;We.Batches=Ke;We.Uploads=Le;We.Responses=ye;We.Realtime=_e;We.Conversations=Fe;We.Evals=Ne;We.Containers=Te;We.Skills=be;We.Videos=ut;class gu extends We{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{We,gu};
|
|
24
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ps.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=rs(a.logLevel,"ClientOptions.logLevel",this)??rs(K("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Ls(),b(this,Wr,Us,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ks(e)}getUserAgent(){return`${this.constructor.name}/JS ${fe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,s){return O.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Is,"m",Ln).call(this)&&r||this.baseURL,n=Cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!Es(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Ie(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,ne({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new F;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new F;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,ne({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ae;throw new xe({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let T=`retrying, ${t} attempts remaining`;return await Bs(u.body),v(this).info(`${R} - ${T}`),v(this).debug(`[${d}] response error (${T})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((T)=>pt(T).message),k=ks(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ne({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await z(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)$s("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,Wr,"f").call(this,{body:e,headers:r})}}Ps=We,Wr=new WeakMap,Is=new WeakSet,Ln=function(){return this.baseURL!=="https://api.openai.com/v1"};We.OpenAI=Ps;We.DEFAULT_TIMEOUT=600000;We.OpenAIError=m;We.APIError=O;We.APIConnectionError=xe;We.APIConnectionTimeoutError=Ae;We.APIUserAbortError=F;We.NotFoundError=yt;We.ConflictError=bt;We.RateLimitError=xt;We.BadRequestError=mt;We.AuthenticationError=_t;We.InternalServerError=At;We.PermissionDeniedError=gt;We.UnprocessableEntityError=wt;We.InvalidWebhookSignatureError=se;We.toFile=Ir;We.Completions=Qe;We.Chat=Re;We.Embeddings=Ze;We.Files=tt;We.Images=ot;We.Audio=ce;We.Moderations=at;We.Models=it;We.FineTuning=te;We.Graders=Me;We.VectorStores=we;We.Webhooks=ht;We.Beta=ee;We.Batches=Ke;We.Uploads=Le;We.Responses=ye;We.Realtime=_e;We.Conversations=Fe;We.Evals=Ne;We.Containers=Te;We.Skills=be;We.Videos=ut;class Au extends We{constructor({baseURL:e=K("OPENAI_BASE_URL"),apiKey:t=K("AZURE_OPENAI_API_KEY"),apiVersion:r=K("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(ui.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Be(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var ui=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{We,Au};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{We}from"./chunk-
|
|
3
|
-
${f}`;r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Pe=(e,n,t)=>{z(e.provider,t?.apiKey,t?.headers);let r=Cr(e,n,t,t?.apiKey),s=t?.reasoning?Hr(e,t.reasoning):void 0,g=s==="off"?void 0:s,f=t?.toolChoice;return se(e,n,{...r,reasoningEffort:g,toolChoice:f})};function oe(e,n,t,r,s,g=P(e)){let f={...e.headers};if(e.provider==="github-copilot"){let k=La(n.messages),i=Za({messages:n.messages,hasImages:k});Object.assign(f,i)}if(s&&g.sendSessionAffinityHeaders)if(g.sessionAffinityFormat==="openrouter")f["x-session-id"]=s;else{if(g.sessionAffinityFormat==="openai")f.session_id=s;f["x-client-request-id"]=s,f["x-session-affinity"]=s}if(r)Object.assign(f,r);return new We({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function ie(e,n,t,r=P(e),s=G(t?.cacheRetention,t?.env),g=Qn(n.tools,r.supportsOpenAIGrammarTools)){let f=me(e,n,r,{grammarToolInputProperties:g}),k=fe(r,s),i={model:e.id,messages:f,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&s!=="none"||s==="long"&&r.supportsLongCacheRetention?
|
|
2
|
+
import{We}from"./chunk-pa1fmskf.js";import{Yr}from"./chunk-ycw3rwhx.js";import{cr}from"./chunk-3h9c5ak3.js";import{La,Za}from"./chunk-dscq4a4k.js";import{ss}from"./chunk-2kxhdnma.js";import{wn,xn}from"./chunk-qgkbxw1k.js";import{xs}from"./chunk-r7e2fmmx.js";import{as}from"./chunk-628k58ek.js";import{qe,sc,ac,uo,Vi,Qn,Cr,fo}from"./chunk-3g5pyw2e.js";import{ln}from"./chunk-gc6m7agb.js";import{cn,Hr}from"./chunk-05tnmf8h.js";import{Yt}from"./chunk-b3aqmcps.js";function B(e,n){if(!e)return!1;let t=n.toLowerCase();for(let[r,s]of Object.entries(e))if(r.toLowerCase()===t&&s!==null&&s.trim().length>0)return!0;return!1}function z(e,n,t){if(n)return n;if(B(t,"authorization")||B(t,"cf-aig-authorization"))return"unused";throw Error(`No API key for provider: ${e}`)}function Q(e){for(let n of e){if(n.role==="toolResult")return!0;if(n.role==="assistant"){if(n.content.some((t)=>t.type==="toolCall"))return!0}}return!1}function X(e){let n=new Set;for(let t of e)if(t.role==="toolResult")for(let r of t.addedToolNames??[])n.add(r);return n}function Y(e,n){if(!e)return[];let t=new Map(e.map((r)=>[r.name,r]));return Array.from(n).map((r)=>t.get(r)).filter((r)=>r!==void 0)}function D(e){return e.type==="text"}function ee(e){return e.type==="thinking"}function te(e){return e.type==="toolCall"}function ne(e){return e.type==="image"}function re(e){if(typeof e!=="object"||e===null)return!1;let n=e;return n.type==="reasoning.encrypted"&&typeof n.id==="string"&&n.id.length>0&&typeof n.data==="string"&&n.data.length>0}function G(e,n){if(e)return e;if(cr("PI_CACHE_RETENTION",n)==="long")return"long";return"short"}var se=(e,n,t)=>{let r=new Yt;return(async()=>{let s={role:"assistant",content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:Date.now()};try{let g=z(e.provider,t?.apiKey,t?.headers),f=P(e),k=Qn(n.tools,f.supportsOpenAIGrammarTools),i=G(t?.cacheRetention,t?.env),d=i==="none"?void 0:t?.sessionId,l=oe(e,n,g,t?.headers,d,f),a=ie(e,n,t,f,i,k),m=await t?.onPayload?.(a,e);if(m!==void 0)a=m;let y={...t?.signal?{signal:t.signal}:{},...t?.timeoutMs!==void 0?{timeout:t.timeoutMs}:{},maxRetries:0},{data:v,response:C}=await as(()=>l.chat.completions.create(a,y).withResponse(),{maxRetries:t?.maxRetries,maxRetryDelayMs:t?.maxRetryDelayMs,signal:t?.signal});await t?.onResponse?.({status:C.status,headers:ln(C.headers)},e),r.push({type:"start",partial:s});let M=null,h=null,T=!1,x=new Map,E=new Map,O=new Map,F=s.content,w=(o)=>F.indexOf(o),q=(o)=>{let u=o.customInput?.property;if(u===void 0)return"";let _=o.arguments[u];return typeof _==="string"?_:""},L=(o,u,_)=>{let c=o.customInput;if(!c)return;let A=ac(c.jsonBuffer,c.property,u,_);return o.arguments={[c.property]:u},A},H=(o)=>{let u=w(o);if(u===-1)return;if(o.type==="text")r.push({type:"text_end",contentIndex:u,content:o.text,partial:s});else if(o.type==="thinking")r.push({type:"thinking_end",contentIndex:u,content:o.thinking,partial:s});else if(o.type==="toolCall"){if(o.customInput){let _=L(o,q(o),!0);if(_!==void 0)r.push({type:"toolcall_delta",contentIndex:u,delta:_,partial:s})}else o.arguments=Yr(o.partialArgs);delete o.partialArgs,delete o.customInput,delete o.streamIndex,r.push({type:"toolcall_end",contentIndex:u,toolCall:o,partial:s})}},W=()=>{if(!M)M={type:"text",text:""},F.push(M),r.push({type:"text_start",contentIndex:w(M),partial:s});return M},U=(o)=>{if(!h)h={type:"thinking",thinking:"",thinkingSignature:o},F.push(h),r.push({type:"thinking_start",contentIndex:w(h),partial:s});return h},J=(o)=>{if(!o.id)return;let u=O.get(o.id);if(u)o.thoughtSignature=u,O.delete(o.id)},V=(o)=>{let u=typeof o.index==="number"?o.index:void 0,_=o.function?.name??o.custom?.name??"",c=u!==void 0?x.get(u):void 0;if(!c&&o.id)c=E.get(o.id);if(!c){let A=o.custom?k.get(_)??"input":void 0,S=A!==void 0;if(c={type:"toolCall",id:o.id||"",name:_,arguments:S?{[A]:""}:{},partialArgs:S?void 0:"",customInput:S?{property:A,jsonBuffer:{input:"",started:!1,closed:!1}}:void 0,streamIndex:u},u!==void 0)x.set(u,c);if(o.id)E.set(o.id,c);F.push(c),r.push({type:"toolcall_start",contentIndex:w(c),partial:s})}if(u!==void 0&&c.streamIndex===void 0)c.streamIndex=u,x.set(u,c);if(o.id)E.set(o.id,c);if(!c.name&&_)c.name=_;if(o.custom&&!c.customInput){let A=k.get(c.name)??"input";c.arguments={[A]:""},c.customInput={property:A,jsonBuffer:{input:"",started:!1,closed:!1}},delete c.partialArgs}return J(c),c};for await(let o of v){if(!o||typeof o!=="object")continue;if(s.responseId||=o.id,typeof o.model==="string"&&o.model.length>0&&o.model!==e.id)s.responseModel||=o.model;if(o.usage)s.usage=N(o.usage,e);let u=Array.isArray(o.choices)?o.choices[0]:void 0;if(!u)continue;if(!o.usage&&u.usage)s.usage=N(u.usage,e);if(u.finish_reason){let _=ye(u.finish_reason);if(s.stopReason=_.stopReason,_.errorMessage)s.errorMessage=_.errorMessage;T=!0}if(u.delta){if(u.delta.content!==null&&u.delta.content!==void 0&&u.delta.content.length>0){let p=W();p.text+=u.delta.content,r.push({type:"text_delta",contentIndex:w(p),delta:u.delta.content,partial:s})}let _=["reasoning_content","reasoning","reasoning_text"],c=u.delta,A=null;for(let p of _){let R=c[p];if(typeof R==="string"&&R.length>0){A=p;break}}if(A){let p=c[A];if(typeof p==="string"&&p.length>0){let R=e.provider==="opencode-go"&&A==="reasoning"?"reasoning_content":A,I=U(R);I.thinking+=p,r.push({type:"thinking_delta",contentIndex:w(I),delta:p,partial:s})}}if(u?.delta?.tool_calls)for(let p of u.delta.tool_calls){let R=V(p);if(!R.id&&p.id)R.id=p.id,E.set(p.id,R);let I=p.function?.name??p.custom?.name;if(!R.name&&I)R.name=I;let b="";if(p.function?.arguments)b=p.function.arguments,R.partialArgs=(R.partialArgs??"")+p.function.arguments,R.arguments=Yr(R.partialArgs);else if(p.custom?.input){let Z=q(R)+p.custom.input;b=L(R,Z,!1)??""}r.push({type:"toolcall_delta",contentIndex:w(R),delta:b,partial:s})}let S=u.delta.reasoning_details;if(Array.isArray(S)){for(let p of S)if(re(p)){let R=JSON.stringify(p),I=E.get(p.id);if(I)I.thoughtSignature=R;else O.set(p.id,R)}}}}for(let o of F)H(o);if(t?.signal?.aborted)throw Error("Request was aborted");if(s.stopReason==="aborted")throw Error("Request was aborted");if(s.stopReason==="error")throw Error(s.errorMessage||"Provider returned an error stop reason");if(!T)throw Error("Stream ended without finish_reason");r.push({type:"done",reason:s.stopReason,message:s}),r.end()}catch(g){for(let k of s.content)delete k.index,delete k.partialArgs,delete k.customInput,delete k.streamIndex;s.stopReason=t?.signal?.aborted?"aborted":"error",s.errorMessage=xn(wn(g));let f=g?.error?.metadata?.raw;if(f&&!s.errorMessage.includes(String(f)))s.errorMessage+=`
|
|
3
|
+
${f}`;r.push({type:"error",reason:s.stopReason,error:s}),r.end()}})(),r},Pe=(e,n,t)=>{z(e.provider,t?.apiKey,t?.headers);let r=Cr(e,n,t,t?.apiKey),s=t?.reasoning?Hr(e,t.reasoning):void 0,g=s==="off"?void 0:s,f=t?.toolChoice;return se(e,n,{...r,reasoningEffort:g,toolChoice:f})};function oe(e,n,t,r,s,g=P(e)){let f={...e.headers};if(e.provider==="github-copilot"){let k=La(n.messages),i=Za({messages:n.messages,hasImages:k});Object.assign(f,i)}if(s&&g.sendSessionAffinityHeaders)if(g.sessionAffinityFormat==="openrouter")f["x-session-id"]=s;else{if(g.sessionAffinityFormat==="openai")f.session_id=s;f["x-client-request-id"]=s,f["x-session-affinity"]=s}if(r)Object.assign(f,r);return new We({apiKey:t,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function ie(e,n,t,r=P(e),s=G(t?.cacheRetention,t?.env),g=Qn(n.tools,r.supportsOpenAIGrammarTools)){let f=me(e,n,r,{grammarToolInputProperties:g}),k=fe(r,s),i={model:e.id,messages:f,stream:!0,prompt_cache_key:e.baseUrl.includes("api.openai.com")&&s!=="none"||s==="long"&&r.supportsLongCacheRetention?ss(t?.sessionId):void 0,prompt_cache_retention:s==="long"&&r.supportsLongCacheRetention?"24h":void 0};if(r.supportsUsageInStreaming!==!1)i.stream_options={include_usage:!0};if(r.supportsStore)i.store=!1;if(t?.maxTokens)if(r.maxTokensField==="max_tokens")i.max_tokens=t.maxTokens;else i.max_completion_tokens=t.maxTokens;if(t?.temperature!==void 0)i.temperature=t.temperature;let d=r.deferredToolsMode==="kimi"?X(n.messages):new Set,l=n.tools?.filter((a)=>!d.has(a.name));if(l&&l.length>0){if(i.tools=K(l,r),r.zaiToolStream)i.tool_stream=!0}else if(Q(n.messages))i.tools=[];if(k)le(f,i.tools,k);if(t?.toolChoice)i.tool_choice=t.toolChoice;if(r.thinkingFormat==="zai"&&e.reasoning){let a=i;if(a.thinking=t?.reasoningEffort?{type:"enabled",clear_thinking:!1}:{type:"disabled"},t?.reasoningEffort&&r.supportsReasoningEffort){let m=e.thinkingLevelMap?.[t.reasoningEffort],y=m===void 0?t.reasoningEffort:m;if(typeof y==="string")a.reasoning_effort=y}}else if(r.thinkingFormat==="qwen"&&e.reasoning)i.enable_thinking=!!t?.reasoningEffort;else if(r.thinkingFormat==="qwen-chat-template"&&e.reasoning)i.chat_template_kwargs={enable_thinking:!!t?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat==="chat-template"&&e.reasoning){let a=ae(e,t,r);if(a)i.chat_template_kwargs=a}else if(r.thinkingFormat==="deepseek"&&e.reasoning){if(t?.reasoningEffort)i.thinking={type:"enabled"};else if(e.thinkingLevelMap?.off!==null)i.thinking={type:"disabled"};if(t?.reasoningEffort&&r.supportsReasoningEffort)i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(r.thinkingFormat==="openrouter"&&e.reasoning){let a=i;if(t?.reasoningEffort)a.reasoning={effort:e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort};else if(e.thinkingLevelMap?.off!==null)a.reasoning={effort:e.thinkingLevelMap?.off??"none"}}else if(r.thinkingFormat==="ant-ling"&&e.reasoning&&t?.reasoningEffort){let a=e.thinkingLevelMap?.[t.reasoningEffort];if(typeof a==="string")i.reasoning={effort:a}}else if(r.thinkingFormat==="together"&&e.reasoning){let a=i;if(a.reasoning={enabled:!!t?.reasoningEffort},t?.reasoningEffort&&r.supportsReasoningEffort)a.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort}else if(r.thinkingFormat==="string-thinking"&&e.reasoning){let a=i;if(t?.reasoningEffort)a.thinking=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(e.thinkingLevelMap?.off!==null)a.thinking=e.thinkingLevelMap?.off??"none"}else if(t?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)i.reasoning_effort=e.thinkingLevelMap?.[t.reasoningEffort]??t.reasoningEffort;else if(!t?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let a=e.thinkingLevelMap?.off;if(typeof a==="string")i.reasoning_effort=a}if(e.compat?.openRouterRouting)i.provider=e.compat.openRouterRouting;if(e.compat?.vercelGatewayRouting){let a=e.compat.vercelGatewayRouting;if(a.only||a.order){let m={};if(a.only)m.only=a.only;if(a.order)m.order=a.order;i.providerOptions={gateway:m}}}return i}function ae(e,n,t){let r={};for(let[s,g]of Object.entries(t.chatTemplateKwargs)){let f=ue(e,n,g);if(f!==void 0)r[s]=f}return Object.keys(r).length>0?r:void 0}function ue(e,n,t){if(typeof t!=="object"||t===null)return t;let r=n?.reasoningEffort;if(!r&&t.omitWhenOff)return;if(t.$var==="thinking.enabled")return!!r;let s=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return s===void 0?r:typeof s==="string"?s:void 0}function fe(e,n){if(e.cacheControlFormat!=="anthropic"||n==="none")return;let t=n==="long"&&e.supportsLongCacheRetention?"1h":void 0;return{type:"ephemeral",...t?{ttl:t}:{}}}function le(e,n,t){ce(e,t),ge(n,t),pe(e,t)}function ce(e,n){for(let t of e)if(t.role==="system"||t.role==="developer"){de(t,n);return}}function pe(e,n){for(let t=e.length-1;t>=0;t--){let r=e[t];if(r.role==="user"||r.role==="assistant"||r.role==="tool"){if(he(r,n))return}}}function ge(e,n){if(!e||e.length===0)return;let t=e[e.length-1];t.cache_control=n}function de(e,n){return j(e,n)}function he(e,n){if(e.role==="user"||e.role==="assistant"||e.role==="tool")return j(e,n);return!1}function j(e,n){let t=e.content;if(typeof t==="string"){if(t.length===0)return!1;return e.content=[{type:"text",text:t,cache_control:n}],!0}if(!Array.isArray(t))return!1;for(let r=t.length-1;r>=0;r--){let s=t[r];if(s?.type==="text"){let g=s;return g.cache_control=n,!0}}return!1}function me(e,n,t,r){let s=[],g=(i)=>{if(i.includes("|")){let d=i.indexOf("|"),l=i.slice(0,d).replace(/[^a-zA-Z0-9_-]/g,"_"),a=i.slice(d+1).replace(/[^a-zA-Z0-9_-]/g,"_"),m=a.length>0?`${l}_${a}`:l;if(m.length<=40)return m;let y=xs(i).slice(0,8);return`${l.slice(0,Math.max(1,40-y.length-1))}_${y}`}if(e.provider==="openai")return i.length>40?i.slice(0,40):i;return i},f=fo(n.messages,e,(i)=>g(i));if(n.systemPrompt){let d=e.reasoning&&t.supportsDeveloperRole?"developer":"system";s.push({role:d,content:qe(n.systemPrompt)})}let k=null;for(let i=0;i<f.length;i++){let d=f[i];if(t.requiresAssistantAfterToolResult&&k==="toolResult"&&d.role==="user")s.push({role:"assistant",content:"I have processed the tool results."});if(d.role==="user")if(typeof d.content==="string")s.push({role:"user",content:qe(d.content)});else{let l=d.content.map((a)=>{if(a.type==="text")return{type:"text",text:qe(a.text)};else return{type:"image_url",image_url:{url:`data:${a.mimeType};base64,${a.data}`}}});if(l.length===0)continue;s.push({role:"user",content:l})}else if(d.role==="assistant"){let l={role:"assistant",content:t.requiresAssistantAfterToolResult?"":null},a=d.content.filter(D).filter((h)=>h.text.trim().length>0).map((h)=>({type:"text",text:qe(h.text)})),m=a.map((h)=>h.text).join(""),y=d.content.filter(ee).filter((h)=>h.thinking.trim().length>0);if(y.length>0)if(t.requiresThinkingAsText){let h=y.map((T)=>qe(T.thinking)).join(`
|
|
4
4
|
|
|
5
5
|
`);l.content=[{type:"text",text:h},...a]}else{if(m.length>0)l.content=m;let h=y[0].thinkingSignature;if(e.provider==="opencode-go"&&h==="reasoning")h="reasoning_content";if(h&&h.length>0)l[h]=y.map((T)=>T.thinking).join(`
|
|
6
6
|
`)}else if(m.length>0)l.content=m;let v=d.content.filter(te);if(v.length>0){l.tool_calls=v.map((T)=>{let x=r?.grammarToolInputProperties?.get(T.name);if(x!==void 0)return{id:T.id,type:"custom",custom:{name:T.name,input:qe(sc(T.name,T.arguments,x))}};return{id:T.id,type:"function",function:{name:T.name,arguments:JSON.stringify(T.arguments)}}});let h=v.filter((T)=>T.thoughtSignature).map((T)=>{try{return JSON.parse(T.thoughtSignature)}catch{return null}}).filter(Boolean);if(h.length>0)l.reasoning_details=h}if(t.requiresReasoningContentOnAssistantMessages&&e.reasoning&&l.reasoning_content===void 0)l.reasoning_content="";let C=l.content;if(!(C!==null&&C!==void 0&&(typeof C==="string"?C.length>0:C.length>0))&&!l.tool_calls)continue;s.push(l)}else if(d.role==="toolResult"){let l=[],a=new Set,m=i;for(;m<f.length&&f[m].role==="toolResult";m++){let y=f[m],v=y.content.filter(D).map((x)=>x.text).join(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{I}from"./chunk-
|
|
1
|
+
import{I}from"./chunk-q6jsw0rr.js";var a=[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]],lo=I("upload",a);
|
|
2
2
|
export{lo};
|