firstly 0.1.0-next.3 → 0.1.0-next.4

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 (87) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/esm/auth/Entities.d.ts +2 -2
  3. package/esm/auth/Entities.js +1 -1
  4. package/esm/auth/static/assets/Page-5iUUg7GN.d.ts +2 -0
  5. package/esm/auth/static/assets/Page-5iUUg7GN.js +1 -0
  6. package/esm/auth/static/assets/Page-BcSzu3xq.d.ts +2 -0
  7. package/esm/auth/static/assets/Page-BcSzu3xq.js +20 -0
  8. package/esm/auth/static/assets/Page-sEK21EQB.d.ts +2 -0
  9. package/esm/auth/static/assets/Page-sEK21EQB.js +1 -0
  10. package/esm/auth/static/assets/index-RpcgeXPm.d.ts +232 -0
  11. package/esm/auth/static/assets/index-RpcgeXPm.js +2 -0
  12. package/esm/auth/static/index.html +1 -1
  13. package/esm/bin/cmd.js +5 -5
  14. package/esm/feedback/ui/DialogIssue.svelte +8 -1
  15. package/esm/feedback/ui/DialogIssues.svelte +1 -1
  16. package/esm/feedback/ui/DialogMilestones.svelte +2 -3
  17. package/esm/feedback/ui/Feedback.svelte +1 -1
  18. package/esm/formats/dates.js +1 -1
  19. package/esm/index.d.ts +3 -83
  20. package/esm/index.js +3 -45
  21. package/esm/{FF_Entity.js → internals/FF_Entity.js} +1 -1
  22. package/esm/{FF_Fields.js → internals/FF_Fields.js} +1 -1
  23. package/esm/{cellsBuildor.d.ts → internals/cellsBuildor.d.ts} +1 -1
  24. package/esm/{common.d.ts → internals/common.d.ts} +0 -2
  25. package/esm/internals/common.js +3 -0
  26. package/esm/{helper.js → internals/helper.js} +1 -1
  27. package/esm/internals/index.d.ts +83 -0
  28. package/esm/internals/index.js +45 -0
  29. package/esm/{storeItem.js → internals/storeItem.js} +2 -2
  30. package/esm/svelte/dialog/DialogPrimitive.svelte +1 -1
  31. package/esm/svelte/dialog/DialogPrimitive.svelte.d.ts +1 -1
  32. package/esm/svelte/dialog/dialog.d.ts +1 -1
  33. package/esm/svelte/dialog/dialog.js +1 -1
  34. package/esm/ui/Button.svelte +1 -1
  35. package/esm/ui/Button.svelte.d.ts +1 -1
  36. package/esm/ui/Field.svelte +2 -2
  37. package/esm/ui/Field.svelte.d.ts +1 -1
  38. package/esm/ui/FieldGroup.svelte +2 -2
  39. package/esm/ui/FieldGroup.svelte.d.ts +3 -3
  40. package/esm/ui/Grid.svelte +3 -3
  41. package/esm/ui/Grid.svelte.d.ts +2 -2
  42. package/esm/ui/Grid2.svelte +3 -3
  43. package/esm/ui/Grid2.svelte.d.ts +1 -1
  44. package/esm/ui/dialog/DialogForm.svelte +2 -2
  45. package/esm/ui/dialog/DialogPrimitive.svelte +1 -1
  46. package/esm/ui/dialog/DialogPrimitive.svelte.d.ts +1 -1
  47. package/esm/ui/dialog/FormEditAction.svelte +1 -1
  48. package/esm/ui/dialog/FormEditAction.svelte.d.ts +1 -1
  49. package/esm/ui/dialog/dialog.d.ts +1 -1
  50. package/esm/ui/dialog/dialog.js +1 -1
  51. package/esm/ui/index.d.ts +1 -1
  52. package/esm/ui/internals/Textarea.svelte +1 -1
  53. package/esm/ui/internals/select/MultiSelectMelt.svelte +1 -1
  54. package/esm/ui/internals/select/MultiSelectMelt.svelte.d.ts +1 -1
  55. package/esm/ui/internals/select/SelectMelt.svelte +1 -1
  56. package/esm/ui/internals/select/SelectMelt.svelte.d.ts +1 -1
  57. package/esm/ui/internals/select/SelectRadio.svelte +1 -1
  58. package/esm/ui/internals/select/SelectRadio.svelte.d.ts +1 -1
  59. package/esm/ui/link/LinkPlus.svelte +1 -1
  60. package/esm/ui/link/LinkPlus.svelte.d.ts +1 -1
  61. package/esm/virtual/Customer.js +1 -1
  62. package/esm/virtual/StateDemoEnum.d.ts +2 -2
  63. package/esm/virtual/StateDemoEnum.js +1 -1
  64. package/esm/virtual/UIEntity.js +1 -1
  65. package/package.json +5 -1
  66. package/esm/ROUTES.d.ts +0 -102
  67. package/esm/ROUTES.js +0 -106
  68. package/esm/auth/static/assets/Page-CTZPxniP.d.ts +0 -6
  69. package/esm/auth/static/assets/Page-CTZPxniP.js +0 -1
  70. package/esm/auth/static/assets/Page-D0d9iZO-.d.ts +0 -6
  71. package/esm/auth/static/assets/Page-D0d9iZO-.js +0 -1
  72. package/esm/auth/static/assets/Page-DXshwJi7.d.ts +0 -6
  73. package/esm/auth/static/assets/Page-DXshwJi7.js +0 -20
  74. package/esm/auth/static/assets/index-LRDptjak.d.ts +0 -217
  75. package/esm/auth/static/assets/index-LRDptjak.js +0 -44
  76. package/esm/common.js +0 -8
  77. /package/esm/{BaseEnum.d.ts → internals/BaseEnum.d.ts} +0 -0
  78. /package/esm/{BaseEnum.js → internals/BaseEnum.js} +0 -0
  79. /package/esm/{FF_Entity.d.ts → internals/FF_Entity.d.ts} +0 -0
  80. /package/esm/{FF_Fields.d.ts → internals/FF_Fields.d.ts} +0 -0
  81. /package/esm/{cellsBuildor.js → internals/cellsBuildor.js} +0 -0
  82. /package/esm/{helper.d.ts → internals/helper.d.ts} +0 -0
  83. /package/esm/{storeItem.d.ts → internals/storeItem.d.ts} +0 -0
  84. /package/esm/{storeList.d.ts → internals/storeList.d.ts} +0 -0
  85. /package/esm/{storeList.js → internals/storeList.js} +0 -0
  86. /package/esm/{theme.d.ts → internals/theme.d.ts} +0 -0
  87. /package/esm/{theme.js → internals/theme.js} +0 -0
package/esm/ROUTES.js DELETED
@@ -1,106 +0,0 @@
1
- /* eslint-disable */
2
- /**
3
- * This file was generated by 'vite-plugin-kit-routes'
4
- *
5
- * >> DO NOT EDIT THIS FILE MANUALLY <<
6
- */
7
- /**
8
- * PAGES
9
- */
10
- const PAGES = {
11
- "/": `/`,
12
- "/auth": `/auth`,
13
- "/demo/FF_Cell": `/demo/FF_Cell`,
14
- "/demo/FF_Form_Grid": `/demo/FF_Form_Grid`,
15
- "/demo/FF_Layout": `/demo/FF_Layout`,
16
- "/demo/FF_Layout/grid": `/demo/FF_Layout/grid`,
17
- "/demo/FF_Simple": `/demo/FF_Simple`,
18
- "/mail": `/mail`,
19
- "/ui/dialog": `/ui/dialog`,
20
- "/ui/enum": `/ui/enum`,
21
- "/ui/fieldGroup": `/ui/fieldGroup`,
22
- "/ui/select": `/ui/select`
23
- };
24
- /**
25
- * SERVERS
26
- */
27
- const SERVERS = {};
28
- /**
29
- * ACTIONS
30
- */
31
- const ACTIONS = {};
32
- /**
33
- * LINKS
34
- */
35
- const LINKS = {
36
- "firstly_sign_in": `/ff/auth/sign-in`,
37
- "remult_admin": `/api/admin`,
38
- "github": (params) => {
39
- params = params ?? {};
40
- params['owner'] = params['owner'] ?? "\"jycouet\"";
41
- params['repo'] = params['repo'] ?? "\"firstly\"";
42
- return `https://github.com/${params['owner']}/${params['repo']}`;
43
- }
44
- };
45
- /**
46
- * Append search params to a string
47
- */
48
- export const appendSp = (sp, prefix = '?') => {
49
- if (sp === undefined)
50
- return '';
51
- const params = new URLSearchParams();
52
- const append = (n, v) => {
53
- if (v !== undefined) {
54
- params.append(n, String(v));
55
- }
56
- };
57
- let anchor = '';
58
- for (const [name, val] of Object.entries(sp)) {
59
- if (name === '__KIT_ROUTES_ANCHOR__' && val !== undefined) {
60
- anchor = `#${val}`;
61
- continue;
62
- }
63
- if (Array.isArray(val)) {
64
- for (const v of val) {
65
- append(name, v);
66
- }
67
- }
68
- else {
69
- append(name, val);
70
- }
71
- }
72
- const formatted = params.toString();
73
- if (formatted || anchor) {
74
- return `${prefix}${formatted}${anchor}`.replace('?#', '#');
75
- }
76
- return '';
77
- };
78
- /**
79
- * get the current search params
80
- *
81
- * Could be use like this:
82
- * ```
83
- * route("/cities", { page: 2 }, { ...currentSP() })
84
- * ```
85
- */
86
- export const currentSp = () => {
87
- const params = new URLSearchParams(window.location.search);
88
- const record = {};
89
- for (const [key, value] of params.entries()) {
90
- record[key] = value;
91
- }
92
- return record;
93
- };
94
- const AllObjs = { ...PAGES, ...ACTIONS, ...SERVERS, ...LINKS };
95
- export const routes = [
96
- ...new Set(Object.keys(AllObjs).map((route) => /^\/.*|[^ ]?\/.*$/.exec(route)?.[0] ?? route)),
97
- ];
98
- export function route(key, ...params) {
99
- if (AllObjs[key] instanceof Function) {
100
- const element = AllObjs[key];
101
- return element(...params);
102
- }
103
- else {
104
- return AllObjs[key];
105
- }
106
- }
@@ -1,6 +0,0 @@
1
- export { a as default };
2
- declare function a(e: any, s: any): any;
3
- declare namespace a {
4
- let ____A_17405: string;
5
- export { ____A_17405 as __@A@17405 };
6
- }
@@ -1 +0,0 @@
1
- import{D as r,E as l,ak as m,S as o,T as d,U as n,V as p,W as u,Y as i}from"./index-LRDptjak.js";p();a[u]="src/lib/modules/admin/Page.svelte";function a(e,s){r(new.target),l(s,!1,a);var t=m("Hello from admin");return o(e,t),d({...n()})}i(a);export{a as default};
@@ -1,6 +0,0 @@
1
- export { a as default };
2
- declare function a(e: any, s: any): any;
3
- declare namespace a {
4
- let ____A_17405: string;
5
- export { ____A_17405 as __@A@17405 };
6
- }
@@ -1 +0,0 @@
1
- import{D as r,E as l,ak as o,S as m,T as p,U as u,V as d,W as f,Y as g}from"./index-LRDptjak.js";d();a[f]="src/lib/modules/storage/Page.svelte";function a(e,s){r(new.target),l(s,!1,a);var t=o("Hello from files");return m(e,t),p({...u()})}g(a);export{a as default};
@@ -1,6 +0,0 @@
1
- export { re as default };
2
- declare function re(n: any, e: any): any;
3
- declare namespace re {
4
- let ____A_17405: string;
5
- export { ____A_17405 as __@A@17405 };
6
- }
@@ -1,20 +0,0 @@
1
- var ts=Object.defineProperty;var di=n=>{throw TypeError(n)};var rs=(n,e,t)=>e in n?ts(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var f=(n,e,t)=>rs(n,typeof e!="symbol"?e+"":e,t),ci=(n,e,t)=>e.has(n)||di("Cannot "+t);var Me=(n,e,t)=>(ci(n,e,"read from private field"),t?t.call(n):e.get(n)),hi=(n,e,t)=>e.has(n)?di("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),pi=(n,e,t,r)=>(ci(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t);import{b as is,a as ns,c as ss,d as as,g as os,e as ls,s as yi,f as us,h as Ht,u as Zi,N as fs,i as ds,L as cs,j as hs,k as ps,l as ys,m as en,n as ms,o as gs,p as ws,q as vs,r as bs,t as tn,v as mi,w as rn,x as _s,y as Is,z as Yr,A as ks,B as nn,C as gr,D as rt,E as it,F as Os,G as Ee,H as gi,I as Cs,J as wi,K as Ur,M as sn,O as Tt,P as Jt,Q as Pe,R as me,S as X,T as nt,U as st,V as at,W as ee,X as an,Y as ot,Z as wt,_ as Te,$ as As,a0 as Vr,a1 as ue,a2 as fe,a3 as vi,a4 as Ce,a5 as Gt,a6 as Z,a7 as Q,a8 as be,a9 as U,aa as wr,ab as le,ac as G,ad as Es,ae as on,af as Ss,ag as Rt,ah as xe,ai as yt,aj as Ar,ak as Dt}from"./index-LRDptjak.js";function Ts(n,e,t,r,i){var s=n,a="",o;is(()=>{a!==(a=e()??"")&&(o!==void 0&&(ls(o),o=void 0),a!==""&&(o=ns(()=>{var l=a+"",u=ss(l);as(os(u),u.lastChild),s.before(u)})))})}function ln(n,e,t,r,i){var o;var s=(o=e.$$slots)==null?void 0:o[t],a=!1;s===!0&&(s=e.children,a=!0),s===void 0||s(n,a?()=>r:r)}function Fe(n,e){return(t,...r)=>{var i=us;yi(n);try{return e(t,...r)}finally{yi(i)}}}function vr(n,e,t){Ht(()=>{var r=Zi(()=>e(n,t==null?void 0:t())||{});if(r!=null&&r.destroy)return()=>r.destroy()})}function un(n){var e,t,r="";if(typeof n=="string"||typeof n=="number")r+=n;else if(typeof n=="object")if(Array.isArray(n)){var i=n.length;for(e=0;e<i;e++)n[e]&&(t=un(n[e]))&&(r&&(r+=" "),r+=t)}else for(t in n)n[t]&&(r&&(r+=" "),r+=t);return r}function Fs(){for(var n,e,t=0,r="",i=arguments.length;t<i;t++)(n=arguments[t])&&(e=un(n))&&(r&&(r+=" "),r+=e);return r}function Ps(n){return typeof n=="object"?Fs(n):n??""}const bi=[...`
2
- \r\f \v\uFEFF`];function Rs(n,e,t){var r=n==null?"":""+n;if(e&&(r=r?r+" "+e:e),t){for(var i in t)if(t[i])r=r?r+" "+i:i;else if(r.length)for(var s=i.length,a=0;(a=r.indexOf(i,a))>=0;){var o=a+s;(a===0||bi.includes(r[a-1]))&&(o===r.length||bi.includes(r[o]))?r=(a===0?"":r.substring(0,a))+r.substring(o+1):a=o}}return r===""?null:r}function _i(n,e=!1){var t=e?" !important;":";",r="";for(var i in n){var s=n[i];s!=null&&s!==""&&(r+=" "+i+": "+s+t)}return r}function Er(n){return n[0]!=="-"||n[1]!=="-"?n.toLowerCase():n}function Ds(n,e){if(e){var t="",r,i;if(Array.isArray(e)?(r=e[0],i=e[1]):r=e,n){n=String(n).replaceAll(/\s*\/\*.*?\*\/\s*/g,"").trim();var s=!1,a=0,o=!1,l=[];r&&l.push(...Object.keys(r).map(Er)),i&&l.push(...Object.keys(i).map(Er));var u=0,d=-1;const _=n.length;for(var c=0;c<_;c++){var h=n[c];if(o?h==="/"&&n[c-1]==="*"&&(o=!1):s?s===h&&(s=!1):h==="/"&&n[c+1]==="*"?o=!0:h==='"'||h==="'"?s=h:h==="("?a++:h===")"&&a--,!o&&s===!1&&a===0){if(h===":"&&d===-1)d=c;else if(h===";"||c===_-1){if(d!==-1){var p=Er(n.substring(u,d).trim());if(!l.includes(p)){h!==";"&&c++;var y=n.substring(u,c).trim();t+=" "+y+";"}}u=c+1,d=-1}}}}return r&&(t+=_i(r)),i&&(t+=_i(i,!0)),t=t.trim(),t===""?null:t}return n==null?null:String(n)}function Ft(n,e,t,r,i,s){var a=n.__className;if(a!==t||a===void 0){var o=Rs(t,r,s);o==null?n.removeAttribute("class"):e?n.className=o:n.setAttribute("class",o),n.__className=t}else if(s&&i!==s)for(var l in s){var u=!!s[l];(i==null||u!==!!i[l])&&n.classList.toggle(l,u)}return s}function Sr(n,e={},t,r){for(var i in t){var s=t[i];e[i]!==s&&(t[i]==null?n.style.removeProperty(i):n.style.setProperty(i,s,r))}}function Ms(n,e,t,r){var i=n.__style;if(i!==e){var s=Ds(e,r);s==null?n.removeAttribute("style"):n.style.cssText=s,n.__style=e}else r&&(Array.isArray(r)?(Sr(n,t==null?void 0:t[0],r[0]),Sr(n,t==null?void 0:t[1],r[1],"important")):Sr(n,t,r));return r}const Mt=Symbol("class"),Nt=Symbol("style"),fn=Symbol("is custom element"),dn=Symbol("is html");function Ns(n,e){e?n.hasAttribute("selected")||n.setAttribute("selected",""):n.removeAttribute("selected")}function je(n,e,t,r){var i=cn(n);i[e]!==(i[e]=t)&&(e==="loading"&&(n[cs]=t),t==null?n.removeAttribute(e):typeof t!="string"&&hn(n).includes(e)?n[e]=t:n.setAttribute(e,t))}function $s(n,e,t,r,i=!1){var s=cn(n),a=s[fn],o=!s[dn],l=e||{},u=n.tagName==="OPTION";for(var d in e)d in t||(t[d]=null);t.class?t.class=Ps(t.class):t[Mt]&&(t.class=null),t[Nt]&&(t.style??(t.style=null));var c=hn(n);for(const O in t){let M=t[O];if(u&&O==="value"&&M==null){n.value=n.__value="",l[O]=M;continue}if(O==="class"){var h=n.namespaceURI==="http://www.w3.org/1999/xhtml";Ft(n,h,M,r,e==null?void 0:e[Mt],t[Mt]),l[O]=M,l[Mt]=t[Mt];continue}if(O==="style"){Ms(n,M,e==null?void 0:e[Nt],t[Nt]),l[O]=M,l[Nt]=t[Nt];continue}var p=l[O];if(M!==p){l[O]=M;var y=O[0]+O[1];if(y!=="$$")if(y==="on"){const S={},v="$$"+O;let I=O.slice(2);var _=ws(I);if(ps(I)&&(I=I.slice(0,-7),S.capture=!0),!_&&p){if(M!=null)continue;n.removeEventListener(I,l[v],S),l[v]=null}if(M!=null)if(_)n[`__${I}`]=M,en([I]);else{let F=function($){l[O].call(this,$)};l[v]=ys(I,n,F,S)}else _&&(n[`__${I}`]=void 0)}else if(O==="style")je(n,O,M);else if(O==="autofocus")ms(n,!!M);else if(!a&&(O==="__value"||O==="value"&&M!=null))n.value=n.__value=M;else if(O==="selected"&&u)Ns(n,M);else{var g=O;o||(g=gs(g));var P=g==="defaultValue"||g==="defaultChecked";if(M==null&&!a&&!P)if(s[O]=null,g==="value"||g==="checked"){let S=n;const v=e===void 0;if(g==="value"){let I=S.defaultValue;S.removeAttribute(g),S.defaultValue=I,S.value=S.__value=v?I:null}else{let I=S.defaultChecked;S.removeAttribute(g),S.defaultChecked=I,S.checked=v?I:!1}}else n.removeAttribute(O);else P||c.includes(g)&&(a||typeof M!="string")?n[g]=M:typeof M!="function"&&je(n,g,M)}}}return l}function cn(n){return n.__attributes??(n.__attributes={[fn]:n.nodeName.includes("-"),[dn]:n.namespaceURI===fs})}var Ii=new Map;function hn(n){var e=Ii.get(n.nodeName);if(e)return e;Ii.set(n.nodeName,e=[]);for(var t,r=n,i=Element.prototype;i!==r;){t=hs(r);for(var s in t)t[s].set&&e.push(s);r=ds(r)}return e}function ct(n,e,t=e){var r=vs();bs(n,"input",i=>{n.type==="checkbox"&&mi();var s=i?n.defaultValue:n.value;if(s=Tr(n)?Fr(s):s,t(s),r&&s!==(s=e())){var a=n.selectionStart,o=n.selectionEnd;n.value=s??"",o!==null&&(n.selectionStart=a,n.selectionEnd=Math.min(o,n.value.length))}}),Zi(e)==null&&n.value&&t(Tr(n)?Fr(n.value):n.value),tn(()=>{n.type==="checkbox"&&mi();var i=e();Tr(n)&&i===Fr(n.value)||n.type==="date"&&!i&&!n.value||i!==n.value&&(n.value=i??"")})}function Tr(n){var e=n.type;return e==="number"||e==="range"}function Fr(n){return n===""?null:+n}function br(n){return function(...e){var t=e[0];return t.preventDefault(),n==null?void 0:n.apply(this,e)}}function Ls(n,e){var s;var t=(s=n.$$events)==null?void 0:s[e.type],r=rn(t)?t.slice():t==null?[]:[t];for(var i of r)i.call(this,e)}function qs(n,e){tn(()=>{const t=new Map,r=n(),i=rn(r)?r:r==null?[]:Array.from(r),s=i.length;for(let a=0;a<s;a++){const o=e(i[a],a);if(t.has(o)){const l=String(t.get(o)),u=String(a);let d=String(o);d.startsWith("[object ")&&(d=null),_s(l,u,d)}t.set(o,a)}})}function vt(n,e){n!=null&&typeof n.subscribe!="function"&&Is(e)}const xs=n=>{const{subscribe:e,update:t}=Yr(n);return{subscribe:e,set:(r={})=>{t(i=>Object.assign(i,r))}}},kt=xs({mode:"window",basePath:null}),Pr=(n=ks(kt).mode)=>{let e="popstate";n==="window"&&(e="popstate"),n==="hash"&&(e="hashchange"),window.dispatchEvent(new Event(e))},ki={go:(n=0)=>{history.go(n),Pr()},push:(n,e=null)=>{history.pushState(e,"",n),Pr()},replace:(n,e=null)=>{history.replaceState(e,"",n),Pr()}},Bs=n=>{const e=n.match(/^(\/[^?#]*)?/),t=n.match(/\?([^#]*)?/),r=n.match(/#(.*)?/);return{path:(e==null?void 0:e[1])||"/",query:t!=null&&t[1]?`?${t==null?void 0:t[1]}`:"",hash:r!=null&&r[1]?`#${r==null?void 0:r[1]}`:""}},Oi=()=>{const{pathname:n,search:e,hash:t}=document.location;return{path:n,query:e,hash:t}},Ci=()=>{let n=document.location.hash.substring(1);return n[0]!=="/"&&(n="/"+n),Bs(n)},js=nn(Oi(),n=>{const e=()=>n(Oi());return window.addEventListener("popstate",e),()=>window.removeEventListener("popstate",e)}),Js=nn(Ci(),n=>{const e=()=>n(Ci());return window.addEventListener("hashchange",e),()=>window.removeEventListener("hashchange",e)}),Zr=gr([kt,js,Js],([n,e,t],r)=>{n.mode==="window"&&r(e),n.mode==="hash"&&r(t)}),Ai=gr(Zr,n=>n.path);gr(Zr,n=>n.query);gr(Zr,n=>n.hash);const Us=()=>{let n=0;return()=>n++},tr=n=>n.split(/(?=\/)/),Vs=(n,e)=>e===null?n:n.startsWith(e)?n.slice(e.length):n;at();Ge[ee]="/home/jycouet/udev/gh/dp/aut-pac-man/firstly/node_modules/.pnpm/svelte-micro@2.5.7_svelte@5.25.6/node_modules/svelte-micro/dist/lib/components/Route.svelte";const Ws=(n,e,t,r,i)=>{const s=(u,d,c)=>{const h=tr(d).filter(p=>Te(p,"/",!1)).length;return(c??0)+(u?1:h)},a=(u,d)=>{const c={invalidPath:`<Route path="${u==null?void 0:u.path}" /> has invalid path. Path must start with '/'`,fallbackOutsideRoot:"<Route fallback /> cannot be outside root <Route />",pathOutsideRoot:`<Route path="${u==null?void 0:u.path}" /> cannot be outside root <Route />`,fallbackInsideFallback:"<Route fallback /> cannot be inside <Route fallback>",pathInsideFallback:`<Route path="${u==null?void 0:u.path}" /> cannot be inside <Route fallback>`};if(Te(u.path[0],"/",!1))throw new Error(c.invalidPath);if(u.root&&u.fallback)throw new Error(c.fallbackOutsideRoot);if(u.root&&Te(u.path,"/",!1))throw new Error(c.pathOutsideRoot);if(d!=null&&d.fallback&&u.fallback)throw new Error(c.fallbackInsideFallback);if(d!=null&&d.fallback&&!u.fallback)throw new Error(c.pathInsideFallback)},o=s(t,r,i==null?void 0:i.depth),l={id:n,root:e,fallback:t,path:r,depth:o};return a(l,i),l},Hs=()=>{const{subscribe:n,update:e}=Yr([]);return{subscribe:n,update:t=>e(r=>[...r.filter(i=>Te(t.id,i.id,!1)),t]),remove:t=>e(r=>r.filter(i=>Te(t.id,i.id,!1)))}},Gs=(n,e,t)=>{const r=(u,d,c,h)=>{let p=tr(u).filter(g=>Te(g,"/",!1)),y=tr(c).filter(g=>Te(g,"/",!1)),_="";if(Te(c,"/"))return d||Te(p.length,h);for(let g=h-y.length;g<h;g++)_=_+p[g];return Te(c,_)},i=(u,d,c)=>{var y,_,g,P;let h=tr(u).filter(O=>Te(O,"/",!1)),p=!1;for(let O=0;O<(c==null?void 0:c.length)&&!p;O++)(y=c[O])!=null&&y.fallback||(p=r(u,((_=c[O])==null?void 0:_.root)??!1,((g=c[O])==null?void 0:g.path)??"",((P=c[O])==null?void 0:P.depth)??0));return h.length>=d&&!p},{root:s,fallback:a,path:o,depth:l}=e;return a?i(n,l,t):r(n,s,o,l)},Qs=Us(),Rr={},Ei={};function Ge(n,e){rt(new.target),it(e,!1,Ge);const[t,r]=an(),i=()=>(vt(p,"route"),wt(p,"$route",t)),s=()=>(vt(y,"contextRoute"),wt(y,"$contextRoute",t)),a=()=>(vt(Ai,"globalPath"),wt(Ai,"$globalPath",t)),o=()=>(vt(kt,"options"),wt(kt,"$options",t)),l=()=>(vt(g,"contextChildRoutes"),wt(g,"$contextChildRoutes",t)),u=Qs(),d=!Os(Rr);let c=Ee(e,"fallback",9,!1),h=Ee(e,"path",9,"/");const p=Yr(),y=gi(Rr),_=Hs(),g=gi(Ei);Cs(()=>g==null?void 0:g.remove(i())),wi(Rr,p),wi(Ei,_),Ur(()=>(Vr(c()),Vr(h()),s()),()=>{As(p,Ws(u,d,c(),h(),s()))}),Ur(()=>i(),()=>{g==null||g.update(i())}),sn(),Tt(!0);var P=Jt(),O=Pe(P);{var M=v=>{var I=Jt(),F=Pe(I);ln(F,e,"default",{}),X(v,I)};me(O,v=>{Gs(Vs(a(),o().basePath),i(),l())&&v(M)})}X(n,P);var S=nt({...st()});return r(),S}ot(Ge);const Si=n=>{var o;const e=(o=n.target)==null?void 0:o.closest("a[href]"),t=e==null?void 0:e.href;if(e===null||t===null)return!0;const r=["","true"].includes(e.getAttribute("data-handle-ignore")??"false"),i=(e.getAttribute("target")??"_self")!=="_self",s=n.metaKey||n.ctrlKey||n.altKey||n.shiftKey,a=new URL(t).origin!==document.location.origin;if(r||i||s||a)return!0;t===document.location.href?ki.replace(t):ki.push(t),n.preventDefault()},Dr=n=>(n.addEventListener("click",Si),{destroy:()=>{n.removeEventListener("click",Si)}});at();Qe[ee]="/home/jycouet/udev/gh/dp/aut-pac-man/firstly/node_modules/.pnpm/svelte-micro@2.5.7_svelte@5.25.6/node_modules/svelte-micro/dist/lib/components/Link.svelte";const zs=(n,e,t)=>(Te(n,"hash")?"#":"")+(e??"")+t;var Ks=ue(fe("<a><!></a>"),Qe[ee],[[16,0]]);function Qe(n,e){rt(new.target);const t=vi(e,["children","$$slots","$$events","$$legacy"]),r=vi(t,["href"]);it(e,!1,Qe);const[i,s]=an(),a=()=>(vt(kt,"options"),wt(kt,"$options",i)),o=be(void 0,!0);let l=Ee(e,"href",9);Ur(()=>(a(),Vr(l())),()=>{Z(o,zs(a().mode,a().basePath,l()))}),sn(),Tt(!0);var u=Ks();let d;var c=Q(u);ln(c,e,"default",{}),vr(u,p=>Dr==null?void 0:Dr(p)),Ht(()=>Gt("click",u,function(p){Ls.call(this,e,p)})),Ce(()=>d=$s(u,d,{href:U(o),...r})),X(n,u);var h=nt({...st()});return s(),h}ot(Qe);const Qt={FF_Role_Admin:"FF_Role.Admin"};class ut{constructor(...e){f(this,"fields");f(this,"options",{});f(this,"target");f(this,"readonly",!0);f(this,"allowNull",!1);f(this,"dbReadOnly",!1);f(this,"isServerExpression",!1);f(this,"key","");f(this,"caption","");f(this,"inputType","");f(this,"dbName","");f(this,"valueType");this.fields=e}apiUpdateAllowed(e){throw new Error("Method not implemented.")}displayValue(e){throw new Error("Method not implemented.")}includedInApi(e){throw new Error("Method not implemented.")}toInput(e,t){throw new Error("Method not implemented.")}fromInput(e,t){throw new Error("Method not implemented.")}getDbName(){return Promise.resolve("")}getId(e){let t=i=>e[i.key];typeof e=="function"&&(t=e);let r="";return this.fields.forEach(i=>{r.length>0&&(r+=","),r+=i.valueConverter.toJson(t(i))}),r}get valueConverter(){throw new Error("cant get value converter of compound id")}isEqualTo(e){let t={},i=e.toString().split(",");return this.fields.forEach((s,a)=>{t[s.key]=s.valueConverter.fromJson(i[a])}),t}}function ne(n,e=!0){var r;if(n===void 0)throw new Error("entity is undefined");let t=n[lt];if(!t&&e)throw new Error("item "+(((r=n.constructor)==null?void 0:r.name)||n)+" was not initialized using a context");return t}const lt=Symbol.for("entityMember"),pn=Symbol.for("entityInfo"),yn=Symbol.for("entityInfo_key");function Se(n,e=!0){if(n===void 0){if(e)throw new Error("Undefined is not an entity :)");return}let t=n[pn];if(!t&&e)throw new Error(n.prototype.constructor.name+" is not a known entity, did you forget to set @Entity() or did you forget to add the '@' before the call to Entity?");return t}function Xs(n){return n[yn]}function Mr(n,e){return{[mn]:{toType:n,type:e}}}const mn=Symbol.for("relationInfo");function Ys(n){return n==null?void 0:n[mn]}const Wr=Symbol.for("fieldRelationInfo");function ae(n){if(n)return n[Wr]}function Zs(n,e,t){for(const r of n.fields.toArray()){const i=Ys(r.options);if(i&&!r[Wr]){const s=i.toType(),a=e.repo(s,t),o=r.options;r[Wr]={type:i.type,toEntity:s,options:o,toRepo:a,getFields:()=>{let l=o.field,u={fields:o.fields,compoundIdField:void 0};function d(p){return Error(`Error for relation: "${n.metadata.key}.${r.key}", `+p)}let c=()=>l||u.fields;if(i.type==="toMany"&&!c()){for(const p of a.fields.toArray())if(!c()){const y=ae(p),_=p.options;if(y&&y.toEntity===n.metadata.entityType){if(y.type==="reference")l=p.key;else if(y.type==="toOne"){if(_.field)l=_.field;else if(_.fields){let g={};for(const P in _.fields)if(Object.prototype.hasOwnProperty.call(_.fields,P)){const O=_.fields[P];g[O]=P}u.fields=g}}}}if(!c())throw d(`No matching field found on target "${a.metadata.key}". Please specify field/fields`)}function h(p,y){const _=y.fields.find(p);if(!_)throw d(`Field "${p}" was not found in "${y.key}".`);return _}i.type==="reference"&&(l=r.key),l&&(i.type==="toOne"||i.type==="reference"?a.metadata.idMetadata.field instanceof ut?u.compoundIdField=l:u.fields={[a.metadata.idMetadata.field.key]:l}:n.metadata.idMetadata.field instanceof ut?u.compoundIdField=l:u.fields={[l]:n.metadata.idMetadata.field.key});for(const p in u.fields)Object.prototype.hasOwnProperty.call(u.fields,p)&&(h(p,a.metadata),h(u.fields[p],n.metadata));return u}}}}}class x{constructor(e){f(this,"apply");this.apply=e}static throwErrorIfFilterIsEmpty(e,t){if(x.isFilterEmpty(e))throw{message:`${t}: requires a filter to protect against accidental delete/update of all rows`,httpStatusCode:400}}static isFilterEmpty(e){if(e.$and){for(const t of e.$and)if(!x.isFilterEmpty(t))return!1}if(e.$or){for(const t of e.$or)if(x.isFilterEmpty(t))return!0;return!1}return Object.keys(e).filter(t=>!["$or","$and"].includes(t)).length==0}static async getPreciseValues(e,t){const r=new fr;return await x.fromEntityFilter(e,t).__applyToConsumer(r),r.preciseValues}async getPreciseValues(){const e=new fr;return await this.__applyToConsumer(e),e.preciseValues}static createCustom(e,t=""){let r={key:t,rawFilterTranslator:e};return Object.assign(i=>{if(i==null&&(i={}),!r.key)throw"Usage of custom filter before a key was assigned to it";return{[ft+r.key]:i}},{rawFilterInfo:r})}static entityFilterToJson(e,t){return x.fromEntityFilter(e,t).toJson()}static entityFilterFromJson(e,t){return rr(e,{get:r=>t[r]})}static fromEntityFilter(e,t){let r=[];for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){let s=t[i];if(i=="$or")r.push(new ra(...s.map(a=>x.fromEntityFilter(e,a))));else if(i=="$not")r.push(new ia(x.fromEntityFilter(e,s)));else if(i=="$and")r.push(new Ti(...s.map(a=>x.fromEntityFilter(e,a))));else if(i.startsWith(ft))r.push(new x(a=>{a.custom(i.substring(ft.length),s)}));else if(i==gn)r.push(new x(a=>a.databaseCustom(s)));else{const a=e.fields[i],o=ae(a),l=a.options;let u=(o==null?void 0:o.type)==="toOne"?l.fields?new ta(a,e.fields,l):new ea(e.fields[l.field]):new or(a),d=!1;if(s!==void 0&&s!=null){s.$id!==void 0&&(s=s.$id);for(const c in s)if(Object.prototype.hasOwnProperty.call(s,c)){const h=s[c];switch(c){case"$gte":case">=":r.push(u.isGreaterOrEqualTo(h)),d=!0;break;case"$gt":case">":r.push(u.isGreaterThan(h)),d=!0;break;case"$lte":case"<=":r.push(u.isLessOrEqualTo(h)),d=!0;break;case"$lt":case"<":r.push(u.isLessThan(h)),d=!0;break;case"$ne":case"$not":case"!=":case"$nin":d=!0,Array.isArray(h)?r.push(u.isNotIn(h)):r.push(u.isDifferentFrom(h));break;case"$in":d=!0,r.push(u.isIn(h));break;case"$contains":d=!0,r.push(u.contains(h));break;case"$startsWith":d=!0,r.push(u.startsWith(h));break;case"$endsWith":d=!0,r.push(u.endsWith(h));break;case"$notContains":d=!0,r.push(u.notContains(h));break}}Array.isArray(s)&&(d=!0,r.push(u.isIn(s)))}!d&&s!==void 0&&r.push(u.isEqualTo(s))}}return new Ti(...r)}__applyToConsumer(e){this.apply(e)}static async resolve(e){return typeof e=="function"?await e():e}toJson(){let e=new lr;return this.__applyToConsumer(e),e.result}static async translateCustomWhere(e,t,r){let i=new ur(async(s,a)=>{let o=[];for(const l in t.entityType){const u=t.entityType[l];u&&u.rawFilterInfo&&u.rawFilterInfo.rawFilterTranslator&&u.rawFilterInfo.key==s&&o.push(await x.fromEntityFilter(t,await u.rawFilterInfo.rawFilterTranslator(a,r)))}return o});return e.__applyToConsumer(i),await i.resolve(),e=new x(s=>i.applyTo(s)),e}}class or{constructor(e){f(this,"metadata");this.metadata=e}processVal(e){if(Se(this.metadata.valueType,!1)){if(e==null){if(e===null&&!this.metadata.allowNull){const r=ae(this.metadata);if((r==null?void 0:r.type)==="reference")return r.toRepo.metadata.idMetadata.field.options.valueType===Number?0:""}return null}return typeof e=="string"||typeof e=="number"?e:ne(e).getId()}return e}contains(e){return new x(t=>t.containsCaseInsensitive(this.metadata,e))}notContains(e){return new x(t=>t.notContainsCaseInsensitive(this.metadata,e))}startsWith(e){return new x(t=>t.startsWithCaseInsensitive(this.metadata,e))}endsWith(e){return new x(t=>t.endsWithCaseInsensitive(this.metadata,e))}isLessThan(e){return e=this.processVal(e),new x(t=>t.isLessThan(this.metadata,e))}isGreaterOrEqualTo(e){return e=this.processVal(e),new x(t=>t.isGreaterOrEqualTo(this.metadata,e))}isNotIn(e){return new x(t=>{for(const r of e)t.isDifferentFrom(this.metadata,this.processVal(r))})}isDifferentFrom(e){return e=this.processVal(e),e==null&&this.metadata.allowNull?new x(t=>t.isNotNull(this.metadata)):new x(t=>t.isDifferentFrom(this.metadata,e))}isLessOrEqualTo(e){return e=this.processVal(e),new x(t=>t.isLessOrEqualTo(this.metadata,e))}isGreaterThan(e){return e=this.processVal(e),new x(t=>t.isGreaterThan(this.metadata,e))}isEqualTo(e){return e=this.processVal(e),e==null&&this.metadata.allowNull?new x(t=>t.isNull(this.metadata)):new x(t=>t.isEqualTo(this.metadata,e))}isIn(e){return e=e.map(t=>this.processVal(t)),(e==null?void 0:e.length)==1&&e[0]!=null&&e[0]!==null?new x(t=>t.isEqualTo(this.metadata,e[0])):new x(t=>t.isIn(this.metadata,e))}}class ea extends or{processVal(e){return e?typeof e=="string"||typeof e=="number"?e:ne(e).getId():null}}class ta{constructor(e,t,r){f(this,"metadata");f(this,"fields");f(this,"relationOptions");this.metadata=e,this.fields=t,this.relationOptions=r}processVal(e){throw new Error("Invalid for Many To One Relation Field")}contains(e){throw new Error("Invalid for Many To One Relation Field")}notContains(e){throw new Error("Invalid for Many To One Relation Field")}endsWith(e){throw new Error("Invalid for Many To One Relation Field")}startsWith(e){throw new Error("Invalid for Many To One Relation Field")}isLessThan(e){throw new Error("Invalid for Many To One Relation Field")}isGreaterOrEqualTo(e){throw new Error("Invalid for Many To One Relation Field")}isNotIn(e){return new x(t=>{e.forEach(r=>this.isDifferentFrom(r).__applyToConsumer(t))})}isDifferentFrom(e){return new x(t=>{const r=[];for(const i in this.relationOptions.fields)if(Object.prototype.hasOwnProperty.call(this.relationOptions.fields,i)){const s=this.relationOptions.fields[i];r.push(new x(a=>new or(this.fields.find(s)).isDifferentFrom(e[i]).__applyToConsumer(a)))}t.or(r)})}isLessOrEqualTo(e){throw new Error("Invalid for Many To One Relation Field")}isGreaterThan(e){throw new Error("Invalid for Many To One Relation Field")}isEqualTo(e){return new x(t=>{for(const r in this.relationOptions.fields)if(Object.prototype.hasOwnProperty.call(this.relationOptions.fields,r)){const i=this.relationOptions.fields[r];new or(this.fields.find(i)).isEqualTo(e[r]).__applyToConsumer(t)}})}isIn(e){return new x(t=>{t.or(e.map(r=>this.isEqualTo(r)))})}}class Ti extends x{constructor(...t){super(r=>{for(const i of this.filters)i&&i.__applyToConsumer(r)});f(this,"filters");this.filters=t}add(t){this.filters.push(t)}}class ra extends x{constructor(...t){super(r=>{let i=this.filters.filter(s=>s!==void 0);i.length>1?r.or(i):i.length==1&&i[0].__applyToConsumer(r)});f(this,"filters");this.filters=t}}class ia extends x{constructor(t){super(r=>{r.not(t)});f(this,"filter");this.filter=t}}const ft="$custom$",gn="$db$",Hr="$an array";class lr{constructor(){f(this,"result",{});f(this,"hasUndefined",!1)}databaseCustom(e){throw new Error("database custom is not allowed with api calls.")}custom(e,t){Array.isArray(t)&&(t={[Hr]:t}),this.add(ft+e,t)}add(e,t){t===void 0&&(this.hasUndefined=!0);let r=this.result;if(!r[e]){r[e]=t;return}let i=r[e];i instanceof Array?i.push(t):i=[i,t],r[e]=i}or(e){this.add("OR",e.map(t=>{let r=new lr;return t.__applyToConsumer(r),r.result}))}not(e){let t=new lr;e.__applyToConsumer(t),this.add("NOT",t.result)}isNull(e){this.add(e.key+".null",!0)}isNotNull(e){this.add(e.key+".null",!1)}isIn(e,t){this.add(e.key+".in",t.map(r=>e.valueConverter.toJson(r)))}isEqualTo(e,t){this.add(e.key,e.valueConverter.toJson(t))}isDifferentFrom(e,t){this.add(e.key+".ne",e.valueConverter.toJson(t))}isGreaterOrEqualTo(e,t){this.add(e.key+".gte",e.valueConverter.toJson(t))}isGreaterThan(e,t){this.add(e.key+".gt",e.valueConverter.toJson(t))}isLessOrEqualTo(e,t){this.add(e.key+".lte",e.valueConverter.toJson(t))}isLessThan(e,t){this.add(e.key+".lt",e.valueConverter.toJson(t))}containsCaseInsensitive(e,t){this.add(e.key+".contains",t)}notContainsCaseInsensitive(e,t){this.add(e.key+".notContains",t)}startsWithCaseInsensitive(e,t){this.add(e.key+".startsWith",t)}endsWithCaseInsensitive(e,t){this.add(e.key+".endsWith",t)}}function rr(n,e){let t={};function r(o){t.$and||(t.$and=[]),t.$and.push(o)}function i(o,l){t[o]===void 0?t[o]=l:r({[o]:l})}[...n.fields].forEach(o=>{function l(d,c,h=!1,p=!1){let y=e.get(o.key+d);if(y!==void 0){let _=g=>{let P=g;if(h){let M;typeof g=="string"?M=JSON.parse(g):M=g,P=M.map(S=>p?S:o.valueConverter.fromJson(S))}else P=p?P:o.valueConverter.fromJson(P);let O=c(P);O!==void 0&&i(o.key,O)};if(!h&&y instanceof Array)y.forEach(g=>{_(g)});else{h&&typeof y=="string"&&(y=JSON.parse(y));const g=a(y);for(const P of g)_(P)}}}l("",d=>d),l(".gt",d=>({$gt:d})),l(".gte",d=>({$gte:d})),l(".lt",d=>({$lt:d})),l(".lte",d=>({$lte:d})),l(".ne",d=>({$ne:d})),l(".in",d=>d,!0);var u=e.get(o.key+".null");if(u)switch(u=u.toString().trim().toLowerCase(),u){case"y":case"true":case"yes":i(o.key,null);break;default:i(o.key,{$ne:null});break}l(".contains",d=>({$contains:d}),!1,!0),l(".notContains",d=>({$notContains:d}),!1,!0),l(".startsWith",d=>({$startsWith:d}),!1,!0),l(".endsWith",d=>({$endsWith:d}),!1,!0)});let s=e.get("OR");if(s){const l=a(s).map(u=>({$or:u.map(d=>rr(n,{get:c=>d[c]}))}));l.length==1?t.$or?t.$or.push(l[0].$or):t.$or=l[0].$or:r({$and:l})}if(s=e.get("NOT"),s){let o=a(s);const l=[];for(const u of o)if(Array.isArray(u))for(const d of u)l.push({$not:rr(n,{get:c=>d[c]})});else l.push({$not:rr(n,{get:d=>u[d]})});l.length==1?t.$not?t.$not.push(l[0].$not):t.$not=l[0].$not:r({$and:l})}for(const o in n.entityType){const l=n.entityType[o];if(l&&l.rawFilterInfo&&l.rawFilterInfo.rawFilterTranslator){let u=e.get(ft+o);if(u!==void 0){const d=c=>{c[Hr]!=null&&(c=c[Hr]),i(ft+o,c)};Array.isArray(u)?u.forEach(c=>d(c)):d(u)}}}return t;function a(o){if(!Array.isArray(o))return[o];const l=[],u=[];for(const d of o)Array.isArray(d)?u.push(d):l.push(d);return u.push(l),u}}class ur{constructor(e){f(this,"translateCustom");f(this,"commands",[]);f(this,"promises",[]);this.translateCustom=e}applyTo(e){this.commands.forEach(t=>t(e))}or(e){let t;this.promises.push(Promise.all(e.map(async r=>{let i=new ur(this.translateCustom);return r.__applyToConsumer(i),await i.resolve(),new x(s=>i.applyTo(s))})).then(r=>{t=r})),this.commands.push(r=>r.or(t))}not(e){let t;this.promises.push((async()=>{let r=new ur(this.translateCustom);e.__applyToConsumer(r),await r.resolve(),t=new x(i=>r.applyTo(i))})()),this.commands.push(r=>r.not(t))}isEqualTo(e,t){this.commands.push(r=>r.isEqualTo(e,t))}isDifferentFrom(e,t){this.commands.push(r=>r.isDifferentFrom(e,t))}isNull(e){this.commands.push(t=>t.isNull(e))}isNotNull(e){this.commands.push(t=>t.isNotNull(e))}isGreaterOrEqualTo(e,t){this.commands.push(r=>r.isGreaterOrEqualTo(e,t))}isGreaterThan(e,t){this.commands.push(r=>r.isGreaterThan(e,t))}isLessOrEqualTo(e,t){this.commands.push(r=>r.isLessOrEqualTo(e,t))}isLessThan(e,t){this.commands.push(r=>r.isLessThan(e,t))}containsCaseInsensitive(e,t){this.commands.push(r=>r.containsCaseInsensitive(e,t))}notContainsCaseInsensitive(e,t){this.commands.push(r=>r.notContainsCaseInsensitive(e,t))}startsWithCaseInsensitive(e,t){this.commands.push(r=>r.startsWithCaseInsensitive(e,t))}endsWithCaseInsensitive(e,t){this.commands.push(r=>r.endsWithCaseInsensitive(e,t))}isIn(e,t){this.commands.push(r=>r.isIn(e,t))}custom(e,t){this.promises.push((async()=>{let r=await this.translateCustom(e,t);r&&(Array.isArray(r)?r.forEach(i=>i.__applyToConsumer(this)):r.__applyToConsumer(this))})())}databaseCustom(e){this.commands.push(t=>t.databaseCustom(e))}async resolve(){for(;this.promises.length>0;){let e=this.promises;this.promises=[],await Promise.all(e)}}}class fr{constructor(){f(this,"rawValues",{});f(this,"preciseValues",new Proxy(this.rawValues,{get:(e,t)=>{if(t in e){let r=e[t];if(r.bad)return;if(r.values.length>0){const i=ae(r.field);if(i){if(i.type==="reference")return r.values.map(s=>i.toRepo.metadata.idMetadata.getIdFilter(s));throw new Error("Only relations toOne without field are supported.")}return r.values}}}}))}ok(e,...t){let r=this.rawValues[e.key];r?r.values.push(...t.filter(i=>!r.values.includes(i))):this.rawValues[e.key]={field:e,bad:!1,values:[...t]}}notOk(e){let t=this.rawValues[e.key];t?t.bad=!0:this.rawValues[e.key]={field:e,bad:!0,values:[]}}not(e){}or(e){const t=e.map(r=>{let i=new fr;return r.__applyToConsumer(i),i});for(const r of t)for(const i in r.rawValues)if(Object.prototype.hasOwnProperty.call(r.rawValues,i)){const s=r.rawValues[i];s&&(s.bad?this.notOk(s.field):this.ok(s.field,...s.values))}for(const r in this.rawValues)if(Object.prototype.hasOwnProperty.call(this.rawValues,r))for(const i of t)i.rawValues[r]||this.notOk(this.rawValues[r].field)}isEqualTo(e,t){this.ok(e,t)}isDifferentFrom(e,t){this.notOk(e)}isNull(e){this.ok(e,null)}isNotNull(e){this.notOk(e)}isGreaterOrEqualTo(e,t){this.notOk(e)}isGreaterThan(e,t){this.notOk(e)}isLessOrEqualTo(e,t){this.notOk(e)}isLessThan(e,t){this.notOk(e)}containsCaseInsensitive(e,t){this.notOk(e)}notContainsCaseInsensitive(e,t){this.notOk(e)}startsWithCaseInsensitive(e,t){this.notOk(e)}endsWithCaseInsensitive(e,t){this.notOk(e)}isIn(e,t){this.ok(e,...t)}custom(e,t){}databaseCustom(e){}}var na={};const Nr=Symbol.for("remult-static1");let ir={defaultRemultFactory:void 0,remultFactory:void 0,defaultRemult:void 0,asyncContext:void 0,columnsOfType:new Map,allEntities:[],classHelpers:new Map,actionInfo:{allActions:[],runningOnServer:!1,runActionWithoutBlockingUI:n=>n(),startBusyWithProgress:()=>({progress:n=>{},close:()=>{}})},fieldOptionsEnricher:void 0,captionTransformer:void 0,defaultDataProvider:()=>{}};typeof process<"u"&&na.IGNORE_GLOBAL_REMULT_IN_TESTS||typeof globalThis[Nr]>"u"?(globalThis[Nr]=ir,ir.remultFactory=()=>wn()):ir=globalThis[Nr];const D=ir;function wn(){return D.defaultRemult||(D.defaultRemult=D.defaultRemultFactory()),D.defaultRemult}function sa(){D.remultFactory=()=>wn()}function dt(n){const e=n;if(typeof e[Ut]=="function")return e[Ut]();throw Error("Error getting repository internal from "+n)}const Ut=Symbol.for("getInternal");class aa{constructor(){f(this,"iAmRemultProxy",!0);f(this,"repoCache",new Map);f(this,"repo",(...e)=>{let t=D,r=this.repoCache.get(e[0]);r||this.repoCache.set(e[0],r=new Map);let i=r.get(e[1]);return i||(i={get fields(){return D.remultFactory().repo(...e).metadata.fields},[Ut](){return t.remultFactory().repo(...e)[Ut]()},relations:s=>t.remultFactory().repo(...e).relations(s),validate:(s,...a)=>t.remultFactory().repo(...e).validate(s,...a),addEventListener:(...s)=>t.remultFactory().repo(...e).addEventListener(...s),count:(...s)=>t.remultFactory().repo(...e).count(...s),create:(...s)=>t.remultFactory().repo(...e).create(...s),delete:s=>t.remultFactory().repo(...e).delete(s),deleteMany:s=>t.remultFactory().repo(...e).deleteMany(s),updateMany:(...s)=>t.remultFactory().repo(...e).updateMany(...s),find:(...s)=>t.remultFactory().repo(...e).find(...s),groupBy:(...s)=>t.remultFactory().repo(...e).groupBy(...s),aggregate:(...s)=>t.remultFactory().repo(...e).aggregate(...s),findFirst:(...s)=>t.remultFactory().repo(...e).findFirst(...s),findOne:(...s)=>t.remultFactory().repo(...e).findOne(...s),findId:(s,a)=>t.remultFactory().repo(...e).findId(s,a),toJson:s=>t.remultFactory().repo(...e).toJson(s),fromJson:(s,a)=>t.remultFactory().repo(...e).fromJson(s,a),getEntityRef:(...s)=>t.remultFactory().repo(...e).getEntityRef(...s),insert:s=>t.remultFactory().repo(...e).insert(s),liveQuery:(...s)=>t.remultFactory().repo(...e).liveQuery(...s),get metadata(){return D.remultFactory().repo(...e).metadata},query:s=>t.remultFactory().repo(...e).query(s),save:s=>t.remultFactory().repo(...e).save(s),upsert:s=>t.remultFactory().repo(...e).upsert(s),update:(s,a)=>t.remultFactory().repo(...e).update(s,a)},r.set(e[1],i),i)})}get liveQuerySubscriber(){return D.remultFactory().liveQuerySubscriber}set liveQuerySubscriber(e){D.remultFactory().liveQuerySubscriber=e}get liveQueryStorage(){return D.remultFactory().liveQueryStorage}set liveQueryStorage(e){D.remultFactory().liveQueryStorage=e}get liveQueryPublisher(){return D.remultFactory().liveQueryPublisher}set liveQueryPublisher(e){D.remultFactory().liveQueryPublisher=e}subscribeAuth(e){return D.remultFactory().subscribeAuth(e)}initUser(){return D.remultFactory().initUser()}call(e,t,...r){return D.remultFactory().call(e,t,...r)}get context(){return D.remultFactory().context}get dataProvider(){return D.remultFactory().dataProvider}set dataProvider(e){D.remultFactory().dataProvider=e}get repCache(){return D.remultFactory().repCache}authenticated(){return D.remultFactory().authenticated()}isAllowed(e){return D.remultFactory().isAllowed(e)}isAllowedForInstance(e,t){return D.remultFactory().isAllowedForInstance(e,t)}clearAllCache(){return D.remultFactory().clearAllCache()}useFetch(e){return D.remultFactory().useFetch(e)}get user(){return D.remultFactory().user}set user(e){D.remultFactory().user=e}get apiClient(){return D.remultFactory().apiClient}set apiClient(e){D.remultFactory().apiClient=e}get subscriptionServer(){return D.remultFactory().subscriptionServer}set subscriptionServer(e){D.remultFactory().subscriptionServer=e}}const _e=new aa,oa="$count",la=Symbol.for("GroupByForApiKey"),ua=["sum","avg","min","max","distinctCount"],vn={error500RetryCount:4};function Gr(n){return n.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,e=>e.toUpperCase()).replace("Email","eMail")}class fa{constructor(e,t,r){f(this,"repository");f(this,"isReferenceRelation");f(this,"allowNull");f(this,"storedItem");f(this,"id");this.repository=e,this.isReferenceRelation=t,this.allowNull=r}toJson(){if(this.storedItem)return this.item===null?null:this.repository.toJson(this.item)}setId(e){this.repository.metadata.idMetadata.field.valueType==Number&&(e=+e),this.id=e}waitLoadOf(e){return e==null?null:dt(this.repository)._getCachedByIdAsync(e,!1)}get(e){if(e==null)return null;const t=dt(this.repository)._getCachedById(e,this.isReferenceRelation);return this.isReferenceRelation&&!this.storedItem?!this.allowNull&&(this.id===0||this.id==="")?null:void 0:t}set(e){if(e===null&&!this.allowNull&&this.isReferenceRelation&&(this.id==0||this.id=="")){this.storedItem={item:null};return}if(this.storedItem=void 0,e)if(typeof e=="string"||typeof e=="number")this.id=e;else{let t=ne(e,!1);t&&!this.isReferenceRelation?(dt(this.repository)._addToCache(e),this.id=t.getId()):(this.storedItem={item:e},this.id=e[this.repository.metadata.idMetadata.field.key])}else e===null?this.id=null:this.id=void 0}get item(){return this.storedItem?this.storedItem.item:this.get(this.id)}async waitLoad(){return this.waitLoadOf(this.id)}}class Fi{constructor(e){f(this,"url");this.url=e}add(e,t){this.url.indexOf("?")>=0?this.url+="&":this.url+="?",this.url+=encodeURIComponent(e)+"="+encodeURIComponent(t)}addObject(e,t=""){if(e!=null)for(var r in e){let i=e[r];this.add(r+t,i)}}}function Ot(n){if(!n)return new Pi;let e;return e||bn(n)&&(e=new da(n)),e||typeof n=="function"&&(e=new Pi(n)),e}function bn(n){let e=n;return!!(e&&e.get&&e.put&&e.post&&e.delete)}class da{constructor(e){f(this,"http");this.http=e}async post(e,t){return await dr(()=>Yt(this.http.post(e,t)))}delete(e){return Yt(this.http.delete(e))}put(e,t){return Yt(this.http.put(e,t))}async get(e){return await dr(()=>Yt(this.http.get(e)))}}async function dr(n){var t,r,i,s;let e=0;for(;;)try{return await n()}catch(a){if(((t=a.message)!=null&&t.startsWith("Error occurred while trying to proxy")||(r=a.message)!=null&&r.startsWith("Error occured while trying to proxy")||(i=a.message)!=null&&i.includes("http proxy error")||(s=a.message)!=null&&s.startsWith("Gateway Timeout")||a.status==500)&&e++<vn.error500RetryCount){await new Promise((o,l)=>{setTimeout(()=>{o({})},500)});continue}throw a}}function Yt(n){let e;return n.toPromise!==void 0?e=n.toPromise():e=n,e.then(t=>t&&(t.status==200||t.status==201)&&t.headers&&t.request&&t.data!==void 0?t.data:t).catch(async t=>{throw await ca(t)})}async function ca(n){var s,a,o;let e=await n;var t;e.error?t=e.error:e.isAxiosError&&(typeof((s=e.response)==null?void 0:s.data)=="string"?t=e.response.data:t=(a=e==null?void 0:e.response)==null?void 0:a.data),t||(t=e.message),e.status==0&&e.error.isTrusted&&(t="Network Error"),typeof t=="string"&&(t={message:t}),e.modelState&&(t.modelState=e.modelState);let r=e.status;r===void 0&&(r=(o=e.response)==null?void 0:o.status),r!=null&&(t.httpStatusCode=r);var i=Object.assign(t??{},{});return i}class Qr{constructor(e,t){f(this,"apiProvider");f(this,"entityRequested");f(this,"isProxy",!0);this.apiProvider=e,this.entityRequested=t}getEntityDataProvider(e){var t;return(t=this.entityRequested)==null||t.call(this,e),new ha(()=>{var r;return _n((r=this.apiProvider())==null?void 0:r.url,e.key)},()=>Ot(this.apiProvider().httpClient),e)}async transaction(e){throw new Error("Method not implemented.")}}function _n(n,e){return n==null&&(n="/api"),n+"/"+e}function ei(n,e){if(n.include){let t={};for(const r in n.include)if(Object.prototype.hasOwnProperty.call(n.include,r)){let i=n.include[r];if(typeof i=="object"){const s=ae(e.fields.find(r));s&&(i=ei(i,s.toRepo.metadata))}t[r]=i}n={...n,include:t}}return n.where&&(n={...n,where:x.entityFilterToJson(e,n.where)}),n.load&&(n={...n,load:n.load(e.fields).map(t=>t.key)}),n}class ha{constructor(e,t,r){f(this,"url");f(this,"http");f(this,"entity");this.url=e,this.http=t,this.entity=r}query(e,t){return this.buildFindRequest(e).run("query",{aggregate:this.buildAggregateOptions(t)}).then(({items:i,aggregates:s})=>({items:i.map(a=>this.translateFromJson(a)),aggregates:s}))}async groupBy(e){const{run:t}=this.buildFindRequest({where:e==null?void 0:e.where,limit:e==null?void 0:e.limit,page:e==null?void 0:e.page}),r=this.buildAggregateOptions(e),i=await t("groupBy",Object.keys(r).length>0?r:void 0);return e!=null&&e.group&&i.forEach(s=>{for(const a of e.group)s[a.key]=a.valueConverter.fromJson(s[a.key])}),i}buildAggregateOptions(e){var t,r,i,s,a,o,l;return{groupBy:(t=e==null?void 0:e.group)==null?void 0:t.map(u=>u.key),sum:(r=e==null?void 0:e.sum)==null?void 0:r.map(u=>u.key),avg:(i=e==null?void 0:e.avg)==null?void 0:i.map(u=>u.key),min:(s=e==null?void 0:e.min)==null?void 0:s.map(u=>u.key),max:(a=e==null?void 0:e.max)==null?void 0:a.map(u=>u.key),distinctCount:(o=e==null?void 0:e.distinctCount)==null?void 0:o.map(u=>u.key),orderBy:(l=e==null?void 0:e.orderBy)==null?void 0:l.map(u=>{var d;return{...u,field:(d=u.field)==null?void 0:d.key}})}}translateFromJson(e){let t={};for(const r of this.entity.fields)t[r.key]=r.valueConverter.fromJson(e[r.key]);return t}translateToJson(e){let t={};for(const r of this.entity.fields)t[r.key]=r.valueConverter.toJson(e[r.key]);return t}async count(e){const{run:t}=this.buildFindRequest({where:e});return t("count").then(r=>+r.count)}async deleteMany(e){const{run:t}=this.buildFindRequest({where:e},"delete");return t("deleteMany").then(r=>+r.deleted)}async updateMany(e,t){const{run:r}=this.buildFindRequest({where:e},"put");return r("updateMany",this.toJsonOfIncludedKeys(t)).then(i=>+i.updated)}async upsertMany(e){const{run:t}=this.buildFindRequest(void 0);return t("upsertMany",e.map(r=>({where:this.toJsonOfIncludedKeys(r.where),set:r.set!==void 0?this.toJsonOfIncludedKeys(r.set):void 0}))).then(r=>r.map(i=>this.translateFromJson(i)))}find(e){let{run:t}=this.buildFindRequest(e);return t().then(r=>r.map(i=>this.translateFromJson(i)))}buildFindRequest(e,t){t||(t="get");let r=new Fi(this.url()),i;if(e){if(e.where&&(i=e.where.toJson(),ya(i,r)&&(i=void 0)),e.orderBy&&e.orderBy.Segments){let a="",o="",l=!1;e.orderBy.Segments.forEach(u=>{a.length>0&&(a+=",",o+=","),a+=u.field.key,o+=u.isDescending?"desc":"asc",u.isDescending&&(l=!0)}),a&&r.add("_sort",a),l&&r.add("_order",o)}e.limit&&r.add("_limit",e.limit),e.page&&r.add("_page",e.page)}const s=(a,o)=>{let l=new Fi(r.url);if(!a&&i&&(a="get"),a&&l.add("__action",a),i){if(t==="put")return this.http().post(l.url,{set:o,where:i});o={...o,where:i}}return o&&t!="put"?this.http().post(l.url,o):this.http()[t](l.url,o)};return{createKey:()=>JSON.stringify({url:r,filterObject:i}),run:s,subscribe:async a=>({result:await s(ma+a),unsubscribe:async()=>D.actionInfo.runActionWithoutBlockingUI(()=>this.http().post(this.url()+"?__action=endLiveQuery",{id:a}))})}}update(e,t){return this.http().put(this.url()+(e!=""?"/"+encodeURIComponent(e):"?__action=emptyId"),this.toJsonOfIncludedKeys(t)).then(r=>this.translateFromJson(r))}toJsonOfIncludedKeys(e){let t={},r=Object.keys(e);for(const i of this.entity.fields)r.includes(i.key)&&(t[i.key]=i.valueConverter.toJson(e[i.key]));return t}async delete(e){if(e=="")await this.deleteMany(x.fromEntityFilter(this.entity,this.entity.idMetadata.getIdFilter(e)));else return this.http().delete(this.url()+"/"+encodeURIComponent(e))}insert(e){return this.http().post(this.url(),this.translateToJson(e)).then(t=>this.translateFromJson(t))}insertMany(e){return this.http().post(this.url(),e.map(t=>this.translateToJson(t))).then(t=>t.map(r=>this.translateFromJson(r)))}}class Pi{constructor(e){f(this,"fetch");this.fetch=e}async get(e){return await dr(async()=>this.myFetch(e).then(t=>t))}put(e,t){return this.myFetch(e,{method:"put",body:JSON.stringify(t)})}delete(e){return this.myFetch(e,{method:"delete"})}async post(e,t){return await dr(()=>this.myFetch(e,{method:"post",body:JSON.stringify(t)}))}myFetch(e,t){const r={};if(t!=null&&t.body&&(r["Content-type"]="application/json"),typeof window<"u"&&typeof window.document<"u"&&typeof(window.document.cookie!=="undefined"))for(const i of window.document.cookie.split(";"))i.trim().startsWith("XSRF-TOKEN=")&&(r["X-XSRF-TOKEN"]=i.split("=")[1]);return(this.fetch||fetch)(e,{credentials:"include",method:t==null?void 0:t.method,body:t==null?void 0:t.body,headers:r}).then(i=>pa(i)).catch(async i=>{throw await i})}}function pa(n){if(n.status!=204){if(n.status>=200&&n.status<300)return n.json();throw n.json().then(e=>({...e,message:e.message||n.statusText,url:n.url,status:n.status})).catch(()=>{throw{message:n.statusText,url:n.url,status:n.status}})}}function ya(n,e){for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)){const r=n[t];if(Array.isArray(r)&&(r.length>0&&typeof r[0]=="object"||r.length>10)||t==="NOT")return!1}for(const t in n)if(Object.prototype.hasOwnProperty.call(n,t)){const r=n[t];Array.isArray(r)?t.endsWith(".in")?e.add(t,JSON.stringify(r)):r.forEach(i=>e.add(t,i)):t.startsWith(ft)?e.add(t,JSON.stringify(r)):e.add(t,r)}return!0}const ma="liveQuery-";var Zt,ga=new Uint8Array(16);function wa(){if(!Zt&&(Zt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Zt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Zt(ga)}const va=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ba(n){return typeof n=="string"&&va.test(n)}var pe=[];for(var $r=0;$r<256;++$r)pe.push(($r+256).toString(16).substr(1));function _a(n){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,t=(pe[n[e+0]]+pe[n[e+1]]+pe[n[e+2]]+pe[n[e+3]]+"-"+pe[n[e+4]]+pe[n[e+5]]+"-"+pe[n[e+6]]+pe[n[e+7]]+"-"+pe[n[e+8]]+pe[n[e+9]]+"-"+pe[n[e+10]]+pe[n[e+11]]+pe[n[e+12]]+pe[n[e+13]]+pe[n[e+14]]+pe[n[e+15]]).toLowerCase();if(!ba(t))throw TypeError("Stringified UUID is invalid");return t}function zr(n,e,t){n=n||{};var r=n.random||(n.rng||wa)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,_a(r)}class Ae{constructor(...e){f(this,"Segments");this.Segments=e}toEntityOrderBy(){let e={};for(const t of this.Segments)t.isDescending?e[t.field.key]="desc":e[t.field.key]="asc";return e}reverse(){let e=new Ae;for(const t of this.Segments)e.Segments.push({field:t.field,isDescending:!t.isDescending});return e}compare(e,t,r){r||(r=i=>i.key);for(let i=0;i<this.Segments.length;i++){let s=this.Segments[i],a=e[r(s.field)],o=t[r(s.field)],l=s.isDescending,u=Ia(a,o,l);if(u!=0)return u}return 0}static translateOrderByToSort(e,t){let r=new Ae;if(t){for(const i in t)if(Object.prototype.hasOwnProperty.call(t,i)){const s=t[i];let a=e.fields.find(i);const o=l=>{switch(s){case"desc":r.Segments.push({field:l,isDescending:!0});break;case"asc":r.Segments.push({field:l})}};if(a){const l=ae(a);if((l==null?void 0:l.type)==="toOne"){const u=l.options;if(typeof u.field=="string")o(e.fields.find(u.field));else if(u.fields){for(const d in u.fields)if(Object.prototype.hasOwnProperty.call(u.fields,d)){const c=u.fields[d];o(e.fields.find(c.toString()))}}}else o(a)}}}return r}static createUniqueSort(e,t){(!t||Object.keys(t).length===0)&&e.options.defaultOrderBy&&(t=Ae.translateOrderByToSort(e,e.options.defaultOrderBy)),t||(t=new Ae);for(const r of e.idMetadata.fields)t.Segments.find(i=>i.field==r)||t.Segments.push({field:r});return t}static createUniqueEntityOrderBy(e,t){(!t||Object.keys(t).length===0)&&(t=e.options.defaultOrderBy),t?t={...t}:t={};for(const r of e.idMetadata.fields)t[r.key]||(t[r.key]="asc");return t}}function Ia(n,e,t){n=Ri(n),e=Ri(e);let r=0;return n>e?r=1:n<e&&(r=-1),t&&(r*=-1),r}function Ri(n){return n==null||n==null?n:n.id!==void 0?n.id:n}const Lr="stream";class ka{constructor(e,t,r){f(this,"repo");f(this,"query");f(this,"queryChannel");f(this,"subscribeCode");f(this,"unsubscribe",()=>{});f(this,"defaultQueryState",[]);f(this,"listeners",[]);f(this,"id",zr());this.repo=e,this.query=t,this.queryChannel=`users:${r}:queries:${this.id}`,this.id=this.queryChannel}sendDefaultState(e){e(this.createReducerType(()=>[...this.defaultQueryState],this.allItemsMessage(this.defaultQueryState)))}async setAllItems(e){const t=await dt(this.repo)._fromJsonArray(e,this.query.options);this.forListeners(r=>{r(()=>t)},this.allItemsMessage(t))}allItemsMessage(e){return[{type:"all",data:e}]}forListeners(e,t){e(r=>{if(this.defaultQueryState=r(this.defaultQueryState),t.find(i=>i.type==="add"||i.type==="replace")&&this.query.options.orderBy){const i=Ae.translateOrderByToSort(this.repo.metadata,this.query.options.orderBy);this.defaultQueryState.sort((s,a)=>i.compare(s,a))}});for(const r of this.listeners)e(i=>{r.next(this.createReducerType(i,t))})}createReducerType(e,t){return{applyChanges:e,changes:t,items:this.defaultQueryState}}async handle(e){{let t=e.filter(({type:i})=>i=="add"||i=="replace"),r=await dt(this.repo)._fromJsonArray(t.map(i=>i.data.item),this.query.options);for(let i=0;i<t.length;i++){const s=t[i];s.data.item=r[i]}}this.forListeners(t=>{t(r=>{r||(r=[]);for(const i of e)switch(i.type){case"all":this.setAllItems(i.data);break;case"replace":{r=r.map(s=>this.repo.metadata.idMetadata.getId(s)===i.data.oldId?i.data.item:s);break}case"add":r=r.filter(s=>this.repo.metadata.idMetadata.getId(s)!==this.repo.metadata.idMetadata.getId(i.data.item)),r.push(i.data.item);break;case"remove":r=r.filter(s=>this.repo.metadata.idMetadata.getId(s)!==i.data.id);break}return r})},e)}}const Oa="_liveQueryKeepAlive";class Ca{constructor(e,t){f(this,"apiProvider");f(this,"getUserId");f(this,"queries",new Map);f(this,"channels",new Map);f(this,"client");f(this,"interval");this.apiProvider=e,this.getUserId=t}wrapMessageHandling(e){var t=this.apiProvider().wrapMessageHandling;t?t(e):e()}hasQueriesForTesting(){return this.queries.size>0}runPromise(e){return e}close(){this.queries.clear(),this.channels.clear(),this.closeIfNoListeners()}async subscribeChannel(e,t){let r=()=>{};const i=await this.openIfNoOpened();try{let s=this.channels.get(e);if(!s){this.channels.set(e,s=new Aa);try{s.unsubscribe=await i.subscribe(e,a=>this.wrapMessageHandling(()=>s.handle(a)),a=>{t.error(a)})}catch(a){throw t.error(a),a}}s.listeners.push(t),r=()=>{s.listeners.splice(s.listeners.indexOf(t),1),s.listeners.length==0&&(this.channels.delete(e),s.unsubscribe()),this.closeIfNoListeners()}}catch(s){throw t.error(s),s}return()=>{r(),r=()=>{}}}closeIfNoListeners(){this.client&&this.queries.size===0&&this.channels.size===0&&(this.runPromise(this.client.then(e=>e.close())),this.client=void 0,clearInterval(this.interval),this.interval=void 0)}subscribe(e,t,r){let i=!0,s=()=>{i=!1};return this.runPromise(dt(e)._buildEntityDataProviderFindOptions(t).then(a=>{if(!i)return;const{createKey:o,subscribe:l}=new Qr(this.apiProvider).getEntityDataProvider(e.metadata).buildFindRequest(a),u=o();let d=this.queries.get(u);d?d.sendDefaultState(r.next):(this.queries.set(u,d=new ka(e,{entityKey:e.metadata.key,options:t},this.getUserId())),d.subscribeCode=()=>{d.unsubscribe&&(d.unsubscribe(),d.unsubscribe=()=>{}),this.runPromise(this.subscribeChannel(d.queryChannel,{next:c=>this.runPromise(d.handle(c)),complete:()=>{},error:c=>{d.listeners.forEach(h=>h.error(c))}}).then(c=>{if(d.listeners.length==0){c();return}this.runPromise(l(d.queryChannel).then(h=>{if(d.listeners.length===0){h.unsubscribe(),c();return}this.runPromise(d.setAllItems(h.result)),d.unsubscribe=()=>{d.unsubscribe=()=>{},c(),this.runPromise(h.unsubscribe())}}).catch(h=>{d.listeners.forEach(p=>p.error(h)),c(),this.queries.delete(u)}))})).catch(c=>{d.listeners.forEach(h=>h.error(c))})},d.subscribeCode()),d.listeners.push(r),s=()=>{d.listeners.splice(d.listeners.indexOf(r),1),r.complete(),d.listeners.length==0&&(this.queries.delete(u),d.unsubscribe()),this.closeIfNoListeners()}}).catch(a=>{r.error(a)})),()=>{s()}}openIfNoOpened(){return this.client?this.client:(this.interval=setInterval(async()=>{const e=[];for(const t of this.queries.values())e.push(t.queryChannel);if(e.length>0){let t=this.apiProvider();const r=await this.runPromise(await D.actionInfo.runActionWithoutBlockingUI(()=>Ot(t.httpClient).post(t.url+"/"+Oa,e)));for(const i of r)for(const s of this.queries.values())s.queryChannel===i&&s.subscribeCode()}},3e4),this.runPromise(this.client=this.apiProvider().subscriptionClient.openConnection(()=>{for(const e of this.queries.values())e.subscribeCode()})))}}class Aa{constructor(){f(this,"unsubscribe",()=>{});f(this,"listeners",[])}async handle(e){for(const t of this.listeners)t.next(e)}}class ti{openConnection(e){let t;const r=new Map,i=Ot(_e.apiClient.httpClient);let s=!1,a;const o={close(){a.close()},async subscribe(d,c){let h=r.get(d);return h||(r.set(d,h=[]),await u(d)),h.push(c),()=>{h.splice(h.indexOf(c,1)),h.length==0&&(D.actionInfo.runActionWithoutBlockingUI(()=>i.post(_e.apiClient.url+"/"+Lr+"/unsubscribe",{channel:d,clientId:t})),r.delete(d))}}},l=()=>new Promise(d=>{h();let c=0;function h(){a&&a.close(),a=ti.createEventSource(_e.apiClient.url+"/"+Lr),a.onmessage=p=>{let y=JSON.parse(p.data);const _=r.get(y.channel);_&&_.forEach(g=>g(y.data))},a.onerror=p=>{console.error("Live Query Event Source Error",p),a.close(),c++<vn.error500RetryCount&&setTimeout(()=>{h()},500)},a.addEventListener("connectionId",async p=>{if(t=p.data,s){for(const y of r.keys())await u(y);e()}else s=!0,d(o)})}});return l();async function u(d){await D.actionInfo.runActionWithoutBlockingUI(()=>i.post(_e.apiClient.url+"/"+Lr+"/subscribe",{channel:d,clientId:t}))===Ea&&await l()}}static createEventSource(e){return new EventSource(e,{withCredentials:!0})}}const Ea="client connection not found",Kr=Symbol.for("serverActionField");class qt{constructor(){f(this,"_subscribers")}reportChanged(){this._subscribers&&this._subscribers.forEach(e=>e.reportChanged())}reportObserved(){this._subscribers&&this._subscribers.forEach(e=>e.reportObserved())}subscribe(e){let t;return typeof e=="function"?t={reportChanged:()=>e(),reportObserved:()=>{}}:t=e,this._subscribers||(this._subscribers=[]),this._subscribers.push(t),()=>this._subscribers=this._subscribers.filter(r=>r!=t)}}class Sa{constructor(e){f(this,"remultObjectStorage");this.remultObjectStorage=e}static enable(){D.remultFactory=()=>{const e=D.asyncContext.getStore();if(e)return e.remult;throw new Error("remult object was requested outside of a valid request cycle.valid context, try running `withRemult` or run within initApi or a remult request cycle")}}static disable(){sa()}async run(e,t){return this.remultObjectStorage?this.remultObjectStorage.run({remult:e},()=>t(e)):t(e)}isInInitRequest(){var e,t;return(t=(e=this.remultObjectStorage)==null?void 0:e.getStore())==null?void 0:t.inInitRequest}setInInitRequest(e){var r,i;const t=(r=this.remultObjectStorage)==null?void 0:r.getStore();t&&(e||(i=this.remultObjectStorage)!=null&&i.isStub)&&(t.inInitRequest=e)}getStore(){if(!this.remultObjectStorage)throw new Error("can't use static remult in this environment, `async_hooks` were not initialized");return this.remultObjectStorage.getStore()}}D.asyncContext||(D.asyncContext=new Sa(void 0));function Vt(){return D.actionInfo.runningOnServer||!_e.dataProvider.isProxy}class Ne{constructor(e){f(this,"repo",(e,t)=>{t===void 0&&(t=this.dataProvider);let r=this.repCache.get(t);r||this.repCache.set(t,r=new Map);let i=r.get(e);return i||(r.set(e,i=new ri(e,this,t,qa(e,this))),Zs(i,this,t)),i});f(this,"_subscribers");f(this,"__user");f(this,"dataProvider",new Qr(()=>this.apiClient));f(this,"repCache",new Map);f(this,"liveQueryStorage");f(this,"subscriptionServer");f(this,"liveQueryPublisher",{itemChanged:async()=>{}});f(this,"liveQuerySubscriber",new Ca(()=>this.apiClient,()=>{var e;return(e=this.user)==null?void 0:e.id}));f(this,"context",{});f(this,"apiClient",{url:"/api",subscriptionClient:new ti});if(e&&e.getEntityDataProvider){this.dataProvider=e;return}if(bn(e))this.apiClient.httpClient=e;else if(typeof e=="function")this.apiClient.httpClient=e;else if(e){const t=e;t.httpClient&&(this.apiClient.httpClient=t.httpClient),t.url&&(this.apiClient.url=t.url),t.subscriptionClient&&(this.apiClient.subscriptionClient=t.subscriptionClient),t.wrapMessageHandling&&(this.apiClient.wrapMessageHandling=t.wrapMessageHandling)}}subscribeAuth(e){return this._subscribers||(this._subscribers=new qt),this._subscribers.subscribe(e)}get user(){var e;return(e=this._subscribers)==null||e.reportObserved(),this.__user}set user(e){var t;this.__user=e,(t=this._subscribers)==null||t.reportChanged()}async initUser(){const t=await Ot(this.apiClient.httpClient).get(_n(this.apiClient.url,"me"));return this.user=(t==null?void 0:t.id)!=null?t:void 0,this.user}authenticated(){var e;return((e=this.user)==null?void 0:e.id)!==void 0}isAllowed(e){var t,r;if(e!=null){if(e instanceof Array){for(const i of e)if(this.isAllowed(i)===!0)return!0;return!1}return typeof e=="function"?e(this):typeof e=="boolean"?e:!!(typeof e=="string"&&(r=(t=this.user)==null?void 0:t.roles)!=null&&r.includes(e.toString()))}}isAllowedForInstance(e,t){if(Array.isArray(t)){for(const r of t)if(this.isAllowedForInstance(e,r))return!0}else return typeof t=="function"?t(e,this):this.isAllowed(t)}useFetch(e){this.dataProvider=new Qr(()=>({httpClient:e}))}call(e,t,...r){const i=e[Kr];if(!i.doWork)throw Error("The method received is not a valid backend method");return i.doWork(r,t,this.apiClient.url,Ot(this.apiClient.httpClient))}clearAllCache(){this.repCache.clear()}}f(Ne,"onFind",(e,t)=>{}),f(Ne,"entityRefInit");D.defaultRemultFactory=()=>new Ne;class In{constructor(){f(this,"classes",new Map)}}function Ta(n,e){let t=n;for(;;){let r=D.classHelpers.get(t);r||D.classHelpers.set(t,r=new In),r.classes.set(n,e);let i=Object.getPrototypeOf(t.prototype);if(i==null)break;t=i.constructor}}const Fa={defaultPageSize:200};async function Pa(n,e){const t=new Ra(n.liveQueryPublisher);let r=!0;const i=n.dataProvider;try{await n.dataProvider.transaction(async s=>{n.dataProvider=s,n.liveQueryPublisher=t,await e(s),r=!0}),r&&await t.flush()}finally{n.dataProvider=i}}class Ra{constructor(e){f(this,"orig");f(this,"transactionItems",new Map);this.orig=e}async itemChanged(e,t){let r=this.transactionItems.get(e);r||this.transactionItems.set(e,r=[]);for(const i of t)if(i.oldId!==void 0){const s=r.find(a=>a.id===i.oldId);s!==void 0?(i.deleted&&(s.deleted=!0),i.id!=s.id&&(s.id=i.id)):r.push(i)}else r.push(i)}async flush(){for(const e of this.transactionItems.keys())await this.orig.itemChanged(e,this.transactionItems.get(e))}}function xt(n,e){return e&&Object.assign(n,e),n}class kn extends Error{constructor(t){super(t.message);f(this,"modelState");f(this,"stack");f(this,"exception");f(this,"httpStatusCode");Object.assign(this,t)}}class Be{}f(Be,"number","number"),f(Be,"date","date"),f(Be,"checkbox","checkbox"),f(Be,"password","password"),f(Be,"email","email"),f(Be,"tel","tel"),f(Be,"time","time");const V=class V{};f(V,"Date",{toJson:e=>{if(e===null)return null;if(!e)return"";if(typeof e=="string"&&(e=new Date(e)),e instanceof Date)return e.toISOString();throw new Error("Expected date but got "+e)},fromJson:e=>{if(e===null)return null;if(e!=null&&e!=""&&!e.startsWith("0000-00-00"))return new Date(Date.parse(e))},toDb:e=>e,fromDb:e=>{if(typeof e=="number"&&(e=new Date(e)),typeof e=="string"&&(e=new Date(e)),e&&!(e instanceof Date))throw"expected date but got "+e;return e},fromInput:e=>V.Date.fromJson(e),toInput:e=>V.Date.toJson(e),displayValue:e=>e?e.toLocaleString():""}),f(V,"DateOnly",{fromInput:e=>V.DateOnly.fromJson(e),toInput:e=>V.DateOnly.toJson(e),toJson:e=>{var t=e;return(typeof t=="string"||typeof t=="number")&&(t=new Date(t)),!t||t==null?null:t.getHours()==0?new Date(t.valueOf()-t.getTimezoneOffset()*6e4).toISOString().substring(0,10):t.toISOString().substring(0,10)},fromJson:e=>{if(!e||e==""||e=="0000-00-00")return null;let t=new Date(Date.parse(e));return t.setMinutes(t.getMinutes()+t.getTimezoneOffset()),t},inputType:Be.date,toDb:e=>e?V.DateOnly.fromJson(V.DateOnly.toJson(e)):null,fromDb:e=>V.Date.fromDb(e),fieldTypeInDb:"date",displayValue:e=>e?e.toLocaleDateString(void 0):""}),f(V,"DateOnlyString",{...V.DateOnly,toDb:e=>{let t=V.DateOnly.toJson(e);if(t)return t.replace(/-/g,"")},fromDb:e=>{if(e===null)return null;if(e)return new Date(e.substring(0,4)+"-"+e.substring(4,6)+"-"+e.substring(6,8))}}),f(V,"Boolean",{toDb:e=>e,inputType:Be.checkbox,fromDb:e=>V.Boolean.fromJson(e),fromJson:e=>typeof e=="boolean"?e:e===1?!0:e!=null?e.toString().trim().toLowerCase()=="true":e,toJson:e=>e,fromInput:e=>V.Boolean.fromJson(e),toInput:e=>V.Boolean.toJson(e)}),f(V,"Number",{fromDb:e=>{if(e===null)return null;if(e!==void 0)return+e},toDb:e=>e,fromJson:e=>V.Number.fromDb(e),toJson:e=>V.Number.toDb(e),fromInput:(e,t)=>{let r=+e;if(e===null)return null;if(e!==void 0)return r},toInput:(e,t)=>(e==null?void 0:e.toString())??"",inputType:Be.number}),f(V,"String",{fromDb:mt,toDb:mt,fromJson:mt,toJson:mt,fromInput:mt,toInput:mt}),f(V,"Integer",{...V.Number,toJson:e=>{let t=V.Number.toDb(e);return t&&+(+t).toFixed(0)},toDb:e=>V.Integer.toJson(e),fieldTypeInDb:"integer"}),f(V,"Default",{fromJson:e=>e,toJson:e=>e,fromDb:e=>V.JsonString.fromDb(e),toDb:e=>V.JsonString.toDb(e),fromInput:e=>V.Default.fromJson(e),toInput:e=>V.Default.toJson(e),displayValue:e=>e+"",fieldTypeInDb:"",inputType:"text"}),f(V,"JsonString",{fromJson:e=>e,toJson:e=>e,fromDb:e=>e==null?null:e?JSON.parse(V.JsonString.fromJson(e)):void 0,toDb:e=>e!==void 0?e===null?null:JSON.stringify(V.JsonString.toJson(e)):void 0,fromInput:e=>V.JsonString.fromJson(e),toInput:e=>V.JsonString.toJson(e)}),f(V,"JsonValue",{fromJson:e=>e,toJson:e=>e,fromDb:e=>e,toDb:e=>e,fromInput:e=>V.JsonString.fromJson(e),toInput:e=>V.JsonString.toJson(e),fieldTypeInDb:"json"});let ve=V;function mt(n){return n==null?n:typeof n!="string"?n.toString():n}function qr(n,e,t){let r=x.fromEntityFilter(n,e);const i=()=>{};r&&r.__applyToConsumer({custom:i,databaseCustom:i,containsCaseInsensitive:i,notContainsCaseInsensitive:i,startsWithCaseInsensitive:i,endsWithCaseInsensitive:i,isDifferentFrom:i,isEqualTo:(s,a)=>{t[s.key]=a},isGreaterOrEqualTo:i,isGreaterThan:i,isIn:i,isLessOrEqualTo:i,isLessThan:i,isNotNull:i,isNull:i,not:i,or:i})}class Bt{constructor(){f(this,"entityLoaders",new Map);f(this,"promises",[])}load(e,t){let r=this.entityLoaders.get(e.entityType);r||this.entityLoaders.set(e.entityType,r=new Da(e));const i=r.find(t);return this.promises.push(i),i}async resolveAll(){for(const t of this.entityLoaders.values())for(const r of t.queries.values())r.resolve();if(this.promises.length===0)return;const e=this.promises;this.promises=[],await Promise.all(e),await this.resolveAll()}}class Da{constructor(e){f(this,"rel");f(this,"queries",new Map);this.rel=e}find(e){const{where:t,...r}=ei(e,this.rel.metadata),i=JSON.stringify(r);let s=this.queries.get(i);return s||this.queries.set(i,s=new Ma(this.rel)),s.find(e,t)}}class Ma{constructor(e){f(this,"rel");f(this,"pendingInStatements",new Map);f(this,"whereVariations",new Map);this.rel=e}find(e,t){const r=JSON.stringify(t);let i=this.whereVariations.get(r);if(!i){const s=Object.keys(t);if(s.length===1&&typeof t[s[0]]!="object"&&!e.limit){let a=this.pendingInStatements.get(s[0]);a||this.pendingInStatements.set(s[0],a=new Na(this.rel,s[0],e)),this.whereVariations.set(r,i={result:a.find(t)})}else this.whereVariations.set(r,i={result:this.rel.find(e)})}return i.result}resolve(){const e=[...this.pendingInStatements.values()];this.pendingInStatements.clear();for(const t of e)t.resolve()}}class Na{constructor(e,t,r){f(this,"rel");f(this,"key");f(this,"options");f(this,"values",new Map);this.rel=e,this.key=t,this.options=r}async resolve(){const e=[...this.values.values()];if(e.length==1){this.rel.find(this.options).then(e[0].resolve,e[0].reject);return}var t={...this.options};t.where={[this.key]:e.map(i=>i.value)},t.limit=1e3,t.page=1;let r=[];try{for(;;){const i=await this.rel.find(t);if(r.push(...i),i.length<t.limit)break;t.page++}for(const i of this.values.values())i.resolve(r.filter(s=>{const o=ne(s).fields.find(this.key),l=ae(o.metadata),u=(l==null?void 0:l.type)==="reference"?o.getId():s[this.key];return i.value==u}))}catch(i){for(const s of this.values.values())s.reject(i)}}find(e){const t=e[this.key];let r=this.values.get(t);if(!r){let i,s,a=new Promise((o,l)=>{i=o,s=l});this.values.set(t,r={value:t,resolve:i,reject:s,result:a})}return r.result}}D.actionInfo;const ce=class ce{};f(ce,"required",jt(async(e,t)=>!t.valueIsNull()&&t.value!==""&&(t.value!==void 0||ae(t.metadata)!==void 0),"Should not be empty")),f(ce,"unique",jt(async(e,t)=>{if(!t.entityRef)throw"unique validation may only work on columns that are attached to an entity";return t.isBackend()&&(t.isNew||t.valueChanged())?await t.entityRef.repository.count({[t.metadata.key]:t.value})==0:!0},"already exists")),f(ce,"uniqueOnBackend",jt(async(e,t)=>t.isBackend()&&(t.isNew||t.valueChanged())?await t.entityRef.repository.count({[t.metadata.key]:t.value})==0:!0,ce.unique.defaultMessage)),f(ce,"regex",et((e,t)=>t.test(e))),f(ce,"email",nr(e=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e),"Invalid Email")),f(ce,"url",nr(e=>!!new URL(e),"Invalid Url")),f(ce,"in",et((e,t)=>t.includes(e),e=>`Value must be one of: ${e.map(t=>typeof t=="object"?(t==null?void 0:t.id)!==void 0?t==null?void 0:t.id:t==null?void 0:t.toString():t).join(", ")}`)),f(ce,"notNull",nr(e=>e!=null,"Should not be null")),f(ce,"enum",et((e,t)=>Object.values(t).includes(e),e=>`Value must be one of ${sr(e).join(", ")}`)),f(ce,"relationExists",jt(async(e,t)=>t.valueIsNull()||!t.isBackend()?!0:!!await t.load(),"Relation value does not exist")),f(ce,"min",et((e,t)=>e>=t,e=>`Value must be bigger than or equal to ${e}`)),f(ce,"max",et((e,t)=>e<=t,e=>`Value must be smaller than or equal to ${e}`)),f(ce,"maxLength",et((e,t)=>e.length<=t,e=>`Value must be at most ${e} characters`)),f(ce,"minLength",et((e,t)=>e.length>=t,e=>`Value must be at least ${e} characters`)),f(ce,"range",et((e,[t,r])=>e>=t&&e<=r,([e,t])=>`Value must be between ${e} and ${t}`)),f(ce,"defaultMessage","Invalid value");let Re=ce;function jt(n,e){const t=async(i,s,a)=>{const o=await n(i,s);typeof o=="string"&&o.length>0?s.error=o:o||(s.error=typeof a=="function"&&a(i,s,void 0)||a||typeof e=="function"&&e(i,s,void 0)||e||Re.defaultMessage)},r=(i,s,a)=>typeof i=="string"||i==="function"||i===void 0&&s===void 0?async(o,l,u)=>await t(o,l,i||u):t(i,s,a);return Object.defineProperty(r,"defaultMessage",{get:()=>e,set:i=>{e=i},enumerable:!0}),Object.assign(r,{withMessage:i=>async(s,a)=>r(s,a,i)})}function nr(n,e){return jt((t,r)=>r.value===void 0||r.value===null?!0:n(r.value),e)}function et(n,e){const t=$a((r,i,s)=>i.value===void 0||i.value===null?!0:n(i.value,s),(r,i,s)=>typeof e=="function"&&e(s)||e,!0);return Object.assign((r,i)=>t(r,i),{get defaultMessage(){return e},set defaultMessage(r){e=r}})}function $a(n,e,t=!1){return Object.assign((i,s)=>async(a,o)=>{const l=await n(a,o,i);typeof l=="string"?o.error=l:l||(o.error=s?typeof s=="function"?t?s(i):s(a,o,i):s:e?typeof e=="function"?e(a,o,i):e:Re.defaultMessage)},{get defaultMessage(){return e},set defaultMessage(i){e=i}})}function sr(n){return Object.values(n).filter(e=>typeof n[e]!="number")}function ar(n,e,t=!1){if(!e)return n;const r=Array.isArray(e)?e:[e],i=Array.isArray(n)?n:n?[n]:[];return t?[...r,...i]:[...i,...r]}function It(n,e){return typeof n[e]<"u"}class La{constructor(e,t){f(this,"options");f(this,"repo");f(this,"_count");f(this,"_aggregates");this.options=e,this.repo=t,this.options||(this.options={}),this.options.pageSize||(this.options.pageSize=Fa.defaultPageSize)}async getPage(e){return(e??0)<1&&(e=1),this.repo.find({where:this.options.where,orderBy:this.options.orderBy,limit:this.options.pageSize,page:e,load:this.options.load,include:this.options.include})}async count(){return this._count===void 0&&(this._count=await this.repo.count(this.options.where)),this._count}async forEach(e){let t=0;for await(const r of this)await e(r),t++;return t}async paginator(e){this.options.orderBy=Ae.createUniqueEntityOrderBy(this.repo.metadata,this.options.orderBy);let t={where:{$and:[this.options.where,e]},orderBy:this.options.orderBy,limit:this.options.pageSize,load:this.options.load,include:this.options.include},r=()=>this.repo.find(t);if(this._aggregates===void 0&&It(this.options,"aggregate")){let o=this.options.aggregate;if(this.repo._dataProvider.isProxy){const l=new Bt;r=()=>this.repo._rawFind(t,!1,l,async u=>{const d=await this.repo._edp.query(u,await this.repo.__buildGroupByOptions(o));return this._aggregates=d.aggregates,d.items}).then(async u=>(await l.resolveAll(),u))}else{let l=r();r=async()=>(this._aggregates=await this.repo.aggregate({...o,where:this.options.where}),this._count=this._aggregates.$count,l)}}let i=await r(),s=()=>{throw new Error("no more pages")},a=i.length==this.options.pageSize;if(a){let o=await this.repo._createAfterFilter(this.options.orderBy,i[i.length-1]);s=()=>this.paginator(o)}return{count:()=>this.count(),hasNextPage:a,items:i,nextPage:s,aggregates:this._aggregates}}[Symbol.asyncIterator](){this.options.where||(this.options.where={});let e=this.options.orderBy;this.options.orderBy=Ae.createUniqueEntityOrderBy(this.repo.metadata,e);let t=-1,r,i,s=0;return i=async()=>{if(this.options.progress&&this.options.progress.progress(s++/await this.count()),r===void 0||t==r.items.length){if(r&&!r.hasNextPage)return{value:void 0,done:!0};let a=r;if(r?r=await r.nextPage():r=await this.paginator(),t=0,r.items.length==0)return{value:void 0,done:!0};if(((a==null?void 0:a.items.length)??!1)&&this.repo.getEntityRef(a.items[0]).getId()==this.repo.getEntityRef(r.items[0]).getId())throw new Error("pagination failure, returned same first row")}return t<r.items.length?{value:r.items[t++],done:!1}:{done:!0,value:void 0}},{next:async()=>i()}}}class ri{constructor(e,t,r,i,s){f(this,"_entity");f(this,"_remult");f(this,"_dataProvider");f(this,"_info");f(this,"_defaultFindOptions");f(this,"__edp");f(this,"_idCache",new Map);f(this,"listeners");f(this,"_cache",new Map);this._entity=e,this._remult=t,this._dataProvider=r,this._info=i,this._defaultFindOptions=s}_notFoundError(e){return{message:`id ${e} not found in entity ${this.metadata.key}`,httpStatusCode:404}}[Ut](){return this}async _createAfterFilter(e,t){let r=new Map;for(const a of Ae.translateOrderByToSort(this.metadata,e).Segments){let o=t[a.field.key];r.set(a.field.key,o)}let i={$or:[]},s=[];for(const a of Ae.translateOrderByToSort(this.metadata,e).Segments){let o={};for(const l of s)o[l.key]=r.get(l.key);s.push(a.field),a.isDescending?o[a.field.key]={$lt:r.get(a.field.key)}:o[a.field.key]={$gt:r.get(a.field.key)},i.$or.push(o)}return i}relations(e){return new Proxy({},{get:(t,r)=>{const i=this.fields.find(r),s=ae(i);if(!s)throw Error(r+" is not a relation");const{toRepo:a,returnNull:o,returnUndefined:l}=this._getFocusedRelationRepo(i,e);return s.type==="toMany"?a:{findOne:u=>o?Promise.resolve(null):l?Promise.resolve(void 0):a.findFirst({},u)}}})}_getFocusedRelationRepo(e,t){const r=ae(e);let i=r.toRepo,{findOptions:s,returnNull:a,returnUndefined:o}=this._findOptionsBasedOnRelation(r,e,void 0,t,i);return{toRepo:new ri(i._entity,i._remult,i._dataProvider,i._info,s),returnNull:a,returnUndefined:o}}get _edp(){return this.__edp?this.__edp:this.__edp=this._dataProvider.getEntityDataProvider(this.metadata)}async aggregate(e){return(await this.groupBy(e))[0]}async groupBy(e){var t=await this.__buildGroupByOptions(e);const r=await this._edp.groupBy(t);if(!(e!=null&&e[la])&&e.group){const i={include:{}};for(const a of e.group)i.include[a]=!0;const s=new Bt;await this._populateRelationsForFields(t.group,i,r,s),await s.resolveAll()}return r}async __buildGroupByOptions(e){var a,o,l,u,d,c;let t=await this._buildEntityDataProviderFindOptions({...e});const r=h=>{const p=this.metadata.fields.find(h);if(p===void 0)throw Error(`key "${h}" not found in entity`);return p},i=h=>{var p;if((p=e==null?void 0:e.group)!=null&&p.includes(h))throw Error(`field "${h}" cannot be used both in an aggregate and in group by`);return r(h)};var s={where:t.where,limit:t.limit,page:t.page,group:(a=e==null?void 0:e.group)==null?void 0:a.map(r),sum:(o=e==null?void 0:e.sum)==null?void 0:o.map(i),avg:(l=e==null?void 0:e.avg)==null?void 0:l.map(i),min:(u=e==null?void 0:e.min)==null?void 0:u.map(i),max:(d=e==null?void 0:e.max)==null?void 0:d.map(i),distinctCount:(c=e==null?void 0:e.distinctCount)==null?void 0:c.map(i)};if(e!=null&&e.orderBy){s.orderBy=[];for(const h in e.orderBy)if(Object.prototype.hasOwnProperty.call(e==null?void 0:e.orderBy,h)){const p=e.orderBy[h];if(p){if(typeof p=="string")s.orderBy.push({field:h==="$count"?void 0:r(h),isDescending:p==="desc",operation:h==="$count"?"count":void 0});else for(const y in p)if(Object.prototype.hasOwnProperty.call(p,y)){const _=p[y];s.orderBy.push({field:this.metadata.fields.find(h),isDescending:_==="desc",operation:y})}}}}return s}_getCachedById(e,t){e=e+"",this._getCachedByIdAsync(e,t);let r=this._idCache.get(e);if(!(r instanceof Promise))return r}async _getCachedByIdAsync(e,t){e=e+"";let r=this._idCache.get(e);if(r instanceof Promise)return await r;if(this._idCache.has(e))return r;if(t)return;this._idCache.set(e,void 0);let i=this.findId(e).then(s=>(s===void 0?r=null:r=s,this._idCache.set(e,r),r));return this._idCache.set(e,i),await i}_addToCache(e){e&&this._idCache.set(this.getEntityRef(e).getId()+"",e)}get metadata(){return this._info}addEventListener(e){return this.listeners||(this.listeners=[]),this.listeners.push(e),()=>{this.listeners.splice(this.listeners.indexOf(e),1)}}query(e){return new La(e,this)}getEntityRef(e){let t=e[lt];return t||(this._fixTypes(e),t=new er(this._info,e,this,this._edp,this._remult,!0),Object.defineProperty(e,lt,{get:()=>t}),t.saveOriginalData()),t}async delete(e){const t=ne(e,!1);if(t)return t.delete();if(typeof e=="string"||typeof e=="number"){if(this._dataProvider.isProxy)return this._edp.delete(e);{let i=await this.findId(e);if(!i)throw this._notFoundError(e);return await ne(i).delete()}}let r=this._getRefForExistingRow(e,void 0);return this._dataProvider.isProxy||await r.reload(),r.delete()}__cleanupPartialObject(e){const t=Object.keys(e);for(let r=0;r<t.length;r++){const i=t[r],s=this.fields[i];if(s){const a=ae(s);a&&a.type==="toOne"&&a.options.field&&t.indexOf(a.options.field)>r&&a.toRepo.getEntityRef(e[i]).getId()!==e[a.options.field]&&delete e[i]}}for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r],ae(this.fields[r]));for(const r of this.fields);}async insert(e){if(Array.isArray(e))if(this._dataProvider.isProxy){let t=[],r=[];for(const i of e){this.__cleanupPartialObject(i);let s=ne(e,!1);if(s){if(!s.isNew())throw"Item is not new"}else s=await this.getEntityRef(this.create(i));t.push(s),r.push(await s.buildDtoForInsert())}return bt(await this._edp.insertMany(r),(i,s)=>t[s].processInsertResponseDto(i))}else{let t=[];for(const r of e)t.push(await this.insert(r));return t}else{let t=ne(e,!1);if(t){if(!t.isNew())throw"Item is not new";return await t.save()}else return this.__cleanupPartialObject(e),await this.getEntityRef(this.create(e)).save()}}get fields(){return this.metadata.fields}async validate(e,...t){{let r=ne(e,!1);if(r||(r=this.getEntityRef({...e})),!t||t.length===0)return await r.validate();{r.__clearErrorsAndReportChanged();let i=!1;for(const s of t)await r.fields.find(s).validate()||(i=!0);return i?r.buildErrorInfoObject():void 0}}}__createDto(e){this.__cleanupPartialObject(e);const r=this.getEntityRef({...e}).copyDataToObject(!1),i=Object.keys(e);for(const s of this.fields)(s.dbReadOnly||!i.includes(s.key))&&delete r[s.key];return r}async updateMany({where:e,set:t}){if(this.__cleanupPartialObject(t),x.throwErrorIfFilterIsEmpty(e,"updateMany"),this._dataProvider.isProxy)return this._edp.updateMany(await this._translateWhereToFilter(e),this.__createDto({...t}));{let r=0;for await(const i of this.query({where:e,aggregate:void 0}))xt(i,t),await ne(i).save(),r++;return r}}async update(e,t){{let i=ne(t,!1);if(i)return await i.save()}{let i=ne(e,!1);if(i)return xt(e,t),i.save()}this.__cleanupPartialObject(t);let r;if(typeof e=="object"?(r=this._getRefForExistingRow(e,this.metadata.idMetadata.getId(e)),Object.assign(r.instance,t)):r=this._getRefForExistingRow(t,e),this._dataProvider.isProxy)return await r.save(Object.keys(t));{const i=await r.reload();if(!i)throw this._notFoundError(r.id);for(const s in t)if(Object.prototype.hasOwnProperty.call(t,s)){let a=r.fields[s];if(t[s]===void 0&&ae(a.metadata))continue;a&&(i[s]=t[s])}return await this._fixTypes(i),await r.save()}}async upsert(e){if(this._dataProvider.isProxy){let s=await this._edp.upsertMany((Array.isArray(e)?e:[e]).map(l=>{var u;return(u=this._defaultFindOptions)!=null&&u.where&&(qr(this.metadata,this._defaultFindOptions.where,l.where),this._fixTypes(l)),{where:this.__createDto(l.where),set:l.set?this.__createDto(l.set):void 0}}));const a=new Bt,o=await this._loadManyToOneForManyRows(s,{},a);return await a.resolveAll(),Array.isArray(e)?o:o[0]}if(Array.isArray(e))return bt(e,s=>this.upsert(s));let t=e;var r=await this.findFirst(t.where,{createIfNotFound:!0}),i=ne(r,!1);return i.isNew()?(t.set&&xt(r,t.set),await i.save()):t.set?(xt(r,t.set),await i.save()):r}_getRefForExistingRow(e,t){let r=ne(e,!1);if(!r){const i=new this._entity(this._remult);for(const a of this._fieldsOf(e)){const o=a.key;i[o]=e[o]}this._fixTypes(i);let s=new er(this._info,i,this,this._edp,this._remult,!1);typeof t=="object"&&(t=this.metadata.idMetadata.getId(t)),t?(s.id=t,s.originalId=t):s.id=s.getId(),r=s,Object.defineProperty(i,lt,{get:()=>s})}return r}async save(e){if(Array.isArray(e))return bt(e,t=>this.save(t));{let t=ne(e,!1);if(t)return await t.save();if(e instanceof Tn)return await this.getEntityRef(e).save();{let r=this.metadata.idMetadata.getId(e);return r===void 0?this.insert(e):this.update(r,e)}}}liveQuery(e){return e||(e={}),{subscribe:t=>{let r=t;return typeof t=="function"&&(r={next:t,complete:()=>{},error:()=>{}}),r.error??(r.error=()=>{}),r.complete??(r.complete=()=>{}),this._remult.liveQuerySubscriber.subscribe(this,e,r)}}}async _rawFind(e,t=!1,r,i){e||(e={}),this._defaultFindOptions&&(e={...this._defaultFindOptions,...e});let s=await this._buildEntityDataProviderFindOptions(e);t&&(delete s.orderBy,delete s.limit),Ne.onFind(this._info,e);const a=await i(s);return await this._loadManyToOneForManyRows(a,e,r)}async find(e,t=!1){const r=new Bt,i=await this._rawFind(e,t,r,s=>this._edp.find(s));return await r.resolveAll(),i}async _buildEntityDataProviderFindOptions(e){e={...e};let t={};return t={},(!e.orderBy||Object.keys(e.orderBy).length===0)&&(this._dataProvider.isProxy||(e.orderBy=this._info.entityInfo.defaultOrderBy)),t.where=await this._translateWhereToFilter(e.where),e.orderBy!==void 0&&(t.orderBy=Ae.translateOrderByToSort(this.metadata,e.orderBy)),e.limit!==void 0&&(t.limit=e.limit),e.page!==void 0&&(t.page=e.page),t}async _fromJsonArray(e,t){const r=new Bt,i=await this._loadManyToOneForManyRows(e.map(s=>{let a={};for(const o of this.metadata.fields.toArray())a[o.key]=o.valueConverter.fromJson(s[o.key]);return a}),t,r);return await r.resolveAll(),i}async _loadManyToOneForManyRows(e,t,r){let i;t!=null&&t.load&&(i=t.load(this.metadata.fields));for(const u of this.metadata.fields)if(Se(u.valueType,!1)&&!ae(u)){let h=!u.options.lazy;if(i!==void 0&&(h=i.includes(u)),h){let p=this._remult.repo(u.valueType),y=[];for(const _ of e){let g=_[u.key];g!=null&&!y.includes(g)&&!p._idCache.has(g+"")&&y.push(g)}y.length>0&&await s(p,y)}}async function s(u,d){let c=await u.find({where:u.metadata.idMetadata.getIdFilter(...d)},!0);for(const h of c)u._addToCache(h)}const a=new Set(this.fields.toArray().map(u=>{const d=this.__getRelationAndInclude(u,t);if(d.rel&&!d.incl)return u.key}).filter(u=>u!==void 0));let o=await bt(e,async u=>await this._mapRawDataToResult(u,i,a));const l=this.metadata.fields.toArray();return this._populateRelationsForFields(l,t,o,r),o}_populateRelationsForFields(e,t,r,i){for(const s of e){let{rel:a,incl:o}=this.__getRelationAndInclude(s,t);if(a)if(o){const l=a.toRepo;for(const u of r){let{findOptions:d,returnNull:c}=this._findOptionsBasedOnRelation(a,s,o,u,l);const h=s.key;if(c)u[h]=null;else{const p=a.toEntity,y=l;i.load({entityType:p,find:_=>y._rawFind(_,!1,i,g=>y._edp.find(g)),metadata:y.metadata},d).then(_=>{_.length==0&&a.type=="toOne"||(u[h]=a.type!=="toMany"?_.length==0?null:_[0]:_)})}}}else for(const l of r)Reflect.deleteProperty(l,s.key)}}__getRelationAndInclude(e,t){var a;let r=ae(e),i=e.options.defaultIncluded;const s=(a=t==null?void 0:t.include)==null?void 0:a[e.key];return s!==void 0&&(i=s),{rel:r,incl:i}}_findOptionsBasedOnRelation(e,t,r,i,s){let a=!1,o=!1,l=[],u={},d=[];typeof e.options.findOptions=="function"?d.push(e.options.findOptions(i)):typeof e.options.findOptions=="object"&&d.push(e.options.findOptions),typeof r=="object"&&d.push(r);for(const p of d){p.where&&l.push(p.where);for(const y of["limit","include","orderBy"])p[y]&&(u[y]=p[y])}const c=e.getFields(),h=p=>{const y=ne(i,!1);let _=e.type==="reference"&&y?y.fields.find(t.key).getId():i[p];return(e.type==="toOne"||e.type==="reference")&&(_===null?a=!0:_===void 0?o=!0:e.type==="reference"&&typeof _=="object"&&(_=s.metadata.idMetadata.getId(_))),_};c.compoundIdField&&(e.type==="toMany"?l.push({[c.compoundIdField]:this.metadata.idMetadata.getId(i)}):l.push(s.metadata.idMetadata.getIdFilter(h(c.compoundIdField))));for(const p in c.fields)Object.prototype.hasOwnProperty.call(c.fields,p)&&l.push({[p]:h(c.fields[p])});return u.where={$and:l},(e.type==="toOne"||e.type==="reference")&&u.orderBy&&(u.limit=1),{findOptions:u,returnNull:a,returnUndefined:o}}async _mapRawDataToResult(e,t,r){let i=new this._entity(this._remult),s=new er(this._info,i,this,this._edp,this._remult,!1,r);return Object.defineProperty(i,lt,{get:()=>s}),await s.loadDataFrom(e,t),s.saveOriginalData(),i}toJson(e){return e==null?e:Array.isArray(e)?e.map(t=>this.toJson(t)):typeof e.then=="function"?e.then(t=>this.toJson(t)):this.getEntityRef(e).toApiJson(!0)}fromJson(e,t){if(e==null)return e;if(Array.isArray(e))return e.map(i=>this.fromJson(i,t));let r=new this._entity(this._remult);for(const i of this._fieldsOf(e)){const s=i.key;if(Se(i.valueType,!1)){let o=e[i.key];typeof o=="string"||typeof o=="number"?r[s]=o:r[s]=this._remult.repo(i.valueType).fromJson(o)}else e[s]!==void 0&&(r[s]=i.valueConverter.fromJson(e[i.key]))}if(this._fixTypes(r),t)return this.create(r);{let i=new er(this._info,r,this,this._edp,this._remult,!1);return Object.defineProperty(r,lt,{get:()=>i}),i.id=i.getId(),i.saveOriginalData(),i.originalId=i.id,r}}async count(e){return this._edp.count(await this._translateWhereToFilter(e))}async deleteMany({where:e}){if(x.throwErrorIfFilterIsEmpty(e,"deleteMany"),this._dataProvider.isProxy)return this._edp.deleteMany(await this._translateWhereToFilter(e));{let t=0;for await(const r of this.query({where:e,aggregate:void 0}))await ne(r).delete(),t++;return t}}async findOne(e,t=!1){let r,i,s=e??{};if(s.useCache){let a=ei(s,this.metadata),o=JSON.stringify(a);if(i=this._cache.get(o),i!==void 0)if(i.value&&this.getEntityRef(i.value).wasDeleted())i=void 0,this._cache.delete(o);else return i.promise;else i={value:void 0,promise:void 0},this._cache.set(o,i)}return r=this.find({...s,limit:1},t).then(async a=>{let o;return a.length>0&&(o=a[0]),!o&&s.createIfNotFound&&(o=this.create(),s.where&&await qr(this.metadata,s.where,o)),o}),i&&(i.promise=r=r.then(a=>(i.value=a,a))),r}async findFirst(e,t,r=!1){if(t||(t={}),e)if(t.where){let i=t.where;t.where={$and:[i,e]}}else t.where=e;return this.findOne(t,r)}_fieldsOf(e){let t=Object.keys(e);return this.metadata.fields.toArray().filter(r=>t.includes(r.key))}create(e){var r;let t=new this._entity(this._remult);if(e){for(const i of this._fieldsOf(e)){const s=i.key;t[s]=e[s]}this._fixTypes(t)}return(r=this._defaultFindOptions)!=null&&r.where&&(qr(this.metadata,this._defaultFindOptions.where,t),this._fixTypes(t)),this.getEntityRef(t),t}async _fixTypes(e){for(const t of this._fieldsOf(e)){const r=e[t.key];if(r!=null)if(t.valueType===Date&&!(r instanceof Date))e[t.key]=t.valueConverter.fromJson(t.valueConverter.toJson(r));else for(const[i,s]of[[String,"string"],[Number,"number"],[Boolean,"boolean"]])t.valueType===i&&typeof r!==s&&(e[t.key]=t.valueConverter.fromJson(t.valueConverter.toJson(r)))}return e}findId(e,t){if(e==null)return Promise.resolve(null);if(typeof e!="string"&&typeof e!="number")throw new Error("id can be either number or string, but got: "+typeof e);return this.findFirst({},{...t,where:this.metadata.idMetadata.getIdFilter(e)},!0)}async _translateWhereToFilter(e){var i,s;let t=e??{};(i=this._defaultFindOptions)!=null&&i.where&&(t={$and:[t,(s=this._defaultFindOptions)==null?void 0:s.where]}),this._dataProvider.isProxy||(this.metadata.options.backendPreprocessFilter&&(t=await this.metadata.options.backendPreprocessFilter(t,{metadata:this.metadata,getFilterPreciseValues:a=>x.getPreciseValues(this.metadata,a||t)})),this.metadata.options.backendPrefilter&&(t={$and:[t,await x.resolve(this.metadata.options.backendPrefilter)]}));let r=await x.fromEntityFilter(this.metadata,t);return r&&!this._dataProvider.isProxy&&(r=await x.translateCustomWhere(r,this.metadata,this._remult)),r}}function qa(n,e){let t=D.columnsOfType.get(n);t||D.columnsOfType.set(n,t=[]);let r=Se(n)(e),i=Xs(n),s=Object.getPrototypeOf(n);for(;s!=null;){let a=D.columnsOfType.get(s);a&&t.unshift(...a.filter(l=>!t.find(u=>u.key==l.key)));let o=Se(s,!1);if(o){let l=o(e);r={...l,...r};let u=["saving","saved","deleting","deleted","validation"];for(const d of u)if(l[d]&&l[d]!==r[d]){let c=r[d];r[d]=async(h,p)=>{await c(h,p),await l[d](h,p)}}}s=Object.getPrototypeOf(s)}return new Ja(Cn(t,e),r,e,n,i)}class On{constructor(e,t,r,i,s){f(this,"fieldsMetadata");f(this,"instance");f(this,"remult");f(this,"isNewRow");f(this,"_error");f(this,"_subscribers");f(this,"_isLoading",!1);f(this,"lookups",new Map);f(this,"errors");f(this,"originalValues",{});this.fieldsMetadata=e,this.instance=t,this.remult=r,this.isNewRow=i;{let a=r;a!=null&&a.iAmRemultProxy&&(r=D.remultFactory())}for(const a of e)if(Se(a.valueType,!1)&&r){let l=new fa(r.repo(a.valueType),!!ae(a),a.allowNull);this.lookups.set(a.key,l);let u=t[a.key],d;Object.defineProperty(t,a.key,{get:()=>(this._subscribers&&(this._subscribers.reportObserved(),d||(d=this.fields.find(a.key),d._subscribers||(d._subscribers=new qt)),d._subscribers.reportObserved()),l.item),set:c=>{var h;l.set(c),(h=this._subscribers)==null||h.reportChanged(),d||(d=this.fields.find(a.key),d._subscribers||(d._subscribers=new qt)),d._subscribers.reportChanged()},enumerable:!(s!=null&&s.has(a.key))}),l.set(u)}else{const l=ae(a);if((l==null?void 0:l.type)==="toOne"){let u=t.hasOwnProperty(a.key),d=t[a.key];i&&!d&&(u=!1),Object.defineProperty(t,a.key,{get:()=>d,set:c=>{if(d=c,c===void 0)return;const h=a.options;if(h.field&&(this.instance[h.field]=l.toRepo.metadata.idMetadata.getId(c)),h.fields){for(const p in h.fields)if(Object.prototype.hasOwnProperty.call(h.fields,p)){const y=h.fields[p];this.instance[y]=c==null?null:c[p]}}},enumerable:!(s!=null&&s.has(a.key))}),u&&(t[a.key]=d)}}}get error(){var e;return(e=this._subscribers)==null||e.reportObserved(),this._error}set error(e){var t;this._error=e,(t=this._subscribers)==null||t.reportChanged()}subscribe(e){return this.initSubscribers(),this._subscribers.subscribe(e)}initSubscribers(){if(!this._subscribers){this._subscribers=new qt;const e=this._subscribers;for(const t of this.fieldsMetadata){let r=Se(t.valueType,!1),i=this.fields.find(t.key);if(i._subscribers=new qt,!(r&&this.remult||ae(t))){let s=this.instance[t.key];Object.defineProperty(this.instance,t.key,{get:()=>(e.reportObserved(),i._subscribers.reportObserved(),s),set:a=>{s=a,e.reportChanged(),i._subscribers.reportChanged()},enumerable:!0})}}}}get isLoading(){var e;return(e=this._subscribers)==null||e.reportObserved(),this._isLoading}set isLoading(e){var t;this._isLoading=e,(t=this._subscribers)==null||t.reportChanged()}async waitLoad(){await bt([...this.lookups.values()],e=>e.waitLoad())}__assertValidity(){if(!this.hasErrors())throw this.buildErrorInfoObject()}buildErrorInfoObject(){var t;let e={modelState:Object.assign({},this.errors),message:this.error};if(!e.message){for(const r of this.fieldsMetadata)if((t=this.errors)!=null&&t[r.key]){e.message=this.fields[r.key].metadata.caption+": "+this.errors[r.key],this.error=e.message;break}}return new kn(e)}catchSaveErrors(e){let t=e;if(t instanceof Promise)return t.then(i=>this.catchSaveErrors(i));t.error&&(t=t.error),t.message?this.error=t.message:t.Message?this.error=t.Message:this.error=t;let r=t.modelState;throw r||(r=t.ModelState),r&&(this.errors=r),e}__clearErrorsAndReportChanged(){this.errors=void 0,this.error=void 0,this._reportChangedToEntityAndFields()}_reportChangedToEntityAndFields(){if(this._subscribers){this._subscribers.reportChanged();for(const e of this.fields)e._subscribers.reportChanged()}}hasErrors(){var e;return(e=this._subscribers)==null||e.reportObserved(),!this.error&&this.errors==null}copyDataToObject(e=!1){let t={};for(const r of this.fieldsMetadata){let i=this.lookups.get(r.key),s;const a=ae(r);i?s=i.id:s=this.instance[r.key],a&&e&&!r.allowNull&&s==null&&(a.toRepo.metadata.idMetadata.field.valueType===Number?s=0:s=""),(!a||a.type==="reference")&&(s!==void 0&&(s=r.valueConverter.toJson(s),s!=null&&(s=r.valueConverter.fromJson(JSON.parse(JSON.stringify(s))))),t[r.key]=s)}return t}saveOriginalData(){this.originalValues=this.copyDataToObject(),this.saveMoreOriginalData()}saveMoreOriginalData(){}async validate(){if(this.__clearErrorsAndReportChanged(),await this.__performColumnAndEntityValidations(),this.hasErrors(),!this.hasErrors())return this.buildErrorInfoObject()}async __validateEntity(){this.__clearErrorsAndReportChanged(),await this.__performColumnAndEntityValidations(),this.__assertValidity()}async __performColumnAndEntityValidations(){}toApiJson(e=!1,t=!1){let r={};for(const i of this.fieldsMetadata)if(t||!this.remult||i.includedInApi(this.instance)){let s,a=this.lookups.get(i.key),o=!1;a?e?(s=a.toJson(),o=!0,r[i.key]=s):s=a.id:ae(i)&&!e?o=!0:(s=this.instance[i.key],this.remult||s&&Se(s.constructor,!1)&&(s=ne(s).getId())),o||(r[i.key]=i.valueConverter.toJson(s))}return r}async _updateEntityBasedOnApi(e,t=!1){let r=Object.keys(e);for(const i of this.fieldsMetadata)if(r.includes(i.key)&&i.includedInApi(this.instance)&&(!this.remult||t||i.apiUpdateAllowed(this.instance))){let s=this.lookups.get(i.key);s?s.id=e[i.key]:this.instance[i.key]=i.valueConverter.fromJson(e[i.key])}await bt([...this.fields].filter(i=>!ae(i.metadata)),i=>i.load())}}class er extends On{constructor(t,r,i,s,a,o,l){super(t.fieldsMetadata,r,a,o,l);f(this,"info");f(this,"repo");f(this,"edp");f(this,"_isNew");f(this,"repository");f(this,"metadata");f(this,"_wasDeleted",!1);f(this,"_columns");f(this,"_saving",!1);f(this,"id");f(this,"originalId");if(this.info=t,this.repo=i,this.edp=s,this._isNew=o,this.repository=i,this.metadata=t,o)for(const u of t.fieldsMetadata){const d=u.key;u.options.defaultValue&&r[d]===void 0&&(typeof u.options.defaultValue=="function"?r[d]=u.options.defaultValue(r):r[d]||(r[d]=u.options.defaultValue))}this.info.entityInfo.entityRefInit&&this.info.entityInfo.entityRefInit(this,r),Ne.entityRefInit&&Ne.entityRefInit(this,r)}clone(){const t=this.toApiJson(!0,!0);return this.repo.fromJson(t,this.isNew())}get relations(){return this.repo.relations(this.instance)}get apiUpdateAllowed(){return this.remult.isAllowedForInstance(this.instance,this.metadata.options.allowApiUpdate)}get apiDeleteAllowed(){return this.remult.isAllowedForInstance(this.instance,this.metadata.options.allowApiDelete)}get apiInsertAllowed(){return this.remult.isAllowedForInstance(this.instance,this.metadata.options.allowApiInsert)}getId(){const t=r=>{let i=this.lookups.get(r.key);return i?i.id:this.instance[r.key]};return this.metadata.idMetadata.field instanceof ut?this.metadata.idMetadata.field.getId(t):t(this.metadata.idMetadata.field)}saveMoreOriginalData(){this.originalId=this.getId()}wasDeleted(){var t;return(t=this._subscribers)==null||t.reportObserved(),this._wasDeleted}undoChanges(){this.loadDataFrom(this.originalValues),this.__clearErrorsAndReportChanged()}async reload(){return await this.edp.find({where:await this.getIdFilter()}).then(async t=>{if(t.length===0)throw this.repo._notFoundError(this.id);await this.loadDataFrom(t[0]),this.saveOriginalData()}),this._reportChangedToEntityAndFields(),this.instance}get fields(){if(!this._columns){let t=[],r={find:i=>r[typeof i=="string"?i:i.key],[Symbol.iterator]:()=>t[Symbol.iterator](),toArray:()=>t};for(const i of this.info.fieldsMetadata)t.push(r[i.key]=new cr(i.options,i,this.instance,this,this));this._columns=r}return this._columns}async save(t){var r,i;try{if(this._saving)throw new Error("cannot save while entity is already saving");if(this._saving=!0,this.wasDeleted())throw new Error("cannot save a deleted row");this.isLoading=!0,t===void 0&&await this.__validateEntity();let s=!1,a=this.buildLifeCycleEvent(()=>s=!0);if(!this.repo._dataProvider.isProxy){for(const c of this.fields)c.metadata.options.saving&&await c.metadata.options.saving(this.instance,c,a);this.info.entityInfo.saving&&await this.info.entityInfo.saving(this.instance,a)}this.__assertValidity();let o=this.copyDataToObject(this.isNew()),l=[];for(const c of this.metadata.fields)if(c.dbReadOnly||t!==void 0&&!t.includes(c.key)){o[c.key]=void 0,l.push(c.key);let h=this.fields.find(c);h.value=h.originalValue}let u,d=this.isNew();try{if((r=this._subscribers)==null||r.reportChanged(),this.isNew())s?u=(u=await this.edp.find({where:await this.getIdFilter()}))[0]:u=await this.edp.insert(o);else{let c={},h=!1;for(const p in o)if(Object.prototype.hasOwnProperty.call(o,p)){const y=o[p];this.fields.find(p).valueChanged()&&!l.includes(p)&&y!==void 0&&(c[p]=y,h=!0)}if(!h)return this.instance;if(s)u=(await this.edp.find({where:await this.getIdFilter()}))[0];else{if(this.id===void 0)throw new Error("Invalid operation, id is undefined");u=await this.edp.update(this.id,c)}}if(u&&await this.loadDataFrom(u),a.id=this.getId(),!this.repo._dataProvider.isProxy&&(this.info.entityInfo.saved&&await this.info.entityInfo.saved(this.instance,a),this.repo.listeners))for(const c of this.repo.listeners)await((i=c.saved)==null?void 0:i.call(c,this.instance,d));return this.repo._remult.liveQueryPublisher.itemChanged(this.repo.metadata.key,[{id:this.getId(),oldId:this.getOriginalId(),deleted:!1}]),this.saveOriginalData(),this._isNew=!1,this.instance}catch(c){throw await this.catchSaveErrors(c)}}finally{this.isLoading=!1,this._reportChangedToEntityAndFields(),this._saving=!1}}async processInsertResponseDto(t){return await this.loadDataFrom(t),this.saveOriginalData(),this._isNew=!1,this.instance}async buildDtoForInsert(){await this.__validateEntity(),this.__assertValidity();let t=this.copyDataToObject(this.isNew());for(const r of this.metadata.fields)if(r.dbReadOnly){t[r.key]=void 0;let i=this.fields.find(r);i.value=i.originalValue}return t}buildLifeCycleEvent(t=()=>{}){const r=this;return{isNew:r.isNew(),fields:r.fields,id:r.getId(),originalId:r.getOriginalId(),metadata:r.repo.metadata,repository:r.repo,preventDefault:()=>t(),relations:r.repo.relations(r.instance)}}async getIdFilter(){return await this.repo._translateWhereToFilter(this.repo.metadata.idMetadata.getIdFilter(this.id))}async delete(){var i;this.__clearErrorsAndReportChanged();let t=!0,r=this.buildLifeCycleEvent(()=>t=!1);this.repo._dataProvider.isProxy||this.info.entityInfo.deleting&&await this.info.entityInfo.deleting(this.instance,r),this.__assertValidity();try{if(t){if(this.id===void 0)throw new Error("Invalid operation, id is undefined");await this.edp.delete(this.id)}if(this.repo._dataProvider.isProxy||this.info.entityInfo.deleted&&await this.info.entityInfo.deleted(this.instance,r),this.repo.listeners)for(const s of this.repo.listeners)await((i=s.deleted)==null?void 0:i.call(s,this.instance));this.repo._remult.liveQueryPublisher.itemChanged(this.repo.metadata.key,[{id:this.getId(),oldId:this.getOriginalId(),deleted:!0}]),this._wasDeleted=!0}catch(s){throw await this.catchSaveErrors(s)}}async loadDataFrom(t,r){for(const i of this.info.fields){let s=this.lookups.get(i.key);s?(s.id=t[i.key],r===void 0?!i.options.lazy&&!ae(i)&&await s.waitLoad():r.includes(i)&&await s.waitLoad()):ae(i)||(t[i.key]===void 0?delete this.instance[i.key]:this.instance[i.key]=t[i.key])}await this.calcServerExpression(),this.id=this.getId()}getOriginalId(){return this.originalId}async calcServerExpression(){if(!this.repo._dataProvider.isProxy){for(const t of this.info.fieldsMetadata)if(t.options.serverExpression){const r=await t.options.serverExpression(this.instance);r!==void 0&&(this.instance[t.key]=r)}}}isNew(){var t;return(t=this._subscribers)==null||t.reportObserved(),this._isNew}wasChanged(){var t;(t=this._subscribers)==null||t.reportObserved();for(const r of this.fields){const i=ae(r.metadata);if((!i||i.type=="reference")&&r.valueChanged())return!0}return!1}async __performColumnAndEntityValidations(){var t;for(const r of this.fieldsMetadata)r.options.validate&&await new cr(r.options,r,this.instance,this,this).__performValidation();if(this.info.entityInfo.validation){let r=this.buildLifeCycleEvent(()=>{});await this.info.entityInfo.validation(this.instance,r)}if(this.repo.listeners)for(const r of this.repo.listeners)await((t=r.validating)==null?void 0:t.call(r,this.instance))}}const Di=Symbol.for("controllerColumns");function Cn(n,e){return n.map(t=>ni(t.settings(e),e))}function Mi(n,e){const t=e||_e;let r=n[Di];if(r||(r=n[lt]),!r){let i=D.columnsOfType.get(n.constructor);i||D.columnsOfType.set(n.constructor,i=[]);let s=Object.getPrototypeOf(n.constructor);for(;s!=null;){let a=D.columnsOfType.get(s);a&&i.unshift(...a.filter(o=>!i.find(l=>l.key==o.key))),s=Object.getPrototypeOf(s)}n[Di]=r=new xa(Cn(i,t).map(a=>new En(a,void 0,t)),n,t)}return r}class xa extends On{constructor(t,r,i){super(t,r,i,!1);f(this,"fields");let s=[],a={find:o=>a[typeof o=="string"?o:o.key],[Symbol.iterator]:()=>s[Symbol.iterator](),toArray:()=>s};for(const o of t)s.push(a[o.key]=new cr(o.options,o,r,void 0,this));this.fields=a}async __performColumnAndEntityValidations(){for(const t of this.fields)t instanceof cr&&await t.__performValidation()}}class cr{constructor(e,t,r,i,s){f(this,"settings");f(this,"metadata");f(this,"container");f(this,"helper");f(this,"rowBase");f(this,"_subscribers");f(this,"target");f(this,"entityRef");this.settings=e,this.metadata=t,this.container=r,this.helper=i,this.rowBase=s,this.target=this.settings.target,this.entityRef=this.helper}subscribe(e){return this._subscribers||this.rowBase.initSubscribers(),this._subscribers.subscribe(e)}valueIsNull(){this.reportObserved();let e=this.rowBase.lookups.get(this.metadata.key);return e?e.id===void 0||e.id===null:this.value===null}originalValueIsNull(){return this.reportObserved(),this.rowBase.lookups.get(this.metadata.key),this.rawOriginalValue()===null}get key(){return this.metadata.key}get repo(){var e;return(e=this.helper)==null?void 0:e.repository}async load(){let e=this.rowBase.lookups.get(this.metadata.key),t=ae(this.metadata);if(t&&this.helper){if(t.type==="toMany")return this.container[this.metadata.key]=await this.repo.relations(this.container)[this.key].find();{let r=await this.repo.relations(this.container)[this.metadata.key].findOne();if(r)this.container[this.metadata.key]=r;else return null}}else if(e)return this.valueChanged()&&await e.waitLoadOf(this.rawOriginalValue()),await e.waitLoad();return this.value}reportObserved(){var e,t;(e=this._subscribers)==null||e.reportObserved(),(t=this.rowBase._subscribers)==null||t.reportObserved()}reportChanged(){var e,t;(e=this._subscribers)==null||e.reportChanged(),(t=this.rowBase._subscribers)==null||t.reportChanged()}get error(){if(this.reportObserved(),!!this.rowBase.errors)return this.rowBase.errors[this.metadata.key]}set error(e){this.rowBase.errors||(this.rowBase.errors={}),this.rowBase.errors[this.metadata.key]=e,this.reportChanged()}get displayValue(){return this.reportObserved(),this.value!=null?this.settings.displayValue?this.settings.displayValue(this.container,this.value):this.metadata.valueConverter.displayValue?this.metadata.valueConverter.displayValue(this.value):this.value.toString():""}get value(){return this.container[this.metadata.key]}set value(e){this.container[this.metadata.key]=e}get originalValue(){this.reportObserved();let e=this.rowBase.lookups.get(this.metadata.key);return e?e.get(this.rawOriginalValue()):this.rowBase.originalValues[this.metadata.key]}rawOriginalValue(){return this.rowBase.originalValues[this.metadata.key]}setId(e){this.value=e}getId(){let e=this.rowBase.lookups.get(this.metadata.key);return e?e.id!=null?e.id:null:this.value}get inputValue(){this.reportObserved();let e=this.rowBase.lookups.get(this.metadata.key);return e?e.id!=null?e.id.toString():null:this.metadata.valueConverter.toInput(this.value,this.settings.inputType)}set inputValue(e){let t=this.rowBase.lookups.get(this.metadata.key);t?t.setId(e):this.value=this.metadata.valueConverter.fromInput(e,this.settings.inputType)}valueChanged(){this.reportObserved();let e=this.value,t=this.rowBase.lookups.get(this.metadata.key);return t&&(e=t.id),JSON.stringify(this.metadata.valueConverter.toJson(this.rowBase.originalValues[this.metadata.key]))!=JSON.stringify(this.metadata.valueConverter.toJson(e))}async __performValidation(){var e;try{const t=r=>{r!==!0&&r!==void 0&&!this.error&&(typeof r=="string"&&r.length>0?this.error=r:this.error="invalid value")};if(this.settings.validate){let r=this,i={entityRef:this.entityRef,get error(){return r.error},set error(s){r.error=s},isNew:((e=this.entityRef)==null?void 0:e.isNew())??!1,load:()=>r.load(),metadata:r.metadata,originalValue:r.originalValue,value:r.value,valueChanged:()=>r.valueChanged(),originalValueIsNull:()=>r.originalValueIsNull(),valueIsNull:()=>r.valueIsNull(),isBackend:()=>{var s,a,o;return!((o=(a=(s=r.rowBase)==null?void 0:s.remult)==null?void 0:a.dataProvider)!=null&&o.isProxy)}};if(Array.isArray(this.settings.validate))for(const s of this.settings.validate)t(await s(this.container,i));else typeof this.settings.validate=="function"&&t(await this.settings.validate(this.container,i))}}catch(t){typeof t=="string"?this.error=t:this.error=t==null?void 0:t.message}}async validate(){return await this.__performValidation(),!this.error}}let Ba={transformCaption:(n,e,t,r)=>t};const xr=D.fieldOptionsEnricher||{enrichFieldOptions:n=>n},ja=D.captionTransformer||(D.captionTransformer=Ba);function An(n,e,t,r){let i;return typeof n=="function"?t&&(i=n(t)):n&&(i=n),i=ja.transformCaption(t,e,i??"",r),i||(e?Gr(e):"")}class En{constructor(e,t,r){f(this,"settings");f(this,"entityDefs");f(this,"remult");f(this,"options");f(this,"target");f(this,"readonly",!1);f(this,"valueConverter");f(this,"allowNull");f(this,"caption");f(this,"dbName");f(this,"inputType");f(this,"key");f(this,"isServerExpression",!1);f(this,"valueType");this.settings=e,this.entityDefs=t,this.remult=r,this.options=this.settings,this.target=this.settings.target,this.valueConverter=new Proxy(this.settings.valueConverter??{},{get:(i,s)=>{let a=i[s];return typeof a=="function"?(...o)=>{try{return i[s](...o)}catch(l){const u=`${String(s)} failed for value ${o==null?void 0:o[0]}. Error: ${typeof l=="string"?l:l.message}`;throw new kn({message:this.caption+": "+u,modelState:{[this.key]:u}})}}:a}}),this.allowNull=!!this.settings.allowNull,this.valueType=this.settings.valueType,this.key=this.settings.key,this.inputType=this.settings.inputType,e.serverExpression&&(this.isServerExpression=!0),typeof this.settings.allowApiUpdate=="boolean"&&(this.readonly=this.settings.allowApiUpdate),this.inputType||(this.inputType=this.valueConverter.inputType),this.dbName=e.dbName,this.dbName==null&&(this.dbName=e.key),this.caption=An(e.caption,e.key,r,t)}apiUpdateAllowed(e){return this.options.allowApiUpdate===void 0?!0:this.remult.isAllowedForInstance(e,this.options.allowApiUpdate)}displayValue(e){return this.entityDefs.getEntityMetadataWithoutBreakingTheEntity(e).fields.find(this.key).displayValue}includedInApi(e){return this.options.includeInApi===void 0?!0:this.remult.isAllowedForInstance(e,this.options.includeInApi)}toInput(e,t){return this.valueConverter.toInput(e,t)}fromInput(e,t){return this.valueConverter.fromInput(e,t)}async getDbName(){return si(this,this.entityDefs)}get dbReadOnly(){return!!this.settings.dbReadOnly}}class Ja{constructor(e,t,r,i,s){f(this,"entityInfo");f(this,"remult");f(this,"entityType");f(this,"key");f(this,"options");f(this,"fieldsMetadata",[]);f(this,"idMetadata",{getId:e=>{if(e==null)return e;const t=ne(e,!1);return t?t.getId():this.idMetadata.field instanceof ut?this.idMetadata.field.getId(e):e[this.idMetadata.field.key]},field:void 0,get fields(){return this.field instanceof ut?this.field.fields:[this.field]},createIdInFilter:e=>e.length>0?{$or:e.map(t=>this.idMetadata.getIdFilter(ne(t).getId()))}:{[this.fields.toArray()[0].key]:[]},isIdField:e=>e.key==this.idMetadata.field.key,getIdFilter:(...e)=>{if(this.idMetadata.field instanceof ut){let t=this.idMetadata.field;return e.length==1?t.isEqualTo(e[0]):{$or:e.map(r=>t.isEqualTo(r))}}return e.length==1?{[this.idMetadata.field.key]:e[0]}:{[this.idMetadata.field.key]:e}}});f(this,"fields");f(this,"dbName");f(this,"caption");if(this.entityInfo=t,this.remult=r,this.entityType=i,this.key=s,this.options=t,this.options.allowApiCrud!==void 0){let o;typeof this.options.allowApiCrud=="function"?o=(l,u)=>this.options.allowApiCrud(u):o=this.options.allowApiCrud,this.options.allowApiDelete===void 0&&(this.entityInfo.allowApiDelete=o),this.options.allowApiInsert===void 0&&(this.entityInfo.allowApiInsert=o),this.options.allowApiUpdate===void 0&&(this.entityInfo.allowApiUpdate=o),this.options.allowApiRead===void 0&&(this.options.allowApiRead=this.options.allowApiCrud)}this.options.allowApiRead===void 0&&(this.options.allowApiRead=!0),this.key||(this.key=i.name),t.dbName||(t.dbName=this.key),this.dbName=t.dbName;let a={find:o=>a[typeof o=="string"?o:o.key],[Symbol.iterator]:()=>this.fieldsMetadata[Symbol.iterator](),toArray:()=>this.fieldsMetadata};for(const o of e)this.fieldsMetadata.push(a[o.key]=new En(o,this,r));if(this.fields=a,this.caption=An(t.caption,this.key,r,this),t.id){let o=typeof t.id=="string"?this.fields.find(t.id):Array.isArray(t.id)?t.id.map(l=>this.fields.find(l)):typeof t.id=="function"?t.id(this.fields):Object.keys(t.id).map(l=>this.fields.find(l));Array.isArray(o)?o.length>1?this.idMetadata.field=new ut(...o):o.length==1&&(this.idMetadata.field=o[0]):this.idMetadata.field=o}if(!this.idMetadata.field){const o=this.fields.id;o?this.idMetadata.field=o:this.idMetadata.field=[...this.fields][0]}}apiUpdateAllowed(e){return this.options.allowApiUpdate===void 0?!1:e?this.getEntityMetadataWithoutBreakingTheEntity(e).apiUpdateAllowed:this.remult.isAllowedForInstance(void 0,this.options.allowApiUpdate)}get apiReadAllowed(){return this.options.allowApiRead===void 0?!0:this.remult.isAllowed(this.options.allowApiRead)}apiDeleteAllowed(e){return this.options.allowApiDelete===void 0?!1:e?this.getEntityMetadataWithoutBreakingTheEntity(e).apiDeleteAllowed:this.remult.isAllowedForInstance(void 0,this.options.allowApiDelete)}apiInsertAllowed(e){return this.options.allowApiUpdate===void 0?!1:e?this.getEntityMetadataWithoutBreakingTheEntity(e).apiInsertAllowed:this.remult.isAllowedForInstance(void 0,this.options.allowApiInsert)}getEntityMetadataWithoutBreakingTheEntity(e){let t=ne(e,!1);return t||this.remult.repo(this.entityType).getEntityRef({...e})}getDbName(){return Rn(this)}}function Ua(...n){return(e,t)=>(n||(n=[]),n.splice(0,0,{valueType:e}),e[ii]=n,e)}function Va(n){var e,t;return((t=(e=n.options)==null?void 0:e.valueConverter)==null?void 0:t.fieldTypeInDb)==="autoincrement"}function Wa(...n){return(e,t)=>{Ua(r=>{r.valueConverter=hr.get(e),r.displayValue=(i,s)=>s==null?void 0:s.caption,r.validate=(i,s)=>{const a=hr.get(e).getValues();return s.value&&!a.find(o=>o===s.value)&&(s.value=a.find(o=>o.id===s.value.id)||s.value),Re.in(a)(i,s)}},...n)(e)}}class hr{constructor(e){f(this,"valueListType");f(this,"byIdMap",new Map);f(this,"values",[]);f(this,"isNumeric",!1);f(this,"fieldTypeInDb");f(this,"inputType");this.valueListType=e;for(let r in this.valueListType){let i=this.valueListType[r];i instanceof this.valueListType&&(i.id===void 0&&(i.id=r),typeof i.id=="number"&&(this.isNumeric=!0),i.caption===void 0&&(i.caption=Gr(i.id!==void 0?i.id.toString():r)),this.byIdMap.set(i.id,i),this.values.push(i))}this.isNumeric&&(this.fieldTypeInDb="integer");var t=this.valueListType[ii];if(t){for(const r of t)r!=null&&r.getValues&&(this.values.splice(0,this.values.length,...r.getValues()),this.byIdMap.clear(),this.values.forEach(i=>{i.caption===void 0&&i.id!==void 0&&(i.caption=Gr(i.id)),this.byIdMap.set(i.id,i)}));if(this.values.find(r=>r.id===void 0))throw new Error(`ValueType ${this.valueListType} has values without an id`)}else throw new Error("ValueType not yet initialized, did you forget to call @ValueListFieldType on "+e)}static get(e){let t=Ni.get(e);return t||(t=new hr(e),Ni.set(e,t)),t}getValues(){return this.values}byId(e){return this.isNumeric&&(e=+e),this.byIdMap.get(e)}fromJson(e){return this.byId(e)}toJson(e){if(e)return e.id}fromDb(e){return this.fromJson(e)}toDb(e){return this.toJson(e)}toInput(e,t){return this.toJson(e)}fromInput(e,t){return this.fromJson(e)}displayValue(e){return e?e.caption:""}}const Ni=new Map,ii=Symbol.for("storableMember"),Br=Symbol.for("fieldOptionalValues");function Sn(n,e){var r;let t={};for(const i of n)if(i)if(typeof i=="function")i(t,e);else{const{validate:s,...a}=i;t.validate=ar(t.validate,s),Object.assign(t,a)}return(r=xr.enrichFieldOptions)==null||r.call(xr,t),t}function ni(n,e){if(n.valueType){let i=n.valueType[ii];i&&(n=Sn([...i,n],e))}if(n.valueType==String){let i=n;n.valueConverter||(i.valueConverter=ve.String)}if(n.valueType==Number){let i=n;n.valueConverter||(i.valueConverter=ve.Number)}if(n.valueType==Date){let i=n;n.valueConverter||(i.valueConverter=ve.Date)}if(n.valueType==Boolean){let i=n;i.valueConverter||(i.valueConverter=ve.Boolean)}if(!n.valueConverter){if(Se(n.valueType,!1)){let s;n.valueConverter={toDb:a=>a,fromDb:a=>a},n.valueConverter=new Proxy(n.valueConverter,{get(a,o){if(a[o]===void 0&&s===void 0){if(o==="inputType")return"";s=e.repo(n.valueType).metadata.idMetadata.field.valueType===Number;for(const l of["fieldTypeInDb","toJson","fromJson","toDb","fromDb"])a[l]=s?ve.Integer[l]:ve.String[l]}return a[o]},set(a,o,l,u){return a[o]=l,!0}})}else n.valueConverter=ve.Default;return n}n.valueConverter.toJson||(n.valueConverter.toJson=i=>i),n.valueConverter.fromJson||(n.valueConverter.fromJson=i=>i);const t=n.valueConverter.fromJson,r=n.valueConverter.toJson;return n.valueConverter.toDb||(n.valueConverter.toDb=i=>r(i)),n.valueConverter.fromDb||(n.valueConverter.fromDb=i=>t(i)),n.valueConverter.toInput||(n.valueConverter.toInput=i=>r(i)),n.valueConverter.fromInput||(n.valueConverter.fromInput=i=>t(i)),n}class Tn{get _(){return ne(this)}save(){return ne(this).save()}assign(e){return xt(this,e),this}delete(){return this._.delete()}isNew(){return this._.isNew()}get $(){return this._.fields}}function Ha(n){return n.metadata?n.metadata:Se(n,!1)?_e.repo(n).metadata:n}function Ga(n){return Se(n,!1)?_e.repo(n):n}async function bt(n,e){const t=[];for(let r=0;r<n.length;r++){const i=n[r];t.push(await e(i,r))}return t}const _t=class _t{constructor(e){f(this,"sql");f(this,"wrapIdentifier",e=>e);f(this,"provideMigrationBuilder");f(this,"createdEntities",[]);f(this,"end");this.sql=e,e.wrapIdentifier&&(this.wrapIdentifier=t=>e.wrapIdentifier(t)),It(e,"provideMigrationBuilder")&&(this.provideMigrationBuilder=t=>e.provideMigrationBuilder(t)),It(e,"end")&&(this.end=()=>e.end())}static getDb(e){const t=e||_e.dataProvider;if(It(t,"createCommand"))return t;throw"the data provider is not an SqlCommandFactory"}createCommand(){return new za(this.sql.createCommand(),_t.LogToConsole)}async execute(e){return await this.createCommand().execute(e)}_getSourceSql(){return this.sql}async ensureSchema(e){this.sql.ensureSchema&&await this.sql.ensureSchema(e)}getEntityDataProvider(e){if(!this.sql.supportsJsonColumnType)for(const t of e.fields.toArray())t.valueConverter.fieldTypeInDb==="json"&&(t.valueConverter={...t.valueConverter,toDb:ve.JsonString.toDb,fromDb:ve.JsonString.fromDb});return new Fn(e,this,async t=>{this.createdEntities.indexOf(t.$entityName)<0&&(this.createdEntities.push(t.$entityName),await this.sql.entityIsUsedForTheFirstTime(e))},this.sql)}transaction(e){return this.sql.transaction(async t=>{let r=!1;try{await e(new _t({createCommand:()=>{let i=t.createCommand();return{addParameterAndReturnSqlToken:s=>i.param(s),param:s=>i.param(s),execute:async s=>{if(r)throw"can't run a command after the transaction was completed";return i.execute(s)}}},getLimitSqlSyntax:this.sql.getLimitSqlSyntax,entityIsUsedForTheFirstTime:i=>t.entityIsUsedForTheFirstTime(i),transaction:i=>t.transaction(i),supportsJsonColumnType:this.sql.supportsJsonColumnType,wrapIdentifier:this.wrapIdentifier,end:this.end,doesNotSupportReturningSyntax:this.sql.doesNotSupportReturningSyntax,doesNotSupportReturningSyntaxOnlyForUpdate:this.sql.doesNotSupportReturningSyntaxOnlyForUpdate,orderByNullsFirst:this.sql.orderByNullsFirst}))}finally{r=!0}})}static rawFilter(e){return{[gn]:{buildSql:e}}}static async filterToRaw(e,t,r,i,s){r||(r=new Ka);const a=Ga(e);var o=new ze(r,i||await Pn(a.metadata,s));return o._addWhere=!1,await(await dt(a)._translateWhereToFilter(t)).__applyToConsumer(o),await o.resolveWhere()}};f(_t,"LogToConsole",!1),f(_t,"durationThreshold",0);let Ct=_t;const Qa=new Map([["INSERT","⚪"],["SELECT","🔵"],["UPDATE","🟣"],["DELETE","🟤"],["CREATE","🟩"],["ALTER","🟨"],["DROP","🟥"],["TRUNCATE","⬛"],["GRANT","🟪"],["REVOKE","🟫"]]);class za{constructor(e,t){f(this,"origin");f(this,"logToConsole");f(this,"args",{});this.origin=e,this.logToConsole=t}addParameterAndReturnSqlToken(e){return this.param(e)}param(e,t){let r=this.origin.param(e);return this.args[r]=e,r}async execute(e){try{let r=new Date,i=await this.origin.execute(e);if(this.logToConsole!==!1){var t=new Date().valueOf()-r.valueOf();if(t>=Ct.durationThreshold){const s=t/1e3;if(this.logToConsole==="oneLiner"){const a=e.replace(/(\r\n|\n|\r|\t)/gm," ").replace(/ +/g," ").trim(),o=a.split(" ")[0].toUpperCase();console.info(`${Qa.get(o)||"💢"} (${s.toFixed(3)}) ${a} ${JSON.stringify(this.args)}`)}else typeof this.logToConsole=="function"?this.logToConsole(s,e,this.args):console.info(e+`
3
- `,{arguments:this.args,duration:s})}}return i}catch(r){throw console.error((r.message||"Sql Error")+`:
4
- `,e,{arguments:this.args,error:r}),r}}}class Fn{constructor(e,t,r,i){f(this,"entity");f(this,"sql");f(this,"iAmUsed");f(this,"strategy");this.entity=e,this.sql=t,this.iAmUsed=r,this.strategy=i}async init(){let e=await Pn(this.entity,t=>this.sql.wrapIdentifier(t));return await this.iAmUsed(e),e}async count(e){let t=await this.init(),r="select count(*) count from "+t.$entityName,i=this.sql.createCommand();if(e){let s=new ze(i,t);e.__applyToConsumer(s),r+=await s.resolveWhere()}return i.execute(r).then(s=>Number(s.rows[0].count))}async groupBy(e){return await Xa(e,await this.init(),this.sql.createCommand(),this.sql._getSourceSql().orderByNullsFirst,this.sql._getSourceSql().getLimitSqlSyntax)}async find(e){let t=await this.init(),{colKeys:r,select:i}=this.buildSelect(t);i="select "+i,i+=`
5
- from `+t.$entityName;let s=this.sql.createCommand();if(e){if(e.where){let a=new ze(s,t);e.where.__applyToConsumer(a),i+=await a.resolveWhere()}if(e.limit&&(e.orderBy=Ae.createUniqueSort(this.entity,e.orderBy)),e.orderBy||(e.orderBy=Ae.createUniqueSort(this.entity,new Ae)),e.orderBy){let a=!0,o=[];for(const l of e.orderBy.Segments)o.push(l);for(const l of o)a?(i+=" Order By ",a=!1):i+=", ",i+=t.$dbNameOf(l.field),l.isDescending&&(i+=" desc"),this.sql._getSourceSql().orderByNullsFirst&&(l.isDescending?i+=" nulls last":i+=" nulls first")}if(e.limit){let a=1;e.page&&(a=e.page),a<1&&(a=1),i+=" "+this.strategy.getLimitSqlSyntax(e.limit,(a-1)*e.limit)}}return s.execute(i).then(a=>a.rows.map(o=>this.buildResultRow(r,o,a)))}buildResultRow(e,t,r){let i={};for(let s=0;s<e.length;s++){const a=e[s];try{i[a.key]=a.valueConverter.fromDb(t[r.getColumnKeyInResultForIndexInSelect(s)])}catch(o){throw new Error("Failed to load from db:"+a.key+`\r
6
- `+o)}}return i}buildSelect(e){let t="",r=[];for(const i of this.entity.fields)i.isServerExpression||(r.length>0&&(t+=", "),t+=e.$dbNameOf(i),i.options.sqlExpression&&(t+=" as "+i.key),r.push(i));return{colKeys:r,select:t}}async update(e,t){let r=await this.init(),i=this.sql.createCommand(),s="update "+r.$entityName+" set ",a=!1;for(const h of this.entity.fields)if(!Li(h,r)){if(t[h.key]!==void 0){let p=h.valueConverter.toDb(t[h.key]);p!==void 0&&(a?s+=", ":a=!0,s+=r.$dbNameOf(h)+" = "+i.param(p))}}const o=this.entity.idMetadata.getIdFilter(e);let l=new ze(i,r);x.fromEntityFilter(this.entity,o).__applyToConsumer(l),s+=await l.resolveWhere();let{colKeys:u,select:d}=this.buildSelect(r),c=!0;return this.sql._getSourceSql().doesNotSupportReturningSyntax&&(c=!1),c&&this.sql._getSourceSql().doesNotSupportReturningSyntaxOnlyForUpdate&&(c=!1),c&&(s+=" returning "+d),i.execute(s).then(h=>{var p,y;if((y=(p=this.sql._getSourceSql()).afterMutation)==null||y.call(p),!c)return $i(this.entity,this,t,e,"update");if(h.rows.length!=1)throw new Error("Failed to update row with id "+e+", rows updated: "+h.rows.length);return this.buildResultRow(u,h.rows[0],h)})}async delete(e){let t=await this.init(),r=this.sql.createCommand(),i=new ze(r,t);x.fromEntityFilter(this.entity,this.entity.idMetadata.getIdFilter(e)).__applyToConsumer(i);let s="delete from "+t.$entityName;return s+=await i.resolveWhere(),r.execute(s).then(()=>{var a,o;(o=(a=this.sql._getSourceSql()).afterMutation)==null||o.call(a)})}async insert(e){let t=await this.init(),r=this.sql.createCommand(),i="",s="",a=!1;for(const d of this.entity.fields)if(!Li(d,t)){let c=d.valueConverter.toDb(e[d.key]);c!=null&&(a?(i+=", ",s+=", "):a=!0,i+=t.$dbNameOf(d),s+=r.param(c))}let o=`insert into ${t.$entityName} (${i}) values (${s})`,{colKeys:l,select:u}=this.buildSelect(t);return this.sql._getSourceSql().doesNotSupportReturningSyntax||(o+=" returning "+u),await r.execute(o).then(d=>{var c,h;if((h=(c=this.sql._getSourceSql()).afterMutation)==null||h.call(c),this.sql._getSourceSql().doesNotSupportReturningSyntax)if(Va(this.entity.idMetadata.field)){const p=d.rows[0];if(typeof p!="number")throw new Error("Auto increment, for a database that is does not support returning syntax, should return an array with the single last added id. Instead it returned: "+JSON.stringify(p));return this.find({where:new x(y=>y.isEqualTo(this.entity.idMetadata.field,p))}).then(y=>y[0])}else return $i(this.entity,this,e,void 0,"insert");return this.buildResultRow(l,d.rows[0],d)})}}f(Fn,"LogToConsole",!1);class Ka{execute(e){throw new Error("Method not implemented.")}addParameterAndReturnSqlToken(e){return this.param(e)}param(e){return e===null?"null":(e instanceof Date&&(e=e.toISOString()),typeof e=="string"?(e==null&&(e=""),"'"+e.replace(/'/g,"''")+"'"):e.toString())}}function $i(n,e,t,r,i){const s=r!==void 0?n.idMetadata.getIdFilter(r):{};return e.find({where:new x(a=>{for(const o of n.idMetadata.fields)a.isEqualTo(o,t[o.key]??s[o.key])})}).then(a=>{if(a.length!=1)throw new Error(`Failed to ${i} row - result contained ${a.length} rows`);return a[0]})}async function Xa(n,e,t,r,i){let s="select count(*) as count",a="";const o=[];if(o.push((c,h)=>{h[oa]=Number(c)}),n!=null&&n.group)for(const c of n==null?void 0:n.group)c.isServerExpression||(s+=", "+e.$dbNameOf(c),c.options.sqlExpression&&(s+=" as "+c.key),a==""?a=" group by ":a+=", ",a+=e.$dbNameOf(c)),o.push((h,p)=>{p[c.key]=c.valueConverter.fromDb(h)});for(const c of ua){const h=n==null?void 0:n[c];if(h)for(const p of h){if(!p.isServerExpression){const _=await e.$dbNameOf(p);s+=`, ${d(c,_)} as ${p.key}_${c}`}const y=p.valueType===Number||c=="distinctCount";o.push((_,g)=>{y&&(_=Number(_)),g[p.key]={...g[p.key],[c]:_}})}}if(s+=`
7
- from `+e.$entityName,n!=null&&n.where){let c=new ze(t,e);n==null||n.where.__applyToConsumer(c),s+=await c.resolveWhere()}a&&(s+=a);let l="";if(n!=null&&n.orderBy){for(const c of n==null?void 0:n.orderBy){l==""?l=" order by ":l+=", ";let h=c.field&&await e.$dbNameOf(c.field);switch(c.operation){case"count":h=c.operation+"(*)";break;case void 0:break;default:h=d(c.operation,h)}l+=h,c.isDescending&&(l+=" desc"),r&&(c.isDescending?l+=" nulls last":l+=" nulls first")}l&&(s+=l)}if(n!=null&&n.limit){let c=1;n.page&&(c=n.page),c<1&&(c=1),s+=" "+i(n.limit,(c-1)*n.limit)}const u=await t.execute(s);return u.rows.map(c=>{let h={};return o.forEach((p,y)=>p(c[u.getColumnKeyInResultForIndexInSelect(y)],h)),h});function d(c,h){return c==="distinctCount"?`count (distinct ${h})`:`${c}( ${h} )`}}class ze{constructor(e,t){f(this,"r");f(this,"nameProvider");f(this,"where","");f(this,"_addWhere",!0);f(this,"promises",[]);this.r=e,this.nameProvider=t}async resolveWhere(){for(;this.promises.length>0;){let e=this.promises;this.promises=[];for(const t of e)await t}return this.where}custom(e,t){throw new Error("Custom filter should be translated before it gets here")}or(e){let t="";this.promises.push((async()=>{for(const r of e){let i=new ze(this.r,this.nameProvider);i._addWhere=!1,r.__applyToConsumer(i);let s=await i.resolveWhere();if(!s)return;s.length>0&&(t.length>0&&(t+=" or "),e.length>1?t+="("+s+")":t+=s)}this.addToWhere("("+t+")")})())}not(e){this.promises.push((async()=>{let t=new ze(this.r,this.nameProvider);t._addWhere=!1,e.__applyToConsumer(t);let r=await t.resolveWhere();r&&this.addToWhere("not ("+r+")")})())}isNull(e){this.promises.push((async()=>this.addToWhere(this.nameProvider.$dbNameOf(e)+" is null"))())}isNotNull(e){this.promises.push((async()=>this.addToWhere(this.nameProvider.$dbNameOf(e)+" is not null"))())}isIn(e,t){this.promises.push((async()=>{t&&t.length>0?this.addToWhere(this.nameProvider.$dbNameOf(e)+" in ("+t.map(r=>this.r.param(e.valueConverter.toDb(r))).join(",")+")"):this.addToWhere("1 = 0 /*isIn with no values*/")})())}isEqualTo(e,t){this.add(e,t,"=")}isDifferentFrom(e,t){this.add(e,t,"<>")}isGreaterOrEqualTo(e,t){this.add(e,t,">=")}isGreaterThan(e,t){this.add(e,t,">")}isLessOrEqualTo(e,t){this.add(e,t,"<=")}isLessThan(e,t){this.add(e,t,"<")}containsCaseInsensitive(e,t){this.promises.push((async()=>{this.addToWhere("lower ("+this.nameProvider.$dbNameOf(e)+") like lower ('%"+t.replace(/'/g,"''")+"%')")})())}notContainsCaseInsensitive(e,t){this.promises.push((async()=>{this.addToWhere("not lower ("+this.nameProvider.$dbNameOf(e)+") like lower ('%"+t.replace(/'/g,"''")+"%')")})())}startsWithCaseInsensitive(e,t){this.promises.push((async()=>{this.addToWhere("lower ("+this.nameProvider.$dbNameOf(e)+") like lower ('"+t.replace(/'/g,"''")+"%')")})())}endsWithCaseInsensitive(e,t){this.promises.push((async()=>{this.addToWhere("lower ("+this.nameProvider.$dbNameOf(e)+") like lower ('%"+t.replace(/'/g,"''")+"')")})())}add(e,t,r){this.promises.push((async()=>{let i=this.nameProvider.$dbNameOf(e)+" "+r+" "+this.r.param(e.valueConverter.toDb(t));this.addToWhere(i)})())}addToWhere(e){this.where.length==0?this._addWhere&&(this.where+=" where "):this.where+=" and ",this.where+=e}databaseCustom(e){this.promises.push((async()=>{if(e!=null&&e.buildSql){let t=new Ya(this.r,this.nameProvider.wrapIdentifier),r=await e.buildSql(t);typeof r!="string"&&(r=t.sql),r&&this.addToWhere("("+r+")")}})())}}class Ya{constructor(e,t){f(this,"r");f(this,"wrapIdentifier");f(this,"sql","");f(this,"param",(e,t)=>(typeof t=="object"&&t.valueConverter.toDb&&(e=t.valueConverter.toDb(e)),this.r.param(e)));f(this,"filterToRaw",async(e,t)=>Ct.filterToRaw(e,t,this,void 0,this.wrapIdentifier));this.r=e,this.wrapIdentifier=t,this.param.bind(this),this.filterToRaw.bind(this)}addParameterAndReturnSqlToken(e){return this.param(e)}}function Li(n,e){return n.dbReadOnly||n.isServerExpression||n.options.sqlExpression&&n.dbName!=e.$dbNameOf(n)}async function Pn(n,e){return Za(n,e,!0)}async function Za(n,e,t=!1){let r=typeof e=="function"?{wrapIdentifier:e}:e||{};var i=Ha(n);r.wrapIdentifier||(r.wrapIdentifier=_e.dataProvider.wrapIdentifier),r.wrapIdentifier||(r.wrapIdentifier=a=>a);const s={$entityName:await Rn(i,r.wrapIdentifier),toString:()=>s.$entityName,$dbNameOf:a=>{var o;return typeof a=="string"?o=a:o=a.key,s[o]},wrapIdentifier:r.wrapIdentifier};for(const a of i.fields){let o=await si(a,i,r.wrapIdentifier,t);a.options.sqlExpression||(typeof r.tableName=="string"?o=r.wrapIdentifier(r.tableName)+"."+o:r.tableName===!0&&(o=s.$entityName+"."+o)),s[a.key]=o}return s}async function Rn(n,e=t=>t){if(n.options.sqlExpression){if(typeof n.options.sqlExpression=="string")return n.options.sqlExpression;if(typeof n.options.sqlExpression=="function"){const t=n.options.sqlExpression;try{return n.options.sqlExpression="recursive sqlExpression call for entity '"+n.key+"'. ",await t(n)}finally{n.options.sqlExpression=t}}}return e(n.dbName)}const jr=Symbol.for("sqlExpressionInProgressKey");async function si(n,e,t=i=>i,r=!1){try{if(n.options.sqlExpression){let a;if(typeof n.options.sqlExpression=="function"){if(n[jr]&&!r)return"recursive sqlExpression call for field '"+n.key+"'. \0";try{n[jr]=!0,a=await n.options.sqlExpression(e),a.includes("\0")||(n.options.sqlExpression=()=>a)}finally{delete n[jr]}}else a=n.options.sqlExpression;return a||n.dbName}const i=ae(n);let s=(i==null?void 0:i.type)==="toOne"&&n.options.field;if(s){let a=e.fields.find(s);if(a)return si(a,e,t,r)}return t(n.dbName)}finally{}}function Dn(n,...e){return(t,r)=>{let i=t;for(;i!=null;){for(const a in i)if(Object.prototype.hasOwnProperty.call(i,a)){const o=t[a];o!=null&&o.rawFilterInfo&&(o.rawFilterInfo.key||(o.rawFilterInfo.key=a))}i=Object.getPrototypeOf(i)}let s=a=>{let o={};for(const u of e)u&&(typeof u=="function"?u(o,a):Object.assign(o,u));let l=Object.getPrototypeOf(t);if(l){let u=Se(l,!1);if(u){let d=u(a);d&&(o={...d,...o})}}return o};return D.allEntities.push(t),Ta(t,{key:n}),t[pn]=s,t[yn]=n,t}}var pr=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},gt={},He={},ie={},he={},qi;function Mn(){if(qi)return he;qi=1,Object.defineProperty(he,"__esModule",{value:!0}),he.output=he.exists=he.hash=he.bytes=he.bool=he.number=he.isBytes=void 0;function n(l){if(!Number.isSafeInteger(l)||l<0)throw new Error(`positive integer expected, not ${l}`)}he.number=n;function e(l){if(typeof l!="boolean")throw new Error(`boolean expected, not ${l}`)}he.bool=e;function t(l){return l instanceof Uint8Array||l!=null&&typeof l=="object"&&l.constructor.name==="Uint8Array"}he.isBytes=t;function r(l,...u){if(!t(l))throw new Error("Uint8Array expected");if(u.length>0&&!u.includes(l.length))throw new Error(`Uint8Array expected of length ${u}, not of length=${l.length}`)}he.bytes=r;function i(l){if(typeof l!="function"||typeof l.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");n(l.outputLen),n(l.blockLen)}he.hash=i;function s(l,u=!0){if(l.destroyed)throw new Error("Hash instance has been destroyed");if(u&&l.finished)throw new Error("Hash#digest() has already been called")}he.exists=s;function a(l,u){r(l);const d=u.outputLen;if(l.length<d)throw new Error(`digestInto() expects output buffer of length at least ${d}`)}he.output=a;const o={number:n,bool:e,bytes:r,hash:i,exists:s,output:a};return he.default=o,he}var j={},xi;function eo(){if(xi)return j;xi=1,Object.defineProperty(j,"__esModule",{value:!0}),j.add5L=j.add5H=j.add4H=j.add4L=j.add3H=j.add3L=j.add=j.rotlBL=j.rotlBH=j.rotlSL=j.rotlSH=j.rotr32L=j.rotr32H=j.rotrBL=j.rotrBH=j.rotrSL=j.rotrSH=j.shrSL=j.shrSH=j.toBig=j.split=j.fromBig=void 0;const n=BigInt(2**32-1),e=BigInt(32);function t(C,k=!1){return k?{h:Number(C&n),l:Number(C>>e&n)}:{h:Number(C>>e&n)|0,l:Number(C&n)|0}}j.fromBig=t;function r(C,k=!1){let E=new Uint32Array(C.length),w=new Uint32Array(C.length);for(let T=0;T<C.length;T++){const{h:N,l:L}=t(C[T],k);[E[T],w[T]]=[N,L]}return[E,w]}j.split=r;const i=(C,k)=>BigInt(C>>>0)<<e|BigInt(k>>>0);j.toBig=i;const s=(C,k,E)=>C>>>E;j.shrSH=s;const a=(C,k,E)=>C<<32-E|k>>>E;j.shrSL=a;const o=(C,k,E)=>C>>>E|k<<32-E;j.rotrSH=o;const l=(C,k,E)=>C<<32-E|k>>>E;j.rotrSL=l;const u=(C,k,E)=>C<<64-E|k>>>E-32;j.rotrBH=u;const d=(C,k,E)=>C>>>E-32|k<<64-E;j.rotrBL=d;const c=(C,k)=>k;j.rotr32H=c;const h=(C,k)=>C;j.rotr32L=h;const p=(C,k,E)=>C<<E|k>>>32-E;j.rotlSH=p;const y=(C,k,E)=>k<<E|C>>>32-E;j.rotlSL=y;const _=(C,k,E)=>k<<E-32|C>>>64-E;j.rotlBH=_;const g=(C,k,E)=>C<<E-32|k>>>64-E;j.rotlBL=g;function P(C,k,E,w){const T=(k>>>0)+(w>>>0);return{h:C+E+(T/2**32|0)|0,l:T|0}}j.add=P;const O=(C,k,E)=>(C>>>0)+(k>>>0)+(E>>>0);j.add3L=O;const M=(C,k,E,w)=>k+E+w+(C/2**32|0)|0;j.add3H=M;const S=(C,k,E,w)=>(C>>>0)+(k>>>0)+(E>>>0)+(w>>>0);j.add4L=S;const v=(C,k,E,w,T)=>k+E+w+T+(C/2**32|0)|0;j.add4H=v;const I=(C,k,E,w,T)=>(C>>>0)+(k>>>0)+(E>>>0)+(w>>>0)+(T>>>0);j.add5L=I;const F=(C,k,E,w,T,N)=>k+E+w+T+N+(C/2**32|0)|0;j.add5H=F;const $={fromBig:t,split:r,toBig:i,shrSH:s,shrSL:a,rotrSH:o,rotrSL:l,rotrBH:u,rotrBL:d,rotr32H:c,rotr32L:h,rotlSH:p,rotlSL:y,rotlBH:_,rotlBL:g,add:P,add3L:O,add3H:M,add4L:S,add4H:v,add5H:F,add5L:I};return j.default=$,j}var Jr={},$t={},Bi;function to(){return Bi||(Bi=1,Object.defineProperty($t,"__esModule",{value:!0}),$t.crypto=void 0,$t.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0),$t}var ji;function ro(){return ji||(ji=1,function(n){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(n,"__esModule",{value:!0}),n.randomBytes=n.wrapXOFConstructorWithOpts=n.wrapConstructorWithOpts=n.wrapConstructor=n.checkOpts=n.Hash=n.concatBytes=n.toBytes=n.utf8ToBytes=n.asyncLoop=n.nextTick=n.hexToBytes=n.bytesToHex=n.byteSwap32=n.byteSwapIfBE=n.byteSwap=n.isLE=n.rotl=n.rotr=n.createView=n.u32=n.u8=n.isBytes=void 0;const e=to(),t=Mn();function r(w){return w instanceof Uint8Array||w!=null&&typeof w=="object"&&w.constructor.name==="Uint8Array"}n.isBytes=r;const i=w=>new Uint8Array(w.buffer,w.byteOffset,w.byteLength);n.u8=i;const s=w=>new Uint32Array(w.buffer,w.byteOffset,Math.floor(w.byteLength/4));n.u32=s;const a=w=>new DataView(w.buffer,w.byteOffset,w.byteLength);n.createView=a;const o=(w,T)=>w<<32-T|w>>>T;n.rotr=o;const l=(w,T)=>w<<T|w>>>32-T>>>0;n.rotl=l,n.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;const u=w=>w<<24&4278190080|w<<8&16711680|w>>>8&65280|w>>>24&255;n.byteSwap=u,n.byteSwapIfBE=n.isLE?w=>w:w=>(0,n.byteSwap)(w);function d(w){for(let T=0;T<w.length;T++)w[T]=(0,n.byteSwap)(w[T])}n.byteSwap32=d;const c=Array.from({length:256},(w,T)=>T.toString(16).padStart(2,"0"));function h(w){(0,t.bytes)(w);let T="";for(let N=0;N<w.length;N++)T+=c[w[N]];return T}n.bytesToHex=h;const p={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function y(w){if(w>=p._0&&w<=p._9)return w-p._0;if(w>=p._A&&w<=p._F)return w-(p._A-10);if(w>=p._a&&w<=p._f)return w-(p._a-10)}function _(w){if(typeof w!="string")throw new Error("hex string expected, got "+typeof w);const T=w.length,N=T/2;if(T%2)throw new Error("padded hex string expected, got unpadded hex of length "+T);const L=new Uint8Array(N);for(let te=0,W=0;te<N;te++,W+=2){const de=y(w.charCodeAt(W)),Ye=y(w.charCodeAt(W+1));if(de===void 0||Ye===void 0){const Ve=w[W]+w[W+1];throw new Error('hex string expected, got non-hex character "'+Ve+'" at index '+W)}L[te]=de*16+Ye}return L}n.hexToBytes=_;const g=async()=>{};n.nextTick=g;async function P(w,T,N){let L=Date.now();for(let te=0;te<w;te++){N(te);const W=Date.now()-L;W>=0&&W<T||(await(0,n.nextTick)(),L+=W)}}n.asyncLoop=P;function O(w){if(typeof w!="string")throw new Error(`utf8ToBytes expected string, got ${typeof w}`);return new Uint8Array(new TextEncoder().encode(w))}n.utf8ToBytes=O;function M(w){return typeof w=="string"&&(w=O(w)),(0,t.bytes)(w),w}n.toBytes=M;function S(...w){let T=0;for(let L=0;L<w.length;L++){const te=w[L];(0,t.bytes)(te),T+=te.length}const N=new Uint8Array(T);for(let L=0,te=0;L<w.length;L++){const W=w[L];N.set(W,te),te+=W.length}return N}n.concatBytes=S;class v{clone(){return this._cloneInto()}}n.Hash=v;const I={}.toString;function F(w,T){if(T!==void 0&&I.call(T)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(w,T)}n.checkOpts=F;function $(w){const T=L=>w().update(M(L)).digest(),N=w();return T.outputLen=N.outputLen,T.blockLen=N.blockLen,T.create=()=>w(),T}n.wrapConstructor=$;function C(w){const T=(L,te)=>w(te).update(M(L)).digest(),N=w({});return T.outputLen=N.outputLen,T.blockLen=N.blockLen,T.create=L=>w(L),T}n.wrapConstructorWithOpts=C;function k(w){const T=(L,te)=>w(te).update(M(L)).digest(),N=w({});return T.outputLen=N.outputLen,T.blockLen=N.blockLen,T.create=L=>w(L),T}n.wrapXOFConstructorWithOpts=k;function E(w=32){if(e.crypto&&typeof e.crypto.getRandomValues=="function")return e.crypto.getRandomValues(new Uint8Array(w));throw new Error("crypto.getRandomValues must be defined")}n.randomBytes=E}(Jr)),Jr}var Ji;function io(){if(Ji)return ie;Ji=1,Object.defineProperty(ie,"__esModule",{value:!0}),ie.shake256=ie.shake128=ie.keccak_512=ie.keccak_384=ie.keccak_256=ie.keccak_224=ie.sha3_512=ie.sha3_384=ie.sha3_256=ie.sha3_224=ie.Keccak=ie.keccakP=void 0;const n=Mn(),e=eo(),t=ro(),r=[],i=[],s=[],a=BigInt(0),o=BigInt(1),l=BigInt(2),u=BigInt(7),d=BigInt(256),c=BigInt(113);for(let S=0,v=o,I=1,F=0;S<24;S++){[I,F]=[F,(2*I+3*F)%5],r.push(2*(5*F+I)),i.push((S+1)*(S+2)/2%64);let $=a;for(let C=0;C<7;C++)v=(v<<o^(v>>u)*c)%d,v&l&&($^=o<<(o<<BigInt(C))-o);s.push($)}const[h,p]=(0,e.split)(s,!0),y=(S,v,I)=>I>32?(0,e.rotlBH)(S,v,I):(0,e.rotlSH)(S,v,I),_=(S,v,I)=>I>32?(0,e.rotlBL)(S,v,I):(0,e.rotlSL)(S,v,I);function g(S,v=24){const I=new Uint32Array(10);for(let F=24-v;F<24;F++){for(let k=0;k<10;k++)I[k]=S[k]^S[k+10]^S[k+20]^S[k+30]^S[k+40];for(let k=0;k<10;k+=2){const E=(k+8)%10,w=(k+2)%10,T=I[w],N=I[w+1],L=y(T,N,1)^I[E],te=_(T,N,1)^I[E+1];for(let W=0;W<50;W+=10)S[k+W]^=L,S[k+W+1]^=te}let $=S[2],C=S[3];for(let k=0;k<24;k++){const E=i[k],w=y($,C,E),T=_($,C,E),N=r[k];$=S[N],C=S[N+1],S[N]=w,S[N+1]=T}for(let k=0;k<50;k+=10){for(let E=0;E<10;E++)I[E]=S[k+E];for(let E=0;E<10;E++)S[k+E]^=~I[(E+2)%10]&I[(E+4)%10]}S[0]^=h[F],S[1]^=p[F]}I.fill(0)}ie.keccakP=g;class P extends t.Hash{constructor(v,I,F,$=!1,C=24){if(super(),this.blockLen=v,this.suffix=I,this.outputLen=F,this.enableXOF=$,this.rounds=C,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,n.number)(F),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,t.u32)(this.state)}keccak(){t.isLE||(0,t.byteSwap32)(this.state32),g(this.state32,this.rounds),t.isLE||(0,t.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(v){(0,n.exists)(this);const{blockLen:I,state:F}=this;v=(0,t.toBytes)(v);const $=v.length;for(let C=0;C<$;){const k=Math.min(I-this.pos,$-C);for(let E=0;E<k;E++)F[this.pos++]^=v[C++];this.pos===I&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:v,suffix:I,pos:F,blockLen:$}=this;v[F]^=I,(I&128)!==0&&F===$-1&&this.keccak(),v[$-1]^=128,this.keccak()}writeInto(v){(0,n.exists)(this,!1),(0,n.bytes)(v),this.finish();const I=this.state,{blockLen:F}=this;for(let $=0,C=v.length;$<C;){this.posOut>=F&&this.keccak();const k=Math.min(F-this.posOut,C-$);v.set(I.subarray(this.posOut,this.posOut+k),$),this.posOut+=k,$+=k}return v}xofInto(v){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(v)}xof(v){return(0,n.number)(v),this.xofInto(new Uint8Array(v))}digestInto(v){if((0,n.output)(v,this),this.finished)throw new Error("digest() was already called");return this.writeInto(v),this.destroy(),v}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(v){const{blockLen:I,suffix:F,outputLen:$,rounds:C,enableXOF:k}=this;return v||(v=new P(I,F,$,k,C)),v.state32.set(this.state32),v.pos=this.pos,v.posOut=this.posOut,v.finished=this.finished,v.rounds=C,v.suffix=F,v.outputLen=$,v.enableXOF=k,v.destroyed=this.destroyed,v}}ie.Keccak=P;const O=(S,v,I)=>(0,t.wrapConstructor)(()=>new P(v,S,I));ie.sha3_224=O(6,144,224/8),ie.sha3_256=O(6,136,256/8),ie.sha3_384=O(6,104,384/8),ie.sha3_512=O(6,72,512/8),ie.keccak_224=O(1,144,224/8),ie.keccak_256=O(1,136,256/8),ie.keccak_384=O(1,104,384/8),ie.keccak_512=O(1,72,512/8);const M=(S,v,I)=>(0,t.wrapXOFConstructorWithOpts)((F={})=>new P(v,S,F.dkLen===void 0?I:F.dkLen,!0));return ie.shake128=M(31,168,128/8),ie.shake256=M(31,136,256/8),ie}var Ui;function no(){if(Ui)return He;Ui=1;const{sha3_512:n}=io(),e=24,t=32,r=(y=4,_=Math.random)=>{let g="";for(;g.length<y;)g=g+Math.floor(_()*36).toString(36);return g};function i(y){let _=8n,g=0n;for(const P of y.values()){const O=BigInt(P);g=(g<<_)+O}return g}const s=(y="")=>i(n(y)).toString(36).slice(1),a=Array.from({length:26},(y,_)=>String.fromCharCode(_+97)),o=y=>a[Math.floor(y()*a.length)],l=({globalObj:y=typeof pr<"u"?pr:typeof window<"u"?window:{},random:_=Math.random}={})=>{const g=Object.keys(y).toString(),P=g.length?g+r(t,_):r(t,_);return s(P).substring(0,t)},u=y=>()=>y++,d=476782367,c=({random:y=Math.random,counter:_=u(Math.floor(y()*d)),length:g=e,fingerprint:P=l({random:y})}={})=>function(){const M=o(y),S=Date.now().toString(36),v=_().toString(36),I=r(g,y),F=`${S+I+v+P}`;return`${M+s(F).substring(1,g)}`},h=c(),p=(y,{minLength:_=2,maxLength:g=t}={})=>{const P=y.length,O=/^[0-9a-z]+$/;try{if(typeof y=="string"&&P>=_&&P<=g&&O.test(y))return!0}finally{}return!1};return He.getConstants=()=>({defaultLength:e,bigLength:t}),He.init=c,He.createId=h,He.bufToBigInt=i,He.createCounter=u,He.createFingerprint=l,He.isCuid=p,He}var Vi;function so(){if(Vi)return gt;Vi=1;const{createId:n,init:e,getConstants:t,isCuid:r}=no();return gt.createId=n,gt.init=e,gt.getConstants=t,gt.isCuid=r,gt}var Wi=so();const Hi=nr(n=>!isNaN(n)&&isFinite(n));class Y{static object(...e){return ye(void 0,...e)}static json(...e){let t=e;return t.valueConverter&&!t.valueConverter.fieldTypeInDb&&(t.valueConverter.fieldTypeInDb="json"),ye(void 0,{valueConverter:{fieldTypeInDb:"json"}},...e)}static dateOnly(...e){return ye(()=>Date,{valueConverter:ve.DateOnly},...e)}static date(...e){return ye(()=>Date,...e)}static integer(...e){return ye(()=>Number,{valueConverter:ve.Integer,validate:Hi},...e)}static autoIncrement(...e){return ye(()=>Number,{allowApiUpdate:!1,dbReadOnly:!0,valueConverter:{...ve.Integer,fieldTypeInDb:"autoincrement"}},...e)}static number(...e){return ye(()=>Number,{validate:Hi},...e)}static createdAt(...e){return ye(()=>Date,{allowApiUpdate:!1,saving:(t,r,{isNew:i})=>{i&&(r.value=new Date)}},...e)}static updatedAt(...e){return ye(()=>Date,{allowApiUpdate:!1,saving:(t,r)=>{r.value=new Date}},...e)}static uuid(...e){return ye(()=>String,{allowApiUpdate:!1,defaultValue:()=>zr(),saving:(t,r)=>{r.value||(r.value=zr())}},...e)}static cuid(...e){return ye(()=>String,{allowApiUpdate:!1,defaultValue:()=>Wi.createId(),saving:(t,r)=>{r.value||(r.value=Wi.createId())}},...e)}static literal(e,...t){return Y.string({validate:(r,i)=>Re.in(e())(r,i),[Br]:e},...t)}static enum(e,...t){let r;return ye(()=>e(),{validate:(i,s)=>Re.enum(e())(i,s),[Br]:()=>sr(e())},...t,i=>{if(i[Br]=()=>sr(e()),r===void 0){let s=e();r=sr(s).find(o=>typeof o=="string")?ve.String:ve.Integer}i.valueConverter?i.valueConverter.fieldTypeInDb||(i.valueConverter.fieldTypeInDb=r.fieldTypeInDb):i.valueConverter=r})}static string(...e){return ye(()=>String,...e)}static boolean(...e){return ye(()=>Boolean,...e)}}class _r{static toOne(e,t){let r=typeof t=="string"?{field:t}:t||{};return!r.field&&!r.fields&&!r.findOptions?ye(e,{...r,...Mr(e,"reference")}):ye(()=>{},{...r,serverExpression:()=>{},...Mr(e,"toOne")})}static toMany(e,t){return ye(()=>{},{...typeof t=="string"?{field:t}:t,serverExpression:()=>{},...Mr(e,"toMany")})}}function ye(n,...e){return(t,r,i)=>{const s=typeof r=="string"?r:r.name.toString();let a=u=>{let d=Sn(e,u);if(d.required&&(d.validate=ar(d.validate,Re.required,!0)),It(d,"maxLength")){let h=d;h.maxLength&&(h.validate=ar(h.validate,Re.maxLength(h.maxLength)))}if(It(d,"minLength")){let h=d;h.minLength&&(h.validate=ar(h.validate,Re.minLength(h.minLength)))}!d.valueType&&n&&(d.valueType=n()),d.key||(d.key=s),d.dbName||(d.dbName=d.key);let c=d.valueType;return c||(c=typeof Reflect.getMetadata=="function"?Reflect.getMetadata("design:type",t,s):[],d.valueType=c),d.target||(d.target=t),d};Nn(t);let o=D.columnsOfType.get(t.constructor);o||(o=[],D.columnsOfType.set(t.constructor,o));let l=o.find(u=>u.key==s);if(!l)o.push({key:s,settings:a});else{let u=l.settings;l.settings=d=>{let c=u(d),h=a(d);return Object.assign(c,h)}}}}function Nn(n){if(!n)throw new Error("Set the 'experimentalDecorators:true' option in your 'tsconfig' or 'jsconfig' (target undefined)")}function ao(n,e,t,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,e,t,r);else for(var o=n.length-1;o>=0;o--)(a=n[o])&&(s=(i<3?a(s):i>3?a(e,t,s):a(e,t))||s);return i>3&&s&&Object.defineProperty(e,t,s),s}function oo(n,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,e)}class yr extends Tn{constructor(){super(...arguments);f(this,"id")}}ao([Y.uuid(),oo("design:type",String)],yr.prototype,"id",void 0);var Gi={};/*! *****************************************************************************
8
- Copyright (C) Microsoft. All rights reserved.
9
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
10
- this file except in compliance with the License. You may obtain a copy of the
11
- License at http://www.apache.org/licenses/LICENSE-2.0
12
-
13
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
15
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
16
- MERCHANTABLITY OR NON-INFRINGEMENT.
17
-
18
- See the Apache Version 2.0 License for specific language governing permissions
19
- and limitations under the License.
20
- ***************************************************************************** */var Qi;function lo(){if(Qi)return Gi;Qi=1;var n;return function(e){(function(t){var r=typeof pr=="object"?pr:typeof self=="object"?self:typeof this=="object"?this:Function("return this;")(),i=s(e);typeof r.Reflect>"u"?r.Reflect=e:i=s(r.Reflect,i),t(i);function s(a,o){return function(l,u){typeof a[l]!="function"&&Object.defineProperty(a,l,{configurable:!0,writable:!0,value:u}),o&&o(l,u)}}})(function(t){var r=Object.prototype.hasOwnProperty,i=typeof Symbol=="function",s=i&&typeof Symbol.toPrimitive<"u"?Symbol.toPrimitive:"@@toPrimitive",a=i&&typeof Symbol.iterator<"u"?Symbol.iterator:"@@iterator",o=typeof Object.create=="function",l={__proto__:[]}instanceof Array,u=!o&&!l,d={create:o?function(){return Cr(Object.create(null))}:l?function(){return Cr({__proto__:null})}:function(){return Cr({})},has:u?function(m,b){return r.call(m,b)}:function(m,b){return b in m},get:u?function(m,b){return r.call(m,b)?m[b]:void 0}:function(m,b){return m[b]}},c=Object.getPrototypeOf(Function),h=typeof process=="object"&&process.env&&process.env.REFLECT_METADATA_USE_MAP_POLYFILL==="true",p=!h&&typeof Map=="function"&&typeof Map.prototype.entries=="function"?Map:Yn(),y=!h&&typeof Set=="function"&&typeof Set.prototype.entries=="function"?Set:Zn(),_=!h&&typeof WeakMap=="function"?WeakMap:es(),g=new _;function P(m,b,A,R){if(oe(A)){if(!oi(m))throw new TypeError;if(!li(b))throw new TypeError;return E(m,b)}else{if(!oi(m))throw new TypeError;if(!ge(b))throw new TypeError;if(!ge(R)&&!oe(R)&&!pt(R))throw new TypeError;return pt(R)&&(R=void 0),A=We(A),w(m,b,A,R)}}t("decorate",P);function O(m,b){function A(R,q){if(!ge(R))throw new TypeError;if(!oe(q)&&!Gn(q))throw new TypeError;de(m,b,R,q)}return A}t("metadata",O);function M(m,b,A,R){if(!ge(A))throw new TypeError;return oe(R)||(R=We(R)),de(m,b,A,R)}t("defineMetadata",M);function S(m,b,A){if(!ge(b))throw new TypeError;return oe(A)||(A=We(A)),N(m,b,A)}t("hasMetadata",S);function v(m,b,A){if(!ge(b))throw new TypeError;return oe(A)||(A=We(A)),L(m,b,A)}t("hasOwnMetadata",v);function I(m,b,A){if(!ge(b))throw new TypeError;return oe(A)||(A=We(A)),te(m,b,A)}t("getMetadata",I);function F(m,b,A){if(!ge(b))throw new TypeError;return oe(A)||(A=We(A)),W(m,b,A)}t("getOwnMetadata",F);function $(m,b){if(!ge(m))throw new TypeError;return oe(b)||(b=We(b)),Ye(m,b)}t("getMetadataKeys",$);function C(m,b){if(!ge(m))throw new TypeError;return oe(b)||(b=We(b)),Ve(m,b)}t("getOwnMetadataKeys",C);function k(m,b,A){if(!ge(b))throw new TypeError;oe(A)||(A=We(A));var R=T(b,A,!1);if(oe(R)||!R.delete(m))return!1;if(R.size>0)return!0;var q=g.get(b);return q.delete(A),q.size>0||g.delete(b),!0}t("deleteMetadata",k);function E(m,b){for(var A=m.length-1;A>=0;--A){var R=m[A],q=R(b);if(!oe(q)&&!pt(q)){if(!li(q))throw new TypeError;b=q}}return b}function w(m,b,A,R){for(var q=m.length-1;q>=0;--q){var ke=m[q],J=ke(b,A,R);if(!oe(J)&&!pt(J)){if(!ge(J))throw new TypeError;R=J}}return R}function T(m,b,A){var R=g.get(m);if(oe(R)){if(!A)return;R=new p,g.set(m,R)}var q=R.get(b);if(oe(q)){if(!A)return;q=new p,R.set(b,q)}return q}function N(m,b,A){var R=L(m,b,A);if(R)return!0;var q=Or(b);return pt(q)?!1:N(m,q,A)}function L(m,b,A){var R=T(b,A,!1);return oe(R)?!1:Wn(R.has(m))}function te(m,b,A){var R=L(m,b,A);if(R)return W(m,b,A);var q=Or(b);if(!pt(q))return te(m,q,A)}function W(m,b,A){var R=T(b,A,!1);if(!oe(R))return R.get(m)}function de(m,b,A,R){var q=T(A,R,!0);q.set(m,b)}function Ye(m,b){var A=Ve(m,b),R=Or(m);if(R===null)return A;var q=Ye(R,b);if(q.length<=0)return A;if(A.length<=0)return q;for(var ke=new y,J=[],H=0,B=A;H<B.length;H++){var z=B[H],K=ke.has(z);K||(ke.add(z),J.push(z))}for(var Ze=0,fi=q;Ze<fi.length;Ze++){var z=fi[Ze],K=ke.has(z);K||(ke.add(z),J.push(z))}return J}function Ve(m,b){var A=[],R=T(m,b,!1);if(oe(R))return A;for(var q=R.keys(),ke=Qn(q),J=0;;){var H=Kn(ke);if(!H)return A.length=J,A;var B=zn(H);try{A[J]=B}catch(z){try{Xn(ke)}finally{throw z}}J++}}function kr(m){if(m===null)return 1;switch(typeof m){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return m===null?1:6;default:return 6}}function oe(m){return m===void 0}function pt(m){return m===null}function Jn(m){return typeof m=="symbol"}function ge(m){return typeof m=="object"?m!==null:typeof m=="function"}function Un(m,b){switch(kr(m)){case 0:return m;case 1:return m;case 2:return m;case 3:return m;case 4:return m;case 5:return m}var A="string",R=ui(m,s);if(R!==void 0){var q=R.call(m,A);if(ge(q))throw new TypeError;return q}return Vn(m)}function Vn(m,b){var A,R;{var q=m.toString;if(Xt(q)){var R=q.call(m);if(!ge(R))return R}var A=m.valueOf;if(Xt(A)){var R=A.call(m);if(!ge(R))return R}}throw new TypeError}function Wn(m){return!!m}function Hn(m){return""+m}function We(m){var b=Un(m);return Jn(b)?b:Hn(b)}function oi(m){return Array.isArray?Array.isArray(m):m instanceof Object?m instanceof Array:Object.prototype.toString.call(m)==="[object Array]"}function Xt(m){return typeof m=="function"}function li(m){return typeof m=="function"}function Gn(m){switch(kr(m)){case 3:return!0;case 4:return!0;default:return!1}}function ui(m,b){var A=m[b];if(A!=null){if(!Xt(A))throw new TypeError;return A}}function Qn(m){var b=ui(m,a);if(!Xt(b))throw new TypeError;var A=b.call(m);if(!ge(A))throw new TypeError;return A}function zn(m){return m.value}function Kn(m){var b=m.next();return b.done?!1:b}function Xn(m){var b=m.return;b&&b.call(m)}function Or(m){var b=Object.getPrototypeOf(m);if(typeof m!="function"||m===c||b!==c)return b;var A=m.prototype,R=A&&Object.getPrototypeOf(A);if(R==null||R===Object.prototype)return b;var q=R.constructor;return typeof q!="function"||q===m?b:q}function Yn(){var m={},b=[],A=function(){function J(H,B,z){this._index=0,this._keys=H,this._values=B,this._selector=z}return J.prototype["@@iterator"]=function(){return this},J.prototype[a]=function(){return this},J.prototype.next=function(){var H=this._index;if(H>=0&&H<this._keys.length){var B=this._selector(this._keys[H],this._values[H]);return H+1>=this._keys.length?(this._index=-1,this._keys=b,this._values=b):this._index++,{value:B,done:!1}}return{value:void 0,done:!0}},J.prototype.throw=function(H){throw this._index>=0&&(this._index=-1,this._keys=b,this._values=b),H},J.prototype.return=function(H){return this._index>=0&&(this._index=-1,this._keys=b,this._values=b),{value:H,done:!0}},J}();return function(){function J(){this._keys=[],this._values=[],this._cacheKey=m,this._cacheIndex=-2}return Object.defineProperty(J.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),J.prototype.has=function(H){return this._find(H,!1)>=0},J.prototype.get=function(H){var B=this._find(H,!1);return B>=0?this._values[B]:void 0},J.prototype.set=function(H,B){var z=this._find(H,!0);return this._values[z]=B,this},J.prototype.delete=function(H){var B=this._find(H,!1);if(B>=0){for(var z=this._keys.length,K=B+1;K<z;K++)this._keys[K-1]=this._keys[K],this._values[K-1]=this._values[K];return this._keys.length--,this._values.length--,H===this._cacheKey&&(this._cacheKey=m,this._cacheIndex=-2),!0}return!1},J.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=m,this._cacheIndex=-2},J.prototype.keys=function(){return new A(this._keys,this._values,R)},J.prototype.values=function(){return new A(this._keys,this._values,q)},J.prototype.entries=function(){return new A(this._keys,this._values,ke)},J.prototype["@@iterator"]=function(){return this.entries()},J.prototype[a]=function(){return this.entries()},J.prototype._find=function(H,B){return this._cacheKey!==H&&(this._cacheIndex=this._keys.indexOf(this._cacheKey=H)),this._cacheIndex<0&&B&&(this._cacheIndex=this._keys.length,this._keys.push(H),this._values.push(void 0)),this._cacheIndex},J}();function R(J,H){return J}function q(J,H){return H}function ke(J,H){return[J,H]}}function Zn(){return function(){function m(){this._map=new p}return Object.defineProperty(m.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),m.prototype.has=function(b){return this._map.has(b)},m.prototype.add=function(b){return this._map.set(b,b),this},m.prototype.delete=function(b){return this._map.delete(b)},m.prototype.clear=function(){this._map.clear()},m.prototype.keys=function(){return this._map.keys()},m.prototype.values=function(){return this._map.values()},m.prototype.entries=function(){return this._map.entries()},m.prototype["@@iterator"]=function(){return this.keys()},m.prototype[a]=function(){return this.keys()},m}()}function es(){var m=16,b=d.create(),A=R();return function(){function B(){this._key=R()}return B.prototype.has=function(z){var K=q(z,!1);return K!==void 0?d.has(K,this._key):!1},B.prototype.get=function(z){var K=q(z,!1);return K!==void 0?d.get(K,this._key):void 0},B.prototype.set=function(z,K){var Ze=q(z,!0);return Ze[this._key]=K,this},B.prototype.delete=function(z){var K=q(z,!1);return K!==void 0?delete K[this._key]:!1},B.prototype.clear=function(){this._key=R()},B}();function R(){var B;do B="@@WeakMap@@"+H();while(d.has(b,B));return b[B]=!0,B}function q(B,z){if(!r.call(B,A)){if(!z)return;Object.defineProperty(B,A,{value:d.create()})}return B[A]}function ke(B,z){for(var K=0;K<z;++K)B[K]=Math.random()*255|0;return B}function J(B){return typeof Uint8Array=="function"?typeof crypto<"u"?crypto.getRandomValues(new Uint8Array(B)):typeof msCrypto<"u"?msCrypto.getRandomValues(new Uint8Array(B)):ke(new Uint8Array(B),B):ke(new Array(B),B)}function H(){var B=J(m);B[6]=B[6]&79|64,B[8]=B[8]&191|128;for(var z="",K=0;K<m;++K){var Ze=B[K];(K===4||K===6||K===8)&&(z+="-"),Ze<16&&(z+="0"),z+=Ze.toString(16).toLowerCase()}return z}}function Cr(m){return m.__=void 0,delete m.__,m}})}(n||(n={})),Gi}lo();const mr=class mr{constructor(e,t,r){f(this,"actionUrl");f(this,"queue");f(this,"allowed");f(this,"doWork");this.actionUrl=e,this.queue=t,this.allowed=r}async run(e,t,r){t===void 0&&(t=_e.apiClient.url),r||(r=Ot(_e.apiClient.httpClient));let i=await r.post(t+"/"+this.actionUrl,e),s=i;if(s&&s.queuedJobId){let a=D.actionInfo.startBusyWithProgress();try{let o;if(await D.actionInfo.runActionWithoutBlockingUI(async()=>{for(;!o||!o.done;)o&&await new Promise(l=>setTimeout(()=>{l(void 0)},200)),o=await r.post(t+"/"+mr.apiUrlForJobStatus,{queuedJobId:i.queuedJobId}),o.progress&&a.progress(o.progress)}),o.error)throw o.error;return a.progress(1),o.result}finally{a.close()}}else return i}__register(e){e(this.actionUrl,this.queue,this.allowed,async(t,r,i)=>{try{var s=await this.execute(t,r,i);i.success(s)}catch(a){a.isForbiddenError?i.forbidden():i.error(a,void 0)}})}};f(mr,"apiUrlForJobStatus","jobStatusInQueue");let Wt=mr;class Xr extends Error{constructor(t="Forbidden"){super(t);f(this,"isForbiddenError",!0)}}class uo extends Wt{constructor(t,r,i,s){super(t,i.queue??!1,i.allowed);f(this,"types");f(this,"options");f(this,"originalMethod");this.types=r,this.options=i,this.originalMethod=s}async execute(t,r,i){let s={data:{}},a=r.dataProvider;return await qn(r,this.options,async()=>{if(!r.isAllowedForInstance(void 0,this.options.allowed))throw new Xr;t.args=await Ln(this.types(),t.args,r,a,i);try{s.data=await this.originalMethod(t.args)}catch(o){throw o}}),s}}function Je(n){return(e,t,r)=>{const i=typeof t=="string"?t:t.name.toString(),s=r?r.value:e;let a=s;Nn(e);function o(){var d=typeof Reflect.getMetadata=="function"?Reflect.getMetadata("design:paramtypes",e,i):[];return n.paramTypes&&(d=typeof n.paramTypes=="function"?n.paramTypes():n.paramTypes),d}if(e.prototype!==void 0){let d=new uo((n!=null&&n.apiPrefix?n.apiPrefix+"/":"")+i,()=>o(),n,c=>s.apply(void 0,c));return d.doWork=async(c,h,p,y)=>(c=Xi(o(),c),n.blockUser===!1?await D.actionInfo.runActionWithoutBlockingUI(async()=>(await d.run({args:c},p,y)).data):(await d.run({args:c},p,y)).data),a=async function(...c){return Vt()?await s.apply(this,c):await d.doWork(c,void 0)},zi(e,a),a[Kr]=d,r?(r.value=a,r):a}let l=D.classHelpers.get(e.constructor);l||(l=new In,D.classHelpers.set(e.constructor,l));let u={__register(d){let c=new Ne;for(const h of l.classes.keys()){let p=l.classes.get(h);p.key||(p.key=c.repo(h).metadata.key),d(p.key+"/"+(n!=null&&n.apiPrefix?n.apiPrefix+"/":"")+i,n?n.queue??!1:!1,n.allowed,async(y,_,g)=>{y.args=y.args.map(O=>$n(O)?void 0:O);let P=n.allowed;try{let O=_,M;await qn(O,n,async()=>{if(y.args=await Ln(o(),y.args,O,O.dataProvider,g),D.allEntities.includes(h)){let S=O.repo(h),v;const I=y.rowInfo;if(I.isNewRow)v=S.create(),await S.getEntityRef(v)._updateEntityBasedOnApi(I.data);else{let $=await S.find({where:{...S.metadata.idMetadata.getIdFilter(I.id),$and:[S.metadata.options.apiPrefilter??{}]}});if($.length!=1)throw new Error("not found or too many matches");v=$[0],await S.getEntityRef(v)._updateEntityBasedOnApi(I.data)}if(!O.isAllowedForInstance(v,P))throw new Xr;let F=ne(v);await F.__validateEntity();try{M={result:await s.apply(v,y.args),rowInfo:{data:await F.toApiJson(),isNewRow:F.isNew(),wasChanged:F.wasChanged(),id:F.getOriginalId()}}}catch($){throw F.catchSaveErrors($)}}else{let S=new h(O,O.dataProvider),v=Mi(S,O);if(await v._updateEntityBasedOnApi(y.fields),!O.isAllowedForInstance(S,P))throw new Xr;await v.__validateEntity();try{M={result:await s.apply(S,y.args),fields:await v.toApiJson()}}catch(I){throw v.catchSaveErrors(I)}}}),g.success(M)}catch(O){O.isForbiddenError?g.forbidden():g.error(O,void 0)}})}},doWork:async function(d,c,h,p){if(d=Xi(o(),d),D.allEntities.includes(e.constructor)){let y=ne(c);await y.__validateEntity();let _=l.classes.get(c.constructor);_.key||(_.key=y.repository.metadata.key+"_methods");try{let g=await new class extends Wt{constructor(){super(...arguments);f(this,"execute")}}(_.key+"/"+(n!=null&&n.apiPrefix?n.apiPrefix+"/":"")+i,(n==null?void 0:n.queue)??!1,n.allowed).run({args:d,rowInfo:{data:await y.toApiJson(),isNewRow:y.isNew(),wasChanged:y.wasChanged(),id:y.getOriginalId()}},h,p);return await y._updateEntityBasedOnApi(g.rowInfo.data,!0),g.result}catch(g){throw y.catchSaveErrors(g)}}else{let y=Mi(c,void 0);try{await y.__validateEntity();let _=await new class extends Wt{constructor(){super(...arguments);f(this,"execute")}}(l.classes.get(c.constructor).key+"/"+(n!=null&&n.apiPrefix?n.apiPrefix+"/":"")+i,(n==null?void 0:n.queue)??!1,n.allowed).run({args:d,fields:await y.toApiJson()},h,p);return await y._updateEntityBasedOnApi(_.fields),_.result}catch(_){throw y.catchSaveErrors(_)}}}};return a=async function(...d){let c=this;return Vt()?await s.apply(c,d):u.doWork(d,c)},zi(e.constructor,a),a[Kr]=u,r?(r.value=a,r):a}}const fo={_isUndefined:!0};function zi(n,e){(n[Yi]||(n[Yi]=[])).push(e),D.actionInfo.allActions.push(e)}function $n(n){return n&&n._isUndefined}class Ki{constructor(e){f(this,"res");this.res=e}progress(e){this.res.progress(e)}}function Xi(n,e){if(n)for(let t=0;t<n.length;t++){const r=n[t];for(const i of[Ne,Ct])(e[t]instanceof i||r==i)&&(e[t]=void 0);if(e[t]!=null){let i={valueType:r};if(i=ni(i,new Ne),Se(r,!1)!=null){let a=ne(e[t]);e[t]=a.getId()}i.valueConverter&&(e[t]=i.valueConverter.toJson(e[t]))}}return e.map(t=>t!==void 0?t:fo)}async function Ln(n,e,t,r,i){for(let s=0;s<e.length;s++){const a=e[s];$n(a)&&(e[s]=void 0)}if(n)for(let s=0;s<n.length;s++)if(e.length<s&&e.push(void 0),n[s]==Ne||n[s]==Ne)e[s]=t;else if(n[s]==Ct&&r)e[s]=r;else if(n[s]==Ki)e[s]=new Ki(i);else{let a={valueType:n[s]};a=ni(a,t),a.valueConverter&&(e[s]=a.valueConverter.fromJson(e[s])),Se(n[s],!1)!=null&&(e[s]===null||e[s]===void 0||(e[s]=await t.repo(n[s]).findId(e[s])))}return e}const Yi=Symbol.for("classBackendMethodsArray");async function qn(n,e,t){if(e.transactional===void 0||e.transactional===!0)return await Pa(n,t);await t(n.dataProvider)}function xn(n,e){return _e.repo(n,e)}class co{constructor(e,t){f(this,"id");f(this,"caption");f(this,"icon");f(this,"where");f(this,"class");f(this,"hide");this.id=e.toString(),this.caption=(t==null?void 0:t.caption)??this.id,this.icon=t==null?void 0:t.icon,this.where=t==null?void 0:t.where,this.class=t==null?void 0:t.class,this.hide=t==null?void 0:t.hide,t!=null&&t.icon&&t.icon.caption===void 0&&(t.icon.caption=t==null?void 0:t.caption)}}var ho=Object.defineProperty,po=Object.getOwnPropertyDescriptor,Xe=(n,e,t,r)=>{for(var i=r>1?void 0:r?po(e,t):e,s=n.length-1,a;s>=0;s--)(a=n[s])&&(i=(r?a(e,t,i):a(i))||i);return r&&i&&ho(e,t,i),i};let De=class{constructor(){f(this,"id","");f(this,"entity","");f(this,"entityId","");f(this,"changeDate",new Date);f(this,"userId","");f(this,"changes",[]);f(this,"newRow",!1);f(this,"deleted",!1)}};Xe([Y.cuid()],De.prototype,"id",2);Xe([Y.string()],De.prototype,"entity",2);Xe([Y.string()],De.prototype,"entityId",2);Xe([Y.date()],De.prototype,"changeDate",2);Xe([Y.string()],De.prototype,"userId",2);Xe([Y.json({dbName:"changesJson"})],De.prototype,"changes",2);Xe([Y.boolean()],De.prototype,"newRow",2);Xe([Y.boolean()],De.prototype,"deleted",2);De=Xe([Dn("_ff_change_logs",{caption:"FF Change Logs",allowApiCrud:!1,defaultOrderBy:{changeDate:"desc"}})],De);async function yo(n,e,t){var r;if(Vt()){const i=[],s=new Bn(n,t),a=(t==null?void 0:t.forceNew)||e.isNew,o=(t==null?void 0:t.forceDate)||new Date;for(const l of s.fields.filter(u=>u.valueChanged()||a&&u.value))try{const u=s.excludedValues.includes(l);i.push({key:l.metadata.key,newValue:u?"***":l.value instanceof yr?l.value.id:l.metadata.options.valueConverter.toJson(l.value),oldValue:e.isNew?"---":u?"***":l.originalValue instanceof yr?l.originalValue.id:l.metadata.options.valueConverter.toJson(l.originalValue)})}catch(u){throw console.error(l),u}i.length>0&&await xn(De).insert({changeDate:o,changes:i,entity:e.metadata.key,entityId:e.metadata.idMetadata.getId(n),userId:((r=_e.user)==null?void 0:r.id)||"",newRow:a})}}async function mo(n,e,t){var a;const r=[],i=new Bn(n,t),s=(t==null?void 0:t.forceDate)||new Date;for(const o of i.fields)try{const l=i.excludedValues.includes(o);r.push({key:o.metadata.key,newValue:l?"***":"---",oldValue:l?"***":o.originalValue instanceof yr?o.originalValue.id:o.metadata.options.valueConverter.toJson(o.originalValue)})}catch(l){throw console.error(o),l}await xn(De).insert({changeDate:s,changes:r,entity:e.metadata.key,entityId:e.metadata.idMetadata.getId(n),userId:((a=_e.user)==null?void 0:a.id)||"",deleted:!0})}class Bn{constructor(e,t){f(this,"fields");f(this,"excludedFields");f(this,"excludedValues");const r=ne(e);t!=null&&t.excludeColumns?this.excludedFields=t.excludeColumns(r.fields):this.excludedFields=[],t!=null&&t.excludeValues?this.excludedValues=t.excludeValues(r.fields):this.excludedValues=[],this.excludedFields.push(...r.fields.toArray().filter(i=>i.metadata.options.serverExpression)),this.excludedFields.push(...r.fields.toArray().filter(i=>i.metadata.options.sqlExpression)),this.fields=r.fields.toArray().filter(i=>!this.excludedFields.includes(i))}}const Lt=n=>{if(n)return Array.isArray(n)?n.map(e=>e.id):n.id};function ai(n,e){return Dn(n,{...e,allowApiCrud:e.allowApiCrud??Lt(e.permissionApiCrud),allowApiDelete:e.allowApiDelete??Lt(e.permissionApiDelete),allowApiInsert:e.allowApiInsert??Lt(e.permissionApiInsert),allowApiRead:e.allowApiRead??Lt(e.permissionApiRead),allowApiUpdate:e.allowApiUpdate??Lt(e.permissionApiUpdate),saved:async(t,r)=>{var i;await((i=e==null?void 0:e.saved)==null?void 0:i.call(e,t,r)),e.changeLog===!1||Vt()&&await yo(t,r,e.changeLog)},deleted:async(t,r)=>{var i;await((i=e==null?void 0:e.deleted)==null?void 0:i.call(e,t,r)),e.changeLog===!1||Vt()&&await mo(t,r,e.changeLog)}})}var jn=Object.defineProperty,go=Object.getOwnPropertyDescriptor,wo=(n,e,t)=>e in n?jn(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,se=(n,e,t,r)=>{for(var i=r>1?void 0:r?go(e,t):e,s=n.length-1,a;s>=0;s--)(a=n[s])&&(i=(r?a(e,t,i):a(i))||i);return r&&i&&jn(e,t,i),i},Ir=(n,e,t)=>wo(n,typeof e!="symbol"?e+"":e,t);const Pt={FF_Role_Auth_Admin:"FF_Role_Auth.Admin",FF_Role_Auth_Invite:"FF_Role_Auth.Invite"};let $e=class{constructor(){f(this,"id");f(this,"createdAt");f(this,"updatedAt");f(this,"identifier");f(this,"roles",[]);f(this,"accounts");f(this,"sessions")}};se([Y.cuid()],$e.prototype,"id",2);se([Y.createdAt({includeInApi:[Pt.FF_Role_Auth_Admin,Qt.FF_Role_Admin]})],$e.prototype,"createdAt",2);se([Y.updatedAt({includeInApi:[Pt.FF_Role_Auth_Admin,Qt.FF_Role_Admin]})],$e.prototype,"updatedAt",2);se([Y.string({allowApiUpdate:!1,validate:[Re.unique(),Re.required(),n=>{var e;if(((e=n.identifier)==null?void 0:e.length)<2)throw"Must be at least 2 characters long"}]})],$e.prototype,"identifier",2);se([Y.json(()=>[],{inputType:"selectEnum",valueConverter:{toDb:n=>n?n.join(","):[],fromDb:n=>n?n.split(",").map(e=>e.replace("{","").replace("}","")).filter(e=>e!==""):[]}})],$e.prototype,"roles",2);se([_r.toMany(()=>Ie,"userId")],$e.prototype,"accounts",2);se([_r.toMany(()=>ht,"userId")],$e.prototype,"sessions",2);$e=se([ai("ff_auth.users",{allowApiCrud:[Pt.FF_Role_Auth_Admin,Qt.FF_Role_Admin],caption:"FF Auth - Users"})],$e);let Ie=class{constructor(){f(this,"id");f(this,"createdAt");f(this,"updatedAt");f(this,"userId");f(this,"user");f(this,"provider",Le.PASSWORD.id);f(this,"providerUserId","");f(this,"hashPassword");f(this,"token");f(this,"expiresAt");f(this,"lastVerifiedAt");f(this,"metadata")}};se([Y.cuid()],Ie.prototype,"id",2);se([Y.createdAt()],Ie.prototype,"createdAt",2);se([Y.updatedAt()],Ie.prototype,"updatedAt",2);se([Y.string()],Ie.prototype,"userId",2);se([_r.toOne(()=>$e,"userId")],Ie.prototype,"user",2);se([Y.string()],Ie.prototype,"provider",2);se([Y.string()],Ie.prototype,"providerUserId",2);se([Y.string({includeInApi:!1,allowNull:!0})],Ie.prototype,"hashPassword",2);se([Y.string({includeInApi:!1,allowNull:!0})],Ie.prototype,"token",2);se([Y.date({includeInApi:!1,allowNull:!0})],Ie.prototype,"expiresAt",2);se([Y.date({includeInApi:!1,allowNull:!0})],Ie.prototype,"lastVerifiedAt",2);se([Y.json({includeInApi:!1,allowNull:!0})],Ie.prototype,"metadata",2);Ie=se([ai("ff_auth.accounts",{allowApiCrud:[Pt.FF_Role_Auth_Admin,Qt.FF_Role_Admin],caption:"FF Auth - Accounts",changeLog:{excludeColumns:n=>[n.hashPassword,n.token]}})],Ie);let ht=class{constructor(){f(this,"id");f(this,"expiresAt");f(this,"userId");f(this,"user")}};se([Y.string()],ht.prototype,"id",2);se([Y.date()],ht.prototype,"expiresAt",2);se([Y.string()],ht.prototype,"userId",2);se([_r.toOne(()=>$e,"userId")],ht.prototype,"user",2);ht=se([ai("ff_auth.users_sessions",{allowApiCrud:[Pt.FF_Role_Auth_Admin,Qt.FF_Role_Admin],caption:"FF Auth - Users sessions",changeLog:!1})],ht);let Le=class extends co{constructor(n,e){super(n,{...e})}};Ir(Le,"DEMO",new Le("DEMO",{caption:"Demo"}));Ir(Le,"PASSWORD",new Le("PASSWORD",{caption:"Password"}));Ir(Le,"OTP",new Le("OTP",{caption:"TOTP"}));Ir(Le,"OAUTH",new Le("OAUTH",{caption:"OAUTH"}));Le=se([Wa()],Le);var vo=Object.defineProperty,bo=Object.getOwnPropertyDescriptor,Ue=(n,e,t,r)=>{for(var i=bo(e,t),s=n.length-1,a;s>=0;s--)(a=n[s])&&(i=a(e,t,i)||i);return i&&vo(e,t,i),i},we,Oe;const qe=(we=class{static _setAbstraction(e){pi(this,Oe,e)}static async signOut(){return await Me(we,Oe).signOut()}static async signInDemo(e){return await Me(we,Oe).signInDemo(e)}static async invite(e){return await Me(we,Oe).invite(e)}static async signUpPassword(e,t){return await Me(we,Oe).signUpPassword(e,t)}static async signInPassword(e,t){return await Me(we,Oe).signInPassword(e,t)}static async forgotPassword(e){return await Me(we,Oe).forgotPassword(e)}static async resetPassword(e,t){return await Me(we,Oe).resetPassword(e,t)}static async signInOTP(e){return await Me(we,Oe).signInOTP(e)}static async verifyOtp(e,t){return await Me(we,Oe).verifyOtp(e,t)}static async signInOAuthGetUrl(e){return await Me(we,Oe).signInOAuthGetUrl(e)}},Oe=new WeakMap,hi(we,Oe),we);Ue([Je({allowed:!0})],qe,"signOut");Ue([Je({allowed:!0})],qe,"signInDemo");Ue([Je({allowed:Pt.FF_Role_Auth_Invite})],qe,"invite");Ue([Je({allowed:!0})],qe,"signUpPassword");Ue([Je({allowed:!0})],qe,"signInPassword");Ue([Je({allowed:!0})],qe,"forgotPassword");Ue([Je({allowed:!0})],qe,"resetPassword");Ue([Je({allowed:!0})],qe,"signInOTP");Ue([Je({allowed:!0})],qe,"verifyOtp");Ue([Je({allowed:!0})],qe,"signInOAuthGetUrl");let zt=qe;function Ke(n){n.focus()}at();At[ee]="src/lib/modules/auth/components/ForgotPassword.svelte";var _o=ue(fe('<div class="login"><p> </p> <form class="svelte-skcj83"><input required type="email"> <button> </button></form></div>'),At[ee],[[30,0,[[31,1],[32,1,[[33,2],[40,2]]]]]]);function At(n,e){rt(new.target),it(e,!1,At);let t=Ee(e,"firstlyDataAuth",8),r=Ee(e,"email",12,""),i=be(""),s=be(""),a=be(!1);async function o(){Z(i,""),Z(s,""),Z(a,!0);try{const g=await zt.forgotPassword(r());Z(s,g.message??"")}catch(g){g&&Z(i,g.message??""),Z(a,!1)}}Tt();var l=_o(),u=Q(l);let d;var c=Q(u),h=G(u,2),p=Q(h);vr(p,g=>Ke==null?void 0:Ke(g)),Ht(()=>ct(p,r));var y=G(p,2),_=Q(y);return Ce((g,P)=>{var O,M;d=Ft(u,1,"message",null,d,g),le(c,`${U(i)??""}${U(s)??""}`),je(p,"placeholder",(O=t().ui)==null?void 0:O.strings.email_placeholder),y.disabled=P,le(_,(M=t().ui)==null?void 0:M.strings.send_password_reset_instructions)},[()=>({error:U(i),success:U(s)}),()=>!r()||!r().includes("@")||!r().includes(".")||U(a)],wr),Gt("submit",h,br(o)),X(n,l),nt({...st()})}ot(At);at();tt[ee]="src/lib/modules/auth/components/OAuth.svelte";var Io=(n,e,t)=>e(U(t).name),ko=ue(fe('<div class="oauth-button-icon svelte-1dwkktf"><!></div>'),tt[ee],[[26,5]]),Oo=ue(fe('<button class="oauth-button svelte-1dwkktf"><!> <span> </span></button>'),tt[ee],[[24,3,[[30,4]]]]),Co=ue(fe('<hr style="margin: 1rem"> <div class="oauth-container svelte-1dwkktf"></div>',1),tt[ee],[[21,1],[22,1]]);function tt(n,e){rt(new.target),it(e,!0,tt);const t=async a=>{const o=await zt.signInOAuthGetUrl({provider:a,redirect:new URL(window.location.href).searchParams.get("redirect")??"/"});window.location.href=o};var r=Jt(),i=Pe(r);{var s=a=>{var o=Co(),l=G(Pe(o),2);qs(()=>{var u;return((u=e.firstlyDataAuth)==null?void 0:u.providers)??[]},u=>u.name),Es(l,21,()=>{var u;return((u=e.firstlyDataAuth)==null?void 0:u.providers)??[]},u=>u.name,(u,d)=>{var c=Oo();c.__click=[Io,t,d];var h=Q(c);{var p=g=>{var P=ko(),O=Q(P);Ts(O,()=>U(d).raw_svg),X(g,P)};me(h,g=>{U(d).raw_svg&&g(p)})}var y=G(h,2),_=Q(y);Ce(()=>le(_,U(d).label)),X(u,c)}),X(a,o)};me(i,a=>{var o;(((o=e.firstlyDataAuth)==null?void 0:o.providers)??Te([].length,0,!1))&&a(s)})}return X(n,r),nt({...st()})}ot(tt);en(["click"]);at();Kt[ee]="src/lib/modules/auth/components/ResetPassword.svelte";var Ao=ue(fe('<div class="login"><p> </p> <form class="svelte-skcj83"> <input type="password" required> <input type="password" required> <button> </button></form></div>'),Kt[ee],[[32,0,[[33,1],[34,1,[[36,2],[43,2],[49,2]]]]]]);function Kt(n,e){rt(new.target),it(e,!1,Kt);let t=Ee(e,"firstlyDataAuth",8),r=Ee(e,"password1",12,""),i=Ee(e,"password2",12,""),s=be(""),a=be(""),o=be(!1);async function l(){Z(s,""),Z(a,""),Z(o,!0);const S=new URL(location.href).searchParams.get("token");try{const v=await zt.resetPassword(S??"",r());Z(a,v.message??""),window.location.href="/"}catch(v){v&&Z(s,v.message??""),Z(o,!1)}}Tt();var u=Ao(),d=Q(u);let c;var h=Q(d),p=G(d,2),y=Q(p),_=G(y),g=G(_),P=G(g),O=G(P,2),M=Q(O);return Ce(S=>{var v,I,F,$,C;c=Ft(d,1,"message",null,c,S),le(h,`${U(s)??""}${U(a)??""}`),le(y,`${((v=t().ui)==null?void 0:v.strings.password)??""} `),je(_,"placeholder",(I=t().ui)==null?void 0:I.strings.password_placeholder),le(g,` ${((F=t().ui)==null?void 0:F.strings.confirm)??""} `),je(P,"placeholder",($=t().ui)==null?void 0:$.strings.password_placeholder),O.disabled=!r()||!i()||U(o),le(M,(C=t().ui)==null?void 0:C.strings.reset)},[()=>({error:U(s)})],wr),ct(_,r),ct(P,i),Gt("submit",p,br(l)),X(n,u),nt({...st()})}ot(Kt);at();Et[ee]="src/lib/modules/auth/components/SignIn.svelte";var Eo=ue(fe('<form class="svelte-skcj83"><p> </p> <label> <input required type="email"></label> <label> <input required type="password"></label> <button> </button></form>'),Et[ee],[[37,1,[[38,2],[39,2,[[41,3]]],[49,2,[[51,3]]],[58,2]]]]);function Et(n,e){rt(new.target),it(e,!1,Et);let t=Ee(e,"firstlyDataAuth",8),r=Ee(e,"view",8,"login"),i=Ee(e,"email",12,""),s=be(""),a=be(""),o=be(),l=be(!1);async function u(){Z(s,""),Z(a,""),Z(l,!0);try{await zt.signInPassword(i(),U(o)),window.location.href=new URL(window.location.href).searchParams.get("redirect")??"/"}catch(p){p&&Z(s,p.message??""),Z(l,!1)}}Tt();var d=Jt(),c=Pe(d);{var h=p=>{var y=Eo(),_=Q(y);let g;var P=Q(_),O=G(_,2),M=Q(O),S=G(M);Ht(()=>ct(S,i)),vr(S,k=>Ke==null?void 0:Ke(k));var v=G(O,2),I=Q(v),F=G(I),$=G(v,2),C=Q($);Ce(k=>{var E,w,T,N,L;g=Ft(_,1,"message",null,g,k),le(P,`${U(s)??""}${U(a)??""}`),le(M,`${((E=t().ui)==null?void 0:E.strings.email)??""} `),je(S,"placeholder",(w=t().ui)==null?void 0:w.strings.email_placeholder),le(I,`${((T=t().ui)==null?void 0:T.strings.password)??""} `),je(F,"placeholder",(N=t().ui)==null?void 0:N.strings.password_placeholder),$.disabled=!i()||!U(o)||U(l),le(C,(L=t().ui)==null?void 0:L.strings.btn_sign_in)},[()=>({error:U(s)})],wr),ct(F,()=>U(o),k=>Z(o,k)),Gt("submit",y,br(u)),X(p,y)};me(c,p=>{on(r(),"login")&&p(h)})}return X(n,d),nt({...st()})}ot(Et);at();St[ee]="src/lib/modules/auth/components/SignUp.svelte";var So=ue(fe('<form class="svelte-skcj83"><p> </p> <label> <input required type="email"></label> <label> <input required type="password"></label> <button> </button></form>'),St[ee],[[39,1,[[40,2],[41,2,[[43,3]]],[51,2,[[53,3]]],[60,2]]]]);function St(n,e){rt(new.target),it(e,!1,St);let t=Ee(e,"firstlyDataAuth",8),r=Ee(e,"view",8,"login"),i=Ee(e,"email",12,""),s=be(""),a=be(""),o=be(),l=be(!1);async function u(){Z(s,""),Z(a,""),Z(l,!0);try{const p=await zt.signUpPassword(i(),U(o));Z(a,p.message??""),await new Promise(y=>setTimeout(y,5e3)),window.location.href=new URL(window.location.href).searchParams.get("redirect")??"/"}catch(p){p&&Z(s,p.message??""),Z(l,!1)}}Tt();var d=Jt(),c=Pe(d);{var h=p=>{var y=So(),_=Q(y);let g;var P=Q(_),O=G(_,2),M=Q(O),S=G(M);Ht(()=>ct(S,i)),vr(S,k=>Ke==null?void 0:Ke(k));var v=G(O,2),I=Q(v),F=G(I),$=G(v,2),C=Q($);Ce(k=>{var E,w,T,N,L;g=Ft(_,1,"message",null,g,k),le(P,`${U(s)??""}${U(a)??""}`),le(M,`${((E=t().ui)==null?void 0:E.strings.email)??""} `),je(S,"placeholder",(w=t().ui)==null?void 0:w.strings.email_placeholder),le(I,`${((T=t().ui)==null?void 0:T.strings.password)??""} `),je(F,"placeholder",(N=t().ui)==null?void 0:N.strings.password_placeholder),$.disabled=!i()||!U(o)||U(l),le(C,(L=t().ui)==null?void 0:L.strings.btn_sign_up)},[()=>({error:U(s)})],wr),ct(F,()=>U(o),k=>Z(o,k)),Gt("submit",y,br(u)),X(p,y)};me(c,p=>{on(r(),"login")&&p(h)})}return X(n,d),nt({...st()})}ot(St);at();re[ee]="src/lib/modules/auth/Page.svelte";var To=ue(fe('<h1 class="svelte-1jjivcr"> </h1>'),re[ee],[[28,3]]),Fo=ue(fe('<!> <div class="form-footer svelte-1jjivcr"><!></div> <!>',1),re[ee],[[35,4]]),Po=ue(fe("<hr> <!>",1),re[ee],[[58,6]]),Ro=ue(fe('<!> <div class="form-footer svelte-1jjivcr"><!> <!></div> <!>',1),re[ee],[[51,4]]),Do=ue(fe('<!> <div class="form-footer svelte-1jjivcr"><!></div>',1),re[ee],[[73,4]]),Mo=ue(fe('<!> <div class="form-footer svelte-1jjivcr"><!></div>',1),re[ee],[[87,4]]),No=ue(fe('<div class="form svelte-1jjivcr"><!> <!> <!> <!> <!></div>'),re[ee],[[26,1]]),$o=ue(fe('<img alt="Authentication" class="svelte-1jjivcr">'),re[ee],[[117,6]]),Lo=ue(fe('<div class="split-layout svelte-1jjivcr"><div class="form-side svelte-1jjivcr"><!></div> <div class="image-side svelte-1jjivcr"><!></div></div>'),re[ee],[[110,3,[[111,4],[115,4]]]]),qo=ue(fe('<div class="centered-layout svelte-1jjivcr"><!></div>'),re[ee],[[122,3]]),xo=ue(fe('<div class="fallback svelte-1jjivcr"><small>- 404 -</small></div> <div class="fallback svelte-1jjivcr"><small>Nothing to see here</small></div>',1),re[ee],[[128,3,[[129,4]]],[131,3,[[132,4]]]]),Bo=ue(fe("<!> <!>",1),re[ee],[]),jo=ue(fe("<div><!></div>"),re[ee],[[107,0]]);function re(n,e){rt(new.target),it(e,!0,re);const t=Fe(re,u=>{var d=No(),c=Q(d);{var h=v=>{var I=To(),F=Q(I,!0);xe(I),Ce(()=>le(F,r.ui.strings.app_name)),X(v,I)};me(c,v=>{var I;(I=r.ui)!=null&&I.strings.app_name&&v(h)})}var p=G(c,2);{var y=v=>{const I=Rt(()=>{var F;return(F=r.ui)==null?void 0:F.paths.sign_up});Ge(v,{get path(){return U(I)},children:Fe(re,(F,$)=>{var C=Fo(),k=Pe(C);Ar(()=>U(i),St),St(k,{firstlyDataAuth:r,get email(){return U(i)},set email(L){Z(i,L,!0)}});var E=G(k,2),w=Q(E);{var T=L=>{Qe(L,{get href(){return r.ui.paths.sign_in},children:Fe(re,(te,W)=>{yt();var de=Dt();Ce(()=>le(de,r.ui.strings.back_to_sign_in)),X(te,de)}),$$slots:{default:!0}})};me(w,L=>{r.ui.paths.sign_in&&L(T)})}xe(E);var N=G(E,2);tt(N,{firstlyDataAuth:r}),X(F,C)}),$$slots:{default:!0}})};me(p,v=>{var I;(I=r.ui)!=null&&I.paths.sign_up&&v(y)})}var _=G(p,2);{var g=v=>{const I=Rt(()=>{var F;return(F=r.ui)==null?void 0:F.paths.sign_in});Ge(v,{get path(){return U(I)},children:Fe(re,(F,$)=>{var C=Ro(),k=Pe(C);Ar(()=>U(i),Et),Et(k,{firstlyDataAuth:r,get email(){return U(i)},set email(W){Z(i,W,!0)}});var E=G(k,2),w=Q(E);{var T=W=>{Qe(W,{get href(){return r.ui.paths.forgot_password},children:Fe(re,(de,Ye)=>{yt();var Ve=Dt();Ce(()=>le(Ve,r.ui.strings.forgot_password)),X(de,Ve)}),$$slots:{default:!0}})};me(w,W=>{var de;(de=r.ui)!=null&&de.paths.forgot_password&&W(T)})}var N=G(w,2);{var L=W=>{var de=Po(),Ye=G(Pe(de),2);Qe(Ye,{get href(){return r.ui.paths.sign_up},children:Fe(re,(Ve,kr)=>{yt();var oe=Dt();Ce(()=>le(oe,r.ui.strings.btn_sign_up)),X(Ve,oe)}),$$slots:{default:!0}}),X(W,de)};me(N,W=>{var de;(de=r.ui)!=null&&de.paths.sign_up&&W(L)})}xe(E);var te=G(E,2);tt(te,{firstlyDataAuth:r}),X(F,C)}),$$slots:{default:!0}})};me(_,v=>{var I;(I=r.ui)!=null&&I.paths.sign_in&&v(g)})}var P=G(_,2);{var O=v=>{const I=Rt(()=>{var F;return(F=r.ui)==null?void 0:F.paths.forgot_password});Ge(v,{get path(){return U(I)},children:Fe(re,(F,$)=>{var C=Do(),k=Pe(C);Ar(()=>U(i),At),At(k,{firstlyDataAuth:r,get email(){return U(i)},set email(N){Z(i,N,!0)}});var E=G(k,2),w=Q(E);{var T=N=>{Qe(N,{get href(){return r.ui.paths.sign_in},children:Fe(re,(L,te)=>{yt();var W=Dt();Ce(()=>le(W,r.ui.strings.back_to_sign_in)),X(L,W)}),$$slots:{default:!0}})};me(w,N=>{var L;(L=r.ui)!=null&&L.paths.sign_in&&N(T)})}xe(E),X(F,C)}),$$slots:{default:!0}})};me(P,v=>{var I;(I=r.ui)!=null&&I.paths.forgot_password&&v(O)})}var M=G(P,2);{var S=v=>{const I=Rt(()=>{var F;return(F=r.ui)==null?void 0:F.paths.reset_password});Ge(v,{get path(){return U(I)},children:Fe(re,(F,$)=>{var C=Mo(),k=Pe(C);Kt(k,{firstlyDataAuth:r});var E=G(k,2),w=Q(E);{var T=N=>{Qe(N,{get href(){return r.ui.paths.sign_in},children:Fe(re,(L,te)=>{yt();var W=Dt();Ce(()=>le(W,r.ui.strings.back_to_sign_in)),X(L,W)}),$$slots:{default:!0}})};me(w,N=>{var L;(L=r.ui)!=null&&L.paths.sign_in&&N(T)})}xe(E),X(F,C)}),$$slots:{default:!0}})};me(M,v=>{var I;(I=r.ui)!=null&&I.paths.reset_password&&v(S)})}xe(d),X(u,d)});let r=e.firstlyData.props,i=Ss(""),s=Rt(()=>{var u,d;return!!((d=(u=r.ui)==null?void 0:u.images)!=null&&d.main)});var a=jo();let o;var l=Q(a);return Ge(l,{children:Fe(re,(u,d)=>{var c=Bo(),h=Pe(c);{var p=g=>{var P=Lo(),O=Q(P),M=Q(O);t(M),xe(O);var S=G(O,2),v=Q(S);{var I=F=>{var $=$o();Ce(()=>je($,"src",r.ui.images.main)),X(F,$)};me(v,F=>{var $,C;(C=($=r.ui)==null?void 0:$.images)!=null&&C.main&&F(I)})}xe(S),xe(P),X(g,P)},y=g=>{var P=qo(),O=Q(P);t(O),xe(P),X(g,P)};me(h,g=>{U(s)?g(p):g(y,!1)})}var _=G(h,2);Ge(_,{fallback:!0,children:Fe(re,(g,P)=>{var O=xo();yt(2),X(g,O)}),$$slots:{default:!0}}),X(u,c)}),$$slots:{default:!0}}),Ce(u=>o=Ft(a,1,"wrapper svelte-1jjivcr",null,o,u),[()=>({"with-image":U(s)})]),X(n,a),nt({...st()})}ot(re);export{re as default};