modelence 0.6.2 → 0.6.3

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {s}from'../chunk-RBP3NX7L.js';import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import K,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ie from'archiver';import Z from'open';var b=".modelence.env";async function F(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function _(e){return String(e).replace(/"/g,'\\"')}async function R(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await R(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await F(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${_(n)}"`).join(`
2
+ import {s}from'../chunk-4WVT64MC.js';import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import K,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ie from'archiver';import Z from'open';var b=".modelence.env";async function F(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function _(e){return String(e).replace(/"/g,'\\"')}async function R(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await R(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await F(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${_(n)}"`).join(`
3
3
  `);await promises.writeFile(o,s.trim()+`
4
4
  `),console.log(`Successfully configured ${b} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,N=null;function A(){if(!w)throw new Error("Environment variables not loaded");return w}function D(){if(!N)throw new Error("Configuration not loaded");return N}function d(e){return `${A().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function h(){let{serverDir:e,serverEntry:o}=D();return join(e,o).replace(/\\/g,"/")}function S(){return D().postBuildCommand}function O(e){let o=x("build");return o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function E(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");N=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function Y(){let e=S();if(e){console.log("Running post-build command..."),execSync(e);return}await H();}async function H(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:K.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function Q(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[h()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=O();await T.rm(e,{recursive:!0,force:!0}),await Q(),await Y(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function j(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Z(t);let r=await te(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function te(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await ne(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function ne(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function P(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await v(),await se(r);let{token:i}=await j(),{bundleName:s}=await ae(e.app,e.env,r,i);await promises.unlink(r),await ce(e.app,e.env,s,join(".modelence","build","app.mjs"),i);}async function se(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=ie("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,u)=>{o.on("close",n),o.on("error",u),t.on("error",u);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.file(p(n),{name:n});for(let n of s)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.directory(p(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ae(e,o,t,r){let i=await fetch(d("/api/upload-bundle"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:s,bundleName:a}=await i.json(),n=await promises.readFile(t),u=await fetch(s,{method:"PUT",body:n,headers:{"Content-Type":"application/zip"}});if(!u.ok)throw new Error(`Failed to upload bundle: ${u.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${a}`),{bundleName:a}}async function ce(e,o,t,r,i){let s=await fetch(d("/api/deploy"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!s.ok)throw new Error(`Failed to trigger deployment: ${s.statusText}`);let{deploymentUrl:a}=await s.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${a}`);}function B(){console.log("Starting Modelence dev server...");let e=h(),o=K.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var f=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");f.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await k(e);});f.command("build").description("Build the application").action(async()=>{await E(),await v();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").action(async e=>{await E(),await P(e);});f.command("dev").description("Start development server").action(async()=>{await E(),B();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
5
5
  //# sourceMappingURL=modelence.js.map
@@ -1,3 +1,3 @@
1
- var s="module",i="modelence",o="0.6.2",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./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"}},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@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",react:"^19.0.0","react-dom":"^19.0.0"},v={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.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"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
- export{s as a,i as b,o as c,p as d,r as e,n as f,d as g,c as h,l as i,a as j,m as k,y as l,u as m,g as n,h as o,b as p,v as q,j as r,x as s};//# sourceMappingURL=chunk-RBP3NX7L.js.map
3
- //# sourceMappingURL=chunk-RBP3NX7L.js.map
1
+ var s="module",i="modelence",o="0.6.3",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./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"}},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@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",react:"^19.0.0","react-dom":"^19.0.0"},v={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.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"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
+ export{s as a,i as b,o as c,p as d,r as e,n as f,d as g,c as h,l as i,a as j,m as k,y as l,u as m,g as n,h as o,b as p,v as q,j as r,x as s};//# sourceMappingURL=chunk-4WVT64MC.js.map
3
+ //# sourceMappingURL=chunk-4WVT64MC.js.map
@@ -1 +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,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,OAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,kBACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,EACAC,CAAAA,CAAO,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,YAAe,6BACjB,CAAA,CACAC,EAAc,CACZ,IAAA,CAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,yBACXC,CAAAA,CAAQ,CACN,IAAO,+CACT,CAAA,CACAC,CAAAA,CAAY,uBAAA,CACZC,CAAAA,CAAmB,CACjB,kBAAmB,QAAA,CACnB,eAAA,CAAiB,SACjB,sBAAA,CAAwB,QAAA,CACxB,iBAAkB,QAAA,CAClB,iBAAA,CAAmB,SAAA,CACnB,aAAA,CAAe,SAAA,CACf,gCAAA,CAAkC,UAClC,cAAA,CAAgB,SAAA,CAChB,mBAAoB,SAAA,CACpB,kBAAA,CAAoB,SACpB,kCAAA,CAAoC,SAAA,CACpC,2BAAA,CAA6B,SAAA,CAC7B,KAAA,CAAS,SAAA,CACT,YAAa,SACf,CAAA,CACAC,EAAgB,CACd,0BAAA,CAA4B,SAC5B,sBAAA,CAAwB,QAAA,CACxB,QAAA,CAAY,QAAA,CACZ,MAAA,CAAU,QAAA,CACV,UAAa,SAAA,CACb,eAAA,CAAiB,SACjB,MAAA,CAAU,SAAA,CACV,mBAAoB,QAAA,CACpB,OAAA,CAAW,SAAA,CACX,UAAA,CAAY,SAAA,CACZ,IAAA,CAAQ,SACR,OAAA,CAAW,QAAA,CACX,KAAQ,SAAA,CACR,QAAA,CAAY,SACZ,yBAAA,CAA2B,QAAA,CAC3B,WAAA,CAAa,QAAA,CACb,kBAAA,CAAoB,QAAA,CACpB,KAAQ,QAAA,CACR,GAAA,CAAO,UACP,UAAA,CAAc,QAAA,CACd,KAAQ,QAAA,CACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,SAAA,CACX,uBAAA,CAAyB,UACzB,GAAA,CAAO,SAAA,CACP,QAAW,QACb,CAAA,CACAC,EAAoB,CAClB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CAzFFC,EAAA,CACE,IAAA,CAAAlB,EACA,IAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,MAAAC,CAAAA,CAIA,GAAA,CAAAC,EAGA,OAAA,CAAAC,CAAAA,CAOA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAgBA,YAAA,CAAAC,CAAAA,CA4BA,gBAAA,CAAAC,CAIF","file":"chunk-RBP3NX7L.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.6.2\",\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 \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\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 \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\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 \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\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\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.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 \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
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,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,OAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,kBACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,EACAC,CAAAA,CAAO,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,YAAe,6BACjB,CAA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C,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,MAAAC,CAAAA,CAIA,GAAA,CAAAC,EAGA,OAAA,CAAAC,CAAAA,CAOA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAgBA,YAAA,CAAAC,CAAAA,CA4BA,gBAAA,CAAAC,CAIF","file":"chunk-4WVT64MC.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.6.3\",\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 \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\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 \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\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 \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\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\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.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 \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-RBP3NX7L.js';//# sourceMappingURL=package-6GIFEHJQ.js.map
2
- //# sourceMappingURL=package-6GIFEHJQ.js.map
1
+ export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-4WVT64MC.js';//# sourceMappingURL=package-5ZEGPCTP.js.map
2
+ //# sourceMappingURL=package-5ZEGPCTP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-6GIFEHJQ.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-5ZEGPCTP.js"}
package/dist/server.js CHANGED
@@ -11,8 +11,8 @@ import {a as a$2}from'./chunk-DN5SVAO2.js';import {d,a as a$3}from'./chunk-C3UES
11
11
  <p><a href="${e}">${e}</a></p>
12
12
  <p>This link will expire in 1 hour.</p>
13
13
  <p>If you did not request this password reset, please ignore this email.</p>
14
- `}var ae={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Xe(t,{connectionInfo:e}){let o=I(t.email),n=await m.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ae;let r=g().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await v.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,p=`${io(a$1,g().passwordReset?.redirectUrl)}?token=${i}`,d=(g()?.passwordReset?.template||so)({email:o,resetUrl:p,name:""}),C=V(d);return await r.sendEmail({to:o,from:g()?.from||"noreply@modelence.com",subject:g()?.passwordReset?.subject||"Reset your password",text:C,html:d}),ae}async function et(t,{}){let e=z$1.string().parse(t.token),o=K(t.password),n=await v.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let r=await m.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await Qt.hash(o,10);return await m.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var tt=new y("_system.user",{stores:[m,L,_,v],queries:{getOwnProfile:Ze},mutations:{signupWithPassword:Ye,loginWithPassword:Ke,logout:Ge,sendResetPasswordToken:Xe,resetPassword:et},cronJobs:{updateDisposableEmailList:Je},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],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:false},"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:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Be}}]});async function ot({configSchema:t,cronJobsMetadata:e,stores:o}){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 r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),i=await ce("/api/connect","POST",{hostname:ao.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function nt(){return await ce("/api/configs","GET")}async function rt(){return await ce("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ce(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var le=false,co=a.seconds(10);function it(){setInterval(async()=>{if(!le){le=true;try{await rt();}catch(t){console.error("Error syncing status",t);}try{await lo();}catch(t){console.error("Error syncing config",t);}le=false;}},co);}async function lo(){let{configs:t}=await nt();c$1(t);}var uo=a.minutes(1),mo=a.seconds(10),O={},de,z=new w("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional(),lock:c.object({containerId:c.string(),acquireDate:c.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function at(t,{description:e="",interval:o,timeout:n=uo,handler:r}){if(O[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(de)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);O[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function ct(){if(de)throw new Error("Cron jobs already started");let t=Object.keys(O);if(t.length>0){let e={alias:{$in:t}},o=await z.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>z.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await po(mo);let n=await z.fetch(e),r=Date.now();n.forEach(i=>{let s=O[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(O).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),de=setInterval(fo,a.seconds(1));}}function po(t){return new Promise(e=>setTimeout(e,t))}async function fo(){let t=Date.now();Object.values(O).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await ho(e);});}async function ho(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now();let i=j$1("cron",`cron:${e}`);n().then(()=>{st(r,o),i.end("success");}).catch(s=>{st(r,o),k$1(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await z.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function st(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function lt(){return Object.values(O).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var dt=new y("_system.cron",{stores:[z]});var ue={};function me(t,e){return R(),ft(t),G("query",t,e)}function ut(t,e){return R(),ft(t),G("mutation",t,e)}function mt(t,e){return R(),ht(t),G("query",t,e)}function pt(t,e){return R(),ht(t),G("mutation",t,e)}function ft(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ht(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function G(t,e,o){if(R(),ue[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];ue[e]={type:t,name:e,handler:n,permissions:r};}async function gt(t,e,o){R();let n=ue[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=j$1("method",`method:${t}`,{type:r,args:e}),a;try{Ue(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var Z=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function wt(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await Z.fetch({version:{$in:e}}),n=new Set(o.map(({version:i})=>i)),r=t.filter(({version:i})=>!n.has(i));if(r.length!==0){console.log(`Running migrations (${r.length})...`);for(let{version:i,description:s,handler:a}of r)console.log(`Running migration v${i}: ${s}`),await Z.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var yt=new y("_system.migration",{stores:[Z]});var bt=new y("_system.rateLimit",{stores:[N]});var fe=class{async init(){this.config=await vo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ye.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ye.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function So(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function xo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.filter(r=>{if(!r||typeof r!="object")return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function vo(){let t=process.cwd(),e=await So(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Eo.existsSync(pe.join(t,i))),n=[Co(),Ro()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:pe.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":pe.resolve(t,"src").replace(/\\/g,"/")}}});return xo(r,e)}function Ro(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Et=new fe;async function St(t,e){let{authToken:o}=await ne(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Mo(t,e){let o=t.user,n=await m.findOne({"authMethods.google.id":o.id}),{session:r,connectionInfo:i}=await ge(t);try{if(n){await St(e,n._id),h().onAfterLogin?.({user:n,session:r,connectionInfo:i}),h().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{let s=o.emails[0]&&o.emails[0]?.value;if(s||e.status(400).json({error:"Email address is required for Google authentication."}),await m.findOne({"emails.address":s},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let l=await m.insertOne({handle:s,emails:[{address:s,verified:!0}],createdAt:new Date,authMethods:{google:{id:o.id}}});await St(e,l.insertedId);let p=await m.findOne({_id:l.insertedId},{readPreference:"primary"});p&&(h().onAfterSignup?.({user:p,session:r,connectionInfo:i}),h().signup?.onSuccess?.(p));}catch(s){throw s instanceof Error&&(h().onSignupError?.({error:s,session:r,connectionInfo:i}),h().signup?.onError?.(s)),s}}function To(){let t=Router(),e=!!a$1("_system.user.auth.google.enabled"),o=String(a$1("_system.user.auth.google.clientId")),n=String(a$1("_system.user.auth.google.clientSecret"));return !e||!o||!n||(he.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(r,i,s,a)=>a(null,s))),t.get("/api/_internal/auth/google",he.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",he.authenticate("google",{session:false}),Mo)),t}var xt=To;function vt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([r,i])=>{o.setHeader(r,i);}),o.send(n.data);}catch(n){n instanceof a$3?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var we=Object.freeze({});function Rt(t){we=Object.freeze(Object.assign({},we,t));}function Q(){return we}function Ao(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,vt(a));});}}async function Dt(t,{combinedModules:e,channels:o}){let n=ye();n.use(ye.json()),n.use(ye.urlencoded({extended:true})),n.use(_o()),n.use(he.initialize()),n.use(xt()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:p}=a.params,b=await ge(a);try{let d=await gt(p,a.body.args,b);l.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${p}:`,d),d instanceof a$3)l.status(d.status).send(d.message);else if(d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let M=d.flatten(),Y=Object.entries(M.fieldErrors).map(([A,ee])=>`${A}: ${(ee??[]).join(", ")}`).join("; "),X=M.formErrors.join("; "),J=[Y,X].filter(Boolean).join("; ");l.status(400).send(J);}else l.status(500).send(d instanceof Error?d.message:String(d));}}),Ao(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=ko.createServer(n),i=Q()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h$1("Application started",{source:"app"}),console.log(`
14
+ `}var ae={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Xe(t,{connectionInfo:e}){let o=I(t.email),n=await m.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ae;let r=g().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await v.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,p=`${io(a$1,g().passwordReset?.redirectUrl)}?token=${i}`,d=(g()?.passwordReset?.template||so)({email:o,resetUrl:p,name:""}),C=V(d);return await r.sendEmail({to:o,from:g()?.from||"noreply@modelence.com",subject:g()?.passwordReset?.subject||"Reset your password",text:C,html:d}),ae}async function et(t,{}){let e=z$1.string().parse(t.token),o=K(t.password),n=await v.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let r=await m.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await Qt.hash(o,10);return await m.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var tt=new y("_system.user",{stores:[m,L,_,v],queries:{getOwnProfile:Ze},mutations:{signupWithPassword:Ye,loginWithPassword:Ke,logout:Ge,sendResetPasswordToken:Xe,resetPassword:et},cronJobs:{updateDisposableEmailList:Je},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],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:false},"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:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Be}}]});async function ot({configSchema:t,cronJobsMetadata:e,stores:o}){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 r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),i=await ce("/api/connect","POST",{hostname:ao.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function nt(){return await ce("/api/configs","GET")}async function rt(){return await ce("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ce(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var le=false,co=a.seconds(10);function it(){setInterval(async()=>{if(!le){le=true;try{await rt();}catch(t){console.error("Error syncing status",t);}try{await lo();}catch(t){console.error("Error syncing config",t);}le=false;}},co);}async function lo(){let{configs:t}=await nt();c$1(t);}var uo=a.minutes(1),mo=a.seconds(10),O={},de,z=new w("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional(),lock:c.object({containerId:c.string(),acquireDate:c.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function at(t,{description:e="",interval:o,timeout:n=uo,handler:r}){if(O[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(de)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);O[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function ct(){if(de)throw new Error("Cron jobs already started");let t=Object.keys(O);if(t.length>0){let e={alias:{$in:t}},o=await z.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>z.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await po(mo);let n=await z.fetch(e),r=Date.now();n.forEach(i=>{let s=O[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(O).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),de=setInterval(fo,a.seconds(1));}}function po(t){return new Promise(e=>setTimeout(e,t))}async function fo(){let t=Date.now();Object.values(O).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await ho(e);});}async function ho(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now();let i=j$1("cron",`cron:${e}`);n().then(()=>{st(r,o),i.end("success");}).catch(s=>{st(r,o),k$1(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await z.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function st(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function lt(){return Object.values(O).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var dt=new y("_system.cron",{stores:[z]});var ue={};function me(t,e){return R(),ft(t),G("query",t,e)}function ut(t,e){return R(),ft(t),G("mutation",t,e)}function mt(t,e){return R(),ht(t),G("query",t,e)}function pt(t,e){return R(),ht(t),G("mutation",t,e)}function ft(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ht(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function G(t,e,o){if(R(),ue[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];ue[e]={type:t,name:e,handler:n,permissions:r};}async function gt(t,e,o){R();let n=ue[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=j$1("method",`method:${t}`,{type:r,args:e}),a;try{Ue(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var Z=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function wt(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await Z.fetch({version:{$in:e}}),n=new Set(o.map(({version:i})=>i)),r=t.filter(({version:i})=>!n.has(i));if(r.length!==0){console.log(`Running migrations (${r.length})...`);for(let{version:i,description:s,handler:a}of r)console.log(`Running migration v${i}: ${s}`),await Z.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var yt=new y("_system.migration",{stores:[Z]});var bt=new y("_system.rateLimit",{stores:[N]});var fe=class{async init(){this.config=await vo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ye.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ye.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function So(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function xo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object")return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function vo(){let t=process.cwd(),e=await So(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Eo.existsSync(pe.join(t,i))),n=[Co(),Ro()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:pe.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":pe.resolve(t,"src").replace(/\\/g,"/")}}});return xo(r,e)}function Ro(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Et=new fe;async function St(t,e){let{authToken:o}=await ne(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Mo(t,e){let o=t.user,n=await m.findOne({"authMethods.google.id":o.id}),{session:r,connectionInfo:i}=await ge(t);try{if(n){await St(e,n._id),h().onAfterLogin?.({user:n,session:r,connectionInfo:i}),h().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{let s=o.emails[0]&&o.emails[0]?.value;if(s||e.status(400).json({error:"Email address is required for Google authentication."}),await m.findOne({"emails.address":s},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let l=await m.insertOne({handle:s,emails:[{address:s,verified:!0}],createdAt:new Date,authMethods:{google:{id:o.id}}});await St(e,l.insertedId);let p=await m.findOne({_id:l.insertedId},{readPreference:"primary"});p&&(h().onAfterSignup?.({user:p,session:r,connectionInfo:i}),h().signup?.onSuccess?.(p));}catch(s){throw s instanceof Error&&(h().onSignupError?.({error:s,session:r,connectionInfo:i}),h().signup?.onError?.(s)),s}}function To(){let t=Router(),e=!!a$1("_system.user.auth.google.enabled"),o=String(a$1("_system.user.auth.google.clientId")),n=String(a$1("_system.user.auth.google.clientSecret"));return !e||!o||!n||(he.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(r,i,s,a)=>a(null,s))),t.get("/api/_internal/auth/google",he.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",he.authenticate("google",{session:false}),Mo)),t}var xt=To;function vt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([r,i])=>{o.setHeader(r,i);}),o.send(n.data);}catch(n){n instanceof a$3?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var we=Object.freeze({});function Rt(t){we=Object.freeze(Object.assign({},we,t));}function Q(){return we}function Ao(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,vt(a));});}}async function Dt(t,{combinedModules:e,channels:o}){let n=ye();n.use(ye.json()),n.use(ye.urlencoded({extended:true})),n.use(_o()),n.use(he.initialize()),n.use(xt()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:p}=a.params,b=await ge(a);try{let d=await gt(p,a.body.args,b);l.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${p}:`,d),d instanceof a$3)l.status(d.status).send(d.message);else if(d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let M=d.flatten(),Y=Object.entries(M.fieldErrors).map(([A,ee])=>`${A}: ${(ee??[]).join(", ")}`).join("; "),X=M.formErrors.join("; "),J=[Y,X].filter(Boolean).join("; ");l.status(400).send(J);}else l.status(500).send(d instanceof Error?d.message:String(d));}}),Ao(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=ko.createServer(n),i=Q()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h$1("Application started",{source:"app"}),console.log(`
15
15
  Application started on http://localhost:${s}
16
- `);});}async function ge(t){let e=S.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=S.object({screenWidth:S.number(),screenHeight:S.number(),windowWidth:S.number(),windowHeight:S.number(),pixelRatio:S.number(),orientation:S.string().nullable()}).parse(t.body.clientInfo),n={ip:Po(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!U()){let{session:i,user:s,roles:a}=await j(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:B()}}function Po(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function $o({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Et,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Ot.config(),Ot.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,p=process.env.MODELENCE_CRON_ENABLED==="true";Zo().then(()=>{}).catch(()=>{});let b=[tt,Ae,dt,yt,bt],d=[...b,...t];e(),zo(b),No(t),Le(e$1,o);let C=Bo(d);d$1(C);let M=Jo(d),Y=Wo(d);p&&Fo(d);let X=qo(d);if(Qe(X),l){let{configs:A,environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t}=await ot({configSchema:C,cronJobsMetadata:p?lt():void 0,stores:M});c$1(A),f({environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t});}else c$1(Go(C));We(i),Ve(s),Rt({...a,provider:a.provider||Ne});let J=U();if(J&&(await $e(),Vo(M)),p&&await wt(r),J)for(let A of M)A.createIndexes();l&&(await g$1(),it()),p&&ct().catch(console.error),await Dt(n,{combinedModules:d,channels:Y});}function No(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))me(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ut(`${e.name}.${o}`,n);}}function zo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))mt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))pt(`${e.name}.${o}`,n);}}function Jo(t){return t.flatMap(e=>e.stores)}function Wo(t){return t.flatMap(e=>e.channels)}function qo(t){return t.flatMap(e=>e.rateLimits)}function Bo(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function Fo(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))at(`${e.name}.${o}`,n);}function Vo(t){let e=F();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ho={MONGODB_URI:"_system.mongodbUri",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_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",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"};function Ko(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Go(t){let e=[];for(let[o,n]of Object.entries(Ho)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:Ko(r,s)});}}return e}async function Zo(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Qo(),r=await import('./package-6GIFEHJQ.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:ao.hostname(),environmentId:o})});}}async function Qo(){try{let t=pe.join(process.cwd(),"package.json"),e=await Lo.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var be=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=Q().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Yo(t){if(!g().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email-configuration for more details.");return g().provider?.sendEmail(t)}
16
+ `);});}async function ge(t){let e=S.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=S.object({screenWidth:S.number(),screenHeight:S.number(),windowWidth:S.number(),windowHeight:S.number(),pixelRatio:S.number(),orientation:S.string().nullable()}).parse(t.body.clientInfo),n={ip:Po(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!U()){let{session:i,user:s,roles:a}=await j(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:B()}}function Po(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function $o({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Et,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Ot.config(),Ot.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,p=process.env.MODELENCE_CRON_ENABLED==="true";Zo().then(()=>{}).catch(()=>{});let b=[tt,Ae,dt,yt,bt],d=[...b,...t];e(),zo(b),No(t),Le(e$1,o);let C=Bo(d);d$1(C);let M=Jo(d),Y=Wo(d);p&&Fo(d);let X=qo(d);if(Qe(X),l){let{configs:A,environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t}=await ot({configSchema:C,cronJobsMetadata:p?lt():void 0,stores:M});c$1(A),f({environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t});}else c$1(Go(C));We(i),Ve(s),Rt({...a,provider:a.provider||Ne});let J=U();if(J&&(await $e(),Vo(M)),p&&await wt(r),J)for(let A of M)A.createIndexes();l&&(await g$1(),it()),p&&ct().catch(console.error),await Dt(n,{combinedModules:d,channels:Y});}function No(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))me(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ut(`${e.name}.${o}`,n);}}function zo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))mt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))pt(`${e.name}.${o}`,n);}}function Jo(t){return t.flatMap(e=>e.stores)}function Wo(t){return t.flatMap(e=>e.channels)}function qo(t){return t.flatMap(e=>e.rateLimits)}function Bo(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function Fo(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))at(`${e.name}.${o}`,n);}function Vo(t){let e=F();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ho={MONGODB_URI:"_system.mongodbUri",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_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",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"};function Ko(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Go(t){let e=[];for(let[o,n]of Object.entries(Ho)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:Ko(r,s)});}}return e}async function Zo(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Qo(),r=await import('./package-5ZEGPCTP.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:ao.hostname(),environmentId:o})});}}async function Qo(){try{let t=pe.join(process.cwd(),"package.json"),e=await Lo.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var be=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=Q().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Yo(t){if(!g().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return g().provider?.sendEmail(t)}
17
17
  export{y as Module,be as ServerChannel,w as Store,j as authenticate,D as consumeRateLimit,me as createQuery,m as dbUsers,c as schema,Yo as sendEmail,$o as startApp};//# sourceMappingURL=server.js.map
18
18
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/role.ts","../src/auth/index.ts","../src/db/client.ts","../src/websocket/socketio/server.ts","../src/auth/disposableEmails.ts","../src/app/emailConfig.ts","../src/utils/index.ts","../src/auth/templates/emailVerficationTemplate.ts","../src/auth/verification.ts","../src/auth/validators.ts","../src/app/authConfig.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/rate-limit/db.ts","../src/rate-limit/rules.ts","../src/auth/signup.ts","../src/auth/resetPassword.ts","../src/auth/user.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/cron/jobs.ts","../src/methods/index.ts","../src/migration/db.ts","../src/migration/index.ts","../src/rate-limit/index.ts","../src/viteServer.ts","../src/auth/providers/google.ts","../src/routes/handler.ts","../src/app/websocketConfig.ts","../src/app/server.ts","../src/app/index.ts","../src/websocket/serverChannel.ts","../src/app/email.ts"],"names":["Module","name","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","channels","Store","options","client","document","selector","ObjectId","query","errorHandler","result","cursor","id","idSelector","documents","update","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","authenticate","userDoc","connect","mongodbUri","getMongodbUri","MongoClient","err","value","getConfig","getClient","socketServer","COLLECTION","init","httpServer","mongodbClient","mongoCollection","error","SocketServer","createAdapter","socket","next","token","channelName","category","channel","broadcast","data","server_default","isDisposableEmail","email","emailParts","domain","updateDisposableEmailListCron","response","domains","batchSize","batch","emailConfig","setEmailConfig","newEmailConfig","getEmailConfig","isServer","requireServer","htmlToText","html","emailVerificationTemplate","verificationUrl","handleVerifyEmail","params","baseUrl","emailVerifiedRedirectUrl","tokenDoc","sendVerificationEmail","emailProvider","verificationToken","htmlTemplate","textContent","validatePassword","validateEmail","authConfig","setAuthConfig","newAuthConfig","getAuthConfig","handleLoginWithPassword","connectionInfo","ip","consumeRateLimit","password","passwordHash","incorrectCredentialsError","e","bcrypt","handleLogout","getOwnProfile","_args","profile","dbRateLimits","allRules","initRateLimits","bucket","type","rules","rule","checkRateLimitRule","createError","createRateLimitError","RateLimitError","record","currentWindowStart","count","modifier","getCount","prevWindowStart","currentWindowCount","prevWindowCount","prevWindowWeight","weight","handleSignupWithPassword","existingUser","existingEmail","hash","userDocument","resolveUrl","configuredUrl","defaultPasswordResetTemplate","resetUrl","passwordResetSent","handleSendResetPasswordToken","resetToken","handleResetPassword","resetTokenDoc","user_default","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","callApi","os","fetchConfigs","syncStatus","endpoint","method","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","handler","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","job","tickCronJobs","ms","resolve","state","startCronJob","transaction","startTransaction","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","permissions","runMethod","context","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","migration_default","rate_limit_default","ViteServer","createServer","staticFolders","express","req","res","loadUserViteConfig","appDir","loadConfigFromFile","safelyMergeConfig","baseConfig","userConfig","mergedConfig","mergeConfig","seenPlugins","plugin","pluginName","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","defineConfig","code","bundle","viteServer","authenticateUser","handleGoogleAuthenticationCallback","googleUser","getCallContext","googleEmail","newUser","getRouter","googleAuthRouter","Router","googleEnabled","googleClientId","googleClientSecret","passport","GoogleStrategy","accessToken","refreshToken","done","google_default","createRouteHandler","key","ModelenceError","websocketConfig","setWebsocketConfig","newWebsocketConfig","getWebsocketConfig","registerModuleRoutes","app","modules","module","route","handlers","startServer","server","combinedModules","cookieParser","methodName","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","http","websocketProvider","port","logInfo","val","clientInfo","getClientIp","forwardedFor","directIp","startApp","auth","websocket","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","getChannels","defineCronJobs","getRateLimits","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","localConfigMap","formatLocalConfigValue","numValue","envVar","configKey","configSchemaEntry","serviceEndpoint","appDetails","getAppDetails","modelencePackageJson","packageJsonPath","packageJsonContent","ServerChannel","canAccessChannel","logError","sendEmail"],"mappings":"q4BAwCaA,CAAAA,CAAN,KAAa,CAqClB,WAAA,CACEC,CAAAA,CACA,CACE,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,OAAA,CAAAC,CAAAA,CAAU,EAAC,CACX,UAAAC,CAAAA,CA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,CAAM,wGAAwG,CAAA,CAE1H,OAAOA,CAAAA,EAAe,CAAE,QAAA,EAAU,SAAA,CAAUmF,CAAO,CACrD","file":"server.js","sourcesContent":["import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /** @internal */\n public readonly rateLimits: RateLimitRule[];\n\n /** @internal */\n public readonly channels: ServerChannel[];\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {},\n rateLimits = [],\n channels = []\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema,\n rateLimits?: RateLimitRule[],\n channels?: ServerChannel[],\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n this.channels = channels;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: Filter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n * \n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: Filter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n\nexport const resetPasswordTokensCollection = new Store('_modelenceResetPasswordTokens', {\n schema: {\n userId: schema.objectId(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import { Server } from \"http\";\nimport { Server as SocketServer, Socket } from 'socket.io';\nimport { createAdapter } from \"@socket.io/mongo-adapter\";\nimport { authenticate } from \"@/auth\";\nimport { getClient } from \"@/db/client\";\nimport { WebsocketServerProvider } from \"../types\";\nimport { ServerChannel } from \"../serverChannel\";\n\nlet socketServer: SocketServer | null = null;\n\nconst COLLECTION = '_modelenceSocketio';\n\nexport async function init({\n httpServer,\n channels,\n}: {\n httpServer: Server;\n channels: ServerChannel[];\n}) {\n\n const mongodbClient = getClient();\n\n if (!mongodbClient) {\n console.error('Socket.IO initialization failed: MongoDB client is not initialized');\n throw new Error('Mongodb Client is not initialized');\n }\n\n console.log('Initializing Socket.IO server...');\n\n const mongoCollection = mongodbClient.db().collection(COLLECTION);\n\n try {\n await mongoCollection.createIndex(\n { createdAt: 1 },\n { expireAfterSeconds: 3600, background: true }\n );\n } catch (error) {\n console.error('Failed to create index on MongoDB collection for Socket.IO:', error);\n }\n\n socketServer = new SocketServer(httpServer, {\n cors: {\n origin: \"*\",\n methods: [\"GET\", \"POST\"]\n },\n adapter: createAdapter(mongoCollection),\n transports: ['polling', 'websocket'],\n allowUpgrades: true,\n perMessageDeflate: false,\n });\n\n socketServer.on('error', (error) => {\n console.error('Socket.IO error:', error);\n });\n\n socketServer.use(async (socket, next) => {\n const token = socket.handshake.auth.token;\n\n try {\n socket.data = await authenticate(token);\n } finally {\n next();\n }\n });\n\n socketServer.on('connection', (socket: Socket) => {\n console.log(`Socket.IO client connected`);\n \n socket.on('disconnect', () => {\n console.log(`Socket.IO client disconnected`);\n });\n\n socket.on('joinChannel', async (channelName) => {\n const [category] = channelName.split(':');\n for (const channel of channels) {\n if (\n channel.category === category &&\n (\n !channel.canAccessChannel ||\n await channel.canAccessChannel(socket.data)\n )\n ) {\n socket.join(channelName);\n }\n }\n\n socket.join(channelName);\n console.log(`User ${socket.id} joined channel ${channelName}`);\n socket.emit('joinedChannel', channelName);\n });\n\n socket.on('leaveChannel', (channelName) => {\n socket.leave(channelName);\n console.log(`User ${socket.id} left channel ${channelName}`);\n socket.emit('leftChannel', channelName);\n });\n });\n\n console.log(\"Socket.IO server initialized\");\n}\n\nfunction broadcast<T>({\n category,\n id,\n data,\n}: {\n category: string,\n id: string,\n data: T,\n}) {\n socketServer?.to(`${category}:${id}`).emit(category, data);\n}\n\nexport default {\n init,\n broadcast,\n} as WebsocketServerProvider;\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import type { EmailProvider } from \"../types\";\n\nexport type EmailConfig = {\n provider?: EmailProvider;\n from?: string;\n verification?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n verificationUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n passwordReset?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n resetUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n // @deprecated use verification.redirectUrl instead\n emailVerifiedRedirectUrl?: string;\n};\n\nlet emailConfig: EmailConfig = Object.freeze({});\n\nexport function setEmailConfig(newEmailConfig: EmailConfig) {\n emailConfig = Object.freeze(Object.assign({}, emailConfig, newEmailConfig));\n}\n\nexport function getEmailConfig() {\n return emailConfig;\n}\n","export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n\nexport function htmlToText(html: string) {\n return html.replace(/<[^>]*>/g, '').replace(/\\s+/g, ' ').trim()\n}\n","export function emailVerificationTemplate({ name, email, verificationUrl }: { name?: string; email: string; verificationUrl: string }) {\n return `\n <p>Hi${name ? ` ${name}` : ''},</p>\n <p>Please verify your email address ${email} by clicking the link below:</p>\n <p><a href=\"${verificationUrl}\">${verificationUrl}</a></p>\n <p>If you did not request this, please ignore this email.</p>\n `;\n}\n","import { z } from 'zod';\n\nimport { usersCollection, emailVerificationTokensCollection } from './db';\nimport { ObjectId, RouteParams, RouteResponse } from '@/server';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { randomBytes } from 'crypto';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { emailVerificationTemplate } from './templates/emailVerficationTemplate';\n\nexport async function handleVerifyEmail(params: RouteParams): Promise<RouteResponse> {\n const baseUrl = process.env.MODELENCE_SITE_URL;\n const emailVerifiedRedirectUrl = getEmailConfig().emailVerifiedRedirectUrl || baseUrl || '/';\n try {\n const token = z.string().parse(params.query.token);\n // Find token in database\n const tokenDoc = await emailVerificationTokensCollection.findOne({\n token,\n expiresAt: { $gt: new Date() }\n });\n\n if (!tokenDoc) {\n throw new Error('Invalid or expired verification token');\n }\n\n // Find user by token's userId\n const userDoc = await usersCollection.findOne({ _id: tokenDoc.userId });\n\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n const email = tokenDoc.email;\n\n if (!email) {\n throw new Error('Email not found in token');\n }\n\n // Mark the specific email as verified atomically\n const updateResult = await usersCollection.updateOne(\n { \n _id: tokenDoc.userId,\n 'emails.address': email,\n 'emails.verified': { $ne: true }\n },\n { $set: { 'emails.$.verified': true } }\n );\n\n if (updateResult.matchedCount === 0) {\n // Check if email exists but is already verified\n const existingUser = await usersCollection.findOne({\n _id: tokenDoc.userId,\n 'emails.address': email\n });\n \n if (existingUser) {\n throw new Error('Email is already verified');\n } else {\n throw new Error('Email address not found for this user');\n }\n }\n\n // Delete the used token\n await emailVerificationTokensCollection.deleteOne({ _id: tokenDoc._id });\n } catch (error) {\n if (error instanceof Error) {\n console.error('Error verifying email:', error);\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=error&message=${encodeURIComponent(error.message)}`,\n };\n }\n }\n\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=verified`,\n };\n}\n\nexport async function sendVerificationEmail({\n userId,\n email,\n baseUrl = process.env.MODELENCE_SITE_URL\n}: {\n userId: ObjectId;\n email: string;\n baseUrl?: string;\n}) {\n if (getEmailConfig().provider) {\n const emailProvider = getEmailConfig().provider;\n\n // Generate verification token\n const verificationToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(24));\n\n // Store token in database\n await emailVerificationTokensCollection.insertOne({\n userId,\n email,\n token: verificationToken,\n createdAt: new Date(),\n expiresAt,\n });\n \n const verificationUrl = `${baseUrl}/api/_internal/auth/verify-email?token=${verificationToken}`;\n \n const template = getEmailConfig()?.verification?.template || emailVerificationTemplate;\n // TODO: we should have also the name on this step\n const htmlTemplate = template({ name: '', email, verificationUrl });\n const textContent = htmlToText(htmlTemplate);\n \n await emailProvider?.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.verification?.subject || 'Verify your email address',\n text: textContent,\n html: htmlTemplate,\n });\n }\n}\n","import { z } from \"zod\";\n\nexport function validatePassword(value: string) {\n return z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(value);\n}\n\nexport function validateEmail(value: string) {\n return z.string()\n .email({ message: 'Invalid email address' })\n .parse(value);\n}\n","import { Session, User } from \"@/auth/types\";\nimport { ConnectionInfo } from \"@/methods/types\";\n\n/**\n * Callback options for authentication operations\n */\nexport type AuthOption = {\n /** Callback executed when authentication succeeds */\n onSuccess?: (user: User) => void;\n /** Callback executed when authentication fails */\n onError?: (error: Error) => void;\n}\n\n/**\n * Authentication configuration for the application\n *\n * @example\n * ```typescript\n * import { startApp } from 'modelence/server';\n *\n * startApp({\n * auth: {\n * onAfterLogin: ({ user }) => {\n * console.log('User logged in:', user.name);\n * // Redirect to dashboard\n * },\n * onLoginError: ({ error }) => {\n * console.error('Login failed:', error.message);\n * // Show error toast\n * },\n * onAfterSignup: ({ user }) => {\n * console.log('User signed up:', user.email);\n * // Send welcome email\n * },\n * onSignupError: ({ error }) => {\n * console.error('Signup failed:', error.message);\n * }\n * }\n * });\n * ```\n */\nexport type AuthConfig = {\n onAfterLogin?: (props: {\n user: User,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onLoginError?: (props: {\n error: Error,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onAfterSignup?: (props: {\n user: User,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onSignupError?: (props: {\n error: Error,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n\n /** deprecated: use onAfterLogin and onLoginError */\n login?: AuthOption;\n /** deprecated: user onAfterSignup and onSignupError */\n signup?: AuthOption;\n};\n\nlet authConfig: AuthConfig = Object.freeze({});\n\nexport function setAuthConfig(newAuthConfig: AuthConfig) {\n authConfig = Object.freeze(Object.assign({}, authConfig, newAuthConfig));\n}\n\nexport function getAuthConfig() {\n return authConfig;\n}\n","import bcrypt from 'bcrypt';\nimport { z } from 'zod';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\nimport { sendVerificationEmail } from './verification';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { consumeRateLimit } from '@/server';\nimport { validateEmail } from './validators';\nimport { getAuthConfig } from '@/app/authConfig';\n\nexport async function handleLoginWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n try {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signin',\n type: 'ip',\n value: ip,\n });\n }\n\n const email = validateEmail(args.email as string);\n // password is accepted just as a string, so users can still sign in if the password validation rules are changed\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const emailDoc = userDoc.emails?.find(e => e.address === email);\n\n if (!emailDoc?.verified && getEmailConfig()?.provider) {\n if (ip) {\n try {\n await consumeRateLimit({\n bucket: 'verification',\n type: 'user',\n value: userDoc._id.toString(),\n });\n } catch {\n throw new Error(\"Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.\");\n }\n }\n\n await sendVerificationEmail({\n userId: userDoc?._id,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n throw new Error(\"Your email address hasn't been verified yet. We've sent a new verification email to your inbox.\");\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n getAuthConfig().onAfterLogin?.({\n user: userDoc,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onSuccess?.(userDoc);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n } catch (error) {\n if (error instanceof Error) {\n getAuthConfig().onLoginError?.({\n error,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onError?.(error);\n }\n throw error;\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\n/**\n * Two-bucket sliding window approximation to track rate limits.\n * This is a trade-off between storage and accuracy.\n * We're not keeping exact event logs, so we can't track the exact number of events in a window.\n * Instead, we're adding a weighted average from the previous window to the current window.\n */\nexport const dbRateLimits = new Store('_modelenceRateLimits', {\n schema: {\n bucket: schema.string(),\n type: schema.enum(['ip', 'user']),\n value: schema.string(),\n windowMs: schema.number(),\n\n windowStart: schema.date(),\n windowCount: schema.number(),\n prevWindowCount: schema.number(),\n\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { bucket: 1, type: 1, value: 1, windowMs: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ]\n});\n","import { RateLimitRule, RateLimitType } from './types';\nimport { dbRateLimits } from './db';\nimport { RateLimitError } from '../error';\n\nlet allRules: Array<RateLimitRule> = [];\n\nexport function initRateLimits(rateLimits: RateLimitRule[]) {\n if (allRules.length > 0) {\n throw new Error('Duplicate call to initRateLimits - already initialized');\n }\n\n allRules = rateLimits;\n}\n\n/**\n * This function will check all rate limit rules on the specified bucket and type,\n * throw an error if any of them are exceeded and increase the count of the rate limit record.\n * \n * @category Rate Limits\n * \n * @example\n * ```ts\n * await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' });\n * ```\n * @param options.bucket - The bucket for the rate limit.\n * @param options.type - The type of the rate limit.\n * @param options.value - The value for the rate limit.\n */\nexport async function consumeRateLimit(\n options: { bucket: string, type: RateLimitType, value: string }\n) {\n const { bucket, type, value } = options;\n const rules = allRules.filter(rule => rule.bucket === bucket && rule.type === type);\n\n for (const rule of rules) {\n await checkRateLimitRule(rule, value);\n }\n}\n\n// Two-bucket sliding window approximation to track rate limits.\nasync function checkRateLimitRule(rule: RateLimitRule, value: string, createError?: () => Error) {\n const createRateLimitError = () => {\n return createError ? createError() : new RateLimitError(`Rate limit exceeded for ${rule.bucket}`);\n };\n\n const record = await dbRateLimits.findOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n });\n\n const now = Date.now();\n const currentWindowStart = Math.floor(now / rule.window) * rule.window;\n\n const { count, modifier } = record\n ? getCount(record, currentWindowStart, now)\n : {\n count: 0,\n modifier: {\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + rule.window + rule.window),\n }\n }\n };\n\n if (count >= rule.limit) {\n throw createRateLimitError();\n }\n\n /*\n Always use upsert, because there is a small chance the document might be auto-removed\n based on the expiration TTL index in between the check and the update\n */\n await dbRateLimits.upsertOne(\n { bucket: rule.bucket, type: rule.type, value, windowMs: rule.window }, \n modifier\n );\n}\n\nfunction getCount(record: typeof dbRateLimits['Doc'], currentWindowStart: number, now: number) {\n const prevWindowStart = currentWindowStart - record.windowMs;\n \n if (record.windowStart.getTime() === currentWindowStart) {\n const currentWindowCount = record.windowCount;\n const prevWindowCount = record.prevWindowCount;\n const prevWindowWeight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(currentWindowCount + prevWindowCount * prevWindowWeight),\n modifier: {\n $inc: { windowCount: 1 },\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n if (record.windowStart.getTime() === prevWindowStart) {\n const weight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(record.windowCount * weight),\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: record.windowCount,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n return {\n count: 0,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { isDisposableEmail } from './disposableEmails';\nimport { consumeRateLimit } from '../rate-limit/rules';\nimport { sendVerificationEmail } from './verification';\nimport { validateEmail, validatePassword } from './validators';\nimport { getAuthConfig } from '@/app/authConfig';\n\nexport async function handleSignupWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n try {\n const email = validateEmail(args.email as string);\n const password = validatePassword(args.password as string);\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signupAttempt',\n type: 'ip',\n value: ip,\n });\n }\n\n if (await isDisposableEmail(email)) {\n throw new Error('Please use a permanent email address');\n }\n\n // TODO: captcha check\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n if (ip) {\n await consumeRateLimit({\n bucket: 'signup',\n type: 'ip',\n value: ip,\n });\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n const userDocument = await usersCollection.findOne(\n { _id: result.insertedId },\n { readPreference: \"primary\" }\n );\n\n if (!userDocument) {\n throw new Error('User not found');\n }\n\n await sendVerificationEmail({\n userId: result?.insertedId,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n\n getAuthConfig().onAfterSignup?.({\n user: userDocument,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onSuccess?.(userDocument);\n\n return result.insertedId;\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().onSignupError?.({\n error,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onError?.(error);\n }\n throw error;\n }\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\nimport { randomBytes } from 'crypto';\n\nimport { Args, Context } from '@/methods/types';\nimport { usersCollection, resetPasswordTokensCollection } from './db';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { validateEmail, validatePassword } from './validators';\n\nfunction resolveUrl(baseUrl: string, configuredUrl?: string): string {\n if (!configuredUrl) {\n return baseUrl;\n }\n \n if (configuredUrl.startsWith('http://') || configuredUrl.startsWith('https://')) {\n return configuredUrl;\n }\n \n // Handle relative URL\n return `${baseUrl}${configuredUrl.startsWith('/') ? '' : '/'}${configuredUrl}`;\n}\n\nfunction defaultPasswordResetTemplate({ email, resetUrl }: { email: string; resetUrl: string }) {\n return `\n <p>Hi,</p>\n <p>We received a request to reset your password for ${email}.</p>\n <p>Click the link below to reset your password:</p>\n <p><a href=\"${resetUrl}\">${resetUrl}</a></p>\n <p>This link will expire in 1 hour.</p>\n <p>If you did not request this password reset, please ignore this email.</p>\n `;\n}\n\nconst passwordResetSent = { success: true, message: 'If an account with that email exists, a password reset link has been sent' };\n\nexport async function handleSendResetPasswordToken(args: Args, { connectionInfo }: Context) {\n const email = validateEmail(args.email as string);\n\n // Find user by email\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (!userDoc) {\n // For security, don't reveal if email exists or not\n return passwordResetSent;\n }\n\n // Check if user has password auth method\n if (!userDoc.authMethods?.password) {\n return passwordResetSent;\n }\n\n const emailProvider = getEmailConfig().provider;\n if (!emailProvider) {\n throw new Error('Email provider is not configured');\n }\n\n // Generate reset token\n const resetToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(1)); // 1 hour expiry\n\n // Store reset token\n await resetPasswordTokensCollection.insertOne({\n userId: userDoc._id,\n token: resetToken,\n createdAt: new Date(),\n expiresAt,\n });\n\n // Build reset URL\n const baseUrl = process.env.MODELENCE_SITE_URL || connectionInfo?.baseUrl;\n const resetPasswordUrl = resolveUrl(baseUrl!, getEmailConfig().passwordReset?.redirectUrl);\n const resetUrl = `${resetPasswordUrl}?token=${resetToken}`;\n\n // Send email\n const template = getEmailConfig()?.passwordReset?.template || defaultPasswordResetTemplate;\n const htmlTemplate = template({ email, resetUrl, name: '' });\n const textContent = htmlToText(htmlTemplate);\n\n await emailProvider.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.passwordReset?.subject || 'Reset your password',\n text: textContent,\n html: htmlTemplate,\n });\n\n return passwordResetSent;\n}\n\nexport async function handleResetPassword(args: Args, { }: Context) {\n const token = z.string().parse(args.token);\n const password = validatePassword(args.password as string);\n\n // Find the reset token\n const resetTokenDoc = await resetPasswordTokensCollection.findOne({ token });\n if (!resetTokenDoc) {\n throw new Error('Invalid or expired reset token');\n }\n\n // Check if token is expired\n if (resetTokenDoc.expiresAt < new Date()) {\n await resetPasswordTokensCollection.deleteOne({ token });\n throw new Error('Reset token has expired');\n }\n\n // Find the user\n const userDoc = await usersCollection.findOne({ _id: resetTokenDoc.userId });\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n // Hash the new password\n const hash = await bcrypt.hash(password, 10);\n\n // Update user's password\n await usersCollection.updateOne(\n { _id: userDoc._id },\n {\n $set: {\n 'authMethods.password.hash': hash\n }\n }\n );\n\n // Delete the used reset token\n await resetPasswordTokensCollection.deleteOne({ token });\n\n return { success: true, message: 'Password has been reset successfully' };\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { time } from '../time';\nimport {\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n usersCollection\n} from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { handleSignupWithPassword } from './signup';\nimport { handleVerifyEmail } from './verification';\nimport { handleResetPassword, handleSendResetPasswordToken } from './resetPassword';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [\n usersCollection,\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n ],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n sendResetPasswordToken: handleSendResetPasswordToken,\n resetPassword: handleResetPassword,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n },\n rateLimits: [{\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(15),\n limit: 20,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.days(1),\n limit: 200,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.minutes(15),\n limit: 3,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.days(1),\n limit: 10,\n }],\n configSchema: {\n 'auth.email.enabled': {\n type: 'boolean',\n isPublic: true,\n default: true,\n },\n 'auth.email.from': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.email.verification': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.enabled': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.clientId': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.google.clientSecret': {\n type: 'secret',\n isPublic: false,\n default: '',\n },\n },\n routes: [\n {\n path: '/api/_internal/auth/verify-email',\n handlers: {\n get: handleVerifyEmail\n },\n }\n ],\n});\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await Promise.all(aliasList.map(alias => \n cronJobsCollection.upsertOne(\n { alias },\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n )\n ));\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","import { Module } from '../app/module';\nimport { dbRateLimits } from './db';\n\nexport default new Module('_system.rateLimit', {\n stores: [dbRateLimits],\n});\n","import { createServer, defineConfig, ViteDevServer, loadConfigFromFile, UserConfig, mergeConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport type { AppServer, ExpressMiddleware } from './types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n private config?: UserConfig;\n\n async init() {\n this.config = await getConfig();\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer(this.config); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n const staticFolders = [express.static('./.modelence/build/client'.replace(/\\\\/g, '/'))];\n if (this.config?.publicDir) {\n staticFolders.push(express.static(this.config.publicDir));\n }\n return staticFolders;\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client'.replace(/\\\\/g, '/') });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function loadUserViteConfig() {\n const appDir = process.cwd();\n \n try {\n const result = await loadConfigFromFile({ command: 'serve', mode: 'development' }, undefined, appDir);\n return result?.config || {};\n } catch (error) {\n console.warn(`Could not load vite config:`, error);\n return {};\n }\n}\n\nfunction safelyMergeConfig(baseConfig: UserConfig, userConfig: UserConfig) {\n const mergedConfig = mergeConfig(baseConfig, userConfig);\n \n // Deduplicate plugins by name, keeping user plugins over framework plugins\n if (mergedConfig.plugins && Array.isArray(mergedConfig.plugins)) {\n const seenPlugins = new Set();\n mergedConfig.plugins = mergedConfig.plugins.filter((plugin: any) => {\n if (!plugin || typeof plugin !== 'object') {\n return true;\n }\n const pluginName = plugin.name;\n if (!pluginName || seenPlugins.has(pluginName)) {\n return false;\n }\n seenPlugins.add(pluginName);\n return true;\n }).reverse(); // Reverse to prioritize user plugins over framework plugins\n mergedConfig.plugins.reverse(); // Reverse back to maintain original order\n }\n \n return mergedConfig;\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n const userConfig = await loadUserViteConfig();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n const baseConfig = defineConfig({\n plugins,\n build: {\n outDir: '.modelence/build/client'.replace(/\\\\/g, '/'),\n emptyOutDir: true\n },\n server: {\n middlewareMode: true,\n },\n root: './src/client',\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src').replace(/\\\\/g, '/')\n }\n },\n });\n\n return safelyMergeConfig(baseConfig, userConfig);\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import { getConfig } from \"@/server\";\nimport { Router, type Request, type Response } from \"express\";\nimport { ObjectId } from \"mongodb\";\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { usersCollection } from \"../db\";\nimport { createSession } from \"../session\";\nimport { getAuthConfig } from \"@/app/authConfig\";\nimport { getCallContext } from \"@/app/server\";\n\ninterface GoogleUser {\n id: string;\n displayName: string;\n emails: { value: string; }[];\n photos: { value: string }[];\n}\n\nasync function authenticateUser(res: Response, userId: ObjectId) {\n const { authToken } = await createSession(userId);\n\n res.cookie(\"authToken\", authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"strict\",\n });\n res.status(301);\n res.redirect(\"/\");\n}\n\n\nasync function handleGoogleAuthenticationCallback(req: Request, res: Response) {\n const googleUser = req.user as GoogleUser;\n\n const existingUser = await usersCollection.findOne(\n { 'authMethods.google.id': googleUser.id },\n );\n\n const {\n session,\n connectionInfo,\n } = await getCallContext(req);\n\n try {\n if (existingUser) {\n await authenticateUser(res, existingUser._id);\n\n getAuthConfig().onAfterLogin?.({\n user: existingUser,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onSuccess?.(existingUser);\n \n return;\n }\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().login?.onError?.(error);\n\n getAuthConfig().onLoginError?.({\n error,\n session,\n connectionInfo,\n });\n }\n throw error;\n }\n\n try {\n const googleEmail = googleUser.emails[0] && googleUser.emails[0]?.value;\n\n if (!googleEmail) {\n res.status(400).json({\n error: \"Email address is required for Google authentication.\",\n });\n }\n\n const existingUserByEmail = await usersCollection.findOne(\n { 'emails.address': googleEmail, },\n { collation: { locale: 'en', strength: 2 } },\n );\n\n // TODO: check if the email is verified\n if (existingUserByEmail) {\n // TODO: handle case with an HTML page\n res.status(400).json({\n error: \"User with this email already exists. Please log in instead.\",\n });\n return;\n }\n\n // If the user does not exist, create a new user\n const newUser = await usersCollection.insertOne({\n handle: googleEmail,\n emails: [{\n address: googleEmail,\n verified: true, // Google email is considered verified\n }],\n createdAt: new Date(),\n authMethods: {\n google: {\n id: googleUser.id,\n },\n },\n });\n\n await authenticateUser(res, newUser.insertedId);\n\n const userDocument = await usersCollection.findOne(\n { _id: newUser.insertedId },\n { readPreference: \"primary\" }\n );\n\n if (userDocument) {\n getAuthConfig().onAfterSignup?.({\n user: userDocument,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onSuccess?.(userDocument);\n }\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().onSignupError?.({\n error,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onError?.(error);\n }\n throw error;\n }\n}\n\nfunction getRouter() {\n const googleAuthRouter = Router();\n const googleEnabled = Boolean(getConfig('_system.user.auth.google.enabled'));\n const googleClientId = String(getConfig('_system.user.auth.google.clientId'));\n const googleClientSecret = String(getConfig('_system.user.auth.google.clientSecret'));\n if (!googleEnabled || !googleClientId || !googleClientSecret) {\n return googleAuthRouter;\n }\n\n passport.use(new GoogleStrategy({\n clientID: googleClientId,\n clientSecret: googleClientSecret,\n callbackURL: '/api/_internal/auth/google/callback',\n proxy: true,\n }, (accessToken, refreshToken, profile, done) => {\n return done(null, profile);\n }));\n\n googleAuthRouter.get(\"/api/_internal/auth/google\", passport.authenticate(\"google\", {\n scope: [\"profile\", \"email\"],\n session: false,\n }));\n\n googleAuthRouter.get(\n \"/api/_internal/auth/google/callback\",\n passport.authenticate(\"google\", { session: false }),\n handleGoogleAuthenticationCallback,\n );\n\n return googleAuthRouter;\n}\n\nexport default getRouter;\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { ModelenceError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.redirect) {\n res.redirect(response.redirect);\n }\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { WebsocketServerProvider } from \"@/websocket/types\";\n\nexport type WebsocketConfig = {\n provider?: WebsocketServerProvider;\n};\n\nlet websocketConfig: WebsocketConfig = Object.freeze({});\n\nexport function setWebsocketConfig(newWebsocketConfig: WebsocketConfig) {\n websocketConfig = Object.freeze(Object.assign({}, websocketConfig, newWebsocketConfig));\n}\n\nexport function getWebsocketConfig() {\n return websocketConfig;\n}\n","import googleAuthRouter from '@/auth/providers/google';\nimport { runMethod } from '@/methods';\nimport { getResponseTypeMap } from '@/methods/serialize';\nimport { createRouteHandler } from '@/routes/handler';\nimport { HttpMethod } from '@/server';\nimport { logInfo } from '@/telemetry';\nimport cookieParser from 'cookie-parser';\nimport express, { Request, Response } from 'express';\nimport http from 'http';\nimport passport from 'passport';\nimport z from 'zod';\nimport type { AppServer } from '../types';\nimport { authenticate } from '../auth';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { ModelenceError } from '../error';\nimport { Module } from './module';\nimport { ConnectionInfo } from '@/methods/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\nimport { getWebsocketConfig } from './websocketConfig';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, {\n combinedModules,\n channels,\n}: {\n combinedModules: Module[],\n channels: ServerChannel[]\n}) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n app.use(passport.initialize());\n\n app.use(googleAuthRouter());\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n \n const websocketProvider = getWebsocketConfig()?.provider;\n if (websocketProvider) {\n websocketProvider.init({\n httpServer,\n channels,\n });\n }\n\n const port = process.env.MODELENCE_PORT || process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`\\nApplication started on http://localhost:${port}\\n`);\n });\n}\n\nexport async function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.cookies.authToken || req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo: ConnectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n baseUrl: req.protocol + '://' + req.get('host'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import dotenv from 'dotenv';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport type { AppServer } from '../types';\nimport socketioServer from '@/websocket/socketio/server';\nimport { initRoles } from '../auth/role';\nimport sessionModule from '../auth/session';\nimport { RoleDefinition } from '../auth/types';\nimport userModule from '../auth/user';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { AppConfig, ConfigSchema, ConfigType } from '../config/types';\nimport cronModule, { defineCronJob, getCronJobsMetadata, startCronJobs } from '../cron/jobs';\nimport { Store } from '../data/store';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { _createSystemMutation, _createSystemQuery, createMutation, createQuery } from '../methods';\nimport { MigrationScript, default as migrationModule, runMigrations } from '../migration';\nimport rateLimitModule from '../rate-limit';\nimport { initRateLimits } from '../rate-limit/rules';\nimport { viteServer } from '../viteServer';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { Module } from './module';\nimport { startServer } from './server';\nimport { markAppStarted, setMetadata } from './state';\nimport { EmailConfig, setEmailConfig } from './emailConfig';\nimport { AuthConfig, setAuthConfig } from './authConfig';\nimport { WebsocketConfig, setWebsocketConfig } from './websocketConfig';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n email?: EmailConfig,\n auth?: AuthConfig,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>,\n websocket?: WebsocketConfig;\n}\n\nexport async function startApp({\n modules = [],\n roles = {},\n defaultRoles = {},\n server = viteServer,\n migrations = [],\n email = {},\n auth = {},\n websocket = {},\n}: AppOptions) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule, rateLimitModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema);\n const stores = getStores(combinedModules);\n const channels = getChannels(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n const rateLimits = getRateLimits(combinedModules);\n initRateLimits(rateLimits);\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs(configSchema));\n }\n\n setEmailConfig(email);\n setAuthConfig(auth);\n setWebsocketConfig({\n ...websocket,\n provider: websocket.provider || socketioServer,\n });\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules, channels });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getChannels(modules: Module[]) {\n return modules.flatMap(module => module.channels);\n}\n\nfunction getRateLimits(modules: Module[]) {\n return modules.flatMap(module => module.rateLimits);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nconst localConfigMap = {\n MONGODB_URI: '_system.mongodbUri',\n MODELENCE_AUTH_GOOGLE_ENABLED: '_system.user.auth.google.enabled',\n MODELENCE_AUTH_GOOGLE_CLIENT_ID: '_system.user.auth.google.clientId',\n MODELENCE_AUTH_GOOGLE_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n MODELENCE_EMAIL_RESEND_API_KEY: '_system.email.resend.apiKey',\n MODELENCE_EMAIL_AWS_SES_REGION: '_system.email.awsSes.region',\n MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID: '_system.email.awsSes.accessKeyId',\n MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY: '_system.email.awsSes.secretAccessKey',\n MODELENCE_EMAIL_SMTP_HOST: '_system.email.smtp.host',\n MODELENCE_EMAIL_SMTP_PORT: '_system.email.smtp.port',\n MODELENCE_EMAIL_SMTP_USER: '_system.email.smtp.user',\n MODELENCE_EMAIL_SMTP_PASS: '_system.email.smtp.pass',\n // deprecated\n GOOGLE_AUTH_ENABLED: '_system.user.auth.google.enabled',\n GOOGLE_AUTH_CLIENT_ID: '_system.user.auth.google.clientId',\n GOOGLE_AUTH_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n};\n\nfunction formatLocalConfigValue(value: string, type: ConfigType): string | number | boolean {\n if (type === 'number') {\n const numValue = Number(value);\n if (isNaN(numValue)) {\n throw new Error(`Invalid number value for config: ${value}`);\n }\n return numValue;\n }\n if (type === 'boolean') {\n if (value.toLowerCase() === 'true') {\n return true;\n }\n if (value.toLowerCase() === 'false') {\n return false;\n }\n throw new Error(`Invalid boolean value for config: ${value}`);\n }\n return value;\n}\n\nfunction getLocalConfigs(configSchema: ConfigSchema): AppConfig[] {\n const configs: AppConfig[] = [];\n\n for (const [envVar, configKey] of Object.entries(localConfigMap)) {\n const value = process.env[envVar];\n const configSchemaEntry = configSchema[configKey];\n if (value) {\n const type = configSchemaEntry?.type ?? 'string';\n configs.push({\n key: configKey,\n type: type,\n value: formatLocalConfigValue(value, type),\n });\n }\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const appDetails = await getAppDetails();\n const modelencePackageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n projectName: appDetails.name,\n version: modelencePackageJson.default.version,\n localHostname: os.hostname(),\n environmentId\n })\n });\n }\n}\n\nasync function getAppDetails() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n \n return {\n name: packageJson.name || 'unknown'\n };\n } catch (error) {\n return {\n name: 'unknown'\n };\n }\n}\n","import { Session, User } from \"@/auth/types\";\nimport { getWebsocketConfig } from \"@/app/websocketConfig\";\nimport { logError } from \"../telemetry\";\n\ntype canAccessChannel = (props: {\n user: User | null,\n session: Session | null,\n roles: string[],\n}) => Promise<boolean>;\n\nexport class ServerChannel<T = any> {\n public readonly category: string;\n public readonly canAccessChannel: canAccessChannel | null;\n\n constructor(\n category: string,\n canAccessChannel?: canAccessChannel,\n ) {\n this.category = category;\n this.canAccessChannel = canAccessChannel || null;\n }\n\n broadcast(id: string, data: T) {\n const websocketProvider = getWebsocketConfig().provider;\n if (!websocketProvider) {\n logError(\"Websockets provider should be added to startApp\", {});\n return;\n }\n\n websocketProvider.broadcast({\n category: this.category,\n id,\n data,\n });\n }\n}\n","import { getEmailConfig } from \"@/app/emailConfig\";\nimport { EmailPayload } from \"../types\";\n\nexport function sendEmail(payload: EmailPayload) {\n if (!getEmailConfig().provider) {\n throw new Error('Email provider is not configured, see https://docs.modelence.com/email-configuration for more details.');\n }\n return getEmailConfig().provider?.sendEmail(payload);\n}\n"]}
1
+ {"version":3,"sources":["../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/role.ts","../src/auth/index.ts","../src/db/client.ts","../src/websocket/socketio/server.ts","../src/auth/disposableEmails.ts","../src/app/emailConfig.ts","../src/utils/index.ts","../src/auth/templates/emailVerficationTemplate.ts","../src/auth/verification.ts","../src/auth/validators.ts","../src/app/authConfig.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/rate-limit/db.ts","../src/rate-limit/rules.ts","../src/auth/signup.ts","../src/auth/resetPassword.ts","../src/auth/user.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/cron/jobs.ts","../src/methods/index.ts","../src/migration/db.ts","../src/migration/index.ts","../src/rate-limit/index.ts","../src/viteServer.ts","../src/auth/providers/google.ts","../src/routes/handler.ts","../src/app/websocketConfig.ts","../src/app/server.ts","../src/app/index.ts","../src/websocket/serverChannel.ts","../src/app/email.ts"],"names":["Module","name","stores","queries","mutations","routes","cronJobs","configSchema","rateLimits","channels","Store","options","client","document","selector","ObjectId","query","errorHandler","result","cursor","id","idSelector","documents","update","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","args","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","emailVerificationTokensCollection","resetPasswordTokensCollection","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","authenticate","userDoc","connect","mongodbUri","getMongodbUri","MongoClient","err","value","getConfig","getClient","socketServer","COLLECTION","init","httpServer","mongodbClient","mongoCollection","error","SocketServer","createAdapter","socket","next","token","channelName","category","channel","broadcast","data","server_default","isDisposableEmail","email","emailParts","domain","updateDisposableEmailListCron","response","domains","batchSize","batch","emailConfig","setEmailConfig","newEmailConfig","getEmailConfig","isServer","requireServer","htmlToText","html","emailVerificationTemplate","verificationUrl","handleVerifyEmail","params","baseUrl","emailVerifiedRedirectUrl","tokenDoc","sendVerificationEmail","emailProvider","verificationToken","htmlTemplate","textContent","validatePassword","validateEmail","authConfig","setAuthConfig","newAuthConfig","getAuthConfig","handleLoginWithPassword","connectionInfo","ip","consumeRateLimit","password","passwordHash","incorrectCredentialsError","e","bcrypt","handleLogout","getOwnProfile","_args","profile","dbRateLimits","allRules","initRateLimits","bucket","type","rules","rule","checkRateLimitRule","createError","createRateLimitError","RateLimitError","record","currentWindowStart","count","modifier","getCount","prevWindowStart","currentWindowCount","prevWindowCount","prevWindowWeight","weight","handleSignupWithPassword","existingUser","existingEmail","hash","userDocument","resolveUrl","configuredUrl","defaultPasswordResetTemplate","resetUrl","passwordResetSent","handleSendResetPasswordToken","resetToken","handleResetPassword","resetTokenDoc","user_default","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","callApi","os","fetchConfigs","syncStatus","endpoint","method","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","handler","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","job","tickCronJobs","ms","resolve","state","startCronJob","transaction","startTransaction","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","permissions","runMethod","context","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","migration_default","rate_limit_default","ViteServer","createServer","staticFolders","express","req","res","loadUserViteConfig","appDir","loadConfigFromFile","safelyMergeConfig","baseConfig","userConfig","mergedConfig","mergeConfig","seenPlugins","plugin","pluginName","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","defineConfig","code","bundle","viteServer","authenticateUser","handleGoogleAuthenticationCallback","googleUser","getCallContext","googleEmail","newUser","getRouter","googleAuthRouter","Router","googleEnabled","googleClientId","googleClientSecret","passport","GoogleStrategy","accessToken","refreshToken","done","google_default","createRouteHandler","key","ModelenceError","websocketConfig","setWebsocketConfig","newWebsocketConfig","getWebsocketConfig","registerModuleRoutes","app","modules","module","route","handlers","startServer","server","combinedModules","cookieParser","methodName","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","http","websocketProvider","port","logInfo","val","clientInfo","getClientIp","forwardedFor","directIp","startApp","auth","websocket","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","getChannels","defineCronJobs","getRateLimits","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","localConfigMap","formatLocalConfigValue","numValue","envVar","configKey","configSchemaEntry","serviceEndpoint","appDetails","getAppDetails","modelencePackageJson","packageJsonPath","packageJsonContent","ServerChannel","canAccessChannel","logError","sendEmail"],"mappings":"q4BAwCaA,CAAAA,CAAN,KAAa,CAqClB,WAAA,CACEC,CAAAA,CACA,CACE,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,OAAA,CAAAC,CAAAA,CAAU,EAAC,CACX,UAAAC,CAAAA,CAAY,EAAC,CACb,MAAA,CAAAC,CAAAA,CAAS,EAAC,CACV,QAAA,CAAAC,CAAAA,CAAW,EAAC,CACZ,YAAA,CAAAC,CAAAA,CAAe,GACf,UAAA,CAAAC,CAAAA,CAAa,EAAC,CACd,QAAA,CAAAC,CAAAA,CAAW,EACb,CAAA,CAUA,CACA,IAAA,CAAK,IAAA,CAAOR,CAAAA,CACZ,KAAK,MAAA,CAASC,CAAAA,CACd,IAAA,CAAK,OAAA,CAAUC,CAAAA,CACf,IAAA,CAAK,SAAA,CAAYC,CAAAA,CACjB,IAAA,CAAK,MAAA,CAASC,CAAAA,CACd,IAAA,CAAK,QAAA,CAAWC,CAAAA,CAChB,KAAK,YAAA,CAAeC,CAAAA,CACpB,IAAA,CAAK,UAAA,CAAaC,CAAAA,CAClB,IAAA,CAAK,QAAA,CAAWC,EAClB,CACF,MC5DaC,CAAAA,CAAN,KAGL,CAuBA,WAAA,CACET,CAAAA,CACAU,CAAAA,CAQA,CACA,IAAA,CAAK,IAAA,CAAOV,CAAAA,CACZ,IAAA,CAAK,MAAA,CAASU,CAAAA,CAAQ,MAAA,CACtB,KAAK,OAAA,CAAUA,CAAAA,CAAQ,OAAA,CACvB,IAAA,CAAK,OAAA,CAAUA,CAAAA,CAAQ,QACzB,CAEA,OAAA,EAAU,CACR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CAC9D,MACF,CAEAnD,CAAAA,CAAkB,SAAA,CAAU,CAC1B,QAAA,CAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAxT,CAAAA,CACA,IAAA,CAAAiF,CACF,CAAC,EACH,CACF,EChCO,SAAS2R,EAAAA,CAAU1L,CAAAA,CAAuB,CAC/C,GAAI,CAACnF,CAAAA,EAAe,CAAE,QAAA,CACpB,MAAM,IAAI,KAAA,CAAM,0FAA0F,CAAA,CAE5G,OAAOA,CAAAA,EAAe,CAAE,QAAA,EAAU,SAAA,CAAUmF,CAAO,CACrD","file":"server.js","sourcesContent":["import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\nimport { RateLimitRule } from '../rate-limit/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /** @internal */\n public readonly rateLimits: RateLimitRule[];\n\n /** @internal */\n public readonly channels: ServerChannel[];\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {},\n rateLimits = [],\n channels = []\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema,\n rateLimits?: RateLimitRule[],\n channels?: ServerChannel[],\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n this.rateLimits = rateLimits;\n this.channels = channels;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /**\n * For convenience, to also allow directy passing a string or ObjectId as the selector\n */\n private getSelector(selector: Filter<this['_type']> | string | ObjectId) {\n if (typeof selector === 'string') {\n return { _id: new ObjectId(selector) } as Filter<this['_type']>;\n }\n\n if (selector instanceof ObjectId) {\n return { _id: selector } as Filter<this['_type']>;\n }\n\n return selector;\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Counts the number of documents that match a query\n * \n * @param query - The query to filter documents\n * @returns The number of documents that match the query\n */\n countDocuments(query: Filter<this['_type']>): Promise<number> {\n return this.requireCollection().countDocuments(query);\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']> | string | ObjectId, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(this.getSelector(selector), update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { ObjectId } from 'mongodb';\nimport { Module } from '../app/module';\nimport { getPublicConfigs } from '../config/server';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { time } from '../time';\nimport { Session } from './types';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nexport async function createSession(userId: ObjectId | null = null): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId,\n });\n\n return {\n authToken,\n expiresAt,\n userId,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n\nexport const emailVerificationTokensCollection = new Store('_modelenceEmailVerificationTokens', {\n schema: {\n userId: schema.objectId(),\n email: schema.string().optional(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n\nexport const resetPasswordTokensCollection = new Store('_modelenceResetPasswordTokens', {\n schema: {\n userId: schema.objectId(),\n token: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n },\n indexes: [\n {\n key: { token: 1 },\n unique: true\n },\n {\n key: { expiresAt: 1 },\n expireAfterSeconds: 0\n }\n ]\n});\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import { Server } from \"http\";\nimport { Server as SocketServer, Socket } from 'socket.io';\nimport { createAdapter } from \"@socket.io/mongo-adapter\";\nimport { authenticate } from \"@/auth\";\nimport { getClient } from \"@/db/client\";\nimport { WebsocketServerProvider } from \"../types\";\nimport { ServerChannel } from \"../serverChannel\";\n\nlet socketServer: SocketServer | null = null;\n\nconst COLLECTION = '_modelenceSocketio';\n\nexport async function init({\n httpServer,\n channels,\n}: {\n httpServer: Server;\n channels: ServerChannel[];\n}) {\n\n const mongodbClient = getClient();\n\n if (!mongodbClient) {\n console.error('Socket.IO initialization failed: MongoDB client is not initialized');\n throw new Error('Mongodb Client is not initialized');\n }\n\n console.log('Initializing Socket.IO server...');\n\n const mongoCollection = mongodbClient.db().collection(COLLECTION);\n\n try {\n await mongoCollection.createIndex(\n { createdAt: 1 },\n { expireAfterSeconds: 3600, background: true }\n );\n } catch (error) {\n console.error('Failed to create index on MongoDB collection for Socket.IO:', error);\n }\n\n socketServer = new SocketServer(httpServer, {\n cors: {\n origin: \"*\",\n methods: [\"GET\", \"POST\"]\n },\n adapter: createAdapter(mongoCollection),\n transports: ['polling', 'websocket'],\n allowUpgrades: true,\n perMessageDeflate: false,\n });\n\n socketServer.on('error', (error) => {\n console.error('Socket.IO error:', error);\n });\n\n socketServer.use(async (socket, next) => {\n const token = socket.handshake.auth.token;\n\n try {\n socket.data = await authenticate(token);\n } finally {\n next();\n }\n });\n\n socketServer.on('connection', (socket: Socket) => {\n console.log(`Socket.IO client connected`);\n \n socket.on('disconnect', () => {\n console.log(`Socket.IO client disconnected`);\n });\n\n socket.on('joinChannel', async (channelName) => {\n const [category] = channelName.split(':');\n for (const channel of channels) {\n if (\n channel.category === category &&\n (\n !channel.canAccessChannel ||\n await channel.canAccessChannel(socket.data)\n )\n ) {\n socket.join(channelName);\n }\n }\n\n socket.join(channelName);\n console.log(`User ${socket.id} joined channel ${channelName}`);\n socket.emit('joinedChannel', channelName);\n });\n\n socket.on('leaveChannel', (channelName) => {\n socket.leave(channelName);\n console.log(`User ${socket.id} left channel ${channelName}`);\n socket.emit('leftChannel', channelName);\n });\n });\n\n console.log(\"Socket.IO server initialized\");\n}\n\nfunction broadcast<T>({\n category,\n id,\n data,\n}: {\n category: string,\n id: string,\n data: T,\n}) {\n socketServer?.to(`${category}:${id}`).emit(category, data);\n}\n\nexport default {\n init,\n broadcast,\n} as WebsocketServerProvider;\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import type { EmailProvider } from \"../types\";\n\nexport type EmailConfig = {\n provider?: EmailProvider;\n from?: string;\n verification?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n verificationUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n passwordReset?: {\n subject?: string;\n template?: (props: {\n name: string;\n email: string;\n resetUrl: string;\n }) => string;\n redirectUrl?: string;\n };\n // @deprecated use verification.redirectUrl instead\n emailVerifiedRedirectUrl?: string;\n};\n\nlet emailConfig: EmailConfig = Object.freeze({});\n\nexport function setEmailConfig(newEmailConfig: EmailConfig) {\n emailConfig = Object.freeze(Object.assign({}, emailConfig, newEmailConfig));\n}\n\nexport function getEmailConfig() {\n return emailConfig;\n}\n","export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n\nexport function htmlToText(html: string) {\n return html.replace(/<[^>]*>/g, '').replace(/\\s+/g, ' ').trim()\n}\n","export function emailVerificationTemplate({ name, email, verificationUrl }: { name?: string; email: string; verificationUrl: string }) {\n return `\n <p>Hi${name ? ` ${name}` : ''},</p>\n <p>Please verify your email address ${email} by clicking the link below:</p>\n <p><a href=\"${verificationUrl}\">${verificationUrl}</a></p>\n <p>If you did not request this, please ignore this email.</p>\n `;\n}\n","import { z } from 'zod';\n\nimport { usersCollection, emailVerificationTokensCollection } from './db';\nimport { ObjectId, RouteParams, RouteResponse } from '@/server';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { randomBytes } from 'crypto';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { emailVerificationTemplate } from './templates/emailVerficationTemplate';\n\nexport async function handleVerifyEmail(params: RouteParams): Promise<RouteResponse> {\n const baseUrl = process.env.MODELENCE_SITE_URL;\n const emailVerifiedRedirectUrl = getEmailConfig().emailVerifiedRedirectUrl || baseUrl || '/';\n try {\n const token = z.string().parse(params.query.token);\n // Find token in database\n const tokenDoc = await emailVerificationTokensCollection.findOne({\n token,\n expiresAt: { $gt: new Date() }\n });\n\n if (!tokenDoc) {\n throw new Error('Invalid or expired verification token');\n }\n\n // Find user by token's userId\n const userDoc = await usersCollection.findOne({ _id: tokenDoc.userId });\n\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n const email = tokenDoc.email;\n\n if (!email) {\n throw new Error('Email not found in token');\n }\n\n // Mark the specific email as verified atomically\n const updateResult = await usersCollection.updateOne(\n { \n _id: tokenDoc.userId,\n 'emails.address': email,\n 'emails.verified': { $ne: true }\n },\n { $set: { 'emails.$.verified': true } }\n );\n\n if (updateResult.matchedCount === 0) {\n // Check if email exists but is already verified\n const existingUser = await usersCollection.findOne({\n _id: tokenDoc.userId,\n 'emails.address': email\n });\n \n if (existingUser) {\n throw new Error('Email is already verified');\n } else {\n throw new Error('Email address not found for this user');\n }\n }\n\n // Delete the used token\n await emailVerificationTokensCollection.deleteOne({ _id: tokenDoc._id });\n } catch (error) {\n if (error instanceof Error) {\n console.error('Error verifying email:', error);\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=error&message=${encodeURIComponent(error.message)}`,\n };\n }\n }\n\n return {\n status: 301,\n redirect: `${emailVerifiedRedirectUrl}?status=verified`,\n };\n}\n\nexport async function sendVerificationEmail({\n userId,\n email,\n baseUrl = process.env.MODELENCE_SITE_URL\n}: {\n userId: ObjectId;\n email: string;\n baseUrl?: string;\n}) {\n if (getEmailConfig().provider) {\n const emailProvider = getEmailConfig().provider;\n\n // Generate verification token\n const verificationToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(24));\n\n // Store token in database\n await emailVerificationTokensCollection.insertOne({\n userId,\n email,\n token: verificationToken,\n createdAt: new Date(),\n expiresAt,\n });\n \n const verificationUrl = `${baseUrl}/api/_internal/auth/verify-email?token=${verificationToken}`;\n \n const template = getEmailConfig()?.verification?.template || emailVerificationTemplate;\n // TODO: we should have also the name on this step\n const htmlTemplate = template({ name: '', email, verificationUrl });\n const textContent = htmlToText(htmlTemplate);\n \n await emailProvider?.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.verification?.subject || 'Verify your email address',\n text: textContent,\n html: htmlTemplate,\n });\n }\n}\n","import { z } from \"zod\";\n\nexport function validatePassword(value: string) {\n return z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(value);\n}\n\nexport function validateEmail(value: string) {\n return z.string()\n .email({ message: 'Invalid email address' })\n .parse(value);\n}\n","import { Session, User } from \"@/auth/types\";\nimport { ConnectionInfo } from \"@/methods/types\";\n\n/**\n * Callback options for authentication operations\n */\nexport type AuthOption = {\n /** Callback executed when authentication succeeds */\n onSuccess?: (user: User) => void;\n /** Callback executed when authentication fails */\n onError?: (error: Error) => void;\n}\n\n/**\n * Authentication configuration for the application\n *\n * @example\n * ```typescript\n * import { startApp } from 'modelence/server';\n *\n * startApp({\n * auth: {\n * onAfterLogin: ({ user }) => {\n * console.log('User logged in:', user.name);\n * // Redirect to dashboard\n * },\n * onLoginError: ({ error }) => {\n * console.error('Login failed:', error.message);\n * // Show error toast\n * },\n * onAfterSignup: ({ user }) => {\n * console.log('User signed up:', user.email);\n * // Send welcome email\n * },\n * onSignupError: ({ error }) => {\n * console.error('Signup failed:', error.message);\n * }\n * }\n * });\n * ```\n */\nexport type AuthConfig = {\n onAfterLogin?: (props: {\n user: User,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onLoginError?: (props: {\n error: Error,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onAfterSignup?: (props: {\n user: User,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n onSignupError?: (props: {\n error: Error,\n session: Session | null,\n connectionInfo: ConnectionInfo,\n }) => void;\n\n /** deprecated: use onAfterLogin and onLoginError */\n login?: AuthOption;\n /** deprecated: user onAfterSignup and onSignupError */\n signup?: AuthOption;\n};\n\nlet authConfig: AuthConfig = Object.freeze({});\n\nexport function setAuthConfig(newAuthConfig: AuthConfig) {\n authConfig = Object.freeze(Object.assign({}, authConfig, newAuthConfig));\n}\n\nexport function getAuthConfig() {\n return authConfig;\n}\n","import bcrypt from 'bcrypt';\nimport { z } from 'zod';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\nimport { sendVerificationEmail } from './verification';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { consumeRateLimit } from '@/server';\nimport { validateEmail } from './validators';\nimport { getAuthConfig } from '@/app/authConfig';\n\nexport async function handleLoginWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n try {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signin',\n type: 'ip',\n value: ip,\n });\n }\n\n const email = validateEmail(args.email as string);\n // password is accepted just as a string, so users can still sign in if the password validation rules are changed\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const emailDoc = userDoc.emails?.find(e => e.address === email);\n\n if (!emailDoc?.verified && getEmailConfig()?.provider) {\n if (ip) {\n try {\n await consumeRateLimit({\n bucket: 'verification',\n type: 'user',\n value: userDoc._id.toString(),\n });\n } catch {\n throw new Error(\"Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.\");\n }\n }\n\n await sendVerificationEmail({\n userId: userDoc?._id,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n throw new Error(\"Your email address hasn't been verified yet. We've sent a new verification email to your inbox.\");\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n getAuthConfig().onAfterLogin?.({\n user: userDoc,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onSuccess?.(userDoc);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n } catch (error) {\n if (error instanceof Error) {\n getAuthConfig().onLoginError?.({\n error,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onError?.(error);\n }\n throw error;\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\n/**\n * Two-bucket sliding window approximation to track rate limits.\n * This is a trade-off between storage and accuracy.\n * We're not keeping exact event logs, so we can't track the exact number of events in a window.\n * Instead, we're adding a weighted average from the previous window to the current window.\n */\nexport const dbRateLimits = new Store('_modelenceRateLimits', {\n schema: {\n bucket: schema.string(),\n type: schema.enum(['ip', 'user']),\n value: schema.string(),\n windowMs: schema.number(),\n\n windowStart: schema.date(),\n windowCount: schema.number(),\n prevWindowCount: schema.number(),\n\n expiresAt: schema.date(),\n },\n indexes: [\n { key: { bucket: 1, type: 1, value: 1, windowMs: 1 }, unique: true },\n { key: { expiresAt: 1 }, expireAfterSeconds: 0 },\n ]\n});\n","import { RateLimitRule, RateLimitType } from './types';\nimport { dbRateLimits } from './db';\nimport { RateLimitError } from '../error';\n\nlet allRules: Array<RateLimitRule> = [];\n\nexport function initRateLimits(rateLimits: RateLimitRule[]) {\n if (allRules.length > 0) {\n throw new Error('Duplicate call to initRateLimits - already initialized');\n }\n\n allRules = rateLimits;\n}\n\n/**\n * This function will check all rate limit rules on the specified bucket and type,\n * throw an error if any of them are exceeded and increase the count of the rate limit record.\n * \n * @category Rate Limits\n * \n * @example\n * ```ts\n * await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' });\n * ```\n * @param options.bucket - The bucket for the rate limit.\n * @param options.type - The type of the rate limit.\n * @param options.value - The value for the rate limit.\n */\nexport async function consumeRateLimit(\n options: { bucket: string, type: RateLimitType, value: string }\n) {\n const { bucket, type, value } = options;\n const rules = allRules.filter(rule => rule.bucket === bucket && rule.type === type);\n\n for (const rule of rules) {\n await checkRateLimitRule(rule, value);\n }\n}\n\n// Two-bucket sliding window approximation to track rate limits.\nasync function checkRateLimitRule(rule: RateLimitRule, value: string, createError?: () => Error) {\n const createRateLimitError = () => {\n return createError ? createError() : new RateLimitError(`Rate limit exceeded for ${rule.bucket}`);\n };\n\n const record = await dbRateLimits.findOne({\n bucket: rule.bucket,\n type: rule.type,\n value,\n windowMs: rule.window,\n });\n\n const now = Date.now();\n const currentWindowStart = Math.floor(now / rule.window) * rule.window;\n\n const { count, modifier } = record\n ? getCount(record, currentWindowStart, now)\n : {\n count: 0,\n modifier: {\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + rule.window + rule.window),\n }\n }\n };\n\n if (count >= rule.limit) {\n throw createRateLimitError();\n }\n\n /*\n Always use upsert, because there is a small chance the document might be auto-removed\n based on the expiration TTL index in between the check and the update\n */\n await dbRateLimits.upsertOne(\n { bucket: rule.bucket, type: rule.type, value, windowMs: rule.window }, \n modifier\n );\n}\n\nfunction getCount(record: typeof dbRateLimits['Doc'], currentWindowStart: number, now: number) {\n const prevWindowStart = currentWindowStart - record.windowMs;\n \n if (record.windowStart.getTime() === currentWindowStart) {\n const currentWindowCount = record.windowCount;\n const prevWindowCount = record.prevWindowCount;\n const prevWindowWeight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(currentWindowCount + prevWindowCount * prevWindowWeight),\n modifier: {\n $inc: { windowCount: 1 },\n $setOnInsert: {\n windowStart: new Date(currentWindowStart),\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n if (record.windowStart.getTime() === prevWindowStart) {\n const weight = 1 - (now - currentWindowStart) / record.windowMs;\n return {\n count: Math.round(record.windowCount * weight),\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: record.windowCount,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n }\n \n return {\n count: 0,\n modifier: {\n $set: {\n windowStart: new Date(currentWindowStart),\n windowCount: 1,\n prevWindowCount: 0,\n expiresAt: new Date(currentWindowStart + record.windowMs + record.windowMs),\n }\n }\n };\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { isDisposableEmail } from './disposableEmails';\nimport { consumeRateLimit } from '../rate-limit/rules';\nimport { sendVerificationEmail } from './verification';\nimport { validateEmail, validatePassword } from './validators';\nimport { getAuthConfig } from '@/app/authConfig';\n\nexport async function handleSignupWithPassword(args: Args, { user, session, connectionInfo }: Context) {\n try {\n const email = validateEmail(args.email as string);\n const password = validatePassword(args.password as string);\n\n const ip = connectionInfo?.ip;\n if (ip) {\n await consumeRateLimit({\n bucket: 'signupAttempt',\n type: 'ip',\n value: ip,\n });\n }\n\n if (await isDisposableEmail(email)) {\n throw new Error('Please use a permanent email address');\n }\n\n // TODO: captcha check\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n if (ip) {\n await consumeRateLimit({\n bucket: 'signup',\n type: 'ip',\n value: ip,\n });\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n const userDocument = await usersCollection.findOne(\n { _id: result.insertedId },\n { readPreference: \"primary\" }\n );\n\n if (!userDocument) {\n throw new Error('User not found');\n }\n\n await sendVerificationEmail({\n userId: result?.insertedId,\n email,\n baseUrl: connectionInfo?.baseUrl,\n });\n\n getAuthConfig().onAfterSignup?.({\n user: userDocument,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onSuccess?.(userDocument);\n\n return result.insertedId;\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().onSignupError?.({\n error,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onError?.(error);\n }\n throw error;\n }\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\nimport { randomBytes } from 'crypto';\n\nimport { Args, Context } from '@/methods/types';\nimport { usersCollection, resetPasswordTokensCollection } from './db';\nimport { getEmailConfig } from '@/app/emailConfig';\nimport { time } from '@/time';\nimport { htmlToText } from '@/utils';\nimport { validateEmail, validatePassword } from './validators';\n\nfunction resolveUrl(baseUrl: string, configuredUrl?: string): string {\n if (!configuredUrl) {\n return baseUrl;\n }\n \n if (configuredUrl.startsWith('http://') || configuredUrl.startsWith('https://')) {\n return configuredUrl;\n }\n \n // Handle relative URL\n return `${baseUrl}${configuredUrl.startsWith('/') ? '' : '/'}${configuredUrl}`;\n}\n\nfunction defaultPasswordResetTemplate({ email, resetUrl }: { email: string; resetUrl: string }) {\n return `\n <p>Hi,</p>\n <p>We received a request to reset your password for ${email}.</p>\n <p>Click the link below to reset your password:</p>\n <p><a href=\"${resetUrl}\">${resetUrl}</a></p>\n <p>This link will expire in 1 hour.</p>\n <p>If you did not request this password reset, please ignore this email.</p>\n `;\n}\n\nconst passwordResetSent = { success: true, message: 'If an account with that email exists, a password reset link has been sent' };\n\nexport async function handleSendResetPasswordToken(args: Args, { connectionInfo }: Context) {\n const email = validateEmail(args.email as string);\n\n // Find user by email\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (!userDoc) {\n // For security, don't reveal if email exists or not\n return passwordResetSent;\n }\n\n // Check if user has password auth method\n if (!userDoc.authMethods?.password) {\n return passwordResetSent;\n }\n\n const emailProvider = getEmailConfig().provider;\n if (!emailProvider) {\n throw new Error('Email provider is not configured');\n }\n\n // Generate reset token\n const resetToken = randomBytes(32).toString('hex');\n const expiresAt = new Date(Date.now() + time.hours(1)); // 1 hour expiry\n\n // Store reset token\n await resetPasswordTokensCollection.insertOne({\n userId: userDoc._id,\n token: resetToken,\n createdAt: new Date(),\n expiresAt,\n });\n\n // Build reset URL\n const baseUrl = process.env.MODELENCE_SITE_URL || connectionInfo?.baseUrl;\n const resetPasswordUrl = resolveUrl(baseUrl!, getEmailConfig().passwordReset?.redirectUrl);\n const resetUrl = `${resetPasswordUrl}?token=${resetToken}`;\n\n // Send email\n const template = getEmailConfig()?.passwordReset?.template || defaultPasswordResetTemplate;\n const htmlTemplate = template({ email, resetUrl, name: '' });\n const textContent = htmlToText(htmlTemplate);\n\n await emailProvider.sendEmail({\n to: email,\n from: getEmailConfig()?.from || 'noreply@modelence.com',\n subject: getEmailConfig()?.passwordReset?.subject || 'Reset your password',\n text: textContent,\n html: htmlTemplate,\n });\n\n return passwordResetSent;\n}\n\nexport async function handleResetPassword(args: Args, { }: Context) {\n const token = z.string().parse(args.token);\n const password = validatePassword(args.password as string);\n\n // Find the reset token\n const resetTokenDoc = await resetPasswordTokensCollection.findOne({ token });\n if (!resetTokenDoc) {\n throw new Error('Invalid or expired reset token');\n }\n\n // Check if token is expired\n if (resetTokenDoc.expiresAt < new Date()) {\n await resetPasswordTokensCollection.deleteOne({ token });\n throw new Error('Reset token has expired');\n }\n\n // Find the user\n const userDoc = await usersCollection.findOne({ _id: resetTokenDoc.userId });\n if (!userDoc) {\n throw new Error('User not found');\n }\n\n // Hash the new password\n const hash = await bcrypt.hash(password, 10);\n\n // Update user's password\n await usersCollection.updateOne(\n { _id: userDoc._id },\n {\n $set: {\n 'authMethods.password.hash': hash\n }\n }\n );\n\n // Delete the used reset token\n await resetPasswordTokensCollection.deleteOne({ token });\n\n return { success: true, message: 'Password has been reset successfully' };\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { time } from '../time';\nimport {\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n usersCollection\n} from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { handleSignupWithPassword } from './signup';\nimport { handleVerifyEmail } from './verification';\nimport { handleResetPassword, handleSendResetPasswordToken } from './resetPassword';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [\n usersCollection,\n dbDisposableEmailDomains,\n emailVerificationTokensCollection,\n resetPasswordTokensCollection,\n ],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n sendResetPasswordToken: handleSendResetPasswordToken,\n resetPassword: handleResetPassword,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n },\n rateLimits: [{\n bucket: 'signup',\n type: 'ip',\n window: time.minutes(15),\n limit: 20,\n }, {\n bucket: 'signup',\n type: 'ip',\n window: time.days(1),\n limit: 200,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signupAttempt',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.minutes(15),\n limit: 50,\n }, {\n bucket: 'signin',\n type: 'ip',\n window: time.days(1),\n limit: 500,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.minutes(15),\n limit: 3,\n }, {\n bucket: 'verification',\n type: 'user',\n window: time.days(1),\n limit: 10,\n }],\n configSchema: {\n 'auth.email.enabled': {\n type: 'boolean',\n isPublic: true,\n default: true,\n },\n 'auth.email.from': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.email.verification': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.enabled': {\n type: 'boolean',\n isPublic: true,\n default: false,\n },\n 'auth.google.clientId': {\n type: 'string',\n isPublic: false,\n default: '',\n },\n 'auth.google.clientSecret': {\n type: 'secret',\n isPublic: false,\n default: '',\n },\n },\n routes: [\n {\n path: '/api/_internal/auth/verify-email',\n handlers: {\n get: handleVerifyEmail\n },\n }\n ],\n});\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await Promise.all(aliasList.map(alias => \n cronJobsCollection.upsertOne(\n { alias },\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n )\n ));\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","import { Module } from '../app/module';\nimport { dbRateLimits } from './db';\n\nexport default new Module('_system.rateLimit', {\n stores: [dbRateLimits],\n});\n","import { createServer, defineConfig, ViteDevServer, loadConfigFromFile, UserConfig, mergeConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport type { AppServer, ExpressMiddleware } from './types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n private config?: UserConfig;\n\n async init() {\n this.config = await getConfig();\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer(this.config); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n const staticFolders = [express.static('./.modelence/build/client'.replace(/\\\\/g, '/'))];\n if (this.config?.publicDir) {\n staticFolders.push(express.static(this.config.publicDir));\n }\n return staticFolders;\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client'.replace(/\\\\/g, '/') });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function loadUserViteConfig() {\n const appDir = process.cwd();\n \n try {\n const result = await loadConfigFromFile({ command: 'serve', mode: 'development' }, undefined, appDir);\n return result?.config || {};\n } catch (error) {\n console.warn(`Could not load vite config:`, error);\n return {};\n }\n}\n\nfunction safelyMergeConfig(baseConfig: UserConfig, userConfig: UserConfig) {\n const mergedConfig = mergeConfig(baseConfig, userConfig);\n \n // Deduplicate plugins by name, keeping user plugins over framework plugins\n if (mergedConfig.plugins && Array.isArray(mergedConfig.plugins)) {\n const seenPlugins = new Set();\n mergedConfig.plugins = mergedConfig.plugins.flat().filter((plugin: any) => {\n if (!plugin || typeof plugin !== 'object') {\n return true;\n }\n const pluginName = plugin.name;\n if (!pluginName || seenPlugins.has(pluginName)) {\n return false;\n }\n seenPlugins.add(pluginName);\n return true;\n }).reverse(); // Reverse to prioritize user plugins over framework plugins\n mergedConfig.plugins.reverse(); // Reverse back to maintain original order\n }\n\n return mergedConfig;\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n const userConfig = await loadUserViteConfig();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n const baseConfig = defineConfig({\n plugins,\n build: {\n outDir: '.modelence/build/client'.replace(/\\\\/g, '/'),\n emptyOutDir: true\n },\n server: {\n middlewareMode: true,\n },\n root: './src/client',\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src').replace(/\\\\/g, '/')\n }\n },\n });\n\n return safelyMergeConfig(baseConfig, userConfig);\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import { getConfig } from \"@/server\";\nimport { Router, type Request, type Response } from \"express\";\nimport { ObjectId } from \"mongodb\";\nimport passport from \"passport\";\nimport { Strategy as GoogleStrategy } from \"passport-google-oauth20\";\nimport { usersCollection } from \"../db\";\nimport { createSession } from \"../session\";\nimport { getAuthConfig } from \"@/app/authConfig\";\nimport { getCallContext } from \"@/app/server\";\n\ninterface GoogleUser {\n id: string;\n displayName: string;\n emails: { value: string; }[];\n photos: { value: string }[];\n}\n\nasync function authenticateUser(res: Response, userId: ObjectId) {\n const { authToken } = await createSession(userId);\n\n res.cookie(\"authToken\", authToken, {\n httpOnly: true,\n secure: process.env.NODE_ENV === \"production\",\n sameSite: \"strict\",\n });\n res.status(301);\n res.redirect(\"/\");\n}\n\n\nasync function handleGoogleAuthenticationCallback(req: Request, res: Response) {\n const googleUser = req.user as GoogleUser;\n\n const existingUser = await usersCollection.findOne(\n { 'authMethods.google.id': googleUser.id },\n );\n\n const {\n session,\n connectionInfo,\n } = await getCallContext(req);\n\n try {\n if (existingUser) {\n await authenticateUser(res, existingUser._id);\n\n getAuthConfig().onAfterLogin?.({\n user: existingUser,\n session,\n connectionInfo,\n });\n getAuthConfig().login?.onSuccess?.(existingUser);\n \n return;\n }\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().login?.onError?.(error);\n\n getAuthConfig().onLoginError?.({\n error,\n session,\n connectionInfo,\n });\n }\n throw error;\n }\n\n try {\n const googleEmail = googleUser.emails[0] && googleUser.emails[0]?.value;\n\n if (!googleEmail) {\n res.status(400).json({\n error: \"Email address is required for Google authentication.\",\n });\n }\n\n const existingUserByEmail = await usersCollection.findOne(\n { 'emails.address': googleEmail, },\n { collation: { locale: 'en', strength: 2 } },\n );\n\n // TODO: check if the email is verified\n if (existingUserByEmail) {\n // TODO: handle case with an HTML page\n res.status(400).json({\n error: \"User with this email already exists. Please log in instead.\",\n });\n return;\n }\n\n // If the user does not exist, create a new user\n const newUser = await usersCollection.insertOne({\n handle: googleEmail,\n emails: [{\n address: googleEmail,\n verified: true, // Google email is considered verified\n }],\n createdAt: new Date(),\n authMethods: {\n google: {\n id: googleUser.id,\n },\n },\n });\n\n await authenticateUser(res, newUser.insertedId);\n\n const userDocument = await usersCollection.findOne(\n { _id: newUser.insertedId },\n { readPreference: \"primary\" }\n );\n\n if (userDocument) {\n getAuthConfig().onAfterSignup?.({\n user: userDocument,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onSuccess?.(userDocument);\n }\n } catch(error) {\n if (error instanceof Error) {\n getAuthConfig().onSignupError?.({\n error,\n session,\n connectionInfo,\n });\n\n getAuthConfig().signup?.onError?.(error);\n }\n throw error;\n }\n}\n\nfunction getRouter() {\n const googleAuthRouter = Router();\n const googleEnabled = Boolean(getConfig('_system.user.auth.google.enabled'));\n const googleClientId = String(getConfig('_system.user.auth.google.clientId'));\n const googleClientSecret = String(getConfig('_system.user.auth.google.clientSecret'));\n if (!googleEnabled || !googleClientId || !googleClientSecret) {\n return googleAuthRouter;\n }\n\n passport.use(new GoogleStrategy({\n clientID: googleClientId,\n clientSecret: googleClientSecret,\n callbackURL: '/api/_internal/auth/google/callback',\n proxy: true,\n }, (accessToken, refreshToken, profile, done) => {\n return done(null, profile);\n }));\n\n googleAuthRouter.get(\"/api/_internal/auth/google\", passport.authenticate(\"google\", {\n scope: [\"profile\", \"email\"],\n session: false,\n }));\n\n googleAuthRouter.get(\n \"/api/_internal/auth/google/callback\",\n passport.authenticate(\"google\", { session: false }),\n handleGoogleAuthenticationCallback,\n );\n\n return googleAuthRouter;\n}\n\nexport default getRouter;\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { ModelenceError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.redirect) {\n res.redirect(response.redirect);\n }\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { WebsocketServerProvider } from \"@/websocket/types\";\n\nexport type WebsocketConfig = {\n provider?: WebsocketServerProvider;\n};\n\nlet websocketConfig: WebsocketConfig = Object.freeze({});\n\nexport function setWebsocketConfig(newWebsocketConfig: WebsocketConfig) {\n websocketConfig = Object.freeze(Object.assign({}, websocketConfig, newWebsocketConfig));\n}\n\nexport function getWebsocketConfig() {\n return websocketConfig;\n}\n","import googleAuthRouter from '@/auth/providers/google';\nimport { runMethod } from '@/methods';\nimport { getResponseTypeMap } from '@/methods/serialize';\nimport { createRouteHandler } from '@/routes/handler';\nimport { HttpMethod } from '@/server';\nimport { logInfo } from '@/telemetry';\nimport cookieParser from 'cookie-parser';\nimport express, { Request, Response } from 'express';\nimport http from 'http';\nimport passport from 'passport';\nimport z from 'zod';\nimport type { AppServer } from '../types';\nimport { authenticate } from '../auth';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { ModelenceError } from '../error';\nimport { Module } from './module';\nimport { ConnectionInfo } from '@/methods/types';\nimport { ServerChannel } from '@/websocket/serverChannel';\nimport { getWebsocketConfig } from './websocketConfig';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, {\n combinedModules,\n channels,\n}: {\n combinedModules: Module[],\n channels: ServerChannel[]\n}) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n app.use(cookieParser());\n\n app.use(passport.initialize());\n\n app.use(googleAuthRouter());\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof ModelenceError) {\n res.status(error.status).send(error.message);\n } else if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n \n const websocketProvider = getWebsocketConfig()?.provider;\n if (websocketProvider) {\n websocketProvider.init({\n httpServer,\n channels,\n });\n }\n\n const port = process.env.MODELENCE_PORT || process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`\\nApplication started on http://localhost:${port}\\n`);\n });\n}\n\nexport async function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.cookies.authToken || req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo: ConnectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n baseUrl: req.protocol + '://' + req.get('host'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import dotenv from 'dotenv';\nimport fs from 'fs/promises';\nimport os from 'os';\nimport path from 'path';\n\nimport type { AppServer } from '../types';\nimport socketioServer from '@/websocket/socketio/server';\nimport { initRoles } from '../auth/role';\nimport sessionModule from '../auth/session';\nimport { RoleDefinition } from '../auth/types';\nimport userModule from '../auth/user';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { AppConfig, ConfigSchema, ConfigType } from '../config/types';\nimport cronModule, { defineCronJob, getCronJobsMetadata, startCronJobs } from '../cron/jobs';\nimport { Store } from '../data/store';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { _createSystemMutation, _createSystemQuery, createMutation, createQuery } from '../methods';\nimport { MigrationScript, default as migrationModule, runMigrations } from '../migration';\nimport rateLimitModule from '../rate-limit';\nimport { initRateLimits } from '../rate-limit/rules';\nimport { viteServer } from '../viteServer';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { Module } from './module';\nimport { startServer } from './server';\nimport { markAppStarted, setMetadata } from './state';\nimport { EmailConfig, setEmailConfig } from './emailConfig';\nimport { AuthConfig, setAuthConfig } from './authConfig';\nimport { WebsocketConfig, setWebsocketConfig } from './websocketConfig';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n email?: EmailConfig,\n auth?: AuthConfig,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>,\n websocket?: WebsocketConfig;\n}\n\nexport async function startApp({\n modules = [],\n roles = {},\n defaultRoles = {},\n server = viteServer,\n migrations = [],\n email = {},\n auth = {},\n websocket = {},\n}: AppOptions) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule, rateLimitModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema);\n const stores = getStores(combinedModules);\n const channels = getChannels(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n const rateLimits = getRateLimits(combinedModules);\n initRateLimits(rateLimits);\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs(configSchema));\n }\n\n setEmailConfig(email);\n setAuthConfig(auth);\n setWebsocketConfig({\n ...websocket,\n provider: websocket.provider || socketioServer,\n });\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules, channels });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getChannels(modules: Module[]) {\n return modules.flatMap(module => module.channels);\n}\n\nfunction getRateLimits(modules: Module[]) {\n return modules.flatMap(module => module.rateLimits);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nconst localConfigMap = {\n MONGODB_URI: '_system.mongodbUri',\n MODELENCE_AUTH_GOOGLE_ENABLED: '_system.user.auth.google.enabled',\n MODELENCE_AUTH_GOOGLE_CLIENT_ID: '_system.user.auth.google.clientId',\n MODELENCE_AUTH_GOOGLE_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n MODELENCE_EMAIL_RESEND_API_KEY: '_system.email.resend.apiKey',\n MODELENCE_EMAIL_AWS_SES_REGION: '_system.email.awsSes.region',\n MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID: '_system.email.awsSes.accessKeyId',\n MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY: '_system.email.awsSes.secretAccessKey',\n MODELENCE_EMAIL_SMTP_HOST: '_system.email.smtp.host',\n MODELENCE_EMAIL_SMTP_PORT: '_system.email.smtp.port',\n MODELENCE_EMAIL_SMTP_USER: '_system.email.smtp.user',\n MODELENCE_EMAIL_SMTP_PASS: '_system.email.smtp.pass',\n // deprecated\n GOOGLE_AUTH_ENABLED: '_system.user.auth.google.enabled',\n GOOGLE_AUTH_CLIENT_ID: '_system.user.auth.google.clientId',\n GOOGLE_AUTH_CLIENT_SECRET: '_system.user.auth.google.clientSecret',\n};\n\nfunction formatLocalConfigValue(value: string, type: ConfigType): string | number | boolean {\n if (type === 'number') {\n const numValue = Number(value);\n if (isNaN(numValue)) {\n throw new Error(`Invalid number value for config: ${value}`);\n }\n return numValue;\n }\n if (type === 'boolean') {\n if (value.toLowerCase() === 'true') {\n return true;\n }\n if (value.toLowerCase() === 'false') {\n return false;\n }\n throw new Error(`Invalid boolean value for config: ${value}`);\n }\n return value;\n}\n\nfunction getLocalConfigs(configSchema: ConfigSchema): AppConfig[] {\n const configs: AppConfig[] = [];\n\n for (const [envVar, configKey] of Object.entries(localConfigMap)) {\n const value = process.env[envVar];\n const configSchemaEntry = configSchema[configKey];\n if (value) {\n const type = configSchemaEntry?.type ?? 'string';\n configs.push({\n key: configKey,\n type: type,\n value: formatLocalConfigValue(value, type),\n });\n }\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const appDetails = await getAppDetails();\n const modelencePackageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n projectName: appDetails.name,\n version: modelencePackageJson.default.version,\n localHostname: os.hostname(),\n environmentId\n })\n });\n }\n}\n\nasync function getAppDetails() {\n try {\n const packageJsonPath = path.join(process.cwd(), 'package.json');\n const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');\n const packageJson = JSON.parse(packageJsonContent);\n \n return {\n name: packageJson.name || 'unknown'\n };\n } catch (error) {\n return {\n name: 'unknown'\n };\n }\n}\n","import { Session, User } from \"@/auth/types\";\nimport { getWebsocketConfig } from \"@/app/websocketConfig\";\nimport { logError } from \"../telemetry\";\n\ntype canAccessChannel = (props: {\n user: User | null,\n session: Session | null,\n roles: string[],\n}) => Promise<boolean>;\n\nexport class ServerChannel<T = any> {\n public readonly category: string;\n public readonly canAccessChannel: canAccessChannel | null;\n\n constructor(\n category: string,\n canAccessChannel?: canAccessChannel,\n ) {\n this.category = category;\n this.canAccessChannel = canAccessChannel || null;\n }\n\n broadcast(id: string, data: T) {\n const websocketProvider = getWebsocketConfig().provider;\n if (!websocketProvider) {\n logError(\"Websockets provider should be added to startApp\", {});\n return;\n }\n\n websocketProvider.broadcast({\n category: this.category,\n id,\n data,\n });\n }\n}\n","import { getEmailConfig } from \"@/app/emailConfig\";\nimport { EmailPayload } from \"../types\";\n\nexport function sendEmail(payload: EmailPayload) {\n if (!getEmailConfig().provider) {\n throw new Error('Email provider is not configured, see https://docs.modelence.com/email for more details.');\n }\n return getEmailConfig().provider?.sendEmail(payload);\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.6.2",
4
+ "version": "0.6.3",
5
5
  "description": "The Node.js Framework for Real-Time MongoDB Apps",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",