modelence 0.4.10 → 0.4.11

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,12 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import S,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O 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 ce from'archiver';import oe from'open';import {Octokit}from'@octokit/rest';import c from'fs-extra';var v=".modelence.env";async function A(e,t){let o=await fetch(`${t}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!o.ok){let n=await o.text();throw new Error(n||`Request failed with status ${o.status}`)}return o.json()}async function R(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(t=>{e.question(`Warning: ${v} already exists. Do you want to overwrite it? (y/N) `,o=>{e.close(),t(o.toLowerCase()==="y");});})}function U(e){return String(e).replace(/"/g,'\\"')}async function V(e){try{let t=e.replace(".env",".backup.env");await promises.copyFile(e,t),console.log(`Backup created at ${t}`);}catch(t){console.warn("Failed to create backup file:",t);}}async function $(e){try{let t=join(process.cwd(),v),o={};try{let a=await promises.readFile(t,"utf8");o=parse(a),await V(t),await R()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let n=await A(e.token,e.host),r={...o,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:n.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:n.serviceToken,MODELENCE_CONTAINER_ID:n.containerId},s=Object.entries(r).map(([a,i])=>`${a}="${U(i)}"`).join(`
3
- `);await promises.writeFile(t,s.trim()+`
4
- `),console.log(`Successfully configured ${v} file`);}catch(t){console.error(`Setup failed: ${t instanceof Error?t.message:"Unknown error"}`),process.exit(1);}}var C=null,b=null;function G(){if(!C)throw new Error("Environment variables not loaded");return C}function D(){if(!b)throw new Error("Configuration not loaded");return b}function p(e){let t=G().MODELENCE_SERVICE_ENDPOINT;if(!t)throw new Error("MODELENCE_SERVICE_ENDPOINT not found in environment variables");return `${t}${e}`}function g(){let{serverDir:e,serverEntry:t}=D();return join(e,t)}function T(){return D().postBuildCommand}function N(e){let t=x("build");return t}function u(e){return join(process.cwd(),e)}function x(e){let t=u(".modelence");return e?join(t,e):t}async function h(){try{let e=join(process.cwd(),"modelence.config.ts"),o=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof o!="object")throw new Error("modelence.config.ts should export an object");b=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(o);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");C=parse(e);}catch(e){if(e.code!=="ENOENT")throw e}}async function Q(){let e=T();if(e){console.log("Running post-build command..."),execSync(e);return}await ee();}async function ee(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),t={build:{outDir:S.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},t,true));}async function te(){return console.log("Building server with tsup..."),new Promise((e,t)=>{build({entry:[g()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:o})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function E(){console.log("Building Modelence project...");try{let e=N();await O.rm(e,{recursive:!0,force:!0}),await te(),await Q(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function P(){let e=await fetch(p("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:t,verificationUrl:o}=await e.json();console.log(`Please visit ${o} to authenticate`),console.log(`Code: ${t}`),await oe(o);let n=await ie(t);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:n})),{token:n}}async function ie(e){let n=Date.now()+6e5;for(;Date.now()<n;){try{let r=await ae(e);if(r)return r}catch(r){console.error("Error polling for CLI token:",r);}await new Promise(r=>setTimeout(r,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function ae(e){let t=await fetch(p(`/api/cli/token?code=${e}`),{method:"GET"});if(!t.ok)throw new Error(`CLI token polling failed: ${t.statusText}`);let{token:o}=await t.json();return o}async function M(e){let t=process.cwd(),o=join(t,".modelence"),n=join(o,"tmp","bundle.zip");await E(),await le(n);let{token:r}=await P(),{bundleName:s}=await de(e.env,n,r);await promises.unlink(n),await pe(e.env,s,join(".modelence","build","app.mjs"),r);}async function le(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(i){if(i.code!=="ENOENT")throw i}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let t=createWriteStream(e),o=ce("zip",{zlib:{level:9}});o.on("warning",i=>{if(i.code==="ENOENT")console.warn("Warning:",i);else throw i}),o.on("error",i=>{throw i});let n=new Promise((i,k)=>{t.on("close",i),t.on("error",k),o.on("error",k);});o.pipe(t);let r=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let i of r)await promises.access(u(i)).then(()=>true).catch(()=>false)&&o.file(u(i),{name:i});for(let i of s)await promises.access(u(i)).then(()=>true).catch(()=>false)&&o.directory(u(i),i);await o.finalize(),await n;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function de(e,t,o){let n=await fetch(p(`/api/environments/${e}/upload`),{method:"POST",headers:{Authorization:`Bearer ${o}`}});if(!n.ok)throw console.error(await n.text()),new Error(`Failed to create upload URL: ${n.statusText}`);let{uploadUrl:r,bundleName:s}=await n.json(),a=await promises.readFile(t),i=await fetch(r,{method:"PUT",body:a,headers:{"Content-Type":"application/zip"}});if(!i.ok)throw new Error(`Failed to upload bundle: ${i.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${s}`),{bundleName:s}}async function pe(e,t,o,n){let r=await fetch(p(`/api/environments/${e}/deploy`),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`},body:JSON.stringify({bundleName:t,entryPoint:o})});if(!r.ok)throw new Error(`Failed to trigger deployment: ${r.statusText}`);let{deploymentUrl:s}=await r.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${s}`);}function B(){console.log("Starting Modelence dev server...");let e=g(),t=S.resolve("./node_modules/.bin/tsx");execSync(`"${t}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var ge="modelence/examples",he="empty-project";async function j(e,t={}){let o=t.template||he;if(console.log(`Creating new Modelence app: ${e}`),console.log(`Using template: ${o}`),!/^[a-zA-Z0-9-_]+$/.test(e))throw new Error("Project name can only contain letters, numbers, dashes and underscores");let n=S.resolve(process.cwd(),e);if(c.existsSync(n))throw new Error(`Directory ${e} already exists`);try{let r=new Octokit,s=await r.repos.getContent({owner:"modelence",repo:"examples",path:o});if(!Array.isArray(s.data))throw new Error("Invalid template structure");c.mkdirSync(n),await I(r,s.data,o,n);let a=S.join(n,"package.json"),i=await c.readJson(a);i.name=e,await c.writeJson(a,i,{spaces:2}),console.log("Installing dependencies..."),execSync("npm install",{cwd:n,stdio:"inherit"}),console.log(`
5
- Successfully created ${e}!
6
-
7
- Get started by typing:
8
-
9
- cd ${e}
10
- npm run dev
11
- `);}catch(r){throw c.existsSync(n)&&c.removeSync(n),r.status===404?new Error(`Template "${o}" not found in ${ge}`):r}}async function I(e,t,o,n){for(let r of t){let s=S.join(n,r.name);if(r.type==="dir"){c.mkdirSync(s);let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});Array.isArray(a.data)&&await I(e,a.data,`${o}/${r.name}`,s);}else {let a=await e.repos.getContent({owner:"modelence",repo:"examples",path:`${o}/${r.name}`});if("content"in a.data&&typeof a.data.content=="string"){let i=Buffer.from(a.data.content,"base64").toString();await c.writeFile(s,i);}}}}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.command("create-app <project-name>").description("Create a new Modelence application").option("-t, --template <template-name>","Template to use (from examples repository)").action(async(e,t)=>{await j(e,{template:t.template});});m.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 $(e);});m.command("build").description("Build the application").action(async()=>{await h(),await E();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await h(),await M(e);});m.command("dev").description("Start development server").action(async()=>{await h(),B();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
2
+ import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import G,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import re from'archiver';import Q from'open';var v=".modelence.env";async function I(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 _(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${v} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function F(e){return String(e).replace(/"/g,'\\"')}async function L(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 x(e){try{let o=join(process.cwd(),v),t={};try{let c=await promises.readFile(o,"utf8");t=parse(c),await L(o),await _()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(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(([c,n])=>`${c}="${F(n)}"`).join(`
3
+ `);await promises.writeFile(o,s.trim()+`
4
+ `),console.log(`Successfully configured ${v} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var y=null,C=null;function z(){if(!y)throw new Error("Environment variables not loaded");return y}function k(){if(!C)throw new Error("Configuration not loaded");return C}function d(e){let o=z().MODELENCE_SERVICE_ENDPOINT;if(!o)throw new Error("MODELENCE_SERVICE_ENDPOINT not found in environment variables");return `${o}${e}`}function g(){let{serverDir:e,serverEntry:o}=k();return join(e,o)}function D(){return k().postBuildCommand}function S(e){let o=b("build");return o}function u(e){return join(process.cwd(),e)}function b(e){let o=u(".modelence");return e?join(o,e):o}async function w(){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");C=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");y=parse(e);}catch(e){if(e.code!=="ENOENT")throw e}}async function X(){let e=D();if(e){console.log("Running post-build command..."),execSync(e);return}await Y();}async function Y(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:G.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function H(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[g()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function E(){console.log("Building Modelence project...");try{let e=S();await O.rm(e,{recursive:!0,force:!0}),await H(),await X(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(b());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function T(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Q(t);let r=await oe(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function oe(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await te(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 te(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function P(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await E(),await ie(r);let{token:i}=await T(),{bundleName:s}=await se(e.env,r,i);await promises.unlink(r),await ce(e.env,s,join(".modelence","build","app.mjs"),i);}async function ie(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=re("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,N)=>{o.on("close",n),o.on("error",N),t.on("error",N);});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(u(n)).then(()=>true).catch(()=>false)&&t.file(u(n),{name:n});for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.directory(u(n),n);await t.finalize(),await r;let c=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(c.size/1024/1024).toFixed(2)} MB)`);}async function se(e,o,t){let r=await fetch(d(`/api/environments/${e}/upload`),{method:"POST",headers:{Authorization:`Bearer ${t}`}});if(!r.ok)throw console.error(await r.text()),new Error(`Failed to create upload URL: ${r.statusText}`);let{uploadUrl:i,bundleName:s}=await r.json(),c=await promises.readFile(o),n=await fetch(i,{method:"PUT",body:c,headers:{"Content-Type":"application/zip"}});if(!n.ok)throw new Error(`Failed to upload bundle: ${n.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${s}`),{bundleName:s}}async function ce(e,o,t,r){let i=await fetch(d(`/api/environments/${e}/deploy`),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({bundleName:o,entryPoint:t})});if(!i.ok)throw new Error(`Failed to trigger deployment: ${i.statusText}`);let{deploymentUrl:s}=await i.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${s}`);}function B(){console.log("Starting Modelence dev server...");let e=g(),o=G.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",env:{...process.env,NODE_ENV:"development"}});}var m=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");m.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 x(e);});m.command("build").description("Build the application").action(async()=>{await w(),await E();});m.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-e, --env <env>","Environment (deployment alias)").action(async e=>{await w(),await P(e);});m.command("dev").description("Start development server").action(async()=>{await w(),B();});m.parse(process.argv);//# sourceMappingURL=modelence.js.map
12
5
  //# sourceMappingURL=modelence.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/create-app.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","studioBaseUrl","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","EXAMPLES_REPO","DEFAULT_TEMPLATE","createApp","projectName","template","projectPath","octokit","Octokit","downloadTemplateFiles","packageJsonPath","packageJson","contents","templateName","targetPath","item","itemPath","dirContents","fileContent","content","program","Command"],"mappings":";8eAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CA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nimport { join } from 'path';\nimport { parse as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 } // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: fileBuffer,\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","import { Octokit } from '@octokit/rest';\nimport fs from 'fs-extra';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nconst EXAMPLES_REPO = 'modelence/examples';\nconst DEFAULT_TEMPLATE = 'empty-project';\n\ninterface CreateAppOptions {\n template?: string;\n}\n\nexport async function createApp(projectName: string, options: CreateAppOptions = {}) {\n const template = options.template || DEFAULT_TEMPLATE;\n \n console.log(`Creating new Modelence app: ${projectName}`);\n console.log(`Using template: ${template}`);\n\n // Validate project name\n if (!/^[a-zA-Z0-9-_]+$/.test(projectName)) {\n throw new Error('Project name can only contain letters, numbers, dashes and underscores');\n }\n\n const projectPath = path.resolve(process.cwd(), projectName);\n\n // Check if directory already exists\n if (fs.existsSync(projectPath)) {\n throw new Error(`Directory ${projectName} already exists`);\n }\n\n try {\n // Initialize Octokit\n const octokit = new Octokit();\n\n // Get template contents from GitHub\n const response = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: template,\n });\n\n if (!Array.isArray(response.data)) {\n throw new Error('Invalid template structure');\n }\n\n // Create project directory\n fs.mkdirSync(projectPath);\n\n // Download and extract template files\n await downloadTemplateFiles(octokit, response.data, template, projectPath);\n\n // Update package.json\n const packageJsonPath = path.join(projectPath, 'package.json');\n const packageJson = await fs.readJson(packageJsonPath);\n packageJson.name = projectName;\n await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });\n\n // Install dependencies\n console.log('Installing dependencies...');\n execSync('npm install', { cwd: projectPath, stdio: 'inherit' });\n\n console.log(`\nSuccessfully created ${projectName}!\n\nGet started by typing:\n\n cd ${projectName}\n npm run dev\n `);\n\n } catch (error: any) {\n // Clean up on error\n if (fs.existsSync(projectPath)) {\n fs.removeSync(projectPath);\n }\n\n if (error.status === 404) {\n throw new Error(`Template \"${template}\" not found in ${EXAMPLES_REPO}`);\n }\n throw error;\n }\n}\n\nasync function downloadTemplateFiles(octokit: Octokit, contents: any[], templateName: string, targetPath: string) {\n for (const item of contents) {\n const itemPath = path.join(targetPath, item.name);\n\n if (item.type === 'dir') {\n fs.mkdirSync(itemPath);\n const dirContents = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n if (Array.isArray(dirContents.data)) {\n await downloadTemplateFiles(octokit, dirContents.data, `${templateName}/${item.name}`, itemPath);\n }\n } else {\n const fileContent = await octokit.repos.getContent({\n owner: 'modelence',\n repo: 'examples',\n path: `${templateName}/${item.name}`,\n });\n \n if ('content' in fileContent.data && typeof fileContent.data.content === 'string') {\n const content = Buffer.from(fileContent.data.content, 'base64').toString();\n await fs.writeFile(itemPath, content);\n }\n }\n }\n} ","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { createApp } from './create-app';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\n// Commands that don't need config\nprogram\n .command('create-app <project-name>')\n .description('Create a new Modelence application')\n .option('-t, --template <template-name>', 'Template to use (from examples repository)')\n .action(async (projectName, options) => {\n await createApp(projectName, {\n template: options.template\n });\n });\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-e, --env <env>', 'Environment (deployment alias)')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
1
+ {"version":3,"sources":["../../src/bin/setup.ts","../../src/bin/config.ts","../../src/bin/build.ts","../../src/bin/auth.ts","../../src/bin/deploy.ts","../../src/bin/dev.ts","../../src/bin/modelence.ts"],"names":["MODELENCE_ENV_FILE","fetchServiceConfig","setupToken","host","response","errorText","confirmOverwrite","rl","createInterface","resolve","answer","escapeEnvValue","value","backupEnvFile","envPath","backupPath","fs","error","setup","options","join","existingEnv","envContent","parseEnv","config","newEnv","key","env","getEnv","getConfig","getStudioUrl","path","studioBaseUrl","getServerPath","serverDir","serverEntry","getPostBuildCommand","getBuildPath","subPath","buildDir","getModelencePath","getProjectPath","modelenceDir","loadEnv","configPath","configModule","createJiti","z","parseDotenv","buildClient","postBuildCommand","execSync","buildVite","userConfig","loadConfigFromFile","modelenceConfig","viteBuild","mergeConfig","buildServer","reject","tsupBuild","format","build","authenticateCli","code","verificationUrl","open","token","waitForAuth","writeFileSync","pollExpireTs","pollForToken","deploy","cwd","bundlePath","createBundle","bundleName","uploadBundle","triggerDeployment","output","createWriteStream","archive","archiver","err","archiveComplete","bundleFiles","bundleDirs","file","dir","stats","deploymentAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";wbAKA,IAAMA,CAAqB,CAAA,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAoBC,CAAAA,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAI,CAAc,UAAA,CAAA,CAAA,CAChD,MAAQ,CAAA,KAAA,CACR,OAAS,CAAA,CACP,yBAA2BD,CAAAA,CAC7B,CACF,CAAC,CAED,CAAA,GAAI,CAACE,CAAAA,CAAS,EAAI,CAAA,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAK,EAAA,CACtC,MAAM,IAAI,KAAMC,CAAAA,CAAAA,EAAa,CAA8BD,2BAAAA,EAAAA,CAAAA,CAAS,MAAM,CAAE,CAAA,CAC9E,CAEA,OAAOA,CAAS,CAAA,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAKC,CAAAA,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAQ,CAAA,KAAA,CACf,MAAQ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as parseEnv } from 'dotenv';\nimport { createInterface } from 'readline';\n\nconst MODELENCE_ENV_FILE = '.modelence.env';\n\ninterface SetupResponse {\n environmentId: string;\n serviceEndpoint: string;\n serviceToken: string;\n containerId: string;\n}\n\nasync function fetchServiceConfig(setupToken: string, host: string): Promise<SetupResponse> {\n const response = await fetch(`${host}/api/setup`, {\n method: 'GET',\n headers: {\n 'X-Modelence-Setup-Token': setupToken,\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(errorText || `Request failed with status ${response.status}`);\n }\n\n return response.json();\n}\n\nasync function confirmOverwrite(): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout\n });\n\n return new Promise((resolve) => {\n rl.question(`Warning: ${MODELENCE_ENV_FILE} already exists. Do you want to overwrite it? (y/N) `, (answer) => {\n rl.close();\n resolve(answer.toLowerCase() === 'y');\n });\n });\n}\n\nfunction escapeEnvValue(value: string | number): string {\n // Convert to string and escape quotes\n return String(value).replace(/\"/g, '\\\\\"');\n}\n\nasync function backupEnvFile(envPath: string): Promise<void> {\n try {\n const backupPath = envPath.replace('.env', '.backup.env');\n await fs.copyFile(envPath, backupPath);\n console.log(`Backup created at ${backupPath}`);\n } catch (error) {\n console.warn('Failed to create backup file:', error);\n }\n}\n\nexport async function setup(options: { token: string, host: string }) {\n try {\n const envPath = join(process.cwd(), MODELENCE_ENV_FILE);\n let existingEnv = {};\n\n try {\n // Check if .modelence.env exists\n const envContent = await fs.readFile(envPath, 'utf8');\n existingEnv = parseEnv(envContent);\n\n // Create backup before overwriting\n await backupEnvFile(envPath);\n\n // Ask for confirmation before overwriting\n const shouldContinue = await confirmOverwrite();\n if (!shouldContinue) {\n console.log('Setup canceled');\n process.exit(0);\n }\n } catch (error) {\n // File doesn't exist, we'll create it\n }\n\n // Fetch service configuration using setup token\n console.log('Fetching service configuration...');\n const config = await fetchServiceConfig(options.token, options.host);\n\n // Update environment variables\n const newEnv = {\n ...existingEnv,\n MODELENCE_CRON_ENABLED: 'true',\n MODELENCE_TELEMETRY_ENABLED: 'false', // TODO: Remove after all usages are gone\n MODELENCE_ENVIRONMENT_ID: config.environmentId,\n MODELENCE_SERVICE_ENDPOINT: options.host, // TODO: Replace with config.serviceEndpoint in the future\n MODELENCE_SERVICE_TOKEN: config.serviceToken,\n MODELENCE_CONTAINER_ID: config.containerId,\n };\n\n // Convert to .env format with escaped values\n const envContent = Object.entries(newEnv)\n .map(([key, value]) => `${key}=\"${escapeEnvValue(value)}\"`)\n .join('\\n');\n\n // Write the file\n await fs.writeFile(envPath, envContent.trim() + '\\n');\n console.log(`Successfully configured ${MODELENCE_ENV_FILE} file`);\n\n } catch (error: unknown) {\n console.error(`Setup failed: ${error instanceof Error ? error.message : 'Unknown error'}`);\n process.exit(1);\n }\n}\n","import { createJiti } from 'jiti';\nimport { parse as parseDotenv } from 'dotenv';\nimport { join } from 'path';\nimport fs from 'fs/promises';\nimport { ModelenceConfig } from '../types';\nimport { z } from 'zod';\n\nlet env: Record<string, string> | null = null;\nlet config: ModelenceConfig | null = null;\n\nexport function getEnv() {\n if (!env) {\n throw new Error('Environment variables not loaded');\n }\n\n return env;\n}\n\nexport function getConfig() {\n if (!config) {\n throw new Error('Configuration not loaded');\n }\n\n return config;\n}\n\nexport function getStudioUrl(path: string) {\n const studioBaseUrl = getEnv().MODELENCE_SERVICE_ENDPOINT;\n if (!studioBaseUrl) {\n throw new Error('MODELENCE_SERVICE_ENDPOINT not found in environment variables');\n }\n\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { env: string }) {\n const cwd = process.cwd();\n const modelenceDir = join(cwd, '.modelence');\n\n const bundlePath = join(modelenceDir, 'tmp', 'bundle.zip');\n\n await build();\n\n await createBundle(bundlePath);\n\n const { token } = await authenticateCli();\n\n const { bundleName } = await uploadBundle(options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.env, bundleName, join('.modelence', 'build', 'app.mjs'), token);\n}\n\nasync function createBundle(bundlePath: string) {\n try {\n await fs.unlink(bundlePath);\n console.log('Removed existing bundle');\n } catch (error) {\n // Ignore error if file doesn't exist\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n\n console.log('Creating deployment bundle...');\n\n await fs.mkdir(join(bundlePath, '..'), { recursive: true });\n\n const output = createWriteStream(bundlePath);\n const archive = archiver('zip', {\n zlib: { level: 9 } // Maximum compression\n });\n\n archive.on('warning', (err) => {\n if (err.code === 'ENOENT') {\n console.warn('Warning:', err);\n } else {\n throw err;\n }\n });\n\n archive.on('error', (err) => {\n throw err;\n });\n\n const archiveComplete = new Promise<void>((resolve, reject) => {\n output.on('close', resolve);\n output.on('error', reject);\n archive.on('error', reject);\n });\n\n archive.pipe(output);\n\n const bundleFiles = [\n 'package.json',\n 'next.config.js',\n 'next.config.ts',\n 'modelence.config.ts',\n ];\n\n const bundleDirs = [\n 'public',\n 'server',\n join('.modelence', 'build'),\n '.next',\n ];\n\n for (const file of bundleFiles) {\n if (await fs.access(getProjectPath(file)).then(() => true).catch(() => false)) {\n archive.file(getProjectPath(file), { name: file });\n }\n }\n\n for (const dir of bundleDirs) {\n if (await fs.access(getProjectPath(dir)).then(() => true).catch(() => false)) {\n archive.directory(getProjectPath(dir), dir);\n }\n }\n\n await archive.finalize();\n await archiveComplete;\n\n const stats = await fs.stat(bundlePath);\n console.log(`Deployment bundle created at: ${bundlePath} (${(stats.size / 1024 / 1024).toFixed(2)} MB)`);\n}\n\nasync function uploadBundle(deploymentAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/upload`), {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${token}`\n }\n });\n\n if (!response.ok) {\n console.error(await response.text());\n throw new Error(`Failed to create upload URL: ${response.statusText}`);\n }\n\n const { uploadUrl, bundleName } = await response.json();\n\n const fileBuffer = await fs.readFile(bundlePath);\n const uploadResponse = await fetch(uploadUrl, {\n method: 'PUT',\n body: fileBuffer,\n headers: {\n 'Content-Type': 'application/zip',\n },\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload bundle: ${uploadResponse.statusText}`);\n }\n\n console.log('Successfully uploaded bundle to Modelence Cloud');\n console.log(`Bundle name: ${bundleName}`);\n\n return { bundleName };\n}\n\nasync function triggerDeployment(deploymentAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/environments/${deploymentAlias}/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n bundleName,\n entryPoint,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to trigger deployment: ${response.statusText}`);\n }\n\n const { deploymentUrl } = await response.json();\n\n console.log('Successfully triggered deployment');\n console.log(`Follow your deployment progress at: ${deploymentUrl}`);\n}\n","import { getServerPath } from './config';\nimport { execSync } from 'child_process';\nimport path from 'path';\n\nexport function dev() {\n console.log('Starting Modelence dev server...');\n \n const serverPath = getServerPath(); \n const tsxPath = path.resolve('./node_modules/.bin/tsx');\n\n execSync(`\"${tsxPath}\" watch \"${serverPath}\"`, {\n stdio: 'inherit',\n env: { ...process.env, NODE_ENV: 'development' }\n }); \n}\n","#!/usr/bin/env node\n\nimport { Command } from 'commander';\nimport { setup } from './setup';\nimport { build } from './build';\nimport { deploy } from './deploy';\nimport { dev } from './dev';\nimport { loadEnv } from './config';\n\nconst program = new Command()\n .name('modelence')\n .description('Modelence CLI tool')\n .version('0.2.1');\n\nprogram\n .command('setup')\n .description('Setup Modelence environment variables')\n .requiredOption('-t, --token <token>', 'Modelence setup token')\n .option('-h, --host <host>', 'Modelence host', 'https://cloud.modelence.com')\n .action(async (options) => {\n await setup(options);\n });\n\nprogram\n .command('build')\n .description('Build the application')\n .action(async () => {\n await loadEnv();\n await build();\n });\n\nprogram\n .command('deploy')\n .description('Deploy to Modelence Cloud')\n .requiredOption('-e, --env <env>', 'Environment (deployment alias)')\n .action(async (options) => {\n await loadEnv();\n await deploy(options);\n });\n\nprogram\n .command('dev')\n .description('Start development server')\n .action(async () => {\n await loadEnv();\n dev();\n });\n\nprogram.parse(process.argv);\n"]}
package/dist/client.d.ts CHANGED
@@ -12,6 +12,10 @@ declare function renderApp({ loadingElement, routesElement, favicon, errorHandle
12
12
  errorHandler?: ErrorHandler;
13
13
  }): void;
14
14
 
15
+ /**
16
+ * @group React Hooks
17
+ * Client-side React hooks for data fetching and mutations
18
+ */
15
19
  type Args = Record<string, unknown>;
16
20
  type MethodResult<T> = {
17
21
  isFetching: boolean;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","triggerMethod","useMethod","useMutation","stableArgs","useMemo","stableOptions","setResult","useState","data","useEffect","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","initConfig","jsx","Fragment","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"qQAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAQ,CAAA,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAASC,MAAAA,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAM,CAAA,yCAAA,CAA2CA,CAAC,CACnD,CAAA,IACT,CACF,CAEO,SAASC,EAAuBC,CAAiB,CAAA,CACtD,aAAa,OAAQ,CAAA,mBAAA,CAAqB,KAAK,SAAUA,CAAAA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAA6B,CAAA,CAACC,CAAOC,CAAAA,CAAAA,GAAe,CACtD,MAAM,IAAI,KAAM,CAAA,CAAA,sBAAA,EAAyBA,CAAU,CAAMD,GAAAA,EAAAA,CAAAA,CAAM,UAAU,CAAA,CAAE,CAC7E,CAAA,CAEO,SAASE,CAAAA,CAAgBC,EAAuB,CACrDJ,CAAAA,CAAeI,EACjB,CAEO,SAASC,EAAYJ,CAAcC,CAAAA,CAAAA,CAAoB,CAC5D,OAAOF,CAAaC,CAAAA,CAAAA,CAAOC,CAAU,CACvC,CCUA,eAAsBI,CAAwBJ,CAAAA,CAAAA,CAAoBK,EAAa,EAAC,CAAe,CAC7F,GAAI,CACF,OAAO,MAAMC,CAAAA,CAAQ,yBAAyBN,CAAU,CAAA,CAAA,CAAIK,CAAI,CAClE,CAAA,MAASN,CAAO,CAAA,CACd,MAAAI,CAAAA,CAAYJ,EAAgBC,CAAU,CAAA,CAChCD,CACR,CACF,CAEA,eAAeO,CAAkBC,CAAAA,CAAAA,CAAkBF,CAAwB,CAAA,CACzE,IAAMG,CAAAA,CAAW,MAAM,KAAMD,CAAAA,CAAAA,CAAU,CACrC,MAAQ,CAAA,MAAA,CACR,QAAS,CACP,cAAA,CAAgB,kBACl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AO,CACH,CAAA,CAAA,CACF,CACF,CAEIC,CAAAA,CAAAA,CAAS,CACX,IAAMG,CAAAA,CAAO,SAAS,aAAc,CAAA,mBAAmB,CACvD,CAAA,GAAKA,CAMHA,CAAAA,CAAAA,CAAK,KAAOH,CANH,CAAA,KAAA,CACT,IAAMI,CAAU,CAAA,QAAA,CAAS,cAAc,MAAM,CAAA,CAC7CA,EAAQ,GAAM,CAAA,MAAA,CACdA,EAAQ,IAAOJ,CAAAA,CAAAA,CACf,SAAS,IAAK,CAAA,WAAA,CAAYI,CAAO,EACnC,CAGF,CACF,CC/BA,eAAsBC,CAAAA,CAAmB,CAAE,KAAAC,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CACjG,MAAMxD,CAAAA,CAAW,iCAAmC,CAAA,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAC,EAGvE,MAAMC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,EAC7C,CAEA,eAAsBC,CAAAA,CAAkB,CAAE,KAAAF,CAAAA,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CAChG,GAAM,CAAE,KAAA5B,CAAK,CAAA,CAAI,MAAM5B,CAA2B,CAAA,gCAAA,CAAkC,CAAE,KAAAuD,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,CAAA,CACvG,OAAApB,CAAeR,CAAAA,CAAI,EACZA,CACT,CAEA,eAAsB8B,CAAS,EAAA,CAC7B,MAAM1D,CAAAA,CAAW,qBAAqB,CAAA,CACtCoC,EAAe,IAAI,EACrB,CClBaG,IAAAA,CAAAA,CAAc,cAAeY,CAEtCA,CAAAA,CAAAA,CAAM,SAAUZ,CAAAA,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { useState, useEffect, useMemo } from 'react';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(methodName: string, args: Args = {}, options?: { enabled?: boolean }): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: options?.enabled ?? true });\n return {\n ...result,\n refetch: (args?: Args) => triggerMethod(args),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}): MethodResult<T> & {\n /** Function to trigger the mutation with optional arguments */\n mutate: (args?: Args) => void,\n /** \n * Async version of mutate that returns a promise with the result.\n * Useful when you need to wait for the mutation to complete.\n */\n mutateAsync: (args?: Args) => Promise<T>\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: false });\n return {\n ...result,\n mutate: (args?: Args) => triggerMethod(args),\n mutateAsync: triggerMethod,\n };\n}\n\nexport function useMethod<T>(methodName: string, args: Args = {}, options: { enabled: boolean }): {\n result: MethodResult<T>,\n triggerMethod: (args?: Args) => Promise<T>\n} {\n // Memoize the args object to maintain reference stability and prevent infinite re-renders\n const stableArgs = useMemo(() => args, [JSON.stringify(args)]);\n const stableOptions = useMemo(() => options, [JSON.stringify(options)]);\n\n const [result, setResult] = useState<MethodResult<T>>({\n isFetching: options.enabled,\n error: null,\n data: null,\n });\n\n const triggerMethod = async (args: Args = stableArgs) => {\n setResult({ isFetching: true, error: null, data: result.data });\n try {\n const data = await callMethod<T>(methodName, args);\n setResult({ isFetching: false, error: null, data });\n return data;\n } catch (error) {\n setResult({ isFetching: false, error: error as Error, data: null });\n throw error;\n }\n };\n\n // TODO: switch to React Query (TanStack Query)\n useEffect(() => {\n if (!options.enabled) {\n return;\n }\n\n triggerMethod();\n }, [methodName, stableArgs, stableOptions]);\n\n return { result, triggerMethod };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return <>{children}</>;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
1
+ {"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","useQuery","options","triggerMethod","useMethod","useMutation","stableArgs","useMemo","stableOptions","setResult","useState","data","useEffect","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","initConfig","jsx","Fragment","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"qQAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAQ,CAAA,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAASC,MAAAA,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAM,CAAA,yCAAA,CAA2CA,CAAC,CACnD,CAAA,IACT,CACF,CAEO,SAASC,EAAuBC,CAAiB,CAAA,CACtD,aAAa,OAAQ,CAAA,mBAAA,CAAqB,KAAK,SAAUA,CAAAA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAA6B,CAAA,CAACC,CAAOC,CAAAA,CAAAA,GAAe,CACtD,MAAM,IAAI,KAAM,CAAA,CAAA,sBAAA,EAAyBA,CAAU,CAAMD,GAAAA,EAAAA,CAAAA,CAAM,UAAU,CAAA,CAAE,CAC7E,CAAA,CAEO,SAASE,CAAAA,CAAgBC,EAAuB,CACrDJ,CAAAA,CAAeI,EACjB,CAEO,SAASC,EAAYJ,CAAcC,CAAAA,CAAAA,CAAoB,CAC5D,OAAOF,CAAaC,CAAAA,CAAAA,CAAOC,CAAU,CACvC,CCeA,eAAsB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,KAAAuD,CAAAA,CAAAA,CAAO,QAAAC,CAAAA,CAAS,CAAC,CAAA,CACvG,OAAApB,CAAeR,CAAAA,CAAI,EACZA,CACT,CAEA,eAAsB8B,CAAS,EAAA,CAC7B,MAAM1D,CAAAA,CAAW,qBAAqB,CAAA,CACtCoC,EAAe,IAAI,EACrB,CClBaG,IAAAA,CAAAA,CAAc,cAAeY,CAEtCA,CAAAA,CAAAA,CAAM,SAAUZ,CAAAA,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/**\n * @group React Hooks\n * Client-side React hooks for data fetching and mutations\n */\n\n/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { useState, useEffect, useMemo } from 'react';\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\ntype Args = Record<string, unknown>;\n\ntype MethodResult<T> = {\n isFetching: boolean;\n error: Error | null;\n data: T | null;\n};\n\nexport async function callMethod<T = unknown>(methodName: string, args: Args = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: Args): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n\n/**\n * React hook for executing a query method.\n * \n * This hook automatically executes the query on mount and provides a refetch capability.\n * Similar to React Query's useQuery hook.\n * \n * @typeParam T - The expected return type of the query\n * @param methodName - The name of the method to query\n * @param args - Optional arguments to pass to the method\n * @param options - Optional options object\n * @param options.enabled - Boolean indicating if the query should be enabled\n * @returns {Object} An object containing the query state and a refetch function:\n * - `data` - The data returned by the query, or null if not yet loaded\n * - `isFetching` - Boolean indicating if the query is in progress\n * - `error` - Any error that occurred during the query, or null\n * - `refetch` - Function to manually trigger a refetch with optional new arguments\n * \n * @example\n * ```tsx\n * function MyComponent() {\n * // This is assuming you have a Module named \"todo\" with a query named \"getItem\"\n * const { data, isFetching, error } = useQuery<Todo>('todo.getItem', { id: '123' });\n * if (isFetching) {\n * return <div>Loading...</div>;\n * }\n * if (error) {\n * return <div>Error: {error.message}</div>;\n * }\n * return <div>{data?.name}</div>;\n * }\n * ```\n */\nexport function useQuery<T = unknown>(methodName: string, args: Args = {}, options?: { enabled?: boolean }): MethodResult<T> & {\n /** Function to manually trigger a refetch of the query with optional new arguments */\n refetch: (args?: Args) => void\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: options?.enabled ?? true });\n return {\n ...result,\n refetch: (args?: Args) => triggerMethod(args),\n };\n}\n\n/**\n * React hook for executing a mutation method.\n * \n * This hook provides functions to trigger the mutation manually and handles loading/error states.\n * Similar to React Query's useMutation hook.\n * \n * @typeParam T - The expected return type of the mutation\n * @param methodName - The name of the method to mutate\n * @param args - Optional default arguments to pass to the method\n * @returns {Object} An object containing the mutation state and trigger functions:\n * - `data` - The data returned by the last successful mutation, or null\n * - `isFetching` - Boolean indicating if the mutation is in progress\n * - `error` - Any error that occurred during the last mutation, or null\n * - `mutate` - Function to trigger the mutation with optional arguments\n * - `mutateAsync` - Promise-returning version of mutate, useful for awaiting the result\n * \n * @example\n * ```tsx\n * const { mutate: updateTodo, isFetching, error } = useMutation<User>('todos.update');\n * \n * // Later in your code:\n * updateTodo({ id: '123', name: 'New Name' });\n * ```\n */\nexport function useMutation<T = unknown>(methodName: string, args: Args = {}): MethodResult<T> & {\n /** Function to trigger the mutation with optional arguments */\n mutate: (args?: Args) => void,\n /** \n * Async version of mutate that returns a promise with the result.\n * Useful when you need to wait for the mutation to complete.\n */\n mutateAsync: (args?: Args) => Promise<T>\n} {\n const { result, triggerMethod } = useMethod<T>(methodName, args, { enabled: false });\n return {\n ...result,\n mutate: (args?: Args) => triggerMethod(args),\n mutateAsync: triggerMethod,\n };\n}\n\nexport function useMethod<T>(methodName: string, args: Args = {}, options: { enabled: boolean }): {\n result: MethodResult<T>,\n triggerMethod: (args?: Args) => Promise<T>\n} {\n // Memoize the args object to maintain reference stability and prevent infinite re-renders\n const stableArgs = useMemo(() => args, [JSON.stringify(args)]);\n const stableOptions = useMemo(() => options, [JSON.stringify(options)]);\n\n const [result, setResult] = useState<MethodResult<T>>({\n isFetching: options.enabled,\n error: null,\n data: null,\n });\n\n const triggerMethod = async (args: Args = stableArgs) => {\n setResult({ isFetching: true, error: null, data: result.data });\n try {\n const data = await callMethod<T>(methodName, args);\n setResult({ isFetching: false, error: null, data });\n return data;\n } catch (error) {\n setResult({ isFetching: false, error: error as Error, data: null });\n throw error;\n }\n };\n\n // TODO: switch to React Query (TanStack Query)\n useEffect(() => {\n if (!options.enabled) {\n return;\n }\n\n triggerMethod();\n }, [methodName, stableArgs, stableOptions]);\n\n return { result, triggerMethod };\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return <>{children}</>;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\ntype User = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: User }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { useQuery, useMutation, callMethod } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout } from './auth/client';\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",n="0.4.11",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@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","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",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",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:a,repository:m,author:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
+ export{u as author,l as bin,y as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,p as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-3BGRNR6U.js.map
3
+ //# sourceMappingURL=package-3BGRNR6U.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,QAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,eACRC,CAAAA,CAAAA,CAAS,mBACTC,CAAW,CAAA,CACT,IAAK,iBACL,CAAA,UAAA,CAAY,mBACZ,UAAY,CAAA,kBAAA,CACZ,WAAa,CAAA,iBACf,EACAC,CAAS,CAAA,CACP,OACA,UACF,CAAA,CACAC,EAAO,CACL,SAAA,CAAa,yBACf,CACAC,CAAAA,CAAAA,CAAW,CACT,KAAS,CAAA,MAAA,CACT,IAAO,cACP,CAAA,cAAA,CAAkB,gBAClB,IAAQ,CAAA,2CAAA,CACR,WAAe,CAAA,6BACjB,EACAC,CAAc,CAAA,CACZ,KAAQ,KACR,CAAA,GAAA,CAAO,gDACT,CACAC,CAAAA,CAAAA,CAAU,YACVC,CAAW,CAAA,wBAAA,CACXC,EAAQ,CACN,GAAA,CAAO,+CACT,CACAC,CAAAA,CAAAA,CAAY,wBACZC,CAAmB,CAAA,CACjB,iBAAmB,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version\": \"0.4.11\",\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 \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/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 \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\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 \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\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"]}
package/dist/server.d.ts CHANGED
@@ -315,17 +315,59 @@ type RouteDefinition = {
315
315
  errorHandler?: RouteHandler;
316
316
  };
317
317
 
318
+ /** Array of Store instances that will be provisioned when the module is loaded */
318
319
  type Stores = Store<any, any>[];
320
+ /** Record of query methods that can be called from the client */
319
321
  type Queries = Record<string, MethodDefinition<any>>;
322
+ /** Record of mutation methods that can be called from the client */
320
323
  type Mutations = Record<string, MethodDefinition<any>>;
324
+ /**
325
+ * The Module class is a core building block of a Modelence application that encapsulates related functionality.
326
+ * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.
327
+ *
328
+ * @category Module
329
+ *
330
+ * @example
331
+ * ```ts
332
+ * const todoModule = new Module('todo', {
333
+ * stores: [dbTodos],
334
+ * queries: {
335
+ * async getAll() {
336
+ * // Fetch and return all Todo items
337
+ * }
338
+ * },
339
+ * mutations: {
340
+ * async create({ title }, { user }) {
341
+ * // Create a new Todo item
342
+ * }
343
+ * }
344
+ * });
345
+ * ```
346
+ */
321
347
  declare class Module {
348
+ /** @internal */
322
349
  readonly name: string;
350
+ /** @internal */
323
351
  readonly stores: Stores;
352
+ /** @internal */
324
353
  readonly queries: Queries;
354
+ /** @internal */
325
355
  readonly mutations: Mutations;
356
+ /** @internal */
326
357
  readonly routes: RouteDefinition[];
358
+ /** @internal */
327
359
  readonly cronJobs: Record<string, CronJobInputParams>;
360
+ /** @internal */
328
361
  readonly configSchema: ConfigSchema;
362
+ /**
363
+ * Creates a new Module instance
364
+ *
365
+ * @param name - The unique name of the module.
366
+ * This name is used to namespace queries, mutations,
367
+ * cron jobs and configuration values with a prefix (e.g. "todo.create")
368
+ *
369
+ * @param options - Module configuration options
370
+ */
329
371
  constructor(name: string, { stores, queries, mutations, routes, cronJobs, configSchema }: {
330
372
  stores?: Stores;
331
373
  queries?: Queries;
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import {a as a$2}from'./chunk-DN5SVAO2.js';import {a as a$3,b as b$1}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import at from'dotenv';import Ot from'http';import G from'express';import w,{z}from'zod';import mt from'elastic-apm-node';import W from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import T from'process';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import Dt from'bcrypt';import jt from'os';import {createServer,defineConfig}from'vite';import Bt from'@vitejs/plugin-react';import te from'path';import Ft from'fs';function ct(){return typeof window!="object"}function b(){if(!ct())throw new Error("This function can only be called on the server")}var B={},F={},se=false;function C(t){return F[t]?.value}function ae(){if(!se)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(F).filter(([t])=>B[t]?.isPublic))}function O(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!B[e]||(F[e]={key:e,type:o,value:n});}),se=true;}function ce(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:i}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(n==="secret"&&i)throw new Error(`Config ${e} with type "secret" cannot be public`)}),B=t;}var x=null;function ue(t){x=Object.assign({},x,t);}function de(){return x?.deploymentId}function me(){return x?.appAlias}function pe(){return x?.deploymentAlias}function fe(){return x?.telemetry?.serviceName}function S(){return !!x?.telemetry?.isEnabled}function P(t,e){S()&&K().info(t,e);}function he(t,e){S()&&K().error(t,e);}var h={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},ut=1;function ye({elasticCloudId:t,elasticApiKey:e}){let o=T.stdout.write,n=T.stderr.write;T.stdout.write=function(i,...r){return ge(i.toString(),h.stdout),o.call(T.stdout,i,...r)},T.stderr.write=function(i,...r){return ge(i.toString(),h.stderr),n.call(T.stderr,i,...r)},we();}function ge(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let i=e[e.length-1];i.timestamp||(i.timestamp=o,i.sequenceId=ut++),t[n]===`
2
- `?e.push({log:"",timestamp:null}):i.log+=t[n];}}async function dt(){let t=h.stdout.slice(0,-1);h.stdout=[h.stdout[h.stdout.length-1]];let e=h.stderr.slice(0,-1);h.stderr=[h.stderr[h.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:i})=>{P(o,{timestamp:n,source:"console",sequenceId:i});}),e.forEach(({log:o,timestamp:n,sequenceId:i})=>{he(o,{timestamp:n,source:"console",sequenceId:i});});}function we(){setTimeout(()=>{dt(),we();},1e3);}var be=false,E=null,H=null,Ce=async()=>{if(be)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');be=true,S()&&await ft();};async function ft(){let t=C("_system.elastic.apmEndpoint"),e=C("_system.elastic.cloudId"),o=C("_system.elastic.apiKey"),n=me()??"unknown",i=pe()??"unknown",r=de()??"unknown",s=fe();E=mt.start({serviceName:s,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:r,appAlias:n,deploymentAlias:i}});let c=new ElasticsearchTransport({apm:E,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});c.on("error",d=>{console.error("Elasticsearch Transport Error:",d);}),H=W.createLogger({level:"debug",defaultMeta:{serviceName:s},format:W.format.combine(W.format.json()),transports:[c]}),ye({elasticCloudId:e,elasticApiKey:o});}function $(t,e,o){if(!S())return {end:()=>{}};if(!E)throw new Error("startTransaction: Elastic APM is not initialized");let n=E.startTransaction(e,t);return o&&E.setCustomContext(o),n}function xe(t){if(!S()){console.error(t);return}if(!E)throw new Error("captureError: Elastic APM is not initialized");E.captureError(t);}function K(){if(!H)throw new Error("Logger is not initialized");return H}var Se=new Map,D={authenticated:null,unauthenticated:null};function Ee(t,e){D.authenticated=e.authenticated,D.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Se.set(o,n);}function k(){return D.unauthenticated?[D.unauthenticated]:[]}function Me(){return D.authenticated?[D.authenticated]:[]}function Te(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=Se.get(o);if(n&&n.permissions.includes(e))return true}return false}var V={};function Z(t,e){return b(),Ie(t),U("query",t,e)}function De(t,e){return b(),Ie(t),U("mutation",t,e)}function Re(t,e){return b(),Oe(t),U("query",t,e)}function ve(t,e){return b(),Oe(t),U("mutation",t,e)}function Ie(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Oe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function U(t,e,o){if(b(),V[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];V[e]={type:t,name:e,handler:n,permissions:i};}async function Ae(t,e,o){b();let n=V[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=$("method",`method:${t}`,{type:i,args:e}),c;try{Te(o.roles,n.permissions),c=await r(e,o);}catch(d){throw s.end("error"),d}return s.end(),c}var p=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}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(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):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 i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}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}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){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(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);}};var gt=z.string.bind(z),yt=z.number.bind(z),wt=z.date.bind(z),bt=z.boolean.bind(z),Ct=z.array.bind(z),xt=z.object.bind(z),St=z.enum.bind(z),a={string:gt,number:yt,date:wt,boolean:bt,array:Ct,object:xt,enum:St,objectId(){return z.instanceof(ObjectId)},userId(){return z.instanceof(ObjectId)},ref(t){return z.instanceof(ObjectId)},union:z.union.bind(z),infer(t){return {}}};var R=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await R.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Mt()}async function Pe(t,e){await R.updateOne({authToken:t},{$set:{userId:e}});}async function $e(t){await R.updateOne({authToken:t},{$set:{userId:null}});}async function Mt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await R.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function Tt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await R.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ke=new p("_system.session",{stores:[R],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:ae()}},heartbeat:async function(t,{session:e}){e&&await Tt(e);}}});async function Ne(t,{user:e}){let o=z.string().email().parse(t.email),n=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await g.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(d=>d.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await Dt.hash(n,10);return (await g.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function qe(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z.string().email().parse(t.email),i=z.string().parse(t.password),r=await g.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await Dt.compare(i,s))throw ze();return await Pe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Je(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await $e(o.authToken);}function ze(){return new Error("Incorrect email/password combination")}var g=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});var Be=new p("_system.user",{stores:[g],mutations:{signupWithPassword:Ne,loginWithPassword:qe,logout:Je}});async function Fe(t){let e=await je(t),o=e.userId?await g.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?Me():k();return {user:n,session:e,roles:i}}function Ke(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$3||n instanceof b$1?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var y=null;async function We(){if(y)return y;let t=A();if(!t)throw new Error("MongoDB URI is not set");y=new MongoClient(t,{maxPoolSize:20});try{return await y.connect(),await y.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),y}catch(e){throw console.error(e),y=null,e}}function A(){let t=C("_system.mongodbUri");return t?String(t):void 0}function He(){return y}function At(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,Ke(c));});}}async function Ve(t,{combinedModules:e}){let o=G();o.use(G.json()),o.use(G.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,d=await _t(r);try{let u=await Ae(c,r.body.args,d);s.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let v=u.flatten(),I=Object.entries(v.fieldErrors).map(([q,J])=>`${q}: ${(J??[]).join(", ")}`).join("; "),L=v.formErrors.join("; "),z=[I,L].filter(Boolean).join("; ");s.status(400).send(z);}else s.status(500).send(u instanceof Error?u.message:String(u));}}),At(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=Ot.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{P("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function _t(t){let e=w.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=w.object({screenWidth:w.number(),screenHeight:w.number(),windowWidth:w.number(),windowHeight:w.number(),pixelRatio:w.number(),orientation:w.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!A()){let{session:r,user:s,roles:c}=await Fe(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:k()}}async function Ze({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 i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await Y("/api/connect","POST",{hostname:jt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Qe(){return await Y("/api/configs","GET")}async function Ge(){return await Y("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Y(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var X=false,Pt=a$1.seconds(10);function Ye(){setInterval(async()=>{if(!X){X=true;try{await Ge();}catch(t){console.error("Error syncing status",t);}try{await $t();}catch(t){console.error("Error syncing config",t);}X=false;}},Pt);}async function $t(){let{configs:t}=await Qe();O(t);}var N=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function Xe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await N.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await N.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var et=new p("_system.migration",{stores:[N]});var kt=a$1.minutes(1),Ut=a$1.seconds(10),M={},ee,_=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function ot(t,{description:e="",interval:o,timeout:n=kt,handler:i}){if(M[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ee)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);M[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function nt(){if(ee)throw new Error("Cron jobs already started");let t=Object.keys(M);if(t.length>0){let e={alias:{$in:t}},o=await _.findOne({...e,"lock.containerId":{$exists:true}});await _.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await Nt(Ut);let n=await _.fetch(e),i=Date.now();n.forEach(r=>{let s=M[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(M).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),ee=setInterval(Lt,a$1.seconds(1));}}function Nt(t){return new Promise(e=>setTimeout(e,t))}async function Lt(){let t=Date.now();Object.values(M).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 zt(e);});}async function zt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=$("cron",`cron:${e}`);n().then(()=>{tt(i,o),r.end("success");}).catch(s=>{tt(i,o),xe(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await _.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function tt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function rt(){return Object.values(M).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var it=new p("_system.cron",{stores:[_]});var oe=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await Wt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[G.static("./.modelence/build/client")]}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"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Wt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Ft.existsSync(te.join(t,n))),o=[Bt(),Ht()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:te.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":te.resolve(t,"src")}}}}function Ht(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var st=new oe;async function Vt({modules:t=[],roles:e={},defaultRoles:o={},server:n=st,migrations:i=[]}){at.config(),at.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true",c=[Be,ke,it,et],d=[...c,...t];Qt(c),Zt(t),Ee(e,o);let u=Yt(d);ce(u??{});let j=Gt(d);if(s&&Xt(d),r){let{configs:I,deploymentId:L,appAlias:z,deploymentAlias:q,telemetry:J}=await Ze({configSchema:u,cronJobsMetadata:s?rt():void 0,stores:j});O(I),ue({deploymentId:L,appAlias:z,deploymentAlias:q,telemetry:J});}else O(to());let v=A();if(v&&(await We(),eo(j)),s&&await Xe(i),v)for(let I of j)I.createIndexes();r&&(await Ce(),Ye()),s&&nt().catch(console.error),await Ve(n,{combinedModules:d});}function Zt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Z(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))De(`${e.name}.${o}`,n);}}function Qt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Re(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ve(`${e.name}.${o}`,n);}}function Gt(t){return t.flatMap(e=>e.stores)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))ot(`${e.name}.${o}`,n);}function eo(t){let e=He();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function to(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}
3
- export{p as Module,f as Store,Z as createQuery,g as dbUsers,C as getConfig,a as schema,Vt as startApp};//# sourceMappingURL=server.js.map
1
+ import {a as a$2}from'./chunk-DN5SVAO2.js';import {a as a$3,b as b$1}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import at from'dotenv';import It from'http';import G from'express';import w,{z}from'zod';import pt from'elastic-apm-node';import W from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import T from'process';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import Dt from'bcrypt';import jt from'os';import {createServer,defineConfig}from'vite';import Bt from'@vitejs/plugin-react';import te from'path';import Ft from'fs';function ct(){return typeof window!="object"}function b(){if(!ct())throw new Error("This function can only be called on the server")}var B={},F={},se=false;function C(t){return F[t]?.value}function ae(){if(!se)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(F).filter(([t])=>B[t]?.isPublic))}function I(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!B[e]||(F[e]={key:e,type:o,value:n});}),se=true;}function ce(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:i}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(n==="secret"&&i)throw new Error(`Config ${e} with type "secret" cannot be public`)}),B=t;}var E=null;function de(t){E=Object.assign({},E,t);}function ue(){return E?.deploymentId}function pe(){return E?.appAlias}function me(){return E?.deploymentAlias}function fe(){return E?.telemetry?.serviceName}function S(){return !!E?.telemetry?.isEnabled}function P(t,e){S()&&K().info(t,e);}function he(t,e){S()&&K().error(t,e);}var h={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},dt=1;function ye({elasticCloudId:t,elasticApiKey:e}){let o=T.stdout.write,n=T.stderr.write;T.stdout.write=function(i,...r){return ge(i.toString(),h.stdout),o.call(T.stdout,i,...r)},T.stderr.write=function(i,...r){return ge(i.toString(),h.stderr),n.call(T.stderr,i,...r)},we();}function ge(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let i=e[e.length-1];i.timestamp||(i.timestamp=o,i.sequenceId=dt++),t[n]===`
2
+ `?e.push({log:"",timestamp:null}):i.log+=t[n];}}async function ut(){let t=h.stdout.slice(0,-1);h.stdout=[h.stdout[h.stdout.length-1]];let e=h.stderr.slice(0,-1);h.stderr=[h.stderr[h.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:i})=>{P(o,{timestamp:n,source:"console",sequenceId:i});}),e.forEach(({log:o,timestamp:n,sequenceId:i})=>{he(o,{timestamp:n,source:"console",sequenceId:i});});}function we(){setTimeout(()=>{ut(),we();},1e3);}var be=false,x=null,V=null,Ce=async()=>{if(be)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');be=true,S()&&await ft();};async function ft(){let t=C("_system.elastic.apmEndpoint"),e=C("_system.elastic.cloudId"),o=C("_system.elastic.apiKey"),n=pe()??"unknown",i=me()??"unknown",r=ue()??"unknown",s=fe();x=pt.start({serviceName:s,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",deploymentId:r,appAlias:n,deploymentAlias:i}});let c=new ElasticsearchTransport({apm:x,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});c.on("error",u=>{console.error("Elasticsearch Transport Error:",u);}),V=W.createLogger({level:"debug",defaultMeta:{serviceName:s},format:W.format.combine(W.format.json()),transports:[c]}),ye({elasticCloudId:e,elasticApiKey:o});}function $(t,e,o){if(!S())return {end:()=>{}};if(!x)throw new Error("startTransaction: Elastic APM is not initialized");let n=x.startTransaction(e,t);return o&&x.setCustomContext(o),n}function Ee(t){if(!S()){console.error(t);return}if(!x)throw new Error("captureError: Elastic APM is not initialized");x.captureError(t);}function K(){if(!V)throw new Error("Logger is not initialized");return V}var Se=new Map,D={authenticated:null,unauthenticated:null};function xe(t,e){D.authenticated=e.authenticated,D.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Se.set(o,n);}function k(){return D.unauthenticated?[D.unauthenticated]:[]}function Me(){return D.authenticated?[D.authenticated]:[]}function Te(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=Se.get(o);if(n&&n.permissions.includes(e))return true}return false}var H={};function Z(t,e){return b(),Oe(t),N("query",t,e)}function De(t,e){return b(),Oe(t),N("mutation",t,e)}function ve(t,e){return b(),Ie(t),N("query",t,e)}function Re(t,e){return b(),Ie(t),N("mutation",t,e)}function Oe(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function Ie(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function N(t,e,o){if(b(),H[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];H[e]={type:t,name:e,handler:n,permissions:i};}async function Ae(t,e,o){b();let n=H[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=$("method",`method:${t}`,{type:i,args:e}),c;try{Te(o.roles,n.permissions),c=await r(e,o);}catch(u){throw s.end("error"),u}return s.end(),c}var m=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}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(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):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 i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}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}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){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(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);}};var gt=z.string.bind(z),yt=z.number.bind(z),wt=z.date.bind(z),bt=z.boolean.bind(z),Ct=z.array.bind(z),Et=z.object.bind(z),St=z.enum.bind(z),a={string:gt,number:yt,date:wt,boolean:bt,array:Ct,object:Et,enum:St,objectId(){return z.instanceof(ObjectId)},userId(){return z.instanceof(ObjectId)},ref(t){return z.instanceof(ObjectId)},union:z.union.bind(z),infer(t){return {}}};var v=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function je(t){let e=t?await v.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Mt()}async function Pe(t,e){await v.updateOne({authToken:t},{$set:{userId:e}});}async function $e(t){await v.updateOne({authToken:t},{$set:{userId:null}});}async function Mt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await v.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function Tt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await v.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ke=new m("_system.session",{stores:[v],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:ae()}},heartbeat:async function(t,{session:e}){e&&await Tt(e);}}});async function Ue(t,{user:e}){let o=z.string().email().parse(t.email),n=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await g.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(u=>u.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await Dt.hash(n,10);return (await g.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function Je(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z.string().email().parse(t.email),i=z.string().parse(t.password),r=await g.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await Dt.compare(i,s))throw ze();return await Pe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function qe(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await $e(o.authToken);}function ze(){return new Error("Incorrect email/password combination")}var g=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]});var Be=new m("_system.user",{stores:[g],mutations:{signupWithPassword:Ue,loginWithPassword:Je,logout:qe}});async function Fe(t){let e=await je(t),o=e.userId?await g.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?Me():k();return {user:n,session:e,roles:i}}function Ke(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$3||n instanceof b$1?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var y=null;async function We(){if(y)return y;let t=A();if(!t)throw new Error("MongoDB URI is not set");y=new MongoClient(t,{maxPoolSize:20});try{return await y.connect(),await y.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),y}catch(e){throw console.error(e),y=null,e}}function A(){let t=C("_system.mongodbUri");return t?String(t):void 0}function Ve(){return y}function At(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,Ke(c));});}}async function He(t,{combinedModules:e}){let o=G();o.use(G.json()),o.use(G.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,u=await _t(r);try{let d=await Ae(c,r.body.args,u);s.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let R=d.flatten(),O=Object.entries(R.fieldErrors).map(([J,q])=>`${J}: ${(q??[]).join(", ")}`).join("; "),L=R.formErrors.join("; "),z=[O,L].filter(Boolean).join("; ");s.status(400).send(z);}else s.status(500).send(d instanceof Error?d.message:String(d));}}),At(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=It.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{P("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function _t(t){let e=w.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=w.object({screenWidth:w.number(),screenHeight:w.number(),windowWidth:w.number(),windowHeight:w.number(),pixelRatio:w.number(),orientation:w.string().nullable()}).parse(t.body.clientInfo),n={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!A()){let{session:r,user:s,roles:c}=await Fe(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:k()}}async function Ze({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 i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await Y("/api/connect","POST",{hostname:jt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Qe(){return await Y("/api/configs","GET")}async function Ge(){return await Y("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Y(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var X=false,Pt=a$1.seconds(10);function Ye(){setInterval(async()=>{if(!X){X=true;try{await Ge();}catch(t){console.error("Error syncing status",t);}try{await $t();}catch(t){console.error("Error syncing config",t);}X=false;}},Pt);}async function $t(){let{configs:t}=await Qe();I(t);}var U=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function Xe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await U.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await U.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var et=new m("_system.migration",{stores:[U]});var kt=a$1.minutes(1),Nt=a$1.seconds(10),M={},ee,_=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function ot(t,{description:e="",interval:o,timeout:n=kt,handler:i}){if(M[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(ee)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);M[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function nt(){if(ee)throw new Error("Cron jobs already started");let t=Object.keys(M);if(t.length>0){let e={alias:{$in:t}},o=await _.findOne({...e,"lock.containerId":{$exists:true}});await _.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await Ut(Nt);let n=await _.fetch(e),i=Date.now();n.forEach(r=>{let s=M[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(M).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),ee=setInterval(Lt,a$1.seconds(1));}}function Ut(t){return new Promise(e=>setTimeout(e,t))}async function Lt(){let t=Date.now();Object.values(M).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 zt(e);});}async function zt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=$("cron",`cron:${e}`);n().then(()=>{tt(i,o),r.end("success");}).catch(s=>{tt(i,o),Ee(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await _.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function tt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function rt(){return Object.values(M).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var it=new m("_system.cron",{stores:[_]});var oe=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await Wt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[G.static("./.modelence/build/client")]}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"});}isDev(){return process.env.NODE_ENV!=="production"}};async function Wt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Ft.existsSync(te.join(t,n))),o=[Bt(),Vt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:te.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":te.resolve(t,"src")}}}}function Vt(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var st=new oe;async function Ht({modules:t=[],roles:e={},defaultRoles:o={},server:n=st,migrations:i=[]}){at.config(),at.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";oo().then(()=>{}).catch(()=>{});let c=[Be,ke,it,et],u=[...c,...t];Qt(c),Zt(t),xe(e,o);let d=Yt(u);ce(d??{});let j=Gt(u);if(s&&Xt(u),r){let{configs:O,deploymentId:L,appAlias:z,deploymentAlias:J,telemetry:q}=await Ze({configSchema:d,cronJobsMetadata:s?rt():void 0,stores:j});I(O),de({deploymentId:L,appAlias:z,deploymentAlias:J,telemetry:q});}else I(to());let R=A();if(R&&(await We(),eo(j)),s&&await Xe(i),R)for(let O of j)O.createIndexes();r&&(await Ce(),Ye()),s&&nt().catch(console.error),await He(n,{combinedModules:u});}function Zt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Z(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))De(`${e.name}.${o}`,n);}}function Qt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ve(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Re(`${e.name}.${o}`,n);}}function Gt(t){return t.flatMap(e=>e.stores)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))ot(`${e.name}.${o}`,n);}function eo(t){let e=Ve();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function to(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function oo(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=await import('./package-3BGRNR6U.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:o.default.version})});}}
3
+ export{m as Module,f as Store,Z as createQuery,g as dbUsers,C as getConfig,a as schema,Ht as startApp};//# sourceMappingURL=server.js.map
4
4
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/index.ts","../src/config/server.ts","../src/app/state.ts","../src/app/logs.ts","../src/app/loggerProcess.ts","../src/app/metrics.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/user.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/migration/db.ts","../src/migration/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","appStarted","metadata","setMetadata","_metadata","getDeploymentId","getAppAlias","getDeploymentAlias","getTelemetryServiceName","isTelemetryEnabled","logInfo","message","args","getLogger","logError","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","deploymentAlias","deploymentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","startTransaction","name","context","transaction","captureError","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","handler","permissions","runMethod","method","response","Module","stores","queries","mutations","routes","cronJobs","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","handleSignupWithPassword","email","password","existingUser","usersCollection","existingEmail","e","hash","bcrypt","handleLoginWithPassword","userDoc","passwordHash","incorrectCredentialsError","handleLogout","user_default","authenticate","createRouteHandler","req","res","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","val","clientInfo","connectionInfo","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","getStores","defineCronJobs","telemetry","getLocalConfigs","initStores","merged","absoluteKey","cronAlias","cronJobParams"],"mappings":"2nBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,IACH,CAAA,MAAM,IAAI,KAAM,CAAA,gDAAgD,CAEpE,CCNA,IAAIE,EAA6B,EAAC,CAC9BC,CAAuC,CAAA,EACvCC,CAAAA,EAAAA,CAAgB,MAEb,SAASC,CAAAA,CAAUC,EAAgB,CACxC,OAAOH,EAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,EAAAA,EAAmB,CACjC,GAAI,CAACH,GACH,MAAM,IAAI,MAAM,0FAA0F,CAAA,CAG5G,OAAO,MAAA,CAAO,WACZ,CAAA,MAAA,CAAO,QAAQD,CAAM,CAAA,CAAE,OAAO,CAAC,CAACG,CAAG,CAAMJ,GAAAA,CAAAA,CAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,EAAYC,CAAsB,CAAA,CAChDA,EAAQ,OAAQ,CAAA,CAAC,CAAE,GAAA,CAAAH,CAAK,CAAA,IAAA,CAAAI,EAAM,KAAAC,CAAAA,CAAM,IAAM,CAGpC,CAFmBL,EAAI,WAAY,EAAA,CAAE,UAAW,CAAA,UAAU,CAEvC,EAAA,CAACJ,EAAaI,CAAG,CAAA,GAKxCH,EAAOG,CAAG,CAAA,CAAI,CACZ,GAA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A,MAAM,IAAI,KAAA,CAAM,6DAA6D,CAAA,CAG/E,QAAWqG,CAAS5G,IAAAA,CAAAA,CAClB4G,CAAM,CAAA,IAAA,CAAKrG,CAAM,EAErB,CAEA,SAASiL,EAA+B,EAAA,CACtC,IAAM9Q,CAAAA,CAAuB,EAAC,CAE9B,OAAI,OAAA,CAAQ,IAAI,WACdA,EAAAA,CAAAA,CAAQ,IAAK,CAAA,CACX,GAAK,CAAA,oBAAA,CACL,IAAM,CAAA,QAAA,CACN,MAAO,OAAQ,CAAA,GAAA,CAAI,WACrB,CAAC,CAGIA,CAAAA,CACT","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\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 (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\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","type AppMetadata = {\n deploymentId: string;\n appAlias: string;\n deploymentAlias: 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 getDeploymentId() {\n return metadata?.deploymentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getDeploymentAlias() {\n return metadata?.deploymentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import { getLogger } from './metrics';\nimport { isTelemetryEnabled } from './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","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from './logs';\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({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\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 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\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}","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 { getAppAlias, getDeploymentAlias, getDeploymentId, getTelemetryServiceName, isTelemetryEnabled } 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 deploymentAlias = getDeploymentAlias() ?? 'unknown';\n const deploymentId = getDeploymentId() ?? '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 deploymentId,\n appAlias,\n deploymentAlias,\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(\n winston.format.json(),\n ),\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 startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n if (!apm) {\n throw new Error('startTransaction: Elastic APM is not initialized');\n }\n\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n if (!apm) {\n throw new Error('captureError: Elastic APM is not initialized');\n }\n\n apm.captureError(error);\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '../app/metrics';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\ntype Stores = Store<any, any>[];\ntype Queries = Record<string, MethodDefinition<any>>;\ntype Mutations = Record<string, MethodDefinition<any>>;\n\nexport class Module {\n public readonly name: string;\n public readonly stores: Stores;\n public readonly queries: Queries;\n public readonly mutations: Mutations;\n public readonly routes: RouteDefinition[];\n public readonly cronJobs: Record<string, CronJobInputParams>;\n public readonly configSchema: ConfigSchema;\n\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Stores, \n queries?: Queries, \n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Optional options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\n\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n }\n});\n\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './user';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from './logs';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n // res.status(500).json({ error: 'Internal server error' });\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: req.ip || req.socket.remoteAddress, // TODO: handle cases with Proxy\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\n// import passport from 'passport';\n// import session from 'express-session';\n// import { Strategy as GoogleStrategy } from 'passport-google-oauth20';\n\n// Session middleware\n// app.use(session({\n// secret: process.env.SESSION_SECRET || 'default_secret',\n// resave: false,\n// saveUninitialized: false\n// }));\n\n// Passport middleware\n// app.use(passport.initialize());\n// app.use(passport.session());\n\n// // Passport Google strategy setup\n// passport.use(new GoogleStrategy({\n// clientID: process.env.GOOGLE_CLIENT_ID || '',\n// clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',\n// callbackURL: \"/auth/google/callback\"\n// },\n// function(accessToken: string, refreshToken: string, profile: any, cb: (error: any, user?: any) => void) {\n// // Here you would typically find or create a user in your database\n// // For now, we'll just pass the profile info\n// return cb(null, profile);\n// }));\n\n// passport.serializeUser((user: Express.User, done: (err: any, id?: unknown) => void) => {\n// done(null, user);\n// });\n\n// passport.deserializeUser((user: Express.User, done: (err: any, user?: Express.User | false | null) => void) => {\n// done(null, user);\n// });\n\n// // Google Auth routes\n// app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));\n\n// app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),\n// function(req: Request, res: Response) {\n// // Successful authentication, redirect home.\n// res.redirect('/');\n// }\n// );\n\n// // Logout route\n// app.get('/logout', (req: Request, res: Response, next: NextFunction) => {\n// req.logout(function(err) {\n// if (err) { return next(err); }\n// res.redirect('/');\n// });\n// });\n\n// // Middleware to check if user is authenticated\n// function ensureAuthenticated(req: Request, res: Response, next: NextFunction) {\n// if (req.isAuthenticated()) {\n// return next();\n// }\n// res.redirect('/login');\n// }\n\n\n// app.get('/bundle.js', function (req: Request, res: Response) {\n// res.sendFile('.modelence/client/bundle.js', { root: '.' });\n// });\n\n\n// // Update your catch-all route\n// app.get('/', function (req: Request, res: Response) {\n// res.sendFile(path.join('client', 'index.html'), { root: path.join(__dirname, '..') });\n// });\n\n\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n) {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '../app/metrics';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\ntype AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs, deploymentId, appAlias, deploymentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ deploymentId, appAlias, deploymentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/index.ts","../src/config/server.ts","../src/app/state.ts","../src/app/logs.ts","../src/app/loggerProcess.ts","../src/app/metrics.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/user.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/migration/db.ts","../src/migration/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","appStarted","metadata","setMetadata","_metadata","getDeploymentId","getAppAlias","getDeploymentAlias","getTelemetryServiceName","isTelemetryEnabled","logInfo","message","args","getLogger","logError","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","deploymentAlias","deploymentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","startTransaction","name","context","transaction","captureError","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","handler","permissions","runMethod","method","response","Module","stores","queries","mutations","routes","cronJobs","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","handleSignupWithPassword","email","password","existingUser","usersCollection","existingEmail","e","hash","bcrypt","handleLoginWithPassword","userDoc","passwordHash","incorrectCredentialsError","handleLogout","user_default","authenticate","createRouteHandler","req","res","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","val","clientInfo","connectionInfo","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","getStores","defineCronJobs","telemetry","getLocalConfigs","initStores","merged","absoluteKey","cronAlias","cronJobParams","serviceEndpoint","packageJson"],"mappings":"2nBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,IACH,CAAA,MAAM,IAAI,KAAM,CAAA,gDAAgD,CAEpE,CCNA,IAAIE,EAA6B,EAAC,CAC9BC,CAAuC,CAAA,EACvCC,CAAAA,EAAAA,CAAgB,MAEb,SAASC,CAAAA,CAAUC,EAAgB,CACxC,OAAOH,EAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,EAAAA,EAAmB,CACjC,GAAI,CAACH,GACH,MAAM,IAAI,MAAM,0FAA0F,CAAA,CAG5G,OAAO,MAAA,CAAO,WACZ,CAAA,MAAA,CAAO,QAAQD,CAAM,CAAA,CAAE,OAAO,CAAC,CAACG,CAAG,CAAMJ,GAAAA,CAAAA,CAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,EAAYC,CAAsB,CAAA,CAChDA,EAAQ,OAAQ,CAAA,CAAC,CAAE,GAAA,CAAAH,CAAK,CAAA,IAAA,CAAAI,EAAM,KAAAC,CAAAA,CAAM,IAAM,CAGpC,CAFmBL,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,OAAI,OAAQ,CAAA,GAAA,CAAI,WACdA,EAAAA,CAAAA,CAAQ,IAAK,CAAA,CACX,GAAK,CAAA,oBAAA,CACL,IAAM,CAAA,QAAA,CACN,KAAO,CAAA,OAAA,CAAQ,IAAI,WACrB,CAAC,CAGIA,CAAAA,CACT,CAEA,eAAesQ,EAAgB,EAAA,CAG7B,GAF0B,OAAQ,CAAA,GAAA,CAAI,0BAA+B,GAAA,OAAA,CAE9C,CACrB,IAAMe,CAAkB,CAAA,OAAA,CAAQ,IAAI,0BAA8B,EAAA,6BAAA,CAE5DC,CAAc,CAAA,MAAa,OAAA,uBAAoB,CAErD,CAAA,MAAM,MAAM,CAAGD,EAAAA,CAAe,CAAwB,oBAAA,CAAA,CAAA,CACpD,MAAQ,CAAA,MAAA,CACR,OAAS,CAAA,CACP,eAAgB,kBAClB,CAAA,CACA,IAAM,CAAA,IAAA,CAAK,SAAU,CAAA,CACnB,OAASC,CAAAA,CAAAA,CAAY,QAAQ,OAC/B,CAAC,CACH,CAAC,EACH,CACF","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\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 (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\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","type AppMetadata = {\n deploymentId: string;\n appAlias: string;\n deploymentAlias: 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 getDeploymentId() {\n return metadata?.deploymentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getDeploymentAlias() {\n return metadata?.deploymentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import { getLogger } from './metrics';\nimport { isTelemetryEnabled } from './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","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from './logs';\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({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\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 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\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}","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 { getAppAlias, getDeploymentAlias, getDeploymentId, getTelemetryServiceName, isTelemetryEnabled } 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 deploymentAlias = getDeploymentAlias() ?? 'unknown';\n const deploymentId = getDeploymentId() ?? '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 deploymentId,\n appAlias,\n deploymentAlias,\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(\n winston.format.json(),\n ),\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 startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n if (!apm) {\n throw new Error('startTransaction: Elastic APM is not initialized');\n }\n\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n if (!apm) {\n throw new Error('captureError: Elastic APM is not initialized');\n }\n\n apm.captureError(error);\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '../app/metrics';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Stores,\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Optional options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\n\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n }\n});\n\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './user';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from './logs';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n // res.status(500).json({ error: 'Internal server error' });\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: req.ip || req.socket.remoteAddress, // TODO: handle cases with Proxy\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\n// import passport from 'passport';\n// import session from 'express-session';\n// import { Strategy as GoogleStrategy } from 'passport-google-oauth20';\n\n// Session middleware\n// app.use(session({\n// secret: process.env.SESSION_SECRET || 'default_secret',\n// resave: false,\n// saveUninitialized: false\n// }));\n\n// Passport middleware\n// app.use(passport.initialize());\n// app.use(passport.session());\n\n// // Passport Google strategy setup\n// passport.use(new GoogleStrategy({\n// clientID: process.env.GOOGLE_CLIENT_ID || '',\n// clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',\n// callbackURL: \"/auth/google/callback\"\n// },\n// function(accessToken: string, refreshToken: string, profile: any, cb: (error: any, user?: any) => void) {\n// // Here you would typically find or create a user in your database\n// // For now, we'll just pass the profile info\n// return cb(null, profile);\n// }));\n\n// passport.serializeUser((user: Express.User, done: (err: any, id?: unknown) => void) => {\n// done(null, user);\n// });\n\n// passport.deserializeUser((user: Express.User, done: (err: any, user?: Express.User | false | null) => void) => {\n// done(null, user);\n// });\n\n// // Google Auth routes\n// app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));\n\n// app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),\n// function(req: Request, res: Response) {\n// // Successful authentication, redirect home.\n// res.redirect('/');\n// }\n// );\n\n// // Logout route\n// app.get('/logout', (req: Request, res: Response, next: NextFunction) => {\n// req.logout(function(err) {\n// if (err) { return next(err); }\n// res.redirect('/');\n// });\n// });\n\n// // Middleware to check if user is authenticated\n// function ensureAuthenticated(req: Request, res: Response, next: NextFunction) {\n// if (req.isAuthenticated()) {\n// return next();\n// }\n// res.redirect('/login');\n// }\n\n\n// app.get('/bundle.js', function (req: Request, res: Response) {\n// res.sendFile('.modelence/client/bundle.js', { root: '.' });\n// });\n\n\n// // Update your catch-all route\n// app.get('/', function (req: Request, res: Response) {\n// res.sendFile(path.join('client', 'index.html'), { root: path.join(__dirname, '..') });\n// });\n\n\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n) {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '../app/metrics';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\ntype AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs, deploymentId, appAlias, deploymentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ deploymentId, appAlias, deploymentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n \n const packageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n version: packageJson.default.version\n })\n });\n }\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.4.10",
4
+ "version": "0.4.11",
5
5
  "description": "The Node.js Framework for Real-Time MongoDB Apps",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",