modelence 0.21.0 → 0.22.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4L4E6PFO.js +3 -0
- package/dist/chunk-4L4E6PFO.js.map +1 -0
- package/dist/chunk-AMJHJA2V.js +2 -0
- package/dist/chunk-AMJHJA2V.js.map +1 -0
- package/dist/chunk-BCUSVRAY.js +2 -0
- package/dist/chunk-BCUSVRAY.js.map +1 -0
- package/dist/chunk-OFRRQZVE.js +37 -0
- package/dist/chunk-OFRRQZVE.js.map +1 -0
- package/dist/chunk-OJ3LMWVQ.js +2 -0
- package/dist/{chunk-TBGXZXAA.js.map → chunk-OJ3LMWVQ.js.map} +1 -1
- package/dist/{chunk-SNADMLAT.js → chunk-PJRYLKYW.js} +2 -2
- package/dist/{chunk-SNADMLAT.js.map → chunk-PJRYLKYW.js.map} +1 -1
- package/dist/chunk-VF4RU7MF.js +3 -0
- package/dist/chunk-VF4RU7MF.js.map +1 -0
- package/dist/chunk-YOJ4ZP5D.js +4 -0
- package/dist/chunk-YOJ4ZP5D.js.map +1 -0
- package/dist/client.d.ts +89 -4
- package/dist/client.js +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{package-BVTS5E5V.js → package-RFIDFU5I.js} +2 -2
- package/dist/{package-BVTS5E5V.js.map → package-RFIDFU5I.js.map} +1 -1
- package/dist/render-CBIFY4DG.js +2 -0
- package/dist/render-CBIFY4DG.js.map +1 -0
- package/dist/renderApp-J347DR2B.js +2 -0
- package/dist/{renderApp-QYMNQ3KS.js.map → renderApp-J347DR2B.js.map} +1 -1
- package/dist/server-LA5VRAGR.js +2 -0
- package/dist/{server-KAHRRRDU.js.map → server-LA5VRAGR.js.map} +1 -1
- package/dist/server.d.ts +53 -8
- package/dist/server.js +1 -1
- package/dist/telemetry.d.ts +6 -1
- package/dist/telemetry.js +1 -1
- package/dist/transport-C7DEK6NV.js +2 -0
- package/dist/{transport-W6JIYZKZ.js.map → transport-C7DEK6NV.js.map} +1 -1
- package/dist/{types-B_R3eHmq.d.ts → types-B8uEAj0y.d.ts} +1 -1
- package/dist/{types-_BTBqn8b.d.ts → types-D_70a365.d.ts} +47 -2
- package/dist/types.d.ts +2 -2
- package/package.json +4 -6
- package/dist/chunk-3SGMDISS.js +0 -29
- package/dist/chunk-3SGMDISS.js.map +0 -1
- package/dist/chunk-7LPSX5A6.js +0 -3
- package/dist/chunk-7LPSX5A6.js.map +0 -1
- package/dist/chunk-KZZYA5HP.js +0 -3
- package/dist/chunk-KZZYA5HP.js.map +0 -1
- package/dist/chunk-SD3ERG2G.js +0 -3
- package/dist/chunk-SD3ERG2G.js.map +0 -1
- package/dist/chunk-TBGXZXAA.js +0 -2
- package/dist/chunk-YLLX26A4.js +0 -2
- package/dist/chunk-YLLX26A4.js.map +0 -1
- package/dist/chunk-YRR32LTF.js +0 -2
- package/dist/chunk-YRR32LTF.js.map +0 -1
- package/dist/render-STDR67WK.js +0 -2
- package/dist/render-STDR67WK.js.map +0 -1
- package/dist/renderApp-QYMNQ3KS.js +0 -2
- package/dist/server-KAHRRRDU.js +0 -2
- package/dist/transport-W6JIYZKZ.js +0 -2
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var s="module",i="modelence",r="0.22.0",c="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",o="dist/global.d.ts",p={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],a={modelence:"./dist/bin/modelence.js"},l={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",bench:"tsx src/bench/index.ts",test:"vitest run","test:watch":"vitest","test:coverage":"vitest run --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",v={"@tanstack/react-query":"^5.100.7","@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0","@vitest/coverage-v8":"^2.1.8",eslint:"^9.37.0",husky:"^9.1.7","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-node":"^10.9.2","vite-tsconfig-paths":"^5.1.4",vitest:"^2.1.8"},j={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},x={"@tanstack/react-query":">=5.0.0",react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:c,main:n,types:o,exports:p,files:d,bin:a,scripts:l,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:u,license:y,bugs:g,homepage:h,devDependencies:v,dependencies:j,peerDependencies:x};
|
|
2
|
+
export{s as a,i as b,r as c,c as d,n as e,o as f,p as g,d as h,a as i,l as j,m as k,u as l,y as m,g as n,h as o,v as p,j as q,x as r,b as s};//# sourceMappingURL=chunk-4L4E6PFO.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-4L4E6PFO.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,SACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,YAAA,CAAc,2BAAA,CACd,cAAA,CAAkB,gBAClB,KAAA,CAAS,wBAAA,CACT,IAAA,CAAQ,YAAA,CACR,YAAA,CAAc,QAAA,CACd,eAAA,CAAiB,uBAAA,CACjB,WAAA,CAAe,6BAAA,CACf,OAAA,CAAW,8CACb,CAAA,CAIAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,CAAAA,CAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA,CAAO,+CACT,CAAA,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AAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAeA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CAyBA,gBAAA,CAAAC,CAKF","file":"chunk-4L4E6PFO.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.22.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"bench\": \"tsx src/bench/index.ts\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@tanstack/react-query\": \"^5.100.7\",\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"@vitest/coverage-v8\": \"^2.1.8\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-node\": \"^10.9.2\",\n \"vite-tsconfig-paths\": \"^5.1.4\",\n \"vitest\": \"^2.1.8\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"@tanstack/react-query\": \">=5.0.0\",\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {c as c$1}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {create}from'zustand';import {z}from'zod';var b="modelence.session";function R(){return typeof globalThis<"u"&&typeof globalThis.localStorage<"u"}function p(){if(!R())return null;let e=globalThis.localStorage.getItem(b);try{return e?JSON.parse(e):null}catch(n){return console.error("Error parsing session from localStorage",n),null}}function h(e){R()&&globalThis.localStorage.setItem(b,JSON.stringify(e));}var _=null;function D(e){_=e;}function a(){return _}var P=(e,n)=>{console.error(`Error calling method '${n}':`,e);};function K(e){P=e;}function N(e,n){return P(e,n)}var S=class extends Error{constructor(n,t,r){super(n),this.name="MethodError",this.status=t,this.code=r;}},M=async(e,n)=>{let t=a()?.baseUrl??"";return W(`${t}/api/_internal/method/${e}`,n)},m="__modelence_call_method_transport__";function H(){return globalThis[m]??M}function B(e){let n=globalThis[m];return globalThis[m]=e,()=>{globalThis[m]=n;}}async function s(e,n,t){n=n??{},t=t??{};try{return await H()(e,n)}catch(r){throw (t.errorHandler??N)(r,e),r}}async function W(e,n){let t=await fetch(e,{method:"POST",credentials:a()?.credentials??"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:n,authToken:w(),clientInfo:A()})});if(!t.ok){let i=await t.text(),l=t.headers?.get("X-Modelence-Error-Code")??void 0;throw new S(i,t.status,l)}let r=await t.text(),o=r?JSON.parse(r):void 0;if(!o)throw new Error("Invalid response from server");return c$1(o.data,o.typeMap)}var E={},k=null;function Q(e){k=e;}function Z(e){return typeof window>"u"&&k?k(e):E[e]?.value}function y(e){E=e;}var c=create(e=>({user:null,setUser:n=>e({user:n})})),g=false,T=false,$=a$1.seconds(30),O=null,j=z.object({id:z.string(),handle:z.string(),roles:z.array(z.string()),firstName:z.string().optional(),lastName:z.string().optional(),avatarUrl:z.string().optional()});function d(e){if(!e)return null;let n=j.safeParse(e);if(!n.success)return console.error("Session Error: Invalid user payload",n.error),null;let t=n.data;return Object.freeze({...t,firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0,hasRole:r=>t.roles.includes(r),requireRole:r=>{if(!t.roles.includes(r))throw new Error(`Access denied - role '${r}' required`)}})}function le(e){if(g)return;g=true,y(e.configs);let t=p()?.authToken,r=e.session;if(t&&!e.user&&t!==r.authToken){T=true,c.getState().setUser(d(e.user));return}h(e.session),c.getState().setUser(d(e.user));}async function ue(){if(T){T=false;try{let{configs:e,session:n,user:t}=await s("_system.session.init");y(e),h(n),c.getState().setUser(d(t));}catch(e){console.error("Modelence: session reconciliation failed",e);}}}function ce(){return T}async function de(){if(g)return;g=true;let{configs:e,session:n,user:t}=await s("_system.session.init");y(e);let r=a();r?r.setAuthToken(n.authToken):h(n),c.getState().setUser(d(t)),await x();}async function fe(){typeof window>"u"||O!==null||await x();}async function x(){if(!(typeof window>"u")){try{await s("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}O=setTimeout(x,$);}}function f(e){let n=d(e);return c.getState().setUser(n),n}function ge(){return g}var C=null;function pe(e){C=e;}function he(e){return d(e)}function me(){return typeof window>"u"&&C?{user:C()}:{user:c(n=>n.user)}}async function Ce(e){let{email:n,password:t,handle:r,firstName:o,lastName:i,avatarUrl:l}=e;await s("_system.user.signupWithPassword",{email:n,password:t,...r!==void 0?{handle:r}:{},...o!==void 0?{firstName:o}:{},...i!==void 0?{lastName:i}:{},...l!==void 0?{avatarUrl:l}:{}});}async function xe(e){let{email:n,password:t}=e,{user:r,session:o}=await s("_system.user.loginWithPassword",{email:n,password:t}),i=a();return i&&i.setAuthToken(o.authToken),f(r)}async function Ue(e){let{firstName:n,lastName:t,avatarUrl:r,handle:o}=e,{user:i}=await s("_system.user.updateProfile",{...n!==void 0?{firstName:n}:{},...t!==void 0?{lastName:t}:{},...r!==void 0?{avatarUrl:r}:{},...o!==void 0?{handle:o}:{}});return f(i)}async function ve(e){let{token:n}=e;await s("_system.user.verifyEmail",{token:n});}async function be(e){let{email:n}=e;await s("_system.user.resendEmailVerification",{email:n});}async function Re(){await s("_system.user.logout");let e=a();e&&e.setAuthToken(null),f(null);}async function _e(e){let{email:n}=e;await s("_system.user.sendResetPasswordToken",{email:n});}async function Pe(e){let{email:n}=e;await s("_system.user.sendMagicLink",{email:n});}async function Ne(){let{user:e,session:n}=await s("_system.user.loginWithMagicLink"),t=a();return t&&t.setAuthToken(n.authToken),f(e)}async function Ae(e){let{email:n,code:t}=e,{user:r,session:o}=await s("_system.user.loginWithOneTimeCode",{email:n,code:t}),i=a();return i&&i.setAuthToken(o.authToken),f(r)}async function Ee(e){let{token:n,password:t}=e;await s("_system.user.resetPassword",{...n?{token:n}:{},password:t});}async function Oe(e){let{provider:n}=e,t=a(),r=t?.baseUrl??"";if(t?.openUrl){let o=w();if(!o)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let i=await fetch(`${r}/api/_internal/auth/issue-link-nonce`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o})});if(!i.ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");let{nonce:l}=await i.json(),I=`${r}/api/_internal/auth/${n}?mode=link&linkNonce=${encodeURIComponent(l)}`;t.openUrl(I);}else {let o=w();if(o&&!(await fetch(`${r}/api/_internal/auth/set-link-cookie`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({authToken:o}),credentials:"include"})).ok)throw new Error("Failed to initialize OAuth linking. Please ensure you are logged in.");window.location.href=`${r}/api/_internal/auth/${n}?mode=link`;}}async function Ie(e){let{provider:n}=e;await s("_system.user.unlinkOAuthProvider",{provider:n});}function w(){let e=a();return e?e.getAuthToken():p()?.authToken}function A(){let e=a();return e?e.getClientInfo():typeof window>"u"?{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null}:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}export{ue as A,ce as B,de as C,fe as D,ge as E,pe as F,he as G,me as H,p as a,D as b,a as c,Ce as d,xe as e,Ue as f,ve as g,be as h,Re as i,_e as j,Pe as k,Ne as l,Ae as m,Ee as n,Oe as o,Ie as p,w as q,A as r,K as s,S as t,M as u,B as v,s as w,Q as x,Z as y,le as z};//# sourceMappingURL=chunk-AMJHJA2V.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-AMJHJA2V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/clientConfig.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/auth/client/index.ts"],"names":["SESSION_KEY","hasLocalStorage","getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","config","configureClient","userConfig","getClientConfig","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","code","defaultCallMethodTransport","args","baseUrl","call","TRANSPORT_KEY","getTransport","setCallMethodTransport","next","previous","callMethod","options","endpoint","response","getAuthToken","getClientInfo","text","result","reviveResponseTypes","ssrConfigResolver","_setSsrConfigResolver","resolver","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","pendingReconciliation","SESSION_HEARTBEAT_INTERVAL","time","heartbeatTimer","userSchema","z","parseUser","parsedData","role","hydrateSession","payload","existingToken","ssrSession","reconcileSession","_isReconciliationPending","initSession","loopSessionHeartbeat","startSessionHeartbeat","setCurrentUser","enrichedUser","isSessionInitialized","ssrSessionResolver","_setSsrSessionResolver","_parseSessionUser","useSession","state","signupWithPassword","email","password","handle","firstName","lastName","avatarUrl","loginWithPassword","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","sendMagicLink","loginWithMagicLink","loginWithOneTimeCode","resetPassword","linkOAuthProvider","provider","nonceResponse","nonce","url","unlinkOAuthProvider"],"mappings":"uIAAA,IAAMA,EAAc,mBAAA,CAEpB,SAASC,CAAAA,EAA2B,CAClC,OAAO,OAAO,UAAA,CAAe,GAAA,EAAe,OAAO,WAAW,YAAA,CAAiB,GACjF,CAEO,SAASC,CAAAA,EAAyB,CACvC,GAAI,CAACD,CAAAA,EAAgB,CACnB,OAAO,IAAA,CAGT,IAAME,EAAc,UAAA,CAAW,YAAA,CAAa,QAAQH,CAAW,CAAA,CAC/D,GAAI,CACF,OAAOG,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,MAAM,yCAAA,CAA2CA,CAAC,CAAA,CACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACjDL,CAAAA,EAAgB,EAIrB,WAAW,YAAA,CAAa,OAAA,CAAQD,EAAa,IAAA,CAAK,SAAA,CAAUM,CAAO,CAAC,EACtE,CCDA,IAAIC,EAA8B,IAAA,CAgC3B,SAASC,EAAgBC,CAAAA,CAA0B,CACxDF,CAAAA,CAASE,EACX,CAEO,SAASC,CAAAA,EAAuC,CACrD,OAAOH,CACT,CC7DA,IAAII,EAA6B,CAACC,CAAAA,CAAOC,CAAAA,GAAe,CACtD,QAAQ,KAAA,CAAM,CAAA,sBAAA,EAAyBA,CAAU,CAAA,EAAA,C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sE,EAG1F,MAAA,CAAO,QAAA,CAAS,IAAA,CAAO,CAAA,EAAGhE,CAAO,CAAA,oBAAA,EAAuByE,CAAQ,aAClE,CACF,CAUA,eAAsBI,EAAAA,CAAoBrE,CAAAA,CAAqD,CAC7F,GAAM,CAAE,QAAA,CAAAiE,CAAS,CAAA,CAAIjE,CAAAA,CACrB,MAAMD,CAAAA,CAAW,kCAAA,CAAoC,CAAE,QAAA,CAAAkE,CAAS,CAAC,EACnE,CAMO,SAAS9D,CAAAA,EAAmC,CACjD,IAAM3B,CAAAA,CAASG,CAAAA,EAAgB,CAC/B,OAAIH,CAAAA,CACKA,CAAAA,CAAO,cAAa,CAEtBL,CAAAA,IAA0B,SACnC,CAEO,SAASiC,CAAAA,EAA4B,CAC1C,IAAM5B,CAAAA,CAASG,GAAgB,CAC/B,OAAIH,EACKA,CAAAA,CAAO,aAAA,EAAc,CAG1B,OAAO,OAAW,GAAA,CACb,CACL,YAAa,CAAA,CACb,YAAA,CAAc,EACd,WAAA,CAAa,CAAA,CACb,YAAA,CAAc,CAAA,CACd,WAAY,CAAA,CACZ,WAAA,CAAa,IACf,CAAA,CAGK,CACL,YAAa,MAAA,CAAO,MAAA,CAAO,KAAA,CAC3B,YAAA,CAAc,OAAO,MAAA,CAAO,MAAA,CAC5B,YAAa,MAAA,CAAO,UAAA,CACpB,aAAc,MAAA,CAAO,WAAA,CACrB,UAAA,CAAY,MAAA,CAAO,iBACnB,WAAA,CAAa,MAAA,CAAO,OAAO,WAAA,EAAa,IAAA,EAAQ,IAClD,CACF","file":"chunk-AMJHJA2V.js","sourcesContent":["const SESSION_KEY = 'modelence.session';\n\nfunction hasLocalStorage(): boolean {\n return typeof globalThis !== 'undefined' && typeof globalThis.localStorage !== 'undefined';\n}\n\nexport function getLocalStorageSession() {\n if (!hasLocalStorage()) {\n return null;\n }\n\n const sessionJson = globalThis.localStorage.getItem(SESSION_KEY);\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n if (!hasLocalStorage()) {\n return;\n }\n\n globalThis.localStorage.setItem(SESSION_KEY, JSON.stringify(session));\n}\n","import type { ClientInfo } from '@/methods/types';\n\nexport interface ClientConfig {\n baseUrl: string;\n getAuthToken: () => string | undefined;\n setAuthToken: (token: string | null) => void;\n getClientInfo: () => ClientInfo;\n /**\n * Opens a URL for OAuth redirects. React Native must use\n * `(url) => Linking.openURL(url)` — WebView is not supported.\n * Defaults to `window.location.href` when not provided.\n */\n openUrl?: (url: string) => void;\n /**\n * Credentials mode for method-call requests. Defaults to `'include'`, which\n * browser apps need for the cookie-based flows (password reset, magic link).\n *\n * Clients configured with token-in-body auth (React Native / Expo) never use\n * cookies, so set `'omit'` there — on Expo Web a credentialed cross-origin\n * request is otherwise blocked by any server answering\n * `Access-Control-Allow-Origin: *`, surfacing as \"TypeError: Failed to fetch\".\n */\n credentials?: RequestCredentials;\n}\n\nlet config: ClientConfig | null = null;\n\n/**\n * Configure the Modelence client for non-browser environments like React Native.\n *\n * When configured, the client uses the provided functions for auth-token\n * storage, client-info collection, and URL resolution instead of the\n * default browser APIs (localStorage, window.screen, relative URLs).\n *\n * @example\n * ```ts\n * import { configureClient } from 'modelence/client';\n * import { Linking } from 'react-native';\n *\n * let authToken: string | undefined;\n *\n * configureClient({\n * baseUrl: 'https://myapp.com',\n * getAuthToken: () => authToken,\n * setAuthToken: (token) => { authToken = token ?? undefined; },\n * getClientInfo: () => ({\n * screenWidth: Dimensions.get('screen').width,\n * screenHeight: Dimensions.get('screen').height,\n * windowWidth: Dimensions.get('window').width,\n * windowHeight: Dimensions.get('window').height,\n * pixelRatio: PixelRatio.get(),\n * orientation: null,\n * }),\n * openUrl: (url) => Linking.openURL(url),\n * });\n * ```\n */\nexport function configureClient(userConfig: ClientConfig) {\n config = userConfig;\n}\n\nexport function getClientConfig(): ClientConfig | null {\n return config;\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n /**\n * Machine-readable error code set by the server (when available), so callers\n * can branch on the error kind without matching the human-readable message.\n * For example, a login attempt with an unverified email yields\n * `code === 'EMAIL_NOT_VERIFIED'`.\n */\n code?: string;\n\n constructor(message: string, status: number, code?: string) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n this.code = code;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\n// Default: fetch HTTP. SSR swaps in an in-process transport via globalThis\n// so Vite's ssrLoadModule (separate module graph) shares the same instance.\nexport type CallMethodTransport = <T = unknown>(methodName: string, args: MethodArgs) => Promise<T>;\n\n/**\n * The default HTTP transport. Exported so alternative transports (e.g. the SSR\n * in-process transport) can delegate to it when they don't apply.\n * @internal\n */\nexport const defaultCallMethodTransport: CallMethodTransport = async <T>(\n methodName: string,\n args: MethodArgs\n) => {\n const baseUrl = getClientConfig()?.baseUrl ?? '';\n return call<T>(`${baseUrl}/api/_internal/method/${methodName}`, args);\n};\n\nconst TRANSPORT_KEY = '__modelence_call_method_transport__';\n\ntype GlobalWithTransport = typeof globalThis & {\n [TRANSPORT_KEY]?: CallMethodTransport;\n};\n\nfunction getTransport(): CallMethodTransport {\n return (globalThis as GlobalWithTransport)[TRANSPORT_KEY] ?? defaultCallMethodTransport;\n}\n\n/** Returns a disposer that restores the previous transport. */\nexport function setCallMethodTransport(next: CallMethodTransport): () => void {\n const previous = (globalThis as GlobalWithTransport)[TRANSPORT_KEY];\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = next;\n return () => {\n (globalThis as GlobalWithTransport)[TRANSPORT_KEY] = previous;\n };\n}\n\n/**\n * Calls a server-side method (query or mutation) defined on a Modelence module.\n *\n * Both `args` and `options` are optional. Use the type parameter `T` to type the return value.\n *\n * @example\n * ```typescript\n * import { callMethod } from 'modelence/client';\n *\n * // No arguments\n * const todos = await callMethod<Todo[]>('todo.getAll');\n *\n * // With arguments\n * const todo = await callMethod<Todo>('todo.getOne', { id: '123' });\n *\n * // With a custom error handler\n * const created = await callMethod<Todo>(\n * 'todo.create',\n * { title: 'Buy groceries' },\n * { errorHandler: (error, methodName) => console.error(methodName, error) }\n * );\n * ```\n *\n * @param methodName - Fully qualified method name, e.g. `'todo.getAll'`.\n * @param args - Arguments passed to the server-side method. Defaults to `{}`.\n * @param options - Call-site options such as a custom {@link CallMethodOptions.errorHandler}. Defaults to `{}`.\n * @returns A promise that resolves to the method's return value.\n */\nexport async function callMethod<T = unknown>(\n methodName: string,\n args?: MethodArgs,\n options?: CallMethodOptions\n): Promise<T> {\n args = args ?? {};\n options = options ?? {};\n try {\n return await getTransport()<T>(methodName, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n // Send cookies even when the SPA and API are on different origins. The\n // password-reset and magic-link flows rely on httpOnly cookies set by the\n // server landing routes; with the default `same-origin` policy the cookie\n // would be dropped on cross-origin POSTs and those flows would fail.\n // (Cross-origin use also requires the server to emit\n // `Access-Control-Allow-Credentials: true` and a non-wildcard origin.)\n // Token-in-body clients (React Native / Expo) don't use cookies and can\n // override this via `configureClient({ credentials: 'omit' })`.\n credentials: getClientConfig()?.credentials ?? 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n const code = response.headers?.get('X-Modelence-Error-Code') ?? undefined;\n throw new MethodError(error, response.status, code);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\ntype SsrConfigResolver = (key: ConfigKey) => string | number | boolean | undefined;\nlet ssrConfigResolver: SsrConfigResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrConfigResolver(resolver: SsrConfigResolver | null) {\n ssrConfigResolver = resolver;\n}\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n if (typeof window === 'undefined' && ssrConfigResolver) {\n return ssrConfigResolver(key);\n }\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { getLocalStorageSession, setLocalStorageSession } from './localStorage';\nimport { getClientConfig } from './clientConfig';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\n// Set when SSR rendered anonymously but localStorage holds a token (no\n// cookie yet). `reconcileSession()` then re-auths via the body and refreshes\n// the cookie for subsequent SSR requests.\nlet pendingReconciliation = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport type SessionInitPayload = {\n configs: Configs;\n session: object & { authToken: string };\n user: object;\n};\n\n/** Hydrate session state from the SSR payload, skipping the network round-trip. */\nexport function hydrateSession(payload: SessionInitPayload) {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n _setConfig(payload.configs);\n\n // localStorage token + anonymous SSR payload = server couldn't read the\n // token (no cookie yet). Preserve the localStorage token and defer to\n // `reconcileSession()`; overwriting here would log the user out permanently.\n const existingLocalSession = getLocalStorageSession() as { authToken?: string } | null;\n const existingToken = existingLocalSession?.authToken;\n const ssrSession = payload.session as { authToken?: string };\n\n if (existingToken && !payload.user && existingToken !== ssrSession.authToken) {\n pendingReconciliation = true;\n // First render must match the server (anonymous); reconcile swaps later.\n useSessionStore.getState().setUser(parseUser(payload.user));\n return;\n }\n\n setLocalStorageSession(payload.session);\n useSessionStore.getState().setUser(parseUser(payload.user));\n}\n\n/** Re-auth via the body token when SSR couldn't read it from a cookie. */\nexport async function reconcileSession() {\n if (!pendingReconciliation) {\n return;\n }\n pendingReconciliation = false;\n\n try {\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n useSessionStore.getState().setUser(parseUser(user));\n } catch (error) {\n console.error('Modelence: session reconciliation failed', error);\n }\n}\n\n/** @internal */\nexport function _isReconciliationPending(): boolean {\n return pendingReconciliation;\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<SessionInitPayload>('_system.session.init');\n _setConfig(configs);\n\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n } else {\n setLocalStorageSession(session);\n }\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\n/** Idempotent, client-only. Auto-started by `initSession`; call explicitly after `hydrateSession`. */\nexport async function startSessionHeartbeat() {\n if (typeof window === 'undefined' || heartbeatTimer !== null) {\n return;\n }\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n if (typeof window === 'undefined') {\n return;\n }\n\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function isSessionInitialized() {\n return isInitialized;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\ntype SsrSessionResolver = () => User | null;\nlet ssrSessionResolver: SsrSessionResolver | null = null;\n\n/** @internal SSR resolver reads from AsyncLocalStorage (per-request scoped). */\nexport function _setSsrSessionResolver(resolver: SsrSessionResolver | null) {\n ssrSessionResolver = resolver;\n}\n\n/** @internal */\nexport function _parseSessionUser(user: unknown): User | null {\n return parseUser(user);\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n if (typeof window === 'undefined' && ssrSessionResolver) {\n return { user: ssrSessionResolver() };\n }\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { getClientConfig } from '@/client/clientConfig';\nimport type { ClientInfo } from '@/methods/types';\nimport { OAuthProvider } from '../types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithPassword',\n {\n email,\n password,\n }\n );\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(null);\n }\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Send a magic sign-in link to the given email address.\n *\n * Clicking the emailed link signs the user in. When the server enables\n * `auth.magicLink.allowSignup`, this also works for new users — the account is\n * created when the link is used; otherwise unknown emails receive no email.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await sendMagicLink({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to send the magic link to.\n */\nexport async function sendMagicLink(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendMagicLink', {\n email,\n });\n}\n\n/**\n * Complete a magic link sign-in.\n *\n * Call this from the page the magic link landing route redirects to. The\n * token is exchanged server-side via an httpOnly cookie, so no arguments are\n * needed. Signs the user in — creating the account first when the email is\n * not registered yet and the server enables `auth.magicLink.allowSignup` —\n * and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithMagicLink();\n * ```\n */\nexport async function loginWithMagicLink() {\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithMagicLink'\n );\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Complete a magic link sign-in by typing the one-time code from the email.\n *\n * Alternative to `loginWithMagicLink()` for contexts where clicking the link\n * can't reach the app — native apps without deep links, or when the email is\n * read on a different device. Signs the user in — creating the account first\n * when the email is not registered yet and the server enables\n * `auth.magicLink.allowSignup` — and returns the logged-in user.\n *\n * @example\n * ```ts\n * const user = await loginWithOneTimeCode({ email: 'user@example.com', code: '482193' });\n * ```\n * @param options.email - The email the magic link was sent to.\n * @param options.code - The one-time code from the email.\n */\nexport async function loginWithOneTimeCode(options: { email: string; code: string }) {\n const { email, code } = options;\n const { user, session } = await callMethod<{ user: RawUserData; session: { authToken: string } }>(\n '_system.user.loginWithOneTimeCode',\n { email, code }\n );\n const config = getClientConfig();\n if (config) {\n config.setAuthToken(session.authToken);\n }\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Reset password.\n *\n * The token is normally exchanged server-side via an httpOnly cookie, so the\n * client only submits the new password. Pass `token` only for legacy flows\n * that still carry it client-side (deprecated).\n *\n * @param options.token - Reset token (optional; read from the httpOnly cookie when omitted).\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token?: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n ...(token ? { token } : {}),\n password,\n });\n}\n\n/**\n * Link an OAuth provider to the currently signed-in user's account.\n * Redirects the browser to the OAuth provider's authorization page.\n * The provider will redirect back and the account will be linked.\n *\n * @example\n * ```ts\n * linkOAuthProvider({ provider: 'google' });\n * ```\n * @param options.provider - The OAuth provider to link ('google' or 'github').\n */\nexport async function linkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n const config = getClientConfig();\n const baseUrl = config?.baseUrl ?? '';\n\n if (config?.openUrl) {\n // React Native: exchange authToken for a single-use nonce via an authenticated\n // request, then put the nonce in the URL. A crafted external link can't work\n // because the nonce is bound to this session and consumed on first use.\n const token = getAuthToken();\n if (!token) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const nonceResponse = await fetch(`${baseUrl}/api/_internal/auth/issue-link-nonce`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n });\n if (!nonceResponse.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n const { nonce } = await nonceResponse.json();\n const url = `${baseUrl}/api/_internal/auth/${provider}?mode=link&linkNonce=${encodeURIComponent(nonce)}`;\n config.openUrl(url);\n } else {\n // Browser: set httpOnly cookie via same-origin fetch (keeps token out of redirect params).\n const token = getAuthToken();\n if (token) {\n const response = await fetch(`${baseUrl}/api/_internal/auth/set-link-cookie`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ authToken: token }),\n credentials: 'include',\n });\n if (!response.ok) {\n throw new Error('Failed to initialize OAuth linking. Please ensure you are logged in.');\n }\n }\n window.location.href = `${baseUrl}/api/_internal/auth/${provider}?mode=link`;\n }\n}\n/**\n * Unlink an OAuth provider from the currently signed-in user's account.\n *\n * @example\n * ```ts\n * await unlinkOAuthProvider({ provider: 'github' });\n * ```\n * @param options.provider - The OAuth provider to unlink ('google' or 'github').\n */\nexport async function unlinkOAuthProvider(options: { provider: OAuthProvider }): Promise<void> {\n const { provider } = options;\n await callMethod('_system.user.unlinkOAuthProvider', { provider });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n const config = getClientConfig();\n if (config) {\n return config.getAuthToken();\n }\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n const config = getClientConfig();\n if (config) {\n return config.getClientInfo();\n }\n\n if (typeof window === 'undefined') {\n return {\n screenWidth: 0,\n screenHeight: 0,\n windowWidth: 0,\n windowHeight: 0,\n pixelRatio: 1,\n orientation: null,\n };\n }\n\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {E,r,q,w as w$1,B as B$1,A as A$1,C,c as c$1}from'./chunk-AMJHJA2V.js';import {c}from'./chunk-5M6FUMUK.js';import {useState,useEffect}from'react';import {jsx}from'react/jsx-runtime';import $ from'socket.io-client';import {hashKey,QueryClient,QueryClientProvider,HydrationBoundary}from'@tanstack/react-query';var K="__MODELENCE_STATE__",R=false;function N(){return typeof document<"u"&&document.getElementById(K)!==null}function le({children:e,loadingElement:n}){let r=typeof window>"u",[t,o]=useState(()=>!r&&!E()&&!N());return useEffect(()=>{async function s(){if(!R){if(R=true,E()){B$1()&&await A$1();return}await C(),o(false);}}s();},[]),t?n??jsx("div",{children:"Loading..."}):e}var y=null,v=new Map;function p(){if(!y)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return y}function B(){let e=q(),n=r();for(let r of v.values())y?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:n});}function F(e){let n=c$1()?.baseUrl??"/";y=$(n,{transports:["websocket"],auth:{token:q()}}),y.on("connect",()=>{v.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${v.size} live queries`),B());}),e.channels?.forEach(r=>r.init());}function j({category:e,listener:n}){p().on(e,n);}function H({category:e,listener:n}){p().once(e,n);}function Y({category:e,listener:n}){p().off(e,n);}function k({eventName:e,category:n,id:r}){p().emit(e,`${n}:${r}`);}function J({category:e,id:n}){k({eventName:"joinChannel",category:e,id:n});}function G({category:e,id:n}){k({eventName:"leaveChannel",category:e,id:n});}var V=0;function S(e,n,r$1,t){let o=`sub-${++V}-${Date.now()}`,s=({subscriptionId:l,data:i,typeMap:f})=>{l===o&&r$1(c(i,f));},a=({subscriptionId:l,error:i})=>{l===o&&(console.error(`[Modelence] Live query error for ${e}:`,i),t?.(i));},c$1=p();return c$1.on("liveQueryData",s),c$1.on("liveQueryError",a),v.set(o,{subscriptionId:o,method:e,args:n}),c$1.connected&&c$1.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:n,authToken:q(),clientInfo:r()}),()=>{v.delete(o),c$1.emit("unsubscribeLiveQuery",{subscriptionId:o}),c$1.off("liveQueryData",s),c$1.off("liveQueryError",a);}}var X={init:F,on:j,once:H,off:Y,emit:k,joinChannel:J,leaveChannel:G},A=X;var w=null;function _(e){w=e;}function Ce(){return w}function L(e){if(w){console.warn("WebSocket already initialized. Skipping initialization.");return}let n=e?.provider||A;_(n);try{n.init({channels:e?.channels});}catch(r){throw _(null),r}}var d=null,g=null,Q=false,u=new Map;function T(e){d!==e&&(d&&Z(),d=e,g=e.getQueryCache().subscribe(n=>{if(n.type==="removed"){let r=hashKey(n.query.queryKey),t=u.get(r);if(t){if(t.resolvers.size>0){let o=new Error("Query was removed from cache");t.resolvers.forEach(s=>s.reject(o)),t.resolvers.clear();}t.unsubscribe(),u.delete(r);}}}));}function Te(){return d!==null}function Z(){g&&(g(),g=null),u.forEach(e=>e.unsubscribe()),u.clear(),d=null,Q=false;}var W=class{connect(n){T(n);}};function Ee(e,n={}){return {queryKey:[e,n],queryFn:()=>w$1(e,n)}}function Pe(e,n={}){let r=["live",e,n],t=hashKey(r);return {queryKey:r,queryFn:()=>new Promise((o,s)=>{if(typeof window>"u")return;if(!d){let c=new Error("Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().");console.error("[Modelence]",c.message),s(c);return}Q||(L(),Q=true);let a=u.get(t);a||(a={unsubscribe:S(e,n,l=>{let i=u.get(t);i?.resolvers.size&&(i.resolvers.forEach(f=>f.resolve(l)),i.resolvers.clear()),d&&d.setQueryData(r,l);},l=>{let i=u.get(t);i&&(i.resolvers.size&&(i.resolvers.forEach(f=>f.reject(new Error(l))),i.resolvers.clear()),i.unsubscribe(),u.delete(t));}),resolvers:new Set},u.set(t,a)),a.resolvers.add({resolve:o,reject:s});}),staleTime:1/0,refetchOnWindowFocus:false,refetchOnMount:false,refetchOnReconnect:false,gcTime:0}}function Me(e,n={}){return {mutationFn:(r={})=>w$1(e,{...n,...r})}}function xe(e,n={}){return [e,n]}var oe="__MODELENCE_QUERY_STATE__";function ie(){if(typeof document>"u")return;let e=document.getElementById(oe);if(!(!e||!e.textContent))try{return JSON.parse(e.textContent)}catch(n){console.error("Modelence: failed to parse SSR query state",n);return}}function Le({children:e,client:n,dehydratedState:r}){let[t]=useState(()=>{let s=n??new QueryClient({defaultOptions:{queries:{staleTime:6e4}}});return typeof window<"u"&&T(s),s}),o=r??ie();return jsx(QueryClientProvider,{client:t,children:jsx(HydrationBoundary,{state:o,children:e})})}export{le as a,S as b,_ as c,Ce as d,L as e,T as f,Te as g,Z as h,W as i,Ee as j,Pe as k,Me as l,xe as m,Le as n};//# sourceMappingURL=chunk-BCUSVRAY.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-BCUSVRAY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/client/AppProvider.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/client/query.ts","../src/client/queryProvider.tsx"],"names":["SSR_STATE_SCRIPT_ID","isInitialized","hasServerRenderedMarkup","AppProvider","children","loadingElement","isServer","isLoading","setIsLoading","useState","isSessionInitialized","useEffect","initConfig","_isReconciliationPending","reconcileSession","initSession","jsx","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","getAuthToken","clientInfo","getClientInfo","sub","init","props","baseUrl","getClientConfig","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","args","onData","onError","subscriptionId","handleData","sid","data","typeMap","reviveResponseTypes","handleError","error","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","queryClientRef","cacheUnsubscribe","websocketsStarted","subscriptions","connectModelenceQueryClient","queryClient","disconnectModelenceQueryClient","event","subscriptionKey","hashKey","cancelError","r","hasConnectedQueryClient","ModelenceQueryClient","modelenceQuery","methodName","callMethod","modelenceLiveQuery","queryKey","resolve","reject","currentSub","modelenceMutation","defaultArgs","variables","createQueryKey","SSR_QUERY_STATE_SCRIPT_ID","readDehydratedState","node","e","ModelenceQueryProvider","client","dehydratedState","internalClient","qc","QueryClient","state","QueryClientProvider","HydrationBoundary"],"mappings":"2TAiBA,IAAMA,CAAAA,CAAsB,qBAAA,CAOxBC,CAAAA,CAAgB,KAAA,CAKpB,SAASC,CAAAA,EAAmC,CAC1C,OAAO,OAAO,QAAA,CAAa,GAAA,EAAe,QAAA,CAAS,cAAA,CAAeF,CAAmB,CAAA,GAAM,IAC7F,CAEO,SAASG,EAAAA,CAAY,CAAE,QAAA,CAAAC,CAAAA,CAAU,cAAA,CAAAC,CAAe,CAAA,CAAqB,CAC1E,IAAMC,CAAAA,CAAW,OAAO,MAAA,CAAW,GAAA,CAC7B,CAACC,CAAAA,CAAWC,CAAY,CAAA,CAAIC,QAAAA,CAChC,IAAM,CAACH,CAAAA,EAAY,CAACI,CAAAA,EAAqB,EAAK,CAACR,CAAAA,EACjD,CAAA,CAyBA,OAvBAS,SAAAA,CAAU,IAAM,CACd,eAAeC,CAAAA,EAAa,CAC1B,GAAI,CAAAX,CAAAA,CAMJ,CAAA,GAFAA,CAAAA,CAAgB,IAAA,CAEZS,CAAAA,EAAqB,CAAG,CAEtBG,GAAAA,EAAyB,EAC3B,MAAMC,GAAAA,EAAiB,CAEzB,MACF,CAEA,MAAMC,CAAAA,EAAY,CAClBP,CAAAA,CAAa,KAAK,EAAA,CACpB,CAEKI,CAAAA,GACP,CAAA,CAAG,EAAE,CAAA,CAEDL,CAAAA,CACKF,CAAAA,EAAkBW,GAAAA,CAAC,KAAA,CAAA,CAAI,QAAA,CAAA,YAAA,CAAU,CAAA,CAGnCZ,CACT,CC5DA,IAAIa,CAAAA,CAA8B,IAAA,CAO5BC,CAAAA,CAA0B,IAAI,GAAA,CAEpC,SAASC,CAAAA,EAAoB,CAC3B,GAAI,CAACF,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,0DAA0D,CAAA,CAE5E,OAAOA,CACT,CAEA,SAASG,CAAAA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7D,MACF,CACF,CAQO,SAASC,EAAAA,CAAuB,CACrC,QAAA,CAAA1F,CAAAA,CACA,MAAA,CAAA2F,CAAAA,CACA,eAAA,CAAAC,CACF,CAAA,CAAgC,CAC9B,GAAM,CAACC,CAAc,CAAA,CAAIxF,QAAAA,CAAS,IAAM,CACtC,IAAMyF,CAAAA,CACJH,CAAAA,EACA,IAAII,WAAAA,CAAY,CACd,cAAA,CAAgB,CACd,OAAA,CAAS,CACP,SAAA,CAAW,GACb,CACF,CACF,CAAC,CAAA,CACH,OAAI,OAAO,MAAA,CAAW,GAAA,EACpB/B,CAAAA,CAA4B8B,CAAE,CAAA,CAEzBA,CACT,CAAC,CAAA,CAEKE,CAAAA,CAAQJ,CAAAA,EAAmBL,EAAAA,EAAoB,CAErD,OACE3E,GAAAA,CAACqF,mBAAAA,CAAA,CAAoB,MAAA,CAAQJ,CAAAA,CAC3B,QAAA,CAAAjF,GAAAA,CAACsF,iBAAAA,CAAA,CAAkB,KAAA,CAAOF,CAAAA,CAAQ,QAAA,CAAAhG,CAAAA,CAAS,CAAA,CAC7C,CAEJ","file":"chunk-BCUSVRAY.js","sourcesContent":["/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n\n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { useState, useEffect, ReactNode } from 'react';\nimport {\n _isReconciliationPending,\n initSession,\n isSessionInitialized,\n reconcileSession,\n} from './session';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\n// Presence of the state script signals server-rendered markup in the DOM,\n// even if `hydrateSession` failed to parse it. Hiding under a loading shell\n// here would cause a hydration mismatch and a flash-of-spinner.\nfunction hasServerRenderedMarkup(): boolean {\n return typeof document !== 'undefined' && document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const isServer = typeof window === 'undefined';\n const [isLoading, setIsLoading] = useState(\n () => !isServer && !isSessionInitialized() && !hasServerRenderedMarkup()\n );\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n if (isSessionInitialized()) {\n // SSR couldn't authenticate via cookie; reconcile via body token now.\n if (_isReconciliationPending()) {\n await reconcileSession();\n }\n return;\n }\n\n await initSession();\n setIsLoading(false);\n }\n\n void initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { getClientConfig } from '@/client/clientConfig';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n const baseUrl = getClientConfig()?.baseUrl ?? '/';\n socketClient = io(baseUrl, {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider | null) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n setWebsocketClientProvider(provider);\n try {\n provider.init({\n channels: props?.channels,\n });\n } catch (error) {\n setWebsocketClientProvider(null);\n throw error;\n }\n}\n","'use client';\n\nimport { QueryClient, hashKey } from '@tanstack/react-query';\nimport { callMethod } from './method';\nimport { startWebsockets, subscribeLiveQuery } from '../websocket/client';\n\ntype Args = Record<string, unknown>;\n\ninterface Subscription {\n unsubscribe: () => void;\n resolvers: Set<{\n resolve: (data: unknown) => void;\n reject: (error: Error) => void;\n }>;\n}\n\nlet queryClientRef: QueryClient | null = null;\nlet cacheUnsubscribe: (() => void) | null = null;\nlet websocketsStarted = false;\nconst subscriptions = new Map<string, Subscription>();\n\n/**\n * Connects a `QueryClient` to Modelence's live-query layer. Auto-called by\n * `<ModelenceQueryProvider>`; only call manually if you mount your own\n * `<QueryClientProvider>`.\n *\n * Note: WebSocket setup is deferred until the first `modelenceLiveQuery`\n * call, so apps that only use `modelenceQuery`/`modelenceMutation` never\n * open a socket.\n */\nexport function connectModelenceQueryClient(queryClient: QueryClient) {\n if (queryClientRef === queryClient) {\n return;\n }\n\n if (queryClientRef) {\n disconnectModelenceQueryClient();\n }\n\n queryClientRef = queryClient;\n\n cacheUnsubscribe = queryClient.getQueryCache().subscribe((event) => {\n if (event.type === 'removed') {\n const subscriptionKey = hashKey(event.query.queryKey);\n const sub = subscriptions.get(subscriptionKey);\n if (sub) {\n if (sub.resolvers.size > 0) {\n const cancelError = new Error('Query was removed from cache');\n sub.resolvers.forEach((r) => r.reject(cancelError));\n sub.resolvers.clear();\n }\n sub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n });\n}\n\n/**\n * Whether a `QueryClient` is already connected to the live-query layer.\n * `renderApp` uses this to avoid injecting its own `<ModelenceQueryProvider>`\n * when the app already mounts its own provider and connects it beforehand.\n */\nexport function hasConnectedQueryClient(): boolean {\n return queryClientRef !== null;\n}\n\nexport function disconnectModelenceQueryClient() {\n if (cacheUnsubscribe) {\n cacheUnsubscribe();\n cacheUnsubscribe = null;\n }\n subscriptions.forEach((sub) => sub.unsubscribe());\n subscriptions.clear();\n queryClientRef = null;\n websocketsStarted = false;\n}\n\n/** @deprecated Use `connectModelenceQueryClient(queryClient)` instead. */\nexport class ModelenceQueryClient {\n connect(queryClient: QueryClient) {\n connectModelenceQueryClient(queryClient);\n }\n}\n\n/**\n * @example\n * ```tsx\n * const { data } = useQuery(modelenceQuery('todo.getAll'));\n * ```\n */\nexport function modelenceQuery<T = unknown>(methodName: string, args: Args = {}) {\n return {\n queryKey: [methodName, args],\n queryFn: () => callMethod<T>(methodName, args),\n };\n}\n\n/**\n * Live query — data updates in real time as the underlying collection changes.\n * Requires a `QueryClient` connected via `<ModelenceQueryProvider>` or\n * `connectModelenceQueryClient(...)`.\n */\nexport function modelenceLiveQuery<T = unknown>(methodName: string, args: Args = {}) {\n const queryKey = ['live', methodName, args] as const;\n const subscriptionKey = hashKey(queryKey);\n\n return {\n queryKey,\n queryFn: () =>\n new Promise<T>((resolve, reject) => {\n // Live queries are WebSocket subscriptions — no server snapshot. Stay\n // pending on the server so Suspense renders; client re-runs after hydration.\n if (typeof window === 'undefined') {\n return;\n }\n\n if (!queryClientRef) {\n const error = new Error(\n 'Modelence: connect a QueryClient before using modelenceLiveQuery(). Mount <ModelenceQueryProvider> or call connectModelenceQueryClient().'\n );\n console.error('[Modelence]', error.message);\n reject(error);\n return;\n }\n\n if (!websocketsStarted) {\n startWebsockets();\n websocketsStarted = true;\n }\n\n let sub = subscriptions.get(subscriptionKey);\n\n if (!sub) {\n const unsubscribe = subscribeLiveQuery<T>(\n methodName,\n args,\n (data) => {\n const currentSub = subscriptions.get(subscriptionKey);\n\n if (currentSub?.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.resolve(data));\n currentSub.resolvers.clear();\n }\n\n if (queryClientRef) {\n queryClientRef.setQueryData(queryKey, data);\n }\n },\n (error) => {\n const currentSub = subscriptions.get(subscriptionKey);\n if (currentSub) {\n if (currentSub.resolvers.size) {\n currentSub.resolvers.forEach((r) => r.reject(new Error(error)));\n currentSub.resolvers.clear();\n }\n currentSub.unsubscribe();\n subscriptions.delete(subscriptionKey);\n }\n }\n );\n\n sub = { unsubscribe, resolvers: new Set() };\n subscriptions.set(subscriptionKey, sub);\n }\n\n // Shared map stores resolvers across `T` instantiations; erase the union.\n sub.resolvers.add({\n resolve: resolve as (data: unknown) => void,\n reject,\n });\n }),\n staleTime: Infinity,\n refetchOnWindowFocus: false,\n refetchOnMount: false,\n refetchOnReconnect: false,\n gcTime: 0,\n };\n}\n\nexport function modelenceMutation<T = unknown>(methodName: string, defaultArgs: Args = {}) {\n return {\n mutationFn: (variables: Args = {}) =>\n callMethod<T>(methodName, { ...defaultArgs, ...variables }),\n };\n}\n\nexport type ModelenceQueryKey<T extends string, U extends Args = Args> = readonly [T, U];\n\n/** Builds a query key matching `modelenceQuery(...)` for cache operations. */\nexport function createQueryKey<T extends string, U extends Args = Args>(\n methodName: T,\n args: U = {} as U\n): ModelenceQueryKey<T, U> {\n return [methodName, args] as const;\n}\n","'use client';\n\nimport { useState, type ReactNode } from 'react';\nimport {\n QueryClient,\n QueryClientProvider,\n HydrationBoundary,\n type DehydratedState,\n} from '@tanstack/react-query';\nimport { connectModelenceQueryClient } from './query';\n\nconst SSR_QUERY_STATE_SCRIPT_ID = '__MODELENCE_QUERY_STATE__';\n\nfunction readDehydratedState(): DehydratedState | undefined {\n if (typeof document === 'undefined') {\n return undefined;\n }\n\n const node = document.getElementById(SSR_QUERY_STATE_SCRIPT_ID);\n if (!node || !node.textContent) {\n return undefined;\n }\n\n try {\n return JSON.parse(node.textContent) as DehydratedState;\n } catch (e) {\n console.error('Modelence: failed to parse SSR query state', e);\n return undefined;\n }\n}\n\ninterface ModelenceQueryProviderProps {\n children: ReactNode;\n client?: QueryClient;\n dehydratedState?: DehydratedState;\n}\n\nexport function ModelenceQueryProvider({\n children,\n client,\n dehydratedState,\n}: ModelenceQueryProviderProps) {\n const [internalClient] = useState(() => {\n const qc =\n client ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000,\n },\n },\n });\n if (typeof window !== 'undefined') {\n connectModelenceQueryClient(qc);\n }\n return qc;\n });\n\n const state = dehydratedState ?? readDehydratedState();\n\n return (\n <QueryClientProvider client={internalClient}>\n <HydrationBoundary state={state}>{children}</HydrationBoundary>\n </QueryClientProvider>\n );\n}\n"]}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import {s as s$1}from'./chunk-4L4E6PFO.js';import {a,b as b$1,c,p,q as q$1,r,s,t,l,m,d,y,k,j,n,i,o,u,z as z$2,A,B,C as C$1,e as e$1,D,w as w$1,v as v$1,f as f$1,G as G$1,E,F as F$1}from'./chunk-YOJ4ZP5D.js';import {b as b$2,d as d$1,a as a$4}from'./chunk-MIRF7FP3.js';import {a as a$2,f,e,g,c as c$1,h,l as l$1,k as k$1,d as d$2,j as j$1,m as m$1,i as i$1,n as n$1}from'./chunk-VF4RU7MF.js';import {a as a$3,b as b$3}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import ir from'dotenv';import _n from'fs/promises';import Jr from'os';import Q from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoServerError,MongoClient,MongoError,ObjectId}from'mongodb';export{ObjectId as m}from'mongodb';import Ar from'bcrypt';import F,{z as z$1}from'zod';import {randomBytes,randomInt,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import fn from'@vitejs/plugin-react';import Oe from'fs';import V,{Router}from'express';import pi from'cookie-parser';import fi from'http';var le=new a("_system",{configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var G=null;async function Vt(){if(G)return G;let e=z();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");G=new MongoClient(e,{driverInfo:{name:"Modelence",version:s$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await G.connect(),await G.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),G}catch(o){throw console.error(o),G=null,o}}function z(){return le.getConfig("mongodbUri")||void 0}function Ee(){return G}var de=null,Er="_modelenceSocketio",Bt=60;async function br({httpServer:e,channels:t}){let o=Ee(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(Er);try{await n.createIndex({createdAt:1},{expireAfterSeconds:Bt,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:Bt,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",i);}}de=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),de.on("error",i=>{console.error("Socket.IO error:",i);}),de.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await w$1(a),s();}catch(c){s(c instanceof Error?c:new Error(String(c)));}}),de.on("connection",i=>{i.on("disconnect",()=>{G$1(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>E(i,s)),i.on("unsubscribeLiveQuery",s=>F$1(i,s));}),console.log("Socket.IO server initialized");}function vr({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var zt={init:br,broadcast:vr};async function be(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await q$1.findOne({domain:o})}var qt={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let o=(await e.text()).split(`
|
|
2
|
+
`).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await q$1.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var ve=3,q=50,Wt=8,Jt=128,Kt=254,Yt=e=>z$1.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),He=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),kr=z$1.object({firstName:He({max:50}),lastName:He({max:50}),avatarUrl:He({max:400}),handle:Yt({min:ve,max:q})}).strict();function ke(e){let t=kr.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function Ce(e){return z$1.string().min(Wt,{message:`Password must contain at least ${Wt} characters`}).max(Jt,{message:`Password must be at most ${Jt} characters`}).parse(e)}function O(e){return z$1.string().max(Kt,{message:`Email must be at most ${Kt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Qt(e){return Yt({min:ve,max:q}).parse(e)}function Se(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function Ae(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function ee(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function Xt(e){let t=e.slice(0,q);try{if(!await p.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o=51;for(let n=2;n<=o;n++){let i=`_${n}`,s=`${t.slice(0,q-i.length)}${i}`;try{if(!await p.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,q-i.length)}${i}`;try{if(!await p.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function L(e,t,{throwOnConflict:o=true}={}){if(e!=null&&String(e).trim()!==""){let n=Qt(String(e).trim());if(o){if(await p.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return Xt(n)}let r=t.split("@")[0].padEnd(ve,"_").slice(0,q);return Xt(r)}var Ge=Object.freeze({});function Fe(e){Ge=Object.freeze(Object.assign({},Ge,e));}function w(){return Ge}var Ve=Object.freeze({});function Zt(e){Ve=Object.freeze(Object.assign({},Ve,e));}function b(){return Ve}function xr(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}async function to(e,{user:t,session:o,connectionInfo:r,res:n}){try{if(!o)throw new Error("Session is not initialized");let i$1=r?.ip;i$1&&await C({bucket:"signin",type:"ip",value:i$1});let s=O(e.email),a=z$1.string().parse(e.password),c=await p.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=c?.authMethods?.password?.hash;if(!l)throw eo();if(!c.emails?.find(f=>f.address.toLowerCase()===s)?.verified&&xr())throw new b$2("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");if(!await Ar.compare(a,l))throw eo();return await i(o.authToken,c._id),n&&m(n,o.authToken),b().onAfterLogin?.({provider:"email",user:c,session:o,connectionInfo:r}),b().login?.onSuccess?.(c),{user:ee(c),session:{authToken:o.authToken}}}catch(i){throw i instanceof Error&&(b().onLoginError?.({provider:"email",error:i,session:o,connectionInfo:r}),b().login?.onError?.(i)),i}}async function oo(e,{session:t,res:o}){if(!t)throw new Error("Session is not initialized");await j(t.authToken),o&&n(o);}function eo(){return new Error("Incorrect email/password combination")}async function ro(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await p.requireById(t.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{}),firstName:o.firstName??void 0,lastName:o.lastName??void 0,avatarUrl:o.avatarUrl??void 0}}async function no(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await p.requireById(t.id),r=ke(e);if(await b().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await p.findOne({handle:r.handle,_id:{$ne:o._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await p.updateOne({_id:o._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o={...o,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:ee(o)}}var Be=["google","github"];async function io({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!Be.includes(e))throw new Error(`Invalid provider. Supported providers are: ${Be.join(", ")}.`);let o=await p.requireById(t.id),r=o.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await p.updateOne({_id:o._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var me=new b$1("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user","email"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var ze=[];function so(e){if(ze.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");ze=e;}async function C(e){let{bucket:t,type:o,value:r,message:n}=e,i=ze.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d$1(n):void 0;for(let a of i)await Or(a,r,s);}async function Or(e,t,o){let r=()=>o?o():new d$1(`Rate limit exceeded for ${e.bucket}`),n=await me.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?_r(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw r();await me.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function _r(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function ao({name:e,email:t,verificationUrl:o}){return `
|
|
3
|
+
<p>Hi${e?` ${e}`:""},</p>
|
|
4
|
+
<p>Please verify your email address ${t} by clicking the link below:</p>
|
|
5
|
+
<p><a href="${o}">${o}</a></p>
|
|
6
|
+
<p>If you did not request this, please ignore this email.</p>
|
|
7
|
+
`}async function Tr(e){let t=await r.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");if(!await p.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}}))throw new Error("User not found");let r$1=t.email;if(!r$1)throw new Error("Email not found in token");let n=await p.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},"emails.address":r$1,"emails.verified":{$ne:true}},{$set:{"emails.$.verified":true}},{returnDocument:"after"});if(!n)throw await p.findOne({_id:t.userId,"emails.address":r$1})?new Error("Email is already verified"):new Error("Email address not found for this user");return await r.deleteOne({_id:t._id}),{userDoc:n,email:r$1}}async function co(e){let t=a$2("_system.site.url"),o=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||t||"/";try{let r=z$1.string().parse(e.query.token),{userDoc:n}=await Tr(r);b().onAfterEmailVerification?.({provider:"email",user:n,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await l(n._id);return m(e.res,s),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=verified`}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return r instanceof Error&&(b().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",r)),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent(n)}`}}}async function We({userId:e,email:t,baseUrl:o}){let r$1=a$2("_system.site.url")||o;if(w().provider){let n=w().provider,i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a$1.hours(24));await r.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:s});let a=`${r$1}/api/_internal/auth/verify-email?token=${i}`,l=(w()?.verification?.template||ao)({name:"",email:t,verificationUrl:a}),d=y(l);await n?.sendEmail({to:t,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:d,html:l});}}var qe={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function lo(e,{connectionInfo:t}){let o=O(e.email),r=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r)return qe;let n=r.emails?.find(i=>i.address.toLowerCase()===o);if(!n||n.verified)return qe;if(!w().provider)throw new Error("Email provider is not configured");return await C({bucket:"verification",type:"user",value:r._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await We({userId:r._id,email:o,baseUrl:t?.baseUrl}),qe}async function uo(e,{user:t,session:o,connectionInfo:r}){let n=b();try{let i=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=i,d=O(i.email),m=Ce(i.password),f=r?.ip;if(f&&await C({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await be(d))throw new Error("Please use a permanent email address");let h=await p.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(h){let _=h.emails?.find(N=>N.address.toLowerCase()===d);throw h.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${_?.address}`)}await n.onBeforeSignup?.({email:d,firstName:s,lastName:a,handle:l,provider:"email",connectionInfo:r}),f&&await C({bucket:"signup",type:"ip",value:f});let y=ke({firstName:s,lastName:a,avatarUrl:c,handle:l});await n.validateSignup?.({email:d,password:m,...y});let k;if(y.handle)k=await L(y.handle,d);else if(n.generateHandle){let _=await n.generateHandle({email:d,firstName:y.firstName,lastName:y.lastName});k=await L(_,d,{throwOnConflict:!1});}else k=await L(void 0,d);let T=await Ar.hash(m,10),M;try{M=await p.insertOne({handle:k,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:T}},...y.firstName!==void 0&&{firstName:y.firstName},...y.lastName!==void 0&&{lastName:y.lastName},...y.avatarUrl!==void 0&&{avatarUrl:y.avatarUrl}});}catch(_){throw Se(_)?new Error(`User with email already exists: ${d}`):_}let S=await p.findOne({_id:M.insertedId},{readPreference:"primary"});if(!S)throw new Error("User not found");return await We({userId:M?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:S,session:o,connectionInfo:r}),n.signup?.onSuccess?.(S),M.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}var Je="resetPasswordToken",Nr="/api/_internal/",go={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Nr};async function ho(e){return s.findOne({token:d(e)})}async function mo(e){return s.findOneAndDelete({_id:e})}function Dr({email:e,resetUrl:t}){return `
|
|
8
|
+
<p>Hi,</p>
|
|
9
|
+
<p>We received a request to reset your password for ${e}.</p>
|
|
10
|
+
<p>Click the link below to reset your password:</p>
|
|
11
|
+
<p><a href="${t}">${t}</a></p>
|
|
12
|
+
<p>This link will expire in 1 hour.</p>
|
|
13
|
+
<p>If you did not request this password reset, please ignore this email.</p>
|
|
14
|
+
`}var po={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function wo(e,{connectionInfo:t}){let o=O(e.email),r=t?.ip;r&&await C({bucket:"passwordReset",type:"ip",value:r}),await C({bucket:"passwordReset",type:"email",value:o});let n=await p.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n)return po;let i=w().provider;if(!i)throw new Error("Email provider is not configured");let s$1=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await s.insertOne({userId:n._id,email:o,token:d(s$1),createdAt:c,expiresAt:l});let d$1=a$2("_system.site.url")||t?.baseUrl;if(!d$1)throw new Error("Unable to build password reset link: set _system.site.url (MODELENCE_SITE_URL)");let m=`${d$1}/api/_internal/auth/reset-password?token=${s$1}`,h=(w()?.passwordReset?.template||Dr)({email:o,resetUrl:m,name:""}),y$1=y(h);return await i.sendEmail({to:o,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:y$1,html:h}),po}async function yo(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=Ae(t,w().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await ho(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Je,r,{...go,maxAge:a$1.hours(1)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling password reset landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This password reset link is invalid or has expired.")}`}}}async function Eo(e,t$1){let o=t$1.req?.cookies?.[Je];!o&&e.token&&console.warn("[modelence] resetPassword received a token via request args instead of the httpOnly cookie. This path is deprecated and will be removed; ensure password reset emails link to /api/_internal/auth/reset-password so the token is exchanged server-side.");let r=z$1.string().parse(o??e.token),n=Ce(e.password),i=()=>{t$1.res?.clearCookie(Je,go);},s=await ho(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await mo(s._id),i(),new Error("Reset token has expired");let a=await p.findOne({_id:s.userId});if(!a)throw new Error("User not found");let c=await Ar.hash(n,10);if(!await mo(s._id))throw i(),new Error("Invalid or expired reset token");await p.updateOne({_id:a._id},{$set:{"authMethods.password.hash":c}}),s.email&&await p.updateOne({_id:a._id,"emails.address":s.email},{$set:{"emails.$.verified":true}},{collation:{locale:"en",strength:2}}),await k(a._id);let d=Array.from(new Set((a.emails??[]).map(m=>m.address?.toLowerCase()).filter(m=>!!m)));return d.length>0&&await t.deleteMany({email:{$in:d}}),i(),{success:true,message:"Password has been reset successfully"}}function bo({name:e,email:t,magicLinkUrl:o,code:r}){return `
|
|
15
|
+
<p>Hi${e?` ${e}`:""},</p>
|
|
16
|
+
<p>Click the link below to sign in as ${t}:</p>
|
|
17
|
+
<p><a href="${o}">${o}</a></p>
|
|
18
|
+
<p>Or enter this one-time code in the app:</p>
|
|
19
|
+
<p><strong style="font-size: 24px; letter-spacing: 4px;">${r}</strong></p>
|
|
20
|
+
<p>The link and code can only be used once and will expire in 15 minutes.</p>
|
|
21
|
+
<p>If you did not request this, please ignore this email.</p>
|
|
22
|
+
`}var Qe="magicLinkToken",Hr="/api/_internal/",ko={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Hr},Co=15,vo=6,Gr=5;function Re(e,t){try{Promise.resolve(t?.()).catch(o=>{console.error(`Error in ${e} hook:`,o);});}catch(o){console.error(`Error in ${e} hook:`,o);}}function et(){return !!b().magicLink?.enabled}function So(){return !!b().magicLink?.allowSignup}async function Ao(e){return t.findOne({token:d(e)})}async function tt(e){return t.findOneAndDelete({_id:e})}async function Ke(e){try{await t.insertOne(e);}catch(t){console.error("Failed to restore a magic link token after a failed signup:",t);}}var Ye={success:true,message:"If this email can be used to sign in, a link has been sent"};async function Ro(e,{connectionInfo:t$1}){if(!et())throw new Error("Magic link authentication is not enabled");let o=O(e.email),r=t$1?.ip;r&&await C({bucket:"magicLink",type:"ip",value:r}),await C({bucket:"magicLink",type:"email",value:o});let n=w().provider;if(!n)throw new Error("Email provider is not configured");let i=w().from;if(!i)throw new Error("Email `from` address is not configured");let s=a$2("_system.site.url");if(!s)throw new Error("Unable to build magic link: set _system.site.url (MODELENCE_SITE_URL)");if(!b().allowDisposableEmails&&await be(o))throw new Error("Please use a permanent email address");let a=await p.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(a&&(a.status==="disabled"||a.status==="deleted")||!a&&!So())return Ye;let c=randomBytes(32).toString("hex"),l=randomInt(0,10**vo).toString().padStart(vo,"0"),d$1=Date.now(),m=new Date(d$1),f=new Date(d$1+a$1.minutes(Co));await t.insertOne({email:o,token:d(c),code:d(l),attempts:0,createdAt:m,expiresAt:f});let h=`${s}/api/_internal/auth/magic-link?token=${c}`,k=(w()?.magicLink?.template||bo)({email:o,magicLinkUrl:h,code:l,name:""}),T=y(k);return await n.sendEmail({to:o,from:i,subject:w()?.magicLink?.subject||"Your sign-in link",text:T,html:k}),Ye}async function xo(e){let t=a$2("_system.site.url")||"",o=Ae(t,w().magicLink?.redirectUrl)||"/";try{let r=z$1.string().parse(e.query.token),n=await Ao(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(Qe,r,{...ko,maxAge:a$1.minutes(Co)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling magic link landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This sign-in link is invalid or has expired.")}`}}}var Xe={locale:"en",strength:2};async function Oo(e){let{tokenDoc:t,session:o,connectionInfo:r,res:n,clearCookie:i$1}=e,s=t.email,a=b(),c=So(),l=false;try{let d=await tt(t._id);if(!d)throw i$1(),new Error("Invalid or expired code or magic link");let m$1;if(c)try{if(!await p.findOne({"emails.address":s},{collation:Xe})){l=!0,await a.onBeforeSignup?.({email:s,provider:"magicLink",connectionInfo:r});let _=r?.ip;_&&await C({bucket:"signup",type:"ip",value:_}),m$1=a.generateHandle?await L(await a.generateHandle({email:s}),s,{throwOnConflict:!1}):await L(void 0,s);}}catch(S){throw await Ke(d),S}let f;try{f=await Fr(s,m$1,c);}catch(S){throw await Ke(d),S}let{userDoc:h,isNew:y}=f;if(!h)throw await Ke(d),i$1(),c&&!l?new Error("User account is not active"):(l=!0,new Error("Sign up with magic link is not enabled"));if(l=y,h.status==="disabled"||h.status==="deleted")throw i$1(),new Error("User account is not active");let k=h,T=h.emails?.find(S=>S.address.toLowerCase()===s),M=!y&&!T?.verified;return M&&(k=await p.findOneAndUpdate({_id:h._id,"emails.address":s},{$set:{"emails.$.verified":!0}},{collation:Xe,returnDocument:"after"})??h),await i(o.authToken,k._id),n&&m(n,o.authToken),y?Re("onAfterSignup",()=>a.onAfterSignup?.({provider:"magicLink",user:k,session:o,connectionInfo:r})):(M&&Re("onAfterEmailVerification",()=>a.onAfterEmailVerification?.({provider:"magicLink",user:k,session:o,connectionInfo:r})),Re("onAfterLogin",()=>a.onAfterLogin?.({provider:"magicLink",user:k,session:o,connectionInfo:r}))),i$1(),{user:ee(k),session:{authToken:o.authToken}}}catch(d){if(d instanceof Error){let m=l?"onSignupError":"onLoginError",f=l?a.onSignupError:a.onLoginError;Re(m,()=>f?.({provider:"magicLink",error:d,session:o,connectionInfo:r}));}throw d}}async function Fr(e,t,o){let r=o&&t!==void 0,n=()=>p.findOneAndUpsert({emails:{$elemMatch:{address:e}}},{$setOnInsert:{handle:t,status:"active",emails:[{address:e,verified:true}],createdAt:new Date,authMethods:{}}},{upsert:r,collation:Xe});try{let{doc:i,isNew:s}=await n();return {userDoc:i,isNew:s}}catch(i){if(!Se(i))throw i;let{doc:s}=await n();return {userDoc:s,isNew:false}}}async function _o(e,t){let{session:o,connectionInfo:r,res:n,req:i}=t;if(!o)throw new Error("Session is not initialized");if(!et())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[Qe]),a=()=>{n?.clearCookie(Qe,ko);},c=await Ao(s);if(!c)throw a(),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await tt(c._id),a(),new Error("Code or magic link has expired");return Oo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:a})}async function Lo(e,t$1){let{session:o,connectionInfo:r,res:n}=t$1;if(!o)throw new Error("Session is not initialized");if(!et())throw new Error("Magic link authentication is not enabled");let i=O(e.email),s=z$1.string().parse(e.code).replace(/[\s-]/g,""),a=r?.ip;a&&await C({bucket:"oneTimeCode",type:"ip",value:a}),await C({bucket:"oneTimeCode",type:"email",value:i});let c=await t.findOne({email:i,code:d(s),attempts:{$lt:Gr}});if(!c)throw await t.updateMany({email:i},{$inc:{attempts:1}}),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await tt(c._id),new Error("Code or magic link has expired");return Oo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:()=>{}})}function Po(e){return `${e.bucket}
|
|
23
|
+
${e.type}
|
|
24
|
+
${e.window}`}function Vr(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10},{bucket:"magicLink",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"magicLink",type:"ip",window:a$1.days(1),limit:100},{bucket:"magicLink",type:"email",window:a$1.hours(1),limit:5},{bucket:"magicLink",type:"email",window:a$1.days(1),limit:10},{bucket:"oneTimeCode",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"oneTimeCode",type:"ip",window:a$1.days(1),limit:100},{bucket:"oneTimeCode",type:"email",window:a$1.hours(1),limit:10},{bucket:"oneTimeCode",type:"email",window:a$1.days(1),limit:20}]}function Br(e){let t=[],o=["signup","signupAttempt","signin","verification","passwordReset","magicLink","oneTimeCode"];for(let r of o){let n=e[r];if(n!==void 0)for(let i of n)t.push({bucket:r,...i});}return t}function ot(e={}){let t=Vr(),o=Br(e),r=new Map;for(let s of o)r.set(Po(s),s);let n=[],i=new Set;for(let s of t){let a=Po(s),c=r.get(a);c!==void 0?(n.push(c),i.add(a)):n.push(s);}for(let[s,a]of r)i.has(s)||n.push(a);return n}var rt=new a("_system.user",{stores:[p,q$1,r,s,t],queries:{getOwnProfile:ro},mutations:{signupWithPassword:uo,loginWithPassword:to,logout:oo,resendEmailVerification:lo,sendResetPasswordToken:wo,resetPassword:Eo,sendMagicLink:Ro,loginWithMagicLink:_o,loginWithOneTimeCode:Lo,updateProfile:no,unlinkOAuthProvider:io},cronJobs:{updateDisposableEmailList:qt},rateLimits:ot(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:true},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:co}},{path:"/api/_internal/auth/reset-password",handlers:{get:yo}},{path:"/api/_internal/auth/magic-link",handlers:{get:xo}}]});var zr={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function qr(e,t){if(t==="number"){let o=Number(e);if(isNaN(o))throw new Error(`Invalid number value for config: ${e}`);return o}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function Wr(e,t){let o=[];for(let[r,n]of Object.entries(e)){let i=process.env[r],s=t[n];if(i){let a=s?.type??"string";o.push({key:n,type:a,value:qr(i,a)});}}return o}function xe(e,t="withoutRemoteServer"){let o=zr[t];return Wr(o,e)}async function To({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=(o??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await P("/api/connect","POST",{hostname:Jr.hostname(),containerId:n,dataModels:i,configSchema:e,cronJobsMetadata:t,roles:r});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Mo(){return P("/api/configs","GET")}async function Io(){return await P("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function P(e,t,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text(),a,c=s;try{a=JSON.parse(s);let d=a.error;if(typeof d=="string")c=d;else if(d&&typeof d=="object"){let m=d.message;typeof m=="string"&&(c=m);}}catch{}let l=new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${c}`);throw a!==void 0&&(l.responseBody=a),l.status=i.status,l}if(!(i.status===204||i.headers?.get("content-length")==="0"))return await i.json()}var nt=false,Kr=a$1.seconds(10);function Uo(){setInterval(async()=>{if(!nt){nt=true;try{await Io();}catch(e){console.error("Error syncing status",e);}try{await Yr();}catch(e){console.error("Error syncing config",e);}nt=false;}},Kr);}function it(e){c$1(e),c$1(xe(d$2(),"withRemoteServer"));}async function Yr(){let{configs:e}=await Mo();it(e);}var W=new b$1("_modelenceLocks",{schema:{_id:c.string(),instanceId:c.string(),acquiredAt:c.date(),resource:c.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var J={},No=a$1.seconds(10),Ho=randomBytes(32).toString("base64url"),Zr=a$1.seconds(30),te=new Map,st=e=>e instanceof MongoError&&e.code===11e3,Do=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),en=async({error:e,resource:t})=>{if(Do(e,"resource"))return true;if(Do(e,"_id"))return false;let o=await W.findOne({resource:t});return !!o&&o._id!==t},$o=async({resource:e,staleThresholdDate:t,instanceId:o})=>{let r=await W.upsertOne({_id:e,$or:[{instanceId:o},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:o,acquiredAt:new Date},$setOnInsert:{_id:e}});return r.upsertedCount>0||r.modifiedCount>0},Go=async({resource:e,instanceId:t,staleThresholdDate:o})=>{let r=o?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:o}}]}:{resource:e,instanceId:t};return (await W.deleteOne(r)).deletedCount>0},tn=e=>{let t=e,o=te.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),te.delete(t));},jo=({resource:e,lockDuration:t,instanceId:o})=>{let r=Math.floor(t/3),n=e,i=te.get(n);if(i&&!i.stopRequested&&i.heartbeatInterval===r&&i.lockDuration===t)return;i&&(i.stopRequested=true,i.timer&&(clearTimeout(i.timer),i.timer=null),te.delete(n));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:r},a=()=>{s.timer=setTimeout(()=>{K(e,{lockDuration:t,bypassCache:true,instanceId:o}).then(c=>{c||(s.stopRequested=true,j$1(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:o}));}).finally(()=>{if(s.stopRequested){te.delete(n);return}a();});},r);};te.set(n,s),a();};async function K(e,{lockDuration:t=Zr,successfulLockCacheDuration:o=No,failedLockCacheDuration:r=No,heartbeat:n,bypassCache:i,instanceId:s=Ho}={}){let a=Date.now();if(!i&&J[e]&&a<J[e].expiresAt)return J[e].value&&n&&jo({resource:e,lockDuration:t,instanceId:s}),J[e].value;let c=new Date(a-t);j$1(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await on({resource:e,staleThresholdDate:c,instanceId:s});return J[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&jo({resource:e,lockDuration:t,instanceId:s}),j$1(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):j$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return J[e]={value:false,expiresAt:a+r},j$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var on=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await $o({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(st(r)&&await en({error:r,resource:e})){if(!await Go({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await $o({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(st(i))return false;throw i}}if(st(r))return false;throw r}};async function pe(e,{instanceId:t=Ho}={}){tn(e);try{let o=await W.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await Go({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete J[e];}}var Y={},at=null,ct=new b$1("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Vo(e,{description:t="",interval:o,timeout:r=Math.min(Math.max(o,a$1.minutes(1)),a$1.days(1)),handler:n}){if(Y[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(at)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);Y[e]={alias:e,params:{description:t,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function Bo(){if(at)throw new Error("Cron jobs already started");let e=Object.keys(Y);if(e.length>0){let t={alias:{$in:e}},o=await ct.fetch(t),r=Date.now();o.forEach(n=>{let i=Y[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(Y).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),at=setInterval(rn,a$1.seconds(1));}}async function rn(){let e=Date.now();await K("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(Y).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<e&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=e&&await nn(o);});}async function nn(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await ct.updateOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)}});let i=m$1("cron",`cron:${t}`);try{await r(),Fo(n,o),i.end("success");}catch(s){Fo(n,o);let a=s instanceof Error?s:new Error(String(s));n$1(a),i.end("error"),console.error(`Error in cron job '${t}':`,s);}}function Fo(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function zo(){return Object.values(Y).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var qo=new a("_system.cron",{stores:[ct]});function Wo(e){let t=[...new Set(e)],o=new Map;for(let i of t){let s=i.getChainRoot();o.set(s,s.getChainTail());}let r=[...new Set(o.values())],n=new Map;for(let[i,s]of o){let a=s.getName(),c=n.get(a);if(c!==void 0&&c!==i)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);n.set(a,i);}return {storesToInit:t,effectiveStores:r}}var lt=new a("_system.lock",{stores:[W]});var fe=new b$1("_modelenceMigrations",{schema:{version:c.number(),status:c.enum(["completed","failed"]),description:c.string().optional(),output:c.string().optional(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function dt(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await K("migrations")){k$1("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let o=e.map(({version:s})=>s),r=await fe.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i=e.filter(({version:s})=>!n.has(s));if(i.length===0)return;k$1(`Running migrations (${i.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i){k$1(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),m=15*1024*1024,f=d.length>m?d.slice(0,m)+`
|
|
25
|
+
[Output truncated - exceeded size limit]`:d;await fe.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:f,appliedAt:new Date}}),k$1(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await fe.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),k$1(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await pe("migrations");}}}function Jo(e){setTimeout(()=>{dt(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var Ko=new a("_system.migration",{stores:[fe]});var Yo=new a("_system.rateLimit",{stores:[me]});async function sn({filePath:e,contentType:t,visibility:o}){return await P("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function an(e){await P("/api/files/delete","POST",{filePath:e});}async function cn(e){return await P("/api/files/download","POST",{filePath:e})}async function ln(e){return await P("/api/files/url","POST",{filePath:e})}var Qo=new a("_system.files",{});function ut(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var ge="./.modelence/build/client".replace(/\\/g,"/"),Zo="./.modelence/build/ssr".replace(/\\/g,"/"),er="/index.tsx",gn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,hn="</head>",mt=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await Cn(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev())console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config);else if(this.ssrEnabled){let o=Q.resolve(process.cwd(),Zo,"index.mjs");if(!Oe.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
|
|
26
|
+
|
|
27
|
+
This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
|
|
28
|
+
\u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
|
|
29
|
+
\u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-C7DEK6NV.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[V.static(ge,t)];return this.config?.publicDir&&o.push(V.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&wn(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:i},{getCallContext:s},a]=await Promise.all([import('./render-CBIFY4DG.js'),import('./server-LA5VRAGR.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);bn(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:m,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:h,rootOpenTag:y,epilogue:k}=yn(r),T=En(h,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(T),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${ut(d)}</script>`),o.write(y),await m(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${ut(f())}</script>`),o.end(k);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,er):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ge)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Q.resolve(process.cwd(),"src/client/index.html"),r=Oe.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Q.resolve(process.cwd(),ge,"index.html");this.prodTemplateCache=Oe.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-J347DR2B.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(er),t()}return this.prodEntryLoaded||(await import(Q.resolve(process.cwd(),Zo,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:ge});}isDev(){return process.env.NODE_ENV!=="production"}};function wn(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function yn(e){let t=e.match(gn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function En(e,t){if(!t)return e;let o=e.lastIndexOf(hn);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function bn(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function vn(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function kn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Cn(e,t={}){let o=process.cwd(),r=await vn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Oe.existsSync(Q.join(o,a))),i=[fn(),Sn()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:Q.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:ge,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Q.resolve(o,"src").replace(/\\/g,"/")}}});return kn(s,r)}function Sn(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var _e=new mt;function An(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function Rn(e){if(e)return Array.isArray(e)?e:[e]}function xn(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:An(e.from),replyTo:Rn(e.replyTo)}}function On(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var tr={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await P("/api/email/send","POST",xn(e));}catch(t){throw On(t)}}};var pt=Object.freeze({});function or(e){pt=Object.freeze(Object.assign({},pt,e));}function rr(){return pt}var ft=Object.freeze({});function nr(e){ft=Object.freeze(Object.assign({},ft,e));}function Le(){return ft}async function Tn({modules:e$1=[],roles:t={},defaultRoles:o$1={},server:r=_e,migrations:n=[],email:i={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===_e&&_e.enableSsr(),ir.config(),ir.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;Vn().then(()=>{}).catch(()=>{});for(let N of e$1)if(N.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${N.name}'
|
|
30
|
+
|
|
31
|
+
The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
|
|
32
|
+
|
|
33
|
+
Rename your module to something that does not start with '_system.'`);let m=[rt,o,qo,Ko,Yo,le,lt,Qo],f$1=[...m,...e$1];f(),In(m),Mn(e$1),u(t,o$1);let h$1=Hn(f$1);e(h$1);let y=Un(f$1),k=Nn(f$1);Gn(f$1),rt.rateLimits=ot(s.rateLimits);let T=Dn(f$1);so(T);let{storesToInit:M,effectiveStores:S}=Wo(y);if(d){let{configs:N,environmentId:mr,appAlias:pr,environmentAlias:fr,telemetry:gr}=await To({configSchema:h$1,cronJobsMetadata:zo(),stores:S,roles:t});it(N),g({environmentId:mr,appAlias:pr,environmentAlias:fr,telemetry:gr});}else c$1(xe(h$1));if(d&&!i.provider?Fe({...i,provider:tr}):Fe(i),Zt(s),or(a),nr({...c,provider:c.provider||zt}),z()){await Vt();let N=[...new Set([...M,...S])];Fn(N),await jn(S,n);}else Jo(n);d&&(await h(),Uo()),Bo().catch(console.error),await sr(r,{combinedModules:f$1,channels:k});}function Mn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))z$2(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))A(`${t.name}.${o}`,r);}}function In(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))B(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))C$1(`${t.name}.${o}`,r);}}function Un(e){return e.flatMap(t=>t.stores)}function Nn(e){return e.flatMap(t=>t.channels)}function Dn(e){return e.flatMap(t=>t.rateLimits)}function $n(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var gt="migrations";async function jn(e,t){if(!await K(gt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await ht(a,"full");for(let a of n)await ht(a,"drop-only");}catch(a){throw await pe(gt),a}let i=(async()=>{for(let a of n)await ht(a,"create-only");})(),s=dt(t,{lockMode:"skip"});Promise.allSettled([i,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await pe(gt);});}async function ht(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){$n(o,r);}}function Hn(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function Gn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))Vo(`${t.name}.${o}`,r);}function Fn(e){let t=Ee();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function Vn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Bn(),n=await import('./package-RFIDFU5I.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Jr.hostname(),environmentId:o})});}}async function Bn(){try{let e=Q.join(process.cwd(),"package.json"),t=await _n.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function ar(e){await r.deleteMany({userId:e}),await s.deleteMany({userId:e});let t$1=await p.findOne({_id:e}),o=Array.from(new Set((t$1?.emails??[]).map(r=>r.address?.toLowerCase()).filter(r=>!!r)));o.length>0&&await t.deleteMany({email:{$in:o}});}async function qn(e){await ar(e),await p.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Wn(e){await ar(e),await p.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var wt=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Le().provider;if(!r){l$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function Jn(e){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(e)}async function Pe(e){return !e||typeof e!="string"?null:f$1(e)}function v(e,t,o){let r=b(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function yt(e,t){let{authToken:o}=await l(t);m(e,o),e.status(302),e.redirect("/");}async function Yn(e,t,o,r,n){let i=b();try{if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o;Object.keys(s).length>0&&(await p.updateOne({_id:o._id},{$set:s}),a={...o,...s}),await yt(e,o._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function Qn(e,t,o,r,n){let i=b();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}if(!o.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await p.updateOne({_id:o._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){v(e,400,"User with this email already exists. Please log in instead.");return}await yt(e,o._id);let m={...o,...c,authMethods:{...o.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:m,session:r,connectionInfo:n}),i.login?.onSuccess?.(m);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function Xn(e,t,o,r){let n=b();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await L(l,t.email,{throwOnConflict:!1});}else i=await L(void 0,t.email);let s={handle:i,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await p.insertOne(s);await yt(e,a.insertedId);let c=await p.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Te(e,t,o){let r=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return Yn(t,o,r,n,i);if(!o.email){v(t,400,`Email address is required for ${o.providerName} authentication.`);return}let s;try{s=await p.findOne({"emails.address":o.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=b();c.onSignupError?.({provider:o.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?Qn(t,o,s,n,i):Xn(t,o,n,i)}function x(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Me(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Ie(e,t,o,r){let n=b(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){x(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){x(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o.providerName}.id`;if((await p.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o.id}]},{$set:{[l]:o.id}})).matchedCount===0){let f=await p.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),x(t),v(t,400,"User account is not active.");return}let h=f?.authMethods?.[o.providerName]?.id;if(h&&h!==o.id){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`User already has a different ${o.providerName} account linked`),session:i,connectionInfo:s})),x(t),v(t,400,`You have already linked a different ${o.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`Unexpected OAuth linking state for ${o.providerName}`),session:i,connectionInfo:s})),x(t),v(t,400,`Unable to link ${o.providerName} account.`);return}let m=await p.findOne({_id:c},{readPreference:"primary"});m&&oe(()=>n.onAfterOAuthLink?.({provider:o.providerName,user:m,session:i,connectionInfo:s})),x(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),v(t,400,`This ${o.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),!t.headersSent)throw l}}function Ue(e){return !e||typeof e!="string"?null:e}async function ti(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function oi(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ri(e,t){let o=Ue(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Me(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await ti(o,s,a,c),d=await oi(l.access_token),m={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Ie(e,t,m,i):await Te(e,t,m);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function ni(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Pe(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,ri),e}var lr=ni;async function ai(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ci(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function li(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function di(e,t){return e.email?e.email:(await li(t)).find(r=>r.primary&&r.verified)?.email??null}async function ui(e,t){let o=Ue(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Me(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await ai(o,s,a,c),d=await ci(l.access_token),m=await di(d,l.access_token);if(!m){n==="link"&&x(t),v(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let f=d.name?d.name.trim().split(/\s+/):[],h=f[0]||void 0,y=f.length>1?f.slice(1).join(" "):void 0,k={id:String(d.id),email:m,emailVerified:!0,providerName:"github",firstName:h,lastName:y,avatarUrl:d.avatar_url||void 0};n==="link"?await Ie(e,t,k,i):await Te(e,t,k);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function mi(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(h=>h.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Pe(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let m=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",m,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,ui),e}var dr=mi;function ur(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&z())try{let{session:l,user:d}=await w$1(s);a={session:l,user:d};}catch{}let c=m$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:i$1(r.query),body:i$1(r.body),params:i$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.contentType&&n.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,m])=>{n.setHeader(d,m);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function gi(e){let t=[];if(!e)return t.push(V.json({limit:"16mb"})),t.push(V.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(V.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(V.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(V.raw(r));}return t}function hi(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=gi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,ur(c,n,l));});}}async function sr(e,{combinedModules:t,channels:o}){let r=V();r.use(pi()),r.use(Ei()),hi(r,t),r.use(V.json({limit:"16mb"})),r.use(V.urlencoded({extended:true,limit:"16mb"})),r.use(lr()),r.use(dr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}c.cookie("oauthLinkToken",l.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),c.json({ok:true});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await e$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await ne(a,c);try{let m=a$3(await D(l,a.body.args,d));c.json({data:m,typeMap:b$3(m)});}catch(m){wi(c,l,m);}});let n=fi.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.all("*",(a,c,l)=>{Promise.resolve(e.handler(a,c)).catch(l);}),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let i=Le()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{k$1("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
|
|
34
|
+
Application started on ${a}
|
|
35
|
+
`);});}async function ne(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=F.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=F.object({screenWidth:F.number(),screenHeight:F.number(),windowWidth:F.number(),windowHeight:F.number(),pixelRatio:F.number(),orientation:F.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:vi(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:bi(e)};if(!!z()){let{session:l,user:d,roles:m}=await w$1(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:m,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:v$1(),req:e,res:t}}function wi(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=yi(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function yi(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function Ei(){let{frameAncestors:e}=rr(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function bi(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function vi(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
|
|
36
|
+
export{C as a,sn as b,an as c,cn as d,ln as e,sr as f,ne as g,Tn as h,qn as i,Wn as j,wt as k,Jn as l};//# sourceMappingURL=chunk-OFRRQZVE.js.map
|
|
37
|
+
//# sourceMappingURL=chunk-OFRRQZVE.js.map
|