appos 0.1.18-0 → 0.1.20-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/build/exports/adapter-factory-CLtf7vT5-djMsiEBl.mjs +88 -0
  2. package/build/exports/appos.d.ts +82 -0
  3. package/build/exports/bun-sqlite-dialect-DN7EKoIB-B0dpsiEy.mjs +1 -0
  4. package/build/exports/chunk-BYI67GdN.mjs +1 -0
  5. package/build/exports/chunk-DQj_Q5LL.mjs +1 -0
  6. package/build/exports/client-Cf0k1wnb.mjs +7 -0
  7. package/build/exports/client.d.ts +2093 -2082
  8. package/build/exports/client.js +22 -60
  9. package/build/exports/date.d.ts +1 -1
  10. package/build/exports/date.js +1 -1
  11. package/build/exports/db.d.mts +5195 -0
  12. package/build/exports/db.mjs +8 -0
  13. package/build/exports/dialect-BeMwdQoz-BUgv8nHa.mjs +1 -0
  14. package/build/exports/dist-cjs-6zIKAlZR.mjs +1 -0
  15. package/build/exports/dist-cjs-8ShtoC4L.mjs +1 -0
  16. package/build/exports/dist-cjs-8w9IfsHf.mjs +1 -0
  17. package/build/exports/dist-cjs-B5EVkyOL.mjs +1 -0
  18. package/build/exports/dist-cjs-BCXEF6CM.mjs +1 -0
  19. package/build/exports/dist-cjs-BEWqPJiY.mjs +1 -0
  20. package/build/exports/dist-cjs-BY2gcA7W.mjs +22 -0
  21. package/build/exports/dist-cjs-BilOG_GK.mjs +5 -0
  22. package/build/exports/dist-cjs-BurjEDDY.mjs +1 -0
  23. package/build/exports/dist-cjs-CkmP5Wcr.mjs +1 -0
  24. package/build/exports/dist-cjs-D9iFq61w.mjs +1 -0
  25. package/build/exports/dist-cjs-DBYzdOBR.mjs +10 -0
  26. package/build/exports/dist-cjs-DO06FS0-.mjs +1 -0
  27. package/build/exports/dist-cjs-Ddwe8ROf.mjs +1 -0
  28. package/build/exports/dist-cjs-DpVGmjIF.mjs +1 -0
  29. package/build/exports/esm-FzcFIiBQ.mjs +3 -0
  30. package/build/exports/event-streams-BOfsfbfw.mjs +1 -0
  31. package/build/exports/file-preview-dialog-BquzKbRO.mjs +59 -0
  32. package/build/exports/kysely-adapter-WhLCdqvu.mjs +1 -0
  33. package/build/exports/magic-string.es-jZcifc5m.mjs +14 -0
  34. package/build/exports/memory-adapter-CBfVsIEf.mjs +1 -0
  35. package/build/exports/node-ponyfill-PofhX7d2.mjs +1 -0
  36. package/build/exports/node-sqlite-dialect-BqISUSC3-DSS_lf2e.mjs +1 -0
  37. package/build/exports/package-DfozRyK6.mjs +1 -0
  38. package/build/exports/react-dom-DRJH8-Wa.mjs +42 -0
  39. package/build/exports/server.d.mts +71688 -0
  40. package/build/exports/server.mjs +325 -0
  41. package/build/exports/sso-oidc-DMxhsWZu.mjs +1 -0
  42. package/build/exports/sts-CqD3bswo.mjs +1 -0
  43. package/build/exports/sts-DJilo-ly.mjs +1 -0
  44. package/build/exports/test.d.mts +8922 -0
  45. package/build/exports/test.mjs +1255 -0
  46. package/build/exports/ui/index.d.ts +1595 -568
  47. package/build/exports/ui/index.js +112 -162
  48. package/build/exports/utils.d.ts +6 -4
  49. package/build/exports/utils.js +1 -1
  50. package/build/exports/zod.d.ts +2 -1
  51. package/build/exports/zod.js +13 -13
  52. package/package.json +9 -8
  53. package/build/exports/bun-sqlite-dialect-DN7EKoIB-U6HWGDKS.js +0 -1
  54. package/build/exports/chunk-2LU65C2X.js +0 -1
  55. package/build/exports/chunk-3RRIQKOV.js +0 -2
  56. package/build/exports/chunk-A2LPCJPF.js +0 -5
  57. package/build/exports/chunk-CWTDMDIJ.js +0 -2
  58. package/build/exports/chunk-FBFACBKZ.js +0 -20
  59. package/build/exports/chunk-FZ26Y4SI.js +0 -1
  60. package/build/exports/chunk-GQYUAAFT.js +0 -1
  61. package/build/exports/chunk-HZYRJBRQ.js +0 -1
  62. package/build/exports/chunk-IAPQO6XO.js +0 -1
  63. package/build/exports/chunk-JIMTVXLP.js +0 -5
  64. package/build/exports/chunk-KNTGSRCW.js +0 -20
  65. package/build/exports/chunk-KRQ2L5OP.js +0 -1
  66. package/build/exports/chunk-MQK6VFZR.js +0 -1
  67. package/build/exports/chunk-N756FM5W.js +0 -6
  68. package/build/exports/chunk-NJ2TZAVN.js +0 -169
  69. package/build/exports/chunk-NM7CITTT.js +0 -2
  70. package/build/exports/chunk-PECJ5CRS.js +0 -1
  71. package/build/exports/chunk-PYGCG54X.js +0 -94
  72. package/build/exports/chunk-QMFB7WUQ.js +0 -1
  73. package/build/exports/chunk-QWUKON2B.js +0 -4
  74. package/build/exports/chunk-S3F2U5VR.js +0 -1
  75. package/build/exports/chunk-S6CGHQRG.js +0 -2
  76. package/build/exports/chunk-TLDYRTHH.js +0 -1
  77. package/build/exports/chunk-TX6WXZHJ.js +0 -1
  78. package/build/exports/chunk-Y6DVQ7FD.js +0 -1
  79. package/build/exports/chunk-YBDDYGAW.js +0 -1
  80. package/build/exports/db.d.ts +0 -5194
  81. package/build/exports/db.js +0 -9
  82. package/build/exports/dist-es-442MVKMG.js +0 -1
  83. package/build/exports/dist-es-5NPX4IPA.js +0 -2
  84. package/build/exports/dist-es-AAGJZOKW.js +0 -1
  85. package/build/exports/dist-es-BA4XRQMD.js +0 -1
  86. package/build/exports/dist-es-CEXBPGKD.js +0 -1
  87. package/build/exports/dist-es-D7P74EQC.js +0 -2
  88. package/build/exports/dist-es-K23RHFIG.js +0 -2
  89. package/build/exports/dist-es-K6CZFUD7.js +0 -5
  90. package/build/exports/dist-es-PV5MXZPQ.js +0 -5
  91. package/build/exports/dist-es-PV6DSUWC.js +0 -1
  92. package/build/exports/dist-es-PYWXCUQO.js +0 -2
  93. package/build/exports/dist-es-QLJ2PEMO.js +0 -1
  94. package/build/exports/dist-es-TDQNJYF5.js +0 -1
  95. package/build/exports/dist-es-VXQY2642.js +0 -1
  96. package/build/exports/event-streams-JL44VPIA.js +0 -1
  97. package/build/exports/file-preview-dialog-XJMPJ764.js +0 -15
  98. package/build/exports/kysely-adapter-UB5EKM3L.js +0 -1
  99. package/build/exports/loadSso-ATQGBCEY.js +0 -1
  100. package/build/exports/loadSso-ILXKFPPV.js +0 -1
  101. package/build/exports/magic-string.es-TEACLLHX.js +0 -13
  102. package/build/exports/memory-adapter-LJJR2XXS.js +0 -1
  103. package/build/exports/node-ponyfill-6NJTIN4I.js +0 -1
  104. package/build/exports/node-sqlite-dialect-BqISUSC3-3545EWOZ.js +0 -1
  105. package/build/exports/plugin-56OEBMME.js +0 -4
  106. package/build/exports/server.d.ts +0 -71779
  107. package/build/exports/server.js +0 -435
  108. package/build/exports/sso-oidc-7POVDJYK.js +0 -1
  109. package/build/exports/sso-oidc-TUR3VC4Y.js +0 -1
  110. package/build/exports/sts-35P3OWOX.js +0 -6
  111. package/build/exports/sts-ZDKVF6HW.js +0 -1
  112. package/build/exports/test.d.ts +0 -8942
  113. package/build/exports/test.js +0 -1583
@@ -0,0 +1,8 @@
1
+ const e=Symbol.for(`drizzle:entityKind`);function t(t,n){if(!t||typeof t!=`object`)return!1;if(t instanceof n)return!0;if(!Object.prototype.hasOwnProperty.call(n,e))throw Error(`Class "${n.name??`<unknown>`}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=Object.getPrototypeOf(t).constructor;if(r)for(;r;){if(e in r&&r[e]===n[e])return!0;r=Object.getPrototypeOf(r)}return!1}var n=class{static[e]=`Column`;name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;length;isLengthExact;config;table;onInit(){}constructor(e,t){this.config=t,this.onInit(),this.table=e,this.name=t.name,this.keyAsName=t.keyAsName,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType,this.generated=t.generated,this.generatedIdentity=t.generatedIdentity,this.length=t.length,this.isLengthExact=t.isLengthExact}mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!==`byDefault`}},r=class{static[e]=`ColumnBuilder`;config;constructor(e,t,n){this.config={name:e,keyAsName:e===``,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){this.config.name===``&&(this.config.name=e)}};const i=Symbol.for(`drizzle:Name`);var a=class{static[e]=`PgForeignKeyBuilder`;reference;_onUpdate=`no action`;_onDelete=`no action`;constructor(e,t){this.reference=()=>{let{name:t,columns:n,foreignColumns:r}=e();return{name:t,columns:n,foreignTable:r[0].table,foreignColumns:r}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=e===void 0?`no action`:e,this}onDelete(e){return this._onDelete=e===void 0?`no action`:e,this}build(e){return new o(e,this)}},o=class{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static[e]=`PgForeignKey`;reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:n}=this.reference(),r=t.map(e=>e.name),a=n.map(e=>e.name),o=[this.table[i],...r,n[0].table[i],...a];return e??`${o.join(`_`)}_fk`}};function s(e){function t(){let{name:t,columns:n,foreignColumns:r}=e;return{name:t,columns:n,foreignColumns:r}}return new a(t)}function c(e,...t){return e(...t)}function l(e){return new f(e)}function u(e,t){return`${e[i]}_${t.join(`_`)}_unique`}var d=class{constructor(e,t){this.name=t,this.columns=e}static[e]=`PgUniqueConstraintBuilder`;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new p(e,this.columns,this.nullsNotDistinctConfig,this.name)}},f=class{static[e]=`PgUniqueOnConstraintBuilder`;name;constructor(e){this.name=e}on(...e){return new d(e,this.name)}},p=class{constructor(e,t,n,r){this.table=e,this.columns=t,this.name=r??u(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static[e]=`PgUniqueConstraint`;columns;name;nullsNotDistinct=!1;getName(){return this.name}};function m(e,t,n){for(let r=t;r<e.length;r++){let i=e[r];if(i===`\\`){r++;continue}if(i===`"`)return[e.slice(t,r).replace(/\\/g,``),r+1];if(!n&&(i===`,`||i===`}`))return[e.slice(t,r).replace(/\\/g,``),r]}return[e.slice(t).replace(/\\/g,``),e.length]}function h(e,t=0){let n=[],r=t,i=!1;for(;r<e.length;){let a=e[r];if(a===`,`){(i||r===t)&&n.push(``),i=!0,r++;continue}if(i=!1,a===`\\`){r+=2;continue}if(a===`"`){let[t,i]=m(e,r+1,!0);n.push(t),r=i;continue}if(a===`}`)return[n,r+1];if(a===`{`){let[t,i]=h(e,r+1);n.push(t),r=i;continue}let[o,s]=m(e,r,!1);n.push(o),r=s}return[n,r]}function g(e){let[t]=h(e,1);return t}function _(e){return`{${e.map(e=>Array.isArray(e)?_(e):typeof e==`string`?`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`:`${e}`).join(`,`)}}`}var v=class extends r{foreignKeyConfigs=[];static[e]=`PgColumnBuilder`;array(e){return new ee(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:`always`,mode:`stored`},this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:n,actions:r})=>c((n,r)=>{let i=new a(()=>{let t=n();return{columns:[e],foreignColumns:[t]}});return r.onUpdate&&i.onUpdate(r.onUpdate),r.onDelete&&i.onDelete(r.onDelete),i.build(t)},n,r))}buildExtraConfigColumn(e){return new b(e,this.config)}},y=class extends n{static[e]=`PgColumn`;table;constructor(e,t){t.uniqueName||=u(e,[t.name]),super(e,t),this.table=e}},b=class extends y{static[e]=`ExtraConfigColumn`;getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??`asc`,nulls:this.config.nulls??`last`,opClass:this.config.opClass};defaultConfig={order:`asc`,nulls:`last`,opClass:void 0};asc(){return this.indexConfig.order=`asc`,this}desc(){return this.indexConfig.order=`desc`,this}nullsFirst(){return this.indexConfig.nulls=`first`,this}nullsLast(){return this.indexConfig.nulls=`last`,this}op(e){return this.indexConfig.opClass=e,this}},x=class{static[e]=`IndexedColumn`;constructor(e,t,n,r){this.name=e,this.keyAsName=t,this.type=n,this.indexConfig=r}name;keyAsName;type;indexConfig},ee=class extends v{static[e]=`PgArrayBuilder`;constructor(e,t,n){super(e,`array basecolumn`,`PgArray`),this.config.baseBuilder=t,this.config.length=n}build(e){let t=this.config.baseBuilder.build(e);return new te(e,this.config,t)}},te=class n extends y{constructor(e,t,n,r){super(e,t),this.baseColumn=n,this.range=r}static[e]=`PgArray`;getSQLType(){return`${this.baseColumn.getSQLType()}[${typeof this.length==`number`?this.length:``}]`}mapFromDriverValue(e){return typeof e==`string`&&(e=g(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapFromJsonValue(e){typeof e==`string`&&(e=g(e));let t=this.baseColumn;return`mapFromJsonValue`in t?e.map(e=>t.mapFromJsonValue(e)):e.map(e=>t.mapFromDriverValue(e))}mapToDriverValue(e,r=!1){let i=e.map(e=>e===null?null:t(this.baseColumn,n)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return r?i:_(i)}},ne=class extends v{static[e]=`PgEnumObjectColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumObjectColumn`),this.config.enum=t}build(e){return new re(e,this.config)}},re=class extends y{static[e]=`PgEnumObjectColumn`;enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};const ie=Symbol.for(`drizzle:isPgEnum`);function ae(e){return!!e&&typeof e==`function`&&ie in e&&e[ie]===!0}var oe=class extends v{static[e]=`PgEnumColumnBuilder`;constructor(e,t){super(e,`string enum`,`PgEnumColumn`),this.config.enum=t}build(e){return new se(e,this.config)}},se=class extends y{static[e]=`PgEnumColumn`;enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}};function ce(e,t){return Array.isArray(t)?le(e,[...t],void 0):ue(e,t,void 0)}function le(e,t,n){let r=Object.assign(e=>new oe(e??``,r),{enumName:e,enumValues:t,schema:n,[ie]:!0});return r}function ue(e,t,n){let r=Object.assign(e=>new ne(e??``,r),{enumName:e,enumValues:Object.values(t),schema:n,[ie]:!0});return r}var S=class{static[e]=`Subquery`;constructor(e,t,n,r=!1,i=[]){this._={brand:`Subquery`,sql:e,selectedFields:t,alias:n,isWith:r,usedTables:i}}},de=class extends S{static[e]=`WithSubquery`};const C={startActiveSpan(e,t){return t()}},w=Symbol.for(`drizzle:ViewBaseConfig`),T=Symbol.for(`drizzle:Schema`),E=Symbol.for(`drizzle:Columns`),fe=Symbol.for(`drizzle:ExtraConfigColumns`),pe=Symbol.for(`drizzle:OriginalName`),me=Symbol.for(`drizzle:BaseName`),D=Symbol.for(`drizzle:IsAlias`),he=Symbol.for(`drizzle:ExtraConfigBuilder`),ge=Symbol.for(`drizzle:IsDrizzleTable`);var O=class{static[e]=`Table`;static Symbol={Name:i,Schema:T,OriginalName:pe,Columns:E,ExtraConfigColumns:fe,BaseName:me,IsAlias:D,ExtraConfigBuilder:he};[i];[pe];[T];[E];[fe];[me];[D]=!1;[ge]=!0;[he]=void 0;constructor(e,t,n){this[i]=this[pe]=e,this[T]=t,this[me]=n}getSQL=void 0};function k(e){return e[i]}function _e(e){return`${e[T]??`public`}.${e[i]}`}function ve(e){return e!=null&&typeof e.getSQL==`function`}function ye(e){let t={sql:``,params:[]};for(let n of e)t.sql+=n.sql,t.params.push(...n.params),n.typings?.length&&(t.typings||=[],t.typings.push(...n.typings));return t}var A=class{static[e]=`StringChunk`;value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new j([this])}},j=class r{constructor(e){this.queryChunks=e;for(let n of e)if(t(n,O)){let e=n[O.Symbol.Schema];this.usedTables.push(e===void 0?n[O.Symbol.Name]:e+`.`+n[O.Symbol.Name])}}static[e]=`SQL`;decoder=Se;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return C.startActiveSpan(`drizzle.buildSQL`,t=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let a=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:o,escapeName:s,escapeParam:c,prepareTyping:l,inlineParams:u,paramStartIndex:d}=a;return ye(e.map(e=>{if(t(e,A))return{sql:e.value.join(``),params:[]};if(t(e,be))return{sql:s(e.value),params:[]};if(e===void 0)return{sql:``,params:[]};if(Array.isArray(e)){let t=[new A(`(`)];for(let[n,r]of e.entries())t.push(r),n<e.length-1&&t.push(new A(`, `));return t.push(new A(`)`)),this.buildQueryFromSourceParams(t,a)}if(t(e,r))return this.buildQueryFromSourceParams(e.queryChunks,{...a,inlineParams:u||e.shouldInlineParams});if(t(e,O)){let t=e[O.Symbol.Schema],n=e[O.Symbol.Name];return{sql:t===void 0||e[D]?s(n):s(t)+`.`+s(n),params:[]}}if(t(e,n)){let t=o.getColumnCasing(e);if(i.invokeSource===`indexes`)return{sql:s(t),params:[]};let n=e.table[O.Symbol.Schema];return{sql:e.table[D]||n===void 0?s(e.table[O.Symbol.Name])+`.`+s(t):s(n)+`.`+s(e.table[O.Symbol.Name])+`.`+s(t),params:[]}}if(t(e,P)){let t=e[w].schema,n=e[w].name;return{sql:t===void 0||e[w].isAlias?s(n):s(t)+`.`+s(n),params:[]}}if(t(e,M)){if(t(e.value,we))return{sql:c(d.value++,e),params:[e],typings:[`none`]};let n=e.value===null?null:e.encoder.mapToDriverValue(e.value);if(t(n,r))return this.buildQueryFromSourceParams([n],a);if(u)return{sql:this.mapInlineParam(n,a),params:[]};let i=[`none`];return l&&(i=[l(e.encoder)]),{sql:c(d.value++,n),params:[n],typings:i}}return t(e,we)?{sql:c(d.value++,e),params:[e],typings:[`none`]}:t(e,r.Aliased)&&e.fieldAlias!==void 0?{sql:s(e.fieldAlias),params:[]}:t(e,S)?e._.isWith?{sql:s(e._.alias),params:[]}:this.buildQueryFromSourceParams([new A(`(`),e._.sql,new A(`) `),new be(e._.alias)],a):ae(e)?e.schema?{sql:s(e.schema)+`.`+s(e.enumName),params:[]}:{sql:s(e.enumName),params:[]}:ve(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],a):this.buildQueryFromSourceParams([new A(`(`),e.getSQL(),new A(`)`)],a):u?{sql:this.mapInlineParam(e,a),params:[]}:{sql:c(d.value++,e),params:[e],typings:[`none`]}}))}mapInlineParam(e,{escapeString:t}){if(e===null)return`null`;if(typeof e==`number`||typeof e==`boolean`)return e.toString();if(typeof e==`string`)return t(e);if(typeof e==`object`){let n=e.toString();return t(n===`[object Object]`?JSON.stringify(e):n)}throw Error(`Unexpected param value: `+e)}getSQL(){return this}as(e){return e===void 0?this:new r.Aliased(this,e)}mapWith(e){return this.decoder=typeof e==`function`?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}},be=class{constructor(e){this.value=e}static[e]=`Name`;brand;getSQL(){return new j([this])}};function xe(e){return typeof e==`object`&&!!e&&`mapToDriverValue`in e&&typeof e.mapToDriverValue==`function`}const Se={mapFromDriverValue:e=>e},Ce={mapToDriverValue:e=>e};({...Se,...Ce});var M=class{constructor(e,t=Ce){this.value=e,this.encoder=t}static[e]=`Param`;brand;getSQL(){return new j([this])}};function N(e,...t){let n=[];(t.length>0||e.length>0&&e[0]!==``)&&n.push(new A(e[0]));for(let[r,i]of t.entries())n.push(i,new A(e[r+1]));return new j(n)}(e=>{function t(){return new j([])}e.empty=t;function n(e){return new j(e)}e.fromList=n;function r(e){return new j([new A(e)])}e.raw=r;function i(e,t){let n=[];for(let[r,i]of e.entries())r>0&&t!==void 0&&n.push(t),n.push(i);return new j(n)}e.join=i;function a(e){return new be(e)}e.identifier=a;function o(e){return new we(e)}e.placeholder=o;function s(e,t){return new M(e,t)}e.param=s})(N||={}),(t=>{class n{constructor(e,t){this.sql=e,this.fieldAlias=t}static[e]=`SQL.Aliased`;isSelectionField=!1;getSQL(){return this.sql}clone(){return new n(this.sql,this.fieldAlias)}}t.Aliased=n})(j||={});var we=class{constructor(e){this.name=e}static[e]=`Placeholder`;getSQL(){return new j([this])}};const Te=Symbol.for(`drizzle:IsDrizzleView`);var P=class{static[e]=`View`;[w];[Te]=!0;get[i](){return this[w].name}get[T](){return this[w].schema}get[D](){return this[w].isAlias}get[pe](){return this[w].originalName}get[E](){return this[w].selectedFields}constructor({name:e,schema:t,selectedFields:n,query:r}){this[w]={name:e,originalName:e,schema:t,selectedFields:n,query:r,isExisting:!r,isAlias:!1}}getSQL(){return new j([this])}};n.prototype.getSQL=function(){return new j([this])},O.prototype.getSQL=function(){return new j([this])},S.prototype.getSQL=function(){return new j([this])};var Ee=class{constructor(e){this.table=e}static[e]=`ColumnAliasProxyHandler`;get(e,t){return t===`table`?this.table:e[t]}},De=class{constructor(e,t){this.alias=e,this.replaceOriginalName=t}static[e]=`TableAliasProxyHandler`;get(e,r){if(r===O.Symbol.IsAlias)return!0;if(r===O.Symbol.Name||this.replaceOriginalName&&r===O.Symbol.OriginalName)return this.alias;if(r===w)return{...e[w],name:this.alias,isAlias:!0};if(r===O.Symbol.Columns){let t=e[O.Symbol.Columns];if(!t)return t;let n={};return Object.keys(t).map(r=>{n[r]=new Proxy(t[r],new Ee(new Proxy(e,this)))}),n}let i=e[r];return t(i,n)?new Proxy(i,new Ee(new Proxy(e,this))):i}};function F(e,t){return new Proxy(e,new De(t,!1))}function I(e,t){return new Proxy(e,new Ee(new Proxy(e.table,new De(t,!1))))}function Oe(e,t){return new j.Aliased(ke(e.sql,t),e.fieldAlias)}function ke(e,r){return N.join(e.queryChunks.map(e=>t(e,n)?I(e,r):t(e,j)?ke(e,r):t(e,j.Aliased)?Oe(e,r):e))}var Ae=class extends Error{static[e]=`DrizzleError`;constructor({message:e,cause:t}){super(e),this.name=`DrizzleError`,this.cause=t}};Error;var L=class{static[e]=`QueryPromise`;[Symbol.toStringTag]=`QueryPromise`;catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}then(e,t){return this.execute().then(e,t)}};function R(e,r){return xe(r)&&!ve(e)&&!t(e,M)&&!t(e,we)&&!t(e,n)&&!t(e,O)&&!t(e,P)?new M(e,r):e}const z=(e,t)=>N`${e} = ${R(t,e)}`,je=(e,t)=>N`${e} <> ${R(t,e)}`;function B(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new j(t):new j([new A(`(`),N.join(t,new A(` and `)),new A(`)`)])}function Me(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return t.length===1?new j(t):new j([new A(`(`),N.join(t,new A(` or `)),new A(`)`)])}function Ne(e){return N`not ${e}`}const Pe=(e,t)=>N`${e} > ${R(t,e)}`,Fe=(e,t)=>N`${e} >= ${R(t,e)}`,Ie=(e,t)=>N`${e} < ${R(t,e)}`,Le=(e,t)=>N`${e} <= ${R(t,e)}`;function Re(e,t){return Array.isArray(t)?t.length===0?N`false`:N`${e} in ${t.map(t=>R(t,e))}`:N`${e} in ${R(t,e)}`}function ze(e,t){return Array.isArray(t)?t.length===0?N`true`:N`${e} not in ${t.map(t=>R(t,e))}`:N`${e} not in ${R(t,e)}`}function Be(e){return N`${e} is null`}function Ve(e){return N`${e} is not null`}function He(e){return N`exists ${e}`}function Ue(e){return N`not exists ${e}`}function We(e,t,n){return N`${e} between ${R(t,e)} and ${R(n,e)}`}function Ge(e,t,n){return N`${e} not between ${R(t,e)} and ${R(n,e)}`}function Ke(e,t){return N`${e} like ${t}`}function qe(e,t){return N`${e} not like ${t}`}function Je(e,t){return N`${e} ilike ${t}`}function Ye(e,t){return N`${e} not ilike ${t}`}function Xe(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContains requires at least one value`);return N`${e} @> ${N`${R(t,e)}`}`}return N`${e} @> ${R(t,e)}`}function Ze(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayContained requires at least one value`);return N`${e} <@ ${N`${R(t,e)}`}`}return N`${e} <@ ${R(t,e)}`}function Qe(e,t){if(Array.isArray(t)){if(t.length===0)throw Error(`arrayOverlaps requires at least one value`);return N`${e} && ${N`${R(t,e)}`}`}return N`${e} && ${R(t,e)}`}function $e(e){return N`${e} asc`}function et(e){return N`${e} desc`}function tt(e,n){for(let n of Object.values(e))for(let[e,r]of Object.entries(n.relations))t(r,V)&&(r.sourceTable=n.table,r.fieldName=e);for(let[r,i]of Object.entries(e))for(let[a,o]of Object.entries(i.relations)){if(!t(o,V))continue;let s,{targetTableName:c,alias:l,sourceColumns:u,targetColumns:d,throughTable:f,sourceTable:p,through:m,targetTable:h,where:g,sourceColumnTableNames:_,targetColumnTableNames:v}=o,y=`relations -> ${i.name}: { ${a}: r.${t(o,it)?`one`:`many`}.${c}(...) }`;if(a in i.table[E])throw Error(`${y}: relation name collides with column "${a}" of table "${i.name}"`);if(typeof l==`string`&&!l)throw Error(`${y}: "alias" cannot be an empty string - omit it if you don't need it`);if(u?.length===0)throw Error(`${y}: "from" cannot be empty`);if(d?.length===0)throw Error(`${y}: "to" cannot be empty`);if(u&&d){if(u.length!==d.length&&!f)throw Error(`${y}: "from" and "to" fields without "through" must have the same length`);for(let e of _)if(e!==r)throw Error(`${y}: all "from" columns must belong to table "${r}", found column of table "${e}"`);for(let e of v)if(e!==c)throw Error(`${y}: all "to" columns must belong to table "${h}", found column of table "${e}"`);if(m){if(m.source.length!==u.length||m.target.length!==d.length)throw Error(`${y}: ".through(column)" must be used either on all columns in "from" and "to" or not defined on any of them`);for(let e of m.source)if(n[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`);for(let e of m.target)if(n[e._.tableName]!==f)throw Error(`${y}: ".through(column)" must be used on the same table by all columns of the relation`)}continue}if(u||d)throw Error(`${y}: relation must have either both "from" and "to" defined, or none of them`);let b=e[c];if(!b)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relations of table "${c}" were found"`);if(l){let e=Object.values(b.relations).filter(e=>t(e,V)&&e.alias===l&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations with alias "${l}" found in table "${c}": ${e.map(e=>`"${e.fieldName}"`).join(`, `)}`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and there is no reverse relation of table "${c}" with alias "${l}"`)}else{let e=Object.values(b.relations).filter(e=>t(e,V)&&e.targetTable===p&&!e.alias&&e!==o);if(e.length>1)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and multiple relations between "${c}" and "${r}" were found.
2
+ Hint: you can specify "alias" on both sides of the relation with the same value`);if(s=e[0],!s)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and no reverse relation of table "${c}" with target table "${r}" was found`)}if(!s.sourceColumns||!s.targetColumns)throw Error(`${y}: not enough data provided to build the relation - "from"/"to" are not defined, and reverse relation "${c}.${s.fieldName}" does not have "from"/"to" defined`);o.sourceColumns=s.targetColumns,o.targetColumns=s.sourceColumns,o.through=s.through?{source:s.through.target,target:s.through.source}:void 0,o.throughTable=s.throughTable,o.isReversed=!g,o.where=g??s.where}return e}function nt(e,t){let n={};for(let[r,i]of Object.entries(e))n[r]={table:i,name:r,relations:t[r]??{}};return tt(n,e)}function rt(e,t){let n={};for(let[r,i]of Object.entries(t))!i||!e[r]||(n[r]={table:e[r],name:r,relations:i});return tt(n,e)}var V=class{constructor(e,t){this.targetTableName=t,this.targetTable=e}static[e]=`RelationV2`;fieldName;sourceColumns;targetColumns;alias;where;sourceTable;targetTable;through;throughTable;isReversed;sourceColumnTableNames=[];targetColumnTableNames=[]},it=class extends V{static[e]=`OneV2`;relationType=`one`;optional;constructor(e,t,n,r){super(t,n),this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)}),this.optional=r?.optional??!0}},at=class extends V{constructor(e,t,n,r){super(t,n),this.config=r,this.alias=r?.alias,this.where=r?.where,r?.from&&(this.sourceColumns=(Array.isArray(r.from)?r.from:[r.from]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.sourceColumnTableNames.push(t._.tableName),t._.column))),r?.to&&(this.targetColumns=(Array.isArray(r.to)?r.to:[r.to]).map(t=>(this.throughTable??=t._.through?e[t._.through._.tableName]:void 0,this.targetColumnTableNames.push(t._.tableName),t._.column))),this.throughTable&&(this.through={source:(Array.isArray(r?.from)?r.from:r?.from?[r.from]:[]).map(e=>e._.through),target:(Array.isArray(r?.to)?r.to:r?.to?[r.to]:[]).map(e=>e._.through)})}static[e]=`ManyV2`;relationType=`many`},ot=class{static[e]=`AggregatedField`;table;onTable(e){return this.table=e,this}},st=class extends ot{static[e]=`AggregatedFieldCount`;query;getSQL(){if(!this.query){if(!this.table)throw Error(`Table must be set before building aggregate field`);this.query=N`select count(*) as ${N.identifier(`r`)} from ${W(this.table)}`.mapWith(Number)}return this.query}};const H={and:B,between:We,eq:z,exists:He,gt:Pe,gte:Fe,ilike:Je,inArray:Re,arrayContains:Xe,arrayContained:Ze,arrayOverlaps:Qe,isNull:Be,isNotNull:Ve,like:Ke,lt:Ie,lte:Le,ne:je,not:Ne,notBetween:Ge,notExists:Ue,notLike:qe,notIlike:Ye,notInArray:ze,or:Me,sql:N},ct={sql:N,asc:$e,desc:et};function lt(e,r,i=e=>e,a=!1,o=!1,s){for(let c of r){if(c.selection){let t=`${s?`${s}.`:``}${c.key}`;if(e[c.key]===null)continue;if(a&&(e[c.key]=JSON.parse(e[c.key])),o&&typeof e[c.key]==`string`&&(e[c.key]=JSON.parse(e[c.key])),c.isArray){for(let n of e[c.key])lt(n,c.selection,i,!1,o,t);continue}lt(e[c.key],c.selection,i,!1,o,t);continue}let r=c.field,l=i(e[c.key]);if(l===null)continue;let u;u=t(r,n)?r:t(r,j)?r.decoder:t(r,j.Aliased)?r.sql.decoder:r.getSQL().decoder,e[c.key]=`mapFromJsonValue`in u?u.mapFromJsonValue(l):u.mapFromDriverValue(l)}return e}var ut=class{static[e]=`RelationsBuilderTable`;_;constructor(e,t){this._={name:t,table:e}}},dt=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n){this._={tableName:t,column:e,key:n}}through(e){return new ft(this._.column,this._.tableName,this._.key,e)}},ft=class{static[e]=`RelationsBuilderColumn`;_;constructor(e,t,n,r){this._={tableName:t,column:e,through:r,key:n}}},pt=class{static[e]=`RelationsHelperStatic`;_;constructor(e){this._={tables:e};let t={},n={};for(let[r,i]of Object.entries(e))t[r]=t=>new it(e,i,r,t),n[r]=t=>new at(e,i,r,t);this.one=t,this.many=n}one;many;aggs={count(){return new st}}};function mt(e){let t=new pt(e),n=Object.entries(e).reduce((e,[t,n])=>{let r=new ut(n,t),i=Object.entries(n[E]).reduce((e,[n,r])=>(e[n]=new dt(r,t,n),e),{});return e[t]=Object.assign(r,i),e},{});return Object.assign(t,n)}function ht(e){return Object.fromEntries(Object.entries(e).filter(([e,n])=>t(n,O)||t(n,P)))}function gt(e,t){let n=ht(e);return nt(n,t?t(mt(n)):{})}function _t(e,t){let n=ht(e);return rt(n,t?t(mt(n)):Object.fromEntries(Object.keys(n).map(e=>[e,{}])))}function vt(e,r){let i=e[E][r];return i?t(i,n)?i:t(i,j.Aliased)?N`${e}.${N.identifier(i.fieldAlias)}`:N`${e}.${N.identifier(r)}`:N`${e}.${N.identifier(r)}`}function yt(e,n){if(typeof n!=`object`||t(n,we))return z(e,n);let r=Object.entries(n);if(!r.length)return;let i=[];for(let[t,n]of r)if(n!==void 0)switch(t){case`NOT`:{let t=yt(e,n);if(!t)continue;i.push(Ne(t));continue}case`OR`:if(!n.length)continue;i.push(Me(...n.map(t=>yt(e,t))));continue;case`AND`:if(!n.length)continue;i.push(B(...n.map(t=>yt(e,t))));continue;case`isNotNull`:case`isNull`:if(!n)continue;i.push(H[t](e));continue;case`in`:i.push(H.inArray(e,n));continue;case`notIn`:i.push(H.notInArray(e,n));continue;default:i.push(H[t](e,n));continue}if(i.length)return B(...i)}function U(e,t,n={},r={},i,a=0){let o=Object.entries(t);if(!o.length)return;let s=[];for(let[t,c]of o)if(c!==void 0)switch(t){case`RAW`:{let t=typeof c==`function`?c(e,H):c.getSQL();s.push(t);continue}case`OR`:if(!c?.length)continue;s.push(Me(...c.map(t=>U(e,t,n,r,i,a))));continue;case`AND`:if(!c?.length)continue;s.push(B(...c.map(t=>U(e,t,n,r,i,a))));continue;case`NOT`:{if(c===void 0)continue;let t=U(e,c,n,r,i,a);if(!t)continue;s.push(Ne(t));continue}default:{if(e[E][t]){let n=yt(vt(e,t),c);n&&s.push(n);continue}let o=n[t];if(!o)throw new Ae({message:`Unknown relational filter field: "${t}"`});let l=F(o.targetTable,`f${a}`),u=o.throughTable?F(o.throughTable,`ft${a}`):void 0,d=r[o.targetTableName],{filter:f,joinCondition:p}=St(i,o,e,l,u),m=B(f,typeof c==`boolean`?void 0:U(l,c,d.relations,r,i,a+1)),h=u?N`(select * from ${W(l)} inner join ${W(u)} on ${p}${N` where ${m}`.if(m)} limit 1)`:N`(select * from ${W(l)}${N` where ${m}`.if(m)} limit 1)`;m&&s.push((c?He:Ue)(h))}}return B(...s)}function bt(e,r){if(typeof r==`function`){let i=r(e,ct);return t(i,j)?i:Array.isArray(i)?i.length?N.join(i.map(e=>t(e,j)?e:$e(e)),N`, `):void 0:t(i,n)?$e(i):void 0}let i=Object.entries(r).filter(([e,t])=>t);if(i.length)return N.join(i.map(([t,n])=>(n===`asc`?$e:et)(vt(e,t))),N`, `)}function xt(e,t){let n=[],r=[];for(let[i,a]of Object.entries(t)){if(!a)continue;let t=typeof a==`function`?a(e,{sql:H.sql}):a,o=N`(${t.getSQL()}) as ${N.identifier(i)}`;o.decoder=t.getSQL().decoder,n.push(o),r.push({key:i,field:o})}return{sql:n.length?N.join(n,N`, `):void 0,selection:r}}function St(e,r,i,a,o){if(r.through){let s=r.sourceColumns.map((a,s)=>{let c=r.through.source[s];return z(N`${i}.${N.identifier(e.getColumnCasing(a))}`,N`${o}.${N.identifier(t(c._.column,n)?e.getColumnCasing(c._.column):c._.key)}`)}),c=r.targetColumns.map((i,s)=>{let c=r.through.target[s];return z(N`${o}.${N.identifier(t(c._.column,n)?e.getColumnCasing(c._.column):c._.key)}`,N`${a}.${N.identifier(e.getColumnCasing(i))}`)});return{filter:B(r.where?U(r.isReversed?i:a,r.where):void 0,...s),joinCondition:B(...c)}}return{filter:B(...r.sourceColumns.map((t,n)=>{let o=r.targetColumns[n];return z(N`${i}.${N.identifier(e.getColumnCasing(t))}`,N`${a}.${N.identifier(e.getColumnCasing(o))}`)}),r.where?U(r.isReversed?i:a,r.where):void 0)}}function W(e){return N`${e[D]?N`${N`${N.identifier(e[T]??``)}.`.if(e[T])}${N.identifier(e[pe])} as ${e}`:e}`}function G(e,r){return Object.entries(e).reduce((e,[i,a])=>{if(typeof i!=`string`)return e;let o=r?[...r,i]:[i];return t(a,n)||t(a,j)||t(a,j.Aliased)?e.push({path:o,field:a}):t(a,O)?e.push(...G(a[O.Symbol.Columns],o)):e.push(...G(a,o)),e},[])}function Ct(e,t){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let[e,t]of n.entries())if(t!==r[e])return!1;return!0}function wt(e,r){let i=Object.entries(r).filter(([,e])=>e!==void 0).map(([r,i])=>t(i,j)||t(i,n)?[r,i]:[r,new M(i,e[O.Symbol.Columns][r])]);if(i.length===0)throw Error(`No values to set`);return Object.fromEntries(i)}function Tt(e,t){for(let n of t)for(let t of Object.getOwnPropertyNames(n.prototype))t!==`constructor`&&Object.defineProperty(e.prototype,t,Object.getOwnPropertyDescriptor(n.prototype,t)||Object.create(null))}function Et(e){return e[O.Symbol.Columns]}function K(e){return t(e,S)?e._.alias:t(e,P)?e[w].name:t(e,j)?void 0:e[O.Symbol.IsAlias]?e[O.Symbol.Name]:e[O.Symbol.BaseName]}function q(e,t){return{name:typeof e==`string`&&e.length>0?e:``,config:typeof e==`object`?e:t}}typeof TextDecoder>`u`||new TextDecoder;function Dt(e,t){return new Proxy(e,new De(t,!1))}var Ot=class{constructor(e,t){this.name=e,this.value=t}static[e]=`PgCheckBuilder`;brand;build(e){return new kt(e,this)}},kt=class{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static[e]=`PgCheck`;name;value};function At(e,t){return new Ot(e,t)}var jt=class extends v{static[e]=`PgIntColumnBaseBuilder`;generatedAlwaysAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`always`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`always`};return this.config.hasDefault=!0,this.config.notNull=!0,this}generatedByDefaultAsIdentity(e){if(e){let{name:t,...n}=e;this.config.generatedIdentity={type:`byDefault`,sequenceName:t,sequenceOptions:n}}else this.config.generatedIdentity={type:`byDefault`};return this.config.hasDefault=!0,this.config.notNull=!0,this}},Mt=class extends jt{static[e]=`PgBigInt53Builder`;constructor(e){super(e,`number int53`,`PgBigInt53`)}build(e){return new Nt(e,this.config)}},Nt=class extends y{static[e]=`PgBigInt53`;getSQLType(){return`bigint`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},Pt=class extends jt{static[e]=`PgBigInt64Builder`;constructor(e){super(e,`bigint int64`,`PgBigInt64`)}build(e){return new Ft(e,this.config)}},Ft=class extends y{static[e]=`PgBigInt64`;getSQLType(){return`bigint`}mapFromDriverValue(e){return BigInt(e)}};function It(e,t){let{name:n,config:r}=q(e,t);return r.mode===`number`?new Mt(n):new Pt(n)}var Lt=class extends v{static[e]=`PgBigSerial53Builder`;constructor(e){super(e,`number int53`,`PgBigSerial53`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new Rt(e,this.config)}},Rt=class extends y{static[e]=`PgBigSerial53`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}},zt=class extends v{static[e]=`PgBigSerial64Builder`;constructor(e){super(e,`bigint int64`,`PgBigSerial64`),this.config.hasDefault=!0}build(e){return new Bt(e,this.config)}},Bt=class extends y{static[e]=`PgBigSerial64`;getSQLType(){return`bigserial`}mapFromDriverValue(e){return BigInt(e)}};function Vt(e,t){let{name:n,config:r}=q(e,t);return r.mode===`number`?new Lt(n):new zt(n)}var Ht=class extends v{static[e]=`PgBooleanBuilder`;constructor(e){super(e,`boolean`,`PgBoolean`)}build(e){return new Ut(e,this.config)}},Ut=class extends y{static[e]=`PgBoolean`;getSQLType(){return`boolean`}};function Wt(e){return new Ht(e??``)}var Gt=class extends v{static[e]=`PgByteaBuilder`;constructor(e){super(e,`object buffer`,`PgBytea`)}build(e){return new Kt(e,this.config)}},Kt=class extends y{static[e]=`PgBytea`;mapFromDriverValue(e){if(Buffer.isBuffer(e))return e;if(typeof e==`string`){let t=e.slice(2,e.length);return Buffer.from(t,`hex`)}return Buffer.from(e)}getSQLType(){return`bytea`}};function qt(e){return new Gt(e??``)}var Jt=class extends v{static[e]=`PgCharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgChar`),this.config.length=t.length??1,this.config.setLength=t.length!==void 0,this.config.enumValues=t.enum,this.config.isLengthExact=!0}build(e){return new Yt(e,this.config)}},Yt=class extends y{static[e]=`PgChar`;enumValues=this.config.enumValues;getSQLType(){return this.config.setLength?`char(${this.length})`:`char`}};function Xt(e,t={}){let{name:n,config:r}=q(e,t);return new Jt(n,r)}var Zt=class extends v{static[e]=`PgCidrBuilder`;constructor(e){super(e,`string cidr`,`PgCidr`)}build(e){return new Qt(e,this.config)}},Qt=class extends y{static[e]=`PgCidr`;getSQLType(){return`cidr`}};function $t(e){return new Zt(e??``)}var en=class extends v{static[e]=`PgCustomColumnBuilder`;constructor(e,t,n){super(e,`custom`,`PgCustomColumn`),this.config.fieldConfig=t,this.config.customTypeParams=n}build(e){return new tn(e,this.config)}},tn=class extends y{static[e]=`PgCustomColumn`;sqlName;mapTo;mapFrom;mapJson;forJsonSelect;constructor(e,t){super(e,t),this.sqlName=t.customTypeParams.dataType(t.fieldConfig),this.mapTo=t.customTypeParams.toDriver,this.mapFrom=t.customTypeParams.fromDriver,this.mapJson=t.customTypeParams.fromJson,this.forJsonSelect=t.customTypeParams.forJsonSelect}getSQLType(){return this.sqlName}mapFromDriverValue(e){return typeof this.mapFrom==`function`?this.mapFrom(e):e}mapFromJsonValue(e){return typeof this.mapJson==`function`?this.mapJson(e):this.mapFromDriverValue(e)}jsonSelectIdentifier(e,t,n){if(typeof this.forJsonSelect==`function`)return this.forJsonSelect(e,t,n);let r=this.getSQLType().toLowerCase(),i=r.indexOf(`(`);switch(i+1?r.slice(0,i):r){case`bytea`:case`geometry`:case`timestamp`:case`numeric`:case`bigint`:{let r=`[]`.repeat(n??0);return t`${e}::text${t.raw(r).if(n)}`}default:return e}}mapToDriverValue(e){return typeof this.mapTo==`function`?this.mapTo(e):e}};function nn(e){return(t,n)=>{let{name:r,config:i}=q(t,n);return new en(r,i,e)}}var rn=class extends v{static[e]=`PgDateColumnBaseBuilder`;defaultNow(){return this.default(N`now()`)}},an=class extends rn{static[e]=`PgDateBuilder`;constructor(e){super(e,`object date`,`PgDate`)}build(e){return new on(e,this.config)}},on=class extends y{static[e]=`PgDate`;getSQLType(){return`date`}mapFromDriverValue(e){return new Date(e)}mapToDriverValue(e){return e.toISOString()}},sn=class extends rn{static[e]=`PgDateStringBuilder`;constructor(e){super(e,`string date`,`PgDateString`)}build(e){return new cn(e,this.config)}},cn=class extends y{static[e]=`PgDateString`;getSQLType(){return`date`}};function ln(e,t){let{name:n,config:r}=q(e,t);return r?.mode===`date`?new an(n):new sn(n)}var un=class extends v{static[e]=`PgDoublePrecisionBuilder`;constructor(e){super(e,`number double`,`PgDoublePrecision`)}build(e){return new dn(e,this.config)}},dn=class extends y{static[e]=`PgDoublePrecision`;getSQLType(){return`double precision`}mapFromDriverValue(e){return typeof e==`string`?Number.parseFloat(e):e}};function fn(e){return new un(e??``)}var pn=class extends v{static[e]=`PgInetBuilder`;constructor(e){super(e,`string inet`,`PgInet`)}build(e){return new mn(e,this.config)}},mn=class extends y{static[e]=`PgInet`;getSQLType(){return`inet`}};function hn(e){return new pn(e??``)}var gn=class extends jt{static[e]=`PgIntegerBuilder`;constructor(e){super(e,`number int32`,`PgInteger`)}build(e){return new _n(e,this.config)}},_n=class extends y{static[e]=`PgInteger`;getSQLType(){return`integer`}mapFromDriverValue(e){return typeof e==`string`?Number.parseInt(e):e}};function vn(e){return new gn(e??``)}var yn=class extends v{static[e]=`PgIntervalBuilder`;constructor(e,t){super(e,`string interval`,`PgInterval`),this.config.intervalConfig=t}build(e){return new bn(e,this.config)}},bn=class extends y{static[e]=`PgInterval`;fields=this.config.intervalConfig.fields;precision=this.config.intervalConfig.precision;getSQLType(){return`interval${this.fields?` ${this.fields}`:``}${this.precision?`(${this.precision})`:``}`}};function xn(e,t={}){let{name:n,config:r}=q(e,t);return new yn(n,r)}var Sn=class extends v{static[e]=`PgJsonBuilder`;constructor(e){super(e,`object json`,`PgJson`)}build(e){return new Cn(e,this.config)}},Cn=class extends y{static[e]=`PgJson`;constructor(e,t){super(e,t)}getSQLType(){return`json`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function wn(e){return new Sn(e??``)}var Tn=class extends v{static[e]=`PgJsonbBuilder`;constructor(e){super(e,`object json`,`PgJsonb`)}build(e){return new En(e,this.config)}},En=class extends y{static[e]=`PgJsonb`;constructor(e,t){super(e,t)}getSQLType(){return`jsonb`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e}};function Dn(e){return new Tn(e??``)}var On=class extends v{static[e]=`PgLineBuilder`;constructor(e){super(e,`array line`,`PgLine`)}build(e){return new kn(e,this.config)}},kn=class extends y{static[e]=`PgLine`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n),Number.parseFloat(r)]}mapToDriverValue(e){return`{${e[0]},${e[1]},${e[2]}}`}},An=class extends v{static[e]=`PgLineABCBuilder`;constructor(e){super(e,`object line`,`PgLineABC`)}build(e){return new jn(e,this.config)}},jn=class extends y{static[e]=`PgLineABC`;getSQLType(){return`line`}mapFromDriverValue(e){let[t,n,r]=e.slice(1,-1).split(`,`);return{a:Number.parseFloat(t),b:Number.parseFloat(n),c:Number.parseFloat(r)}}mapToDriverValue(e){return`{${e.a},${e.b},${e.c}}`}};function Mn(e,t){let{name:n,config:r}=q(e,t);return!r?.mode||r.mode===`tuple`?new On(n):new An(n)}var Nn=class extends v{static[e]=`PgMacaddrBuilder`;constructor(e){super(e,`string macaddr`,`PgMacaddr`)}build(e){return new Pn(e,this.config)}},Pn=class extends y{static[e]=`PgMacaddr`;getSQLType(){return`macaddr`}};function Fn(e){return new Nn(e??``)}var In=class extends v{static[e]=`PgMacaddr8Builder`;constructor(e){super(e,`string macaddr8`,`PgMacaddr8`)}build(e){return new Ln(e,this.config)}},Ln=class extends y{static[e]=`PgMacaddr8`;getSQLType(){return`macaddr8`}};function Rn(e){return new In(e??``)}var zn=class extends v{static[e]=`PgNumericBuilder`;constructor(e,t,n){super(e,`string numeric`,`PgNumeric`),this.config.precision=t,this.config.scale=n}build(e){return new Bn(e,this.config)}},Bn=class extends y{static[e]=`PgNumeric`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`string`?e:String(e)}getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Vn=class extends v{static[e]=`PgNumericNumberBuilder`;constructor(e,t,n){super(e,`number`,`PgNumericNumber`),this.config.precision=t,this.config.scale=n}build(e){return new Hn(e,this.config)}},Hn=class extends y{static[e]=`PgNumericNumber`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue(e){return typeof e==`number`?e:Number(e)}mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}},Un=class extends v{static[e]=`PgNumericBigIntBuilder`;constructor(e,t,n){super(e,`bigint int64`,`PgNumericBigInt`),this.config.precision=t,this.config.scale=n}build(e){return new Wn(e,this.config)}},Wn=class extends y{static[e]=`PgNumericBigInt`;precision;scale;constructor(e,t){super(e,t),this.precision=t.precision,this.scale=t.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return this.precision!==void 0&&this.scale!==void 0?`numeric(${this.precision}, ${this.scale})`:this.precision===void 0?`numeric`:`numeric(${this.precision})`}};function Gn(e,t){let{name:n,config:r}=q(e,t),i=r?.mode;return i===`number`?new Vn(n,r?.precision,r?.scale):i===`bigint`?new Un(n,r?.precision,r?.scale):new zn(n,r?.precision,r?.scale)}const Kn=Gn;var qn=class extends v{static[e]=`PgPointTupleBuilder`;constructor(e){super(e,`array point`,`PgPointTuple`)}build(e){return new Jn(e,this.config)}},Jn=class extends y{static[e]=`PgPointTuple`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return[Number.parseFloat(t),Number.parseFloat(n)]}return[e.x,e.y]}mapToDriverValue(e){return`(${e[0]},${e[1]})`}},Yn=class extends v{static[e]=`PgPointObjectBuilder`;constructor(e){super(e,`object point`,`PgPointObject`)}build(e){return new Xn(e,this.config)}},Xn=class extends y{static[e]=`PgPointObject`;getSQLType(){return`point`}mapFromDriverValue(e){if(typeof e==`string`){let[t,n]=e.slice(1,-1).split(`,`);return{x:Number.parseFloat(t),y:Number.parseFloat(n)}}return e}mapToDriverValue(e){return`(${e.x},${e.y})`}};function Zn(e,t){let{name:n,config:r}=q(e,t);return!r?.mode||r.mode===`tuple`?new qn(n):new Yn(n)}function Qn(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(Number.parseInt(e.slice(n,n+2),16));return new Uint8Array(t)}function $n(e,t){let n=new ArrayBuffer(8),r=new DataView(n);for(let n=0;n<8;n++)r.setUint8(n,e[t+n]);return r.getFloat64(0,!0)}function er(e){let t=Qn(e),n=0,r=t[n];n+=1;let i=new DataView(t.buffer),a=i.getUint32(n,r===1);if(n+=4,a&536870912&&(i.getUint32(n,r===1),n+=4),(a&65535)==1){let e=$n(t,n);n+=8;let r=$n(t,n);return n+=8,[e,r]}throw Error(`Unsupported geometry type`)}var tr=class extends v{static[e]=`PgGeometryBuilder`;constructor(e){super(e,`array geometry`,`PgGeometry`)}build(e){return new nr(e,this.config)}},nr=class extends y{static[e]=`PgGeometry`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){return typeof e==`string`?er(e):e}mapToDriverValue(e){return`point(${e[0]} ${e[1]})`}},rr=class extends v{static[e]=`PgGeometryObjectBuilder`;constructor(e){super(e,`object geometry`,`PgGeometryObject`)}build(e){return new ir(e,this.config)}},ir=class extends y{static[e]=`PgGeometryObject`;getSQLType(){return`geometry(point)`}mapFromDriverValue(e){let t=er(e);return{x:t[0],y:t[1]}}mapToDriverValue(e){return`point(${e.x} ${e.y})`}};function ar(e,t){let{name:n,config:r}=q(e,t);return!r?.mode||r.mode===`tuple`?new tr(n):new rr(n)}var or=class extends v{static[e]=`PgRealBuilder`;constructor(e,t){super(e,`number float`,`PgReal`),this.config.length=t}build(e){return new sr(e,this.config)}},sr=class extends y{static[e]=`PgReal`;constructor(e,t){super(e,t)}getSQLType(){return`real`}mapFromDriverValue=e=>typeof e==`string`?Number.parseFloat(e):e};function cr(e){return new or(e??``)}var lr=class extends v{static[e]=`PgSerialBuilder`;constructor(e){super(e,`number int32`,`PgSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new ur(e,this.config)}},ur=class extends y{static[e]=`PgSerial`;getSQLType(){return`serial`}};function dr(e){return new lr(e??``)}var fr=class extends jt{static[e]=`PgSmallIntBuilder`;constructor(e){super(e,`number int16`,`PgSmallInt`)}build(e){return new pr(e,this.config)}},pr=class extends y{static[e]=`PgSmallInt`;getSQLType(){return`smallint`}mapFromDriverValue=e=>typeof e==`string`?Number(e):e};function mr(e){return new fr(e??``)}var hr=class extends v{static[e]=`PgSmallSerialBuilder`;constructor(e){super(e,`number int16`,`PgSmallSerial`),this.config.hasDefault=!0,this.config.notNull=!0}build(e){return new gr(e,this.config)}},gr=class extends y{static[e]=`PgSmallSerial`;getSQLType(){return`smallserial`}};function _r(e){return new hr(e??``)}var vr=class extends v{static[e]=`PgTextBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgText`),this.config.enumValues=t.enum}build(e){return new yr(e,this.config,this.config.enumValues)}},yr=class extends y{static[e]=`PgText`;enumValues;constructor(e,t,n){super(e,t),this.enumValues=n}getSQLType(){return`text`}};function br(e,t={}){let{name:n,config:r}=q(e,t);return new vr(n,r)}var xr=class extends rn{constructor(e,t,n){super(e,`string time`,`PgTime`),this.withTimezone=t,this.precision=n,this.config.withTimezone=t,this.config.precision=n}static[e]=`PgTimeBuilder`;build(e){return new Sr(e,this.config)}},Sr=class extends y{static[e]=`PgTime`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`time${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function Cr(e,t={}){let{name:n,config:r}=q(e,t);return new xr(n,r.withTimezone??!1,r.precision)}var wr=class extends rn{static[e]=`PgTimestampBuilder`;constructor(e,t,n){super(e,`object date`,`PgTimestamp`),this.config.withTimezone=t,this.config.precision=n}build(e){return new Tr(e,this.config)}},Tr=class extends y{static[e]=`PgTimestamp`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:` (${this.precision})`}${this.withTimezone?` with time zone`:``}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+`+0000`);mapToDriverValue=e=>e.toISOString()},Er=class extends rn{static[e]=`PgTimestampStringBuilder`;constructor(e,t,n){super(e,`string timestamp`,`PgTimestampString`),this.config.withTimezone=t,this.config.precision=n}build(e){return new Dr(e,this.config)}},Dr=class extends y{static[e]=`PgTimestampString`;withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){return`timestamp${this.precision===void 0?``:`(${this.precision})`}${this.withTimezone?` with time zone`:``}`}};function Or(e,t={}){let{name:n,config:r}=q(e,t);return r?.mode===`string`?new Er(n,r.withTimezone??!1,r.precision):new wr(n,r?.withTimezone??!1,r?.precision)}var kr=class extends v{static[e]=`PgUUIDBuilder`;constructor(e){super(e,`string uuid`,`PgUUID`)}defaultRandom(){return this.default(N`gen_random_uuid()`)}build(e){return new Ar(e,this.config)}},Ar=class extends y{static[e]=`PgUUID`;getSQLType(){return`uuid`}};function jr(e){return new kr(e??``)}var Mr=class extends v{static[e]=`PgVarcharBuilder`;constructor(e,t){super(e,t.enum?.length?`string enum`:`string`,`PgVarchar`),this.config.length=t.length,this.config.enumValues=t.enum}build(e){return new Nr(e,this.config)}},Nr=class extends y{static[e]=`PgVarchar`;enumValues=this.config.enumValues;getSQLType(){return this.length===void 0?`varchar`:`varchar(${this.length})`}};function Pr(e,t={}){let{name:n,config:r}=q(e,t);return new Mr(n,r)}var Fr=class extends v{static[e]=`PgBinaryVectorBuilder`;constructor(e,t){super(e,`string binary`,`PgBinaryVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new Ir(e,this.config)}},Ir=class extends y{static[e]=`PgBinaryVector`;getSQLType(){return`bit(${this.length})`}};function Lr(e,t){let{name:n,config:r}=q(e,t);return new Fr(n,r)}var Rr=class extends v{static[e]=`PgHalfVectorBuilder`;constructor(e,t){super(e,`array halfvector`,`PgHalfVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new zr(e,this.config)}},zr=class extends y{static[e]=`PgHalfVector`;getSQLType(){return`halfvec(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function Br(e,t){let{name:n,config:r}=q(e,t);return new Rr(n,r)}var Vr=class extends v{static[e]=`PgSparseVectorBuilder`;constructor(e,t){super(e,`string sparsevec`,`PgSparseVector`),this.config.dimensions=t.dimensions}build(e){return new Hr(e,this.config)}},Hr=class extends y{static[e]=`PgSparseVector`;dimensions=this.config.dimensions;getSQLType(){return`sparsevec(${this.dimensions})`}};function Ur(e,t){let{name:n,config:r}=q(e,t);return new Vr(n,r)}var Wr=class extends v{static[e]=`PgVectorBuilder`;constructor(e,t){super(e,`array vector`,`PgVector`),this.config.length=t.dimensions,this.config.isLengthExact=!0}build(e){return new Gr(e,this.config)}},Gr=class extends y{static[e]=`PgVector`;getSQLType(){return`vector(${this.length})`}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){return e.slice(1,-1).split(`,`).map(e=>Number.parseFloat(e))}};function Kr(e,t){let{name:n,config:r}=q(e,t);return new Wr(n,r)}var J=class r{static[e]=`SelectionProxyHandler`;config;constructor(e){this.config={...e}}get(e,i){if(i===`_`)return{...e._,selectedFields:new Proxy(e._.selectedFields,this)};if(i===w)return{...e[w],selectedFields:new Proxy(e[w].selectedFields,this)};if(typeof i==`symbol`)return e[i];let a=(t(e,S)?e._.selectedFields:t(e,P)?e[w].selectedFields:e)[i];if(t(a,j.Aliased)){if(this.config.sqlAliasedBehavior===`sql`&&!a.isSelectionField)return a.sql;let e=a.clone();return e.isSelectionField=!0,e}if(t(a,j)){if(this.config.sqlBehavior===`sql`)return a;throw Error(`You tried to reference "${i}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`)}return t(a,n)?this.config.alias?new Proxy(a,new Ee(new Proxy(a.table,new De(this.config.alias,this.config.replaceOriginalName??!1)))):a:typeof a!=`object`||!a?a:new Proxy(a,new r(this.config))}};function qr(){return{bigint:It,bigserial:Vt,boolean:Wt,char:Xt,cidr:$t,customType:nn,date:ln,doublePrecision:fn,inet:hn,integer:vn,interval:xn,json:wn,jsonb:Dn,line:Mn,macaddr:Fn,macaddr8:Rn,numeric:Gn,point:Zn,geometry:ar,real:cr,serial:dr,smallint:mr,smallserial:_r,text:br,time:Cr,timestamp:Or,uuid:jr,varchar:Pr,bit:Lr,halfvec:Br,sparsevec:Ur,vector:Kr}}const Jr=Symbol.for(`drizzle:PgInlineForeignKeys`),Yr=Symbol.for(`drizzle:EnableRLS`);var Y=class extends O{static[e]=`PgTable`;static Symbol=Object.assign({},O.Symbol,{InlineForeignKeys:Jr,EnableRLS:Yr});[Jr]=[];[Yr]=!1;[O.Symbol.ExtraConfigBuilder]=void 0;[O.Symbol.ExtraConfigColumns]={}};function Xr(e,t,n,r,i=e){let a=new Y(e,r,i),o=typeof t==`function`?t(qr()):t,s=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;n.setName(e);let r=n.build(a);return a[Jr].push(...n.buildForeignKeys(r,a)),[e,r]})),c=Object.fromEntries(Object.entries(o).map(([e,t])=>{let n=t;return n.setName(e),[e,n.buildExtraConfigColumn(a)]})),l=Object.assign(a,s);return l[O.Symbol.Columns]=s,l[O.Symbol.ExtraConfigColumns]=c,n&&(l[Y.Symbol.ExtraConfigBuilder]=n),Object.assign(l,{enableRLS:()=>(l[Y.Symbol.EnableRLS]=!0,l)})}const X=(e,t,n)=>Xr(e,t,n,void 0);function Zr(e){return(t,n,r)=>Xr(e(t),n,r,void 0,t)}var Qr=class{constructor(e,t){this.unique=e,this.name=t}static[e]=`PgIndexBuilderOn`;on(...e){return new $r(e.map(e=>{if(t(e,j))return e;e=e;let n=new x(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),n}),this.unique,!1,this.name)}onOnly(...e){return new $r(e.map(e=>{if(t(e,j))return e;e=e;let n=new x(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=e.defaultConfig,n}),this.unique,!0,this.name)}using(e,...n){return new $r(n.map(e=>{if(t(e,j))return e;e=e;let n=new x(e.name,!!e.keyAsName,e.columnType,e.indexConfig);return e.indexConfig=JSON.parse(JSON.stringify(e.defaultConfig)),n}),this.unique,!0,this.name,e)}},$r=class{static[e]=`PgIndexBuilder`;config;constructor(e,t,n,r,i=`btree`){this.config={name:r,columns:e,unique:t,only:n,method:i}}concurrently(){return this.config.concurrently=!0,this}with(e){return this.config.with=e,this}where(e){return this.config.where=e,this}build(e){return new ei(this.config,e)}},ei=class{static[e]=`PgIndex`;config;constructor(e,t){this.config={...e,table:t}}};function Z(e){return new Qr(!1,e)}function ti(e){return new Qr(!0,e)}var ni=class{constructor(e,t){this.name=e,t&&(this.as=t.as,this.for=t.for,this.to=t.to,this.using=t.using,this.withCheck=t.withCheck)}static[e]=`PgPolicy`;as;for;to;using;withCheck;_linkedTable;link(e){return this._linkedTable=e,this}};function ri(e,t){return new ni(e,t)}function ii(...e){return e[0].columns?new ai(e[0].columns,e[0].name):new ai(e)}var ai=class{static[e]=`PgPrimaryKeyBuilder`;columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new oi(e,this.columns,this.name)}},oi=class{constructor(e,t,n){this.table=e,this.columns=t,this.name=n}static[e]=`PgPrimaryKey`;columns;name;getName(){return this.name??`${this.table[Y.Symbol.Name]}_${this.columns.map(e=>e.name).join(`_`)}_pk`}};const si=Symbol.for(`drizzle:PgViewConfig`);var ci=class{constructor(e,t,n){this.sourceTable=e,this.referencedTable=t,this.relationName=n,this.referencedTableName=t[O.Symbol.Name]}static[e]=`Relation`;referencedTableName;fieldName},li=class t extends ci{constructor(e,t,n,r){super(e,t,n?.relationName),this.config=n,this.isNullable=r}static[e]=`One`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config,this.isNullable);return n.fieldName=e,n}},ui=class t extends ci{constructor(e,t,n){super(e,t,n?.relationName),this.config=n}static[e]=`Many`;withFieldName(e){let n=new t(this.sourceTable,this.referencedTable,this.config);return n.fieldName=e,n}};function di(){return{and:B,between:We,eq:z,exists:He,gt:Pe,gte:Fe,ilike:Je,inArray:Re,isNull:Be,isNotNull:Ve,like:Ke,lt:Ie,lte:Le,ne:je,not:Ne,notBetween:Ge,notExists:Ue,notLike:qe,notIlike:Ye,notInArray:ze,or:Me,sql:N}}function fi(){return{sql:N,asc:$e,desc:et}}function pi(e,n,r){if(t(r,li)&&r.config)return{fields:r.config.fields,references:r.config.references};let i=n[_e(r.referencedTable)];if(!i)throw Error(`Table "${r.referencedTable[O.Symbol.Name]}" not found in schema`);let a=e[i];if(!a)throw Error(`Table "${i}" not found in schema`);let o=r.sourceTable,s=n[_e(o)];if(!s)throw Error(`Table "${o[O.Symbol.Name]}" not found in schema`);let c=[];for(let e of Object.values(a.relations))(r.relationName&&r!==e&&e.relationName===r.relationName||!r.relationName&&e.referencedTable===r.sourceTable)&&c.push(e);if(c.length>1)throw r.relationName?Error(`There are multiple relations with name "${r.relationName}" in table "${i}"`):Error(`There are multiple relations between "${i}" and "${r.sourceTable[O.Symbol.Name]}". Please specify relation name`);if(c[0]&&t(c[0],li)&&c[0].config)return{fields:c[0].config.references,references:c[0].config.fields};throw Error(`There is not enough information to infer relation "${s}.${r.fieldName}"`)}function mi(e,r,i,a,o=e=>e){let s={};for(let[c,l]of a.entries())if(l.isJson){let n=r.relations[l.tsKey],a=i[c],u=typeof a==`string`?JSON.parse(a):a;s[l.tsKey]=t(n,li)?u&&mi(e,e[l.relationTableTsKey],u,l.selection,o):u.map(t=>mi(e,e[l.relationTableTsKey],t,l.selection,o))}else{let e=o(i[c]),r=l.field,a;a=t(r,n)?r:t(r,j)?r.decoder:r.sql.decoder,s[l.tsKey]=e===null?null:a.mapFromDriverValue(e)}return s}function hi(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join(`_`)}function gi(e){return(e.replace(/['\u2019]/g,``).match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,t,n)=>e+(n===0?t.toLowerCase():`${t[0].toUpperCase()}${t.slice(1)}`),``)}function _i(e){return e}var vi=class{static[e]=`CasingCache`;cache={};cachedTables={};convert;constructor(e){this.convert=e===`snake_case`?hi:e===`camelCase`?gi:_i}getColumnCasing(e){if(!e.keyAsName)return e.name;let t=`${e.table[O.Symbol.Schema]??`public`}.${e.table[O.Symbol.OriginalName]}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let r=`${e[O.Symbol.Schema]??`public`}.${e[O.Symbol.OriginalName]}`;if(!this.cachedTables[r]){for(let i of Object.values(e[O.Symbol.Columns])){if(!t(i,n))continue;let e=`${r}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[r]=!0}}clearCache(){this.cache={},this.cachedTables={}}},yi=class extends P{static[e]=`PgViewBase`},bi=class{static[e]=`PgDialect`;casing;constructor(e){this.casing=new vi(e?.casing)}async migrate(e,t,n){let r=typeof n==`string`?`__drizzle_migrations`:n.migrationsTable??`__drizzle_migrations`,i=typeof n==`string`?`drizzle`:n.migrationsSchema??`drizzle`,a=N`
3
+ CREATE TABLE IF NOT EXISTS ${N.identifier(i)}.${N.identifier(r)} (
4
+ id SERIAL PRIMARY KEY,
5
+ hash text NOT NULL,
6
+ created_at bigint
7
+ )
8
+ `;await t.execute(N`CREATE SCHEMA IF NOT EXISTS ${N.identifier(i)}`),await t.execute(a);let o=(await t.all(N`select id, hash, created_at from ${N.identifier(i)}.${N.identifier(r)} order by created_at desc limit 1`))[0];await t.transaction(async t=>{for await(let n of e)if(!o||Number(o.created_at)<n.folderMillis){for(let e of n.sql)await t.execute(N.raw(e));await t.execute(N`insert into ${N.identifier(i)}.${N.identifier(r)} ("hash", "created_at") values(${n.hash}, ${n.folderMillis})`)}})}escapeName(e){return`"${e}"`}escapeParam(e){return`$${e+1}`}escapeString(e){return`'${e.replace(/'/g,`''`)}'`}buildWithCTE(e){if(!e?.length)return;let t=[N`with `];for(let[n,r]of e.entries())t.push(N`${N.identifier(r._.alias)} as (${r._.sql})`),n<e.length-1&&t.push(N`, `);return t.push(N` `),N.join(t)}buildDeleteQuery({table:e,where:t,returning:n,withList:r}){let i=this.buildWithCTE(r),a=n?N` returning ${this.buildSelection(n,{isSingleTable:!0})}`:void 0;return N`${i}delete from ${e}${t?N` where ${t}`:void 0}${a}`}buildUpdateSet(e,t){let n=e[O.Symbol.Columns],r=Object.keys(n).filter(e=>t[e]!==void 0||n[e]?.onUpdateFn!==void 0),i=r.length;return N.join(r.flatMap((e,r)=>{let a=n[e],o=t[e]??N.param(a.onUpdateFn(),a),s=N`${N.identifier(this.casing.getColumnCasing(a))} = ${o}`;return r<i-1?[s,N.raw(`, `)]:[s]}))}buildUpdateQuery({table:e,set:t,where:n,returning:r,withList:i,from:a,joins:o}){let s=this.buildWithCTE(i),c=e[Y.Symbol.Name],l=e[Y.Symbol.Schema],u=e[Y.Symbol.OriginalName],d=c===u?void 0:c,f=N`${l?N`${N.identifier(l)}.`:void 0}${N.identifier(u)}${d&&N` ${N.identifier(d)}`}`,p=this.buildUpdateSet(e,t),m=a&&N.join([N.raw(` from `),this.buildFromTable(a)]),h=this.buildJoins(o),g=r?N` returning ${this.buildSelection(r,{isSingleTable:!a})}`:void 0;return N`${s}update ${f} set ${p}${m}${h}${n?N` where ${n}`:void 0}${g}`}buildSelection(e,{isSingleTable:r=!1}={}){let i=e.length,a=e.flatMap(({field:e},a)=>{let o=[];if(t(e,j.Aliased)&&e.isSelectionField)o.push(N.identifier(e.fieldAlias));else if(t(e,j.Aliased)||t(e,j)){let n=t(e,j.Aliased)?e.sql:e;r?o.push(new j(n.queryChunks.map(e=>t(e,y)?N.identifier(this.casing.getColumnCasing(e)):e))):o.push(n),t(e,j.Aliased)&&o.push(N` as ${N.identifier(e.fieldAlias)}`)}else t(e,n)&&(r?o.push(N.identifier(this.casing.getColumnCasing(e))):o.push(e));return a<i-1&&o.push(N`, `),o});return N.join(a)}buildJoins(e){if(!e||e.length===0)return;let n=[];for(let[r,i]of e.entries()){r===0&&n.push(N` `);let a=i.table,o=i.lateral?N` lateral`:void 0,s=i.on?N` on ${i.on}`:void 0;if(t(a,Y)){let e=a[Y.Symbol.Name],t=a[Y.Symbol.Schema],r=a[Y.Symbol.OriginalName],c=e===r?void 0:i.alias;n.push(N`${N.raw(i.joinType)} join${o} ${t?N`${N.identifier(t)}.`:void 0}${N.identifier(r)}${c&&N` ${N.identifier(c)}`}${s}`)}else if(t(a,P)){let e=a[w].name,t=a[w].schema,r=a[w].originalName,c=e===r?void 0:i.alias;n.push(N`${N.raw(i.joinType)} join${o} ${t?N`${N.identifier(t)}.`:void 0}${N.identifier(r)}${c&&N` ${N.identifier(c)}`}${s}`)}else n.push(N`${N.raw(i.joinType)} join${o} ${a}${s}`);r<e.length-1&&n.push(N` `)}return N.join(n)}buildFromTable(e){if(t(e,O)&&e[O.Symbol.IsAlias]){let t=N`${N.identifier(e[O.Symbol.OriginalName])}`;return e[O.Symbol.Schema]&&(t=N`${N.identifier(e[O.Symbol.Schema])}.${t}`),N`${t} ${N.identifier(e[O.Symbol.Name])}`}return e}buildSelectQuery({withList:e,fields:r,fieldsFlat:i,where:a,having:o,table:s,joins:c,orderBy:l,groupBy:u,limit:d,offset:f,lockingClause:p,distinct:m,setOperators:h}){let g=i??G(r);for(let e of g)if(t(e.field,n)&&k(e.field.table)!==(t(s,S)?s._.alias:t(s,yi)?s[w].name:t(s,j)?void 0:k(s))&&!(e=>c?.some(({alias:t})=>t===(e[O.Symbol.IsAlias]?k(e):e[O.Symbol.BaseName])))(e.field.table)){let t=k(e.field.table);throw Error(`Your "${e.path.join(`->`)}" field references a column "${t}"."${e.field.name}", but the table "${t}" is not part of the query! Did you forget to join it?`)}let _=!c||c.length===0,v=this.buildWithCTE(e),y;m&&(y=m===!0?N` distinct`:N` distinct on (${N.join(m.on,N`, `)})`);let b=this.buildSelection(g,{isSingleTable:_}),x=this.buildFromTable(s),ee=this.buildJoins(c),te=a?N` where ${a}`:void 0,ne=o?N` having ${o}`:void 0,re;l&&l.length>0&&(re=N` order by ${N.join(l,N`, `)}`);let ie;u&&u.length>0&&(ie=N` group by ${N.join(u,N`, `)}`);let ae=typeof d==`object`||typeof d==`number`&&d>=0?N` limit ${d}`:void 0,oe=f?N` offset ${f}`:void 0,se=N.empty();if(p){let e=N` for ${N.raw(p.strength)}`;p.config.of&&e.append(N` of ${N.join(Array.isArray(p.config.of)?p.config.of:[p.config.of],N`, `)}`),p.config.noWait?e.append(N` nowait`):p.config.skipLocked&&e.append(N` skip locked`),se.append(e)}let ce=N`${v}select${y} ${b} from ${x}${ee}${te}${ie}${ne}${re}${ae}${oe}${se}`;return h.length>0?this.buildSetOperations(ce,h):ce}buildSetOperations(e,t){let[n,...r]=t;if(!n)throw Error(`Cannot pass undefined values to any set operator`);return r.length===0?this.buildSetOperationQuery({leftSelect:e,setOperator:n}):this.buildSetOperations(this.buildSetOperationQuery({leftSelect:e,setOperator:n}),r)}buildSetOperationQuery({leftSelect:e,setOperator:{type:n,isAll:r,rightSelect:i,limit:a,orderBy:o,offset:s}}){let c=N`(${e.getSQL()}) `,l=N`(${i.getSQL()})`,u;if(o&&o.length>0){let e=[];for(let n of o)if(t(n,y))e.push(N.identifier(n.name));else if(t(n,j)){for(let e=0;e<n.queryChunks.length;e++){let r=n.queryChunks[e];t(r,y)&&(n.queryChunks[e]=N.identifier(r.name))}e.push(N`${n}`)}else e.push(N`${n}`);u=N` order by ${N.join(e,N`, `)} `}let d=typeof a==`object`||typeof a==`number`&&a>=0?N` limit ${a}`:void 0,f=N.raw(`${n} ${r?`all `:``}`),p=s?N` offset ${s}`:void 0;return N`${c}${f}${l}${u}${d}${p}`}buildInsertQuery({table:e,values:n,onConflict:r,returning:i,withList:a,select:o,overridingSystemValue_:s}){let c=[],l=e[O.Symbol.Columns],u=Object.entries(l).filter(([e,t])=>!t.shouldDisableInsert()),d=u.map(([,e])=>N.identifier(this.casing.getColumnCasing(e)));if(o){let e=n;t(e,j)?c.push(e):c.push(e.getSQL())}else{let e=n;c.push(N.raw(`values `));for(let[n,r]of e.entries()){let i=[];for(let[e,n]of u){let a=r[e];if(a===void 0||t(a,M)&&a.value===void 0)if(n.defaultFn!==void 0){let e=n.defaultFn(),r=t(e,j)?e:N.param(e,n);i.push(r)}else if(!n.default&&n.onUpdateFn!==void 0){let e=n.onUpdateFn(),r=t(e,j)?e:N.param(e,n);i.push(r)}else i.push(N`default`);else i.push(a)}c.push(i),n<e.length-1&&c.push(N`, `)}}let f=this.buildWithCTE(a),p=N.join(c),m=i?N` returning ${this.buildSelection(i,{isSingleTable:!0})}`:void 0,h=r?N` on conflict ${r}`:void 0;return N`${f}insert into ${e} ${d} ${s===!0?N`overriding system value `:void 0}${p}${h}${m}`}buildRefreshMaterializedViewQuery({view:e,concurrently:t,withNoData:n}){return N`refresh materialized view${t?N` concurrently`:void 0} ${e}${n?N` with no data`:void 0}`}prepareTyping(e){return t(e,En)||t(e,Cn)?`json`:t(e,Bn)?`decimal`:t(e,Sr)?`time`:t(e,Tr)||t(e,Dr)?`timestamp`:t(e,on)||t(e,cn)?`date`:t(e,Ar)?`uuid`:`none`}sqlToQuery(e,t){return e.toQuery({casing:this.casing,escapeName:this.escapeName,escapeParam:this.escapeParam,escapeString:this.escapeString,prepareTyping:this.prepareTyping,invokeSource:t})}_buildRelationalQuery({fullSchema:e,schema:r,tableNamesMap:i,table:a,tableConfig:o,queryConfig:s,tableAlias:c,nestedQueryRelation:l,joinOn:u}){let d=[],f,p,m=[],h,g=[];if(s===!0)d=Object.entries(o.columns).map(([e,t])=>({dbKey:t.name,tsKey:e,field:I(t,c),relationTableTsKey:void 0,isJson:!1,selection:[]}));else{let a=Object.fromEntries(Object.entries(o.columns).map(([e,t])=>[e,I(t,c)]));if(s.where){let e=typeof s.where==`function`?s.where(a,di()):s.where;h=e&&ke(e,c)}let l=[],u=[];if(s.columns){let e=!1;for(let[t,n]of Object.entries(s.columns))n!==void 0&&t in o.columns&&(!e&&n===!0&&(e=!0),u.push(t));u.length>0&&(u=e?u.filter(e=>s.columns?.[e]===!0):Object.keys(o.columns).filter(e=>!u.includes(e)))}else u=Object.keys(o.columns);for(let e of u){let t=o.columns[e];l.push({tsKey:e,value:t})}let _=[];s.with&&(_=Object.entries(s.with).filter(e=>!!e[1]).map(([e,t])=>({tsKey:e,queryConfig:t,relation:o.relations[e]})));let v;if(s.extras){v=typeof s.extras==`function`?s.extras(a,{sql:N}):s.extras;for(let[e,t]of Object.entries(v))l.push({tsKey:e,value:Oe(t,c)})}for(let{tsKey:e,value:r}of l)d.push({dbKey:t(r,j.Aliased)?r.fieldAlias:o.columns[e].name,tsKey:e,field:t(r,n)?I(r,c):r,relationTableTsKey:void 0,isJson:!1,selection:[]});let y=typeof s.orderBy==`function`?s.orderBy(a,fi()):s.orderBy??[];Array.isArray(y)||(y=[y]),m=y.map(e=>t(e,n)?I(e,c):ke(e,c)),f=s.limit,p=s.offset;for(let{tsKey:n,queryConfig:a,relation:o}of _){let s=pi(r,i,o),l=i[_e(o.referencedTable)],u=`${c}_${n}`,f=B(...s.fields.map((e,t)=>z(I(s.references[t],u),I(e,c)))),p=this._buildRelationalQuery({fullSchema:e,schema:r,tableNamesMap:i,table:e[l],tableConfig:r[l],queryConfig:t(o,li)?a===!0?{limit:1}:{...a,limit:1}:a,tableAlias:u,joinOn:f,nestedQueryRelation:o}),m=N`${N.identifier(u)}.${N.identifier(`data`)}`.as(n);g.push({on:N`true`,table:new S(p.sql,{},u),alias:u,joinType:`left`,lateral:!0}),d.push({dbKey:n,tsKey:n,field:m,relationTableTsKey:l,isJson:!0,selection:p.selection})}}if(d.length===0)throw new Ae({message:`No fields selected for table "${o.tsName}" ("${c}")`});let _;if(h=B(u,h),l){let e=N`json_build_array(${N.join(d.map(({field:e,tsKey:n,isJson:r})=>r?N`${N.identifier(`${c}_${n}`)}.${N.identifier(`data`)}`:t(e,j.Aliased)?e.sql:e),N`, `)})`;t(l,ui)&&(e=N`coalesce(json_agg(${e}${m.length>0?N` order by ${N.join(m,N`, `)}`:void 0}), '[]'::json)`);let r=[{dbKey:`data`,tsKey:`data`,field:e.as(`data`),isJson:!0,relationTableTsKey:o.tsName,selection:d}];f!==void 0||p!==void 0||m.length>0?(_=this.buildSelectQuery({table:F(a,c),fields:{},fieldsFlat:[{path:[],field:N.raw(`*`)}],where:h,limit:f,offset:p,orderBy:m,setOperators:[]}),h=void 0,f=void 0,p=void 0,m=[]):_=F(a,c),_=this.buildSelectQuery({table:t(_,Y)?_:new S(_,{},c),fields:{},fieldsFlat:r.map(({field:e})=>({path:[],field:t(e,n)?I(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]})}else _=this.buildSelectQuery({table:F(a,c),fields:{},fieldsFlat:d.map(({field:e})=>({path:[],field:t(e,n)?I(e,c):e})),joins:g,where:h,limit:f,offset:p,orderBy:m,setOperators:[]});return{tableTsKey:o.tsName,sql:_,selection:d}}nestedSelectionerror(){throw new Ae({message:`Views with nested selections are not supported by the relational query builder`})}buildRqbColumn(e,r,i){if(t(r,n)){let n=N`${e}.${N.identifier(this.casing.getColumnCasing(r))}`,a=r.columnType,o=r,s=0;for(;t(o,te);)o=o.baseColumn,a=o.columnType,++s;switch(a){case`PgNumeric`:case`PgNumericNumber`:case`PgNumericBigInt`:case`PgBigInt64`:case`PgBigSerial64`:case`PgTimestampString`:case`PgGeometry`:case`PgGeometryObject`:case`PgBytea`:{let e=`[]`.repeat(s);return N`${n}::text${N.raw(e).if(e)} as ${N.identifier(i)}`}case`PgCustomColumn`:return N`${o.jsonSelectIdentifier(n,N,s>0?s:void 0)} as ${N.identifier(i)}`;default:return N`${n} as ${N.identifier(i)}`}}return N`${e}.${t(r,j.Aliased)?N.identifier(r.fieldAlias):ve(r)?N.identifier(i):this.nestedSelectionerror()} as ${N.identifier(i)}`}unwrapAllColumns=(e,t)=>N.join(Object.entries(e[E]).map(([n,r])=>(t.push({key:n,field:r}),this.buildRqbColumn(e,r,n))),N`, `);buildColumns=(e,t,n)=>n?.columns?(()=>{let r=Object.entries(n.columns),i=e[E],a=[],o;for(let[n,s]of r)if(s!==void 0&&(o||=s,s)){let r=i[n];a.push(this.buildRqbColumn(e,r,n)),t.push({key:n,field:r})}if(o===!1)for(let[r,o]of Object.entries(i))n.columns[r]!==!1&&(a.push(this.buildRqbColumn(e,o,r)),t.push({key:r,field:o}));return a.length?N.join(a,N`, `):void 0})():this.unwrapAllColumns(e,t);buildRelationalQuery({schema:e,table:n,tableConfig:r,queryConfig:i,relationWhere:a,mode:o,errorPath:s,depth:c,throughJoin:l}){let u=[],d=o===`first`,f=i===!0?void 0:i,p=s??``,m=c??0;m||(n=F(n,`d${m}`));let h=d?1:f?.limit,g=f?.offset,_=f?.where&&a?B(U(n,f.where,r.relations,e,this.casing),a):f?.where?U(n,f.where,r.relations,e,this.casing):a,v=f?.orderBy?bt(n,f.orderBy):void 0,y=this.buildColumns(n,u,f),b=f?.extras?xt(n,f.extras):void 0;b&&u.push(...b.selection);let x=y?[y]:[],ee=f?(()=>{let{with:i}=f;if(!i)return;let a=Object.entries(i).filter(([e,t])=>t);if(a.length)return N.join(a.map(([i,a])=>{let o=r.relations[i],s=t(o,it),c=F(o.targetTable,`d${m+1}`),l=o.throughTable?F(o.throughTable,`tr${m}`):void 0,{filter:d,joinCondition:f}=St(this.casing,o,n,c,l);x.push(N`${N.identifier(i)}.${N.identifier(`r`)} as ${N.identifier(i)}`);let h=l?N` inner join ${W(l)} on ${f}`:void 0,g=this.buildRelationalQuery({table:c,mode:s?`first`:`many`,schema:e,queryConfig:a,tableConfig:e[o.targetTableName],relationWhere:d,errorPath:`${p.length?`${p}.`:``}${i}`,depth:m+1,throughJoin:h});return u.push({field:c,key:i,selection:g.selection,isArray:!s,isOptional:(o.optional??!1)||a!==!0&&!!a.where}),N`left join lateral(select ${s?N`row_to_json(${N.identifier(`t`)}.*) ${N.identifier(`r`)}`:N`coalesce(json_agg(row_to_json(${N.identifier(`t`)}.*)), '[]') as ${N.identifier(`r`)}`} from (${g.sql}) as ${N.identifier(`t`)}) as ${N.identifier(i)} on true`}),N` `)})():void 0;if(b?.sql&&x.push(b.sql),!x.length)throw new Ae({message:`No fields selected for table "${r.name}"${p?` ("${p}")`:``}`});return{sql:N`select ${N.join(x.filter(e=>e!==void 0),N`, `)} from ${W(n)}${l}${N` ${ee}`.if(ee)}${N` where ${_}`.if(_)}${N` order by ${v}`.if(v)}${N` limit ${h}`.if(h!==void 0)}${N` offset ${g}`.if(g!==void 0)}`,selection:u}}},xi=class{static[e]=`TypedQueryBuilder`;getSelectedFields(){return this._.selectedFields}},Q=class{static[e]=`PgSelectBuilder`;fields;session;dialect;withList=[];distinct;constructor(e){this.fields=e.fields,this.session=e.session,this.dialect=e.dialect,e.withList&&(this.withList=e.withList),this.distinct=e.distinct}authToken;setToken(e){return this.authToken=e,this}from(e){let n=!!this.fields,r=e,i;return i=this.fields?this.fields:t(r,S)?Object.fromEntries(Object.keys(r._.selectedFields).map(e=>[e,r[e]])):t(r,yi)?r[w].selectedFields:t(r,j)?{}:Et(r),new Ci({table:r,fields:i,isPartialSelect:n,session:this.session,dialect:this.dialect,withList:this.withList,distinct:this.distinct}).setToken(this.authToken)}},Si=class extends xi{static[e]=`PgSelectQueryBuilder`;_;config;joinsNotNullableMap;tableName;isPartialSelect;session;dialect;cacheConfig=void 0;usedTables=new Set;constructor({table:e,fields:t,isPartialSelect:n,session:r,dialect:i,withList:a,distinct:o}){super(),this.config={withList:a,table:e,fields:{...t},distinct:o,setOperators:[]},this.isPartialSelect=n,this.session=r,this.dialect=i,this._={selectedFields:t,config:this.config},this.tableName=K(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{};for(let t of $(e))this.usedTables.add(t)}getUsedTables(){return[...this.usedTables]}createJoin(e,n){return(r,i)=>{let a=this.tableName,o=K(r);for(let e of $(r))this.usedTables.add(e);if(typeof o==`string`&&this.config.joins?.some(e=>e.alias===o))throw Error(`Alias "${o}" is already used in this query`);if(!this.isPartialSelect&&(Object.keys(this.joinsNotNullableMap).length===1&&typeof a==`string`&&(this.config.fields={[a]:this.config.fields}),typeof o==`string`&&!t(r,j))){let e=t(r,S)?r._.selectedFields:t(r,P)?r[w].selectedFields:r[O.Symbol.Columns];this.config.fields[o]=e}if(typeof i==`function`&&(i=i(new Proxy(this.config.fields,new J({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.joins||(this.config.joins=[]),this.config.joins.push({on:i,table:r,joinType:e,alias:o,lateral:n}),typeof o==`string`)switch(e){case`left`:this.joinsNotNullableMap[o]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!0;break;case`cross`:case`inner`:this.joinsNotNullableMap[o]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[o]=!1;break}return this}}leftJoin=this.createJoin(`left`,!1);leftJoinLateral=this.createJoin(`left`,!0);rightJoin=this.createJoin(`right`,!1);innerJoin=this.createJoin(`inner`,!1);innerJoinLateral=this.createJoin(`inner`,!0);fullJoin=this.createJoin(`full`,!1);crossJoin=this.createJoin(`cross`,!1);crossJoinLateral=this.createJoin(`cross`,!0);createSetOperator(e,t){return n=>{let r=typeof n==`function`?n(Ti()):n;if(!Ct(this.getSelectedFields(),r.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return this.config.setOperators.push({type:e,isAll:t,rightSelect:r}),this}}union=this.createSetOperator(`union`,!1);unionAll=this.createSetOperator(`union`,!0);intersect=this.createSetOperator(`intersect`,!1);intersectAll=this.createSetOperator(`intersect`,!0);except=this.createSetOperator(`except`,!1);exceptAll=this.createSetOperator(`except`,!0);addSetOperators(e){return this.config.setOperators.push(...e),this}where(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new J({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.where=e,this}having(e){return typeof e==`function`&&(e=e(new Proxy(this.config.fields,new J({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))),this.config.having=e,this}groupBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new J({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`})));this.config.groupBy=Array.isArray(t)?t:[t]}else this.config.groupBy=e;return this}orderBy(...e){if(typeof e[0]==`function`){let t=e[0](new Proxy(this.config.fields,new J({sqlAliasedBehavior:`alias`,sqlBehavior:`sql`}))),n=Array.isArray(t)?t:[t];this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=n:this.config.orderBy=n}else{let t=e;this.config.setOperators.length>0?this.config.setOperators.at(-1).orderBy=t:this.config.orderBy=t}return this}limit(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).limit=e:this.config.limit=e,this}offset(e){return this.config.setOperators.length>0?this.config.setOperators.at(-1).offset=e:this.config.offset=e,this}for(e,t={}){return this.config.lockingClause={strength:e,config:t},this}getSQL(){return this.dialect.buildSelectQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}as(e){let t=[];if(t.push(...$(this.config.table)),this.config.joins)for(let e of this.config.joins)t.push(...$(e.table));return new Proxy(new S(this.getSQL(),this.config.fields,e,!1,[...new Set(t)]),new J({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}getSelectedFields(){return new Proxy(this.config.fields,new J({alias:this.tableName,sqlAliasedBehavior:`alias`,sqlBehavior:`error`}))}$dynamic(){return this}$withCache(e){return this.cacheConfig=e===void 0?{config:{},enable:!0,autoInvalidate:!0}:e===!1?{enable:!1}:{enable:!0,autoInvalidate:!0,...e},this}},Ci=class extends Si{static[e]=`PgSelect`;_prepare(e){let{session:t,config:n,dialect:r,joinsNotNullableMap:i,authToken:a,cacheConfig:o,usedTables:s}=this;if(!t)throw Error(`Cannot execute a query on a query builder. Please use a database instance instead.`);let{fields:c}=n;return C.startActiveSpan(`drizzle.prepareQuery`,()=>{let n=G(c),l=t.prepareQuery(r.sqlToQuery(this.getSQL()),n,e,!0,void 0,{type:`select`,tables:[...s]},o);return l.joinsNotNullableMap=i,l.setToken(a)})}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))};Tt(Ci,[L]);function wi(e,t){return(n,r,...i)=>{let a=[r,...i].map(n=>({type:e,isAll:t,rightSelect:n}));for(let e of a)if(!Ct(n.getSelectedFields(),e.rightSelect.getSelectedFields()))throw Error(`Set operator error (union / intersect / except): selected fields are not the same or are in a different order`);return n.addSetOperators(a)}}const Ti=()=>({union:Ei,unionAll:Di,intersect:Oi,intersectAll:ki,except:Ai,exceptAll:ji}),Ei=wi(`union`,!1),Di=wi(`union`,!0),Oi=wi(`intersect`,!1),ki=wi(`intersect`,!0),Ai=wi(`except`,!1),ji=wi(`except`,!0);var Mi=class{static[e]=`PgQueryBuilder`;dialect;dialectConfig;constructor(e){this.dialect=t(e,bi)?e:void 0,this.dialectConfig=t(e,bi)?void 0:e}$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(n)),new Proxy(new de(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new J({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),withList:e})}function r(e){return new Q({fields:e??void 0,session:void 0,dialect:t.getDialect(),distinct:!0})}function i(e,n){return new Q({fields:n??void 0,session:void 0,dialect:t.getDialect(),distinct:{on:e}})}return{select:n,selectDistinct:r,selectDistinctOn:i}}select(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect()})}selectDistinct(e){return new Q({fields:e??void 0,session:void 0,dialect:this.getDialect(),distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:void 0,dialect:this.getDialect(),distinct:{on:e}})}getDialect(){return this.dialect||=new bi(this.dialectConfig),this.dialect}},Ni=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgDefaultViewBuilderCore`;config={};with(e){return this.config.with=e,this}},Pi=class extends Ni{static[e]=`PgViewBuilder`;as(e){typeof e==`function`&&(e=e(new Mi));let t=new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new zi({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Fi=class extends Ni{static[e]=`PgManualViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Et(X(e,t))}existing(){return new Proxy(new zi({pgConfig:void 0,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new zi({pgConfig:this.config,config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},Ii=class{constructor(e,t){this.name=e,this.schema=t}static[e]=`PgMaterializedViewBuilderCore`;config={};using(e){return this.config.using=e,this}with(e){return this.config.with=e,this}tablespace(e){return this.config.tablespace=e,this}withNoData(){return this.config.withNoData=!0,this}},Li=class extends Ii{static[e]=`PgMaterializedViewBuilder`;as(e){typeof e==`function`&&(e=e(new Mi));let t=new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}),n=new Proxy(e.getSelectedFields(),t);return new Proxy(new Vi({pgConfig:{with:this.config.with,using:this.config.using,tablespace:this.config.tablespace,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:n,query:e.getSQL().inlineParams()}}),t)}},Ri=class extends Ii{static[e]=`PgManualMaterializedViewBuilder`;columns;constructor(e,t,n){super(e,n),this.columns=Et(X(e,t))}existing(){return new Proxy(new Vi({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:void 0}}),new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}as(e){return new Proxy(new Vi({pgConfig:{tablespace:this.config.tablespace,using:this.config.using,with:this.config.with,withNoData:this.config.withNoData},config:{name:this.name,schema:this.schema,selectedFields:this.columns,query:e.inlineParams()}}),new J({alias:this.name,sqlBehavior:`error`,sqlAliasedBehavior:`alias`,replaceOriginalName:!0}))}},zi=class extends yi{static[e]=`PgView`;[si];constructor({pgConfig:e,config:t}){super(t),e&&(this[si]={with:e.with})}};const Bi=Symbol.for(`drizzle:PgMaterializedViewConfig`);var Vi=class extends yi{static[e]=`PgMaterializedView`;[Bi];constructor({pgConfig:e,config:t}){super(t),this[Bi]={with:e?.with,using:e?.using,tablespace:e?.tablespace,withNoData:e?.withNoData}}};function Hi(e,t,n){return t?new Fi(e,t,n):new Pi(e,n)}function Ui(e,t,n){return t?new Ri(e,t,n):new Li(e,n)}function Wi(e,t){return Hi(e,t,void 0)}function Gi(e,t){return Ui(e,t,void 0)}function Ki(e){return t(e,zi)}function qi(e){return t(e,Vi)}function Ji(e){let n=Object.values(e[O.Symbol.Columns]),r=[],i=[],o=[],s=Object.values(e[Y.Symbol.InlineForeignKeys]),c=[],l=e[O.Symbol.Name],u=e[O.Symbol.Schema],f=[],p=e[Y.Symbol.EnableRLS],m=e[Y.Symbol.ExtraConfigBuilder];if(m!==void 0){let n=m(e[O.Symbol.ExtraConfigColumns]),l=Array.isArray(n)?n.flat(1):Object.values(n);for(let n of l)t(n,$r)?r.push(n.build(e)):t(n,Ot)?i.push(n.build(e)):t(n,d)?c.push(n.build(e)):t(n,ai)?o.push(n.build(e)):t(n,a)?s.push(n.build(e)):t(n,ni)&&f.push(n)}return{columns:n,indexes:r,foreignKeys:s,checks:i,primaryKeys:o,uniqueConstraints:c,name:l,schema:u,policies:f,enableRLS:p}}function $(e){return t(e,Y)?[e[T]?`${e[T]}.${e[O.Symbol.BaseName]}`:e[O.Symbol.BaseName]]:t(e,S)?e._.usedTables??[]:t(e,j)?e.usedTables??[]:[]}function Yi(e){return{...e[w],...e[si]}}function Xi(e){return{...e[w],...e[Bi]}}var Zi=class extends L{constructor(e,t,n,r){super(),this.session=t,this.dialect=n,this.config={table:e,withList:r}}static[e]=`PgDelete`;config;cacheConfig;where(e){return this.config.where=e,this}returning(e=this.config.table[O.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=G(e),this}getSQL(){return this.dialect.buildDeleteQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return C.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`delete`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},Qi=class{constructor(e,t,n,r,i){this.table=e,this.session=t,this.dialect=n,this.withList=r,this.overridingSystemValue_=i}static[e]=`PgInsertBuilder`;authToken;setToken(e){return this.authToken=e,this}overridingSystemValue(){return this.overridingSystemValue_=!0,this}values(e){if(e=Array.isArray(e)?e:[e],e.length===0)throw Error(`values() must be called with at least one value`);let n=e.map(e=>{let n={},r=this.table[O.Symbol.Columns];for(let i of Object.keys(e)){let a=e[i];n[i]=t(a,j)?a:new M(a,r[i])}return n});return new $i(this.table,n,this.session,this.dialect,this.withList,!1,this.overridingSystemValue_).setToken(this.authToken)}select(e){let n=typeof e==`function`?e(new Mi):e;if(!t(n,j)&&!Ct(this.table[E],n._.selectedFields))throw Error(`Insert select error: selected fields are not the same or are in a different order compared to the table definition`);return new $i(this.table,n,this.session,this.dialect,this.withList,!0)}},$i=class extends L{constructor(e,t,n,r,i,a,o){super(),this.session=n,this.dialect=r,this.config={table:e,values:t,withList:i,select:a,overridingSystemValue_:o}}static[e]=`PgInsert`;config;cacheConfig;returning(e=this.config.table[O.Symbol.Columns]){return this.config.returningFields=e,this.config.returning=G(e),this}onConflictDoNothing(e={}){if(e.target===void 0)this.config.onConflict=N`do nothing`;else{let t=``;t=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target));let n=e.where?N` where ${e.where}`:void 0;this.config.onConflict=N`(${N.raw(t)})${n} do nothing`}return this}onConflictDoUpdate(e){if(e.where&&(e.targetWhere||e.setWhere))throw Error(`You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.`);let t=e.where?N` where ${e.where}`:void 0,n=e.targetWhere?N` where ${e.targetWhere}`:void 0,r=e.setWhere?N` where ${e.setWhere}`:void 0,i=this.dialect.buildUpdateSet(this.config.table,wt(this.config.table,e.set)),a=``;return a=Array.isArray(e.target)?e.target.map(e=>this.dialect.escapeName(this.dialect.casing.getColumnCasing(e))).join(`,`):this.dialect.escapeName(this.dialect.casing.getColumnCasing(e.target)),this.config.onConflict=N`(${N.raw(a)})${n} do update set ${i}${t}${r}`,this}getSQL(){return this.dialect.buildInsertQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return C.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken));getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},ea=class extends L{constructor(e,t,n){super(),this.session=t,this.dialect=n,this.config={view:e}}static[e]=`PgRefreshMaterializedView`;config;concurrently(){if(this.config.withNoData!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.concurrently=!0,this}withNoData(){if(this.config.concurrently!==void 0)throw Error(`Cannot use concurrently and withNoData together`);return this.config.withNoData=!0,this}getSQL(){return this.dialect.buildRefreshMaterializedViewQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){return C.startActiveSpan(`drizzle.prepareQuery`,()=>this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),void 0,e,!0))}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(e,this.authToken))},ta=class{constructor(e,t,n,r){this.table=e,this.session=t,this.dialect=n,this.withList=r}static[e]=`PgUpdateBuilder`;authToken;setToken(e){return this.authToken=e,this}set(e){return new na(this.table,wt(this.table,e),this.session,this.dialect,this.withList).setToken(this.authToken)}},na=class extends L{constructor(e,t,n,r,i){super(),this.session=n,this.dialect=r,this.config={set:t,table:e,withList:i,joins:[]},this.tableName=K(e),this.joinsNotNullableMap=typeof this.tableName==`string`?{[this.tableName]:!0}:{}}static[e]=`PgUpdate`;config;tableName;joinsNotNullableMap;cacheConfig;from(e){let t=e,n=K(t);return typeof n==`string`&&(this.joinsNotNullableMap[n]=!0),this.config.from=t,this}getTableLikeFields(e){return t(e,Y)?e[O.Symbol.Columns]:t(e,S)?e._.selectedFields:e[w].selectedFields}createJoin(e){return(n,r)=>{let i=K(n);if(typeof i==`string`&&this.config.joins.some(e=>e.alias===i))throw Error(`Alias "${i}" is already used in this query`);if(typeof r==`function`){let e=this.config.from&&!t(this.config.from,j)?this.getTableLikeFields(this.config.from):void 0;r=r(new Proxy(this.config.table[O.Symbol.Columns],new J({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})),e&&new Proxy(e,new J({sqlAliasedBehavior:`sql`,sqlBehavior:`sql`})))}if(this.config.joins.push({on:r,table:n,joinType:e,alias:i}),typeof i==`string`)switch(e){case`left`:this.joinsNotNullableMap[i]=!1;break;case`right`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!0;break;case`inner`:this.joinsNotNullableMap[i]=!0;break;case`full`:this.joinsNotNullableMap=Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([e])=>[e,!1])),this.joinsNotNullableMap[i]=!1;break}return this}}leftJoin=this.createJoin(`left`);rightJoin=this.createJoin(`right`);innerJoin=this.createJoin(`inner`);fullJoin=this.createJoin(`full`);where(e){return this.config.where=e,this}returning(e){if(!e&&(e=Object.assign({},this.config.table[O.Symbol.Columns]),this.config.from)){let n=K(this.config.from);typeof n==`string`&&this.config.from&&!t(this.config.from,j)&&(e[n]=this.getTableLikeFields(this.config.from));for(let n of this.config.joins){let r=K(n.table);typeof r==`string`&&!t(n.table,j)&&(e[r]=this.getTableLikeFields(n.table))}}return this.config.returningFields=e,this.config.returning=G(e),this}getSQL(){return this.dialect.buildUpdateQuery(this.config)}toSQL(){let{typings:e,...t}=this.dialect.sqlToQuery(this.getSQL());return t}_prepare(e){let t=this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()),this.config.returning,e,!0,void 0,{type:`insert`,tables:$(this.config.table)},this.cacheConfig);return t.joinsNotNullableMap=this.joinsNotNullableMap,t}prepare(e){return this._prepare(e)}authToken;setToken(e){return this.authToken=e,this}execute=e=>this._prepare().execute(e,this.authToken);getSelectedFields(){return this.config.returningFields?new Proxy(this.config.returningFields,new J({alias:k(this.config.table),sqlAliasedBehavior:`alias`,sqlBehavior:`error`})):void 0}$dynamic(){return this}},ra=class{constructor(e,t,n,r,i,a,o){this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o}static[e]=`PgRelationalQueryBuilder`;findMany(e){return new ia(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e||{},`many`)}findFirst(e){return new ia(this.fullSchema,this.schema,this.tableNamesMap,this.table,this.tableConfig,this.dialect,this.session,e?{...e,limit:1}:{limit:1},`first`)}},ia=class extends L{constructor(e,t,n,r,i,a,o,s,c){super(),this.fullSchema=e,this.schema=t,this.tableNamesMap=n,this.table=r,this.tableConfig=i,this.dialect=a,this.session=o,this.config=s,this.mode=c}static[e]=`PgRelationalQuery`;_prepare(e){return C.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareQuery(n,void 0,e,!0,(e,n)=>{let r=e.map(e=>mi(this.schema,this.tableConfig,e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect._buildRelationalQuery({fullSchema:this.fullSchema,schema:this.schema,tableNamesMap:this.tableNamesMap,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,tableAlias:this.tableConfig.tsName})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},aa=class t extends j{constructor(e){super(t.buildEmbeddedCount(e.source,e.filters).queryChunks),this.params=e,this.mapWith(Number),this.session=e.session,this.sql=t.buildCount(e.source,e.filters)}sql;token;static[e]=`PgCountBuilder`;[Symbol.toStringTag]=`PgCountBuilder`;session;static buildEmbeddedCount(e,t){return N`(select count(*) from ${e}${N.raw(` where `).if(t)}${t})`}static buildCount(e,t){return N`select count(*) as count from ${e}${N.raw(` where `).if(t)}${t};`}setToken(e){return this.token=e,this}then(e,t){return Promise.resolve(this.session.count(this.sql,this.token)).then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return this.then(t=>(e?.(),t),t=>{throw e?.(),t})}},oa=class{constructor(e,t,n,r,i){this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i}static[e]=`PgRelationalQueryBuilderV2`;findMany(e){return new sa(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`many`)}findFirst(e){return new sa(this.schema,this.table,this.tableConfig,this.dialect,this.session,e??!0,`first`)}},sa=class extends L{constructor(e,t,n,r,i,a,o){super(),this.schema=e,this.table=t,this.tableConfig=n,this.dialect=r,this.session=i,this.config=a,this.mode=o}static[e]=`PgRelationalQueryV2`;_prepare(e){return C.startActiveSpan(`drizzle.prepareQuery`,()=>{let{query:t,builtQuery:n}=this._toSQL();return this.session.prepareRelationalQuery(n,void 0,e,(e,n)=>{let r=e.map(e=>lt(e,t.selection,n));return this.mode===`first`?r[0]:r})})}prepare(e){return this._prepare(e)}_getQuery(){return this.dialect.buildRelationalQuery({schema:this.schema,table:this.table,tableConfig:this.tableConfig,queryConfig:this.config,mode:this.mode})}getSQL(){return this._getQuery().sql}_toSQL(){let e=this._getQuery();return{query:e,builtQuery:this.dialect.sqlToQuery(e.sql)}}toSQL(){return this._toSQL().builtQuery}authToken;setToken(e){return this.authToken=e,this}execute(){return C.startActiveSpan(`drizzle.operation`,()=>this._prepare().execute(void 0,this.authToken))}},ca=class extends L{constructor(e,t,n,r){super(),this.execute=e,this.sql=t,this.query=n,this.mapBatchResult=r}static[e]=`PgRaw`;getSQL(){return this.sql}getQuery(){return this.query}mapResult(e,t){return t?this.mapBatchResult(e):e}_prepare(){return this}isResponseInArrayMode(){return!1}},la=class{constructor(e,t,n,r){if(this.dialect=e,this.session=t,this._=r?{schema:r.schema,fullSchema:r.fullSchema,tableNamesMap:r.tableNamesMap,relations:n,session:t}:{schema:void 0,fullSchema:{},tableNamesMap:{},relations:n,session:t},this._query={},this._.schema)for(let[n,i]of Object.entries(this._.schema))this._query[n]=new ra(r.fullSchema,this._.schema,this._.tableNamesMap,r.fullSchema[n],i,e,t);this.query={};for(let[r,i]of Object.entries(n))this.query[r]=new oa(n,n[i.name].table,i,e,t);this.$cache={invalidate:async e=>{}}}static[e]=`PgDatabase`;_query;query;$with=(e,t)=>{let n=this;return{as:r=>(typeof r==`function`&&(r=r(new Mi(n.dialect))),new Proxy(new de(r.getSQL(),t??(`getSelectedFields`in r?r.getSelectedFields()??{}:{}),e,!0),new J({alias:e,sqlAliasedBehavior:`alias`,sqlBehavior:`error`})))}};$count(e,t){return new aa({source:e,filters:t,session:this.session})}$cache;with(...e){let t=this;function n(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e})}function r(n){return new Q({fields:n??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:!0})}function i(n,r){return new Q({fields:r??void 0,session:t.session,dialect:t.dialect,withList:e,distinct:{on:n}})}function a(n){return new ta(n,t.session,t.dialect,e)}function o(n){return new Qi(n,t.session,t.dialect,e)}function s(n){return new Zi(n,t.session,t.dialect,e)}return{select:n,selectDistinct:r,selectDistinctOn:i,update:a,insert:o,delete:s}}select(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect})}selectDistinct(e){return new Q({fields:e??void 0,session:this.session,dialect:this.dialect,distinct:!0})}selectDistinctOn(e,t){return new Q({fields:t??void 0,session:this.session,dialect:this.dialect,distinct:{on:e}})}update(e){return new ta(e,this.session,this.dialect)}insert(e){return new Qi(e,this.session,this.dialect)}delete(e){return new Zi(e,this.session,this.dialect)}refreshMaterializedView(e){return new ea(e,this.session,this.dialect)}authToken;execute(e){let t=typeof e==`string`?N.raw(e):e.getSQL(),n=this.dialect.sqlToQuery(t),r=this.session.prepareQuery(n,void 0,void 0,!1);return new ca(()=>r.execute(void 0,this.authToken),t,n,e=>r.mapResult(e,!0))}transaction(e,t){return this.session.transaction(e,t)}};const ua=(e,t,n=()=>t[Math.floor(Math.random()*t.length)])=>{let r=(...e)=>n(t).select(...e),i=(...e)=>n(t).selectDistinct(...e),a=(...e)=>n(t).selectDistinctOn(...e),o=(...e)=>n(t).$count(...e),s=(...e)=>n(t).with(...e),c=e=>n(t).$with(e),l=(...t)=>e.update(...t),u=(...t)=>e.insert(...t),d=(...t)=>e.delete(...t),f=(...t)=>e.execute(...t),p=(...t)=>e.transaction(...t),m=(...t)=>e.refreshMaterializedView(...t);return{...e,update:l,insert:u,delete:d,execute:f,transaction:p,refreshMaterializedView:m,$primary:e,select:r,selectDistinct:i,selectDistinctOn:a,$count:o,$with:c,with:s,get _query(){return n(t)._query},get query(){return n(t).query}}};var da=class{constructor(e,t){this.name=e,t&&(this.createDb=t.createDb,this.createRole=t.createRole,this.inherit=t.inherit)}static[e]=`PgRole`;_existing;createDb;createRole;inherit;existing(){return this._existing=!0,this}};function fa(e,t){return new da(e,t)}var pa=class{constructor(e,t,n){this.seqName=e,this.seqOptions=t,this.schema=n}static[e]=`PgSequence`};function ma(e,t){return ha(e,t,void 0)}function ha(e,t,n){return new pa(e,t,n)}function ga(e){return t(e,pa)}var _a=class{constructor(e){this.schemaName=e}static[e]=`PgSchema`;table=(e,t,n)=>Xr(e,t,n,this.schemaName);view=(e,t)=>Hi(e,t,this.schemaName);materializedView=(e,t)=>Ui(e,t,this.schemaName);enum(e,t){return Array.isArray(t)?le(e,[...t],this.schemaName):ue(e,t,this.schemaName)}sequence=(e,t)=>ha(e,t,this.schemaName);getSQL(){return new j([N.identifier(this.schemaName)])}shouldOmitSQLParens(){return!0}};function va(e){return t(e,_a)}function ya(e){if(e===`public`)throw Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`);return new _a(e)}function ba(){let e=X(`accounts`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),accessToken:e.text(`access_token`),accessTokenExpiresAt:e.timestamp(`access_token_expires_at`,{withTimezone:!0}),accountId:e.text(`account_id`).notNull(),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),idToken:e.text(`id_token`),providerId:e.text(`provider_id`).notNull(),password:e.text(`password`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),refreshToken:e.text(`refresh_token`),refreshTokenExpiresAt:e.timestamp(`refresh_token_expires_at`,{withTimezone:!0}),scope:e.text(`scope`),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),t=X(`api_keys`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`),enabled:e.boolean(`enabled`).default(!0),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}),key:e.text(`key`).notNull(),lastRefillAt:e.timestamp(`last_refill_at`,{withTimezone:!0}),lastRequest:e.timestamp(`last_request`,{withTimezone:!0}),lastUsedAt:e.timestamp(`last_used_at`,{withTimezone:!0}),metadata:e.text(`metadata`),permissions:e.text(`permissions`),prefix:e.text(`prefix`),rateLimitEnabled:e.boolean(`rate_limit_enabled`).default(!0),rateLimitTimeWindow:e.integer(`rate_limit_time_window`).default(864e5),rateLimitMax:e.integer(`rate_limit_max`).default(10),refillInterval:e.integer(`refill_interval`),refillAmount:e.integer(`refill_amount`),requestCount:e.integer(`request_count`),remaining:e.integer(`remaining`),start:e.text(`start`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),n=X(`invitations`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),email:e.text(`email`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),inviterId:e.text(`inviter_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`),status:e.text(`status`).default(`pending`).notNull(),teamId:e.text(`team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),r=X(`members`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),role:e.text(`role`).default(`member`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),i=X(`organizations`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`).notNull(),slug:e.text(`slug`).unique(),logo:e.text(`logo`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),metadata:e.text(`metadata`)}),e=>[]),a=X(`sessions`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),activeOrganizationId:e.text(`active_organization_id`).references(()=>i.id,{onDelete:`set null`}),activeTeamId:e.text(`active_team_id`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),impersonatedBy:e.text(`impersonated_by`).references(()=>s.id,{onDelete:`set null`}),ipAddress:e.text(`ip_address`),token:e.text(`token`).notNull().unique(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),userAgent:e.text(`user_agent`),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),o=X(`sso_providers`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),domain:e.text(`domain`).notNull(),issuer:e.text(`issuer`).notNull(),oidcConfig:e.text(`oidc_config`),organizationId:e.text(`organization_id`).references(()=>i.id,{onDelete:`cascade`}),providerId:e.text(`provider_id`).notNull().unique(),samlConfig:e.text(`saml_config`),userId:e.text(`user_id`).references(()=>s.id,{onDelete:`cascade`})}),e=>[]),s=X(`users`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),banExpires:e.timestamp(`ban_expires`,{withTimezone:!0}),banReason:e.text(`ban_reason`),banned:e.boolean(`banned`).default(!1),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),displayUsername:e.text(`display_username`),email:e.text(`email`).notNull().unique(),emailVerified:e.boolean(`email_verified`).default(!1).notNull(),image:e.text(`image`),isAnonymous:e.boolean(`is_anonymous`),lastLoginMethod:e.text(`last_login_method`),name:e.text(`name`).notNull(),phoneNumber:e.text(`phone_number`).unique(),phoneNumberVerified:e.boolean(`phone_number_verified`),role:e.text(`role`),twoFactorEnabled:e.boolean(`two_factor_enabled`).default(!1),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),username:e.text(`username`).unique()}),e=>[]),c=X(`teams`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),name:e.text(`name`).notNull(),organizationId:e.text(`organization_id`).notNull().references(()=>i.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]);return{tables:{accounts:e,apiKeys:t,invitations:n,members:r,organizations:i,sessions:a,ssoProviders:o,teams:c,teamMembers:X(`team_members`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),teamId:e.text(`team_id`).notNull().references(()=>c.id,{onDelete:`cascade`}),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`}),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[]),twoFactors:X(`two_factors`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),secret:e.text(`secret`).notNull(),backupCodes:e.text(`backup_codes`).notNull(),userId:e.text(`user_id`).notNull().references(()=>s.id,{onDelete:`cascade`})}),e=>[]),users:s,verifications:X(`verifications`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),expiresAt:e.timestamp(`expires_at`,{withTimezone:!0}).notNull(),identifier:e.text(`identifier`).notNull(),updatedAt:e.timestamp(`updated_at`,{withTimezone:!0}).default(N`NOW()`).notNull(),value:e.text(`value`).notNull()}),e=>[])},relations:e=>({users:{sessions:e.many.sessions({from:e.users.id,to:e.sessions.userId}),accounts:e.many.accounts({from:e.users.id,to:e.accounts.userId}),apiKeys:e.many.apiKeys({from:e.users.id,to:e.apiKeys.userId}),memberships:e.many.members({from:e.users.id,to:e.members.userId}),invitations:e.many.invitations({from:e.users.id,to:e.invitations.inviterId}),ssoProvider:e.one.ssoProviders({from:e.users.id,to:e.ssoProviders.userId}),twoFactor:e.one.twoFactors({from:e.users.id,to:e.twoFactors.userId})},sessions:{user:e.one.users({from:e.sessions.userId,to:e.users.id})},accounts:{user:e.one.users({from:e.accounts.userId,to:e.users.id})},apiKeys:{user:e.one.users({from:e.apiKeys.userId,to:e.users.id})},organizations:{members:e.many.members({from:e.organizations.id,to:e.members.organizationId}),invitations:e.many.invitations({from:e.organizations.id,to:e.invitations.organizationId}),teams:e.many.teams({from:e.organizations.id,to:e.teams.organizationId})},members:{organization:e.one.organizations({from:e.members.organizationId,to:e.organizations.id}),user:e.one.users({from:e.members.userId,to:e.users.id})},invitations:{organization:e.one.organizations({from:e.invitations.organizationId,to:e.organizations.id}),inviter:e.one.users({from:e.invitations.inviterId,to:e.users.id})},teams:{organization:e.one.organizations({from:e.teams.organizationId,to:e.organizations.id})},ssoProviders:{user:e.one.users({from:e.ssoProviders.userId,to:e.users.id})},verifications:{},twoFactors:{user:e.one.users({from:e.twoFactors.userId,to:e.users.id})}})}}function xa(){let e=X(`storage_blobs`,e=>({id:e.text(`id`).primaryKey().default(N`uuidv7()`),key:e.text(`key`).notNull().unique(),filename:e.text(`filename`).notNull(),contentType:e.text(`content_type`),metadata:e.jsonb(`metadata`),serviceName:e.text(`service_name`).notNull().default(`private`),byteSize:e.bigint(`byte_size`,{mode:`number`}).notNull(),checksum:e.text(`checksum`),createdAt:e.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[Z(`storage_blobs_key_idx`).on(e.key),Z(`storage_blobs_service_name_idx`).on(e.serviceName)]);return{tables:{storageBlobs:e,storageAttachments:X(`storage_attachments`,t=>({id:t.text(`id`).primaryKey().default(N`uuidv7()`),name:t.text(`name`).notNull(),recordType:t.text(`record_type`).notNull(),recordId:t.text(`record_id`).notNull(),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).notNull().default(N`NOW()`)}),e=>[Z(`storage_attachments_record_idx`).on(e.recordType,e.recordId),Z(`storage_attachments_blob_id_idx`).on(e.blobId)]),storageVariantRecords:X(`storage_variant_records`,t=>({id:t.text(`id`).primaryKey().default(N`uuidv7()`),blobId:t.text(`blob_id`).notNull().references(()=>e.id,{onDelete:`cascade`}),variationDigest:t.text(`variation_digest`).notNull(),createdAt:t.timestamp(`created_at`,{withTimezone:!0}).default(N`NOW()`).notNull()}),e=>[Z(`storage_variant_records_blob_id_idx`).on(e.blobId),l(`storage_variant_records_unique`).on(e.blobId,e.variationDigest)])},relations:e=>({storageBlobs:{attachments:e.many.storageAttachments({from:e.storageBlobs.id,to:e.storageAttachments.blobId}),variantRecords:e.many.storageVariantRecords({from:e.storageBlobs.id,to:e.storageVariantRecords.blobId})},storageAttachments:{blob:e.one.storageBlobs({from:e.storageAttachments.blobId,to:e.storageBlobs.id})},storageVariantRecords:{blob:e.one.storageBlobs({from:e.storageVariantRecords.blobId,to:e.storageBlobs.id})}})}}xa();export{kt as Check,Ot as CheckBuilder,o as ForeignKey,a as ForeignKeyBuilder,ei as Index,$r as IndexBuilder,Qr as IndexBuilderOn,x as IndexedColumn,te as PgArray,ee as PgArrayBuilder,Nt as PgBigInt53,Mt as PgBigInt53Builder,Ft as PgBigInt64,Pt as PgBigInt64Builder,Rt as PgBigSerial53,Lt as PgBigSerial53Builder,Bt as PgBigSerial64,zt as PgBigSerial64Builder,Ir as PgBinaryVector,Fr as PgBinaryVectorBuilder,Ut as PgBoolean,Ht as PgBooleanBuilder,Kt as PgBytea,Gt as PgByteaBuilder,Yt as PgChar,Jt as PgCharBuilder,Qt as PgCidr,Zt as PgCidrBuilder,y as PgColumn,v as PgColumnBuilder,tn as PgCustomColumn,en as PgCustomColumnBuilder,la as PgDatabase,on as PgDate,an as PgDateBuilder,cn as PgDateString,sn as PgDateStringBuilder,Zi as PgDeleteBase,bi as PgDialect,nr as PgGeometry,tr as PgGeometryBuilder,ir as PgGeometryObject,rr as PgGeometryObjectBuilder,zr as PgHalfVector,Rr as PgHalfVectorBuilder,Qi as PgInsertBuilder,_n as PgInteger,gn as PgIntegerBuilder,Cn as PgJson,Sn as PgJsonBuilder,En as PgJsonb,Tn as PgJsonbBuilder,jn as PgLineABC,An as PgLineABCBuilder,On as PgLineBuilder,Pn as PgMacaddr,Ln as PgMacaddr8,In as PgMacaddr8Builder,Nn as PgMacaddrBuilder,Bi as PgMaterializedViewConfig,Bn as PgNumeric,Wn as PgNumericBigInt,Un as PgNumericBigIntBuilder,zn as PgNumericBuilder,Hn as PgNumericNumber,Vn as PgNumericNumberBuilder,sr as PgReal,or as PgRealBuilder,Y as PgTable,yr as PgText,vr as PgTextBuilder,oi as PrimaryKey,Mi as QueryBuilder,p as UniqueConstraint,d as UniqueConstraintBuilder,f as UniqueOnConstraintBuilder,Dt as alias,It as bigint,Vt as bigserial,Lr as bit,Wt as boolean,qt as bytea,Xt as char,At as check,$t as cidr,nn as customType,ln as date,Kn as decimal,ba as defineAuthSchema,gt as defineRelations,_t as defineRelationsPart,xa as defineStorageSchema,fn as doublePrecision,Ai as except,ji as exceptAll,$ as extractUsedTable,s as foreignKey,ar as geometry,Xi as getMaterializedViewConfig,Ji as getTableConfig,Yi as getViewConfig,Br as halfvec,Z as index,hn as inet,vn as integer,Oi as intersect,ki as intersectAll,xn as interval,ae as isPgEnum,qi as isPgMaterializedView,va as isPgSchema,ga as isPgSequence,Ki as isPgView,wn as json,Dn as jsonb,Mn as line,Fn as macaddr,Rn as macaddr8,_ as makePgArray,Gn as numeric,g as parsePgArray,h as parsePgNestedArray,ce as pgEnum,Gi as pgMaterializedView,ri as pgPolicy,fa as pgRole,ya as pgSchema,ma as pgSequence,X as pgTable,Zr as pgTableCreator,Wi as pgView,Zn as point,ii as primaryKey,cr as real,dr as serial,mr as smallint,_r as smallserial,Ur as sparsevec,N as sql,br as text,Cr as time,Or as timestamp,Ei as union,Di as unionAll,l as unique,ti as uniqueIndex,u as uniqueKeyName,jr as uuid,ua as withReplicas};
@@ -0,0 +1 @@
1
+ import{i as e,n as t,r as n,t as r,u as i}from"./esm-FzcFIiBQ.mjs";function a(i){if(!i)return null;if(`dialect`in i)return a(i.dialect);if(`createDriver`in i){if(i instanceof e)return`sqlite`;if(i instanceof n)return`mysql`;if(i instanceof t)return`postgres`;if(i instanceof r)return`mssql`}return`aggregate`in i?`sqlite`:`getConnection`in i?`mysql`:`connect`in i?`postgres`:`fileControl`in i||`open`in i&&`close`in i&&`prepare`in i?`sqlite`:null}const o=async r=>{let o=r.database;if(!o)return{kysely:null,databaseType:null,transaction:void 0};if(`db`in o)return{kysely:o.db,databaseType:o.type,transaction:o.transaction};if(`dialect`in o)return{kysely:new i({dialect:o.dialect}),databaseType:o.type,transaction:o.transaction};let s,c=a(o);if(`createDriver`in o&&(s=o),`aggregate`in o&&!(`createSession`in o)&&(s=new e({database:o})),`getConnection`in o&&(s=new n(o)),`connect`in o&&(s=new t({pool:o})),`fileControl`in o){let{BunSqliteDialect:e}=await import(`./bun-sqlite-dialect-DN7EKoIB-B0dpsiEy.mjs`);s=new e({database:o})}if(`createSession`in o&&typeof window>`u`){let e;try{({DatabaseSync:e}=await import(`node:sqlite`))}catch(e){if(typeof e==`object`&&e&&`code`in e&&e.code!==`ERR_UNKNOWN_BUILTIN_MODULE`)throw e}if(e&&o instanceof e){let{NodeSqliteDialect:e}=await import(`./node-sqlite-dialect-BqISUSC3-DSS_lf2e.mjs`);s=new e({database:o})}}return{kysely:s?new i({dialect:s}):null,databaseType:c,transaction:void 0}};export{a as n,o as t};
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./chunk-DQj_Q5LL.mjs";var n=t((e=>{e.isArrayBuffer=e=>typeof ArrayBuffer==`function`&&e instanceof ArrayBuffer||Object.prototype.toString.call(e)===`[object ArrayBuffer]`})),r=t((t=>{var r=n(),i=e(`buffer`);t.fromArrayBuffer=(e,t=0,n=e.byteLength-t)=>{if(!r.isArrayBuffer(e))throw TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof e} (${e})`);return i.Buffer.from(e,t,n)},t.fromString=(e,t)=>{if(typeof e!=`string`)throw TypeError(`The "input" argument must be of type string. Received type ${typeof e} (${e})`);return t?i.Buffer.from(e,t):i.Buffer.from(e)}})),i=t((e=>{var t=r();let n=e=>{let n=t.fromString(e,`utf8`);return new Uint8Array(n.buffer,n.byteOffset,n.byteLength/Uint8Array.BYTES_PER_ELEMENT)};e.fromUtf8=n,e.toUint8Array=e=>typeof e==`string`?n(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(e),e.toUtf8=e=>{if(typeof e==`string`)return e;if(typeof e!=`object`||typeof e.byteOffset!=`number`||typeof e.byteLength!=`number`)throw Error(`@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.`);return t.fromArrayBuffer(e.buffer,e.byteOffset,e.byteLength).toString(`utf8`)}}));export{r as n,n as r,i as t};
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./chunk-DQj_Q5LL.mjs";import{t as n}from"./dist-cjs-D9iFq61w.mjs";var r=t((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.getHomeDir=void 0;let n=e(`os`),r=e(`path`),i={},a=()=>process&&process.geteuid?`${process.geteuid()}`:`DEFAULT`;t.getHomeDir=()=>{let{HOME:e,USERPROFILE:t,HOMEPATH:o,HOMEDRIVE:s=`C:${r.sep}`}=process.env;if(e)return e;if(t)return t;if(o)return`${s}${o}`;let c=a();return i[c]||(i[c]=(0,n.homedir)()),i[c]}})),i=t((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.getSSOTokenFilepath=void 0;let n=e(`crypto`),i=e(`path`),a=r();t.getSSOTokenFilepath=e=>{let t=(0,n.createHash)(`sha1`).update(e).digest(`hex`);return(0,i.join)((0,a.getHomeDir)(),`.aws`,`sso`,`cache`,`${t}.json`)}})),a=t((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.getSSOTokenFromFile=t.tokenIntercept=void 0;let n=e(`fs`),r=i(),{readFile:a}=n.promises;t.tokenIntercept={},t.getSSOTokenFromFile=async e=>{if(t.tokenIntercept[e])return t.tokenIntercept[e];let n=await a((0,r.getSSOTokenFilepath)(e),`utf8`);return JSON.parse(n)}})),o=t((t=>{Object.defineProperty(t,`__esModule`,{value:!0}),t.slurpFile=t.fileIntercept=t.filePromisesHash=void 0;let{readFile:n}=e(`fs`).promises;t.filePromisesHash={},t.fileIntercept={},t.slurpFile=(e,r)=>t.fileIntercept[e]===void 0?((!t.filePromisesHash[e]||r?.ignoreCache)&&(t.filePromisesHash[e]=n(e,`utf8`)),t.filePromisesHash[e]):t.fileIntercept[e]})),s=t((t=>{var s=r(),c=i(),l=a(),u=e(`path`),d=n(),f=o();let p=`AWS_PROFILE`,m=`default`,h=e=>e.profile||process.env[p]||m,g=e=>Object.entries(e).filter(([e])=>{let t=e.indexOf(`.`);return t===-1?!1:Object.values(d.IniSectionType).includes(e.substring(0,t))}).reduce((e,[t,n])=>{let r=t.indexOf(`.`),i=t.substring(0,r)===d.IniSectionType.PROFILE?t.substring(r+1):t;return e[i]=n,e},{...e.default&&{default:e.default}}),_=()=>process.env.AWS_CONFIG_FILE||u.join(s.getHomeDir(),`.aws`,`config`),v=()=>process.env.AWS_SHARED_CREDENTIALS_FILE||u.join(s.getHomeDir(),`.aws`,`credentials`),y=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,b=[`__proto__`,`profile __proto__`],x=e=>{let t={},n,r;for(let i of e.split(/\r?\n/)){let e=i.split(/(^|\s)[;#]/)[0].trim();if(e[0]===`[`&&e[e.length-1]===`]`){n=void 0,r=void 0;let t=e.substring(1,e.length-1),i=y.exec(t);if(i){let[,e,,t]=i;Object.values(d.IniSectionType).includes(e)&&(n=[e,t].join(`.`))}else n=t;if(b.includes(t))throw Error(`Found invalid profile name "${t}"`)}else if(n){let a=e.indexOf(`=`);if(![0,-1].includes(a)){let[o,s]=[e.substring(0,a).trim(),e.substring(a+1).trim()];if(s===``)r=o;else{r&&i.trimStart()===i&&(r=void 0),t[n]=t[n]||{};let e=r?[r,o].join(`.`):o;t[n][e]=s}}}}return t},S=()=>({}),C=async(e={})=>{let{filepath:t=v(),configFilepath:n=_()}=e,r=s.getHomeDir(),i=t;t.startsWith(`~/`)&&(i=u.join(r,t.slice(2)));let a=n;n.startsWith(`~/`)&&(a=u.join(r,n.slice(2)));let o=await Promise.all([f.slurpFile(a,{ignoreCache:e.ignoreCache}).then(x).then(g).catch(S),f.slurpFile(i,{ignoreCache:e.ignoreCache}).then(x).catch(S)]);return{configFile:o[0],credentialsFile:o[1]}},w=e=>Object.entries(e).filter(([e])=>e.startsWith(d.IniSectionType.SSO_SESSION+`.`)).reduce((e,[t,n])=>({...e,[t.substring(t.indexOf(`.`)+1)]:n}),{}),T=()=>({}),E=async(e={})=>f.slurpFile(e.configFilepath??_()).then(x).then(w).catch(T),D=(...e)=>{let t={};for(let n of e)for(let[e,r]of Object.entries(n))t[e]===void 0?t[e]=r:Object.assign(t[e],r);return t};Object.defineProperty(t,`getSSOTokenFromFile`,{enumerable:!0,get:function(){return l.getSSOTokenFromFile}}),t.CONFIG_PREFIX_SEPARATOR=`.`,t.DEFAULT_PROFILE=m,t.ENV_PROFILE=p,t.externalDataInterceptor={getFileRecord(){return f.fileIntercept},interceptFile(e,t){f.fileIntercept[e]=Promise.resolve(t)},getTokenRecord(){return l.tokenIntercept},interceptToken(e,t){l.tokenIntercept[e]=t}},t.getProfileName=h,t.loadSharedConfigFiles=C,t.loadSsoSessionData=E,t.parseKnownFiles=async e=>{let t=await C(e);return D(t.configFile,t.credentialsFile)},Object.keys(s).forEach(function(e){e!==`default`&&!Object.prototype.hasOwnProperty.call(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}})}),Object.keys(c).forEach(function(e){e!==`default`&&!Object.prototype.hasOwnProperty.call(t,e)&&Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}})})}));export{s as t};
@@ -0,0 +1 @@
1
+ import"./dist-cjs-DO06FS0-.mjs";import"./client-Cf0k1wnb.mjs";import{t as e}from"./dist-cjs-DpVGmjIF.mjs";export default e();export{};
@@ -0,0 +1 @@
1
+ import{a as e,o as t,t as n}from"./chunk-DQj_Q5LL.mjs";import{t as r}from"./dist-cjs-DO06FS0-.mjs";import{t as i}from"./dist-cjs-8ShtoC4L.mjs";import"./dist-cjs-D9iFq61w.mjs";import{n as a,t as o}from"./client-Cf0k1wnb.mjs";var s=n((n=>{var s=i(),c=r(),l=e(`child_process`),u=e(`util`),d=(a(),t(o));let f=(e,t,n)=>{if(t.Version!==1)throw Error(`Profile ${e} credential_process did not return Version 1.`);if(t.AccessKeyId===void 0||t.SecretAccessKey===void 0)throw Error(`Profile ${e} credential_process returned invalid credentials.`);if(t.Expiration){let n=new Date;if(new Date(t.Expiration)<n)throw Error(`Profile ${e} credential_process returned expired credentials.`)}let r=t.AccountId;!r&&n?.[e]?.aws_account_id&&(r=n[e].aws_account_id);let i={accessKeyId:t.AccessKeyId,secretAccessKey:t.SecretAccessKey,...t.SessionToken&&{sessionToken:t.SessionToken},...t.Expiration&&{expiration:new Date(t.Expiration)},...t.CredentialScope&&{credentialScope:t.CredentialScope},...r&&{accountId:r}};return d.setCredentialFeature(i,`CREDENTIALS_PROCESS`,`w`),i},p=async(e,t,n)=>{let r=t[e];if(t[e]){let i=r.credential_process;if(i!==void 0){let r=u.promisify(s.externalDataInterceptor?.getTokenRecord?.().exec??l.exec);try{let{stdout:n}=await r(i),a;try{a=JSON.parse(n.trim())}catch{throw Error(`Profile ${e} credential_process returned invalid JSON.`)}return f(e,a,t)}catch(e){throw new c.CredentialsProviderError(e.message,{logger:n})}}else throw new c.CredentialsProviderError(`Profile ${e} did not contain credential_process.`,{logger:n})}else throw new c.CredentialsProviderError(`Profile ${e} could not be found in shared credentials file.`,{logger:n})};n.fromProcess=(e={})=>async({callerClientConfig:t}={})=>{e.logger?.debug(`@aws-sdk/credential-provider-process - fromProcess`);let n=await s.parseKnownFiles(e);return p(s.getProfileName({profile:e.profile??t?.profile}),n,e.logger)}}));export default s();export{};
@@ -0,0 +1 @@
1
+ import{a as e,t}from"./chunk-DQj_Q5LL.mjs";import{t as n}from"./dist-cjs-DO06FS0-.mjs";import"./dist-cjs-8ShtoC4L.mjs";import"./dist-cjs-D9iFq61w.mjs";import{n as r,t as i}from"./dist-cjs-CkmP5Wcr.mjs";var a=t((t=>{var a=n(),o=e(`url`),s=e(`buffer`),c=e(`http`),l=r(),u=i();function d(e){return new Promise((t,n)=>{let r=c.request({method:`GET`,...e,hostname:e.hostname?.replace(/^\[(.+)\]$/,`$1`)});r.on(`error`,e=>{n(Object.assign(new a.ProviderError(`Unable to connect to instance metadata service`),e)),r.destroy()}),r.on(`timeout`,()=>{n(new a.ProviderError(`TimeoutError from instance metadata service`)),r.destroy()}),r.on(`response`,e=>{let{statusCode:i=400}=e;(i<200||300<=i)&&(n(Object.assign(new a.ProviderError(`Error response received from instance metadata service`),{statusCode:i})),r.destroy());let o=[];e.on(`data`,e=>{o.push(e)}),e.on(`end`,()=>{t(s.Buffer.concat(o)),r.destroy()})}),r.end()})}let f=e=>!!e&&typeof e==`object`&&typeof e.AccessKeyId==`string`&&typeof e.SecretAccessKey==`string`&&typeof e.Token==`string`&&typeof e.Expiration==`string`,p=e=>({accessKeyId:e.AccessKeyId,secretAccessKey:e.SecretAccessKey,sessionToken:e.Token,expiration:new Date(e.Expiration),...e.AccountId&&{accountId:e.AccountId}}),m=1e3,h=({maxRetries:e=0,timeout:t=m})=>({maxRetries:e,timeout:t}),g=(e,t)=>{let n=e();for(let r=0;r<t;r++)n=n.catch(e);return n},_=`AWS_CONTAINER_CREDENTIALS_FULL_URI`,v=`AWS_CONTAINER_CREDENTIALS_RELATIVE_URI`,y=`AWS_CONTAINER_AUTHORIZATION_TOKEN`,b=(e={})=>{let{timeout:t,maxRetries:n}=h(e);return()=>g(async()=>{let n=await w({logger:e.logger}),r=JSON.parse(await x(t,n));if(!f(r))throw new a.CredentialsProviderError(`Invalid response received from instance metadata service.`,{logger:e.logger});return p(r)},n)},x=async(e,t)=>(process.env[y]&&(t.headers={...t.headers,Authorization:process.env[y]}),(await d({...t,timeout:e})).toString()),S={localhost:!0,"127.0.0.1":!0},C={"http:":!0,"https:":!0},w=async({logger:e})=>{if(process.env[v])return{hostname:`169.254.170.2`,path:process.env[v]};if(process.env[_]){let t=o.parse(process.env[_]);if(!t.hostname||!(t.hostname in S))throw new a.CredentialsProviderError(`${t.hostname} is not a valid container metadata service hostname`,{tryNextLink:!1,logger:e});if(!t.protocol||!(t.protocol in C))throw new a.CredentialsProviderError(`${t.protocol} is not a valid container metadata service protocol`,{tryNextLink:!1,logger:e});return{...t,port:t.port?parseInt(t.port,10):void 0}}throw new a.CredentialsProviderError(`The container metadata credential provider cannot be used unless the ${v} or ${_} environment variable is set`,{tryNextLink:!1,logger:e})};var T=class e extends a.CredentialsProviderError{tryNextLink;name=`InstanceMetadataV1FallbackError`;constructor(t,n=!0){super(t,n),this.tryNextLink=n,Object.setPrototypeOf(this,e.prototype)}};t.Endpoint=void 0,(function(e){e.IPv4=`http://169.254.169.254`,e.IPv6=`http://[fd00:ec2::254]`})(t.Endpoint||={});let E={environmentVariableSelector:e=>e.AWS_EC2_METADATA_SERVICE_ENDPOINT,configFileSelector:e=>e.ec2_metadata_service_endpoint,default:void 0};var D;(function(e){e.IPv4=`IPv4`,e.IPv6=`IPv6`})(D||={});let O={environmentVariableSelector:e=>e.AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE,configFileSelector:e=>e.ec2_metadata_service_endpoint_mode,default:D.IPv4},k=async()=>u.parseUrl(await A()||await j()),A=async()=>l.loadConfig(E)(),j=async()=>{let e=await l.loadConfig(O)();switch(e){case D.IPv4:return t.Endpoint.IPv4;case D.IPv6:return t.Endpoint.IPv6;default:throw Error(`Unsupported endpoint mode: ${e}. Select from ${Object.values(D)}`)}},M=(e,t)=>{let n=300+Math.floor(Math.random()*300),r=new Date(Date.now()+n*1e3);t.warn(`Attempting credential expiration extension due to a credential service availability issue. A refresh of these credentials will be attempted after ${new Date(r)}.\nFor more information, please visit: https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html`);let i=e.originalExpiration??e.expiration;return{...e,...i?{originalExpiration:i}:{},expiration:r}},N=(e,t={})=>{let n=t?.logger||console,r;return async()=>{let t;try{t=await e(),t.expiration&&t.expiration.getTime()<Date.now()&&(t=M(t,n))}catch(e){if(r)n.warn(`Credential renew failed: `,e),t=M(r,n);else throw e}return r=t,t}},P=`/latest/meta-data/iam/security-credentials/`,F=`AWS_EC2_METADATA_V1_DISABLED`,I=`ec2_metadata_v1_disabled`,L=`x-aws-ec2-metadata-token`,R=(e={})=>N(z(e),{logger:e.logger}),z=(e={})=>{let t=!1,{logger:n,profile:r}=e,{timeout:i,maxRetries:o}=h(e),s=async(n,i)=>{if(t||i.headers?.[L]==null){let t=!1,n=!1,i=await l.loadConfig({environmentVariableSelector:t=>{let r=t[F];if(n=!!r&&r!==`false`,r===void 0)throw new a.CredentialsProviderError(`${F} not set in env, checking config file next.`,{logger:e.logger});return n},configFileSelector:e=>{let n=e[I];return t=!!n&&n!==`false`,t},default:!1},{profile:r})();if(e.ec2MetadataV1Disabled||i){let r=[];throw e.ec2MetadataV1Disabled&&r.push(`credential provider initialization (runtime option ec2MetadataV1Disabled)`),t&&r.push(`config file profile (${I})`),n&&r.push(`process environment variable (${F})`),new T(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${r.join(`, `)}].`)}}let o=(await g(async()=>{let e;try{e=await V(i)}catch(e){throw e.statusCode===401&&(t=!1),e}return e},n)).trim();return g(async()=>{let n;try{n=await H(o,i,e)}catch(e){throw e.statusCode===401&&(t=!1),e}return n},n)};return async()=>{let e=await k();if(t)return n?.debug(`AWS SDK Instance Metadata`,`using v1 fallback (no token fetch)`),s(o,{...e,timeout:i});{let r;try{r=(await B({...e,timeout:i})).toString()}catch(r){if(r?.statusCode===400)throw Object.assign(r,{message:`EC2 Metadata token request returned error`});return(r.message===`TimeoutError`||[403,404,405].includes(r.statusCode))&&(t=!0),n?.debug(`AWS SDK Instance Metadata`,`using v1 fallback (initial)`),s(o,{...e,timeout:i})}return s(o,{...e,headers:{[L]:r},timeout:i})}}},B=async e=>d({...e,path:`/latest/api/token`,method:`PUT`,headers:{"x-aws-ec2-metadata-token-ttl-seconds":`21600`}}),V=async e=>(await d({...e,path:P})).toString(),H=async(e,t,n)=>{let r=JSON.parse((await d({...t,path:P+e})).toString());if(!f(r))throw new a.CredentialsProviderError(`Invalid response received from instance metadata service.`,{logger:n.logger});return p(r)};t.DEFAULT_MAX_RETRIES=0,t.DEFAULT_TIMEOUT=m,t.ENV_CMDS_AUTH_TOKEN=y,t.ENV_CMDS_FULL_URI=_,t.ENV_CMDS_RELATIVE_URI=v,t.fromContainerMetadata=b,t.fromInstanceMetadata=R,t.getInstanceMetadataEndpoint=k,t.httpRequest=d,t.providerConfigFromInit=h}));export default a();export{};
@@ -0,0 +1 @@
1
+ import{o as e,s as t,t as n}from"./chunk-DQj_Q5LL.mjs";import{t as r}from"./dist-cjs-DO06FS0-.mjs";import{t as i}from"./dist-cjs-8ShtoC4L.mjs";import"./dist-cjs-D9iFq61w.mjs";import{n as a,t as o}from"./client-Cf0k1wnb.mjs";var s=n((n=>{var s=i(),c=r(),l=(a(),e(o));let u=(e,n,r)=>{let i={EcsContainer:async e=>{let{fromHttp:n}=await import(`./dist-cjs-BilOG_GK.mjs`).then(t()),{fromContainerMetadata:i}=await import(`./dist-cjs-BCXEF6CM.mjs`).then(t());return r?.debug(`@aws-sdk/credential-provider-ini - credential_source is EcsContainer`),async()=>c.chain(n(e??{}),i(e))().then(d)},Ec2InstanceMetadata:async e=>{r?.debug(`@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata`);let{fromInstanceMetadata:n}=await import(`./dist-cjs-BCXEF6CM.mjs`).then(t());return async()=>n(e)().then(d)},Environment:async e=>{r?.debug(`@aws-sdk/credential-provider-ini - credential_source is Environment`);let{fromEnv:n}=await import(`./dist-cjs-8w9IfsHf.mjs`).then(t());return async()=>n(e)().then(d)}};if(e in i)return i[e];throw new c.CredentialsProviderError(`Unsupported credential source in profile ${n}. Got ${e}, expected EcsContainer or Ec2InstanceMetadata or Environment.`,{logger:r})},d=e=>l.setCredentialFeature(e,`CREDENTIALS_PROFILE_NAMED_PROVIDER`,`p`),f=(e,{profile:t=`default`,logger:n}={})=>!!e&&typeof e==`object`&&typeof e.role_arn==`string`&&[`undefined`,`string`].indexOf(typeof e.role_session_name)>-1&&[`undefined`,`string`].indexOf(typeof e.external_id)>-1&&[`undefined`,`string`].indexOf(typeof e.mfa_serial)>-1&&(p(e,{profile:t,logger:n})||m(e,{profile:t,logger:n})),p=(e,{profile:t,logger:n})=>{let r=typeof e.source_profile==`string`&&e.credential_source===void 0;return r&&n?.debug?.(` ${t} isAssumeRoleWithSourceProfile source_profile=${e.source_profile}`),r},m=(e,{profile:t,logger:n})=>{let r=typeof e.credential_source==`string`&&e.source_profile===void 0;return r&&n?.debug?.(` ${t} isCredentialSourceProfile credential_source=${e.credential_source}`),r},h=async(e,t,n,r={},i)=>{n.logger?.debug(`@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)`);let a=t[e],{source_profile:o,region:d}=a;if(!n.roleAssumer){let{getDefaultRoleAssumer:e}=await import(`./sts-DJilo-ly.mjs`);n.roleAssumer=e({...n.clientConfig,credentialProviderLogger:n.logger,parentClientConfig:{...n?.parentClientConfig,region:d??n?.parentClientConfig?.region}},n.clientPlugins)}if(o&&o in r)throw new c.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile ${s.getProfileName(n)}. Profiles visited: `+Object.keys(r).join(`, `),{logger:n.logger});n.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${o?`source_profile=[${o}]`:`profile=[${e}]`}`);let f=o?i(o,t,n,{...r,[o]:!0},g(t[o]??{})):(await u(a.credential_source,e,n.logger)(n))();if(g(a))return f.then(e=>l.setCredentialFeature(e,`CREDENTIALS_PROFILE_SOURCE_PROFILE`,`o`));{let t={RoleArn:a.role_arn,RoleSessionName:a.role_session_name||`aws-sdk-js-${Date.now()}`,ExternalId:a.external_id,DurationSeconds:parseInt(a.duration_seconds||`3600`,10)},{mfa_serial:r}=a;if(r){if(!n.mfaCodeProvider)throw new c.CredentialsProviderError(`Profile ${e} requires multi-factor authentication, but no MFA code callback was provided.`,{logger:n.logger,tryNextLink:!1});t.SerialNumber=r,t.TokenCode=await n.mfaCodeProvider(r)}let i=await f;return n.roleAssumer(i,t).then(e=>l.setCredentialFeature(e,`CREDENTIALS_PROFILE_SOURCE_PROFILE`,`o`))}},g=e=>!e.role_arn&&!!e.credential_source,_=e=>!!e&&typeof e==`object`&&typeof e.credential_process==`string`,v=async(e,n)=>import(`./dist-cjs-B5EVkyOL.mjs`).then(t()).then(({fromProcess:t})=>t({...e,profile:n})().then(e=>l.setCredentialFeature(e,`CREDENTIALS_PROFILE_PROCESS`,`v`))),y=async(e,n,r={})=>{let{fromSSO:i}=await import(`./dist-cjs-Ddwe8ROf.mjs`).then(t());return i({profile:e,logger:r.logger,parentClientConfig:r.parentClientConfig,clientConfig:r.clientConfig})().then(e=>n.sso_session?l.setCredentialFeature(e,`CREDENTIALS_PROFILE_SSO`,`r`):l.setCredentialFeature(e,`CREDENTIALS_PROFILE_SSO_LEGACY`,`t`))},b=e=>e&&(typeof e.sso_start_url==`string`||typeof e.sso_account_id==`string`||typeof e.sso_session==`string`||typeof e.sso_region==`string`||typeof e.sso_role_name==`string`),x=e=>!!e&&typeof e==`object`&&typeof e.aws_access_key_id==`string`&&typeof e.aws_secret_access_key==`string`&&[`undefined`,`string`].indexOf(typeof e.aws_session_token)>-1&&[`undefined`,`string`].indexOf(typeof e.aws_account_id)>-1,S=async(e,t)=>{t?.logger?.debug(`@aws-sdk/credential-provider-ini - resolveStaticCredentials`);let n={accessKeyId:e.aws_access_key_id,secretAccessKey:e.aws_secret_access_key,sessionToken:e.aws_session_token,...e.aws_credential_scope&&{credentialScope:e.aws_credential_scope},...e.aws_account_id&&{accountId:e.aws_account_id}};return l.setCredentialFeature(n,`CREDENTIALS_PROFILE`,`n`)},C=e=>!!e&&typeof e==`object`&&typeof e.web_identity_token_file==`string`&&typeof e.role_arn==`string`&&[`undefined`,`string`].indexOf(typeof e.role_session_name)>-1,w=async(e,n)=>import(`./dist-cjs-BurjEDDY.mjs`).then(t()).then(({fromTokenFile:t})=>t({webIdentityTokenFile:e.web_identity_token_file,roleArn:e.role_arn,roleSessionName:e.role_session_name,roleAssumerWithWebIdentity:n.roleAssumerWithWebIdentity,logger:n.logger,parentClientConfig:n.parentClientConfig})().then(e=>l.setCredentialFeature(e,`CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN`,`q`))),T=async(e,t,n,r={},i=!1)=>{let a=t[e];if(Object.keys(r).length>0&&x(a))return S(a,n);if(i||f(a,{profile:e,logger:n.logger}))return h(e,t,n,r,T);if(x(a))return S(a,n);if(C(a))return w(a,n);if(_(a))return v(n,e);if(b(a))return await y(e,a,n);throw new c.CredentialsProviderError(`Could not resolve credentials using profile: [${e}] in configuration/credentials file(s).`,{logger:n.logger})};n.fromIni=(e={})=>async({callerClientConfig:t}={})=>{let n={...e,parentClientConfig:{...t,...e.parentClientConfig}};n.logger?.debug(`@aws-sdk/credential-provider-ini - fromIni`);let r=await s.parseKnownFiles(n);return T(s.getProfileName({profile:e.profile??t?.profile}),r,n)}}));export default s();export{};