@theobourgeois/ytdb 0.4.0 → 0.5.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 (110) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/app-path-routes-manifest.json +6 -6
  3. package/.next/build-manifest.json +3 -3
  4. package/.next/prerender-manifest.json +5 -5
  5. package/.next/server/app/[connectionId]/[schema]/[table]/page.js +1 -1
  6. package/.next/server/app/[connectionId]/[schema]/[table]/page.js.nft.json +1 -1
  7. package/.next/server/app/[connectionId]/[schema]/[table]/page_client-reference-manifest.js +1 -1
  8. package/.next/server/app/[connectionId]/diff/page.js +1 -1
  9. package/.next/server/app/[connectionId]/diff/page.js.nft.json +1 -1
  10. package/.next/server/app/[connectionId]/diff/page_client-reference-manifest.js +1 -1
  11. package/.next/server/app/[connectionId]/migrations/(index)/page.js +1 -1
  12. package/.next/server/app/[connectionId]/migrations/(index)/page.js.nft.json +1 -1
  13. package/.next/server/app/[connectionId]/migrations/(index)/page_client-reference-manifest.js +1 -1
  14. package/.next/server/app/[connectionId]/migrations/(index)/release/page.js +1 -1
  15. package/.next/server/app/[connectionId]/migrations/(index)/release/page.js.nft.json +1 -1
  16. package/.next/server/app/[connectionId]/migrations/(index)/release/page_client-reference-manifest.js +1 -1
  17. package/.next/server/app/[connectionId]/migrations/(index)/timeline/page.js +1 -1
  18. package/.next/server/app/[connectionId]/migrations/(index)/timeline/page.js.nft.json +1 -1
  19. package/.next/server/app/[connectionId]/migrations/(index)/timeline/page_client-reference-manifest.js +1 -1
  20. package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page.js +1 -1
  21. package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page.js.nft.json +1 -1
  22. package/.next/server/app/[connectionId]/migrations/[setId]/diagram/page_client-reference-manifest.js +1 -1
  23. package/.next/server/app/[connectionId]/migrations/[setId]/page.js +1 -1
  24. package/.next/server/app/[connectionId]/migrations/[setId]/page.js.nft.json +1 -1
  25. package/.next/server/app/[connectionId]/migrations/[setId]/page_client-reference-manifest.js +1 -1
  26. package/.next/server/app/[connectionId]/migrations/[setId]/schema/page.js +1 -1
  27. package/.next/server/app/[connectionId]/migrations/[setId]/schema/page.js.nft.json +1 -1
  28. package/.next/server/app/[connectionId]/migrations/[setId]/schema/page_client-reference-manifest.js +1 -1
  29. package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page.js +1 -1
  30. package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page.js.nft.json +1 -1
  31. package/.next/server/app/[connectionId]/migrations/[setId]/timeline/page_client-reference-manifest.js +1 -1
  32. package/.next/server/app/[connectionId]/page.js +1 -1
  33. package/.next/server/app/[connectionId]/page.js.nft.json +1 -1
  34. package/.next/server/app/[connectionId]/page_client-reference-manifest.js +1 -1
  35. package/.next/server/app/[connectionId]/query/page.js +1 -1
  36. package/.next/server/app/[connectionId]/query/page.js.nft.json +1 -1
  37. package/.next/server/app/[connectionId]/query/page_client-reference-manifest.js +1 -1
  38. package/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  39. package/.next/server/app/_global-error.html +1 -1
  40. package/.next/server/app/_global-error.rsc +1 -1
  41. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  42. package/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  43. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  44. package/.next/server/app/_not-found/page.js +1 -1
  45. package/.next/server/app/_not-found/page.js.nft.json +1 -1
  46. package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  47. package/.next/server/app/_not-found.html +1 -1
  48. package/.next/server/app/_not-found.rsc +7 -7
  49. package/.next/server/app/_not-found.segments/_full.segment.rsc +7 -7
  50. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +7 -7
  51. package/.next/server/app/_not-found.segments/_tree.segment.rsc +3 -3
  52. package/.next/server/app/api/note/route.js +1 -1
  53. package/.next/server/app/api/note/route.js.nft.json +1 -1
  54. package/.next/server/app/api/release/label/route.js +1 -1
  55. package/.next/server/app/api/release/label/route.js.nft.json +1 -1
  56. package/.next/server/app/api/release/merge/route.js +1 -1
  57. package/.next/server/app/api/release/merge/route.js.nft.json +1 -1
  58. package/.next/server/app/api/release/route.js +1 -1
  59. package/.next/server/app/api/release/route.js.nft.json +1 -1
  60. package/.next/server/app/api/release/sync/route.js +1 -1
  61. package/.next/server/app/api/release/sync/route.js.nft.json +1 -1
  62. package/.next/server/app/api/repo/route.js +1 -1
  63. package/.next/server/app/api/repo/route.js.nft.json +1 -1
  64. package/.next/server/app/index.html +1 -1
  65. package/.next/server/app/index.rsc +8 -8
  66. package/.next/server/app/index.segments/__PAGE__.segment.rsc +8 -8
  67. package/.next/server/app/index.segments/_full.segment.rsc +8 -8
  68. package/.next/server/app/index.segments/_tree.segment.rsc +3 -3
  69. package/.next/server/app/page.js +1 -1
  70. package/.next/server/app/page.js.nft.json +1 -1
  71. package/.next/server/app/page_client-reference-manifest.js +1 -1
  72. package/.next/server/app-paths-manifest.json +6 -6
  73. package/.next/server/chunks/3128.js +1 -1
  74. package/.next/server/chunks/4809.js +1 -1
  75. package/.next/server/chunks/{7928.js → 4829.js} +2 -2
  76. package/.next/server/chunks/535.js +1 -1
  77. package/.next/server/chunks/5529.js +1 -1
  78. package/.next/server/chunks/6326.js +1 -1
  79. package/.next/server/chunks/6729.js +1 -1
  80. package/.next/server/chunks/9955.js +2 -0
  81. package/.next/server/chunks/9975.js +1 -0
  82. package/.next/server/middleware-build-manifest.js +1 -1
  83. package/.next/server/pages/404.html +1 -1
  84. package/.next/server/pages/500.html +1 -1
  85. package/.next/server/server-reference-manifest.json +1 -1
  86. package/.next/static/chunks/544-4b9895b378c705d5.js +1 -0
  87. package/.next/static/chunks/5882-93a86897269a2357.js +1 -0
  88. package/.next/static/chunks/{6090-6747af370e06526b.js → 6090-da786d958e55f4a0.js} +1 -1
  89. package/.next/static/chunks/{223-ae41c085e76173d8.js → 6204-83d5772d4de805ed.js} +1 -1
  90. package/.next/static/chunks/app/[connectionId]/layout-7003c682ec8f6509.js +1 -0
  91. package/.next/static/chunks/app/[connectionId]/migrations/(index)/layout-600db79333f35616.js +1 -0
  92. package/.next/static/chunks/app/[connectionId]/migrations/[setId]/layout-0301fd5781bab720.js +1 -0
  93. package/.next/static/chunks/app/[connectionId]/page-1a00b3257a09dd92.js +1 -0
  94. package/.next/static/chunks/app/{layout-2ed8b1f837adb32a.js → layout-99d6b2a5165968f9.js} +1 -1
  95. package/.next/static/chunks/{webpack-469ae59d9719e191.js → webpack-a9d4b191c6c579a9.js} +1 -1
  96. package/.next/static/css/15730e9f7c5c55ef.css +1 -0
  97. package/.next/static/css/7990d32d787a4f50.css +1 -0
  98. package/package.json +1 -1
  99. package/.next/server/chunks/1421.js +0 -1
  100. package/.next/server/chunks/2783.js +0 -2
  101. package/.next/static/chunks/544-624e05bf7e7a38d4.js +0 -1
  102. package/.next/static/chunks/5882-80bb4c4b772c9896.js +0 -1
  103. package/.next/static/chunks/app/[connectionId]/layout-b8ad40b3da6824ed.js +0 -1
  104. package/.next/static/chunks/app/[connectionId]/migrations/(index)/layout-4156ea75d3316171.js +0 -1
  105. package/.next/static/chunks/app/[connectionId]/migrations/[setId]/layout-a4421cb4d144bdb0.js +0 -1
  106. package/.next/static/chunks/app/[connectionId]/page-33495fc674565a49.js +0 -1
  107. package/.next/static/css/3f63e021c3018af1.css +0 -1
  108. package/.next/static/css/5df9ea52964d1443.css +0 -1
  109. /package/.next/static/{o6yjJlz_K9qa2rPdFBH6P → Kaj0NPa3KimVM4bTHOpOs}/_buildManifest.js +0 -0
  110. /package/.next/static/{o6yjJlz_K9qa2rPdFBH6P → Kaj0NPa3KimVM4bTHOpOs}/_ssgManifest.js +0 -0
@@ -1,2 +1,2 @@
1
- (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[223],{1934:(e,t,s)=>{"use strict";s.d(t,{v:()=>o});var i=s(12115);let n=e=>{let t,s=new Set,i=(e,i)=>{let n="function"==typeof e?e(t):e;if(!Object.is(n,t)){let e=t;t=(null!=i?i:"object"!=typeof n||null===n)?n:Object.assign({},t,n),s.forEach(s=>s(t,e))}},n=()=>t,r={setState:i,getState:n,getInitialState:()=>o,subscribe:e=>(s.add(e),()=>s.delete(e))},o=t=e(i,n,r);return r},r=e=>{let t=e?n(e):n,s=e=>(function(e,t=e=>e){let s=i.useSyncExternalStore(e.subscribe,i.useCallback(()=>t(e.getState()),[e,t]),i.useCallback(()=>t(e.getInitialState()),[e,t]));return i.useDebugValue(s),s})(t,e);return Object.assign(s,t),s},o=e=>e?r(e):r},31692:(e,t,s)=>{"use strict";function i(e,t){let s;try{s=e()}catch(e){return}return{getItem:e=>{var i;let n=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),r=null!=(i=s.getItem(e))?i:null;return r instanceof Promise?r.then(n):n(r)},setItem:(e,i)=>s.setItem(e,JSON.stringify(i,null==t?void 0:t.replacer)),removeItem:e=>s.removeItem(e)}}s.d(t,{KU:()=>i,Zr:()=>r});let n=e=>t=>{try{let s=e(t);if(s instanceof Promise)return s;return{then:e=>n(e)(s),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>n(t)(e)}}},r=(e,t)=>(s,r,o)=>{let a,u={storage:i(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},h=!1,l=0,c=new Set,d=new Set,g=u.storage;if(!g)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${u.name}', the given storage is currently unavailable.`),s(...e)},r,o);let f=()=>{let e=u.partialize({...r()});return g.setItem(u.name,{state:e,version:u.version})},y=o.setState;o.setState=(e,t)=>(y(e,t),f());let p=e((...e)=>(s(...e),f()),r,o);o.getInitialState=()=>p;let m=()=>{var e,t;if(!g)return;let i=++l;h=!1,c.forEach(e=>{var t;return e(null!=(t=r())?t:p)});let o=(null==(t=u.onRehydrateStorage)?void 0:t.call(u,null!=(e=r())?e:p))||void 0;return n(g.getItem.bind(g))(u.name).then(e=>{if(e)if("number"!=typeof e.version||e.version===u.version)return[!1,e.state];else{if(u.migrate){let t=u.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;if(i!==l)return;let[n,o]=e;if(s(a=u.merge(o,null!=(t=r())?t:p),!0),n)return f()}).then(()=>{i===l&&(null==o||o(r(),void 0),a=r(),h=!0,d.forEach(e=>e(a)))}).catch(e=>{i===l&&(null==o||o(void 0,e))})};return o.persist={setOptions:e=>{u={...u,...e},e.storage&&(g=e.storage)},clearStorage:()=>{++l,null==g||g.removeItem(u.name)},getOptions:()=>u,rehydrate:()=>m(),hasHydrated:()=>h,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(d.add(e),()=>{d.delete(e)})},u.skipHydration||m(),a||p}},34244:e=>{e.exports={style:{fontFamily:"'Geist', 'Geist Fallback'",fontStyle:"normal"},className:"__className_8eaea4",variable:"__variable_8eaea4"}},64939:e=>{e.exports={style:{fontFamily:"'Geist Mono', 'Geist Mono Fallback'",fontStyle:"normal"},className:"__className_8c25df",variable:"__variable_8c25df"}},73321:(e,t,s)=>{"use strict";var i=s(74645);s.o(i,"useParams")&&s.d(t,{useParams:function(){return i.useParams}}),s.o(i,"usePathname")&&s.d(t,{usePathname:function(){return i.usePathname}}),s.o(i,"useRouter")&&s.d(t,{useRouter:function(){return i.useRouter}})},92328:(e,t,s)=>{"use strict";let i;s.d(t,{hD:()=>eW,eH:()=>eD});for(var n,r,o=s(12115),a=[],u=[],h=Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,d=l.length;c<d;++c)a[c]=l[c],u[l.charCodeAt(c)]=c;function g(e){var t,s,i=function(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=t);var i=s===t?0:4-s%4;return[s,i]}(e),n=i[0],r=i[1],o=new h((n+r)*3/4-r),a=0,l=r>0?n-4:n;for(s=0;s<l;s+=4)t=u[e.charCodeAt(s)]<<18|u[e.charCodeAt(s+1)]<<12|u[e.charCodeAt(s+2)]<<6|u[e.charCodeAt(s+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===r&&(t=u[e.charCodeAt(s)]<<2|u[e.charCodeAt(s+1)]>>4,o[a++]=255&t),1===r&&(t=u[e.charCodeAt(s)]<<10|u[e.charCodeAt(s+1)]<<4|u[e.charCodeAt(s+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o}function f(e){for(var t,s=e.length,i=s%3,n=[],r=0,o=s-i;r<o;r+=16383)n.push(function(e,t,s){for(var i,n=[],r=t;r<s;r+=3)i=(e[r]<<16&0xff0000)+(e[r+1]<<8&65280)+(255&e[r+2]),n.push(a[i>>18&63]+a[i>>12&63]+a[i>>6&63]+a[63&i]);return n.join("")}(e,r,r+16383>o?o:r+16383));return 1===i?n.push(a[(t=e[s-1])>>2]+a[t<<4&63]+"=="):2===i&&n.push(a[(t=(e[s-2]<<8)+e[s-1])>>10]+a[t>>4&63]+a[t<<2&63]+"="),n.join("")}function y(e){if(void 0===e)return{};if(!p(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function p(e){let t="object"==typeof e,s=Object.getPrototypeOf(e),i=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&i}u[45]=62,u[95]=63;let m=BigInt("-9223372036854775808"),v=BigInt("9223372036854775807"),b=BigInt("0"),S=BigInt("8"),k=BigInt("256"),w="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.";class R{[Symbol.toPrimitive](e){if("string"===e)return this.toString();throw Error(w)}valueOf(){throw Error(w)}toJSON(){throw Error(w)}toString(){return"[unresolved commit timestamp]"}}let C=new R;function T(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}let A=DataView.prototype.setBigInt64?function(e){if(e<m||v<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),f(new Uint8Array(t))}:function(e){e<b&&(e-=m+m);let t=e.toString(16);t.length%2==1&&(t="0"+t);let s=new Uint8Array(new ArrayBuffer(8)),i=0;for(let n of t.match(/.{2}/g).reverse())s.set([parseInt(n,16)],i++),e>>=S;return f(s)},q=DataView.prototype.getBigInt64?function(e){let t=g(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){let t=g(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=b,i=b;for(let e of t)s+=BigInt(e)*k**i,i++;return s>v&&(s+=m+m),s};function M(e){if(e.length>1024)throw Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let s=e.charCodeAt(t);if(s<32||s>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function I(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>I(e));if("object"!=typeof e)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(1===t.length){let s=t[0][0];if("$bytes"===s){if("string"!=typeof e.$bytes)throw Error(`Malformed $bytes field on ${e}`);return g(e.$bytes).buffer}if("$integer"===s){if("string"!=typeof e.$integer)throw Error(`Malformed $integer field on ${e}`);return q(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw Error(`Malformed $float field on ${e}`);let t=g(e.$float);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let s=new DataView(t.buffer).getFloat64(0,!0);if(!T(s))throw Error(`Float ${s} should be encoded as a number`);return s}if("$commitTs"===s){if(null!==e.$commitTs)throw Error(`Malformed $commitTs field on ${e}`);return C}if("$set"===s)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===s)throw Error("Received a Map which is no longer supported as a Convex type.")}let s={};for(let[t,i]of Object.entries(e))M(t),s[t]=I(i);return s}function $(e){let t=JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t);if(t.length>16384){let e="[...truncated]",s=16384-e.length,i=t.codePointAt(s-1);return void 0!==i&&i>65535&&(s-=1),t.substring(0,s)+e}return t}function Q(e,t,s,i){return e?`${t}${$(s)} is not a supported Convex type (present at path ${e} in original object ${$(i)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${$(s)} is not a supported Convex type.`}function O(e){return function e(t,s,i,n){if(void 0===t){let e=i&&` (present at path ${i} in original object ${$(s)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===t)return t;if("bigint"==typeof t){if(t<m||v<t)throw Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:A(t)}}if("number"==typeof t)if(!T(t))return t;else{let e=new ArrayBuffer(8);return new DataView(e).setFloat64(0,t,!0),{$float:f(new Uint8Array(e))}}if("boolean"==typeof t||"string"==typeof t)return t;if(t instanceof ArrayBuffer)return{$bytes:f(new Uint8Array(t))};if(t instanceof R)return{$commitTs:null};if(Array.isArray(t))return t.map((t,n)=>e(t,s,i+`[${n}]`,!1));if(t instanceof Set)throw Error(Q(i,"Set",[...t],s));if(t instanceof Map)throw Error(Q(i,"Map",[...t],s));if(!p(t)){let e=t?.constructor?.name;throw Error(Q(i,e?`${e} `:"",t,s))}let r={},o=Object.entries(t);for(let[t,a]of(o.sort(([e,t],[s,i])=>e===s?0:e<s?-1:1),o))void 0!==a?(M(t),r[t]=e(a,s,i+`.${t}`,!1)):n&&(M(t),r[t]=function(t,s,i){if(void 0===t)return{$undefined:null};if(void 0===s)throw Error(`Programming error. Current value is ${$(t)} but original value is undefined`);return e(t,s,i,!1)}(a,s,i+`.${t}`));return r}(e,e,"",!1)}var x=Object.defineProperty,E=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?x(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};let P=Symbol.for("ConvexError");class V extends(r=Error,n=P,r){constructor(e){super("string"==typeof e?e:$(e)),E(this,"name","ConvexError"),E(this,"data"),E(this,n,!0),this.data=e}}let L=()=>Array.from({length:4},()=>0);L(),L();let _="1.45.0";var N=Object.defineProperty,F=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?N(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function B(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class U{constructor(e){F(this,"_onLogLineFuncs"),F(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&void 0!==this._onLogLineFuncs[t];e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t("error",...e)}}function D(e){let t=new U(e);return t.addLogLineListener((e,...t)=>{switch(e){case"debug":console.debug(...t);break;case"info":default:console.log(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}),t}function j(e,t,s,i,n){let r=B(s);if("object"==typeof n&&(n=`ConvexError ${JSON.stringify(n.errorData,null,2)}`),"info"===t){let t=n.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${i})] Could not parse console.log`);let s=n.slice(1,t[0].length-2),o=n.slice(t[0].length);e.log(`%c[CONVEX ${r}(${i})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${r}(${i})] ${n}`)}function W(e,t,s){let i=B(e);return`[CONVEX ${i}(${t})] ${s.errorMessage}
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[6204],{1934:(e,t,s)=>{"use strict";s.d(t,{v:()=>o});var i=s(12115);let n=e=>{let t,s=new Set,i=(e,i)=>{let n="function"==typeof e?e(t):e;if(!Object.is(n,t)){let e=t;t=(null!=i?i:"object"!=typeof n||null===n)?n:Object.assign({},t,n),s.forEach(s=>s(t,e))}},n=()=>t,r={setState:i,getState:n,getInitialState:()=>o,subscribe:e=>(s.add(e),()=>s.delete(e))},o=t=e(i,n,r);return r},r=e=>{let t=e?n(e):n,s=e=>(function(e,t=e=>e){let s=i.useSyncExternalStore(e.subscribe,i.useCallback(()=>t(e.getState()),[e,t]),i.useCallback(()=>t(e.getInitialState()),[e,t]));return i.useDebugValue(s),s})(t,e);return Object.assign(s,t),s},o=e=>e?r(e):r},17301:e=>{e.exports={style:{fontFamily:"'Geist', 'Geist Fallback'",fontStyle:"normal"},className:"__className_8eaea4",variable:"__variable_8eaea4"}},31692:(e,t,s)=>{"use strict";function i(e,t){let s;try{s=e()}catch(e){return}return{getItem:e=>{var i;let n=e=>null===e?null:JSON.parse(e,null==t?void 0:t.reviver),r=null!=(i=s.getItem(e))?i:null;return r instanceof Promise?r.then(n):n(r)},setItem:(e,i)=>s.setItem(e,JSON.stringify(i,null==t?void 0:t.replacer)),removeItem:e=>s.removeItem(e)}}s.d(t,{KU:()=>i,Zr:()=>r});let n=e=>t=>{try{let s=e(t);if(s instanceof Promise)return s;return{then:e=>n(e)(s),catch(e){return this}}}catch(e){return{then(e){return this},catch:t=>n(t)(e)}}},r=(e,t)=>(s,r,o)=>{let a,u={storage:i(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},h=!1,l=0,c=new Set,d=new Set,g=u.storage;if(!g)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${u.name}', the given storage is currently unavailable.`),s(...e)},r,o);let f=()=>{let e=u.partialize({...r()});return g.setItem(u.name,{state:e,version:u.version})},y=o.setState;o.setState=(e,t)=>(y(e,t),f());let p=e((...e)=>(s(...e),f()),r,o);o.getInitialState=()=>p;let m=()=>{var e,t;if(!g)return;let i=++l;h=!1,c.forEach(e=>{var t;return e(null!=(t=r())?t:p)});let o=(null==(t=u.onRehydrateStorage)?void 0:t.call(u,null!=(e=r())?e:p))||void 0;return n(g.getItem.bind(g))(u.name).then(e=>{if(e)if("number"!=typeof e.version||e.version===u.version)return[!1,e.state];else{if(u.migrate){let t=u.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}return[!1,void 0]}).then(e=>{var t;if(i!==l)return;let[n,o]=e;if(s(a=u.merge(o,null!=(t=r())?t:p),!0),n)return f()}).then(()=>{i===l&&(null==o||o(r(),void 0),a=r(),h=!0,d.forEach(e=>e(a)))}).catch(e=>{i===l&&(null==o||o(void 0,e))})};return o.persist={setOptions:e=>{u={...u,...e},e.storage&&(g=e.storage)},clearStorage:()=>{++l,null==g||g.removeItem(u.name)},getOptions:()=>u,rehydrate:()=>m(),hasHydrated:()=>h,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(d.add(e),()=>{d.delete(e)})},u.skipHydration||m(),a||p}},64939:e=>{e.exports={style:{fontFamily:"'Geist Mono', 'Geist Mono Fallback'",fontStyle:"normal"},className:"__className_8c25df",variable:"__variable_8c25df"}},73321:(e,t,s)=>{"use strict";var i=s(74645);s.o(i,"useParams")&&s.d(t,{useParams:function(){return i.useParams}}),s.o(i,"usePathname")&&s.d(t,{usePathname:function(){return i.usePathname}}),s.o(i,"useRouter")&&s.d(t,{useRouter:function(){return i.useRouter}})},92328:(e,t,s)=>{"use strict";let i;s.d(t,{hD:()=>eW,eH:()=>eD});for(var n,r,o=s(12115),a=[],u=[],h=Uint8Array,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c=0,d=l.length;c<d;++c)a[c]=l[c],u[l.charCodeAt(c)]=c;function g(e){var t,s,i=function(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var s=e.indexOf("=");-1===s&&(s=t);var i=s===t?0:4-s%4;return[s,i]}(e),n=i[0],r=i[1],o=new h((n+r)*3/4-r),a=0,l=r>0?n-4:n;for(s=0;s<l;s+=4)t=u[e.charCodeAt(s)]<<18|u[e.charCodeAt(s+1)]<<12|u[e.charCodeAt(s+2)]<<6|u[e.charCodeAt(s+3)],o[a++]=t>>16&255,o[a++]=t>>8&255,o[a++]=255&t;return 2===r&&(t=u[e.charCodeAt(s)]<<2|u[e.charCodeAt(s+1)]>>4,o[a++]=255&t),1===r&&(t=u[e.charCodeAt(s)]<<10|u[e.charCodeAt(s+1)]<<4|u[e.charCodeAt(s+2)]>>2,o[a++]=t>>8&255,o[a++]=255&t),o}function f(e){for(var t,s=e.length,i=s%3,n=[],r=0,o=s-i;r<o;r+=16383)n.push(function(e,t,s){for(var i,n=[],r=t;r<s;r+=3)i=(e[r]<<16&0xff0000)+(e[r+1]<<8&65280)+(255&e[r+2]),n.push(a[i>>18&63]+a[i>>12&63]+a[i>>6&63]+a[63&i]);return n.join("")}(e,r,r+16383>o?o:r+16383));return 1===i?n.push(a[(t=e[s-1])>>2]+a[t<<4&63]+"=="):2===i&&n.push(a[(t=(e[s-2]<<8)+e[s-1])>>10]+a[t>>4&63]+a[t<<2&63]+"="),n.join("")}function y(e){if(void 0===e)return{};if(!p(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function p(e){let t="object"==typeof e,s=Object.getPrototypeOf(e),i=null===s||s===Object.prototype||s?.constructor?.name==="Object";return t&&i}u[45]=62,u[95]=63;let m=BigInt("-9223372036854775808"),v=BigInt("9223372036854775807"),b=BigInt("0"),S=BigInt("8"),k=BigInt("256"),w="This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.";class R{[Symbol.toPrimitive](e){if("string"===e)return this.toString();throw Error(w)}valueOf(){throw Error(w)}toJSON(){throw Error(w)}toString(){return"[unresolved commit timestamp]"}}let C=new R;function T(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}let A=DataView.prototype.setBigInt64?function(e){if(e<m||v<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),f(new Uint8Array(t))}:function(e){e<b&&(e-=m+m);let t=e.toString(16);t.length%2==1&&(t="0"+t);let s=new Uint8Array(new ArrayBuffer(8)),i=0;for(let n of t.match(/.{2}/g).reverse())s.set([parseInt(n,16)],i++),e>>=S;return f(s)},q=DataView.prototype.getBigInt64?function(e){let t=g(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}:function(e){let t=g(e);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let s=b,i=b;for(let e of t)s+=BigInt(e)*k**i,i++;return s>v&&(s+=m+m),s};function M(e){if(e.length>1024)throw Error(`Field name ${e} exceeds maximum field name length 1024.`);if(e.startsWith("$"))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let s=e.charCodeAt(t);if(s<32||s>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function I(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e)return e;if(Array.isArray(e))return e.map(e=>I(e));if("object"!=typeof e)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(1===t.length){let s=t[0][0];if("$bytes"===s){if("string"!=typeof e.$bytes)throw Error(`Malformed $bytes field on ${e}`);return g(e.$bytes).buffer}if("$integer"===s){if("string"!=typeof e.$integer)throw Error(`Malformed $integer field on ${e}`);return q(e.$integer)}if("$float"===s){if("string"!=typeof e.$float)throw Error(`Malformed $float field on ${e}`);let t=g(e.$float);if(8!==t.byteLength)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let s=new DataView(t.buffer).getFloat64(0,!0);if(!T(s))throw Error(`Float ${s} should be encoded as a number`);return s}if("$commitTs"===s){if(null!==e.$commitTs)throw Error(`Malformed $commitTs field on ${e}`);return C}if("$set"===s)throw Error("Received a Set which is no longer supported as a Convex type.");if("$map"===s)throw Error("Received a Map which is no longer supported as a Convex type.")}let s={};for(let[t,i]of Object.entries(e))M(t),s[t]=I(i);return s}function $(e){let t=JSON.stringify(e,(e,t)=>void 0===t?"undefined":"bigint"==typeof t?`${t.toString()}n`:t);if(t.length>16384){let e="[...truncated]",s=16384-e.length,i=t.codePointAt(s-1);return void 0!==i&&i>65535&&(s-=1),t.substring(0,s)+e}return t}function Q(e,t,s,i){return e?`${t}${$(s)} is not a supported Convex type (present at path ${e} in original object ${$(i)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${$(s)} is not a supported Convex type.`}function O(e){return function e(t,s,i,n){if(void 0===t){let e=i&&` (present at path ${i} in original object ${$(s)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(null===t)return t;if("bigint"==typeof t){if(t<m||v<t)throw Error(`BigInt ${t} does not fit into a 64-bit signed integer.`);return{$integer:A(t)}}if("number"==typeof t)if(!T(t))return t;else{let e=new ArrayBuffer(8);return new DataView(e).setFloat64(0,t,!0),{$float:f(new Uint8Array(e))}}if("boolean"==typeof t||"string"==typeof t)return t;if(t instanceof ArrayBuffer)return{$bytes:f(new Uint8Array(t))};if(t instanceof R)return{$commitTs:null};if(Array.isArray(t))return t.map((t,n)=>e(t,s,i+`[${n}]`,!1));if(t instanceof Set)throw Error(Q(i,"Set",[...t],s));if(t instanceof Map)throw Error(Q(i,"Map",[...t],s));if(!p(t)){let e=t?.constructor?.name;throw Error(Q(i,e?`${e} `:"",t,s))}let r={},o=Object.entries(t);for(let[t,a]of(o.sort(([e,t],[s,i])=>e===s?0:e<s?-1:1),o))void 0!==a?(M(t),r[t]=e(a,s,i+`.${t}`,!1)):n&&(M(t),r[t]=function(t,s,i){if(void 0===t)return{$undefined:null};if(void 0===s)throw Error(`Programming error. Current value is ${$(t)} but original value is undefined`);return e(t,s,i,!1)}(a,s,i+`.${t}`));return r}(e,e,"",!1)}var x=Object.defineProperty,E=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?x(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};let P=Symbol.for("ConvexError");class V extends(r=Error,n=P,r){constructor(e){super("string"==typeof e?e:$(e)),E(this,"name","ConvexError"),E(this,"data"),E(this,n,!0),this.data=e}}let L=()=>Array.from({length:4},()=>0);L(),L();let _="1.45.0";var N=Object.defineProperty,F=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?N(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function B(e){switch(e){case"query":return"Q";case"mutation":return"M";case"action":return"A";case"any":return"?"}}class U{constructor(e){F(this,"_onLogLineFuncs"),F(this,"_verbose"),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&void 0!==this._onLogLineFuncs[t];e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t("debug",`${new Date().toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t("info",...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t("warn",...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t("error",...e)}}function D(e){let t=new U(e);return t.addLogLineListener((e,...t)=>{switch(e){case"debug":console.debug(...t);break;case"info":default:console.log(...t);break;case"warn":console.warn(...t);break;case"error":console.error(...t)}}),t}function j(e,t,s,i,n){let r=B(s);if("object"==typeof n&&(n=`ConvexError ${JSON.stringify(n.errorData,null,2)}`),"info"===t){let t=n.match(/^\[.*?\] /);if(null===t)return void e.error(`[CONVEX ${r}(${i})] Could not parse console.log`);let s=n.slice(1,t[0].length-2),o=n.slice(t[0].length);e.log(`%c[CONVEX ${r}(${i})] [${s}]`,"color:rgb(0, 145, 255)",o)}else e.error(`[CONVEX ${r}(${i})] ${n}`)}function W(e,t,s){let i=B(e);return`[CONVEX ${i}(${t})] ${s.errorMessage}
2
2
  Called by client`}function K(e,t){return t.data=e.errorData,t}function H(e){let t,s,i=e.split(":");return 1===i.length?(t=i[0],s="default"):(t=i.slice(0,i.length-1).join(":"),s=i[i.length-1]),t.endsWith(".js")&&(t=t.slice(0,-3)),`${t}:${s}`}function J(e,t){return JSON.stringify({udfPath:H(e),args:O(t)})}function z(e,t,s){let{initialNumItems:i,id:n}=s;return JSON.stringify({type:"paginated",udfPath:H(e),args:O(t),options:O({initialNumItems:i,id:n})})}var G=Object.defineProperty,X=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?G(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class Y{constructor(){X(this,"nextQueryId"),X(this,"querySetVersion"),X(this,"querySet"),X(this,"queryIdToToken"),X(this,"identityVersion"),X(this,"auth"),X(this,"outstandingQueriesOlderThanRestart"),X(this,"outstandingAuthOlderThanRestart"),X(this,"paused"),X(this,"pendingQuerySetModifications"),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=new Map,this.queryIdToToken=new Map,this.outstandingQueriesOlderThanRestart=new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=new Map}hasSyncedPastLastReconnect(){return 0===this.outstandingQueriesOlderThanRestart.size&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,s,i){let n=H(e),r=J(n,t),o=this.querySet.get(r);if(void 0!==o)return o.numSubscribers+=1,{queryToken:r,modification:null,unsubscribe:()=>this.removeSubscriber(r)};{let e=this.nextQueryId++;this.querySet.set(r,{id:e,canonicalizedUdfPath:n,args:t,numSubscribers:1,journal:s,componentPath:i}),this.queryIdToToken.set(e,r);let o=this.querySetVersion,a=this.querySetVersion+1,u={type:"Add",queryId:e,udfPath:n,args:[O(t)],journal:s,componentPath:i};return this.paused?this.pendingQuerySetModifications.set(e,u):this.querySetVersion=a,{queryToken:r,modification:{type:"ModifyQuerySet",baseVersion:o,newVersion:a,modifications:[u]},unsubscribe:()=>this.removeSubscriber(r)}}}transition(e){for(let t of e.modifications)switch(t.type){case"QueryUpdated":case"QueryFailed":{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(void 0!==e){let s=this.queryIdToToken.get(t.queryId);void 0!==s&&(this.querySet.get(s).journal=e)}break}case"QueryRemoved":this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let s=J(H(e),t),i=this.querySet.get(s);return void 0!==i?i.id:null}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:"User",value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:"Authenticate",baseVersion:t,...this.auth}}setAdminAuth(e,t){let s={tokenType:"Admin",value:e,impersonating:t};this.auth=s;let i=this.identityVersion;return this.paused||(this.identityVersion=i+1),{type:"Authenticate",baseVersion:i,...s}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:"Authenticate",tokenType:"None",baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let s={type:"Add",queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[O(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(s),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:"ModifyQuerySet",baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let s={type:"Authenticate",baseVersion:0,...this.auth};return this.identityVersion=1,[t,s]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:"ModifyQuerySet",baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=void 0!==this.auth?{type:"Authenticate",baseVersion:this.identityVersion++,...this.auth}:void 0;return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return t.numSubscribers-=1,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let s=this.querySetVersion,i=this.querySetVersion+1,n={type:"Remove",queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,n):this.querySetVersion=i,{type:"ModifyQuerySet",baseVersion:s,newVersion:i,modifications:[n]}}}}var Z=Object.defineProperty,ee=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?Z(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class et{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,ee(this,"inflightRequests"),ee(this,"requestsOlderThanRestart"),ee(this,"inflightMutationsCount",0),ee(this,"inflightActionsCount",0),this.inflightRequests=new Map,this.requestsOlderThanRestart=new Set}request(e,t){let s=new Promise(s=>{this.inflightRequests.set(e.requestId,{message:e,status:{status:t?"Requested":"NotSent",requestedAt:new Date,onResult:s}}),"Mutation"===e.type?this.inflightMutationsCount++:"Action"===e.type&&this.inflightActionsCount++});return this.markConnectionStateDirty(),s}onResponse(e){let t,s,i=this.inflightRequests.get(e.requestId);if(void 0===i||"Completed"===i.status.status)return null;let n="Mutation"===i.message.type?"mutation":"action",r=i.message.udfPath;for(let t of e.logLines)j(this.logger,"info",n,r,t);let o=i.status;if(e.success)t={success:!0,logLines:e.logLines,value:I(e.result)},s=()=>o.onResult(t);else{let i=e.result,{errorData:a}=e;j(this.logger,"error",n,r,i),t={success:!1,errorMessage:i,errorData:void 0!==a?I(a):void 0,logLines:e.logLines},s=()=>o.onResult(t)}return"ActionResponse"!==e.type&&e.success?(i.status={status:"Completed",result:t,ts:e.ts,onResolve:s},null):(s(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),"Action"===i.message.type?this.inflightActionsCount--:"Mutation"===i.message.type&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:t})}removeCompleted(e){let t=new Map;for(let[s,i]of this.inflightRequests.entries()){let n=i.status;"Completed"===n.status&&n.ts.lessThanOrEqual(e)&&(n.onResolve(),t.set(s,n.result),"Mutation"===i.message.type?this.inflightMutationsCount--:"Action"===i.message.type&&this.inflightActionsCount--,this.inflightRequests.delete(s),this.requestsOlderThanRestart.delete(s))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,s]of this.inflightRequests){if("NotSent"===s.status.status){s.status.status="Requested",e.push(s.message);continue}if("Mutation"===s.message.type)e.push(s.message);else if("Action"===s.message.type){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,"Completed"===s.status.status)throw Error("Action should never be in 'Completed' state");s.status.onResult({success:!1,errorMessage:"Connection lost while action was in flight",logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if("NotSent"===t.status.status){t.status.status="Requested",e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if("Requested"===e.status.status)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return 0===this.requestsOlderThanRestart.size}timeOfOldestInflightRequest(){if(0===this.inflightRequests.size)return null;let e=Date.now();for(let t of this.inflightRequests.values())"Completed"!==t.status.status&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}}let es=Symbol.for("functionName"),ei=Symbol.for("toReferencePath");function en(e){let t=function(e){let t;if("string"==typeof e)t=e.startsWith("function://")?{functionHandle:e}:{name:e};else if(e[es])t={name:e[es]};else{let s=e[ei]??null;if(!s)throw Error(`${e} is not a functionReference`);t={reference:s}}return t}(e);if(void 0===t.name){if(void 0!==t.functionHandle)throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(void 0!==t.reference)throw Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`);throw Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`)}if("string"==typeof e)return e;let s=e[es];if(!s)throw Error(`${e} is not a functionReference`);return s}!function e(t=[]){return new Proxy({},{get(s,i){if("string"==typeof i)return e([...t,i]);if(i===es){if(t.length<2){let e=["api",...t].join(".");throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${e}\``)}let e=t.slice(0,-1).join("/"),s=t[t.length-1];return"default"===s?e:e+":"+s}return i===Symbol.toStringTag?"FunctionReference":void 0}})}();var er=Object.defineProperty,eo=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?er(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class ea{constructor(e){eo(this,"queryResults"),eo(this,"modifiedQueries"),this.queryResults=e,this.modifiedQueries=[]}getQuery(e,...t){let s=y(t[0]),i=en(e),n=this.queryResults.get(J(i,s));if(void 0!==n)return ea.queryValue(n.result)}getAllQueries(e){let t=[],s=en(e);for(let e of this.queryResults.values())e.udfPath===H(s)&&t.push({args:e.args,value:ea.queryValue(e.result)});return t}setQuery(e,t,s){let i=y(t),n=en(e),r=J(n,i);this.queryResults.set(r,{udfPath:n,args:i,result:void 0===s?void 0:{success:!0,value:s,logLines:[]}}),this.modifiedQueries.push(r)}static queryValue(e){return void 0===e?void 0:e.success?e.value:void 0}}class eu{constructor(){eo(this,"queryResults"),eo(this,"optimisticUpdates"),this.queryResults=new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let s=this.queryResults;this.queryResults=new Map(e);let i=new ea(this.queryResults);for(let e of this.optimisticUpdates)e.update(i);let n=[];for(let[e,t]of this.queryResults){let i=s.get(e);(void 0===i||i.result!==t.result)&&n.push(e)}return n}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let s=new ea(this.queryResults);return e(s),s.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(void 0!==t)return t.result}queryResult(e){let t=this.queryResults.get(e);if(void 0===t)return;let s=t.result;if(void 0!==s){if(s.success)return s.value;if(void 0!==s.errorData)throw K(s,new V(W("query",t.udfPath,s)));throw Error(W("query",t.udfPath,s))}}hasQueryResult(e){return void 0!==this.queryResults.get(e)}queryLogs(e){let t=this.queryResults.get(e);return t?.result?.logLines}}var eh=Object.defineProperty,el=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eh(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class ec{constructor(e,t){el(this,"low"),el(this,"high"),el(this,"__isUnsignedLong__"),this.low=0|e,this.high=0|t,this.__isUnsignedLong__=!0}static isLong(e){return!0===(e&&e.__isUnsignedLong__)}static fromBytesLE(e){return new ec(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(e){return isNaN(e)||e<0?ed:e>=ef?ey:new ec(e%eg|0,e/eg|0)}toString(){return(BigInt(this.high)*BigInt(eg)+BigInt(this.low)).toString()}equals(e){return ec.isLong(e)||(e=ec.fromValue(e)),(this.high>>>31!=1||e.high>>>31!=1)&&this.high===e.high&&this.low===e.low}notEquals(e){return!this.equals(e)}comp(e){return(ec.isLong(e)||(e=ec.fromValue(e)),this.equals(e))?0:e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return 0>=this.comp(e)}static fromValue(e){return"number"==typeof e?ec.fromNumber(e):new ec(e.low,e.high)}}let ed=new ec(0,0),eg=0x100000000,ef=0xffffffffffffffff,ey=new ec(-1,-1);var ep=Object.defineProperty,em=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ep(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class ev{constructor(e,t){em(this,"version"),em(this,"remoteQuerySet"),em(this,"queryPath"),em(this,"logger"),this.version={querySet:0,ts:ec.fromNumber(0),identity:0},this.remoteQuerySet=new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case"QueryUpdated":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)j(this.logger,"info","query",e,s);let s=I(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:s,logLines:t.logLines});break}case"QueryFailed":{let e=this.queryPath(t.queryId);if(e)for(let s of t.logLines)j(this.logger,"info","query",e,s);let{errorData:s}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:void 0!==s?I(s):void 0,logLines:t.logLines});break}case"QueryRemoved":this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}}function eb(e){let t=g(e);return ec.fromBytesLE(Array.from(t))}function eS(e){switch(e.type){case"FatalError":case"AuthError":case"ActionResponse":case"TransitionChunk":case"Ping":return{...e};case"MutationResponse":if(e.success)return{...e,ts:eb(e.ts)};return{...e};case"Transition":return{...e,startVersion:{...e.startVersion,ts:eb(e.startVersion.ts)},endVersion:{...e.endVersion,ts:eb(e.endVersion.ts)}}}}var ek=Object.defineProperty,ew=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?ek(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};function eR(){return(void 0===i&&(i=Date.now()),"u"<typeof performance||!performance.now)?Date.now():Math.round(i+performance.now())}function eC(){return`t=${Math.round((eR()-i)/100)/10}s`}let eT={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};class eA{constructor(e,t,s,i,n,r){this.markConnectionStateDirty=n,this.debug=r,ew(this,"socket"),ew(this,"connectionCount"),ew(this,"_hasEverConnected",!1),ew(this,"lastCloseReason"),ew(this,"transitionChunkBuffer",null),ew(this,"defaultInitialBackoff"),ew(this,"maxBackoff"),ew(this,"retries"),ew(this,"serverInactivityThreshold"),ew(this,"reconnectDueToServerInactivityTimeout"),ew(this,"scheduledReconnect",null),ew(this,"networkOnlineHandler",null),ew(this,"pendingNetworkRecoveryInfo",null),ew(this,"uri"),ew(this,"onOpen"),ew(this,"onResume"),ew(this,"onMessage"),ew(this,"webSocketConstructor"),ew(this,"logger"),ew(this,"onServerDisconnectError"),this.webSocketConstructor=s,this.socket={state:"disconnected"},this.connectionCount=0,this.lastCloseReason="InitialConnect",this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=i,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){"u"<typeof window||"function"!=typeof window.addEventListener||null===this.networkOnlineHandler&&(this.networkOnlineHandler=()=>{this._logVerbose("network online event detected"),this.tryReconnectImmediately()},window.addEventListener("online",this.networkOnlineHandler),this._logVerbose("network online event listener registered"))}cleanupNetworkListener(){this.networkOnlineHandler&&"u">typeof window&&"function"==typeof window.removeEventListener&&(window.removeEventListener("online",this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose("network online event listener removed"))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||0===e.totalParts||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error("Invalid TransitionChunk");if(null===this.transitionChunkBuffer&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join("");this.transitionChunkBuffer=null;let t=eS(JSON.parse(e));if("Transition"!==t.type)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if("terminated"===this.socket.state)return;if("disconnected"!==this.socket.state&&"stopped"!==this.socket.state)throw Error("Didn't start connection from disconnected state: "+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose("constructed WebSocket"),this.setSocketState({state:"connecting",ws:e,paused:"no"}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose("begin ws.onopen"),"connecting"!==this.socket.state)throw Error("onopen called with socket not in connecting state");if(this.setSocketState({state:"ready",ws:e,paused:"yes"===this.socket.paused?"uninitialized":"no"}),this.resetServerInactivityTimeout(),"no"===this.socket.paused&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:eR()})),"InitialConnect"!==this.lastCloseReason&&(this.lastCloseReason?this.logger.log("WebSocket reconnected at",eC(),"after disconnect due to",this.lastCloseReason):this.logger.log("WebSocket reconnected at",eC())),this.connectionCount+=1,this.lastCloseReason=null,null!==this.pendingNetworkRecoveryInfo){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:"Event",eventType:"NetworkRecoveryReconnect",event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,s=eS(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${s.type}`),"Ping"!==s.type){if("TransitionChunk"===s.type){let e=this.assembleTransition(s);if(!e)return;s=e,this._logVerbose(`assembled full ws message of type ${s.type}`)}null!==this.transitionChunkBuffer&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${s.type} while buffering TransitionChunks`)),"Transition"===s.type&&this.reportLargeTransition({messageLength:t,transition:s}),this.onMessage(s).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose("begin ws.onclose"),this.transitionChunkBuffer=null,null===this.lastCloseReason&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),1e3!==e.code&&1001!==e.code&&1005!==e.code&&4040!==e.code){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=function(e){if(void 0===e)return"Unknown";for(let t of Object.keys(eT))if(e.startsWith(t))return t;return"Unknown"}(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,..."Authenticate"===e.type&&"User"===e.tokenType?{value:`...${e.value.slice(-7)}`}:{}};if("ready"===this.socket.state&&"no"===this.socket.paused){let s=JSON.stringify(function(e){switch(e.type){case"Authenticate":case"ModifyQuerySet":case"Mutation":case"Action":case"Event":return{...e};case"Connect":if(void 0===e.maxObservedTimestamp)return{...e,maxObservedTimestamp:void 0};return{...e,maxObservedTimestamp:f(new Uint8Array(e.maxObservedTimestamp.toBytesLE()))}}}(e)),i=!1;try{this.socket.ws.send(s),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect("FailedToSendMessage")}return this._logVerbose(`${i?"sent":"failed to send"} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${"paused"in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){"terminated"!==this.socket.state&&(null!==this.reconnectDueToServerInactivityTimeout&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect("InactiveServer")},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:"disconnected"};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let s=eR(),i=setTimeout(()=>{this.scheduledReconnect?.timeout===i&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:i,scheduledAt:s,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case"disconnected":case"terminated":case"stopped":return;case"connecting":case"ready":this.lastCloseReason=e,this.close(),this.scheduleReconnect("client");return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case"disconnected":case"terminated":case"stopped":return Promise.resolve();case"connecting":{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose("Ignoring message received after close")},new Promise(t=>{e.onclose=()=>{this._logVerbose("Closed after connecting"),t()},e.onopen=()=>{this._logVerbose("Opened after connecting"),e.close()}})}case"ready":{this._logVerbose("ws.close called");let e=this.socket.ws;e.onmessage=e=>{this._logVerbose("Ignoring message received after close")};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case"terminated":case"stopped":case"disconnected":case"connecting":case"ready":{let e=this.close();return this.setSocketState({state:"terminated"}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case"terminated":return Promise.resolve();case"connecting":case"stopped":case"disconnected":case"ready":{this.cleanupNetworkListener();let e=this.close();return this.socket={state:"stopped"},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case"stopped":break;case"terminated":case"connecting":case"ready":case"disconnected":this.logger.logVerbose("Restart called without stopping first");return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case"disconnected":case"stopped":case"terminated":return;case"connecting":case"ready":this.socket={...this.socket,paused:"yes"};return;default:return void this.socket}}tryReconnectImmediately(){if(this._logVerbose("tryReconnectImmediately called"),"disconnected"!==this.socket.state)return void this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);let e=null;if(this.scheduledReconnect){let t=eR()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose("canceled scheduled reconnect")}this.logger.log("Network recovery detected, reconnecting immediately"),this.pendingNetworkRecoveryInfo=null!==e?{timeSavedMs:e}:null,this.connect()}resume(){switch(this.socket.state){case"connecting":this.socket={...this.socket,paused:"no"};return;case"ready":"uninitialized"===this.socket.paused?(this.socket={...this.socket,paused:"no"},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:eR()})):"yes"===this.socket.paused&&(this.socket={...this.socket,paused:"no"},this.onResume());return;case"terminated":case"stopped":case"disconnected":return;default:this.socket}this.connect()}connectionState(){return{isConnected:"ready"===this.socket.state,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=("client"===e?100:"Unknown"===e?this.defaultInitialBackoff:eT[e].timeout)*Math.pow(2,this.retries);this.retries+=1;let s=Math.min(t,this.maxBackoff),i=s*(Math.random()-.5);return s+i}reportLargeTransition({transition:e,messageLength:t}){if(void 0===e.clientClockSkew||void 0===e.serverTs)return;let s=eR()-e.clientClockSkew-e.serverTs/1e6,i=`${Math.round(s)}ms`,n=`${Math.round(t/1e4)/100}MB`,r=t/(s/1e3),o=`${Math.round(r/1e4)/100}MB per second`;this._logVerbose(`received ${n} transition in ${i} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${n}) which will take a long time to download on slower connections`):s>2e4&&this.logger.log(`received query results totaling ${n} which took more than 20s to arrive (${i})`),this.debug&&this.sendMessage({type:"Event",eventType:"ClientReceivedTransition",event:{transitionTransitTime:s,messageLength:t}})}}class eq extends Error{}function eM(e,t){let s;if("string"!=typeof e)throw new eq("Invalid token specified: must be a string");t||(t={});let i=+(!0!==t.header),n=e.split(".")[i];if("string"!=typeof n)throw new eq(`Invalid token specified: missing part #${i+1}`);try{s=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw Error("base64 string is not of the correct length")}try{var s;return s=t,decodeURIComponent(atob(s).replace(/(.)/g,(e,t)=>{let s=t.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}catch{return atob(t)}}(n)}catch(e){throw new eq(`Invalid token specified: invalid base64 for part #${i+1} (${e.message})`)}try{return JSON.parse(s)}catch(e){throw new eq(`Invalid token specified: invalid json for part #${i+1} (${e.message})`)}}eq.prototype.name="InvalidTokenError";var eI=Object.defineProperty,e$=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eI(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eQ{constructor(e,t,s){e$(this,"authState",{state:"noAuth"}),e$(this,"configVersion",0),e$(this,"syncState"),e$(this,"authenticate"),e$(this,"stopSocket"),e$(this,"tryRestartSocket"),e$(this,"pauseSocket"),e$(this,"resumeSocket"),e$(this,"clearAuth"),e$(this,"logger"),e$(this,"refreshTokenLeewaySeconds"),e$(this,"initialAuthTokenReuse"),e$(this,"lastRefreshChange"),e$(this,"tokenConfirmationAttempts",0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=s.logger,this.refreshTokenLeewaySeconds=s.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=s.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){"noAuth"!==this.authState.state&&"initialRefetch"!==this.authState.state&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,s){this.resetAuthState(),this._logVerbose("pausing WS for auth token fetch"),this.pauseSocket();let i=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(i.isFromOutdatedConfig)return;let n={fetchToken:e,onAuthChange:t,onRefreshChange:s};i.value?(this.setAuthState({state:"waitingForServerConfirmationOfCachedToken",config:n,hasRetried:!1}),this.authenticate(i.value)):(this.setAuthState({state:"initialRefetch",config:n}),await this.refetchToken()),this._logVerbose("resuming WS after auth token fetch"),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),"waitingForServerConfirmationOfCachedToken"===this.authState.state){this._logVerbose("server confirmed auth token is valid");let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}"waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this._logVerbose("server confirmed new auth token is valid"),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(!1===e.authUpdateAttempted&&("waitingForServerConfirmationOfFreshToken"===this.authState.state||"waitingForServerConfirmationOfCachedToken"===this.authState.state))return void this._logVerbose("ignoring non-auth token expired error");let{baseVersion:t}=e;this.syncState.isCurrentOrNewerAuthVersion(t+1)?this.tryToReauthenticate(e):this._logVerbose("ignoring auth error for previous auth attempt")}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),"noAuth"===this.authState.state||"waitingForServerConfirmationOfFreshToken"===this.authState.state&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),"noAuth"!==this.authState.state&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if("waitingForServerConfirmationOfFreshToken"===this.authState.state&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),"noAuth"===this.authState.state)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",config:this.authState.config,token:t.value,hadAuth:"notRefetching"===this.authState.state||"waitingForScheduledRefetch"===this.authState.state})):(this._logVerbose("reauthentication failed, could not fetch a new token"),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if("noAuth"===this.authState.state)return;this._logVerbose("refetching auth token");let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:"waitingForServerConfirmationOfFreshToken",hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:"notRefetching",config:this.authState.config}):(this._logVerbose("refetching token failed"),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose("restarting WS after auth token fetch (if currently stopped)"),this.tryRestartSocket())}scheduleTokenRefetch(e,t){let s;if("noAuth"===this.authState.state)return;let i=this.decodeToken(e);if(!i)return void this.logger.error("Auth token is not a valid JWT, cannot refetch the token");let{iat:n,exp:r}=i;if(!n||!r)return void this.logger.error("Auth token does not have required fields, cannot refetch the token");let o=r-n;if(o<=2)return void this.logger.error("Auth token does not live long enough, cannot refetch the token");void 0!==t?(s=r-(Date.now()-t)/1e3)<=0&&(s=0):s=o;let a=Math.min(1728e6,(s-this.refreshTokenLeewaySeconds)*1e3);a<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${s}s`),a=0);let u=setTimeout(()=>{this._logVerbose("running scheduled token refetch"),this.refetchToken()},a);this.setAuthState({state:"waitingForScheduledRefetch",refetchTokenTimeoutId:u,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${a}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let s=++this.configVersion;this._logVerbose(`fetching token with config version ${s}`);let i=await e(t);return this.configVersion!==s?(this._logVerbose(`stale config version, expected ${s}, got ${this.configVersion}`),{isFromOutdatedConfig:!0}):{isFromOutdatedConfig:!1,value:i}}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:"noAuth"})}setAuthState(e){let t="waitingForServerConfirmationOfFreshToken"===e.state?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case"waitingForScheduledRefetch":case"notRefetching":case"noAuth":this.tokenConfirmationAttempts=0}"waitingForScheduledRefetch"===this.authState.state&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return eM(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:"Unknown error"}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}}let eO=["convexClientConstructed","convexWebSocketOpen","convexFirstMessageReceived"];function ex(e){let t=e.name.slice(6);return{name:t=t.charAt(0).toLowerCase()+t.slice(1),startTime:e.startTime}}var eE=Object.defineProperty,eP=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eE(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eV{constructor(e,t,s){let i;if(eP(this,"address"),eP(this,"state"),eP(this,"requestManager"),eP(this,"webSocketManager"),eP(this,"authenticationManager"),eP(this,"remoteQuerySet"),eP(this,"optimisticQueryResults"),eP(this,"_transitionHandlerCounter",0),eP(this,"_nextRequestId"),eP(this,"_onTransitionFns",new Map),eP(this,"_sessionId"),eP(this,"firstMessageReceived",!1),eP(this,"debug"),eP(this,"logger"),eP(this,"maxObservedTimestamp"),eP(this,"connectionStateSubscribers",new Map),eP(this,"nextConnectionStateSubscriberId",0),eP(this,"_lastPublishedConnectionState"),eP(this,"markConnectionStateDirty",()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState))for(let t of(this._lastPublishedConnectionState=e,this.connectionStateSubscribers.values()))t(e)})}),eP(this,"mark",e=>{var t;this.debug&&(t=this.sessionId,"u">typeof performance&&performance.mark&&performance.mark(e,{detail:{sessionId:t}}))}),"object"==typeof e)throw Error("Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.");s?.skipConvexDeploymentUrlCheck!==!0&&function(e){if(void 0===e)throw Error("Client created with undefined deployment address. If you used an environment variable, check that it's set.");if("string"!=typeof e)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith("http:")||e.startsWith("https:")))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(".convex.site"))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}(e);const n=(s={...s}).authRefreshTokenLeewaySeconds??10;let r=s.webSocketConstructor;if(!r&&"u"<typeof WebSocket)throw Error("No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient");r=r||WebSocket,this.debug=s.reportDebugInfoToConvex??!1,this.address=e,this.logger=!1===s.logger?function(e){return new U(e)}({verbose:s.verbose??!1}):!0!==s.logger&&s.logger?s.logger:D({verbose:s.verbose??!1});const o=e.search("://");if(-1===o)throw Error("Provided address was not an absolute URL.");const a=e.substring(o+3),u=e.substring(0,o);if("http"===u)i="ws";else if("https"===u)i="wss";else throw Error(`Unknown parent protocol ${u}`);const h=`${i}://${a}/api/${_}/sync`;this.state=new Y,this.remoteQuerySet=new ev(e=>this.state.queryPath(e),this.logger),this.requestManager=new et(this.logger,this.markConnectionStateDirty);const l=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new eQ(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:l,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:n,initialAuthTokenReuse:s.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new eu,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)});const{unsavedChangesWarning:c}=s;if("u"<typeof window||void 0===window.addEventListener){if(!0===c)throw Error("unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.")}else!1!==c&&window.addEventListener("beforeunload",e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t="Are you sure you want to leave? Your changes may not be saved.";return(e||window.event).returnValue=t,t}});this.webSocketManager=new eA(h,{onOpen:e=>{this.mark("convexWebSocketOpen"),this.webSocketManager.sendMessage({...e,type:"Connect",sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new ev(e=>this.state.queryPath(e),this.logger);let[t,s]=this.state.restart();for(let e of(s&&this.webSocketManager.sendMessage(s),this.webSocketManager.sendMessage(t),this.requestManager.restart()))this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();for(let s of(t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e),this.requestManager.resume()))this.webSocketManager.sendMessage(s)},onMessage:e=>{switch(!this.firstMessageReceived&&(this.firstMessageReceived=!0,this.mark("convexFirstMessageReceived"),this.reportMarks()),e.type){case"Transition":{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case"MutationResponse":{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);null!==t&&this.notifyOnQueryResultChanges(new Map([[t.requestId,t.result]]));break}case"ActionResponse":this.requestManager.onResponse(e);break;case"AuthError":this.authenticationManager.onAuthError(e);break;case"FatalError":{var t,s;let i,n=(t=this.logger,s=e.error,i=`[CONVEX FATAL ERROR] ${s}`,t.error(i),Error(i));throw this.webSocketManager.terminate(),n}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:s.onServerDisconnectError},r,this.logger,this.markConnectionStateDirty,this.debug),this.mark("convexClientConstructed"),s.expectAuth&&l()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(void 0===this.maxObservedTimestamp||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),s=new Map;for(let[e,i]of t){let t=this.state.queryToken(e);if(null!==t){let n={result:i,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};s.set(t,n)}}let i=this.optimisticQueryResults.ingestQueryResultsFromServer(s,new Set(e.keys()));this.handleTransition({queries:i.map(e=>{let t=this.optimisticQueryResults.rawQueryResult(e);return{token:e,modification:{kind:"Updated",result:t}}}),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&"User"===e.tokenType){try{t=e?eM(e.value):{}}catch{t={}}return{token:e.value,decoded:t}}}setAuth(e,t,s){this.authenticationManager.setConfig(e,t,s)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let s=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(s)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,s){let i=y(t),{modification:n,queryToken:r,unsubscribe:o}=this.state.subscribe(e,i,s?.journal,s?.componentPath);return null!==n&&this.webSocketManager.sendMessage(n),{queryToken:r,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let s=J(e,y(t));return this.optimisticQueryResults.queryResult(s)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let s=J(e,y(t));return this.optimisticQueryResults.queryLogs(s)}queryJournal(e,t){let s=J(e,y(t));return this.state.queryJournal(s)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,s){let i=await this.mutationInternal(e,t,s);if(!i.success){if(void 0!==i.errorData)throw K(i,new V(W("mutation",e,i)));throw Error(W("mutation",e,i))}return i.value}async mutationInternal(e,t,s,i){let{mutationPromise:n}=this.enqueueMutation(e,t,s,i);return n}enqueueMutation(e,t,s,i){let n=y(t);this.tryReportLongDisconnect();let r=this.nextRequestId;if(this._nextRequestId++,void 0!==s){let e=s.optimisticUpdate;if(void 0!==e){let t=t=>{e(t,n)instanceof Promise&&this.logger.warn("Optimistic update handler returned a Promise. Optimistic updates should be synchronous.")},s=this.optimisticQueryResults.applyOptimisticUpdate(t,r).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:"Updated",result:void 0===t?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:s,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:"Mutation",requestId:r,udfPath:e,componentPath:i,args:[O(n)]},a=this.webSocketManager.sendMessage(o);return{requestId:r,mutationPromise:this.requestManager.request(o,a)}}async action(e,t){let s=await this.actionInternal(e,t);if(!s.success){if(void 0!==s.errorData)throw K(s,new V(W("action",e,s)));throw Error(W("action",e,s))}return s.value}async actionInternal(e,t,s){let i=y(t),n=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let r={type:"Action",requestId:n,udfPath:e,componentPath:s,args:[O(i)]},o=this.webSocketManager.sendMessage(r);return this.requestManager.request(r,o)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let e=function(e){if("u"<typeof performance||!performance.getEntriesByName)return[];let t=[];for(let s of eO){let i=performance.getEntriesByName(s).filter(e=>"mark"===e.entryType).filter(t=>t.detail.sessionId===e);t.push(...i)}return t.map(ex)}(this.sessionId);this.webSocketManager.sendMessage({type:"Event",eventType:"ClientConnect",event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;null===e||Date.now()-e.getTime()<=6e4||fetch(`${this.address}/api/debug_event`,{method:"POST",headers:{"Content-Type":"application/json","Convex-Client":`npm-${_}`},body:JSON.stringify({event:"LongWebsocketDisconnect"})}).then(e=>{e.ok||this.logger.warn("Analytics request failed with response:",e.body)}).catch(e=>{this.logger.warn("Analytics response failed with error:",e)})}}function eL(e){if("object"!=typeof e||null===e||!Array.isArray(e.page)||"boolean"!=typeof e.isDone||"string"!=typeof e.continueCursor)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var e_=Object.defineProperty,eN=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?e_(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};class eF{constructor(e,t){this.client=e,this.onTransition=t,eN(this,"paginatedQuerySet",new Map),eN(this,"lastTransitionTs"),this.lastTransitionTs=ec.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,s){let i=H(e),n=z(i,t,s),r=()=>this.removePaginatedQuerySubscriber(n),o=this.paginatedQuerySet.get(n);return o?o.numSubscribers+=1:(this.paginatedQuerySet.set(n,{token:n,canonicalizedUdfPath:i,args:t,numSubscribers:1,options:{initialNumItems:s.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:new Map,ongoingSplits:new Map,skip:!1,id:s.id}),this.addPageToPaginatedQuery(n,null,s.initialNumItems)),{paginatedQueryToken:n,unsubscribe:r}}localQueryResult(e,t,s){let i=z(H(e),t,s);return this.localQueryResultByToken(i)}localQueryResultByToken(e){let t,s=this.paginatedQuerySet.get(e);if(!s)return;let i=this.activePageQueryTokens(s);if(0===i.length)return{results:[],status:"LoadingFirstPage",loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let n=[],r=!1,o=!1;for(let e of i){let t=this.client.localQueryResultByToken(e);if(void 0===t){r=!0,o=!1;continue}let s=eL(t);n=n.concat(s.page),o=!!s.isDone}return t=r?0===n.length?"LoadingFirstPage":"LoadingMore":o?"Exhausted":"CanLoadMore",{results:n,status:t,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),s=this.queriesContainingTokens(t),i=[];s.length>0&&(this.processPaginatedQuerySplits(s,e=>this.client.localQueryResultByToken(e)),i=s.map(e=>({token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}})));let n={...e,paginatedQueries:i};this.onTransition(n)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let s=this.queryTokenForLastPageOfPaginatedQuery(e),i=this.client.localQueryResultByToken(s);if(!i)return!1;let n=eL(i);if(n.isDone)return!1;this.addPageToPaginatedQuery(e,n.continueCursor,t);let r={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:"Updated",result:this.localQueryResultByToken(e)}}]};return this.onTransition(r),!0}queriesContainingTokens(e){if(0===e.length)return[];let t=[],s=new Set(e);for(let[e,i]of this.paginatedQuerySet)for(let n of this.allQueryTokens(i))if(s.has(n)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let s of e){let e=this.mustGetPaginatedQuery(s),{ongoingSplits:i,pageKeyToQuery:n,pageKeys:r}=e;for(let[s,[r,o]]of i)void 0!==t(n.get(r).queryToken)&&void 0!==t(n.get(o).queryToken)&&this.completePaginatedQuerySplit(e,s,r,o);for(let s of r){if(i.has(s))continue;let r=n.get(s);if(!r)throw Error(`No page query for active pageKey ${s}`);let o=t(r.queryToken);if(!o)continue;let a=eL(o);a.splitCursor&&("SplitRecommended"===a.pageStatus||"SplitRequired"===a.pageStatus||a.page.length>2*e.options.initialNumItems)&&this.splitPaginatedQueryPage(e,s,r.cursor,a.splitCursor,a.continueCursor)}}}splitPaginatedQueryPage(e,t,s,i,n){let r=e.nextPageKey++,o=e.nextPageKey++,a={numItems:e.options.initialNumItems,id:e.id},u=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:s,endCursor:i}});e.pageKeyToQuery.set(r,{...u,cursor:s});let h=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...a,cursor:i,endCursor:n}});e.pageKeyToQuery.set(o,{...h,cursor:i}),e.ongoingSplits.set(t,[r,o])}addPageToPaginatedQuery(e,t,s){let i=this.mustGetPaginatedQuery(e),n=i.nextPageKey++,r={cursor:t,numItems:s,id:i.id},o={...i.args,paginationOpts:r},a=this.client.subscribe(i.canonicalizedUdfPath,o);return i.pageKeys.push(n),i.pageKeyToQuery.set(n,{...a,cursor:t}),a}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(t.numSubscribers-=1,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,s,i){let n=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let r=e.pageKeys.indexOf(t);e.pageKeys.splice(r,1,s,i),e.ongoingSplits.delete(t),n.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),s=t.pageKeys[t.pageKeys.length-1];if(void 0===s)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(s).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error("paginated query no longer exists for token "+e);return t}}var eB=Object.defineProperty,eU=(e,t,s)=>{let i;return(i="symbol"!=typeof t?t+"":t)in e?eB(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s};if(void 0===o)throw Error("Required dependency 'react' not found");class eD{constructor(e,t){if(eU(this,"address"),eU(this,"cachedSync"),eU(this,"cachedPaginatedQueryClient"),eU(this,"listeners"),eU(this,"options"),eU(this,"closed",!1),eU(this,"_logger"),eU(this,"adminAuth"),eU(this,"fakeUserIdentity"),void 0===e)throw Error("No address provided to ConvexReactClient.\nIf trying to deploy to production, make sure to follow all the instructions found at https://docs.convex.dev/production/hosting/\nIf running locally, make sure to run `convex dev` and ensure the .env.local file is populated.");if("string"!=typeof e)throw Error(`ConvexReactClient requires a URL like 'https://happy-otter-123.convex.cloud', received something of type ${typeof e} instead.`);if(!e.includes("://"))throw Error("Provided address was not an absolute URL.");this.address=e,this.listeners=new Map,this._logger=t?.logger===!1?function(e){return new U(e)}({verbose:t?.verbose??!1}):t?.logger!==!0&&t?.logger?t.logger:D({verbose:t?.verbose??!1}),this.options={...t,logger:this._logger}}get url(){return this.address}get sync(){if(this.closed)throw Error("ConvexReactClient has already been closed.");return this.cachedSync||(this.cachedSync=this.options.baseClient??new eV(this.address,()=>{},this.options),this.adminAuth&&this.cachedSync.setAdminAuth(this.adminAuth,this.fakeUserIdentity),this.cachedPaginatedQueryClient=new eF(this.cachedSync,e=>this.handleTransition(e))),this.cachedSync}get paginatedQueryClient(){if(this.sync,this.cachedPaginatedQueryClient)return this.cachedPaginatedQueryClient;throw Error("Should already be instantiated")}setAuth(e,t,s){if("string"==typeof e)throw Error("Passing a string to ConvexReactClient.setAuth is no longer supported, please upgrade to passing in an async function to handle reauthentication.");this.sync.setAuth(e,t??(()=>{}),s)}clearAuth(){this.sync.clearAuth()}setAdminAuth(e,t){if(this.adminAuth=e,this.fakeUserIdentity=t,this.closed)throw Error("ConvexReactClient has already been closed.");this.cachedSync&&this.sync.setAdminAuth(e,t)}watchQuery(e,...t){let[s,i]=t,n=en(e);return{onUpdate:e=>{let{queryToken:t,unsubscribe:r}=this.sync.subscribe(n,s,i),o=this.listeners.get(t);return void 0!==o?o.add(e):this.listeners.set(t,new Set([e])),()=>{if(this.closed)return;let s=this.listeners.get(t);s.delete(e),0===s.size&&this.listeners.delete(t),r()}},localQueryResult:()=>{if(this.cachedSync)return this.cachedSync.localQueryResult(n,s)},localQueryLogs:()=>{if(this.cachedSync)return this.cachedSync.localQueryLogs(n,s)},journal:()=>{if(this.cachedSync)return this.cachedSync.queryJournal(n,s)}}}prewarmQuery(e){let t=e.extendSubscriptionFor??5e3;setTimeout(this.watchQuery(e.query,e.args||{}).onUpdate(()=>{}),t)}watchPaginatedQuery(e,t,s){let i=en(e);return{onUpdate:e=>{let{paginatedQueryToken:n,unsubscribe:r}=this.paginatedQueryClient.subscribe(i,t||{},s),o=this.listeners.get(n);return void 0!==o?o.add(e):this.listeners.set(n,new Set([e])),()=>{if(this.closed)return;let t=this.listeners.get(n);t.delete(e),0===t.size&&this.listeners.delete(n),r()}},localQueryResult:()=>this.paginatedQueryClient.localQueryResult(i,t,s)}}mutation(e,...t){let[s,i]=t,n=en(e);return this.sync.mutation(n,s,i)}action(e,...t){let s=en(e);return this.sync.action(s,...t)}query(e,...t){let s=this.watchQuery(e,...t),i=s.localQueryResult();return void 0!==i?Promise.resolve(i):new Promise((e,t)=>{let i=s.onUpdate(()=>{i();try{e(s.localQueryResult())}catch(e){t(e)}})})}connectionState(){return this.sync.connectionState()}subscribeToConnectionState(e){return this.sync.subscribeToConnectionState(e)}get logger(){return this._logger}async close(){if(this.closed=!0,this.listeners=new Map,this.cachedPaginatedQueryClient&&(this.cachedPaginatedQueryClient=void 0),this.cachedSync){let e=this.cachedSync;this.cachedSync=void 0,await e.close()}}handleTransition(e){let t=e.queries.map(e=>e.token),s=e.paginatedQueries.map(e=>e.token);this.transition([...t,...s])}transition(e){for(let t of e){let e=this.listeners.get(t);if(e)for(let t of e)t()}}}let ej=o.createContext(void 0),eW=({client:e,children:t})=>o.createElement(ej.Provider,{value:e},t);Symbol("includePageKeys"),Symbol("page"),(0,o.createContext)(void 0)}}]);
@@ -0,0 +1 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[7123],{7412:(e,t,n)=>{"use strict";n.d(t,{L:()=>l});var r=n(95155),a=n(13267),s=n(40980);function l({trailing:e,className:t,...n}){return(0,r.jsxs)("div",{className:(0,s.cn)("flex h-8 items-center gap-1.5 rounded-lg px-2 text-muted-foreground transition-colors focus-within:bg-muted/60 hover:bg-muted/60",t),children:[(0,r.jsx)(a.TfF,{className:"size-3.5 shrink-0"}),(0,r.jsx)("input",{type:"text",spellCheck:!1,autoComplete:"off",...n,className:"h-full min-w-0 flex-1 bg-transparent text-[0.8rem] text-foreground outline-none placeholder:text-muted-foreground"}),e]})}},12860:(e,t,n)=>{Promise.resolve().then(n.bind(n,97173))},15923:(e,t,n)=>{"use strict";n.d(t,{T:()=>a,r:()=>s});let r=new Set;function a(e){return r.add(e),()=>{r.delete(e)}}function s(){for(let e of r)e()}},19065:(e,t,n)=>{"use strict";function r(e,t){if(0===t)return!0;let n=e[t-1];return"_"===n||"-"===n||" "===n||"."===n}function a(e,t,n){return s(e,t,e=>[n(e)])}function s(e,t,n){if(!e.trim())return[];let a=[];for(let s of t){let t=n(s),l=null;for(let n of t){let t=function(e,t){let n=e.trim().toLocaleLowerCase(),a=t.toLocaleLowerCase();if(!n)return 0;if(0===a.length)return null;if(a===n)return 1e4;if(a.startsWith(n))return 5e3-a.length;let s=a.indexOf(n);if(-1!==s)return 2400+1200*!!r(t,s)-s-a.length;let l=0,o=0,i=0;for(let e=0;e<a.length&&l<n.length;e+=1){if(a[e]!==n[l]){i=0;continue}o+=12,(i+=1)>1&&(o+=18*i),r(t,e)&&(o+=40),l+=1}if(l<n.length)return null;let c=t.split(/[_\-\s.]+/).map(e=>e[0]??"").join("").toLocaleLowerCase();return c.startsWith(n)?o+=2200:c.includes(n)&&(o+=700),o-(a.length-n.length)}(e,n);null!==t&&(null===l||t>l)&&(l=t)}null!==l&&a.push({item:s,score:l})}return a.sort((e,t)=>t.score!==e.score?t.score-e.score:n(e.item)[0]?.localeCompare(n(t.item)[0]??"")??0)}n.d(t,{R6:()=>a,UO:()=>s})},23716:(e,t,n)=>{"use strict";n.d(t,{V:()=>o});var r=n(95155),a=n(13267),s=n(72264),l=n(40980);function o({schemas:e,selected:t,onChange:n,compact:i=!1}){let c=null===t||t.length===e.length,u=null===t||t.length===e.length?"All schemas":0===t.length?"No schemas":1===t.length?t[0]:`${t.length} of ${e.length} schemas`;return(0,r.jsxs)(s.rI,{children:[i?(0,r.jsxs)(s.ty,{"aria-label":`Schemas: ${u}`,title:u,className:(0,l.cn)("flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-md px-1 text-[11px] tabular-nums outline-none transition-colors hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 data-open:bg-foreground/10 data-open:text-foreground",c?"text-muted-foreground":"text-foreground"),children:[(0,r.jsx)(a.olY,{className:"size-3.5"}),!c&&(0,r.jsx)("span",{children:t.length})]}):(0,r.jsxs)(s.ty,{className:"group flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg px-2 text-left text-[0.8rem] outline-none transition-colors hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/60 data-open:bg-muted/60",children:[(0,r.jsx)(a.olY,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",children:u}),(0,r.jsx)(a.RQe,{className:"size-3.5 shrink-0 text-muted-foreground transition-transform group-data-open:rotate-180"})]}),(0,r.jsx)(s.SQ,{align:i?"end":"start",sideOffset:6,className:(0,l.cn)("max-h-80 min-w-52",!i&&"w-(--anchor-width)"),children:(0,r.jsxs)(s.I,{children:[(0,r.jsx)(s.hO,{checked:c,onCheckedChange:e=>n(e?null:[]),children:"All schemas"}),(0,r.jsx)(s.mB,{}),e.map(a=>(0,r.jsx)(s.hO,{checked:c||(t?.includes(a)??!1),onCheckedChange:r=>{let s,l;return s=t??e,void n((l=r?[...new Set([...s,a])]:s.filter(e=>e!==a)).length===e.length?null:l)},children:(0,r.jsx)("span",{className:"truncate",children:a})},a))]})})]})}},35942:(e,t,n)=>{"use strict";n.d(t,{F:()=>u});var r=n(95155);n(12115);var a=n(76166),s=n(90839),l=n(84588),o=n(66784),i=n(64084),c=n(40980);function u({className:e,children:t,...n}){return(0,r.jsxs)(a.V,{"data-slot":"scroll-area",className:(0,c.cn)("relative",e),...n,children:[(0,r.jsx)(s.B,{"data-slot":"scroll-area-viewport",className:"size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1",children:t}),(0,r.jsx)(d,{}),(0,r.jsx)(l.I,{})]})}function d({className:e,orientation:t="vertical",...n}){return(0,r.jsx)(o.V,{"data-slot":"scroll-area-scrollbar","data-orientation":t,orientation:t,className:(0,c.cn)("flex touch-none p-px transition-colors select-none data-horizontal:h-2.5 data-horizontal:flex-col data-horizontal:border-t data-horizontal:border-t-transparent data-vertical:h-full data-vertical:w-2.5 data-vertical:border-l data-vertical:border-l-transparent",e),...n,children:(0,r.jsx)(i.l,{"data-slot":"scroll-area-thumb",className:"relative flex-1 rounded-full bg-border"})})}},49393:(e,t,n)=>{"use strict";n.d(t,{g:()=>s});var r=n(1934),a=n(31692);let s=(0,r.v)()((0,a.Zr)(e=>({tabView:!1,setTabView:t=>e({tabView:t})}),{name:"ytdb:preferences",partialize:e=>({tabView:e.tabView})}))},79781:(e,t,n)=>{"use strict";n.d(t,{$C:()=>u,yG:()=>d});var r=n(73321),a=n(12115),s=n(27529),l=n(15923),o=n(20185),i=n(69586),c=n(36331);function u(){let e=(0,r.useRouter)(),t=(0,r.usePathname)(),{connection:n}=(0,c.k)(),u=(0,i.Z)(e=>e.connections);return(0,a.useCallback)(async r=>{if(r===n.id)return;let a=u.find(e=>e.id===r);if(!a)return;(0,l.r)();let i=(0,o.ZG)(t),c=!!n.layoutGroup&&n.layoutGroup===a.layoutGroup,d=!0;if("table"===i.kind&&!c)try{var m,f;m=await s.F.tables(a.url),f=i.table,d=m.some(e=>e.schema===f.schema&&e.name===f.name)}catch{d=!1}e.push((0,o.gZ)(t,r,{tableExists:d}))},[n.id,n.layoutGroup,u,t,e])}function d(){let{connection:e}=(0,c.k)(),t=(0,i.Z)(e=>e.connections),n=u(),r=function(e,t){let n=e.findIndex(e=>e.id===t);if(!(e.length<2)&&-1!==n)return e[(n+1)%e.length]}(t,e.id);return{run:()=>r?n(r.id):Promise.resolve(),enabled:void 0!==r,next:r}}},86846:(e,t,n)=>{"use strict";n.d(t,{E:()=>s});var r=n(95155),a=n(40980);function s({className:e,...t}){return(0,r.jsx)("div",{"data-slot":"skeleton",className:(0,a.cn)("animate-pulse rounded-md bg-muted",e),...t})}},97173:(e,t,n)=>{"use strict";n.d(t,{ExplorerShell:()=>ei});var r=n(95155),a=n(98500),s=n.n(a),l=n(13267),o=n(89239),i=n(95377),c=n(69586),u=n(40544),d=n(49393),m=n(32538),f=n(36331),h=n(73321),p=n(12115),x=n(35942),g=n(7412),b=n(86846),w=n(43262),v=n(95848),y=n(40980),j=n(72264),k=n(72194),N=n(79781);function C({current:e}){let t=(0,c.Z)(e=>e.connections),n=(0,N.$C)();return(0,r.jsxs)(j.rI,{children:[(0,r.jsxs)(j.ty,{className:"flex h-8 w-full items-center justify-between gap-2 rounded-lg px-2 text-left font-medium outline-none hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 data-open:bg-muted/60",children:[(0,r.jsxs)("span",{className:"flex min-w-0 items-center gap-2",children:[(0,r.jsx)(k.F,{connection:e}),(0,r.jsx)("span",{className:"truncate",children:e.name}),e.layoutGroup&&(0,r.jsx)(l.WnQ,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,r.jsx)(l.klM,{className:"size-3.5 shrink-0 text-muted-foreground"})]}),(0,r.jsxs)(j.SQ,{align:"start",className:"w-(--anchor-width)",children:[t.map(t=>(0,r.jsxs)(j._2,{onClick:()=>void n(t.id),className:t.id===e.id?"font-medium":void 0,children:[(0,r.jsx)(k.F,{connection:t}),(0,r.jsx)("span",{className:"min-w-0 flex-1 truncate",children:t.name}),t.layoutGroup&&t.layoutGroup===e.layoutGroup&&(0,r.jsx)(l.WnQ,{className:"size-3.5 shrink-0 text-muted-foreground"})]},t.id)),(0,r.jsx)(j.mB,{}),(0,r.jsx)(j._2,{render:(0,r.jsx)(s(),{href:"/"}),children:"Manage connections"})]})]})}var S=n(23716);function T(e,t){let n=e.trim(),r=n.lastIndexOf(".");return -1===r?n:"schema"===t?n.slice(0,r):n.slice(r+1)}function E({text:e,query:t}){if(!t)return e;let n=[],a=e.toLocaleLowerCase(),s=t.toLocaleLowerCase(),l=0,o=a.indexOf(s);if(-1===o)return e;for(;-1!==o;)o>l&&n.push(e.slice(l,o)),n.push((0,r.jsx)("mark",{className:"rounded-[3px] bg-yellow-300/90 px-px text-yellow-950 dark:bg-yellow-400/85 dark:text-yellow-950",children:e.slice(o,o+t.length)},o)),l=o+t.length,o=a.indexOf(s,l);return l<e.length&&n.push(e.slice(l)),n}function z({connectionId:e,table:t,search:n,pinned:a,showSchema:o,active:i,reorderable:c,dragging:u,dropEdge:d,onTogglePin:m,onDragStart:f,onDragOver:h,onDrop:p,onDragEnd:x,onMove:g}){return(0,r.jsxs)("li",{onDragOver:h,onDrop:p,className:(0,y.cn)("group/table-row relative flex h-7 items-center rounded-md text-[13px] transition-[color,background-color,opacity] hover:bg-muted/60",i&&"bg-muted text-foreground",!i&&"text-foreground/80",u&&"opacity-45","before"===d&&"before:absolute before:inset-x-1 before:top-0 before:z-10 before:h-0.5 before:-translate-y-1/2 before:rounded-full before:bg-primary","after"===d&&"after:absolute after:inset-x-1 after:bottom-0 after:z-10 after:h-0.5 after:translate-y-1/2 after:rounded-full after:bg-primary"),children:[c&&(0,r.jsx)("button",{type:"button",draggable:!0,"aria-label":`Reorder ${t.schema}.${t.name}`,title:"Drag to reorder; use Up and Down arrow keys",onDragStart:f,onDragEnd:x,onKeyDown:e=>{("ArrowUp"===e.key||"ArrowDown"===e.key)&&(e.preventDefault(),g?.("ArrowUp"===e.key?-1:1))},className:"ml-1.5 flex size-5 shrink-0 cursor-grab touch-none items-center justify-center rounded text-muted-foreground opacity-50 outline-none transition-[color,background-color,opacity] hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:opacity-100 active:cursor-grabbing",children:(0,r.jsx)(l.Mvf,{className:"size-3.5"})}),(0,r.jsxs)(s(),{href:`/${e}/${encodeURIComponent(t.schema)}/${encodeURIComponent(t.name)}`,className:(0,y.cn)("flex h-full min-w-0 flex-1 items-center gap-1.5 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/60",c?"pl-1":"pl-6"),children:[(0,r.jsx)("span",{className:"truncate",children:(0,r.jsx)(E,{text:t.name,query:T(n,"table")})}),o?(0,r.jsx)("span",{className:"ml-auto max-w-20 truncate text-[10px] text-muted-foreground",children:t.schema}):"view"===t.kind&&(0,r.jsx)("span",{className:"ml-auto text-[10px] text-muted-foreground",children:"view"})]}),(0,r.jsx)("button",{type:"button","aria-label":`${a?"Unpin":"Pin"} ${t.schema}.${t.name}`,"aria-pressed":a,title:a?"Unpin table":"Pin table",onClick:()=>m(t),className:(0,y.cn)("mr-0.5 flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground opacity-0 outline-none transition-[color,background-color,opacity] hover:bg-foreground/10 hover:text-foreground hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:opacity-100 group-hover/table-row:opacity-100",a&&"text-foreground"),children:a?(0,r.jsx)(l.M0d,{className:"size-3.5"}):(0,r.jsx)(l.rq5,{className:"size-3.5"})})]})}function $({label:e,count:t,collapsed:n,pinned:a,search:s,onToggle:o}){return(0,r.jsxs)("button",{type:"button","aria-expanded":!n,onClick:o,className:"flex h-7 w-full cursor-pointer items-center gap-1 rounded-md px-1 text-xs font-medium text-muted-foreground outline-none transition-colors hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60",children:[(0,r.jsx)(l.nNJ,{className:(0,y.cn)("size-3.5 transition-transform",!n&&"rotate-90")}),a&&(0,r.jsx)(l.M0d,{className:"mr-0.5 size-3"}),(0,r.jsx)("span",{className:"truncate",children:a?e:(0,r.jsx)(E,{text:e,query:T(s,"schema")})}),(0,r.jsx)("span",{className:"ml-auto pr-1 tabular-nums opacity-60",children:t})]})}function D({connectionId:e,tables:t,search:n,collapsedSchemas:a,pinnedTables:s,onToggleSchema:l,onTogglePin:o,onReorderPinned:i}){let c=(0,h.useParams)(),[u,d]=(0,p.useState)(!1),[m,f]=(0,p.useState)(null),[x,g]=(0,p.useState)(null),b=new Map(t.map(e=>[(0,v.i)(e),e])),w=s.flatMap(e=>{let t=b.get(e);return t?[t]:[]});function y(){f(null),g(null)}return 0===t.length?(0,r.jsx)("p",{className:"px-3 py-8 text-center text-xs text-muted-foreground",children:n.trim()?"No tables match your search":"No tables in these schemas"}):(0,r.jsxs)("div",{className:"flex flex-col gap-1 px-2 pb-4",children:[w.length>0&&(0,r.jsxs)("div",{className:"mb-1 border-b border-border/60 pb-1",children:[(0,r.jsx)($,{label:"Pinned tables",count:w.length,collapsed:u,pinned:!0,search:n,onToggle:()=>d(e=>!e)}),!u&&(0,r.jsx)("ul",{children:w.map(t=>{let a=(0,v.i)(t);return(0,r.jsx)(z,{connectionId:e,table:t,search:n,pinned:!0,showSchema:!0,active:c.schema===t.schema&&c.table===t.name,reorderable:!0,dragging:m===a,dropEdge:x?.key===a?x.edge:null,onTogglePin:o,onDragStart:e=>{e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/plain",a),f(a),g(null)},onDragOver:e=>(function(e,t){if(!m||m===t)return;e.preventDefault(),e.dataTransfer.dropEffect="move";let n=e.currentTarget.getBoundingClientRect(),r=e.clientY<n.top+n.height/2?"before":"after";g(e=>e?.key===t&&e.edge===r?e:{key:t,edge:r})})(e,a),onDrop:e=>{let t,n;return e.preventDefault(),t=m??e.dataTransfer.getData("text/plain"),n=x?.key===a?x.edge:"before",void(t&&i(t,a,n),y())},onDragEnd:y,onMove:e=>{let t,n;return t=w.findIndex(e=>(0,v.i)(e)===a),void((n=w[t+e])&&i(a,(0,v.i)(n),-1===e?"before":"after"))}},a)})})]}),(function(e){let t=new Map;for(let n of e)t.set(n.schema,[...t.get(n.schema)??[],n]);return[...t.entries()].sort(([e],[t])=>{let n;return((n=new Map([["public",0],["auth",1]])).get(e)??2)-(n.get(t)??2)||e.localeCompare(t)})})(t).map(([t,i])=>{let u=a.includes(t);return(0,r.jsxs)("div",{children:[(0,r.jsx)($,{label:t,count:i.length,collapsed:u,search:n,onToggle:()=>l(t)}),!u&&(0,r.jsx)("ul",{children:i.map(t=>(0,r.jsx)(z,{connectionId:e,table:t,search:n,pinned:s.includes((0,v.i)(t)),active:c.schema===t.schema&&c.table===t.name,onTogglePin:o},(0,v.i)(t)))})]},t)})]})}function L(e){return Math.min(480,Math.max(180,Math.round(e)))}function R(e,t){let n=new Map([["public",0],["auth",1]]);return(n.get(e)??2)-(n.get(t)??2)||e.localeCompare(t)}function I(e,t,n){let r=t.trim().toLocaleLowerCase();return e.filter(e=>(null===n||!!n.includes(e.schema))&&(!r||e.name.toLocaleLowerCase().includes(r)||`${e.schema}.${e.name}`.toLocaleLowerCase().includes(r)))}function M({href:e,active:t,shortcut:n,children:a}){return(0,r.jsxs)(s(),{href:e,"aria-current":t?"page":void 0,className:(0,y.cn)((0,o.r)({variant:t?"secondary":"ghost",size:"sm"}),"h-8 w-full justify-start px-2"),children:[a,(0,r.jsx)("kbd",{className:"ml-auto font-mono text-[10px] text-muted-foreground/55",children:n})]})}function A({width:e,onWidthChange:t,onCollapse:n}){let a=(0,h.usePathname)(),{connection:s,tables:i}=(0,f.k)(),[d,m]=(0,u.DE)(s.id),y=(0,c.Z)(e=>e.connections.length>1),[j,k]=(0,p.useState)(()=>L(e)),N=(0,p.useRef)(null),T=(0,p.useMemo)(()=>[...new Set((i.data??[]).map(e=>e.schema))].sort(R),[i.data]),E=(0,p.useMemo)(()=>null===d.selectedSchemas?null:d.selectedSchemas.filter(e=>T.includes(e)),[d.selectedSchemas,T]),z=(0,p.useMemo)(()=>I(i.data??[],d.search,E),[i.data,d.search,E]),$=`/${encodeURIComponent(s.id)}`,U=`${$}/query`,O=`${$}/diff`,P=`${$}/migrations`;function K(e,t){let n=new Set(I(i.data??[],e,t).map(e=>e.schema));return d.collapsedSchemas.filter(e=>!n.has(e))}return(0,r.jsxs)("aside",{id:"database-explorer-sidebar",style:{width:j},className:"relative flex h-full shrink-0 flex-col border-r bg-sidebar",children:[(0,r.jsxs)("div",{className:"flex flex-col gap-0.5 border-b border-sidebar-border/60 p-2",children:[(0,r.jsxs)("div",{className:"mb-1 flex items-center gap-1",children:[(0,r.jsx)("div",{className:"min-w-0 flex-1",children:(0,r.jsx)(C,{current:s})}),(0,r.jsx)(o.$,{variant:"ghost",size:"icon-sm","aria-label":"Collapse database sidebar",title:"Collapse sidebar",onClick:n,children:(0,r.jsx)(l.cFu,{})})]}),(0,r.jsxs)(M,{href:U,active:a===U,shortcut:w.Ar.sqlEditor,children:[(0,r.jsx)(l.Uoo,{"data-icon":"inline-start"}),"SQL query"]}),(0,r.jsxs)(M,{href:P,active:a===P||a.startsWith(`${P}/`),shortcut:w.Ar.migrations,children:[(0,r.jsx)(l.olY,{"data-icon":"inline-start"}),"Migrations"]}),y&&(0,r.jsxs)(M,{href:O,active:a===O,shortcut:w.Ar.compareSchema,children:[(0,r.jsx)(l.R4X,{"data-icon":"inline-start"}),"Compare schema"]}),(0,r.jsx)(g.L,{value:d.search,onChange:e=>{var t;m({search:t=e.target.value,collapsedSchemas:t.trim()?K(t,E):d.collapsedSchemas})},placeholder:"Search tables","aria-label":"Search tables",className:"mt-1",trailing:(0,r.jsxs)(r.Fragment,{children:[!d.search&&(0,r.jsx)("kbd",{className:"font-mono text-[10px] text-muted-foreground/55",children:w.Ar.tableSearch}),(0,r.jsx)(S.V,{compact:!0,schemas:T,selected:E,onChange:function(e){m({selectedSchemas:e,collapsedSchemas:d.search.trim()?K(d.search,e):d.collapsedSchemas})}})]})})]}),(0,r.jsx)(x.F,{className:"min-h-0 flex-1 pt-1.5",children:i.error?(0,r.jsx)("p",{className:"px-3 py-4 text-xs text-destructive",children:i.error}):i.data?(0,r.jsx)(D,{connectionId:s.id,tables:z,search:d.search,collapsedSchemas:d.collapsedSchemas,pinnedTables:d.pinnedTables,onToggleSchema:function(e){m({collapsedSchemas:d.collapsedSchemas.includes(e)?d.collapsedSchemas.filter(t=>t!==e):[...d.collapsedSchemas,e]})},onTogglePin:function(e){let t=(0,v.i)(e);m({pinnedTables:d.pinnedTables.includes(t)?d.pinnedTables.filter(e=>e!==t):[...d.pinnedTables,t]})},onReorderPinned:function(e,t,n){if(e===t)return;let r=d.pinnedTables.filter(t=>t!==e),a=r.indexOf(t);-1!==a&&(r.splice(a+ +("after"===n),0,e),m({pinnedTables:r}))}}):(0,r.jsx)("div",{className:"flex flex-col gap-2 px-3 py-2",children:Array.from({length:8},(e,t)=>(0,r.jsx)(b.E,{className:"h-5 w-full"},t))})}),(0,r.jsx)("div",{role:"separator","aria-orientation":"vertical","aria-label":"Resize database sidebar","aria-valuemin":180,"aria-valuemax":480,"aria-valuenow":j,tabIndex:0,title:"Drag to resize; double-click to reset",onPointerDown:function(e){e.preventDefault(),N.current={pointerId:e.pointerId,startX:e.clientX,startWidth:j},e.currentTarget.setPointerCapture(e.pointerId)},onPointerMove:function(e){let t=N.current;t&&t.pointerId===e.pointerId&&(e.preventDefault(),k(L(t.startWidth+e.clientX-t.startX)))},onPointerUp:function(e){let n=N.current;if(!n||n.pointerId!==e.pointerId)return;let r=L(n.startWidth+e.clientX-n.startX);N.current=null,k(r),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),t(r)},onPointerCancel:function(e){let n=N.current;n&&n.pointerId===e.pointerId&&(N.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),t(j))},onKeyDown:function(e){if("ArrowLeft"!==e.key&&"ArrowRight"!==e.key)return;e.preventDefault();let n=L(j+("ArrowLeft"===e.key?-1:1)*16);k(n),t(n)},onDoubleClick:function(e){e.preventDefault(),k(256),t(256)},className:"group/resize absolute inset-y-0 -right-1 z-30 w-2 cursor-col-resize touch-none outline-none after:absolute after:inset-y-0 after:left-1/2 after:w-px after:-translate-x-1/2 after:bg-transparent after:transition-colors hover:after:bg-primary focus-visible:after:bg-primary"})]})}var U=n(67385),O=n(88406),P=n(86989),K=n(15923),F=n(19065);function q(e,{nested:t=!1}={}){let n=(0,h.useRouter)(),r=(0,h.usePathname)(),{connection:a,tables:s}=(0,f.k)(),[l]=(0,u.DE)(a.id),o=(0,d.g)(e=>e.tabView),i=`/${encodeURIComponent(a.id)}`,c=`${i}/${e}`,m=t?r===c||r.startsWith(`${c}/`):r===c;return{open:m,href:c,toggle:()=>n.push(m?function(){for(let e of(0,u.K7)(l,o)){let t=(s.data??[]).find(t=>(0,v.i)(t)===e);if(t)return`${i}/${encodeURIComponent(t.schema)}/${encodeURIComponent(t.name)}`}return i}():c)}}function G(){let e=q("migrations",{nested:!0});return{open:e.open,migrationsHref:e.href,toggle:e.toggle}}var V=n(48861);function Z(){let e=q("diff");return{open:e.open,diffHref:e.href,toggle:e.toggle}}function B(){let e=q("query");return{open:e.open,queryHref:e.href,toggle:e.toggle}}var W=n(20185);function Q(){let e=(0,h.useRouter)(),t=(0,h.useParams)(),{connection:n,tables:r}=(0,f.k)(),[a,s]=(0,u.DE)(n.id),l=(0,d.g)(e=>e.tabView),o=t.schema&&t.table?(0,v.i)({schema:decodeURIComponent(t.schema),name:decodeURIComponent(t.table)}):null,i=(0,p.useMemo)(()=>{let e=new Map((r.data??[]).map(e=>[(0,v.i)(e),e]));return a.openTabs.flatMap(t=>e.get(t)??[])},[a.openTabs,r.data]);return{enabled:l,tabs:i,activeKey:o,close:function(t){var r;let a=i.findIndex(e=>(0,v.i)(e)===t);if(-1===a)return;let l=i.filter(e=>(0,v.i)(e)!==t);s({openTabs:l.map(v.i)}),t===o&&(r=l[Math.min(a,l.length-1)],e.push(r?(0,W.Jn)({kind:"table",connectionId:n.id,table:r}):(0,W.Jn)({kind:"connection",connectionId:n.id})))},closeOthers:function(e){s({openTabs:i.some(t=>(0,v.i)(t)===e)?[e]:[]})}}}function _({text:e,query:t}){if(!t)return e;let n=e.toLocaleLowerCase(),a=t.toLocaleLowerCase(),s=n.indexOf(a);return -1===s?e:(0,r.jsxs)(r.Fragment,{children:[e.slice(0,s),(0,r.jsx)("mark",{className:"rounded-[3px] bg-yellow-300/90 px-px text-yellow-950 dark:bg-yellow-400/85 dark:text-yellow-950",children:e.slice(s,s+t.length)}),e.slice(s+t.length)]})}async function X(e){try{await navigator.clipboard.writeText(e)}catch{let t=document.createElement("textarea");t.value=e,t.style.position="fixed",t.style.opacity="0",document.body.appendChild(t),t.select(),document.execCommand("copy"),t.remove()}}function H(){let e=(0,h.useRouter)(),t=(0,h.useParams)(),{connection:n,tables:a}=(0,f.k)(),s=B(),o=Z(),i=G(),m=(0,u.y3)(n.id),x=(0,N.yG)(),g=(0,V.Q)(n.id),b=Q(),j=(0,d.g)(e=>e.setTabView),k=(0,c.Z)(e=>e.add),[C,S]=(0,u.DE)(n.id),[T,E]=(0,p.useState)(!1),[z,$]=(0,p.useState)("commands"),[D,L]=(0,p.useState)(""),[R,I]=(0,p.useState)(0),[M,A]=(0,p.useState)(!1),q=(0,p.useRef)(null),W=(0,p.useRef)(null),H=(0,p.useRef)(null),J=(0,p.useRef)(z),Y=(0,O.C)(e=>e.theme),ee=t.schema&&t.table?{schema:decodeURIComponent(t.schema),name:decodeURIComponent(t.table)}:null,et=!!ee&&C.pinnedTables.includes((0,v.i)(ee)),en=(0,u.lz)(e=>ee?e.tables[`${n.id}:${(0,v.i)(ee)}`]:void 0),er=(0,p.useMemo)(()=>[{id:"sql-editor",title:s.open?"Back to Table":"Open SQL Query",keywords:["new","query","sql","console","editor","close","back","table"],enabled:!0,shortcut:w.Ar.sqlEditor,run:()=>s.toggle()},{id:"go-back",title:g.back?`Back to ${g.back.label}`:"Back",keywords:["back","previous","return","history","undo"],enabled:null!==g.back,shortcut:w.Ar.back,run:()=>g.goBack()},{id:"go-forward",title:g.forward?`Forward to ${g.forward.label}`:"Forward",keywords:["forward","next","history","redo"],enabled:null!==g.forward,shortcut:w.Ar.forward,run:()=>g.goForward()},{id:"switch-connection",title:x.next?`Switch Connection (${x.next.name})`:"Switch Connection",keywords:["database","env","environment","next","cycle","other"],enabled:x.enabled,shortcut:w.Ar.switchConnection,run:()=>void x.run()},{id:"migrations",title:i.open?"Back to Table":"Open Migrations",keywords:["migration","migrate","apply","revert","rollback","ledger","schema","run"],enabled:!0,shortcut:w.Ar.migrations,run:()=>i.toggle()},{id:"compare-schema",title:m.target?`Compare Schema with ${m.target.name}`:"Compare Schema",keywords:["diff","difference","migration","drift","prod","dev","schema","compare"],enabled:null!==m.target,shortcut:w.Ar.compareSchema,run:()=>o.toggle()},{id:"search-tables",title:"Search Tables",keywords:["find","jump","open","goto","table"],enabled:!0,shortcut:w.Ar.tableSearch,run:()=>window.requestAnimationFrame(()=>(0,w.tT)())},{id:"search-columns",title:"Search Columns",keywords:["find","jump","goto","column","field"],enabled:null!==ee,shortcut:w.Ar.columnSearch,run:()=>window.requestAnimationFrame(()=>(0,w.vI)())},{id:"reload-tables",title:"Reload Tables",keywords:["refresh","reload","tables","sync"],enabled:!0,run:()=>a.reload()},{id:"pin-table",title:et?"Unpin Table":"Pin Table",keywords:["pin","unpin","favorite","star"],enabled:null!==ee,run:()=>{if(!ee)return;let e=(0,v.i)(ee);S({pinnedTables:C.pinnedTables.includes(e)?C.pinnedTables.filter(t=>t!==e):[...C.pinnedTables,e]})}},{id:"clear-filters",title:"Clear Filters",keywords:["filter","reset","remove"],enabled:null!==ee,run:()=>{ee&&u.lz.getState().setTable(n.id,ee,{filters:[],page:0})}},{id:"clear-search",title:"Clear Search",keywords:["find","search","reset"],enabled:null!==ee&&!!en?.search,run:()=>{ee&&u.lz.getState().setTable(n.id,ee,{search:"",page:0})}},{id:"reset-columns",title:"Reset Columns",keywords:["pin","hide","frozen","layout","show"],enabled:null!==ee,run:()=>{ee&&u.lz.getState().setTable(n.id,ee,{pinnedColumns:void 0,hiddenColumns:[]})}},{id:"tab-view",title:b.enabled?"Turn Off Tab View":"Turn On Tab View",keywords:["tabs","tab","view","layout","setting","preferences","toggle","show","hide"],enabled:!0,run:()=>j(!b.enabled)},{id:"close-tab",title:"Close Tab",keywords:["tabs","tab","close"],enabled:b.enabled&&null!==b.activeKey,run:()=>{b.activeKey&&b.close(b.activeKey)}},{id:"close-other-tabs",title:"Close Other Tabs",keywords:["tabs","tab","close","others","all"],enabled:b.enabled&&null!==b.activeKey&&b.tabs.length>1,run:()=>{b.activeKey&&b.closeOthers(b.activeKey)}},{id:"copy-table",title:"Copy Schema.Table",keywords:["copy","name","qualified"],enabled:null!==ee,run:()=>{ee&&X((0,v.i)(ee))}},{id:"color-theme",title:"Color Theme",keywords:["theme","appearance","dark","light","color","set","preferences"],enabled:!0,keepOpen:!0,run:()=>{let e=O.C.getState().theme,t=P.zG.findIndex(t=>t.id===e);$("themes"),L(""),I(-1===t?0:t)}},{id:"add-connection",title:"Add Connection",keywords:["new","database","postgres"],enabled:!0,run:()=>A(!0)}],[C.pinnedTables,m.target,n.id,g,i,et,o,S,j,s,x,ee,en?.search,a,b]),ea=(0,p.useMemo)(()=>D.trim()?(0,F.R6)(D,er,e=>[e.title,...e.keywords].join(" ")).map(e=>e.item):er,[er,D]),es=(0,p.useMemo)(()=>D.trim()?(0,F.R6)(D,[...P.zG],e=>[e.name,...e.keywords].join(" ")).map(e=>e.item):[...P.zG],[D]),el="themes"===z?es:ea,eo="commands"===z?ea[R]??null:null,ei="themes"===z?es[R]??null:null;function ec(e){e?.revertTheme&&"themes"===J.current&&(0,P.AZ)(O.C.getState().theme),E(!1),L(""),I(0),$("commands")}function eu(){ec({revertTheme:!0})}function ed(){"themes"===J.current&&(0,P.AZ)(O.C.getState().theme),$("commands"),L(""),I(0)}function em(e){e.enabled&&(e.keepOpen||eu(),e.run())}function ef(e){O.C.getState().setTheme(e.id),(0,P.AZ)(e.id),ec({revertTheme:!1})}return(0,p.useEffect)(()=>{J.current=z},[z]),(0,p.useEffect)(()=>{if("themes"===z&&!D.trim()){let e=P.zG.findIndex(e=>e.id===O.C.getState().theme);I(-1===e?0:e);return}I(0)},[D,T,z]),(0,p.useEffect)(()=>{let e=H.current?.querySelector("[data-active=true]");e?.scrollIntoView({block:"nearest"})},[R,el]),(0,p.useEffect)(()=>{if(!T)return;let e=window.requestAnimationFrame(()=>q.current?.focus());return()=>window.cancelAnimationFrame(e)},[T,z]),(0,p.useEffect)(()=>{if(!T||"themes"!==z)return;let e=es[R];e&&(0,P.AZ)(e.id)},[T,z,R,es]),(0,p.useEffect)(()=>(0,K.T)(eu),[]),(0,p.useEffect)(()=>{function e(e){let t=e.key.toLowerCase(),n="k"===t&&!e.shiftKey||"p"===t&&e.shiftKey;if((e.metaKey||e.ctrlKey)&&n){if(e.preventDefault(),T){"themes"===J.current&&ed(),q.current?.select();return}(0,K.r)(),L(""),I(0),$("commands"),E(!0);return}if(T&&"Escape"===e.key){if(e.preventDefault(),"themes"===J.current)return void ed();eu()}}function t(e){!T||W.current?.contains(e.target)||eu()}return window.addEventListener("keydown",e,!0),window.addEventListener("pointerdown",t),()=>{window.removeEventListener("keydown",e,!0),window.removeEventListener("pointerdown",t)}},[T]),(0,r.jsxs)(r.Fragment,{children:[T&&(0,r.jsxs)("div",{ref:W,"data-command-palette":"",className:"fixed top-3 left-1/2 z-50 flex w-[min(36rem,calc(100%-1.5rem))] -translate-x-1/2 flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 border-b px-3",children:[(0,r.jsx)("span",{className:"font-mono text-sm text-muted-foreground",children:">"}),(0,r.jsx)("input",{ref:q,value:D,onChange:e=>L(e.target.value),onKeyDown:function(e){if("ArrowDown"===e.key){if(e.preventDefault(),0===el.length)return;I(e=>(e+1)%el.length);return}if("ArrowUp"===e.key){if(e.preventDefault(),0===el.length)return;I(e=>(e-1+el.length)%el.length);return}if("Enter"===e.key){if(e.preventDefault(),"themes"===z){ei&&ef(ei);return}eo&&em(eo)}},spellCheck:!1,autoComplete:"off",autoCorrect:"off",placeholder:"themes"===z?"Select color theme":"Type a command","aria-label":"themes"===z?"Color theme":"Command palette",className:"h-11 min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"})]}),(0,r.jsx)("div",{ref:H,role:"listbox","aria-label":"themes"===z?"Color themes":"Commands",className:"max-h-[min(24rem,50vh)] overflow-auto py-1",children:0===el.length?(0,r.jsx)("p",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"themes"===z?"No matching themes":"No matching commands"}):"themes"===z?es.map((e,t)=>{let n=t===R,a=e.id===Y;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,"data-active":n||void 0,onMouseEnter:()=>I(t),onClick:()=>ef(e),className:(0,y.cn)("flex h-8 w-full cursor-pointer items-center gap-2 px-3 text-left text-[13px] outline-none",n&&"bg-primary/10"),children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"size-3.5 shrink-0 rounded-sm border",style:{background:e.swatch}}),(0,r.jsx)("span",{className:"min-w-0 truncate",children:(0,r.jsx)(_,{text:e.name,query:D.trim()})}),a&&(0,r.jsx)(l.wiW,{className:"ml-auto size-3.5 shrink-0 text-muted-foreground"})]},e.id)}):ea.map((e,t)=>{let n=t===R;return(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,"aria-disabled":!e.enabled,"data-active":n||void 0,onMouseEnter:()=>I(t),onClick:()=>em(e),className:(0,y.cn)("flex h-8 w-full cursor-pointer items-center px-3 text-left text-[13px] outline-none",n&&"bg-primary/10",!e.enabled&&"cursor-default opacity-40"),children:[(0,r.jsx)("span",{className:"min-w-0 truncate",children:(0,r.jsx)(_,{text:e.title,query:D.trim()})}),e.shortcut&&(0,r.jsx)("kbd",{className:"ml-auto shrink-0 pl-3 font-mono text-[11px] text-muted-foreground/70",children:e.shortcut})]},e.id)})})]}),(0,r.jsx)(U.f,{open:M,onOpenChange:A,onSubmit:t=>{let{shareWith:n,...r}=t,a=k(r);(0,u.mQ)(a.id,n),e.push(`/${a.id}`)}})]})}function J(){let{toggle:e}=B(),{toggle:t}=Z(),{toggle:n}=G(),{run:r}=(0,N.yG)(),a=(0,V.Q)(),s=(0,c.Z)(e=>e.connections.length>1),l=(0,p.useRef)(e),o=(0,p.useRef)(t),i=(0,p.useRef)(n),u=(0,p.useRef)(r),d=(0,p.useRef)(a),m=(0,p.useRef)(s);return(0,p.useEffect)(()=>{l.current=e},[e]),(0,p.useEffect)(()=>{o.current=t},[t]),(0,p.useEffect)(()=>{i.current=n},[n]),(0,p.useEffect)(()=>{u.current=r},[r]),(0,p.useEffect)(()=>{m.current=s},[s]),(0,p.useEffect)(()=>{d.current=a},[a]),(0,p.useEffect)(()=>{function e(e){if(!(e.metaKey||e.ctrlKey)||e.altKey||e.repeat)return;let t=e.key.toLowerCase();if("["===t||"]"===t){if(e.shiftKey||function(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;let t=e.tagName;return"INPUT"===t||"TEXTAREA"===t||"SELECT"===t}(e.target))return;e.preventDefault(),(0,K.r)(),"["===t?d.current.goBack():d.current.goForward();return}if("m"===t&&e.shiftKey){e.preventDefault(),(0,K.r)(),i.current();return}if("d"===t&&e.shiftKey){if(!m.current)return;e.preventDefault(),(0,K.r)(),o.current();return}if("e"===t){if(e.preventDefault(),(0,K.r)(),e.shiftKey)return void u.current();l.current()}}return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[]),null}var Y=n(27529);let ee={pinned:"Pinned",recent:"Recent",tables:"Tables",connections:"Connections"};function et({text:e,query:t}){if(!t)return e;let n=e.toLocaleLowerCase(),a=t.toLocaleLowerCase(),s=n.indexOf(a);return -1===s?e:(0,r.jsxs)(r.Fragment,{children:[e.slice(0,s),(0,r.jsx)("mark",{className:"rounded-[3px] bg-yellow-300/90 px-px text-yellow-950 dark:bg-yellow-400/85 dark:text-yellow-950",children:e.slice(s,s+t.length)}),e.slice(s+t.length)]})}function en(e){try{return new URL(e).hostname}catch{return""}}function er(e){return[e.name,en(e.url)].filter(Boolean)}function ea(e,t){let n=new Map([["public",0],["auth",1]]);return(n.get(e.schema)??2)-(n.get(t.schema)??2)||e.schema.localeCompare(t.schema)||e.name.localeCompare(t.name)}function es(e,t){return e.map((e,n)=>0===n?{...e,section:t}:e)}function el(){let e=(0,h.useRouter)(),t=(0,N.$C)(),n=(0,h.useParams)(),{connection:a,tables:s}=(0,f.k)(),o=(0,c.Z)(e=>e.connections),[i,d]=(0,p.useState)(!1),[m,x]=(0,p.useState)(""),[g,b]=(0,p.useState)(0),[j,C]=(0,p.useState)(null),S=(0,p.useRef)(null),T=(0,p.useRef)(null),E=(0,p.useRef)(null),z=o.find(e=>e.id===j)??null,$=z??a,D=z&&z.id!==a.id?z.url:null,L=function(e){let[t]=(0,p.useState)(()=>new Map),[n,r]=(0,p.useState)({url:"",error:null});if((0,p.useEffect)(()=>{if(!e)return;let n=new AbortController;return Y.F.tables(e,n.signal).then(n=>{t.set(e,n),r({url:e,data:n,error:null})}).catch(a=>{if(n.signal.aborted)return;let s=a instanceof Error?a.message:String(a);r(n=>({url:e,data:n.url===e?n.data:t.get(e),error:s}))}),()=>n.abort()},[t,e]),!e)return{data:void 0,error:null,loading:!1};let a=n.url===e?n.data:t.get(e);return{data:a,error:n.url===e?n.error:null,loading:void 0===a}}(D),[R,I]=(0,u.DE)(a.id),[M,A]=(0,u.DE)($.id),U=$.id===a.id?R:M,O=(0,p.useMemo)(()=>D?L.data??[]:s.data??[],[L.data,D,s.data]),P=D?L.loading:s.loading,q=D?L.error:null,G=(0,p.useMemo)(()=>[...new Set(O.map(e=>e.schema))],[O]),V=null===U.selectedSchemas?null:U.selectedSchemas.filter(e=>G.includes(e)),Z=(0,p.useMemo)(()=>null===V?O:O.filter(e=>V.includes(e.schema)),[O,V]),B=U.pinnedTables,W=U.recentTables,Q=(0,p.useMemo)(()=>{let e,t;return -1===(t=(e=m.trim()).indexOf(":"))?{schema:null,table:e}:{schema:e.slice(0,t).trim(),table:e.slice(t+1).trim()}},[m]),_=Q.table||(Q.schema?"":m.trim()),X=(0,p.useMemo)(()=>{let e=new Set(B),t=new Set(W),n=null===Q.schema?null:function(e,t){if(!e)return t;let n=e.toLocaleLowerCase(),r=t.filter(e=>e.toLocaleLowerCase()===n);if(r.length>0)return r;let a=t.filter(e=>e.toLocaleLowerCase().startsWith(n));return a.length>0?a:(0,F.R6)(e,t,e=>e).map(e=>e.item)}(Q.schema,G),r=null===n?Z:O.filter(e=>n.includes(e.schema)),s=new Map(r.map(e=>[(0,v.i)(e),e])),l=B.flatMap(e=>{let t=s.get(e);return t?[t]:[]}),i=W.flatMap(t=>{let n=s.get(t);return!n||e.has(t)?[]:[n]}),c=(e,t)=>({type:"table",key:`table:${(0,v.i)(e)}`,table:e,...t}),u=e=>({type:"connection",key:`connection:${e.id}`,connection:e,current:e.id===a.id}),d=null===Q.schema?m.trim():Q.table,f=null===z&&null===Q.schema;if(!d){let e=new Set([...l.map(e=>(0,v.i)(e)),...i.map(e=>(0,v.i)(e))]),n=r.filter(t=>!e.has((0,v.i)(t))).sort(ea),s=f?o.filter(e=>e.id!==a.id):[];return[...es(l.map(e=>c(e,{pinned:!0})),"pinned"),...es(i.map(e=>c(e,{pinned:!1,recent:!0})),"recent"),...es(n.map(e=>c(e,{pinned:!1,recent:t.has((0,v.i)(e))})),"tables"),...es(s.map(u),"connections")]}let h=(0,F.UO)(d,r,e=>null===Q.schema?[e.name,`${e.schema}.${e.name}`,e.schema]:[e.name]).map(n=>({...n,score:n.score+80*!!e.has((0,v.i)(n.item))+40*!!t.has((0,v.i)(n.item))})).sort((e,t)=>t.score-e.score).map(n=>c(n.item,{pinned:e.has((0,v.i)(n.item)),recent:t.has((0,v.i)(n.item))}));return[...es(f?(0,F.UO)(m,o,er).map(e=>u(e.item)):[],"connections"),...es(h,"tables")]},[O,a.id,o,z,Q.schema,Q.table,B,m,W,G,Z]),H=X[g]??null;function J(){d(!1),x(""),b(0),C(null)}function el(){C(null),b(0),S.current?.focus()}function eo(n){var r,a;(J(),"connection"===n.type)?t(n.connection.id):e.push((r=$.id,a=n.table,`/${r}/${encodeURIComponent(a.schema)}/${encodeURIComponent(a.name)}`))}function ei(e){let t=(0,v.i)(e),n=U.pinnedTables.includes(t)?U.pinnedTables.filter(e=>e!==t):[...U.pinnedTables,t];($.id===a.id?I:A)({pinnedTables:n})}(0,p.useEffect)(()=>{b(0)},[m,i,j]),(0,p.useEffect)(()=>{let e=E.current?.querySelector("[data-active=true]");e?.scrollIntoView({block:"nearest"})},[g,X]),(0,p.useEffect)(()=>{if(!i)return;let e=window.requestAnimationFrame(()=>S.current?.focus());return()=>window.cancelAnimationFrame(e)},[i]),(0,p.useEffect)(()=>{if(!n.schema||!n.table)return;let e=`${decodeURIComponent(n.schema)}.${decodeURIComponent(n.table)}`,t=u.lz.getState().browse[a.id]?.recentTables??[];t[0]!==e&&I({recentTables:[e,...t.filter(t=>t!==e)].slice(0,12)})},[a.id,n.schema,n.table,I]),(0,p.useEffect)(()=>{function e(){i?S.current?.select():((0,K.r)(),x(""),b(0),C(null),d(!0))}function t(t){if((t.metaKey||t.ctrlKey)&&"p"===t.key.toLowerCase()){if(t.shiftKey)return;t.preventDefault(),e();return}i&&"Escape"===t.key&&(t.preventDefault(),J())}function n(e){!i||T.current?.contains(e.target)||J()}window.addEventListener("keydown",t,!0),window.addEventListener("pointerdown",n);let r=(0,w.s5)(e);return()=>{window.removeEventListener("keydown",t,!0),window.removeEventListener("pointerdown",n),r()}},[i]),(0,p.useEffect)(()=>(0,K.T)(J),[]);let ec=$.id===a.id&&n.schema&&n.table?`${decodeURIComponent(n.schema)}.${decodeURIComponent(n.table)}`:null;return i?(0,r.jsxs)("div",{ref:T,"data-table-palette":"",className:"fixed top-3 left-1/2 z-50 flex w-[min(36rem,calc(100%-1.5rem))] -translate-x-1/2 flex-col overflow-hidden rounded-lg border bg-popover text-popover-foreground shadow-lg ring-1 ring-foreground/10",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2 border-b px-3",children:[(0,r.jsx)(l.TfF,{className:"size-4 shrink-0 text-muted-foreground"}),z&&(0,r.jsxs)("button",{type:"button",onClick:el,"aria-label":`Stop searching ${z.name}`,className:"flex h-6 max-w-40 shrink-0 items-center gap-1.5 rounded-md bg-muted px-1.5 text-xs outline-none hover:bg-muted/80",children:[(0,r.jsx)(k.F,{connection:z,className:"size-2"}),(0,r.jsx)("span",{className:"truncate",children:z.name})]}),(0,r.jsx)("input",{ref:S,value:m,onChange:e=>x(e.target.value),onKeyDown:function(e){if("ArrowDown"===e.key){if(e.preventDefault(),0===X.length)return;b(e=>(e+1)%X.length);return}if("ArrowUp"===e.key){if(e.preventDefault(),0===X.length)return;b(e=>(e-1+X.length)%X.length);return}if("Tab"===e.key){if(e.preventDefault(),z||e.shiftKey)return;H?.type==="connection"&&(C(H.connection.id),x(""),b(0));return}if("Backspace"===e.key&&""===m&&z){e.preventDefault(),el();return}"Enter"===e.key&&(e.preventDefault(),e.shiftKey&&H?.type==="table"?ei(H.table):H&&eo(H))},spellCheck:!1,autoComplete:"off",autoCorrect:"off",placeholder:z?`Search tables in ${z.name}`:"Go to table (schema:name)","aria-label":z?`Go to table in ${z.name}`:"Go to table or connection",className:"h-11 min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"})]}),(0,r.jsx)("div",{ref:E,role:"listbox","aria-label":z?`Tables in ${z.name}`:"Tables and connections",className:"max-h-[min(24rem,50vh)] overflow-auto py-1",children:P&&0===O.length&&0===X.length?(0,r.jsx)("p",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"Loading tables…"}):q&&0===O.length?(0,r.jsx)("p",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:q}):0===X.length?(0,r.jsx)("p",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:m.trim()?"No matches":"No tables"}):X.map((e,t)=>{let n=t===g;if("connection"===e.type){let a=en(e.connection.url);return(0,r.jsxs)("div",{children:[e.section&&(0,r.jsx)("p",{className:"px-3 pt-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:ee[e.section]}),(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,"data-active":n||void 0,onMouseEnter:()=>b(t),onClick:()=>eo(e),className:(0,y.cn)("flex h-8 w-full cursor-pointer items-center gap-2 px-3 text-left text-[13px] outline-none",n&&"bg-primary/10"),children:[(0,r.jsx)(l.bkQ,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)(k.F,{connection:e.connection,className:"size-2"}),(0,r.jsx)("span",{className:(0,y.cn)("min-w-0 truncate",e.current&&"font-medium"),children:(0,r.jsx)(et,{text:e.connection.name,query:_})}),(0,r.jsx)("span",{className:"ml-auto flex min-w-0 shrink-0 items-center gap-2 text-[11px] text-muted-foreground",children:n?(0,r.jsx)("span",{children:"Tab to search"}):(0,r.jsx)("span",{className:"max-w-36 truncate",children:e.current?"current":a||"connection"})})]})]},e.key)}let a=(0,v.i)(e.table)===ec;return(0,r.jsxs)("div",{children:[e.section&&(0,r.jsx)("p",{className:"px-3 pt-2 pb-1 text-[10px] font-medium tracking-wide text-muted-foreground uppercase",children:ee[e.section]}),(0,r.jsxs)("div",{onMouseEnter:()=>b(t),className:(0,y.cn)("group/table-result flex items-center",n&&"bg-primary/10"),children:[(0,r.jsxs)("button",{type:"button",role:"option","aria-selected":n,"data-active":n||void 0,onClick:()=>eo(e),className:"flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 pl-3 text-left text-[13px] outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/60",children:[e.recent&&!e.pinned?(0,r.jsx)(l.A01,{className:"size-3.5 shrink-0 text-muted-foreground"}):(0,r.jsx)(l.ooN,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,r.jsx)("span",{className:(0,y.cn)("min-w-0 truncate",a&&"font-medium"),children:(0,r.jsx)(et,{text:e.table.name,query:_})}),(0,r.jsxs)("span",{className:"ml-auto flex min-w-0 shrink-0 items-center gap-2 text-[11px] text-muted-foreground",children:["view"===e.table.kind&&(0,r.jsx)("span",{children:"view"}),(0,r.jsx)("span",{className:"max-w-36 truncate",children:e.table.schema})]})]}),(0,r.jsx)("button",{type:"button","aria-label":`${e.pinned?"Unpin":"Pin"} ${(0,v.i)(e.table)}`,"aria-pressed":e.pinned,title:e.pinned?"Unpin table":"Pin table",onClick:()=>ei(e.table),className:(0,y.cn)("mr-2 flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground opacity-0 outline-none transition-[color,background-color,opacity] hover:bg-foreground/10 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:opacity-100 group-hover/table-result:opacity-100",(e.pinned||n)&&"opacity-100",e.pinned&&"text-foreground"),children:e.pinned?(0,r.jsx)(l.M0d,{className:"size-3.5"}):(0,r.jsx)(l.rq5,{className:"size-3.5"})})]})]},e.key)})}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-3 border-t px-3 py-1.5 text-[10px] text-muted-foreground",children:[(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"font-mono text-foreground/70",children:"↑↓"}),"Navigate"]}),(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"font-mono text-foreground/70",children:"↵"}),"Open"]}),H?.type==="table"&&(0,r.jsxs)("span",{className:"flex items-center gap-1",children:[(0,r.jsx)("kbd",{className:"font-mono text-foreground/70",children:"⇧↵"}),H.pinned?"Unpin":"Pin"]})]})]}):null}function eo(){let{connection:e}=(0,f.k)(),{tabs:t,activeKey:n,close:a}=Q(),o=(0,p.useRef)(null),i=(0,u.lz)(e=>e.setBrowse);return(0,p.useEffect)(()=>{if(!n)return;let t=u.lz.getState().browse[e.id]?.openTabs??[];t.includes(n)||i(e.id,{openTabs:[...t,n]})},[n,e.id,i]),(0,p.useEffect)(()=>{let e=o.current?.querySelector("[aria-selected=true]");e?.scrollIntoView({block:"nearest",inline:"nearest"})},[n,t.length]),(0,r.jsxs)("div",{ref:o,role:"tablist","aria-label":"Open tables",className:"flex h-9 shrink-0 overflow-x-auto overflow-y-hidden bg-sidebar [scrollbar-width:none]",children:[t.map(t=>{let o=(0,v.i)(t),i=o===n;return(0,r.jsxs)("div",{className:(0,y.cn)("group/tab relative flex max-w-60 shrink-0 items-center border-r",i?"bg-background text-foreground":"border-b text-muted-foreground hover:text-foreground"),children:[i&&(0,r.jsx)("span",{"aria-hidden":!0,className:"absolute inset-x-0 top-0 h-px bg-primary"}),(0,r.jsxs)(s(),{role:"tab","aria-selected":i,href:(0,W.Jn)({kind:"table",connectionId:e.id,table:t}),title:o,onMouseDown:e=>{1===e.button&&e.preventDefault()},onAuxClick:e=>{1===e.button&&(e.preventDefault(),a(o))},className:"flex h-full min-w-0 items-center gap-1.5 pr-1 pl-3 text-xs outline-none",children:[(0,r.jsx)(l.ooN,{className:"size-3.5 shrink-0 opacity-70"}),(0,r.jsxs)("span",{className:"truncate",children:[(0,r.jsxs)("span",{className:"text-muted-foreground",children:[t.schema,"."]}),t.name]})]}),(0,r.jsx)("button",{type:"button","aria-label":`Close ${o}`,title:"Close",onClick:()=>a(o),className:(0,y.cn)("mr-1.5 grid size-4 shrink-0 place-items-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100",i?"opacity-100":"opacity-0 group-hover/tab:opacity-100"),children:(0,r.jsx)(l.yBK,{className:"size-3"})})]},o)}),(0,r.jsx)("div",{className:"flex min-w-0 flex-1 items-center border-b pl-1",children:(0,r.jsx)("button",{type:"button","aria-label":"Open a table",title:`Open a table (${w.Ar.tableSearch})`,onClick:()=>(0,w.tT)(),className:"grid size-6 shrink-0 place-items-center rounded-sm text-muted-foreground hover:bg-muted hover:text-foreground",children:(0,r.jsx)(l.enO,{className:"size-3.5"})})})]})}function ei({connectionId:e,children:t}){let n=(0,i.p)(),a=(0,c.w)(e),[h,p]=(0,u.DE)(e),x=(0,d.g)(e=>e.tabView);if(!n)return null;if(!a)return(0,r.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground",children:[(0,r.jsx)("p",{children:"Connection not found"}),(0,r.jsx)(s(),{href:"/",className:"text-foreground underline underline-offset-4",children:"Connections"})]});let g=(0,m.Mq)(a);return(0,r.jsxs)(f.Z,{connection:a,children:[(0,r.jsxs)("div",{className:"flex h-dvh flex-col overflow-hidden",children:[(0,r.jsx)("div",{"aria-hidden":!0,title:a.name,className:"h-1.5 w-full shrink-0",style:{background:g}}),(0,r.jsxs)("div",{className:"flex min-h-0 flex-1 overflow-hidden",children:[h.sidebarCollapsed?(0,r.jsxs)("aside",{className:"relative flex h-full w-10 shrink-0 justify-center border-r bg-sidebar pt-2",children:[(0,r.jsx)("span",{"aria-hidden":!0,className:"absolute inset-y-0 left-0 w-1",style:{background:g}}),(0,r.jsx)(o.$,{variant:"ghost",size:"icon-sm","aria-label":"Show database sidebar",title:"Show sidebar",onClick:()=>p({sidebarCollapsed:!1}),children:(0,r.jsx)(l.cFu,{})})]}):(0,r.jsx)(A,{width:h.sidebarWidth,onWidthChange:e=>p({sidebarWidth:e}),onCollapse:()=>p({sidebarCollapsed:!0})},a.id),(0,r.jsxs)("main",{className:"flex min-w-0 flex-1 flex-col",children:[x&&(0,r.jsx)(eo,{}),t]})]})]}),(0,r.jsx)(el,{}),(0,r.jsx)(H,{}),(0,r.jsx)(J,{})]})}}},e=>{e.O(0,[4506,1731,8026,2435,8361,8322,544,6090,577,8441,3794,7358],()=>e(e.s=12860)),_N_E=e.O()}]);
@@ -0,0 +1 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8755],{28330:(e,t,n)=>{Promise.resolve().then(n.bind(n,31664))},31664:(e,t,n)=>{"use strict";n.d(t,{MigrationsIndex:()=>ev});var s=n(95155),r=n(98500),a=n.n(r),i=n(73321),l=n(20185),o=n(12115),d=n(13267),c=n(72194),u=n(36331),m=n(17491),h=n(89239),x=n(72264),p=n(66289),g=n(91075),f=n(85488),b=n(35942),j=n(7412),v=n(87364),N=n(27529),k=n(9385),y=n(62417),w=n(40544),$=n(79668),C=n(40980),S=n(17021),z=n(20642),M=n(77649),R=n(27013),F=n(41069),q=n(42763),A=n(83504);let O=[{verdict:"applied",title:"Already there",hint:"Everything these create or change is in the database.",preselected:!0},{verdict:"partial",title:"Partly there",hint:"Some of what these do is in the database and some is not — often a later migration changed it again.",preselected:!1},{verdict:"unknown",title:"Leaves no trace",hint:"Data changes, seeds, and grants cannot be seen in the schema. Include them if you know they ran.",preselected:!1},{verdict:"pending",title:"Not there",hint:"Nothing these do is in the database. Marking these hides work that still needs to run.",preselected:!1}];function E(e){return`${e.setName}\0${e.version}`}function L({connection:e,ledgerSchema:t,plan:n,onDone:r,onOpenChange:a}){let[i,l]=(0,o.useState)(null),[u,m]=(0,o.useState)(null),[x,p]=(0,o.useState)(new Set),[g,f]=(0,o.useState)([]),[b,j]=(0,o.useState)(!1),[v,k]=(0,o.useState)(null),[y,w]=(0,o.useState)(null);(0,o.useEffect)(()=>{let t=new AbortController;return N.F.detect(e.url,n.entries.map(e=>({setName:e.setName,version:e.version,sql:e.applySql})),t.signal).then(({results:e})=>{l(e);let t=new Set;for(let n of e)O.find(e=>e.verdict===n.verdict)?.preselected&&t.add(E(n));p(t)}).catch(e=>{t.signal.aborted||m(e instanceof Error?e.message:String(e))}),()=>t.abort()},[e.url,n.entries]);let $=(0,o.useMemo)(()=>{if(!i)return[];let e=new Map(n.entries.map(e=>[E(e),e]));return O.map(t=>({verdict:t.verdict,title:t.title,hint:t.hint,entries:i.filter(e=>e.verdict===t.verdict).flatMap(t=>{let n=e.get(E(t));return n?[{entry:n,result:t}]:[]})})).filter(e=>e.entries.length>0)},[i,n.entries]),S=n.entries.filter(e=>x.has(E(e)));async function z(n){j(!0),w(null);try{k(await N.F.adopt(e.url,{ledgerSchema:t,entries:n})),r()}catch(e){w(e instanceof Error?e.message:String(e))}finally{j(!1)}}let M=!i&&!u;return(0,s.jsx)(q.lG,{open:!0,onOpenChange:e=>!b&&a(e),children:(0,s.jsxs)(q.Cf,{className:"sm:max-w-xl",children:[(0,s.jsxs)(q.c7,{children:[(0,s.jsx)(q.L3,{children:v?`Marked ${v.recorded} as applied`:M?`Checking ${e.name}…`:`Mark as already applied on ${e.name}`}),(0,s.jsx)(q.rr,{children:(0,s.jsxs)("span",{className:"flex flex-wrap items-center gap-1.5",children:[(0,s.jsx)("span",{children:v?"Recorded on":"Records on"}),(0,s.jsx)(c.F,{connection:e}),(0,s.jsx)("span",{className:"font-medium text-foreground",children:e.name}),(0,s.jsx)("span",{className:"font-mono text-[11px]",children:(0,A.p)(e.url)})]})})]}),v?(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:v.existing>0?`${v.existing} were already in the ledger and were left as they were.`:"Every one of them was new to the ledger."}):M?(0,s.jsxs)("p",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,s.jsx)(d.gnh,{className:"size-3.5 animate-spin"}),"Reading the schema to see which of the ",n.entries.length," have already run…"]}):u?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{className:"max-h-32 overflow-auto rounded-md border border-destructive/25 bg-destructive/5 px-3 py-2 font-mono text-[11px] whitespace-pre-wrap text-destructive",children:u}),(0,s.jsxs)("p",{className:"text-xs text-muted-foreground",children:["The check could not run. You can still mark all ",n.entries.length," as applied if you know the database already has these changes."]})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("div",{className:"max-h-80 overflow-y-auto rounded-md border",children:$.map(e=>{let t=e.entries.filter(({entry:e})=>x.has(E(e))).length,n=g.includes(e.verdict);return(0,s.jsxs)("div",{className:"border-b last:border-b-0",children:[(0,s.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2",children:[(0,s.jsx)("input",{type:"checkbox","aria-label":`Include ${e.title}`,className:"size-3.5 cursor-pointer accent-primary",checked:t===e.entries.length,ref:n=>{n&&(n.indeterminate=t>0&&t<e.entries.length)},onChange:t=>{var n;return n=t.target.checked,void p(t=>{let s=new Set(t);for(let{entry:t}of e.entries)n?s.add(E(t)):s.delete(E(t));return s})}}),(0,s.jsxs)("button",{type:"button","aria-expanded":n,onClick:()=>{var t;return t=e.verdict,void f(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},className:"flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-left",children:[(0,s.jsx)(d.nNJ,{className:(0,C.cn)("size-3.5 shrink-0 text-muted-foreground/70 transition-transform",n&&"rotate-90")}),(0,s.jsx)("span",{className:"text-sm",children:e.title}),(0,s.jsxs)("span",{className:"tabular-nums text-xs text-muted-foreground",children:[t,"/",e.entries.length]})]}),(0,s.jsx)(I,{verdict:e.verdict})]}),!n&&(0,s.jsx)("p",{className:"px-9 pb-2 text-[11px] text-muted-foreground",children:e.hint}),n&&(0,s.jsxs)("div",{className:"bg-muted/25",children:[(0,s.jsx)("p",{className:"px-9 py-1.5 text-[11px] text-muted-foreground",children:e.hint}),e.entries.map(({entry:e,result:t})=>{let n=t.evidence.filter(e=>!e.satisfied),r=t.evidence.find(e=>e.note)?.note;return(0,s.jsxs)("label",{className:"flex cursor-pointer items-start gap-2 border-t px-3 py-1.5 text-xs hover:bg-muted/40",children:[(0,s.jsx)("input",{type:"checkbox",className:"mt-0.5 size-3.5 cursor-pointer accent-primary",checked:x.has(E(e)),onChange:()=>{p(t=>{let n=new Set(t),s=E(e);return n.has(s)?n.delete(s):n.add(s),n})}}),(0,s.jsxs)("span",{className:"min-w-0 flex-1",children:[(0,s.jsxs)("span",{className:"flex items-center gap-2",children:[(0,s.jsx)("span",{className:"shrink-0 text-muted-foreground",children:e.setName}),(0,s.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e.version}),(0,s.jsx)("span",{className:"min-w-0 truncate",children:e.name})]}),(n.length>0||r)&&(0,s.jsxs)("span",{className:"mt-0.5 block truncate text-[11px] text-muted-foreground",children:[n.length>0&&(0,s.jsxs)(s.Fragment,{children:["Missing: ",n.slice(0,2).map(e=>e.description).join(", "),n.length>2&&` and ${n.length-2} more`]}),n.length>0&&r&&" \xb7 ",r]})]})]},E(e))})]})]},e.verdict)})}),(0,s.jsxs)("p",{className:"rounded-md border border-amber-600/25 bg-amber-500/8 px-3 py-2 text-xs",children:[(0,s.jsx)("span",{className:"font-medium",children:"No SQL runs."})," Only the ledger on"," ",e.name," changes, in one transaction. Rows already there are not touched."]})]}),y&&(0,s.jsx)("p",{className:"max-h-32 overflow-auto rounded-md border border-destructive/25 bg-destructive/5 px-3 py-2 font-mono text-[11px] whitespace-pre-wrap text-destructive",children:y}),(0,s.jsx)(q.Es,{children:v?(0,s.jsx)(h.$,{onClick:()=>a(!1),children:"Close"}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(h.$,{variant:"outline",disabled:b,onClick:()=>a(!1),children:"Cancel"}),u?(0,s.jsx)(h.$,{disabled:b,onClick:()=>void z(n.entries),children:b?"Marking…":`Mark all ${n.entries.length} as applied`}):(0,s.jsx)(h.$,{disabled:b||M||0===S.length,onClick:()=>void z(S),children:b?"Marking…":`Mark as applied (${S.length})`})]})})]})})}function I({verdict:e}){return"applied"===e?(0,s.jsx)(d.wiW,{className:"size-4 shrink-0 text-emerald-600 dark:text-emerald-400"}):"partial"===e?(0,s.jsx)(d.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}):"pending"===e?(0,s.jsx)(d.e5t,{className:"size-3.5 shrink-0 text-destructive"}):(0,s.jsx)("span",{className:"size-1.5 shrink-0 rounded-full bg-muted-foreground/40"})}var V=n(65194),G=n(60529),H=n(33807),_=n(56012),T=n(67227),P=n(17639);let D=new Map,B=new Map;function U({scope:e,root:t,repoName:n,onPickFolder:r,...a}){let i=(0,$.ev)(e),l=(0,$.jV)(t=>t.releaseTabs[e]),c=(0,$.jV)(e=>e.setReleaseTab),u=(0,$.jV)(e=>e.addReleaseRepo),m=(0,$.jV)(e=>e.removeReleaseRepo),[h,x]=(0,o.useState)(!1),[p,g]=(0,o.useState)({}),f=l&&i.includes(l)?l:null,b=(0,$.DR)(e,f),j=(0,o.useCallback)(e=>g(t=>t[b]===e?t:{...t,[b]:e}),[b]),v=[{path:null,name:B.get((0,$.DR)(e,null))??n??"Migrations repo"},...i.map(t=>{var n;return{path:t,name:B.get((0,$.DR)(e,t))??(n=t).split(/[\\/]/).filter(Boolean).pop()??n}})],N=(0,s.jsxs)("div",{className:"flex min-w-0 items-center gap-1 overflow-x-auto",children:[v.map(n=>{let r=n.path===f,a=p[(0,$.DR)(e,n.path)];return(0,s.jsxs)("button",{type:"button",onClick:()=>c(e,n.path),title:n.path??t??void 0,className:(0,C.cn)("-mb-px flex h-9 shrink-0 cursor-pointer items-center gap-2 border-b-2 px-2.5 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/60",r?"border-foreground font-medium text-foreground":"border-transparent text-muted-foreground hover:text-foreground"),children:[n.name,void 0!==a&&a>0&&(0,s.jsx)("span",{className:"rounded-full bg-emerald-600/15 px-1.5 text-xs tabular-nums text-emerald-700 dark:text-emerald-400",children:a})]},n.path??"")}),(0,s.jsxs)("button",{type:"button",onClick:()=>x(!0),title:"Add another repository's release, read from its folder on this computer",className:"-mb-px flex h-9 shrink-0 cursor-pointer items-center gap-1.5 border-b-2 border-transparent px-2.5 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60",children:[(0,s.jsx)(d.enO,{className:"size-3"}),"Add repo"]})]});return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(K,{storeKey:b,root:f??t,migrations:f?null:a,tabs:N,onCount:j,onPickFolder:r,onRemove:f?()=>m(e,f):void 0},b),h&&(0,s.jsx)(ex,{onOpenChange:x,onAdd:t=>u(e,t)})]})}function K({storeKey:e,root:t,migrations:n,tabs:r,onCount:a,onPickFolder:i,onRemove:l}){let c=(0,$.o9)(e),u=(0,$.vL)(e),m=(0,$.jV)(e=>e.setReleaseSettings),x=(0,$.jV)(e=>e.toggleReleasePin),[p,g]=(0,o.useState)(!1),[f,j]=(0,o.useState)({read:null,map:{}}),[k,y]=(0,o.useState)(null),[w,S]=(0,o.useState)(null),[z,M]=(0,o.useState)(null),R=`release:${t??""}:${!!n}:${c.base}:${c.head}:${c.label}:${u.join(",")}`,F=(0,v.Y)(R,async s=>{if(!t)return null;let r=await N.F.release({root:t,migrations:!!n,...c,pinned:u},s);return D.set(R,r),r.repo&&B.set(e,r.repo.name),r}),q=F.data??D.get(R)??null,A=w&&w.read===F.data&&!F.error?w:null,O=(0,o.useCallback)(e=>f.read===q&&e.number in f.map?f.map[e.number]:"label"===e.planned||u.includes(e.number),[f,q,u]),E=(0,o.useMemo)(()=>q?.open.filter(O)??[],[q,O]),L=(0,o.useMemo)(()=>q?.open.filter(e=>!O(e)&&e.base===eg(c.head))??[],[q,O,c.head]),I=(0,o.useMemo)(()=>q?function(e,t){let n=new Map,s=(e,t,s)=>{let r=`${e.setName}\u0000${e.version}`,a=n.get(r);if(a){a.sources.some(e=>e.label===t.label)||a.sources.push(t),a.planned&&=s;return}n.set(r,{...e,sources:[t],planned:s})};for(let t of e.pullRequests)for(let e of t.migrations)s(e,{label:`#${t.number}`,url:t.url,title:t.title},!1);for(let t of e.direct)for(let e of t.migrations)s(e,{label:t.sha.slice(0,7),url:t.url,title:t.subject},!1);for(let e of t)for(let t of e.migrations)s(t,{label:`#${e.number}`,url:e.url,title:e.title,ref:e.branch},!0);return[...n.values()].sort((e,t)=>e.setName.localeCompare(t.setName)||e.version.localeCompare(t.version))}(q,E):[],[q,E]),V=q?E.length:void 0;(0,o.useEffect)(()=>{void 0!==V&&a(V)},[V,a]);let G=n?.folderSets,H=n?.migrationHref,T=(0,o.useMemo)(()=>new Set((G??[]).flatMap(e=>e.steps.map(t=>`${e.name}\u0000${t.version}`))),[G]),P=q?.repo?.url??null,U=(0,o.useCallback)((e,t)=>H&&T.has(`${e.setName}\u0000${e.version}`)?{href:`${H((0,_.K9)(e.setName))}#migration-${encodeURIComponent(e.version)}`,external:!1}:P?{href:`${P}/blob/${t}/${e.path}`,external:!0}:null,[T,H,P]);if(!t)return(0,s.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,s.jsx)("div",{className:"mx-auto w-full max-w-5xl px-6 pt-6",children:(0,s.jsx)(W,{tabs:r})}),(0,s.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 p-6 text-center",children:[(0,s.jsx)("p",{className:"text-sm",children:"This tab reads the repository your migrations folder is in."}),(0,s.jsxs)(h.$,{size:"sm",variant:"outline",onClick:i,children:[(0,s.jsx)(d.WzY,{"data-icon":"inline-start"}),"Read from a folder"]})]})]});let J=eg(c.head),Z=eg(c.base),X=q?q.pullRequests.length+q.direct.length:0,ee=c.head.trim()===c.base.trim();async function et(n,s){if(q&&t){if(y(null),!c.label||"pinned"===n.planned)return void x(e,n.number);j({read:q,map:{...f.read===q?f.map:{},[n.number]:s}});try{await N.F.releaseLabel({root:t,number:n.number,label:c.label,add:s}),F.reload()}catch(e){j({read:null,map:{}}),y(e instanceof Error?e.message:String(e))}}}async function en(e,n){if(t&&e.standing){y(null),S({number:e.number,kind:n,read:F.data});try{let s={root:t,number:e.number,sha:e.standing.headSha};"merge"===n?await N.F.releaseMerge(s):await N.F.releaseSync(s),F.reload()}catch(e){S(null),y(e instanceof Error?e.message:String(e))}}}let ei=(e,t)=>(0,s.jsx)(es,{item:e,head:J,label:c.label,picked:t,busy:A?.number===e.number?A.kind:null,migrationLink:U,onPick:t=>et(e,t),onSync:()=>en(e,"sync"),onMerge:()=>M(e)},e.number);return(0,s.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,s.jsx)(b.F,{className:"min-h-0 flex-1",children:(0,s.jsxs)("div",{className:"mx-auto flex w-full max-w-5xl flex-col gap-8 px-6 pt-6 pb-12",children:[(0,s.jsxs)(W,{tabs:r,children:[(0,s.jsxs)("button",{type:"button",onClick:()=>g(!0),title:"Change which branches are compared",className:"flex cursor-pointer items-center gap-1.5 rounded-md px-1.5 py-0.5 outline-none hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60",children:[!ee&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:"font-mono",children:J}),(0,s.jsx)(d.juJ,{className:"size-3"})]}),(0,s.jsx)("span",{className:"font-mono",children:Z}),(0,s.jsx)(d.NOV,{className:"ml-1 size-3"})]}),(0,s.jsx)("span",{className:"ml-2",children:F.loading?"Fetching…":q?.fetchedAt?`Fetched ${new Date(q.fetchedAt).toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}`:null}),(0,s.jsx)(h.$,{size:"icon-sm",variant:"ghost",disabled:F.loading,"aria-label":"Refresh the release",title:"Fetch both branches and re-read GitHub",onClick:F.reload,children:(0,s.jsx)(d.oS8,{className:(0,C.cn)(F.loading&&"animate-spin")})})]}),(F.error||k||(q?.warnings.length??0)>0)&&(0,s.jsxs)("div",{className:"-mt-4 flex flex-col gap-2",children:[[F.error,k].filter(Boolean).map(e=>(0,s.jsxs)(Q,{tone:"error",children:[e,e===F.error&&(0,s.jsx)(h.$,{size:"xs",variant:"ghost",className:"ml-auto",onClick:()=>g(!0),children:"Change branches"})]},e)),q?.warnings.map(e=>(0,s.jsx)(Q,{tone:"warning",children:e},e))]}),!q&&F.loading?(0,s.jsxs)("p",{className:"text-sm text-muted-foreground",children:["Reading pull requests and ",J,"…"]}):q?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(Y,{title:"Going out",count:E.length,hint:`Open pull requests picked for this release, not merged into ${J} yet`,empty:"Nothing picked yet. Click the circle beside an open pull request below to add it.",trailing:(0,s.jsx)(em,{head:J,options:q.openPullRequests.filter(e=>!u.includes(e.number)),onAdd:t=>x(e,t)}),children:E.map(e=>ei(e,!0))}),(0,s.jsx)(Y,{title:`Open into ${J}`,count:L.length,hint:"Not planned for this release",empty:`No other open pull requests into ${J}.`,children:L.map(e=>ei(e,!1))}),!ee&&(0,s.jsxs)(Y,{title:`Already in ${J}`,count:X,hint:`Merged, waiting to go out to ${Z}`,empty:`${J} has nothing ${Z} does not. Everything merged has shipped.`,children:[q.pullRequests.map(e=>(0,s.jsx)(er,{item:e,head:J,migrationLink:U},e.number)),q.direct.map(e=>(0,s.jsx)(ea,{commit:e,head:J,migrationLink:U},e.sha))]}),n&&(0,s.jsx)(Y,{title:"Migrations to run",count:I.length,hint:"Every migration file this release adds or changes, and where each one has run",empty:"No migration files change in this release.",children:(0,s.jsx)(el,{rows:I,notes:q.notes,head:J,environments:n.environments,ledgers:n.ledgers,setHref:e=>n.migrationHref((0,_.K9)(e)),migrationLink:U})})]}):null]})}),p&&(0,s.jsx)(eh,{settings:c,onOpenChange:g,onSave:t=>m(e,t),onRemove:l}),z&&(0,s.jsx)(ed,{item:z,onOpenChange:e=>!e&&M(null),onMerge:()=>{M(null),en(z,"merge")}})]})}function W({tabs:e,children:t}){return(0,s.jsxs)("header",{className:"flex flex-col gap-4",children:[(0,s.jsx)("h2",{className:"text-lg font-semibold tracking-tight",children:"Next release"}),(0,s.jsxs)("div",{className:"flex items-end gap-4 border-b",children:[(0,s.jsx)("div",{className:"min-w-0 flex-1",children:e}),(0,s.jsx)("div",{className:"flex shrink-0 items-center gap-1 pb-1 text-xs text-muted-foreground",children:t})]})]})}function Q({tone:e,children:t}){return(0,s.jsxs)("p",{className:(0,C.cn)("flex items-center gap-2 rounded-lg border px-3 py-2 text-xs","error"===e?"border-destructive/30 bg-destructive/5 text-destructive":"border-amber-600/30 bg-amber-500/5 text-amber-700 dark:text-amber-400"),children:[(0,s.jsx)(d.e5t,{className:"size-3.5 shrink-0"}),t]})}function Y({title:e,count:t,hint:n,empty:r,trailing:a,children:i}){return(0,s.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,s.jsxs)("div",{className:"flex items-center gap-3",children:[(0,s.jsxs)("h3",{title:n,className:"flex min-w-0 flex-1 items-baseline gap-2 text-sm font-semibold",children:[e,(0,s.jsx)("span",{className:"text-xs font-normal text-muted-foreground tabular-nums",children:t})]}),a]}),0===t?(0,s.jsx)("p",{className:"rounded-lg border border-dashed px-4 py-4 text-sm text-muted-foreground",children:r}):(0,s.jsx)("div",{className:"divide-y overflow-hidden rounded-lg border bg-muted/25",children:i})]})}function J({parts:e,className:t}){let n=e.filter(e=>null!==e&&!1!==e&&""!==e);return(0,s.jsx)("p",{className:(0,C.cn)("mt-1 flex min-w-0 items-center gap-1.5 overflow-hidden text-xs text-muted-foreground",t),children:n.map((e,t)=>(0,s.jsxs)("span",{className:(0,C.cn)("flex items-center gap-1.5 whitespace-nowrap",1===t?"min-w-0 shrink [&>*:last-child]:truncate":"shrink-0"),children:[t>0&&(0,s.jsx)("span",{"aria-hidden":!0,children:"\xb7"}),e]},t))})}let Z=new Set(["CLEAN","HAS_HOOKS","UNSTABLE"]);function X(e){let t=e.standing;if(!t)return null;let n=t.behind??0,s="CONFLICTING"===t.mergeable||"DIRTY"===t.mergeState,r="UNKNOWN"===t.mergeable||"UNKNOWN"===t.mergeState,a=!s&&!r&&(n>0||"BEHIND"===t.mergeState),i={canMerge:!e.draft&&"MERGEABLE"===t.mergeable&&Z.has(t.mergeState),canSync:a};return s?{...i,tone:"conflict",text:`Conflicts with ${e.base}`,detail:`Does not merge cleanly into ${e.base}. Open it on GitHub to resolve the conflicts.`}:r?{...i,tone:"quiet",text:"Checking",detail:"GitHub is still working out whether it merges. Refresh in a moment."}:n>0||"BEHIND"===t.mergeState?{...i,tone:"warning",text:n>0?`${n} behind ${e.base}`:`Behind ${e.base}`,detail:`${e.base} has ${n>0?ep(n,"commit"):"commits"} this branch does not. It syncs without conflicts.`}:e.draft?{...i,tone:"quiet",text:"Draft",detail:"Mark it ready for review on GitHub to merge it."}:"BLOCKED"===t.mergeState?{...i,tone:"warning",text:"Blocked",detail:"A required review or check has not passed yet."}:"UNSTABLE"===t.mergeState?{...i,tone:"warning",text:"Checks failing",detail:"It merges cleanly, but some checks are failing."}:{...i,tone:"ready",text:"Ready to merge",detail:`Up to date with ${e.base} and merges cleanly.`}}let ee={ready:"bg-emerald-500",warning:"bg-amber-500",conflict:"bg-red-500",quiet:"bg-muted-foreground/50"};function et({standing:e,url:t}){let n=(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("span",{className:(0,C.cn)("size-1.5 shrink-0 rounded-full",ee[e.tone])}),e.text]}),r=(0,C.cn)("flex shrink-0 items-center gap-1.5 text-xs whitespace-nowrap","conflict"===e.tone?"text-red-600 dark:text-red-400":"text-muted-foreground");return"conflict"===e.tone?(0,s.jsxs)("a",{href:`${t}/conflicts`,target:"_blank",rel:"noreferrer",title:e.detail,className:(0,C.cn)(r,"hover:underline"),children:[n,(0,s.jsx)(d.qM8,{className:"size-3"})]}):(0,s.jsx)("span",{title:e.detail,className:r,children:n})}function en({picked:e,label:t,pinned:n,onPick:r}){let a=e?n?"Picked on this machine only. Click to take it out of the release.":`Labelled "${t}" on GitHub. Click to take it out of the release.`:t?`Add to the next release. Labels it "${t}" on GitHub.`:"Add to the next release on this machine";return(0,s.jsx)("button",{type:"button",role:"checkbox","aria-checked":e,"aria-label":a,title:a,onClick:()=>r(!e),className:(0,C.cn)("flex size-5 shrink-0 cursor-pointer items-center justify-center rounded-full border outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/60",e?"group/pick border-emerald-600 bg-emerald-600 text-white hover:border-muted-foreground hover:bg-transparent hover:text-foreground":"border-muted-foreground/40 text-transparent hover:border-foreground hover:text-foreground"),children:e?(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(d.wiW,{className:"size-3 group-hover/pick:hidden"}),(0,s.jsx)(d.yBK,{className:"hidden size-3 group-hover/pick:block"})]}):(0,s.jsx)(d.enO,{className:"size-3"})})}function es({item:e,head:t,label:n,picked:r,busy:a,migrationLink:i,onPick:l,onSync:o,onMerge:c}){let u=X(e),m=r&&"pinned"===e.planned;return(0,s.jsxs)("div",{className:"group flex items-center gap-4 px-4 py-3 transition-colors hover:bg-muted/50",children:[(0,s.jsx)(en,{picked:r,label:n,pinned:m,onPick:l}),(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"block truncate text-sm font-medium outline-none hover:underline focus-visible:underline",children:e.title}),(0,s.jsx)(J,{parts:[(0,s.jsxs)("span",{className:"font-mono",children:["#",e.number]},"number"),(0,s.jsxs)("span",{className:"block truncate font-mono",title:e.branch,children:[e.branch,e.base!==t?` → ${e.base}`:""]},"branch"),e.author.name,e.updatedAt?`updated ${ef(e.updatedAt)}`:null,m&&(0,s.jsxs)("span",{className:"flex items-center gap-1",title:"Picked on this machine only, not labelled on GitHub",children:[(0,s.jsx)(d.rq5,{className:"size-3"}),"just you"]},"pinned")]})]}),(0,s.jsx)(ei,{migrations:e.migrations,link:t=>i(t,e.branch)}),u&&(0,s.jsx)(et,{standing:u,url:e.url}),(0,s.jsxs)("div",{className:"flex shrink-0 items-center gap-1.5",children:[u?.canSync&&(0,s.jsxs)(h.$,{size:"xs",variant:"outline",disabled:null!==a,onClick:o,title:`Merge ${e.base} into ${e.branch} on GitHub, like the Update branch button`,children:["sync"===a?(0,s.jsx)(d.gnh,{className:"animate-spin"}):(0,s.jsx)(d.oS8,{}),"sync"===a?"Syncing":"Sync"]}),(0,s.jsxs)(h.$,{size:"xs",variant:"outline",disabled:!u?.canMerge||null!==a,onClick:c,title:u?.canMerge?`Merge into ${e.base} on GitHub`:u?.detail??"Not mergeable yet",className:(0,C.cn)(!r&&!a&&"opacity-0 group-hover:opacity-100 focus-visible:opacity-100"),children:["merge"===a?(0,s.jsx)(d.gnh,{className:"animate-spin"}):(0,s.jsx)(d._p3,{}),"merge"===a?"Merging":"Merge"]})]})]})}function er({item:e,head:t,migrationLink:n}){return(0,s.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3 transition-colors hover:bg-muted/50",children:[(0,s.jsx)(d._p3,{className:"size-5 shrink-0 text-violet-500"}),(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("a",{href:e.url,target:"_blank",rel:"noreferrer",className:"block truncate text-sm font-medium outline-none hover:underline focus-visible:underline",children:e.title}),(0,s.jsx)(J,{parts:[(0,s.jsxs)("span",{className:"font-mono",children:["#",e.number]},"number"),e.author.name,e.mergedAt?`merged ${ef(e.mergedAt)}`:null]})]}),(0,s.jsx)(ei,{migrations:e.migrations,link:e=>n(e,t)})]})}function ea({commit:e,head:t,migrationLink:n}){return(0,s.jsxs)("div",{className:"flex items-center gap-4 px-4 py-3 transition-colors hover:bg-muted/50",children:[(0,s.jsx)(d.txO,{className:"size-5 shrink-0 text-muted-foreground"}),(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("a",{href:e.url??void 0,target:"_blank",rel:"noreferrer",className:"block truncate text-sm font-medium outline-none hover:underline focus-visible:underline",children:e.subject}),(0,s.jsx)(J,{parts:[(0,s.jsx)("span",{className:"font-mono",children:e.sha.slice(0,7)},"sha"),"pushed without a pull request",e.author.name,ef(e.date)]})]}),(0,s.jsx)(ei,{migrations:e.migrations,link:e=>n(e,t)})]})}function ei({migrations:e,link:t}){let n=(0,i.useRouter)();if(0===e.length)return null;let r=new Map;for(let t of e)r.set(t.setName,[...r.get(t.setName)??[],t]);return(0,s.jsxs)(x.rI,{children:[(0,s.jsxs)(x.ty,{className:"flex h-6 shrink-0 cursor-pointer items-center gap-1 rounded-md bg-sky-500/10 px-2 text-xs text-sky-700 outline-none hover:bg-sky-500/20 focus-visible:ring-2 focus-visible:ring-ring/60 data-popup-open:bg-sky-500/20 dark:text-sky-300",children:[(0,s.jsx)(d.bkQ,{className:"size-3"}),ep(e.length,"migration"),(0,s.jsx)(d.RQe,{className:"size-3 opacity-70"})]}),(0,s.jsx)(x.SQ,{align:"end",children:[...r.entries()].map(([e,r])=>(0,s.jsxs)(x.I,{children:[(0,s.jsx)(x.lp,{children:e}),r.map(e=>{let r=t(e);return(0,s.jsxs)(x._2,{disabled:!r,title:r?.external?"Not in the folder you have checked out, so it opens on GitHub":void 0,onClick:()=>{r&&(r.external?window.open(r.href,"_blank","noopener,noreferrer"):n.push(r.href))},children:[(0,s.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:e.version}),(0,s.jsx)("span",{className:"truncate",children:e.name||e.path.split("/").at(-1)}),r?.external?(0,s.jsx)(d.qM8,{className:"ml-auto size-3 text-muted-foreground"}):(0,s.jsx)(d.juJ,{className:"ml-auto size-3 text-muted-foreground"})]},e.version)})]},e))})]})}function el({rows:e,notes:t,head:n,environments:r,ledgers:i,setHref:l,migrationLink:o}){return(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)("div",{className:"flex h-9 items-center bg-muted/40 pl-4 text-xs text-muted-foreground",children:[(0,s.jsx)("span",{className:"flex-1",children:"Migration"}),r.map(e=>(0,s.jsxs)("span",{className:(0,C.cn)("flex shrink-0 items-center justify-center gap-1.5",P.Z_),children:[(0,s.jsx)(c.F,{connection:e,className:"size-1.5"}),(0,s.jsx)("span",{className:"truncate",children:e.name})]},e.id))]}),(function(e){let t=new Map;for(let n of e)t.set(n.setName,[...t.get(n.setName)??[],n]);return[...t.entries()]})(e).map(([e,d])=>(0,s.jsxs)("div",{className:"py-1.5",children:[(0,s.jsx)("div",{className:"flex items-center gap-3 px-4 pt-1.5 pb-1",children:(0,s.jsx)(a(),{href:l(e),title:t[e],className:"truncate text-sm font-medium hover:underline",children:e})}),d.map(e=>(0,s.jsxs)(eo,{target:o(e,e.planned?e.sources[0]?.ref??n:n),children:[(0,s.jsxs)("span",{className:"flex min-w-0 flex-1 items-center gap-3 py-1.5 pr-3 pl-4",children:[(0,s.jsx)("span",{className:"w-10 shrink-0 font-mono text-xs text-muted-foreground",children:e.version}),(0,s.jsx)("span",{className:"min-w-0 truncate text-sm",children:e.name||e.path.split("/").at(-1)}),(0,s.jsxs)("span",{className:"flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground",children:[e.modified&&(0,s.jsx)("span",{className:"text-amber-700 dark:text-amber-400",title:"This file existed before and was edited in this release",children:"edited"}),e.planned&&(0,s.jsx)("span",{title:"Only on a pull request that is not merged yet",children:"not merged"}),!e.hasRevert&&(0,s.jsx)("span",{className:"text-muted-foreground/70",children:"no revert"})]}),(0,s.jsx)("span",{className:"ml-auto shrink-0 pl-2 font-mono text-xs text-muted-foreground",title:e.sources.map(e=>e.title).join("\n"),children:e.sources.map(e=>e.label).join(" ")})]}),r.map(t=>{let n=i?.[t.id],r=function(e,t){if(!e)return"unknown";let n=ec(e,t);return n?n.checksum&&t.checksum&&n.checksum!==t.checksum?"drifted":"applied":"pending"}(n?.ledger??null,e),a=ec(n?.ledger??null,e);return(0,s.jsx)("span",{title:n?.error?`${t.name}: ${n.error}`:`${e.version} is ${eu[r]} on ${t.name}${a?`, ${new Date(a.appliedAt).toLocaleString()}`:""}`,className:(0,C.cn)("flex h-8 shrink-0 items-center justify-center",P.Z_),children:(0,s.jsx)(P.oy,{status:r})},t.id)})]},e.version))]},e))]})}function eo({target:e,children:t}){let n="flex items-center outline-none transition-colors hover:bg-muted/50 focus-visible:bg-muted/50";return e?e.external?(0,s.jsx)("a",{href:e.href,target:"_blank",rel:"noreferrer",title:"Not in the folder you have checked out, so it opens on GitHub",className:n,children:t}):(0,s.jsx)(a(),{href:e.href,className:n,children:t}):(0,s.jsx)("div",{className:n,children:t})}function ed({item:e,onOpenChange:t,onMerge:n}){let r=X(e);return(0,s.jsx)(q.lG,{open:!0,onOpenChange:t,children:(0,s.jsxs)(q.Cf,{className:"sm:max-w-md",children:[(0,s.jsxs)(q.c7,{children:[(0,s.jsxs)(q.L3,{children:["Merge #",e.number," into ",e.base,"?"]}),(0,s.jsx)(q.rr,{children:e.title})]}),(0,s.jsxs)("div",{className:"flex flex-col gap-2 text-sm text-muted-foreground",children:[e.migrations.length>0&&(0,s.jsxs)("p",{children:["It brings ",ep(e.migrations.length,"migration"),". Check they have run on ",e.base,"'s database under Migrations to run."]}),r?.tone==="warning"&&(0,s.jsx)("p",{className:"text-amber-700 dark:text-amber-400",children:r.detail}),(0,s.jsx)("p",{children:"This merges it on GitHub right away."})]}),(0,s.jsxs)(q.Es,{children:[(0,s.jsx)(h.$,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),(0,s.jsxs)(h.$,{onClick:n,children:[(0,s.jsx)(d._p3,{"data-icon":"inline-start"}),"Merge pull request"]})]})]})})}function ec(e,t){return e?.entries.find(e=>e.setName===t.setName&&e.version===t.version)??null}let eu={applied:"applied",drifted:"applied, but the file changed since",pending:"not applied",unknown:"not read yet"};function em({head:e,options:t,onAdd:n}){let[r,a]=(0,o.useState)(""),i=(0,o.useMemo)(()=>{let e=r.trim().toLowerCase();return e?t.filter(t=>String(t.number).includes(e)||t.title.toLowerCase().includes(e)||t.author.name.toLowerCase().includes(e)):t},[t,r]);return 0===t.length?null:(0,s.jsxs)(f.G3,{items:i,filter:null,value:null,inputValue:r,onInputValueChange:e=>a(e),onOpenChange:e=>e&&a(""),itemToStringLabel:e=>`#${e.number} ${e.title}`,isItemEqualToValue:(e,t)=>e.number===t.number,onValueChange:e=>e&&n(e.number),children:[(0,s.jsxs)(p.M,{title:`Open pull requests into other branches than ${e}`,className:"flex h-7 shrink-0 cursor-pointer items-center gap-1.5 rounded-md px-2 text-xs text-muted-foreground outline-none hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60",children:[(0,s.jsx)(d.enO,{className:"size-3"}),"Add from another branch"]}),(0,s.jsxs)(f.h5,{className:"w-[28rem]",children:[(0,s.jsxs)("div",{className:"m-1 mb-0 flex h-8 items-center gap-1.5 rounded-lg px-2 text-muted-foreground focus-within:bg-muted/60",children:[(0,s.jsx)(d.TfF,{className:"size-3.5 shrink-0"}),(0,s.jsx)(g.o,{placeholder:"Search open pull requests",spellCheck:!1,autoComplete:"off",className:"h-full min-w-0 flex-1 bg-transparent text-[0.8rem] text-foreground outline-none placeholder:text-muted-foreground"})]}),(0,s.jsx)(f.$U,{children:"No matching pull requests"}),(0,s.jsx)(f.ex,{children:e=>(0,s.jsxs)(f.x4,{value:e,children:[(0,s.jsx)(d.rq5,{className:"size-3.5 shrink-0 text-muted-foreground"}),(0,s.jsxs)("span",{className:"font-mono text-[11px] text-muted-foreground",children:["#",e.number]}),(0,s.jsx)("span",{className:"min-w-0 flex-1 truncate text-xs",children:e.title}),(0,s.jsxs)("span",{className:"max-w-32 shrink-0 truncate font-mono text-[11px] text-muted-foreground",title:e.base,children:["→ ",e.base]})]},e.number)})]})]})}function eh({settings:e,onOpenChange:t,onSave:n,onRemove:r}){let[a,i]=(0,o.useState)(e),[l,d]=(0,o.useState)(e.head.trim()===e.base.trim());function c(){let e=l?a.base:a.head.trim()===a.base.trim()?T.A.head:a.head;n({...a,head:e}),t(!1)}let u=(e,t,n,r)=>(0,s.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,s.jsx)(H.J,{htmlFor:`release-${e}`,children:t}),(0,s.jsx)(G.p,{id:`release-${e}`,value:a[e],placeholder:n,spellCheck:!1,autoComplete:"off",onChange:t=>i({...a,[e]:t.target.value}),onKeyDown:e=>"Enter"===e.key&&c()}),(0,s.jsx)("p",{className:"text-xs text-muted-foreground",children:r})]});return(0,s.jsx)(q.lG,{open:!0,onOpenChange:t,children:(0,s.jsxs)(q.Cf,{className:"sm:max-w-lg",children:[(0,s.jsxs)(q.c7,{children:[(0,s.jsx)(q.L3,{children:"Release"}),(0,s.jsx)(q.rr,{children:l?"The release is the open pull requests into production, merged one at a time.":"The release is everything on the next-release branch that production does not have yet."})]}),(0,s.jsxs)("div",{className:"flex flex-col gap-4",children:[(0,s.jsx)("div",{role:"radiogroup","aria-label":"How changes reach production",className:"grid grid-cols-2 gap-1 rounded-lg bg-muted/60 p-1",children:[{on:!1,label:"Release branch",title:"Pull requests merge into a branch like dev, which ships to production"},{on:!0,label:"Straight to production",title:"Pull requests merge into production directly, with no release branch"}].map(e=>(0,s.jsx)("button",{type:"button",role:"radio","aria-checked":l===e.on,title:e.title,onClick:()=>d(e.on),className:(0,C.cn)("cursor-pointer rounded-md px-3 py-1.5 text-sm outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring/60",l===e.on?"bg-background font-medium text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:e.label},e.label))}),u("base","Production","origin/main","What is running in production. A branch or a commit."),!l&&u("head","Next release","origin/dev","What ships next. origin/ branches are fetched on every read."),u("label","Planned label","next-release","Open pull requests with this GitHub label count as planned for the release.")]}),(0,s.jsxs)(q.Es,{children:[r&&(0,s.jsx)(h.$,{variant:"ghost",className:"mr-auto text-destructive hover:text-destructive",onClick:()=>{r(),t(!1)},children:"Remove this repo"}),(0,s.jsx)(h.$,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),(0,s.jsx)(h.$,{onClick:c,children:"Save"})]})]})})}function ex({onOpenChange:e,onAdd:t}){let[n,r]=(0,o.useState)(""),a=n.trim(),i=a.startsWith("/")||a.startsWith("~")||/^[A-Za-z]:[\\/]/.test(a);function l(){a&&i&&(t(a),e(!1))}return(0,s.jsx)(q.lG,{open:!0,onOpenChange:e,children:(0,s.jsxs)(q.Cf,{className:"sm:max-w-lg",children:[(0,s.jsxs)(q.c7,{children:[(0,s.jsx)(q.L3,{children:"Add a repository"}),(0,s.jsx)(q.rr,{children:"A git checkout on this computer. Its pull requests are read with the GitHub CLI, so any repository you can open with gh works. It does not need a migrations folder."})]}),(0,s.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,s.jsx)(H.J,{htmlFor:"release-repo",children:"Folder"}),(0,s.jsx)(G.p,{id:"release-repo",value:n,placeholder:"~/code/backend",spellCheck:!1,autoComplete:"off",autoFocus:!0,"aria-invalid":a.length>0&&!i,onChange:e=>r(e.target.value),onKeyDown:e=>"Enter"===e.key&&l()}),a.length>0&&!i&&(0,s.jsx)("p",{className:"text-xs text-destructive",children:"An absolute path, or one starting with ~."})]}),(0,s.jsxs)(q.Es,{children:[(0,s.jsx)(h.$,{variant:"outline",onClick:()=>e(!1),children:"Cancel"}),(0,s.jsx)(h.$,{disabled:!a||!i,onClick:l,children:"Add"})]})]})})}function ep(e,t){return`${e} ${t}${1===e?"":"s"}`}function eg(e){return e.replace(/^origin\//,"")}function ef(e){let t=(Date.now()-new Date(e).getTime())/1e3;return Number.isFinite(t)?t<3600?`${Math.max(1,Math.round(t/60))}m ago`:t<86400?`${Math.round(t/3600)}h ago`:`${Math.round(t/86400)}d ago`:""}function eb({root:e,environmentNames:t,onOpenChange:n,onSave:r}){let[a,i]=(0,o.useState)(e??""),l=a.trim(),d=l.startsWith("/")||l.startsWith("~")||/^[A-Za-z]:[\\/]/.test(l);function c(){l&&d&&(r(l),n(!1))}return(0,s.jsx)(q.lG,{open:!0,onOpenChange:n,children:(0,s.jsxs)(q.Cf,{className:"sm:max-w-lg",children:[(0,s.jsxs)(q.c7,{children:[(0,s.jsx)(q.L3,{children:"Migrations folder"}),(0,s.jsxs)(q.rr,{children:["A folder on this computer. Each folder inside it that holds .sql files is one migration, read fresh from disk every time — whatever branch is checked out is what shows. ",t.join(", ")," will all read from it."]})]}),(0,s.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,s.jsx)(H.J,{htmlFor:"repo-root",children:"Path"}),(0,s.jsx)(G.p,{id:"repo-root",value:a,placeholder:"~/code/app/src/lib/supabase/migrations",spellCheck:!1,autoComplete:"off",autoFocus:!0,"aria-invalid":l.length>0&&!d,onChange:e=>i(e.target.value),onKeyDown:e=>"Enter"===e.key&&c()}),l.length>0&&!d&&(0,s.jsx)("p",{className:"text-xs text-destructive",children:"An absolute path, or one starting with ~."})]}),(0,s.jsxs)(q.Es,{children:[e&&(0,s.jsx)(h.$,{variant:"ghost",className:"mr-auto",onClick:function(){r(null),n(!1)},children:"Stop reading from disk"}),(0,s.jsx)(h.$,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),(0,s.jsx)(h.$,{disabled:!l||!d,onClick:c,children:"Save"})]})]})})}var ej=n(71612);function ev(){var e;let t,n=(0,i.useRouter)(),{connection:r}=(0,u.k)(),a=(0,$.jV)(e=>e.sets),c=(0,$.jV)(e=>e.createSet),p=(0,$.jV)(e=>e.adoptSet),g=(0,$.jV)(e=>e.addFiles),f=(0,$.jV)(e=>e.removeSet),j=(0,$.jV)(e=>e.ledgerSchema),q=(0,$.jV)(e=>e.history),A=(0,w.gz)(r.id),O=(0,l.ZG)((0,i.usePathname)()),E="migrations"===O.kind?O.view:void 0,I="timeline"===E?"history":"release"===E?"release":"migrations",[V,G]=(0,o.useState)(null),[H,_]=(0,o.useState)(null),[T,P]=(0,o.useState)(!1),[D,B]=(0,o.useState)(!1),[K,W]=(0,o.useState)(null),Q=(0,o.useMemo)(()=>[r,...A],[r,A]),Y=Q.map(e=>e.url).join("|"),{scope:J,root:Z,checkout:X}=(0,$.ox)(r.id),ee=(0,$.jV)(e=>e.setRepoRoot),et=(0,$.jV)(e=>e.setRepoCheckout),en=(0,$.ec)(),es=(0,$.kG)(J),er=(0,$.jV)(e=>e.setListFilter),ea=(0,ej.y)(Z,X),ei=(0,o.useMemo)(()=>[...ea.data?.sets??[]].sort((e,t)=>t.importedAt-e.importedAt),[ea.data]),el=(0,v.Y)(`ledgers:${j}:${Y}`,async e=>Object.fromEntries(await Promise.all(Q.map(async t=>{try{return[t.id,{ledger:await N.F.ledger(t.url,j,e),error:null}]}catch(n){if(e.aborted)throw n;return[t.id,{ledger:null,error:n instanceof Error?n.message:String(n)}]}})))),eo=(0,o.useCallback)((e,t)=>[...ei,...a].find(t=>t.name===e)?.steps.find(e=>e.version===t)??null,[ei,a]),ed=(0,o.useMemo)(()=>(0,k.x)(Q.map(e=>({connection:e,ledger:el.data?.[e.id]?.ledger??null})),q),[Q,el.data,q]),ec=`/${encodeURIComponent(r.id)}/migrations`,eu=(0,o.useCallback)(e=>{let t=c(e.name);g(t,e.files),n.push(`${ec}/${encodeURIComponent(t)}`)},[c,g,n,ec]);async function em(e){G(e),_(null);try{let t=await Promise.all(Q.map(async e=>{try{return{read:await N.F.ledger(e.url,j,void 0,!0),error:null}}catch(e){return{read:null,error:e instanceof Error?e.message:String(e)}}})),s=t.find(e=>e.error);if(s?.error)return void _(s.error);let r=t.some(e=>e.read&&void 0===e.read.withSql),a=new Map;for(let{read:n}of t)for(let t of n?.entries??[]){if(t.setName.trim()!==e)continue;let n=a.get(t.version);n?.applySql||a.set(t.version,t)}let{set:i,missing:l}=(0,z.wQ)(e,[...a.values()]);if(0===i.steps.length)return void _(r?"The YTDB running on your machine is older than this page and cannot send stored SQL. Restart it with `npx @theobourgeois/ytdb@latest`.":`${e} was applied before YTDB stored SQL, so it cannot be rebuilt. Drop its folder instead.`);p(i),l.length>0&&_(`Rebuilt ${i.steps.length} of ${i.steps.length+l.length}. No SQL was stored for ${l.join(", ")}.`),n.push(`${ec}/${encodeURIComponent(i.id)}`)}catch(e){_(e instanceof Error?e.message:String(e))}finally{G(null)}}let eh=(0,o.useMemo)(()=>[...a].sort((e,t)=>t.importedAt-e.importedAt),[a]),ex=(0,o.useMemo)(()=>(0,y.lF)(Q.map(e=>({connection:e,ledger:el.data?.[e.id]?.ledger??null})),[...ei,...a].map(e=>e.name)),[Q,el.data,ei,a]),ep=(0,o.useMemo)(()=>{let e=el.data?.[r.id]?.ledger??null,t=[],n=0;if(!e)return{sets:0,entries:t};for(let s of ei){let r=(0,y.gj)(s,(0,y.Gf)(e,s.name)).steps.filter(e=>!e.origins);if(0!==r.length)for(let e of(n+=1,r))t.push({setName:s.name,version:e.version,name:e.name,checksum:e.checksum,applySql:e.applySql,revertSql:e.revertSql})}return{sets:n,entries:t}},[el.data,r.id,ei]),eg=el.loading||ea.loading,ef=0===ei.length&&0===a.length&&0===ex.length,ev=(0,o.useCallback)(e=>Q.map(t=>({connection:t,summary:(0,y.eh)(e,el.data?.[t.id]?.ledger??null),read:!!el.data?.[t.id]?.ledger,error:el.data?.[t.id]?.error??null})),[Q,el.data]),eN=(0,o.useCallback)(e=>(0,y.yy)(e,ev(e).map(e=>({connectionId:e.connection.id,summary:e.summary,read:e.read})),es),[ev,es]),ey=(0,o.useMemo)(()=>ei.filter(eN),[ei,eN]),eS=(0,o.useMemo)(()=>eh.filter(eN),[eh,eN]),ez=""!==es.query.trim()||"all"!==es.status,eM="all"!==es.status&&void 0===el.data,eR=eM?0:ei.length+eh.length-ey.length-eS.length;return(0,s.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,s.jsxs)(m.X,{children:[(0,s.jsx)(d.olY,{className:"size-4 shrink-0 text-muted-foreground"}),(0,s.jsx)("span",{className:"font-medium",children:"Migrations"}),Z&&(0,s.jsx)(ew,{root:ea.data?.root??Z,git:ea.data?.git??null,checkouts:ea.data?.checkouts??[],checkout:ea.data?.checkout??null,onEdit:()=>B(!0),onPick:e=>et(J,e),worktreeCount:ea.data?.checkouts.length??0}),(0,s.jsxs)("div",{className:"ml-auto flex items-center gap-1",children:[(0,s.jsx)(h.$,{size:"icon-sm",variant:"ghost",disabled:eg,"aria-label":"Refresh",title:Z?"Re-read the folder and every environment's ledger":"Re-read every environment's ledger",onClick:function(){el.reload(),ea.reload()},children:(0,s.jsx)(d.oS8,{className:(0,C.cn)(eg&&"animate-spin")})}),!Z&&(0,s.jsxs)(h.$,{size:"sm",variant:"ghost",onClick:()=>B(!0),children:[(0,s.jsx)(d.WzY,{"data-icon":"inline-start"}),"Read from a folder"]}),(0,s.jsxs)(h.$,{size:"sm",variant:"ghost",onClick:()=>P(!0),children:[(0,s.jsx)(d.enO,{"data-icon":"inline-start"}),"New migration"]}),(Z||a.length>0)&&(0,s.jsxs)(x.rI,{children:[(0,s.jsx)(x.ty,{render:(0,s.jsx)(h.$,{size:"icon-sm",variant:"ghost","aria-label":"More migration actions"}),className:"cursor-pointer",children:(0,s.jsx)(d.YKd,{})}),(0,s.jsxs)(x.SQ,{align:"end",className:"min-w-72",children:[Z&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsxs)(x._2,{disabled:eg||0===ep.entries.length,onClick:()=>W(ep),children:[(0,s.jsx)(d.nXx,{}),"Mark everything as applied on ",r.name,(0,s.jsx)("span",{className:"ml-auto pl-3 font-mono text-[11px] text-muted-foreground",children:ep.entries.length})]}),(0,s.jsx)(x.mB,{}),(0,s.jsxs)(x._2,{onClick:()=>B(!0),children:[(0,s.jsx)(d.WzY,{}),"Change folder…"]})]}),a.length>0&&(0,s.jsxs)(s.Fragment,{children:[Z&&(0,s.jsx)(x.mB,{}),(0,s.jsxs)(x._2,{variant:"destructive",onClick:function(){for(let e of a)f(e.id)},children:["Forget ",a.length," imported migration",1===a.length?"":"s"]})]})]})]})]})]}),ea.error&&(0,s.jsxs)("p",{className:"flex items-start gap-2 border-b bg-destructive/5 px-4 py-1.5 text-xs text-destructive",children:[(0,s.jsx)(d.e5t,{className:"mt-px size-3.5 shrink-0"}),(0,s.jsx)("span",{className:"min-w-0 flex-1",children:ea.error}),(0,s.jsx)(h.$,{size:"xs",variant:"ghost",onClick:()=>B(!0),children:"Change folder"})]}),"release"===I?en?(0,s.jsx)(U,{scope:J,root:Z?ea.data?.root??Z:null,repoName:(t=(e=ea.data?.checkouts??[]).find(e=>e.main)??e[0])?t.path.split(/[\\/]/).filter(Boolean).pop()??null:null,environments:Q,ledgers:el.data,folderSets:ea.data?.sets,migrationHref:e=>`${ec}/${encodeURIComponent(e)}`,onPickFolder:()=>B(!0)}):(0,s.jsx)("div",{className:"min-h-0 flex-1"}):"history"===I?(0,s.jsx)(b.F,{className:"min-h-0 flex-1",children:(0,s.jsx)(S.H,{events:ed,connections:Q,loading:el.loading,ledgerSchema:j,findStep:eo,onLedgerChange:el.reload})}):en?ef&&Z&&ea.loading?(0,s.jsxs)("p",{className:"px-4 py-6 text-sm text-muted-foreground",children:["Reading ",Z,"…"]}):ef&&Z?(0,s.jsxs)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 p-6 text-center",children:[(0,s.jsxs)("p",{className:"text-sm",children:["Nothing in ",Z," yet."]}),(0,s.jsx)("p",{className:"max-w-md text-xs text-muted-foreground",children:"Each folder inside it that holds .sql files becomes a migration here, the moment it exists in any worktree of the repository."})]}):ef?(0,s.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-6",children:[(0,s.jsx)(M.k,{onFiles:eu,className:"w-full max-w-xl"}),(0,s.jsxs)("p",{className:"text-xs text-muted-foreground",children:["Or"," ",(0,s.jsx)("button",{type:"button",className:"cursor-pointer underline underline-offset-4 hover:text-foreground",onClick:()=>B(!0),children:"read straight from a folder on this computer"}),", so nothing has to be imported."]})]}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(ek,{filter:es,environments:Q,hidden:eR,onChange:e=>er(J,e)}),(0,s.jsx)(b.F,{className:"min-h-0 flex-1",children:eM?(0,s.jsx)("p",{className:"px-4 py-6 text-sm text-muted-foreground",children:"Reading ledgers…"}):(0,s.jsxs)(s.Fragment,{children:[ey.map(e=>(0,s.jsx)(e$,{set:e,href:`${ec}/${encodeURIComponent(e.id)}`,environments:ev(e)},e.id)),eS.length>0&&Z&&(0,s.jsx)("p",{className:"border-b px-4 pt-2.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase",title:"Imported into this browser rather than read from the folder.",children:"Imported"}),eS.map(e=>(0,s.jsx)(e$,{set:e,href:`${ec}/${encodeURIComponent(e.id)}`,environments:ev(e)},e.id)),ez&&0===ey.length&&0===eS.length&&(0,s.jsxs)("p",{className:"px-4 py-6 text-sm text-muted-foreground",children:["Nothing matches."," ",(0,s.jsx)("button",{type:"button",className:"cursor-pointer underline underline-offset-4 hover:text-foreground",onClick:()=>er(J,{query:"",status:"all"}),children:"Clear the filter"})]}),ex.length>0&&(0,s.jsxs)("div",{className:"border-b bg-muted/20",children:[(0,s.jsx)("p",{className:"px-4 pt-2.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase",title:"Applied to a database from elsewhere. The SQL is kept in its ledger, so it opens without the folder.",children:"In the ledger only"}),ex.map(e=>(0,s.jsx)(eC,{migration:e,busy:V===e.name,onOpen:()=>void em(e.name)},e.name)),H&&(0,s.jsx)("p",{className:"px-4 pt-1 pb-2 text-xs text-destructive",children:H})]}),!Z&&(0,s.jsx)("div",{className:"p-4",children:(0,s.jsx)(M.k,{onFiles:eu,compact:!0,className:"w-full"})})]})})]}):(0,s.jsx)("div",{className:"min-h-0 flex-1"}),(0,s.jsx)(F.lj,{caption:function(e,t,n,s){if(s&&0===e)return"Reading folder…";if(0===e&&0===t&&0===n)return"No migrations yet";let r=[];return e>0&&r.push(`${e} migration${1===e?"":"s"} on disk`),t>0&&r.push(`${t} imported`),n>0&&r.push(`${n} in the ledger only`),r.join(" \xb7 ")}(ei.length,a.length,ex.length,null!==Z&&ea.loading),pane:I,onPaneChange:e=>{e!==I&&n.push((0,l.Jn)({kind:"migrations",connectionId:r.id,view:"history"===e?"timeline":"release"===e?"release":void 0}),{scroll:!1})},historyCount:ed.length,showRelease:!0}),D&&(0,s.jsx)(eb,{root:Z,environmentNames:Q.map(e=>e.name),onOpenChange:B,onSave:e=>ee(J,e)}),K&&(0,s.jsx)(L,{connection:r,ledgerSchema:j,plan:K,onDone:()=>el.reload(),onOpenChange:e=>!e&&W(null)}),(0,s.jsx)(R.K,{open:T,title:"New migration",submitLabel:"Create",onOpenChange:P,onSubmit:function(e){let t=c(e);n.push(`${ec}/${encodeURIComponent(t)}`)}})]})}let eN={all:"All",pending:"Not fully applied",untouched:"Not started anywhere",complete:"Applied everywhere"};function ek({filter:e,environments:t,hidden:n,onChange:r}){let a="all"!==e.status;return(0,s.jsxs)("div",{className:"flex items-center gap-1 border-b px-2 py-1",children:[(0,s.jsx)(j.L,{value:e.query,onChange:e=>r({query:e.target.value}),placeholder:"Search migrations","aria-label":"Search migrations",className:"min-w-0 flex-1",trailing:e.query?(0,s.jsx)("button",{type:"button","aria-label":"Clear search",className:"cursor-pointer rounded p-0.5 hover:text-foreground",onClick:()=>r({query:""}),children:(0,s.jsx)(d.yBK,{className:"size-3.5"})}):null}),(0,s.jsxs)(x.rI,{children:[(0,s.jsxs)(x.ty,{render:(0,s.jsx)(h.$,{size:"sm",variant:a?"outline":"ghost"}),className:"cursor-pointer",children:[function(e,t){if(e.startsWith("pending:")){let n=t.find(t=>t.id===e.slice(8));return n?`Pending on ${n.name}`:eN.pending}return eN[e]}(e.status,t),(0,s.jsx)(d.RQe,{"data-icon":"inline-end"})]}),(0,s.jsx)(x.SQ,{align:"end",className:"min-w-56",children:(0,s.jsxs)(x.Hr,{value:e.status,onValueChange:e=>r({status:e}),children:[Object.keys(eN).map(e=>(0,s.jsx)(x.Ht,{value:e,children:eN[e]},e)),t.length>1&&(0,s.jsx)(x.mB,{}),t.length>1&&t.map(e=>(0,s.jsxs)(x.Ht,{value:`pending:${e.id}`,children:[(0,s.jsx)(c.F,{connection:e,className:"size-1.5"}),"Pending on ",e.name]},e.id))]})})]}),n>0&&(0,s.jsxs)("span",{className:"shrink-0 pr-1 text-[11px] tabular-nums text-muted-foreground",children:[n," hidden"]})]})}let ey={path:"",branch:"All worktrees",main:!1};function ew({root:e,git:t,checkouts:n,checkout:r,worktreeCount:a,onEdit:i,onPick:l}){var c;let u,[m,h]=(0,o.useState)(""),x=(0,o.useMemo)(()=>{let e=m.trim().toLowerCase();return e?n.filter(t=>t.branch.toLowerCase().includes(e)||t.path.toLowerCase().includes(e)):[ey,...n]},[n,m]),b=null===r,j="cursor-pointer rounded-md outline-none hover:bg-muted/60 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60",v=t&&(0,s.jsxs)("span",{className:"shrink-0 rounded border px-1.5 font-mono text-[10px]",children:[t.branch,t.dirty&&"*"]}),N=(0,s.jsx)("span",{className:"shrink-0 rounded border px-1.5 text-[10px]",children:"All worktrees"});return(0,s.jsxs)("div",{className:"flex min-w-0 items-center text-xs text-muted-foreground",children:[(0,s.jsxs)("button",{type:"button",title:`Reading from ${e}. Click to change.`,onClick:i,className:(0,C.cn)("flex min-w-0 items-center gap-1.5 px-1.5 py-0.5",j),children:[(0,s.jsx)(d.WzY,{className:"size-3.5 shrink-0"}),(0,s.jsx)("span",{className:"max-w-64 truncate font-mono text-[11px]",children:(u=(c=e).split(/[\/]/).filter(Boolean)).length>2?`…/${u.slice(-2).join("/")}`:c})]}),t&&n.length>1?(0,s.jsxs)(f.G3,{items:x,filter:null,value:b?ey:n.find(e=>e.path===r)??null,inputValue:m,onInputValueChange:e=>h(e),onOpenChange:e=>e&&h(""),itemToStringLabel:e=>e.branch,isItemEqualToValue:(e,t)=>e.path===t.path,onValueChange:e=>e&&l(e.path||null),children:[(0,s.jsxs)(p.M,{title:b?`Every worktree of the repository, ${a} in all, in one list. Pick one to read it alone.`:`${t.branch} (${t.commit}${t.dirty?", uncommitted changes":""}). Read from another worktree.`,className:(0,C.cn)("flex shrink-0 items-center gap-0.5 px-1 py-0.5",j),children:[b?N:v,(0,s.jsx)(d.klM,{className:"size-3"})]}),(0,s.jsxs)(f.h5,{className:"w-max min-w-56",children:[(0,s.jsxs)("div",{className:"m-1 mb-0 flex h-8 items-center gap-1.5 rounded-lg px-2 text-muted-foreground focus-within:bg-muted/60",children:[(0,s.jsx)(d.TfF,{className:"size-3.5 shrink-0"}),(0,s.jsx)(g.o,{placeholder:"Search worktrees",spellCheck:!1,autoComplete:"off",className:"h-full min-w-0 flex-1 bg-transparent text-[0.8rem] text-foreground outline-none placeholder:text-muted-foreground"})]}),(0,s.jsx)(f.$U,{children:"No matching worktrees"}),(0,s.jsx)(f.ex,{children:e=>(0,s.jsx)(f.x4,{value:e,title:e.path||void 0,children:e===ey?(0,s.jsx)("span",{className:"text-xs",children:"All worktrees"}):(0,s.jsx)("span",{className:"font-mono text-xs",children:e.branch})},e.path||"all")})]})]}):t&&(0,s.jsx)("span",{className:"px-1",title:`${t.branch} (${t.commit}${t.dirty?", uncommitted changes":""})`,children:v})]})}function e$({set:e,href:t,environments:n}){return(0,s.jsxs)(a(),{href:t,className:"flex items-center gap-3 border-b px-4 py-3 outline-none transition-colors hover:bg-muted/40 focus-visible:bg-muted/40",children:[(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsxs)("p",{className:"flex min-w-0 items-center gap-1.5 text-sm font-medium",children:[(0,s.jsx)("span",{className:"truncate",children:e.name}),e.note&&(0,s.jsx)("span",{title:e.note,className:"shrink-0 text-muted-foreground",children:(0,s.jsx)(d.UA_,{className:"size-3.5"})}),e.conflicts&&(0,s.jsx)("span",{title:(e.conflicts??[]).map(e=>`${e.version} differs: using ${e.used.branch}, also in ${e.others.map(e=>e.branch).join(", ")}`).join("\n"),className:"shrink-0 text-amber-600 dark:text-amber-400",children:(0,s.jsx)(d.e5t,{className:"size-3.5"})}),(0,s.jsx)(V.c,{origins:e.origins})]}),(0,s.jsxs)("p",{className:"truncate text-xs text-muted-foreground",children:[0===e.steps.length?"No files yet":`${e.steps.length} migration${1===e.steps.length?"":"s"}`,e.steps.length>0&&` \xb7 ${e.steps[0].version}–${e.steps.at(-1)?.version}`,e.skipped.length>0&&` \xb7 ${e.skipped.length} skipped`]})]}),(0,s.jsx)("div",{className:"flex shrink-0 items-center gap-1.5",children:n.map(e=>(0,s.jsx)(eS,{environment:e},e.connection.id))}),(0,s.jsx)(d.nNJ,{className:"size-4 shrink-0 text-muted-foreground/60"})]})}function eC({migration:e,busy:t,onOpen:n}){return(0,s.jsxs)("div",{className:"flex items-center gap-3 border-t px-4 py-2.5 first:border-t-0",children:[(0,s.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,s.jsx)("p",{className:"truncate text-sm",children:e.name}),(0,s.jsxs)("p",{className:"truncate text-xs text-muted-foreground",children:[e.total," migration",1===e.total?"":"s",e.versions.length>0&&` \xb7 ${e.versions[0]}–${e.versions.at(-1)}`]})]}),(0,s.jsx)("div",{className:"flex shrink-0 items-center gap-1.5",children:e.applied.map(t=>(0,s.jsxs)("span",{className:"flex h-6 items-center gap-1.5 rounded-lg border border-dashed px-2 text-[11px] text-muted-foreground",children:[(0,s.jsx)("span",{className:"max-w-24 truncate",children:t.connectionName}),(0,s.jsxs)("span",{className:"tabular-nums",children:[t.count,"/",e.total]})]},t.connectionId))}),(0,s.jsx)(h.$,{size:"xs",variant:"outline",disabled:t,onClick:n,children:t?"Opening…":"Open"})]})}function eS({environment:e}){let{connection:t,summary:n,read:r,error:a}=e,i=r&&n.total>0&&0===n.pending&&0===n.drifted,l=r&&0===n.applied&&0===n.drifted;return(0,s.jsxs)("span",{title:a?`${t.name}: ${a}`:r?`${t.name}: ${n.applied} of ${n.total} applied`:`${t.name}: reading…`,className:(0,C.cn)("flex h-6 items-center gap-1.5 rounded-lg border px-2 text-[11px]",a&&"border-destructive/30 text-destructive",i&&"border-emerald-600/30 bg-emerald-500/10",!a&&!i&&!l&&"border-amber-600/30 bg-amber-500/10",l&&"text-muted-foreground"),children:[(0,s.jsx)(c.F,{connection:t,className:"size-1.5"}),(0,s.jsx)("span",{className:"max-w-24 truncate",children:t.name}),(0,s.jsx)("span",{className:"tabular-nums",children:a?"—":r?`${n.applied}/${n.total}`:"…"})]})}},85488:(e,t,n)=>{"use strict";n.d(t,{G3:()=>C,h5:()=>R,$U:()=>A,oK:()=>M,x4:()=>q,ex:()=>F});var s=n(95155);n(12115);var r=n(92953),a=n(66289),i=n(58565),l=n(91075),o=n(2385),d=n(19001),c=n(93313),u=n(29432),m=n(56758),h=n(47028),x=n(63205),p=n(40980),g=n(89239),f=n(18460),b=n(60529);function j({className:e,...t}){return(0,s.jsx)("div",{"data-slot":"input-group",role:"group",className:(0,p.cn)("group/input-group relative flex h-8 w-full min-w-0 items-center rounded-lg border border-input transition-colors outline-none in-data-[slot=combobox-content]:focus-within:border-inherit in-data-[slot=combobox-content]:focus-within:ring-0 has-disabled:bg-input/50 has-disabled:opacity-50 has-[[data-slot=input-group-control]:focus-visible]:border-ring has-[[data-slot=input-group-control]:focus-visible]:ring-3 has-[[data-slot=input-group-control]:focus-visible]:ring-ring/50 has-[[data-slot][aria-invalid=true]]:border-destructive has-[[data-slot][aria-invalid=true]]:ring-3 has-[[data-slot][aria-invalid=true]]:ring-destructive/20 has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col has-[>textarea]:h-auto dark:bg-input/30 dark:has-disabled:bg-input/80 dark:has-[[data-slot][aria-invalid=true]]:ring-destructive/40 has-[>[data-align=block-end]]:[&>input]:pt-3 has-[>[data-align=block-start]]:[&>input]:pb-3 has-[>[data-align=inline-end]]:[&>input]:pr-1.5 has-[>[data-align=inline-start]]:[&>input]:pl-1.5",e),...t})}n(18349);let v=(0,f.F)("flex h-auto cursor-text items-center justify-center gap-2 py-1.5 text-sm font-medium text-muted-foreground select-none group-data-[disabled=true]/input-group:opacity-50 [&>kbd]:rounded-[calc(var(--radius)-5px)] [&>svg:not([class*='size-'])]:size-4",{variants:{align:{"inline-start":"order-first pl-2 has-[>button]:ml-[-0.3rem] has-[>kbd]:ml-[-0.15rem]","inline-end":"order-last pr-2 has-[>button]:mr-[-0.3rem] has-[>kbd]:mr-[-0.15rem]","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-2 [.border-b]:pb-2","block-end":"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-2 [.border-t]:pt-2"}},defaultVariants:{align:"inline-start"}});function N({className:e,align:t="inline-start",...n}){return(0,s.jsx)("div",{role:"group","data-slot":"input-group-addon","data-align":t,className:(0,p.cn)(v({align:t}),e),onClick:e=>{e.target.closest("button")||e.currentTarget.parentElement?.querySelector("input")?.focus()},...n})}let k=(0,f.F)("flex items-center gap-2 text-sm shadow-none",{variants:{size:{xs:"h-6 gap-1 rounded-[calc(var(--radius)-3px)] px-1.5 [&>svg:not([class*='size-'])]:size-3.5",sm:"","icon-xs":"size-6 rounded-[calc(var(--radius)-3px)] p-0 has-[>svg]:p-0","icon-sm":"size-8 p-0 has-[>svg]:p-0"}},defaultVariants:{size:"xs"}});function y({className:e,type:t="button",variant:n="ghost",size:r="xs",...a}){return(0,s.jsx)(g.$,{type:t,"data-size":r,variant:n,className:(0,p.cn)(k({size:r}),e),...a})}function w({className:e,...t}){return(0,s.jsx)(b.p,{"data-slot":"input-group-control",className:(0,p.cn)("flex-1 rounded-none border-0 bg-transparent shadow-none ring-0 focus-visible:ring-0 disabled:bg-transparent aria-invalid:ring-0 dark:bg-transparent dark:disabled:bg-transparent",e),...t})}var $=n(13267);let C=r.i;function S({className:e,children:t,...n}){return(0,s.jsxs)(a.M,{"data-slot":"combobox-trigger",className:(0,p.cn)("[&_svg:not([class*='size-'])]:size-4",e),...n,children:[t,(0,s.jsx)($.RQe,{className:"pointer-events-none size-4 text-muted-foreground"})]})}function z({className:e,...t}){return(0,s.jsx)(i.V,{"data-slot":"combobox-clear",render:(0,s.jsx)(y,{variant:"ghost",size:"icon-xs"}),className:(0,p.cn)(e),...t,children:(0,s.jsx)($.yBK,{className:"pointer-events-none"})})}function M({className:e,children:t,disabled:n=!1,showTrigger:r=!0,showClear:a=!1,inputRef:i,...o}){return(0,s.jsxs)(j,{className:(0,p.cn)("w-auto",e),children:[(0,s.jsx)(l.o,{ref:i,render:(0,s.jsx)(w,{disabled:n}),...o}),(0,s.jsxs)(N,{align:"inline-end",children:[r&&(0,s.jsx)(y,{size:"icon-xs",variant:"ghost",render:(0,s.jsx)(S,{}),"data-slot":"input-group-button",className:"group-has-data-[slot=combobox-clear]/input-group:hidden data-pressed:bg-transparent",disabled:n}),a&&(0,s.jsx)(z,{disabled:n})]}),t]})}function R({className:e,side:t="bottom",sideOffset:n=6,align:r="start",alignOffset:a=0,anchor:i,...l}){return(0,s.jsx)(o.K,{children:(0,s.jsx)(d.o,{side:t,sideOffset:n,align:r,alignOffset:a,anchor:i,className:"isolate z-80",children:(0,s.jsx)(c.I,{"data-slot":"combobox-content","data-chips":!!i,className:(0,p.cn)("group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...l})})})}function F({className:e,...t}){return(0,s.jsx)(u.e,{"data-slot":"combobox-list",className:(0,p.cn)("no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",e),...t})}function q({className:e,children:t,...n}){return(0,s.jsxs)(m.x,{"data-slot":"combobox-item",className:(0,p.cn)("relative flex h-8 w-full cursor-pointer items-center gap-2 rounded-lg pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[t,(0,s.jsx)(h.Q,{render:(0,s.jsx)("span",{className:"pointer-events-none absolute right-2 flex size-4 items-center justify-center"}),children:(0,s.jsx)($.wiW,{className:"pointer-events-none"})})]})}function A({className:e,...t}){return(0,s.jsx)(x.$,{"data-slot":"combobox-empty",className:(0,p.cn)("hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",e),...t})}}},e=>{e.O(0,[4506,1731,8026,2435,8361,8322,3960,544,6090,1413,5882,8441,3794,7358],()=>e(e.s=28330)),_N_E=e.O()}]);
@@ -0,0 +1 @@
1
+ (self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[9385],{5214:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"workAsyncStorage",{enumerable:!0,get:function(){return s.workAsyncStorageInstance}});let s=n(17828)},15923:(e,t,n)=>{"use strict";n.d(t,{T:()=>r,r:()=>i});let s=new Set;function r(e){return s.add(e),()=>{s.delete(e)}}function i(){for(let e of s)e()}},17828:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"workAsyncStorageInstance",{enumerable:!0,get:function(){return s}});let s=(0,n(64054).createAsyncLocalStorage)()},21957:(e,t,n)=>{"use strict";function s({moduleIds:e}){return null}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"PreloadChunks",{enumerable:!0,get:function(){return s}}),n(95155),n(47650),n(5214),n(2451),n(53887)},28242:(e,t,n)=>{"use strict";n.d(t,{MigrationDetail:()=>X});var s=n(95155),r=n(75707),i=n.n(r),a=n(98500),l=n.n(a),o=n(73321),d=n(12115),c=n(13267),u=n(36331),m=n(79781),p=n(17491),h=n(89239),f=n(72264),x=n(35942),g=n(87364),j=n(27529),v=n(25),b=n(62417),y=n(56012),k=n(40544),N=n(9385),w=n(85904),S=n(79668),C=n(34263),$=n(40980),O=n(72194),R=n(17639);function _({environments:e,targetId:t,onSelect:n}){let r=e.find(e=>e.connection.id===t);return r?(0,s.jsxs)("div",{className:"flex items-center gap-1.5",children:[(0,s.jsx)("span",{className:"text-xs text-muted-foreground",children:"Running against"}),(0,s.jsxs)(f.rI,{children:[(0,s.jsxs)(f.ty,{disabled:e.length<2,className:"flex h-7 cursor-pointer items-center gap-1.5 rounded-lg border bg-background px-2 text-xs font-medium outline-none hover:bg-muted/60 focus-visible:ring-3 focus-visible:ring-ring/50 disabled:cursor-default data-open:bg-muted/60",children:[(0,s.jsx)(O.F,{connection:r.connection}),(0,s.jsx)("span",{className:"max-w-32 truncate",children:r.connection.name})]}),(0,s.jsx)(f.SQ,{align:"start",className:"min-w-52",children:e.map(e=>(0,s.jsxs)(f._2,{onClick:()=>n(e.connection.id),className:e.connection.id===t?"font-medium":void 0,children:[(0,s.jsx)(O.F,{connection:e.connection}),(0,s.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.connection.name}),(0,s.jsxs)("span",{className:"shrink-0 tabular-nums text-muted-foreground",children:[e.summary.applied,"/",e.summary.total]})]},e.connection.id))})]})]}):null}function F({environments:e,targetId:t,caption:n,loading:r,selection:i,onSelect:a,onCompare:l}){return(0,s.jsxs)("div",{className:"flex h-11 shrink-0 items-center border-b bg-muted/20",children:[(0,s.jsx)("span",{className:"flex h-11 shrink-0 items-center pl-3",children:(0,s.jsx)(R.aL,{checked:i.checked,label:i.checked?"Clear selection":"Select all",onToggle:()=>i.onToggle()})}),(0,s.jsx)("span",{className:"min-w-0 flex-1 truncate px-2 text-xs text-muted-foreground",children:n}),e.map(e=>{let{connection:n,summary:i,ledger:l,error:o}=e,d=n.id===t;return(0,s.jsxs)("button",{type:"button",disabled:d,"aria-current":d?"true":void 0,title:d?`${n.name} is what Apply and Revert run against`:`Run against ${n.name} instead`,onClick:()=>a(n.id),className:(0,$.cn)("flex h-11 shrink-0 flex-col items-center justify-center gap-0.5 border-l text-[11px] outline-none",R.Z_,d?"cursor-default bg-foreground/[0.04] font-medium":"cursor-pointer text-muted-foreground hover:bg-muted/60 hover:text-foreground",r&&"opacity-60"),children:[(0,s.jsxs)("span",{className:"flex max-w-full items-center gap-1",children:[(0,s.jsx)(O.F,{connection:n,className:"size-1.5"}),(0,s.jsx)("span",{className:"truncate",children:n.name})]}),o?(0,s.jsx)("span",{className:"text-destructive",children:"unreachable"}):l?(0,s.jsxs)("span",{className:"tabular-nums text-muted-foreground/80",children:[i.applied,"/",i.total,i.drifted>0&&(0,s.jsx)("span",{className:"text-amber-600 dark:text-amber-400",children:" !"})]}):(0,s.jsx)("span",{className:"text-muted-foreground/70",children:"reading…"})]},n.id)}),(0,s.jsx)("div",{className:(0,$.cn)("flex shrink-0 items-center justify-end border-l pr-2 pl-1",R.yr),children:e.length>1&&(0,s.jsx)(h.$,{size:"icon-xs",variant:"ghost",title:"Compare the two schemas","aria-label":"Compare schemas",onClick:()=>{let n=e.find(e=>e.connection.id!==t);n&&l(n.connection.id)},children:(0,s.jsx)(c.R4X,{})})})]})}var M=n(65194),E=n(42763),I=n(60529),P=n(33807);function A({schema:e,found:t,onOpenChange:n,onSave:r}){let[i,a]=(0,d.useState)(e),l=i.trim(),o=(0,y.hD)(l),c=t.filter(e=>e.schema!==l);function u(){o&&(r(l),n(!1))}return(0,s.jsx)(E.lG,{open:!0,onOpenChange:n,children:(0,s.jsxs)(E.Cf,{className:"sm:max-w-md",children:[(0,s.jsxs)(E.c7,{children:[(0,s.jsx)(E.L3,{children:"Ledger schema"}),(0,s.jsx)(E.rr,{children:"Where each database keeps its record of what has run. Created on the first apply."})]}),(0,s.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,s.jsx)(P.J,{htmlFor:"ledger-schema",children:"Schema"}),(0,s.jsx)(I.p,{id:"ledger-schema",value:i,spellCheck:!1,autoComplete:"off","aria-invalid":l.length>0&&!o,onChange:e=>a(e.target.value),onKeyDown:e=>"Enter"===e.key&&u()}),(0,s.jsx)("p",{className:"font-mono text-xs text-muted-foreground",children:o?`${l}.${y.R9}`:"\xa0"}),l.length>0&&!o&&(0,s.jsx)("p",{className:"text-xs text-destructive",children:"Letters, digits and underscores only, starting with a letter or underscore."})]}),c.length>0&&(0,s.jsxs)("p",{className:"rounded-md border border-amber-600/25 bg-amber-500/8 px-3 py-2 text-xs",children:[c.map(e=>`${e.name} keeps its ledger in ${e.schema}`).join("; "),". That one stays where it is."]}),(0,s.jsxs)(E.Es,{children:[l!==y.aC&&(0,s.jsx)(h.$,{variant:"ghost",onClick:()=>a(y.aC),children:"Reset"}),(0,s.jsx)(h.$,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),(0,s.jsx)(h.$,{disabled:!o,onClick:u,children:"Save"})]})]})})}var z=n(17021),D=n(41069),q=n(20185),T=n(77649),L=n(27013),B=n(18349);function V({initial:e,file:t,onOpenChange:n,onSave:r}){let[i,a]=(0,d.useState)(e),[l,o]=(0,d.useState)(!1),[c,u]=(0,d.useState)(null),m=i.trim()!==e.trim();async function p(e){if(e?.preventDefault(),m&&!l){o(!0),u(null);try{await r(i.trim()),n(!1)}catch(e){u(e instanceof Error?e.message:String(e))}finally{o(!1)}}}return(0,s.jsx)(E.lG,{open:!0,onOpenChange:e=>!l&&n(e),children:(0,s.jsx)(E.Cf,{className:"sm:max-w-lg",showCloseButton:!1,children:(0,s.jsxs)("form",{onSubmit:e=>void p(e),className:"flex flex-col gap-4",children:[(0,s.jsx)(E.c7,{children:(0,s.jsxs)("div",{className:"flex items-baseline gap-3",children:[(0,s.jsx)(E.L3,{children:"Note"}),t&&(0,s.jsx)("span",{className:"ml-auto truncate font-mono text-[11px] text-muted-foreground",title:"Written into the migration's folder, to commit with the SQL",children:t})]})}),(0,s.jsx)(B.T,{autoFocus:!0,"aria-label":"Note",value:i,maxLength:y.XG,placeholder:"Apply 0001–0007, deploy the app, then apply 0008.",className:"max-h-[50vh] min-h-32",onChange:e=>a(e.target.value),onKeyDown:e=>{"Enter"===e.key&&(e.metaKey||e.ctrlKey)&&p()}}),c&&(0,s.jsx)("p",{className:"text-xs text-destructive",children:c}),(0,s.jsxs)(E.Es,{children:[(0,s.jsx)(h.$,{type:"button",variant:"ghost",disabled:l,onClick:()=>n(!1),children:"Cancel"}),(0,s.jsx)(h.$,{type:"submit",disabled:!m||l,children:l?"Saving…":"Save"})]})]})})})}var G=n(59221),U=n(83504),Y=n(67369),Z=n(71612);let K=i()(()=>Promise.all([n.e(7446),n.e(8238),n.e(3862),n.e(9406),n.e(9146)]).then(n.bind(n,79146)).then(e=>e.SchemaDiagram),{loadableGenerated:{webpack:()=>[79146]},ssr:!1});function X({setId:e}){let t=(0,o.useRouter)(),{connection:n,tables:r}=(0,u.k)(),i=(0,S.jV)(e=>e.addFiles),a=(0,S.jV)(e=>e.renameSet),p=(0,S.jV)(e=>e.setNote),O=(0,S.jV)(e=>e.removeSet),E=(0,S.jV)(e=>e.removeStep),I=(0,S.jV)(e=>e.record),P=(0,S.jV)(e=>e.ledgerSchema),B=(0,S.jV)(e=>e.setLedgerSchema),G=(0,S.Ss)(e),{scope:ee,root:et,checkout:en}=(0,S.ox)(n.id),es=(0,S.jV)(e=>e.setRepoCheckout),er=(0,Z.y)((0,y.km)(e)?et:null,en),ei=(0,y.km)(e)?er.data?.sets.find(t=>t.id===e)??null:G,ea=!!ei?.source,el=(0,k.gz)(n.id),eo=(0,C.En)(e=>e.setDraft),ed=(0,m.$C)(),ec=(0,q.ZG)((0,o.usePathname)()),eu=(0,D.hX)("migration"===ec.kind?ec.view:void 0),em=(0,d.useCallback)(s=>{s!==eu&&t.push((0,q.Jn)({kind:"migration",connectionId:n.id,setId:e,view:(0,D.z2)(s)}),{scroll:!1})},[eu,t,n.id,e]),ep=(0,d.useRef)(null);(0,d.useEffect)(()=>{let e=ep.current;"migrations"===eu&&e&&(ep.current=null,window.requestAnimationFrame(()=>document.getElementById(`migration-${e}`)?.scrollIntoView({block:"start",behavior:"smooth"})))},[eu]);let[eh,ef]=(0,d.useState)([]),ex=(0,d.useRef)(null),eg=ei?.steps.map(e=>e.version).join(",")??"";(0,d.useEffect)(()=>{let t=/^#migration-(.+)$/.exec(window.location.hash),n=t?`${e}:${t[1]}`:null;if(!t||"migrations"!==eu||ex.current===n)return;let s=document.getElementById(`migration-${decodeURIComponent(t[1])}`);if(!s)return;ex.current=n;let r=decodeURIComponent(t[1]);window.requestAnimationFrame(()=>{ef(e=>e.includes(r)?e:[...e,r]),s.scrollIntoView({block:"start",behavior:"smooth"})})},[e,eu,eg]);let[ej,ev]=(0,d.useState)([]),eb=(0,d.useRef)(null),[ey,ek]=(0,d.useState)(null),[eN,ew]=(0,d.useState)(null),[eS,eC]=(0,d.useState)(!1),[e$,eO]=(0,d.useState)(!1),[eR,e_]=(0,d.useState)(!1),[eF,eM]=(0,d.useState)(null),[eE,eI]=(0,d.useState)(null),[eP,eA]=(0,d.useState)(!1),[ez,eD]=(0,d.useState)(!1),[eq,eT]=(0,d.useState)(!1),eL=(0,d.useRef)(null),eB=(0,d.useRef)(!1),eV=(0,d.useMemo)(()=>[n,...el],[n,el]),eG=eV.map(e=>e.url).join("|"),eU=(0,g.Y)(`ledgers:${P}:${eG}`,async e=>Object.fromEntries(await Promise.all(eV.map(async t=>{try{return[t.id,{ledger:await j.F.ledger(t.url,P,e),error:null}]}catch(n){if(e.aborted)throw n;return[t.id,{ledger:null,error:n instanceof Error?n.message:String(n)}]}})))),eY=eU.data?.[n.id]??null,eZ=ei?.name??"",eK=(0,d.useMemo)(()=>(0,b.Gf)(eY?.ledger,eZ),[eY?.ledger,eZ]),eX=(0,d.useMemo)(()=>eV.map(e=>{let t=eU.data?.[e.id]??null,n=(0,b.Gf)(t?.ledger,eZ);return{connection:e,ledger:n,error:t?.error??null,summary:(0,b.eh)(ei,n)}}),[eV,eU.data,ei,eZ]),eH=(0,d.useMemo)(()=>{let e=new Set;for(let t of ei?.steps??[])if(eh.includes(t.version))for(let n of eX)"drifted"===(0,b.FY)(t,n.ledger)&&e.add(n.connection.id);return eV.filter(t=>e.has(t.id))},[ei,eh,eX,eV]),eW=(0,g.Y)(`stored:${P}:${eH.map(e=>e.url).join("|")}`,async e=>Object.fromEntries(await Promise.all(eH.map(async t=>{try{return[t.id,{ledger:await j.F.ledger(t.url,P,e,!0),error:null}]}catch(n){if(e.aborted)throw n;return[t.id,{ledger:null,error:n instanceof Error?n.message:String(n)}]}})))),eQ=`/${encodeURIComponent(n.id)}/migrations`,eJ=(0,S.jV)(e=>e.history),e0=(0,d.useMemo)(()=>(0,N.x)(eX.map(e=>({connection:e.connection,ledger:e.ledger})),eJ).filter(e=>e.setName===eZ),[eX,eJ,eZ]),e1=(0,d.useMemo)(()=>"schema"===eu&&ei?(0,w.DT)(ei.steps.map(e=>({version:e.version,sql:e.applySql}))):null,[eu,ei]),[e2,e5]=(0,d.useState)(null),e4=(0,d.useCallback)(e=>{e5(e),em("diagram")},[em]),e3=(0,d.useCallback)(e=>{ep.current=e,ef(t=>t.includes(e)?t:[...t,e]),em("migrations")},[em]),e6=(0,b.eh)(ei,eK),e7=(0,d.useMemo)(()=>(0,b.nb)(ei,eK),[ei,eK]),e8=(0,b.kB)(ei,eK),e9=(0,d.useCallback)(e=>{em("migrations"),ew(null),eO(!1),ek({steps:[e],blockedBy:null,direction:"apply"})},[em]),te=(0,d.useCallback)((e,t)=>ei&&ei.name===e?ei.steps.find(e=>e.version===t)??null:null,[ei]),tt=(0,d.useCallback)(t=>{eM(i(e,t.files)),em("migrations")},[i,e,em]),tn=(0,T.$)(tt);function ts(e,t,n=!1){(0!==t.steps.length||t.blockedBy)&&(ew(null),eO(!1),ek({...t,direction:e,recordOnly:n}))}function tr(e,t){return"apply"===t?e.applySql:e.revertSql}async function ti(){if(!ey||!ei)return;eO(!0),eC(!0);let e=ey.steps.map(e=>({version:e.version,name:e.name,status:"running"}));ew(e);try{let t=await j.F.rehearse(n.url,{steps:ey.steps.map(e=>({version:e.version,name:e.name,sql:tr(e,ey.direction)??""}))}),s=new Map(t.steps.map(e=>[e.version,e]));e=e.map(e=>{let n=s.get(e.version);return n?{...e,status:"ok",durationMs:n.durationMs}:t.failed?.version===e.version?{...e,status:"failed",error:t.failed.error}:{...e,status:"skipped"}})}catch(n){let t=n instanceof Error?n.message:String(n);e=e.map((e,n)=>0===n?{...e,status:"failed",error:t}:{...e,status:"skipped"})}ew(e),eC(!1)}function ta(e){return{steps:e,blockedBy:null}}async function tl(){if(!ey||!ei)return;eB.current=!1,eO(!1),eC(!0);let e=ey.steps.map(e=>({version:e.version,name:e.name,status:"waiting"}));ew(e);let t=(t,n)=>{ew(e=e.map((e,s)=>s===t?{...e,...n}:e))},s=t=>{ew(e=e.map((e,n)=>n>=t&&"waiting"===e.status?{...e,status:"skipped"}:e))};for(let[e,r]of ey.steps.entries()){if(eB.current){s(e);break}let i="apply"===ey.direction?r.applySql:r.revertSql;if(!i&&!ey.recordOnly){t(e,{status:"failed",error:"No revert file for this migration."}),s(e+1);break}t(e,{status:"running"});let a=crypto.randomUUID();try{let s=await j.F.migrate(n.url,{runId:a,direction:ey.direction,version:r.version,name:r.name,checksum:r.checksum,setName:ei.name,sql:i??"",revertSql:"apply"===ey.direction?r.revertSql:void 0,ledgerSchema:P,recordOnly:ey.recordOnly});t(e,{status:"ok",durationMs:s.durationMs}),I({runId:s.runId??a,setId:ei.id,setName:ei.name,connectionId:n.id,connectionName:n.name,direction:ey.direction,version:r.version,name:r.name,status:"ok",recorded:ey.recordOnly,durationMs:s.durationMs})}catch(l){let i=l instanceof Error?l.message:String(l);t(e,{status:"failed",error:i}),s(e+1),I({runId:a,setId:ei.id,setName:ei.name,connectionId:n.id,connectionName:n.name,direction:ey.direction,version:r.version,name:r.name,status:"failed",durationMs:0,error:i});break}}eC(!1),eU.reload(),eW.reload(),r.reload(),e.every(e=>"ok"===e.status)&&ev([])}function to(e){eo(n.id,e),t.push(`/${encodeURIComponent(n.id)}/query`)}function td(e){ed(e)}async function tc(e){ei&&(ei.source?(await j.F.note(ei.source.root,ei.source.path,e),er.reload()):p(ei.id,e))}async function tu(e){let t=e?.[0];eI(null),t&&eE&&ei&&eM(i(ei.id,[{path:`revert/${eE}_${t.name}`,text:await t.text()}]))}if(!ei){let t=(0,y.km)(e)&&er.loading;return(0,s.jsxs)("div",{className:"flex min-h-0 flex-1 flex-col",children:[(0,s.jsx)(H,{name:t?"Reading…":"Not found"}),(0,s.jsx)("div",{className:"flex flex-1 flex-col items-center justify-center gap-2 text-muted-foreground",children:t?(0,s.jsx)("p",{className:"text-sm",children:"Reading the folder…"}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)("p",{className:"text-sm",children:er.error?er.error:(0,y.km)(e)?en?"That migration is not in the folder in the worktree you picked.":"That migration is not in the folder in any worktree.":"That migration is no longer here."}),(0,s.jsx)(l(),{href:eQ,className:"text-foreground underline underline-offset-4",children:"All migrations"})]})})]})}let tm=new Set(ej),tp=ei.steps.filter(e=>tm.has(e.version)).length,th=tp>0,tf=th?(0,b.DM)(ei,eK,tm):(0,b.gj)(ei,eK),tx=th?(0,b.n9)(ei,eK,tm):(0,b.e)(ei,eK),tg=eS||eU.loading||er.loading;return(0,s.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",onDragOver:e=>{!ea&&e.dataTransfer.types.includes("Files")&&(e.preventDefault(),e_(!0))},children:[(0,s.jsxs)(H,{name:ei?.name??"",indexHref:eQ,children:[ei.source&&(0,s.jsxs)("span",{className:"flex min-w-0 items-center gap-1 text-[11px] text-muted-foreground",title:`Read from ${ei.source.path}`,children:[(0,s.jsx)(c.WzY,{className:"size-3.5 shrink-0"}),(0,s.jsx)("span",{className:"max-w-48 truncate font-mono",children:ei.source.path}),ei.origins?(0,s.jsx)(M.c,{origins:ei.origins,limit:3}):er.data?.git&&(0,s.jsxs)("span",{className:"shrink-0 rounded border px-1.5 font-mono text-[10px]",children:[er.data.git.branch,er.data.git.dirty&&"*"]})]}),(0,s.jsx)(_,{environments:eX,targetId:n.id,onSelect:td}),(0,s.jsxs)("div",{className:"ml-auto flex items-center gap-2",children:[(0,s.jsx)(h.$,{size:"icon-sm",variant:"ghost",disabled:eU.loading||er.loading,"aria-label":"Refresh",title:ea?"Re-read the files and every environment's ledger":"Re-read every environment's ledger",onClick:function(){eU.reload(),eW.reload(),ea&&er.reload()},children:(0,s.jsx)(c.oS8,{className:(0,$.cn)((eU.loading||er.loading)&&"animate-spin")})}),!ea&&(0,s.jsxs)(h.$,{size:"sm",variant:"ghost",onClick:()=>e_(!0),children:[(0,s.jsx)(c.FeY,{"data-icon":"inline-start"}),"Import"]}),(0,s.jsxs)(f.rI,{children:[(0,s.jsx)(f.ty,{render:(0,s.jsx)(h.$,{size:"icon-sm",variant:"ghost","aria-label":"More migration actions"}),className:"cursor-pointer",children:(0,s.jsx)(c.YKd,{})}),(0,s.jsxs)(f.SQ,{align:"end",className:"min-w-64",children:[(0,s.jsxs)(f._2,{disabled:tg||0===tf.steps.length,onClick:()=>ts("apply",ta(tf.steps),!0),children:[(0,s.jsx)(c.nXx,{}),"Mark ",tf.steps.length," as already applied"]}),(0,s.jsx)(f.mB,{}),(0,s.jsxs)(f._2,{disabled:tg||0===tx.steps.length,onClick:()=>ts("revert",tx),children:[(0,s.jsx)(c.ij9,{}),th?`Revert ${tx.steps.length} selected on ${n.name}`:`Revert everything on ${n.name}`]}),(0,s.jsx)(f.mB,{}),(0,s.jsxs)(f._2,{onClick:()=>eT(!0),children:[(0,s.jsx)(c.UA_,{}),ei.note?"Edit note":"Add note"]}),!ea&&(0,s.jsxs)(f._2,{onClick:()=>eD(!0),children:[(0,s.jsx)(c.NOV,{}),"Rename"]}),(0,s.jsxs)(f._2,{onClick:()=>eA(!0),children:[(0,s.jsx)(c.ooN,{}),"Ledger table",(0,s.jsxs)("span",{className:"ml-auto pl-3 font-mono text-[11px] text-muted-foreground",children:[P,".",y.R9]})]}),!ea&&(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(f.mB,{}),(0,s.jsx)(f._2,{variant:"destructive",onClick:function(){ei&&(O(ei.id),t.push(eQ))},children:"Forget this migration"})]})]})]}),(0,s.jsxs)(h.$,{size:"sm",disabled:tg||0===tf.steps.length,onClick:()=>ts("apply",tf),children:[(0,s.jsx)(c.eGB,{"data-icon":"inline-start"}),0===tf.steps.length?th?"Nothing selected to apply":"Up to date":`Apply ${tf.steps.length}${th?" selected":""} to ${n.name}`]})]})]}),eF&&(0,s.jsx)(Q,{report:eF,onDismiss:()=>eM(null)}),tn.error&&(0,s.jsx)("p",{className:"border-b bg-destructive/5 px-4 py-1.5 text-xs text-destructive",children:tn.error}),"migrations"===eu&&ei.note&&(0,s.jsx)(W,{note:ei.note,notePath:ei.source?.notePath??null,onEdit:()=>eT(!0)}),(0,s.jsxs)("div",{className:"relative flex min-h-0 flex-1 flex-col",children:["history"===eu?(0,s.jsx)(x.F,{className:"min-h-0 flex-1",children:(0,s.jsx)(z.H,{events:e0,connections:eV,loading:eU.loading,ledgerSchema:P,setName:eZ,findStep:te,onLedgerChange:eU.reload,onRetry:e9})}):"schema"===eu&&e1?(0,s.jsx)(x.F,{className:"min-h-0 flex-1",children:(0,s.jsx)(Y.ku,{changes:e1,onVersion:e3,className:"py-2"})}):"diagram"===eu?(0,s.jsx)(K,{steps:ei.steps,live:r.data??null,at:e2,onAt:e5,onVersion:e3}):eY?.error?(0,s.jsx)("p",{className:"flex-1 px-4 py-6 font-mono text-xs text-destructive",children:eY.error}):(0,s.jsxs)(s.Fragment,{children:[(0,s.jsx)(F,{environments:eX,targetId:n.id,caption:th?`${tp} selected`:function(e,t){if(t&&0===e.total)return"Reading…";let n=`${e.total} migration${1===e.total?"":"s"}`;return e.foreign>0?`${n} \xb7 ${e.foreign} not in this folder`:n}(e6,eU.loading),loading:eU.loading,selection:{checked:0!==tp&&(tp===ei.steps.length||"mixed"),onToggle:function(){if(!ei)return;let e=ei.steps.map(e=>e.version);ev(t=>t.some(t=>e.includes(t))?[]:e)}},onSelect:td,onCompare:function(e){k.lz.getState().setCompareTarget(n.id,e),t.push(`/${encodeURIComponent(n.id)}/diff`)}}),(0,s.jsxs)(x.F,{className:(0,$.cn)("min-h-0 flex-1",eU.loading&&"opacity-70"),children:[(ei?.steps.length??0)===0&&!ea&&(0,s.jsx)("div",{className:"p-6",children:(0,s.jsx)(T.k,{onFiles:tt,compact:!0})}),ei.conflicts&&(0,s.jsxs)("div",{className:"border-b bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:[(0,s.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,s.jsx)(c.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Worktrees disagree on ",1===ei.conflicts.length?"one file":`${ei.conflicts.length} files`,". Runs use the copy named first; read another worktree alone to run its copy."]}),(0,s.jsx)("ul",{className:"mt-1 space-y-1 pl-5",children:ei.conflicts.map(e=>(0,s.jsxs)("li",{className:"flex flex-wrap items-center gap-1.5",children:[(0,s.jsx)("span",{className:"font-mono text-[11px]",children:e.version}),(0,s.jsx)("span",{className:"rounded border px-1.5 font-mono text-[10px] text-foreground",children:e.used.branch}),e.others.map(e=>(0,s.jsx)(h.$,{size:"xs",variant:"ghost",title:`Read only ${e.path}`,onClick:()=>es(ee,e.path),children:(0,s.jsx)("span",{className:"font-mono text-[10px]",children:e.branch})},e.path))]},e.version))})]}),ei.skipped.length>0&&ea&&(0,s.jsxs)("div",{className:"border-b bg-muted/20 px-4 py-2 text-xs text-muted-foreground",children:[(0,s.jsxs)("span",{className:"flex items-center gap-1.5",children:[(0,s.jsx)(c.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Skipped ",ei.skipped.length," file",1===ei.skipped.length?"":"s"]}),(0,s.jsx)("ul",{className:"mt-1 space-y-0.5 pl-5 font-mono text-[11px]",children:ei.skipped.map(e=>(0,s.jsx)("li",{children:e},e))})]}),(ei?.steps??[]).map(e=>(0,s.jsx)(R.Tj,{step:e,targetId:n.id,status:(0,b.FY)(e,eK),environments:eX.map(t=>({connection:t.connection,status:(0,b.FY)(e,t.ledger),entry:(0,b.ay)(e,t.ledger),error:t.error})),isNewestApplied:e8?.version===e.version,expanded:eh.includes(e.version),busy:tg,editable:!ea,drift:function(e){let t=eX.filter(t=>"drifted"===(0,b.FY)(e,t.ledger)),s=t.find(e=>e.connection.id===n.id)??t[0];if(!s)return null;let r=eW.data?.[s.connection.id],i=r?.ledger?.entries.find(t=>t.setName===eZ&&t.version===e.version);return{connectionName:s.connection.name,appliedSql:r?.ledger?i?.applySql??null:void 0,error:r?.error??null}}(e),selected:tm.has(e.version),onSelect:t=>(function(e,t){if(!ei)return;let n=ei.steps.map(e=>e.version),s=eb.current;eb.current=e,ev(r=>{let i=!r.includes(e),a=[e];if(t&&s&&s!==e&&n.includes(s)){let[t,r]=[n.indexOf(s),n.indexOf(e)].sort((e,t)=>e-t);a=n.slice(t,r+1)}let l=new Set(r);for(let e of a)i?l.add(e):l.delete(e);return n.filter(e=>l.has(e))})})(e.version,t),onToggle:()=>{var t;return t=e.version,void ef(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t])},actions:{onApplyThrough:()=>ts("apply",(0,b.gj)(ei,eK,e.version)),onApplyOne:()=>ts("apply",{steps:[e],blockedBy:null}),onRevertThrough:()=>ts("revert",(0,b.e)(ei,eK,e.version)),onMarkApplied:()=>ts("apply",ta([e]),!0),onMarkPending:()=>ts("revert",ta([e]),!0),onAttachRevert:()=>{eI(e.version),window.requestAnimationFrame(()=>eL.current?.click())},onRemove:()=>ei&&E(ei.id,e.version),onOpenInEditor:to,onShowDiagram:()=>e4(e.version)}},e.version)),e7.length>0&&(0,s.jsx)(J,{entries:e7,connectionName:n.name})]})]}),eR&&!ea&&(0,s.jsx)("div",{className:"absolute inset-0 z-20 flex items-center justify-center bg-background/85 p-6",onDragOver:e=>e.preventDefault(),onDragLeave:()=>e_(!1),onDrop:e=>{e.preventDefault(),e_(!1),tn.importFrom(e.dataTransfer)},children:(0,s.jsx)(T.k,{onFiles:tt,className:"w-full max-w-xl bg-background"})})]}),(0,s.jsx)(D.lj,{pane:eu,onPaneChange:em,historyCount:e0.length,migrationsLabel:"Files",showSchema:!0,caption:e1?(0,Y.Zg)(e1):function({connectionName:e,summary:t,initialized:n,loading:s,foundIn:r,configuredSchema:i}){if(s&&null===n)return"Reading ledgers…";let a=[];return!1===n||t.pending>0?a.push(`${t.pending} of ${t.total} pending on ${e}`):a.push(`${e} is up to date`),t.drifted>0&&a.push(`${t.drifted} changed since applied`),r&&r!==i&&a.push(`ledger in ${r}`),a.join(" \xb7 ")}({connectionName:n.name,summary:e6,initialized:eK?.initialized??null,loading:eU.loading,foundIn:eK?.initialized?eK.schema:null,configuredSchema:P})}),(0,s.jsx)("input",{ref:eL,type:"file",accept:".sql",className:"sr-only",onChange:e=>{tu(e.target.files),e.target.value=""}}),(0,s.jsx)(L.K,{open:ez,title:"Rename migration",initial:ei.name,submitLabel:"Rename",onOpenChange:eD,onSubmit:function(e){ei&&a(ei.id,e)}}),eq&&(0,s.jsx)(V,{initial:ei.note??"",file:ei.source?ei.source.notePath?.split(/[\\/]/).at(-1)??"README.md":null,onOpenChange:eT,onSave:tc}),eP&&(0,s.jsx)(A,{schema:P,found:eX.filter(e=>e.ledger?.initialized).map(e=>({name:e.connection.name,schema:e.ledger?.schema??P})),onOpenChange:eA,onSave:e=>{B(e),eU.reload()}}),ey&&(0,s.jsx)(U.I,{open:!0,direction:ey.direction,connection:n,steps:ey.steps,blockedBy:ey.blockedBy,progress:eN,running:eS,recordOnly:ey.recordOnly??!1,note:ei.note,outOfOrder:"apply"!==ey.direction||ey.recordOnly?null:(0,b.nj)(eK,ey.steps),rehearsal:e$,onRun:()=>void tl(),onRehearse:!ey.recordOnly&&0!==ey.steps.length&&ey.steps.every(e=>{let t=tr(e,ey.direction);return!!t&&(0,v.Ol)(t).atomic})?()=>void ti():null,onStop:()=>{eB.current=!0},onClose:function(){eS||(ek(null),ew(null),eO(!1))}})]})}function H({name:e,indexHref:t,children:n}){let r=(0,s.jsx)(c.olY,{className:"size-4 shrink-0 text-muted-foreground"});return(0,s.jsxs)(p.X,{children:[t?(0,s.jsx)(l(),{href:t,title:"All migrations","aria-label":"All migrations",className:"flex size-6 shrink-0 items-center justify-center rounded-md outline-none hover:bg-muted/60 focus-visible:ring-2 focus-visible:ring-ring/60",children:r}):r,(0,s.jsx)("span",{className:"min-w-0 truncate font-medium",children:e}),n]})}function W({note:e,notePath:t,onEdit:n}){return(0,s.jsxs)("div",{title:t?`${t} \xb7 click to edit`:"Click to edit",onClick:e=>{e.target.closest("a")||n()},className:"group flex w-full cursor-pointer items-start gap-2 border-b px-4 py-2.5 text-left text-xs hover:bg-muted/30",children:[(0,s.jsx)(c.UA_,{className:"mt-px size-3.5 shrink-0 text-muted-foreground"}),(0,s.jsx)(G.o,{text:e,className:"max-h-40 min-w-0 flex-1 overflow-y-auto"}),(0,s.jsx)("button",{type:"button","aria-label":"Edit note",onClick:e=>{e.stopPropagation(),n()},className:"mt-px shrink-0 rounded-sm text-muted-foreground opacity-0 outline-none group-hover:opacity-100 focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring",children:(0,s.jsx)(c.NOV,{className:"size-3.5"})})]})}function Q({report:e,onDismiss:t}){let n=[];return e.added>0&&n.push(`added ${e.added}`),e.updated>0&&n.push(`updated ${e.updated}`),e.reverts>0&&n.push(`${e.reverts} revert file${1===e.reverts?"":"s"}`),(0,s.jsxs)("div",{className:"flex items-start gap-2 border-b bg-muted/30 px-4 py-1.5 text-xs",children:[(0,s.jsxs)("span",{className:"min-w-0 flex-1",children:[n.length>0?`Imported: ${n.join(", ")}`:"Nothing new in those files",e.skipped.length>0&&(0,s.jsxs)("span",{className:"text-muted-foreground",children:[" ","\xb7 skipped ",e.skipped.slice(0,2).join(", "),e.skipped.length>2&&` and ${e.skipped.length-2} more`]})]}),(0,s.jsx)(h.$,{size:"xs",variant:"ghost",onClick:t,children:"Dismiss"})]})}function J({entries:e,connectionName:t}){return(0,s.jsxs)("div",{className:"border-t bg-muted/20",children:[(0,s.jsxs)("p",{className:"flex items-center gap-2 px-4 py-2 text-xs text-muted-foreground",children:[(0,s.jsx)(c.e5t,{className:"size-3.5 shrink-0 text-amber-600 dark:text-amber-400"}),"Applied on ",t,", not in this folder"]}),e.map(e=>(0,s.jsxs)("div",{className:"flex items-center gap-2 px-4 py-1.5 text-xs opacity-70",children:[(0,s.jsx)(R.oy,{status:"applied"}),(0,s.jsx)("span",{className:"shrink-0 font-mono text-muted-foreground",children:e.version}),(0,s.jsx)("span",{className:"min-w-0 flex-1 truncate",children:e.name||"—"}),(0,s.jsx)("span",{className:"shrink-0 text-muted-foreground/70",children:new Date(e.appliedAt).toLocaleString()})]},e.version))]})}},34263:(e,t,n)=>{"use strict";n.d(t,{En:()=>c,Pc:()=>d,jl:()=>o});var s=n(1934),r=n(31692),i=n(40980),a=n(63307);let l="ytdb:queries";(0,a.q)("db-studio:queries",l);let o=144,d=800,c=(0,s.v)()((0,r.Zr)(e=>({drafts:{},editorHeight:224,history:[],setDraft:(t,n)=>e(e=>({drafts:{...e.drafts,[t]:n}})),setEditorHeight:t=>e({editorHeight:Math.min(d,Math.max(o,Math.round(t)))}),record:(t,n)=>e(e=>{let s=n.trim();if(!s)return e;let r=e.history.find(e=>e.connectionId===t&&e.sql===s),a={id:r?.id??(0,i.z)(),connectionId:t,sql:s,executedAt:Date.now()},l=0,o=0;return{history:[a,...e.history.filter(e=>e.id!==a.id)].filter(e=>!(l>=200)&&!(o+e.sql.length>1e6)&&(l+=1,o+=e.sql.length,!0))}}),remove:t=>e(e=>({history:e.history.filter(e=>e.id!==t)}))}),{name:l}))},41112:(e,t,n)=>{"use strict";function s({reason:e,children:t}){return t}Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"BailoutToCSR",{enumerable:!0,get:function(){return s}}),n(1980)},52310:(e,t,n)=>{Promise.resolve().then(n.bind(n,28242))},64054:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={bindSnapshot:function(){return o},createAsyncLocalStorage:function(){return l},createSnapshot:function(){return d}};for(var s in n)Object.defineProperty(t,s,{enumerable:!0,get:n[s]});let r=Object.defineProperty(Error("Invariant: AsyncLocalStorage accessed in runtime where it is not available"),"__NEXT_ERROR_CODE",{value:"E504",enumerable:!1,configurable:!0});class i{disable(){throw r}getStore(){}run(){throw r}exit(){throw r}enterWith(){throw r}static bind(e){return e}}let a="u">typeof globalThis&&globalThis.AsyncLocalStorage;function l(){return a?new a:new i}function o(e){return a?a.bind(e):i.bind(e)}function d(){return a?a.snapshot():function(e,...t){return e(...t)}}},68635:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return o}});let s=n(95155),r=n(12115),i=n(41112);function a(e){return{default:e&&"default"in e?e.default:e}}n(21957);let l={loader:()=>Promise.resolve(a(()=>null)),loading:null,ssr:!0},o=function(e){let t={...l,...e},n=(0,r.lazy)(()=>t.loader().then(a)),o=t.loading;function d(e){let a=o?(0,s.jsx)(o,{isLoading:!0,pastDelay:!0,error:null}):null,l=!t.ssr||!!t.loading,d=l?r.Suspense:r.Fragment,c=t.ssr?(0,s.jsxs)(s.Fragment,{children:[null,(0,s.jsx)(n,{...e})]}):(0,s.jsx)(i.BailoutToCSR,{reason:"next/dynamic",children:(0,s.jsx)(n,{...e})});return(0,s.jsx)(d,{...l?{fallback:a}:{},children:c})}return d.displayName="LoadableComponent",d}},75707:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r}});let s=n(73623)._(n(68635));function r(e,t){let n={};"function"==typeof e&&(n.loader=e);let r={...n,...t};return(0,s.default)({...r,modules:r.loadableGenerated?.modules})}("function"==typeof t.default||"object"==typeof t.default&&null!==t.default)&&void 0===t.default.__esModule&&(Object.defineProperty(t.default,"__esModule",{value:!0}),Object.assign(t.default,t),e.exports=t.default)},79781:(e,t,n)=>{"use strict";n.d(t,{$C:()=>c,yG:()=>u});var s=n(73321),r=n(12115),i=n(27529),a=n(15923),l=n(20185),o=n(69586),d=n(36331);function c(){let e=(0,s.useRouter)(),t=(0,s.usePathname)(),{connection:n}=(0,d.k)(),c=(0,o.Z)(e=>e.connections);return(0,r.useCallback)(async s=>{if(s===n.id)return;let r=c.find(e=>e.id===s);if(!r)return;(0,a.r)();let o=(0,l.ZG)(t),d=!!n.layoutGroup&&n.layoutGroup===r.layoutGroup,u=!0;if("table"===o.kind&&!d)try{var m,p;m=await i.F.tables(r.url),p=o.table,u=m.some(e=>e.schema===p.schema&&e.name===p.name)}catch{u=!1}e.push((0,l.gZ)(t,s,{tableExists:u}))},[n.id,n.layoutGroup,c,t,e])}function u(){let{connection:e}=(0,d.k)(),t=(0,o.Z)(e=>e.connections),n=c(),s=function(e,t){let n=e.findIndex(e=>e.id===t);if(!(e.length<2)&&-1!==n)return e[(n+1)%e.length]}(t,e.id);return{run:()=>s?n(s.id):Promise.resolve(),enabled:void 0!==s,next:s}}}},e=>{e.O(0,[4506,1731,8026,2435,8361,8322,544,6090,1413,5882,8441,3794,7358],()=>e(e.s=52310)),_N_E=e.O()}]);