modelence 0.6.14 → 0.6.16

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-CNLYVHOP.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-DOPT3L7H.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 p(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 d(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=d(".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=>{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:()=>({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(p("/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(p(`/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(d(n)).then(()=>true).catch(()=>false)&&t.file(d(n),{name:n});for(let n of s)await promises.access(d(n)).then(()=>true).catch(()=>false)&&t.directory(d(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(p("/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:new Uint8Array(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(p("/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",r="0.6.14",o="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",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",x={"@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/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",eslint:"^9.37.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0"},j={"@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","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"},b={react:">=18.0.0","react-dom":">=18.0.0"},v={type:s,name:i,version:r,description:o,main:n,types:p,exports:c,files:d,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:x,dependencies:j,peerDependencies:b};
2
- export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,g as n,h as o,x as p,j as q,b as r,v as s};//# sourceMappingURL=chunk-CNLYVHOP.js.map
3
- //# sourceMappingURL=chunk-CNLYVHOP.js.map
1
+ var s="module",i="modelence",r="0.6.16",o="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",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",x={"@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/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",eslint:"^9.37.0",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0"},j={"@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","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"},b={react:">=18.0.0","react-dom":">=18.0.0"},v={type:s,name:i,version:r,description:o,main:n,types:p,exports:c,files:d,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:x,dependencies:j,peerDependencies:b};
2
+ export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,g as n,h as o,x as p,j as q,b as r,v as s};//# sourceMappingURL=chunk-DOPT3L7H.js.map
3
+ //# sourceMappingURL=chunk-DOPT3L7H.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,QAAA,CACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,mBACTC,CAAAA,CAAW,CACT,IAAK,iBAAA,CACL,UAAA,CAAY,mBACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,UAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,EAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,CAAAA,CAAW,CACT,MAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,0DAChB,IAAA,CAAQ,iCAAA,CACR,aAAc,2BAAA,CACd,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC,CAAAA,CAAQ,CACN,GAAA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,CAIA,IAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAWA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAiBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-CNLYVHOP.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.6.14\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"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/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 \"eslint\": \"^9.37.0\",\n \"prettier\": \"^3.6.2\",\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 \"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,CAA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wB,QAAA,CACxB,SAAY,QAAA,CACZ,MAAA,CAAU,SACV,SAAA,CAAa,SAAA,CACb,eAAA,CAAiB,QAAA,CACjB,MAAA,CAAU,SAAA,CACV,mBAAoB,QAAA,CACpB,OAAA,CAAW,UACX,UAAA,CAAY,SAAA,CACZ,KAAQ,QAAA,CACR,OAAA,CAAW,QAAA,CACX,IAAA,CAAQ,SAAA,CACR,WAAA,CAAa,SACb,kBAAA,CAAoB,QAAA,CACpB,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,WAAc,QAAA,CACd,IAAA,CAAQ,QAAA,CACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,UACX,uBAAA,CAAyB,SAAA,CACzB,IAAO,SAAA,CACP,OAAA,CAAW,QACb,CAAA,CACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,CAAA,CA5FFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,MAAAC,CAAAA,CACA,OAAA,CAAAC,EAWA,KAAA,CAAAC,CAAAA,CAIA,IAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAWA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAiBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-DOPT3L7H.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.6.16\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"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/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 \"eslint\": \"^9.37.0\",\n \"prettier\": \"^3.6.2\",\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 \"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,3 +1,3 @@
1
1
  import B from'elastic-apm-node';import A from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import c from'process';var m={},d={},x=false;function g(t){return d[t]?.value}function q(){if(!x)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(m).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:d[t]?.value??e.default}]))}function U(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!m[e]||(d[e]={key:e,type:o,value:r});}),x=true;}function D(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),m=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function L({elasticCloudId:t,elasticApiKey:e}){let o=c.stdout.write,r=c.stderr.write;c.stdout.write=function(n,...s){return b(n.toString(),i.stdout),o.call(c.stdout,n,...s)},c.stderr.write=function(n,...s){return b(n.toString(),i.stderr),r.call(c.stderr,n,...s)},h();}function b(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=z++),t[r]===`
2
- `?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function R(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{y(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{E(o,{timestamp:r,source:"console",sequenceId:n});});}function h(){setTimeout(()=>{R(),h();},1e3);}var a=null;function J(){}function Q(t){a=Object.assign({},a,t);}function I(){return a?.environmentId}function S(){return a?.appAlias}function T(){return a?.environmentAlias}function K(){return a?.telemetry?.serviceName}function l(){return !!a?.telemetry?.isEnabled}var M=false,f=null,C=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,l()&&await N();};async function N(){let t=g("_system.elastic.apmEndpoint"),e=g("_system.elastic.cloudId"),o=g("_system.elastic.apiKey"),r=S()??"unknown",n=T()??"unknown",s=I()??"unknown",p=K();f=B.start({serviceName:p,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let u=new ElasticsearchTransport({apm:f,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),C=A.createLogger({level:"debug",defaultMeta:{serviceName:p},format:A.format.combine(A.format.json()),transports:[u]}),L({elasticCloudId:e,elasticApiKey:o});}function w(){if(!f)throw new Error("APM is not initialized");return f}function v(){if(!C)throw new Error("Logger is not initialized");return C}function y(t,e){l()&&v().info(t,e);}function E(t,e){l()&&v().error(t,e);}function O(t,e,o){if(!l())return {end:()=>{},setContext:()=>{}};let r=w(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:p,context:u}={})=>{u&&r.setCustomContext(u),n.end(s,p);},setContext:s=>{r.setCustomContext(s);}}}function W(t){if(!l()){console.error(t);return}w().captureError(t);}export{g as a,q as b,U as c,D as d,J as e,Q as f,rt as g,y as h,E as i,O as j,W as k};//# sourceMappingURL=chunk-SOW7YLKS.js.map
3
- //# sourceMappingURL=chunk-SOW7YLKS.js.map
2
+ `?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function R(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{y(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{E(o,{timestamp:r,source:"console",sequenceId:n});});}function h(){setTimeout(()=>{R(),h();},1e3);}var a=null;function J(){}function Q(t){a=Object.assign({},a,t);}function I(){return a?.environmentId}function S(){return a?.appAlias}function T(){return a?.environmentAlias}function K(){return a?.telemetry?.serviceName}function l(){return !!a?.telemetry?.isEnabled}var M=false,f=null,C=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,l()&&await N();};async function N(){let t=g("_system.elastic.apmEndpoint"),e=g("_system.elastic.cloudId"),o=g("_system.elastic.apiKey"),r=S()??"unknown",n=T()??"unknown",s=I()??"unknown",p=K();f=B.start({serviceName:p,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let u=new ElasticsearchTransport({apm:f,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),C=A.createLogger({level:"debug",defaultMeta:{serviceName:p},format:A.format.combine(A.format.json()),transports:[u]}),L({elasticCloudId:e,elasticApiKey:o});}function w(){if(!f)throw new Error("APM is not initialized");return f}function v(){if(!C)throw new Error("Logger is not initialized");return C}function y(t,e){l()&&v().info(t,e);}function E(t,e){l()&&v().error(t,e);}function O(t,e,o){if(!l())return {end:()=>{},setContext:()=>{}};let r=w(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:p,context:u}={})=>{u&&r.setCustomContext(u),n.end(s,p);},setContext:s=>{r.setCustomContext(s);}}}function W(t){if(!l()){console.error(t);return}w().captureError(t);}export{g as a,q as b,U as c,D as d,J as e,Q as f,rt as g,y as h,E as i,O as j,W as k};//# sourceMappingURL=chunk-LQOYD6LG.js.map
3
+ //# sourceMappingURL=chunk-LQOYD6LG.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","result","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,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A6D,EAAC,GAC9E,CACCA,CAAAA,EACFrB,CAAAA,CAAI,gBAAA,CAAiBqB,CAAO,CAAA,CAE9BC,CAAAA,CAAY,GAAA,CAAIC,CAAAA,CAAQC,CAAO,EACjC,CAAA,CACA,UAAA,CAAaH,CAAAA,EAAqC,CAChDrB,CAAAA,CAAI,gBAAA,CAAiBqB,CAAO,EAC9B,CACF,CACF,CAEO,SAASI,CAAAA,CAAaX,CAAAA,CAAc,CACzC,GAAI,CAACf,CAAAA,EAAmB,CAAG,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,CAAA,CACnB,MACF,CAEAE,CAAAA,EAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-SOW7YLKS.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport,\n ],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
1
+ {"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","result","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAQb,SAASC,CAAAA,CAAUC,CAAAA,CAAgB,CACxC,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAAA,CAGF,OAAO,MAAA,CAAO,YACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CACxB,OAAO,CAAC,CAACM,CAAAA,CAAGC,CAAM,IAAMA,CAAAA,CAAO,QAAQ,CAAA,CACvC,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKG,CAAM,IACT,CACLH,CAAAA,CACA,CACE,GAAA,CAAAA,EACA,IAAA,CAAMG,CAAAA,CAAO,IAAA,CACb,KAAA,CAAON,EAAOG,CAAG,CAAA,EAAG,KAAA,EAASG,CAAAA,CAAO,OACtC,CACF,CACD,CACL,CACF,CAEO,SAASC,CAAAA,CAAYC,CAAAA,CAAsB,CAChDA,CAAAA,CAAQ,OAAA,CAAQ,CAAC,CAAE,IAAAL,CAAAA,CAAK,IAAA,CAAAM,CAAAA,CAAM,KAAA,CAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBP,EAAI,WAAA,EAAY,CAAE,UAAA,CAAW,UAAU,GAEvC,CAACJ,CAAAA,CAAaI,CAAG,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pB,GAAI,CAACtB,CAAAA,EAAmB,CACtB,OAAO,CACL,GAAA,CAAK,IAAM,EAEX,CACA,UAAA,CAAY,IAAM,EAGpB,CAAA,CAGF,IAAMC,CAAAA,CAAMgB,CAAAA,EAAO,CACbM,CAAAA,CAActB,CAAAA,CAAI,gBAAA,CAAiBoB,CAAAA,CAAMtD,CAAI,CAAA,CACnD,OAAIuD,CAAAA,EACFrB,CAAAA,CAAI,gBAAA,CAAiBqB,CAAO,CAAA,CAGvB,CACL,GAAA,CAAK,CACHE,CAAAA,CACA,CAAE,OAAA,CAAAC,CAAAA,CAAS,OAAA,CAAAH,CAAQ,CAAA,CAA6D,EAAC,GAC9E,CACCA,CAAAA,EACFrB,CAAAA,CAAI,gBAAA,CAAiBqB,CAAO,CAAA,CAE9BC,CAAAA,CAAY,GAAA,CAAIC,CAAAA,CAAQC,CAAO,EACjC,CAAA,CACA,UAAA,CAAaH,CAAAA,EAAqC,CAChDrB,CAAAA,CAAI,gBAAA,CAAiBqB,CAAO,EAC9B,CACF,CACF,CAEO,SAASI,CAAAA,CAAaX,CAAAA,CAAc,CACzC,GAAI,CAACf,CAAAA,EAAmB,CAAG,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,CAAA,CACnB,MACF,CAEAE,CAAAA,EAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-LQOYD6LG.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport,\n ],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\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-CNLYVHOP.js';//# sourceMappingURL=package-YWKBBYAP.js.map
2
- //# sourceMappingURL=package-YWKBBYAP.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-DOPT3L7H.js';//# sourceMappingURL=package-PIJFHPEI.js.map
2
+ //# sourceMappingURL=package-PIJFHPEI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-YWKBBYAP.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-PIJFHPEI.js"}
package/dist/server.js CHANGED
@@ -1,18 +1,18 @@
1
- import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$1,c as c$1,f,g as g$1,i,a as a$1,h,j as j$1,k as k$1}from'./chunk-SOW7YLKS.js';export{a as getConfig}from'./chunk-SOW7YLKS.js';import Pt from'dotenv';import Ho from'fs/promises';import ho from'os';import we from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import T,{z as z$1}from'zod';import ro from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import _o from'@vitejs/plugin-react';import Ro from'fs';import Ce,{Router}from'express';import Wo from'cookie-parser';import Bo from'http';var b=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:p=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=p;}};function C(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:C(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=C(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...C(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...C(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(C)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:C(o.schema)}return {type:"custom",typeName:e.typeName}}function J(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?C(r):J(r)):typeof n=="object"&&"_def"in n?e[o]=C(n):e[o]=J(n);return e}var w=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return J(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Lt=z$1.string.bind(z$1),$t=z$1.number.bind(z$1),zt=z$1.date.bind(z$1),Zt=z$1.boolean.bind(z$1),qt=z$1.array.bind(z$1),Wt=z$1.object.bind(z$1),Bt=z$1.enum.bind(z$1),c={string:Lt,number:$t,date:zt,boolean:Zt,array:qt,object:Wt,enum:Bt,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(t){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(t){return {}}};var k=new w("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await k.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ce()}async function Ue(t,e){await k.updateOne({authToken:t},{$set:{userId:e}});}async function Ne(t){await k.updateOne({authToken:t},{$set:{userId:null}});}async function ce(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await k.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Jt(t){let e=Date.now(),o=new Date(e+a.days(7));await k.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Le=new b("_system.session",{stores:[k],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await Jt(e);}}});var m=new w("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),createdAt:c.date(),roles:c.array(c.string()).optional(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional(),github:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),$=new w("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),A=new w("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new w("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var $e=new Map,P={authenticated:null,unauthenticated:null};function ze(t,e){P.authenticated=e.authenticated,P.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))$e.set(o,n);}function H(){return P.unauthenticated?[P.unauthenticated]:[]}function Ze(){return P.authenticated?[P.authenticated]:[]}function qe(t,e){let o=e.find(n=>!Ht(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Ht(t,e){for(let o of t){let n=$e.get(o);if(n&&n.permissions.includes(e))return true}return false}async function D(t){let e=await je(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Ze():H();return {user:n,session:e,roles:r}}var x=null;async function We(){if(x)return x;let t=_();if(!t)throw new Error("MongoDB URI is not set");x=new MongoClient(t,{maxPoolSize:20});try{return await x.connect(),await x.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),x}catch(e){throw console.error(e),x=null,e}}function _(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function V(){return x}var z=null,Yt="_modelenceSocketio";async function Xt({httpServer:t,channels:e}){let o=V();if(!o)throw console.error("Socket.IO initialization failed: MongoDB client is not initialized"),new Error("Mongodb Client is not initialized");console.log("Initializing Socket.IO server...");let n=o.db().collection(Yt);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}z=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:createAdapter(n),transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),z.on("error",r=>{console.error("Socket.IO error:",r);}),z.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await D(s);}finally{i();}}),z.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),r.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(r.data))&&r.join(i);r.join(i),console.log(`User ${r.id} joined channel ${i}`),r.emit("joinedChannel",i);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function eo({category:t,id:e,data:o}){z?.to(`${t}:${e}`).emit(t,o);}var Be={init:Xt,broadcast:eo};async function Fe(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await $.findOne({domain:o})}var Je={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
- `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await $.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var le=Object.freeze({});function He(t){le=Object.freeze(Object.assign({},le,t));}function y(){return le}function to(){return typeof window!="object"}function R(){if(!to())throw new Error("This function can only be called on the server")}function G(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function Ve({name:t,email:e,verificationUrl:o}){return `
1
+ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$1,c as c$1,f,g as g$1,i,a as a$1,h,j as j$1,k}from'./chunk-LQOYD6LG.js';export{a as getConfig}from'./chunk-LQOYD6LG.js';import Pt from'dotenv';import Ho from'fs/promises';import ho from'os';import we from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import T,{z as z$1}from'zod';import ro from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import _o from'@vitejs/plugin-react';import Ro from'fs';import Se,{Router}from'express';import Wo from'cookie-parser';import Bo from'http';var b=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:d=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=d;}};function S(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:S(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=S(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...S(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...S(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(S)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:S(o.schema)}return {type:"custom",typeName:e.typeName}}function J(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?S(r):J(r)):typeof n=="object"&&"_def"in n?e[o]=S(n):e[o]=J(n);return e}var w=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return J(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Lt=z$1.string.bind(z$1),$t=z$1.number.bind(z$1),zt=z$1.date.bind(z$1),Zt=z$1.boolean.bind(z$1),qt=z$1.array.bind(z$1),Wt=z$1.object.bind(z$1),Bt=z$1.enum.bind(z$1),c={string:Lt,number:$t,date:zt,boolean:Zt,array:qt,object:Wt,enum:Bt,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(t){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(t){return {}}};var A=new w("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await A.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ce()}async function Ue(t,e){await A.updateOne({authToken:t},{$set:{userId:e}});}async function Ne(t){await A.updateOne({authToken:t},{$set:{userId:null}});}async function ce(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await A.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Jt(t){let e=Date.now(),o=new Date(e+a.days(7));await A.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Le=new b("_system.session",{stores:[A],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await Jt(e);}}});var p=new w("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),createdAt:c.date(),roles:c.array(c.string()).optional(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional(),github:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),z=new w("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),P=new w("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new w("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var $e=new Map,j={authenticated:null,unauthenticated:null};function ze(t,e){j.authenticated=e.authenticated,j.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))$e.set(o,n);}function H(){return j.unauthenticated?[j.unauthenticated]:[]}function Ze(){return j.authenticated?[j.authenticated]:[]}function qe(t,e){let o=e.find(n=>!Ht(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Ht(t,e){for(let o of t){let n=$e.get(o);if(n&&n.permissions.includes(e))return true}return false}async function D(t){let e=await je(t),o=e.userId?await p.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Ze():H();return {user:n,session:e,roles:r}}var x=null;async function We(){if(x)return x;let t=_();if(!t)throw new Error("MongoDB URI is not set");x=new MongoClient(t,{maxPoolSize:20});try{return await x.connect(),await x.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),x}catch(e){throw console.error(e),x=null,e}}function _(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function V(){return x}var Z=null,Yt="_modelenceSocketio";async function Xt({httpServer:t,channels:e}){let o=V();console.log("Initializing Socket.IO server...");let n=null;if(o){n=o.db().collection(Yt);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}}Z=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),Z.on("error",r=>{console.error("Socket.IO error:",r);}),Z.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await D(s);}finally{i();}}),Z.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),r.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(r.data))&&r.join(i);r.join(i),console.log(`User ${r.id} joined channel ${i}`),r.emit("joinedChannel",i);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function eo({category:t,id:e,data:o}){Z?.to(`${t}:${e}`).emit(t,o);}var Be={init:Xt,broadcast:eo};async function Fe(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await z.findOne({domain:o})}var Je={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await z.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var le=Object.freeze({});function He(t){le=Object.freeze(Object.assign({},le,t));}function y(){return le}function to(){return typeof window!="object"}function R(){if(!to())throw new Error("This function can only be called on the server")}function G(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function Ve({name:t,email:e,verificationUrl:o}){return `
3
3
  <p>Hi${t?` ${t}`:""},</p>
4
4
  <p>Please verify your email address ${e} by clicking the link below:</p>
5
5
  <p><a href="${o}">${o}</a></p>
6
6
  <p>If you did not request this, please ignore this email.</p>
7
- `}async function Ge(t){let e=process.env.MODELENCE_SITE_URL,o=y().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await A.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await m.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await m.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await m.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await A.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function K({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(y().provider){let n=y().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await A.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,l=(y()?.verification?.template||Ve)({name:"",email:e,verificationUrl:s}),p=G(l);await n?.sendEmail({to:e,from:y()?.from||"noreply@modelence.com",subject:y()?.verification?.subject||"Verify your email address",text:p,html:l});}}function Q(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function j(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var de=Object.freeze({});function Qe(t){de=Object.freeze(Object.assign({},de,t));}function g(){return de}async function Xe(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await O({bucket:"signin",type:"ip",value:r});let i=j(t.email),s=z$1.string().parse(t.password),a=await m.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw Ye();if(!a.emails?.find(d=>d.address===i)?.verified&&y()?.provider){if(r)try{await O({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await K({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await ro.compare(s,l))throw Ye();return await Ue(o.authToken,a._id),g().onAfterLogin?.({user:a,session:o,connectionInfo:n}),g().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(g().onLoginError?.({error:r,session:o,connectionInfo:n}),g().login?.onError?.(r)),r}}async function et(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Ne(e.authToken);}function Ye(){return new Error("Incorrect email/password combination")}async function tt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var Z=new w("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var ue=[];function ot(t){if(ue.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");ue=t;}async function O(t){let{bucket:e,type:o,value:n}=t,r=ue.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await so(i,n);}async function so(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),r=await Z.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=r?ao(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await Z.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function ao(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function nt(t,{user:e,session:o,connectionInfo:n}){try{let r=j(t.email),i=Q(t.password),s=n?.ip;if(s&&await O({bucket:"signupAttempt",type:"ip",value:s}),await Fe(r))throw new Error("Please use a permanent email address");let a=await m.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let d=a.emails?.find(S=>S.address===r);throw new Error(`User with email already exists: ${d?.address}`)}s&&await O({bucket:"signup",type:"ip",value:s});let l=await ro.hash(i,10),p=await m.insertOne({handle:r,emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),E=await m.findOne({_id:p.insertedId},{readPreference:"primary"});if(!E)throw new Error("User not found");return await K({userId:p?.insertedId,email:r,baseUrl:n?.baseUrl}),g().onAfterSignup?.({user:E,session:o,connectionInfo:n}),g().signup?.onSuccess?.(E),p.insertedId}catch(r){throw r instanceof Error&&(g().onSignupError?.({error:r,session:o,connectionInfo:n}),g().signup?.onError?.(r)),r}}function po(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function fo({email:t,resetUrl:e}){return `
7
+ `}async function Ge(t){let e=process.env.MODELENCE_SITE_URL,o=y().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await P.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await p.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await p.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await p.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await P.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function K({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(y().provider){let n=y().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await P.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,l=(y()?.verification?.template||Ve)({name:"",email:e,verificationUrl:s}),d=G(l);await n?.sendEmail({to:e,from:y()?.from||"noreply@modelence.com",subject:y()?.verification?.subject||"Verify your email address",text:d,html:l});}}function Q(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function U(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var de=Object.freeze({});function Qe(t){de=Object.freeze(Object.assign({},de,t));}function g(){return de}async function Xe(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await O({bucket:"signin",type:"ip",value:r});let i=U(t.email),s=z$1.string().parse(t.password),a=await p.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw Ye();if(!a.emails?.find(u=>u.address===i)?.verified&&y()?.provider){if(r)try{await O({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await K({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await ro.compare(s,l))throw Ye();return await Ue(o.authToken,a._id),g().onAfterLogin?.({user:a,session:o,connectionInfo:n}),g().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(g().onLoginError?.({error:r,session:o,connectionInfo:n}),g().login?.onError?.(r)),r}}async function et(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Ne(e.authToken);}function Ye(){return new Error("Incorrect email/password combination")}async function tt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await p.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var q=new w("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var ue=[];function ot(t){if(ue.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");ue=t;}async function O(t){let{bucket:e,type:o,value:n}=t,r=ue.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await so(i,n);}async function so(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),r=await q.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=r?ao(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await q.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function ao(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function nt(t,{user:e,session:o,connectionInfo:n}){try{let r=U(t.email),i=Q(t.password),s=n?.ip;if(s&&await O({bucket:"signupAttempt",type:"ip",value:s}),await Fe(r))throw new Error("Please use a permanent email address");let a=await p.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let u=a.emails?.find(C=>C.address===r);throw new Error(`User with email already exists: ${u?.address}`)}s&&await O({bucket:"signup",type:"ip",value:s});let l=await ro.hash(i,10),d=await p.insertOne({handle:r,emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),E=await p.findOne({_id:d.insertedId},{readPreference:"primary"});if(!E)throw new Error("User not found");return await K({userId:d?.insertedId,email:r,baseUrl:n?.baseUrl}),g().onAfterSignup?.({user:E,session:o,connectionInfo:n}),g().signup?.onSuccess?.(E),d.insertedId}catch(r){throw r instanceof Error&&(g().onSignupError?.({error:r,session:o,connectionInfo:n}),g().signup?.onError?.(r)),r}}function po(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function fo({email:t,resetUrl:e}){return `
8
8
  <p>Hi,</p>
9
9
  <p>We received a request to reset your password for ${t}.</p>
10
10
  <p>Click the link below to reset your password:</p>
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 me={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function rt(t,{connectionInfo:e}){let o=j(t.email),n=await m.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return me;let r=y().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=`${po(a$1,y().passwordReset?.redirectUrl)}?token=${i}`,d=(y()?.passwordReset?.template||fo)({email:o,resetUrl:p,name:""}),S=G(d);return await r.sendEmail({to:o,from:y()?.from||"noreply@modelence.com",subject:y()?.passwordReset?.subject||"Reset your password",text:S,html:d}),me}async function it(t,{}){let e=z$1.string().parse(t.token),o=Q(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 ro.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 st=new b("_system.user",{stores:[m,$,A,v],queries:{getOwnProfile:tt},mutations:{signupWithPassword:nt,loginWithPassword:Xe,logout:et,sendResetPasswordToken:rt,resetPassword:it},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:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Ge}}]});async function at({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.getSerializedSchema(),collections:[s.getName()],version:2})),i=await pe("/api/connect","POST",{hostname:ho.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 ct(){return await pe("/api/configs","GET")}async function lt(){return await pe("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function pe(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 fe=false,go=a.seconds(10);function dt(){setInterval(async()=>{if(!fe){fe=true;try{await lt();}catch(t){console.error("Error syncing status",t);}try{await yo();}catch(t){console.error("Error syncing config",t);}fe=false;}},go);}async function yo(){let{configs:t}=await ct();c$1(t);}var wo=a.minutes(1),bo=a.seconds(10),I={},he,q=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 mt(t,{description:e="",interval:o,timeout:n=wo,handler:r}){if(I[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(he)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}]`);I[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function pt(){if(he)throw new Error("Cron jobs already started");let t=Object.keys(I);if(t.length>0){let e={alias:{$in:t}},o=await q.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>q.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Eo(bo);let n=await q.fetch(e),r=Date.now();n.forEach(i=>{let s=I[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(I).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),he=setInterval(So,a.seconds(1));}}function Eo(t){return new Promise(e=>setTimeout(e,t))}async function So(){let t=Date.now();Object.values(I).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 Co(e);});}async function Co(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(()=>{ut(r,o),i.end("success");}).catch(s=>{ut(r,o),k$1(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await q.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function ut(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function ft(){return Object.values(I).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var ht=new b("_system.cron",{stores:[q]});var ge={};function ye(t,e){return R(),bt(t),Y("query",t,e)}function gt(t,e){return R(),bt(t),Y("mutation",t,e)}function yt(t,e){return R(),Et(t),Y("query",t,e)}function wt(t,e){return R(),Et(t),Y("mutation",t,e)}function bt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Et(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function Y(t,e,o){if(R(),ge[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??[];ge[e]={type:t,name:e,handler:n,permissions:r};}async function St(t,e,o){R();let n=ge[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{qe(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var X=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function Ct(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await X.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 X.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var xt=new b("_system.migration",{stores:[X]});var Tt=new b("_system.rateLimit",{stores:[Z]});var vt=new b("_system.site",{configSchema:{url:{type:"string",isPublic:true,default:""}}});var be=class{async init(){this.config=await Mo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[Ce.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(Ce.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 Oo(){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 Io(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"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Mo(){let t=process.cwd(),e=await Oo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Ro.existsSync(we.join(t,i))),n=[_o(),ko()];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:we.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:{"@":we.resolve(t,"src").replace(/\\/g,"/")}}});return Io(r,e)}function ko(){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}}}var _t=new be;async function Rt(t,e){let{authToken:o}=await ce(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function U(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ee(t,e,o){let n=await m.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await Ee(t);try{if(n){await Rt(e,n._id),g().onAfterLogin?.({user:n,session:r,connectionInfo:i}),g().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(g().login?.onError?.(s),g().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await m.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await m.insertOne({handle:o.email,emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Rt(e,a.insertedId);let l=await m.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(g().onAfterSignup?.({user:l,session:r,connectionInfo:i}),g().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(g().onSignupError?.({error:s,session:r,connectionInfo:i}),g().signup?.onError?.(s)),s}}function te(t){return !t||typeof t!="string"?null:t}async function Po(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function jo(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Uo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=U("google");try{let s=await Po(o,n,r,i),a=await jo(s.access_token),l={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await ee(t,e,l);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function No(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=U("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,Uo),t}var Ot=No;async function $o(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function zo(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Zo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=U("github");try{let s=await $o(o,n,r,i),a=await zo(s.access_token),l=a.email||"";if(!l){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let p={id:String(a.id),email:l,emailVerified:!0,providerName:"github"};await ee(t,e,p);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function qo(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=U("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(p=>p.trim()).join(" "):"user:email",l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",r),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a),n.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,Zo),t}var It=qo;function Mt(t){return async(e,o,n)=>{let r=e.headers["x-modelence-auth-token"],i={session:null,user:null};if(typeof r=="string"&&_())try{let{session:s,user:a}=await D(r);i={session:s,user:a};}catch{}try{let s=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e,res:o,next:n},i);s&&(o.status(s.status||200),s.redirect&&o.redirect(s.redirect),s.headers&&Object.entries(s.headers).forEach(([a,l])=>{o.setHeader(a,l);}),o.send(s.data));}catch(s){s instanceof a$3?o.status(s.status).send(s.message):(console.error(`Error in route handler: ${e.path}`),console.error(s),o.status(500).send(String(s)));}}}var Se=Object.freeze({});function kt(t){Se=Object.freeze(Object.assign({},Se,t));}function oe(){return Se}function Fo(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,Mt(a));});}}async function At(t,{combinedModules:e,channels:o}){let n=Ce();n.use(Ce.json({limit:"16mb"})),n.use(Ce.urlencoded({extended:true,limit:"16mb"})),n.use(Wo()),n.use(Ot()),n.use(It()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:p}=a.params,E=await Ee(a);try{let d=await St(p,a.body.args,E);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(),ne=Object.entries(M.fieldErrors).map(([N,ie])=>`${N}: ${(ie??[]).join(", ")}`).join("; "),re=M.formErrors.join("; "),W=[ne,re].filter(Boolean).join("; ");l.status(400).send(W);}else l.status(500).send(d instanceof Error?d.message:String(d));}}),Fo(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=Bo.createServer(n),i=oe()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h("Application started",{source:"app"}),console.log(`
14
+ `}var me={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function rt(t,{connectionInfo:e}){let o=U(t.email),n=await p.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return me;let r=y().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,d=`${po(a$1,y().passwordReset?.redirectUrl)}?token=${i}`,u=(y()?.passwordReset?.template||fo)({email:o,resetUrl:d,name:""}),C=G(u);return await r.sendEmail({to:o,from:y()?.from||"noreply@modelence.com",subject:y()?.passwordReset?.subject||"Reset your password",text:C,html:u}),me}async function it(t,{}){let e=z$1.string().parse(t.token),o=Q(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 p.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await ro.hash(o,10);return await p.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var st=new b("_system.user",{stores:[p,z,P,v],queries:{getOwnProfile:tt},mutations:{signupWithPassword:nt,loginWithPassword:Xe,logout:et,sendResetPasswordToken:rt,resetPassword:it},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:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Ge}}]});async function at({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.getSerializedSchema(),collections:[s.getName()],version:2})),i=await pe("/api/connect","POST",{hostname:ho.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 ct(){return await pe("/api/configs","GET")}async function lt(){return await pe("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function pe(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 fe=false,go=a.seconds(10);function dt(){setInterval(async()=>{if(!fe){fe=true;try{await lt();}catch(t){console.error("Error syncing status",t);}try{await yo();}catch(t){console.error("Error syncing config",t);}fe=false;}},go);}async function yo(){let{configs:t}=await ct();c$1(t);}var wo=a.minutes(1),bo=a.seconds(10),I={},he,W=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 mt(t,{description:e="",interval:o,timeout:n=wo,handler:r}){if(I[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(he)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}]`);I[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function pt(){if(he)throw new Error("Cron jobs already started");let t=Object.keys(I);if(t.length>0){let e={alias:{$in:t}},o=await W.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>W.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Eo(bo);let n=await W.fetch(e),r=Date.now();n.forEach(i=>{let s=I[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(I).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),he=setInterval(Co,a.seconds(1));}}function Eo(t){return new Promise(e=>setTimeout(e,t))}async function Co(){let t=Date.now();Object.values(I).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 So(e);});}async function So(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(()=>{ut(r,o),i.end("success");}).catch(s=>{ut(r,o),k(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await W.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function ut(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function ft(){return Object.values(I).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var ht=new b("_system.cron",{stores:[W]});var ge={};function ye(t,e){return R(),bt(t),Y("query",t,e)}function gt(t,e){return R(),bt(t),Y("mutation",t,e)}function yt(t,e){return R(),Et(t),Y("query",t,e)}function wt(t,e){return R(),Et(t),Y("mutation",t,e)}function bt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Et(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function Y(t,e,o){if(R(),ge[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??[];ge[e]={type:t,name:e,handler:n,permissions:r};}async function Ct(t,e,o){R();let n=ge[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{qe(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var X=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function St(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await X.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 X.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var xt=new b("_system.migration",{stores:[X]});var Tt=new b("_system.rateLimit",{stores:[q]});var vt=new b("_system.site",{configSchema:{url:{type:"string",isPublic:true,default:""}}});var be=class{async init(){this.config=await Mo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[Se.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(Se.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 Oo(){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 Io(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"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Mo(){let t=process.cwd(),e=await Oo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Ro.existsSync(we.join(t,i))),n=[_o(),ko()];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:we.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:{"@":we.resolve(t,"src").replace(/\\/g,"/")}}});return Io(r,e)}function ko(){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}}}var _t=new be;async function Rt(t,e){let{authToken:o}=await ce(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function N(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ee(t,e,o){let n=await p.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await Ee(t);try{if(n){await Rt(e,n._id),g().onAfterLogin?.({user:n,session:r,connectionInfo:i}),g().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(g().login?.onError?.(s),g().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await p.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await p.insertOne({handle:o.email,emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await Rt(e,a.insertedId);let l=await p.findOne({_id:a.insertedId},{readPreference:"primary"});l&&(g().onAfterSignup?.({user:l,session:r,connectionInfo:i}),g().signup?.onSuccess?.(l));}catch(s){throw s instanceof Error&&(g().onSignupError?.({error:s,session:r,connectionInfo:i}),g().signup?.onError?.(s)),s}}function te(t){return !t||typeof t!="string"?null:t}async function Po(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function jo(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Uo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=N("google");try{let s=await Po(o,n,r,i),a=await jo(s.access_token),l={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await ee(t,e,l);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function No(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=N("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,Uo),t}var Ot=No;async function $o(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function zo(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function Zo(t,e){let o=te(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=N("github");try{let s=await $o(o,n,r,i),a=await zo(s.access_token),l=a.email||"";if(!l){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let d={id:String(a.id),email:l,emailVerified:!0,providerName:"github"};await ee(t,e,d);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function qo(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=N("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(d=>d.trim()).join(" "):"user:email",l=new URL("https://github.com/login/oauth/authorize");l.searchParams.append("client_id",r),l.searchParams.append("redirect_uri",i),l.searchParams.append("scope",a),n.redirect(l.toString());}),t.get("/api/_internal/auth/github/callback",e,Zo),t}var It=qo;function Mt(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&_())try{let{session:d,user:E}=await D(s);a={session:d,user:E};}catch{}let l=j$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let d=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,req:n,res:r,next:i},a);l.end(),d&&(r.status(d.status||200),d.redirect&&r.redirect(d.redirect),d.headers&&Object.entries(d.headers).forEach(([E,u])=>{r.setHeader(E,u);}),r.send(d.data));}catch(d){l.end("error"),d instanceof a$3?r.status(d.status).send(d.message):(console.error(`Error in route handler: ${n.path}`),console.error(d),r.status(500).send(String(d)));}}}var Ce=Object.freeze({});function kt(t){Ce=Object.freeze(Object.assign({},Ce,t));}function oe(){return Ce}function Fo(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,Mt(s,r,a));});}}async function At(t,{combinedModules:e,channels:o}){let n=Se();n.use(Se.json({limit:"16mb"})),n.use(Se.urlencoded({extended:true,limit:"16mb"})),n.use(Wo()),n.use(Ot()),n.use(It()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:d}=a.params,E=await Ee(a);try{let u=await Ct(d,a.body.args,E);l.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${d}:`,u),u instanceof a$3)l.status(u.status).send(u.message);else if(u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let M=u.flatten(),ne=Object.entries(M.fieldErrors).map(([L,ie])=>`${L}: ${(ie??[]).join(", ")}`).join("; "),re=M.formErrors.join("; "),B=[ne,re].filter(Boolean).join("; ");l.status(400).send(B);}else l.status(500).send(u instanceof Error?u.message:String(u));}}),Fo(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=Bo.createServer(n),i=oe()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h("Application started",{source:"app"}),console.log(`
15
15
  Application started on http://localhost:${s}
16
- `);});}async function Ee(t){let e=T.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=T.object({screenWidth:T.number(),screenHeight:T.number(),windowWidth:T.number(),windowHeight:T.number(),pixelRatio:T.number(),orientation:T.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:Jo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!_()){let{session:i,user:s,roles:a}=await D(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:H()}}function Jo(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 Ko({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=_t,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Pt.config(),Pt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,p=process.env.MODELENCE_CRON_ENABLED==="true";ln().then(()=>{}).catch(()=>{});let E=[st,Le,ht,xt,Tt,vt],d=[...E,...t];e(),Yo(E),Qo(t),ze(e$1,o);let S=on(d);d$1(S);let M=Xo(d),ne=en(d);p&&nn(d);let re=tn(d);if(ot(re),l){let{configs:N,environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt}=await at({configSchema:S,cronJobsMetadata:p?ft():void 0,stores:M});c$1(N),f({environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt});}else c$1(cn(S));He(i),Qe(s),kt({...a,provider:a.provider||Be});let W=_();if(W&&(await We(),rn(M)),p&&await Ct(r),W)for(let N of M)N.createIndexes();l&&(await g$1(),dt()),p&&pt().catch(console.error),await At(n,{combinedModules:d,channels:ne});}function Qo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ye(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))gt(`${e.name}.${o}`,n);}}function Yo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))yt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))wt(`${e.name}.${o}`,n);}}function Xo(t){return t.flatMap(e=>e.stores)}function en(t){return t.flatMap(e=>e.channels)}function tn(t){return t.flatMap(e=>e.rateLimits)}function on(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 nn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))mt(`${e.name}.${o}`,n);}function rn(t){let e=V();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var sn={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_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",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 an(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 cn(t){let e=[];for(let[o,n]of Object.entries(sn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:an(r,s)});}}return e}async function ln(){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 dn(),r=await import('./package-YWKBBYAP.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:ho.hostname(),environmentId:o})});}}async function dn(){try{let t=we.join(process.cwd(),"package.json"),e=await Ho.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var xe=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=oe().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function un(t){if(!y().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return y().provider?.sendEmail(t)}
17
- export{b as Module,xe as ServerChannel,w as Store,D as authenticate,O as consumeRateLimit,ye as createQuery,m as dbUsers,c as schema,un as sendEmail,Ko as startApp};//# sourceMappingURL=server.js.map
16
+ `);});}async function Ee(t){let e=T.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=T.object({screenWidth:T.number(),screenHeight:T.number(),windowWidth:T.number(),windowHeight:T.number(),pixelRatio:T.number(),orientation:T.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:Jo(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!_()){let{session:i,user:s,roles:a}=await D(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:H()}}function Jo(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 Ko({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=_t,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Pt.config(),Pt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,d=process.env.MODELENCE_CRON_ENABLED==="true";ln().then(()=>{}).catch(()=>{});let E=[st,Le,ht,xt,Tt,vt],u=[...E,...t];e(),Yo(E),Qo(t),ze(e$1,o);let C=on(u);d$1(C);let M=Xo(u),ne=en(u);d&&nn(u);let re=tn(u);if(ot(re),l){let{configs:L,environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt}=await at({configSchema:C,cronJobsMetadata:d?ft():void 0,stores:M});c$1(L),f({environmentId:ie,appAlias:jt,environmentAlias:Ut,telemetry:Nt});}else c$1(cn(C));He(i),Qe(s),kt({...a,provider:a.provider||Be});let B=_();if(B&&(await We(),rn(M)),d&&await St(r),B)for(let L of M)L.createIndexes();l&&(await g$1(),dt()),d&&pt().catch(console.error),await At(n,{combinedModules:u,channels:ne});}function Qo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ye(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))gt(`${e.name}.${o}`,n);}}function Yo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))yt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))wt(`${e.name}.${o}`,n);}}function Xo(t){return t.flatMap(e=>e.stores)}function en(t){return t.flatMap(e=>e.channels)}function tn(t){return t.flatMap(e=>e.rateLimits)}function on(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 nn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))mt(`${e.name}.${o}`,n);}function rn(t){let e=V();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var sn={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_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",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 an(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 cn(t){let e=[];for(let[o,n]of Object.entries(sn)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:an(r,s)});}}return e}async function ln(){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 dn(),r=await import('./package-PIJFHPEI.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:ho.hostname(),environmentId:o})});}}async function dn(){try{let t=we.join(process.cwd(),"package.json"),e=await Ho.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var xe=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=oe().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function un(t){if(!y().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return y().provider?.sendEmail(t)}
17
+ export{b as Module,xe as ServerChannel,w as Store,D as authenticate,O as consumeRateLimit,ye as createQuery,p as dbUsers,c as schema,un as sendEmail,Ko as startApp};//# sourceMappingURL=server.js.map
18
18
  //# sourceMappingURL=server.js.map