modelence 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {s}from'../chunk-KKXU66LY.js';import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import K,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ie from'archiver';import Z from'open';var b=".modelence.env";async function F(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function _(e){return String(e).replace(/"/g,'\\"')}async function R(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await R(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await F(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${_(n)}"`).join(`
2
+ import {s}from'../chunk-4WVT64MC.js';import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import K,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import T from'fs/promises';import {createJiti}from'jiti';import {z}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import ie from'archiver';import Z from'open';var b=".modelence.env";async function F(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function L(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${b} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function _(e){return String(e).replace(/"/g,'\\"')}async function R(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function k(e){try{let o=join(process.cwd(),b),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await R(o),await L()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await F(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${_(n)}"`).join(`
3
3
  `);await promises.writeFile(o,s.trim()+`
4
4
  `),console.log(`Successfully configured ${b} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,N=null;function A(){if(!w)throw new Error("Environment variables not loaded");return w}function D(){if(!N)throw new Error("Configuration not loaded");return N}function d(e){return `${A().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function h(){let{serverDir:e,serverEntry:o}=D();return join(e,o).replace(/\\/g,"/")}function S(){return D().postBuildCommand}function O(e){let o=x("build");return o.replace(/\\/g,"/")}function p(e){return join(process.cwd(),e).replace(/\\/g,"/")}function x(e){let o=p(".modelence");return e?join(o,e).replace(/\\/g,"/"):o.replace(/\\/g,"/")}async function E(){try{let e=join(process.cwd(),"modelence.config.ts"),t=await createJiti(import.meta.url,{interopDefault:!0,requireCache:!1}).import(e);if(typeof t!="object")throw new Error("modelence.config.ts should export an object");N=z.object({serverDir:z.string(),serverEntry:z.string(),postBuildCommand:z.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await T.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function Y(){let e=S();if(e){console.log("Running post-build command..."),execSync(e);return}await H();}async function H(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:K.resolve(process.cwd(),".modelence/build/client").replace(/\\/g,"/"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function Q(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[h()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,platform:"node",external:[...Object.keys(s.dependencies??{}),...Object.keys(s.peerDependencies??{})],outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=O();await T.rm(e,{recursive:!0,force:!0}),await Q(),await Y(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await T.access(x());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function j(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Z(t);let r=await te(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function te(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await ne(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function ne(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function P(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await v(),await se(r);let{token:i}=await j(),{bundleName:s}=await ae(e.app,e.env,r,i);await promises.unlink(r),await ce(e.app,e.env,s,join(".modelence","build","app.mjs"),i);}async function se(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=ie("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,u)=>{o.on("close",n),o.on("error",u),t.on("error",u);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.file(p(n),{name:n});for(let n of s)await promises.access(p(n)).then(()=>true).catch(()=>false)&&t.directory(p(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function ae(e,o,t,r){let i=await fetch(d("/api/upload-bundle"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({appAlias:e,envAlias:o})});if(!i.ok)throw console.error(await i.text()),new Error(`Failed to create upload URL: ${i.statusText}`);let{uploadUrl:s,bundleName:a}=await i.json(),n=await promises.readFile(t),u=await fetch(s,{method:"PUT",body:n,headers:{"Content-Type":"application/zip"}});if(!u.ok)throw new Error(`Failed to upload bundle: ${u.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${a}`),{bundleName:a}}async function ce(e,o,t,r,i){let s=await fetch(d("/api/deploy"),{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({appAlias:e,envAlias:o,bundleName:t,entryPoint:r})});if(!s.ok)throw new Error(`Failed to trigger deployment: ${s.statusText}`);let{deploymentUrl:a}=await s.json();console.log("Successfully triggered deployment"),console.log(`Follow your deployment progress at: ${a}`);}function B(){console.log("Starting Modelence dev server...");let e=h(),o=K.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",cwd:process.cwd(),env:{...process.env,NODE_ENV:"development"}});}var f=new Command().name("modelence").description("Modelence CLI tool").version("0.2.1");f.command("setup").description("Setup Modelence environment variables").requiredOption("-t, --token <token>","Modelence setup token").option("-h, --host <host>","Modelence host","https://cloud.modelence.com").action(async e=>{await k(e);});f.command("build").description("Build the application").action(async()=>{await E(),await v();});f.command("deploy").description("Deploy to Modelence Cloud").requiredOption("-a, --app <app>","Application alias").requiredOption("-e, --env <env>","Environment alias").action(async e=>{await E(),await P(e);});f.command("dev").description("Start development server").action(async()=>{await E(),B();});f.parse(process.argv);//# sourceMappingURL=modelence.js.map
5
5
  //# sourceMappingURL=modelence.js.map
@@ -1 +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/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","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","package_default","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","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";sdAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,IAAA,EAClB,CAEA,eAAeE,CAAAA,EAAqC,CAClD,IAAMC,CAAAA,CAAKC,eAAAA,CAAgB,CACzB,KAAA,CAAO,OAAA,CAAQ,KAAA,CACf,MAAA,CAAQ,OAAA,CAAQ,MAClB,CAAC,CAAA,CAED,OAAO,IAAI,OAAA,CAASC,CAAAA,EAAY,CAC9BF,CAAAA,CAAG,QAAA,CAAS,CAAA,SAAA,EAAYP,CAAkB,uDAAyDU,CAAAA,EAAW,CAC5GH,CAAAA,CAAG,KAAA,EAAM,CACTE,CAAAA,CAAQC,CAAAA,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A,CAAOrD,CAAO,EACtB,CAAC,CAAA,CAEHiF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM1D,CAAAA,EAAQ,CACduD,IACF,CAAC,EAEHG,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\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 || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\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 // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\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';\nimport pkg from '../../package.json';\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').replace(/\\\\/g, '/'),\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 platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\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: { app: string; 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.app, options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.app, 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(appAlias: string, envAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/upload-bundle`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\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(appAlias: string, envAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\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 cwd: process.cwd(),\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('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment 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","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","package_default","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","appAlias","envAlias","uploadUrl","fileBuffer","uploadResponse","entryPoint","deploymentUrl","dev","serverPath","tsxPath","program","Command"],"mappings":";sdAKA,IAAMA,CAAAA,CAAqB,gBAAA,CAS3B,eAAeC,CAAAA,CAAmBC,CAAAA,CAAoBC,CAAAA,CAAsC,CAC1F,IAAMC,EAAW,MAAM,KAAA,CAAM,CAAA,EAAGD,CAAI,CAAA,UAAA,CAAA,CAAc,CAChD,MAAA,CAAQ,KAAA,CACR,OAAA,CAAS,CACP,yBAAA,CAA2BD,CAC7B,CACF,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAS,EAAA,CAAI,CAChB,IAAMC,CAAAA,CAAY,MAAMD,CAAAA,CAAS,IAAA,EAAK,CACtC,MAAM,IAAI,KAAA,CAAMC,CAAAA,EAAa,CAAA,2BAAA,EAA8BD,CAAAA,CAAS,MAAM,CAAA,CAAE,CAC9E,CAEA,OAAOA,CAAAA,CAAS,IAAA,EAClB,CAEA,eAAeE,CA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A,CACnC,MAAA,CAAO,SAAY,CAClB,MAAM1D,GAAQ,CACd,MAAMoB,CAAAA,GACR,CAAC,CAAA,CAEHsC,CAAAA,CACG,QAAQ,QAAQ,CAAA,CAChB,YAAY,2BAA2B,CAAA,CACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,EACrD,MAAA,CAAO,MAAOjF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,EAAQ,CACd,MAAM8B,CAAAA,CAAOrD,CAAO,EACtB,CAAC,CAAA,CAEHiF,CAAAA,CACG,OAAA,CAAQ,KAAK,CAAA,CACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAM1D,CAAAA,EAAQ,CACduD,IACF,CAAC,EAEHG,CAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"modelence.js","sourcesContent":["import { promises as fs } from 'fs';\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 type { 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 || 'https://cloud.modelence.com';\n return `${studioBaseUrl}${path}`;\n}\n\nexport function getServerPath() {\n const { serverDir, serverEntry } = getConfig();\n const path = join(serverDir, serverEntry);\n // Normalize path to use forward slashes for cross-platform compatibility\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n if (subPath) {\n const path = join(buildDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return buildDir.replace(/\\\\/g, '/');\n}\n\nexport function getProjectPath(subPath: string) {\n const path = join(process.cwd(), subPath);\n return path.replace(/\\\\/g, '/');\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n if (subPath) {\n const path = join(modelenceDir, subPath);\n return path.replace(/\\\\/g, '/');\n }\n return modelenceDir.replace(/\\\\/g, '/');\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 // Initialize with empty object to prevent \"Environment variables not loaded\" error\n env = {};\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';\nimport pkg from '../../package.json';\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').replace(/\\\\/g, '/'),\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 platform: 'node',\n external: [\n ...Object.keys(pkg.dependencies ?? {}),\n ...Object.keys(pkg.peerDependencies ?? {}),\n ],\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: { app: string; 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.app, options.env, bundlePath, token);\n\n await fs.unlink(bundlePath);\n\n await triggerDeployment(options.app, 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(appAlias: string, envAlias: string, bundlePath: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/upload-bundle`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\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(appAlias: string, envAlias: string, bundleName: string, entryPoint: string, token: string) {\n const response = await fetch(getStudioUrl(`/api/deploy`), {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${token}`\n },\n body: JSON.stringify({\n appAlias,\n envAlias,\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 cwd: process.cwd(),\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('-a, --app <app>', 'Application alias')\n .requiredOption('-e, --env <env>', 'Environment 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"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",o="0.6.3",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",g={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0"},v={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:y,license:u,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
+ export{s as a,i as b,o as c,p as d,r as e,n as f,d as g,c as h,l as i,a as j,m as k,y as l,u as m,g as n,h as o,b as p,v as q,j as r,x as s};//# sourceMappingURL=chunk-4WVT64MC.js.map
3
+ //# sourceMappingURL=chunk-4WVT64MC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,SACRC,CAAAA,CAAQ,WAAA,CACRC,EAAW,OAAA,CACXC,CAAAA,CAAe,mDACfC,CAAAA,CAAQ,eAAA,CACRC,EAAS,kBAAA,CACTC,CAAAA,CAAW,CACT,GAAA,CAAK,iBAAA,CACL,WAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,kBACb,SAAA,CAAW,CACT,MAAS,mBAAA,CACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,EACAC,CAAAA,CAAO,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,cAAA,CAAkB,gBAClB,IAAA,CAAQ,2CAAA,CACR,YAAe,6BACjB,CAAA,CACAC,EAAc,CACZ,IAAA,CAAQ,KAAA,C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AAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CAWA,MAAAC,CAAAA,CAIA,GAAA,CAAAC,EAGA,OAAA,CAAAC,CAAAA,CAOA,UAAA,CAAAC,CAAAA,CAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAgBA,YAAA,CAAAC,CAAAA,CA4BA,gBAAA,CAAAC,CAIF","file":"chunk-4WVT64MC.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.6.3\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
@@ -0,0 +1,2 @@
1
+ //# sourceMappingURL=chunk-55J6XMHW.js.map
2
+ //# sourceMappingURL=chunk-55J6XMHW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"chunk-55J6XMHW.js"}
@@ -0,0 +1,15 @@
1
+ import { Request, Response, NextFunction } from 'express';
2
+
3
+ interface ModelenceConfig {
4
+ serverDir: string;
5
+ serverEntry: string;
6
+ postBuildCommand?: string;
7
+ }
8
+ type ExpressMiddleware = (req: Request, res: Response, next: NextFunction) => void | Promise<void>;
9
+ interface AppServer {
10
+ init: () => Promise<void>;
11
+ handler: (req: Request, res: Response) => void;
12
+ middlewares?: () => ExpressMiddleware[];
13
+ }
14
+
15
+ export type { AppServer as A, ExpressMiddleware as E, ModelenceConfig as M };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  export { C as ConfigSchema, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-B8cRKzII.js';
2
+ export { M as ModelenceConfig } from './index-CwdohC5n.js';
2
3
  import 'http';
3
4
  import 'mongodb';
5
+ import 'express';
4
6
 
5
7
  declare const time: {
6
8
  seconds: (x: number) => number;
@@ -26,10 +28,4 @@ declare class RateLimitError extends ModelenceError {
26
28
  constructor(message: string);
27
29
  }
28
30
 
29
- interface ModelenceConfig {
30
- serverDir: string;
31
- serverEntry: string;
32
- postBuildCommand?: string;
33
- }
34
-
35
- export { AuthError, type ModelenceConfig, RateLimitError, ValidationError, time };
31
+ export { AuthError, RateLimitError, ValidationError, time };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- export{b as AuthError,d as RateLimitError,c as ValidationError}from'./chunk-C3UESBRX.js';export{a as time}from'./chunk-R7MPLJMA.js';//# sourceMappingURL=index.js.map
1
+ export{b as AuthError,d as RateLimitError,c as ValidationError}from'./chunk-C3UESBRX.js';export{a as time}from'./chunk-R7MPLJMA.js';import'./chunk-55J6XMHW.js';//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map
@@ -1,2 +1,2 @@
1
- export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-KKXU66LY.js';//# sourceMappingURL=package-R4BMS5HW.js.map
2
- //# sourceMappingURL=package-R4BMS5HW.js.map
1
+ export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-4WVT64MC.js';//# sourceMappingURL=package-5ZEGPCTP.js.map
2
+ //# sourceMappingURL=package-5ZEGPCTP.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-R4BMS5HW.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-5ZEGPCTP.js"}
package/dist/server.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { EmailProvider, AppServer, EmailPayload } from '@modelence/types';
1
+ import { A as AppServer } from './index-CwdohC5n.js';
2
2
  import { P as Permission, S as Session, U as UserInfo, C as ConfigSchema, d as ServerChannel, e as User, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, A as AppConfig, f as Role } from './types-B8cRKzII.js';
3
3
  import { ObjectId as ObjectId$1, WithId, IndexDescription, MongoClient, Collection, Filter, FindOptions, Document, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, ClientSession, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult, Db } from 'mongodb';
4
4
  export { ObjectId } from 'mongodb';
5
5
  import * as zod from 'zod';
6
6
  import { z } from 'zod';
7
7
  import { Request } from 'express';
8
+ import { EmailProvider, EmailPayload } from './types.js';
8
9
  import 'http';
9
10
 
10
11
  type CronJobHandler = () => Promise<void>;
@@ -444,33 +445,49 @@ type AuthOption = {
444
445
  *
445
446
  * startApp({
446
447
  * auth: {
447
- * login: {
448
- * onSuccess: (user) => {
449
- * console.log('User logged in:', user.name);
450
- * // Redirect to dashboard
451
- * },
452
- * onError: (error) => {
453
- * console.error('Login failed:', error.message);
454
- * // Show error toast
455
- * }
448
+ * onAfterLogin: ({ user }) => {
449
+ * console.log('User logged in:', user.name);
450
+ * // Redirect to dashboard
456
451
  * },
457
- * signup: {
458
- * onSuccess: (user) => {
459
- * console.log('User signed up:', user.email);
460
- * // Send welcome email
461
- * },
462
- * onError: (error) => {
463
- * console.error('Signup failed:', error.message);
464
- * }
452
+ * onLoginError: ({ error }) => {
453
+ * console.error('Login failed:', error.message);
454
+ * // Show error toast
455
+ * },
456
+ * onAfterSignup: ({ user }) => {
457
+ * console.log('User signed up:', user.email);
458
+ * // Send welcome email
459
+ * },
460
+ * onSignupError: ({ error }) => {
461
+ * console.error('Signup failed:', error.message);
465
462
  * }
466
463
  * }
467
464
  * });
468
465
  * ```
469
466
  */
470
467
  type AuthConfig = {
471
- /** Authentication options for login operations */
468
+ onAfterLogin?: (props: {
469
+ user: User;
470
+ session: Session | null;
471
+ connectionInfo: ConnectionInfo;
472
+ }) => void;
473
+ onLoginError?: (props: {
474
+ error: Error;
475
+ session: Session | null;
476
+ connectionInfo: ConnectionInfo;
477
+ }) => void;
478
+ onAfterSignup?: (props: {
479
+ user: User;
480
+ session: Session | null;
481
+ connectionInfo: ConnectionInfo;
482
+ }) => void;
483
+ onSignupError?: (props: {
484
+ error: Error;
485
+ session: Session | null;
486
+ connectionInfo: ConnectionInfo;
487
+ }) => void;
488
+ /** deprecated: use onAfterLogin and onLoginError */
472
489
  login?: AuthOption;
473
- /** Authentication options for signup operations */
490
+ /** deprecated: user onAfterSignup and onSignupError */
474
491
  signup?: AuthOption;
475
492
  };
476
493
 
package/dist/server.js CHANGED
@@ -1,18 +1,18 @@
1
- import {a as a$2}from'./chunk-DN5SVAO2.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-R7MPLJMA.js';import {b,e,d as d$1,c as c$1,f as f$1,g as g$1,i,a as a$1,h,j as j$1,k as k$1}from'./chunk-2QLNYYBR.js';export{a as getConfig}from'./chunk-2QLNYYBR.js';import Dt from'dotenv';import Ao from'fs/promises';import so from'os';import pe from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import C,{z as z$1}from'zod';import Zt from'bcrypt';import {createServer,defineConfig,loadConfigFromFile}from'vite';import yo from'@vitejs/plugin-react';import bo from'fs';import we,{Router}from'express';import he from'passport';import {Strategy}from'passport-google-oauth20';import Oo from'cookie-parser';import Mo from'http';var w=class{constructor(e,{stores:o=[],queries:r={},mutations:n={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:h=[]}){this.name=e,this.stores=o,this.queries=r,this.mutations=n,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=h;}};var g=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}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let r=await this.requireCollection().findOne(e,o);return r?this.wrapDocument(r):null}async requireOne(e,o,r){let n=await this.findOne(e,o);if(!n)throw r?r():new Error(`Record not found in ${this.name}`);return n}find(e,o){let r=this.requireCollection().find(e);return o?.sort&&r.sort(o.sort),o?.limit&&r.limit(o.limit),o?.skip&&r.skip(o.skip),r}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let r=await this.findById(e);if(!r)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return r}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,r){return await this.requireCollection().updateMany(e,o,r)}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 r=this.getDatabase();if(!this.collection||!r)throw new Error(`Store ${this.name} is not provisioned`);if((await r.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await r.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await r.collection(e).rename(this.name,o);}};var _t=z$1.string.bind(z$1),kt=z$1.number.bind(z$1),It=z$1.date.bind(z$1),At=z$1.boolean.bind(z$1),Pt=z$1.array.bind(z$1),Lt=z$1.object.bind(z$1),jt=z$1.enum.bind(z$1),c={string:_t,number:kt,date:It,boolean:At,array:Pt,object:Lt,enum:jt,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var T=new g("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function Te(t){let e=t?await T.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await re()}async function _e(t,e){await T.updateOne({authToken:t},{$set:{userId:e}});}async function ke(t){await T.updateOne({authToken:t},{$set:{userId:null}});}async function re(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),r=new Date(o+a.days(7));return await T.insertOne({authToken:e,createdAt:new Date(o),expiresAt:r,userId:t}),{authToken:e,expiresAt:r,userId:t}}async function Ut(t){let e=Date.now(),o=new Date(e+a.days(7));await T.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Ie=new w("_system.session",{stores:[T],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b()}},heartbeat:async function(t,{session:e}){e&&await Ut(e);}}});var u=new g("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),createdAt:c.date(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),L=new g("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),_=new g("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),x=new g("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Ae=new Map,k={authenticated:null,unauthenticated:null};function Pe(t,e){k.authenticated=e.authenticated,k.unauthenticated=e.unauthenticated;for(let[o,r]of Object.entries(t))Ae.set(o,r);}function B(){return k.unauthenticated?[k.unauthenticated]:[]}function Le(){return k.authenticated?[k.authenticated]:[]}function je(t,e){let o=e.find(r=>!Nt(t,r));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Nt(t,e){for(let o of t){let r=Ae.get(o);if(r&&r.permissions.includes(e))return true}return false}async function j(t){let e=await Te(t),o=e.userId?await u.findOne({_id:new ObjectId(e.userId)}):null,r=o?{id:o._id.toString(),handle:o.handle}:null,n=r?Le():B();return {user:r,session:e,roles:n}}var E=null;async function $e(){if(E)return E;let t=$();if(!t)throw new Error("MongoDB URI is not set");E=new MongoClient(t,{maxPoolSize:20});try{return await E.connect(),await E.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),E}catch(e){throw console.error(e),E=null,e}}function $(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function F(){return E}var U=null,Bt="_modelenceSocketio";async function Ft({httpServer:t,channels:e}){let o=F();if(!o)throw console.error("Socket.IO initialization failed: MongoDB client is not initialized"),new Error("Mongodb Client is not initialized");console.log("Initializing Socket.IO server...");let r=o.db().collection(Bt);try{await r.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(n){console.error("Failed to create index on MongoDB collection for Socket.IO:",n);}U=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:createAdapter(r),transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),U.on("error",n=>{console.error("Socket.IO error:",n);}),U.use(async(n,i)=>{let s=n.handshake.auth.token;try{n.data=await j(s);}finally{i();}}),U.on("connection",n=>{console.log("Socket.IO client connected"),n.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),n.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(n.data))&&n.join(i);n.join(i),console.log(`User ${n.id} joined channel ${i}`),n.emit("joinedChannel",i);}),n.on("leaveChannel",i=>{n.leave(i),console.log(`User ${n.id} left channel ${i}`),n.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function Vt({category:t,id:e,data:o}){U?.to(`${t}:${e}`).emit(t,o);}var Ue={init:Ft,broadcast:Vt};async function Ne(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await L.findOne({domain:o})}var ze={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
- `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await L.insertMany(s.map(a=>({domain:a,addedAt:r})));}catch(a){a.name==="MongoBulkWriteError"&&a.result?.nInserted;}}}};var ne=Object.freeze({});function Je(t){ne=Object.freeze(Object.assign({},ne,t));}function f(){return ne}function Ht(){return typeof window!="object"}function v(){if(!Ht())throw new Error("This function can only be called on the server")}function V(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function We({name:t,email:e,verificationUrl:o}){return `
1
+ import {a as a$2}from'./chunk-DN5SVAO2.js';import {d,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-R7MPLJMA.js';import {b,e,d as d$1,c as c$1,f,g as g$1,i,a as a$1,h as h$1,j as j$1,k as k$1}from'./chunk-2QLNYYBR.js';export{a as getConfig}from'./chunk-2QLNYYBR.js';import Ot from'dotenv';import Lo from'fs/promises';import ao from'os';import pe from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import S,{z as z$1}from'zod';import Qt from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Co from'@vitejs/plugin-react';import Eo from'fs';import ye,{Router}from'express';import he from'passport';import {Strategy}from'passport-google-oauth20';import _o from'cookie-parser';import ko from'http';var y=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:l=[],channels:p=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=l,this.channels=p;}};var w=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}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var kt=z$1.string.bind(z$1),It=z$1.number.bind(z$1),At=z$1.date.bind(z$1),Pt=z$1.boolean.bind(z$1),Lt=z$1.array.bind(z$1),jt=z$1.object.bind(z$1),Ut=z$1.enum.bind(z$1),c={string:kt,number:It,date:At,boolean:Pt,array:Lt,object:jt,enum:Ut,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var T=new w("_modelenceSessions",{schema:{authToken:c.string(),createdAt:c.date(),expiresAt:c.date(),userId:c.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function _e(t){let e=t?await T.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ne()}async function ke(t,e){await T.updateOne({authToken:t},{$set:{userId:e}});}async function Ie(t){await T.updateOne({authToken:t},{$set:{userId:null}});}async function ne(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await T.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function Nt(t){let e=Date.now(),o=new Date(e+a.days(7));await T.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Ae=new y("_system.session",{stores:[T],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b()}},heartbeat:async function(t,{session:e}){e&&await Nt(e);}}});var m=new w("_modelenceUsers",{schema:{handle:c.string(),emails:c.array(c.object({address:c.string(),verified:c.boolean()})).optional(),createdAt:c.date(),authMethods:c.object({password:c.object({hash:c.string()}).optional(),google:c.object({id:c.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),L=new w("_modelenceDisposableEmailDomains",{schema:{domain:c.string(),addedAt:c.date()},indexes:[{key:{domain:1},unique:true}]}),_=new w("_modelenceEmailVerificationTokens",{schema:{userId:c.objectId(),email:c.string().optional(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),v=new w("_modelenceResetPasswordTokens",{schema:{userId:c.objectId(),token:c.string(),createdAt:c.date(),expiresAt:c.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Pe=new Map,k={authenticated:null,unauthenticated:null};function Le(t,e){k.authenticated=e.authenticated,k.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Pe.set(o,n);}function B(){return k.unauthenticated?[k.unauthenticated]:[]}function je(){return k.authenticated?[k.authenticated]:[]}function Ue(t,e){let o=e.find(n=>!zt(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function zt(t,e){for(let o of t){let n=Pe.get(o);if(n&&n.permissions.includes(e))return true}return false}async function j(t){let e=await _e(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,r=n?je():B();return {user:n,session:e,roles:r}}var E=null;async function $e(){if(E)return E;let t=U();if(!t)throw new Error("MongoDB URI is not set");E=new MongoClient(t,{maxPoolSize:20});try{return await E.connect(),await E.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),E}catch(e){throw console.error(e),E=null,e}}function U(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function F(){return E}var $=null,Ft="_modelenceSocketio";async function Vt({httpServer:t,channels:e}){let o=F();if(!o)throw console.error("Socket.IO initialization failed: MongoDB client is not initialized"),new Error("Mongodb Client is not initialized");console.log("Initializing Socket.IO server...");let n=o.db().collection(Ft);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}$=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:createAdapter(n),transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),$.on("error",r=>{console.error("Socket.IO error:",r);}),$.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await j(s);}finally{i();}}),$.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected");}),r.on("joinChannel",async i=>{let[s]=i.split(":");for(let a of e)a.category===s&&(!a.canAccessChannel||await a.canAccessChannel(r.data))&&r.join(i);r.join(i),console.log(`User ${r.id} joined channel ${i}`),r.emit("joinedChannel",i);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);});}),console.log("Socket.IO server initialized");}function Ht({category:t,id:e,data:o}){$?.to(`${t}:${e}`).emit(t,o);}var Ne={init:Vt,broadcast:Ht};async function ze(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await L.findOne({domain:o})}var Je={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await L.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a.name==="MongoBulkWriteError"&&a.result?.nInserted;}}}};var re=Object.freeze({});function We(t){re=Object.freeze(Object.assign({},re,t));}function g(){return re}function Kt(){return typeof window!="object"}function R(){if(!Kt())throw new Error("This function can only be called on the server")}function V(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}function qe({name:t,email:e,verificationUrl:o}){return `
3
3
  <p>Hi${t?` ${t}`:""},</p>
4
4
  <p>Please verify your email address ${e} by clicking the link below:</p>
5
5
  <p><a href="${o}">${o}</a></p>
6
6
  <p>If you did not request this, please ignore this email.</p>
7
- `}async function qe(t){let e=process.env.MODELENCE_SITE_URL,o=f().emailVerifiedRedirectUrl||e||"/";try{let r=z$1.string().parse(t.query.token),n=await _.findOne({token:r,expiresAt:{$gt:new Date}});if(!n)throw new Error("Invalid or expired verification token");if(!await u.findOne({_id:n.userId}))throw new Error("User not found");let s=n.email;if(!s)throw new Error("Email not found in token");if((await u.updateOne({_id:n.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await u.findOne({_id:n.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await _.deleteOne({_id:n._id});}catch(r){if(r instanceof Error)return console.error("Error verifying email:",r),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(r.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function H({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(f().provider){let r=f().provider,n=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await _.insertOne({userId:t,email:e,token:n,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${n}`,l=(f()?.verification?.template||We)({name:"",email:e,verificationUrl:s}),h=V(l);await r?.sendEmail({to:e,from:f()?.from||"noreply@modelence.com",subject:f()?.verification?.subject||"Verify your email address",text:h,html:l});}}function K(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function I(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var ie=Object.freeze({});function Fe(t){ie=Object.freeze(Object.assign({},ie,t));}function y(){return ie}async function He(t,{user:e,session:o,connectionInfo:r}){try{if(!o)throw new Error("Session is not initialized");let n=r?.ip;n&&await R({bucket:"signin",type:"ip",value:n});let i=I(t.email),s=z$1.string().parse(t.password),a=await u.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw Ve();if(!a.emails?.find(d=>d.address===i)?.verified&&f()?.provider){if(n)try{await R({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await H({userId:a?._id,email:i,baseUrl:r?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await Zt.compare(s,l))throw Ve();return await _e(o.authToken,a._id),y().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(n){throw n instanceof Error&&y().login?.onError?.(n),n}}async function Ke(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await ke(o.authToken);}function Ve(){return new Error("Incorrect email/password combination")}async function Ge(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await u.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var N=new g("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var se=[];function Ze(t){if(se.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");se=t;}async function R(t){let{bucket:e,type:o,value:r}=t,n=se.filter(i=>i.bucket===e&&i.type===o);for(let i of n)await Yt(i,r);}async function Yt(t,e,o){let r=()=>new d(`Rate limit exceeded for ${t.bucket}`),n=await N.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=n?Xt(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw r();await N.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function Xt(t,e,o){let r=e-t.windowMs;if(t.windowStart.getTime()===e){let n=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===r){let n=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*n),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function Qe(t,{user:e,connectionInfo:o}){try{let r=I(t.email),n=K(t.password),i=o?.ip;if(i&&await R({bucket:"signupAttempt",type:"ip",value:i}),await Ne(r))throw new Error("Please use a permanent email address");let s=await u.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(s){let b=s.emails?.find(d=>d.address===r);throw new Error(`User with email already exists: ${b?.address}`)}i&&await R({bucket:"signup",type:"ip",value:i});let a=await Zt.hash(n,10),l=await u.insertOne({handle:r,emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:a}}}),h=await u.findOne({_id:l.insertedId},{readPreference:"primary"});if(!h)throw new Error("User not found");return await H({userId:l?.insertedId,email:r,baseUrl:o?.baseUrl}),y().signup?.onSuccess?.(h),l.insertedId}catch(r){throw r instanceof Error&&y().signup?.onError?.(r),r}}function no(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function io({email:t,resetUrl:e}){return `
7
+ `}async function Be(t){let e=process.env.MODELENCE_SITE_URL,o=g().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await _.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await m.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await m.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await m.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await _.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function H({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(g().provider){let n=g().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await _.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,l=(g()?.verification?.template||qe)({name:"",email:e,verificationUrl:s}),p=V(l);await n?.sendEmail({to:e,from:g()?.from||"noreply@modelence.com",subject:g()?.verification?.subject||"Verify your email address",text:p,html:l});}}function K(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function I(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var ie=Object.freeze({});function Ve(t){ie=Object.freeze(Object.assign({},ie,t));}function h(){return ie}async function Ke(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await D({bucket:"signin",type:"ip",value:r});let i=I(t.email),s=z$1.string().parse(t.password),a=await m.findOne({"emails.address":i},{collation:{locale:"en",strength:2}}),l=a?.authMethods?.password?.hash;if(!l)throw He();if(!a.emails?.find(d=>d.address===i)?.verified&&g()?.provider){if(r)try{await D({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await H({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await Qt.compare(s,l))throw He();return await ke(o.authToken,a._id),h().onAfterLogin?.({user:a,session:o,connectionInfo:n}),h().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(h().onLoginError?.({error:r,session:o,connectionInfo:n}),h().login?.onError?.(r)),r}}async function Ge(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await Ie(o.authToken);}function He(){return new Error("Incorrect email/password combination")}async function Ze(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var N=new w("_modelenceRateLimits",{schema:{bucket:c.string(),type:c.enum(["ip","user"]),value:c.string(),windowMs:c.number(),windowStart:c.date(),windowCount:c.number(),prevWindowCount:c.number(),expiresAt:c.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var se=[];function Qe(t){if(se.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");se=t;}async function D(t){let{bucket:e,type:o,value:n}=t,r=se.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await Xt(i,n);}async function Xt(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),r=await N.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:l}=r?eo(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await N.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},l);}function eo(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function Ye(t,{user:e,session:o,connectionInfo:n}){try{let r=I(t.email),i=K(t.password),s=n?.ip;if(s&&await D({bucket:"signupAttempt",type:"ip",value:s}),await ze(r))throw new Error("Please use a permanent email address");let a=await m.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let d=a.emails?.find(C=>C.address===r);throw new Error(`User with email already exists: ${d?.address}`)}s&&await D({bucket:"signup",type:"ip",value:s});let l=await Qt.hash(i,10),p=await m.insertOne({handle:r,emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:l}}}),b=await m.findOne({_id:p.insertedId},{readPreference:"primary"});if(!b)throw new Error("User not found");return await H({userId:p?.insertedId,email:r,baseUrl:n?.baseUrl}),h().onAfterSignup?.({user:b,session:o,connectionInfo:n}),h().signup?.onSuccess?.(b),p.insertedId}catch(r){throw r instanceof Error&&(h().onSignupError?.({error:r,session:o,connectionInfo:n}),h().signup?.onError?.(r)),r}}function io(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function so({email:t,resetUrl:e}){return `
8
8
  <p>Hi,</p>
9
9
  <p>We received a request to reset your password for ${t}.</p>
10
10
  <p>Click the link below to reset your password:</p>
11
11
  <p><a href="${e}">${e}</a></p>
12
12
  <p>This link will expire in 1 hour.</p>
13
13
  <p>If you did not request this password reset, please ignore this email.</p>
14
- `}var ae={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Ye(t,{connectionInfo:e}){let o=I(t.email),r=await u.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!r||!r.authMethods?.password)return ae;let n=f().provider;if(!n)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await x.insertOne({userId:r._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,h=`${no(a$1,f().passwordReset?.redirectUrl)}?token=${i}`,d=(f()?.passwordReset?.template||io)({email:o,resetUrl:h,name:""}),O=V(d);return await n.sendEmail({to:o,from:f()?.from||"noreply@modelence.com",subject:f()?.passwordReset?.subject||"Reset your password",text:O,html:d}),ae}async function Xe(t,{}){let e=z$1.string().parse(t.token),o=K(t.password),r=await x.findOne({token:e});if(!r)throw new Error("Invalid or expired reset token");if(r.expiresAt<new Date)throw await x.deleteOne({token:e}),new Error("Reset token has expired");let n=await u.findOne({_id:r.userId});if(!n)throw new Error("User not found");let i=await Zt.hash(o,10);return await u.updateOne({_id:n._id},{$set:{"authMethods.password.hash":i}}),await x.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var et=new w("_system.user",{stores:[u,L,_,x],queries:{getOwnProfile:Ge},mutations:{signupWithPassword:Qe,loginWithPassword:He,logout:Ke,sendResetPasswordToken:Ye,resetPassword:Xe},cronJobs:{updateDisposableEmailList:ze},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:qe}}]});async function tt({configSchema:t,cronJobsMetadata:e,stores:o}){let r=process.env.MODELENCE_CONTAINER_ID;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),i=await ce("/api/connect","POST",{hostname:so.hostname(),containerId:r,dataModels:n,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function ot(){return await ce("/api/configs","GET")}async function rt(){return await ce("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ce(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var le=false,ao=a.seconds(10);function nt(){setInterval(async()=>{if(!le){le=true;try{await rt();}catch(t){console.error("Error syncing status",t);}try{await co();}catch(t){console.error("Error syncing config",t);}le=false;}},ao);}async function co(){let{configs:t}=await ot();c$1(t);}var lo=a.minutes(1),mo=a.seconds(10),D={},de,z=new g("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional(),lock:c.object({containerId:c.string(),acquireDate:c.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function st(t,{description:e="",interval:o,timeout:r=lo,handler:n}){if(D[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(de)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(r>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);D[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function at(){if(de)throw new Error("Cron jobs already started");let t=Object.keys(D);if(t.length>0){let e={alias:{$in:t}},o=await z.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>z.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await uo(mo);let r=await z.fetch(e),n=Date.now();r.forEach(i=>{let s=D[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:n);}),Object.values(D).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=n);}),de=setInterval(po,a.seconds(1));}}function uo(t){return new Promise(e=>setTimeout(e,t))}async function po(){let t=Date.now();Object.values(D).forEach(async e=>{let{params:o,state:r}=e;if(r.isRunning){r.startTs&&r.startTs+o.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await fo(e);});}async function fo(t){let{alias:e,params:o,handler:r,state:n}=t;n.isRunning=true,n.startTs=Date.now();let i=j$1("cron",`cron:${e}`);r().then(()=>{it(n,o),i.end("success");}).catch(s=>{it(n,o),k$1(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await z.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});}function it(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function ct(){return Object.values(D).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var lt=new w("_system.cron",{stores:[z]});var me={};function ue(t,e){return v(),pt(t),G("query",t,e)}function dt(t,e){return v(),pt(t),G("mutation",t,e)}function mt(t,e){return v(),ft(t),G("query",t,e)}function ut(t,e){return v(),ft(t),G("mutation",t,e)}function pt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ft(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function G(t,e,o){if(v(),me[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof o=="function"?o:o.handler,n=typeof o=="function"?[]:o.permissions??[];me[e]={type:t,name:e,handler:r,permissions:n};}async function ht(t,e,o){v();let r=me[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:i}=r,s=j$1("method",`method:${t}`,{type:n,args:e}),a;try{je(o.roles,r.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var Z=new g("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function gt(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await Z.fetch({version:{$in:e}}),r=new Set(o.map(({version:i})=>i)),n=t.filter(({version:i})=>!r.has(i));if(n.length!==0){console.log(`Running migrations (${n.length})...`);for(let{version:i,description:s,handler:a}of n)console.log(`Running migration v${i}: ${s}`),await Z.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var wt=new w("_system.migration",{stores:[Z]});var yt=new w("_system.rateLimit",{stores:[N]});var fe=class{async init(){this.config=await Co(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(this.config),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[we.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(we.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(r){console.error("Error serving index.html:",r),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Eo(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}async function Co(){let t=process.cwd(),e=await Eo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>bo.existsSync(pe.join(t,n))),r=[yo(),So()];if(o){let n=(await import('vite-plugin-eslint')).default;r.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:pe.resolve(t,o)}));}return {plugins:r,root:t,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),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:{"@":pe.resolve(t,"src").replace(/\\/g,"/")}},publicDir:e.publicDir}}function So(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Et=new fe;async function Ct(t,e){let{authToken:o}=await re(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Ro(t,e){let o=t.user,r=await u.findOne({"authMethods.google.id":o.id});try{if(r){await Ct(e,r._id),y().login?.onSuccess?.(r);return}}catch(n){throw n instanceof Error&&y().login?.onError?.(n),n}try{let n=o.emails[0]&&o.emails[0]?.value;if(n||e.status(400).json({error:"Email address is required for Google authentication."}),await u.findOne({"emails.address":n},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await u.insertOne({handle:n,emails:[{address:n,verified:!0}],createdAt:new Date,authMethods:{google:{id:o.id}}});await Ct(e,s.insertedId);let a=await u.findOne({_id:s.insertedId},{readPreference:"primary"});a&&y().signup?.onSuccess?.(a);}catch(n){throw n instanceof Error&&y().signup?.onError?.(n),n}}function Do(){let t=Router(),e=!!a$1("_system.user.auth.google.enabled"),o=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret"));return !e||!o||!r||(he.use(new Strategy({clientID:o,clientSecret:r,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(n,i,s,a)=>a(null,s))),t.get("/api/_internal/auth/google",he.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",he.authenticate("google",{session:false}),Ro)),t}var St=Do;function xt(t){return async(e,o)=>{try{let r=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(r.status||200),r.redirect&&o.redirect(r.redirect),r.headers&&Object.entries(r.headers).forEach(([n,i])=>{o.setHeader(n,i);}),o.send(r.data);}catch(r){r instanceof a$3?o.status(r.status).send(r.message):(console.error(`Error in route handler: ${e.path}`),console.error(r),o.status(500).send(String(r)));}}}var ge=Object.freeze({});function vt(t){ge=Object.freeze(Object.assign({},ge,t));}function Q(){return ge}function _o(t,e){for(let o of e)for(let r of o.routes){let{path:n,handlers:i}=r;Object.entries(i).forEach(([s,a])=>{t[s](n,xt(a));});}}async function Rt(t,{combinedModules:e,channels:o}){let r=we();r.use(we.json()),r.use(we.urlencoded({extended:true})),r.use(Oo()),r.use(he.initialize()),r.use(St()),r.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:h}=a.params,b=await ko(a);try{let d=await ht(h,a.body.args,b);l.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${h}:`,d),d instanceof a$3)l.status(d.status).send(d.message);else if(d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let M=d.flatten(),Y=Object.entries(M.fieldErrors).map(([A,ee])=>`${A}: ${(ee??[]).join(", ")}`).join("; "),X=M.formErrors.join("; "),J=[Y,X].filter(Boolean).join("; ");l.status(400).send(J);}else l.status(500).send(d instanceof Error?d.message:String(d));}}),_o(r,e),await t.init(),t.middlewares&&r.use(t.middlewares()),r.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let n=Mo.createServer(r),i=Q()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{h("Application started",{source:"app"}),console.log(`
14
+ `}var ae={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Xe(t,{connectionInfo:e}){let o=I(t.email),n=await m.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return ae;let r=g().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=new Date(Date.now()+a.hours(1));await v.insertOne({userId:n._id,token:i,createdAt:new Date,expiresAt:s});let a$1=process.env.MODELENCE_SITE_URL||e?.baseUrl,p=`${io(a$1,g().passwordReset?.redirectUrl)}?token=${i}`,d=(g()?.passwordReset?.template||so)({email:o,resetUrl:p,name:""}),C=V(d);return await r.sendEmail({to:o,from:g()?.from||"noreply@modelence.com",subject:g()?.passwordReset?.subject||"Reset your password",text:C,html:d}),ae}async function et(t,{}){let e=z$1.string().parse(t.token),o=K(t.password),n=await v.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await v.deleteOne({token:e}),new Error("Reset token has expired");let r=await m.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await Qt.hash(o,10);return await m.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await v.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var tt=new y("_system.user",{stores:[m,L,_,v],queries:{getOwnProfile:Ze},mutations:{signupWithPassword:Ye,loginWithPassword:Ke,logout:Ge,sendResetPasswordToken:Xe,resetPassword:et},cronJobs:{updateDisposableEmailList:Je},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:Be}}]});async function ot({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),i=await ce("/api/connect","POST",{hostname:ao.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function nt(){return await ce("/api/configs","GET")}async function rt(){return await ce("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function ce(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var le=false,co=a.seconds(10);function it(){setInterval(async()=>{if(!le){le=true;try{await rt();}catch(t){console.error("Error syncing status",t);}try{await lo();}catch(t){console.error("Error syncing config",t);}le=false;}},co);}async function lo(){let{configs:t}=await nt();c$1(t);}var uo=a.minutes(1),mo=a.seconds(10),O={},de,z=new w("_modelenceCronJobs",{schema:{alias:c.string(),lastStartDate:c.date().optional(),lock:c.object({containerId:c.string(),acquireDate:c.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function at(t,{description:e="",interval:o,timeout:n=uo,handler:r}){if(O[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(de)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);O[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function ct(){if(de)throw new Error("Cron jobs already started");let t=Object.keys(O);if(t.length>0){let e={alias:{$in:t}},o=await z.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(i=>z.upsertOne({alias:i},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await po(mo);let n=await z.fetch(e),r=Date.now();n.forEach(i=>{let s=O[i.alias];s&&(s.state.scheduledRunTs=i.lastStartDate?i.lastStartDate.getTime()+s.params.interval:r);}),Object.values(O).forEach(i=>{i.state.scheduledRunTs||(i.state.scheduledRunTs=r);}),de=setInterval(fo,a.seconds(1));}}function po(t){return new Promise(e=>setTimeout(e,t))}async function fo(){let t=Date.now();Object.values(O).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await ho(e);});}async function ho(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now();let i=j$1("cron",`cron:${e}`);n().then(()=>{st(r,o),i.end("success");}).catch(s=>{st(r,o),k$1(s),i.end("error"),console.error(`Error in cron job '${e}':`,s);}),await z.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});}function st(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function lt(){return Object.values(O).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var dt=new y("_system.cron",{stores:[z]});var ue={};function me(t,e){return R(),ft(t),G("query",t,e)}function ut(t,e){return R(),ft(t),G("mutation",t,e)}function mt(t,e){return R(),ht(t),G("query",t,e)}function pt(t,e){return R(),ht(t),G("mutation",t,e)}function ft(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ht(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function G(t,e,o){if(R(),ue[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];ue[e]={type:t,name:e,handler:n,permissions:r};}async function gt(t,e,o){R();let n=ue[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=j$1("method",`method:${t}`,{type:r,args:e}),a;try{Ue(o.roles,n.permissions),a=await i(e,o);}catch(l){throw s.end("error"),l}return s.end(),a}var Z=new w("_modelenceMigrations",{schema:{version:c.number(),appliedAt:c.date()},indexes:[{key:{version:1},unique:true}]});async function wt(t){if(t.length===0)return;let e=t.map(({version:i})=>i),o=await Z.fetch({version:{$in:e}}),n=new Set(o.map(({version:i})=>i)),r=t.filter(({version:i})=>!n.has(i));if(r.length!==0){console.log(`Running migrations (${r.length})...`);for(let{version:i,description:s,handler:a}of r)console.log(`Running migration v${i}: ${s}`),await Z.insertOne({version:i,appliedAt:new Date}),await a(),console.log(`Migration v${i} complete`);}}var yt=new y("_system.migration",{stores:[Z]});var bt=new y("_system.rateLimit",{stores:[N]});var fe=class{async init(){this.config=await vo(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[ye.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(ye.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function So(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function xo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object")return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function vo(){let t=process.cwd(),e=await So(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Eo.existsSync(pe.join(t,i))),n=[Co(),Ro()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:pe.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":pe.resolve(t,"src").replace(/\\/g,"/")}}});return xo(r,e)}function Ro(){return {name:"modelence-asset-handler",async transform(t,e){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(e))return process.env.NODE_ENV==="development",t},async generateBundle(t,e){}}}var Et=new fe;async function St(t,e){let{authToken:o}=await ne(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Mo(t,e){let o=t.user,n=await m.findOne({"authMethods.google.id":o.id}),{session:r,connectionInfo:i}=await ge(t);try{if(n){await St(e,n._id),h().onAfterLogin?.({user:n,session:r,connectionInfo:i}),h().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(h().login?.onError?.(s),h().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{let s=o.emails[0]&&o.emails[0]?.value;if(s||e.status(400).json({error:"Email address is required for Google authentication."}),await m.findOne({"emails.address":s},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let l=await m.insertOne({handle:s,emails:[{address:s,verified:!0}],createdAt:new Date,authMethods:{google:{id:o.id}}});await St(e,l.insertedId);let p=await m.findOne({_id:l.insertedId},{readPreference:"primary"});p&&(h().onAfterSignup?.({user:p,session:r,connectionInfo:i}),h().signup?.onSuccess?.(p));}catch(s){throw s instanceof Error&&(h().onSignupError?.({error:s,session:r,connectionInfo:i}),h().signup?.onError?.(s)),s}}function To(){let t=Router(),e=!!a$1("_system.user.auth.google.enabled"),o=String(a$1("_system.user.auth.google.clientId")),n=String(a$1("_system.user.auth.google.clientSecret"));return !e||!o||!n||(he.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(r,i,s,a)=>a(null,s))),t.get("/api/_internal/auth/google",he.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",he.authenticate("google",{session:false}),Mo)),t}var xt=To;function vt(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.redirect&&o.redirect(n.redirect),n.headers&&Object.entries(n.headers).forEach(([r,i])=>{o.setHeader(r,i);}),o.send(n.data);}catch(n){n instanceof a$3?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var we=Object.freeze({});function Rt(t){we=Object.freeze(Object.assign({},we,t));}function Q(){return we}function Ao(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i}=n;Object.entries(i).forEach(([s,a])=>{t[s](r,vt(a));});}}async function Dt(t,{combinedModules:e,channels:o}){let n=ye();n.use(ye.json()),n.use(ye.urlencoded({extended:true})),n.use(_o()),n.use(he.initialize()),n.use(xt()),n.post("/api/_internal/method/:methodName(*)",async(a,l)=>{let{methodName:p}=a.params,b=await ge(a);try{let d=await gt(p,a.body.args,b);l.json({data:d,typeMap:a$2(d)});}catch(d){if(console.error(`Error in method ${p}:`,d),d instanceof a$3)l.status(d.status).send(d.message);else if(d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let M=d.flatten(),Y=Object.entries(M.fieldErrors).map(([A,ee])=>`${A}: ${(ee??[]).join(", ")}`).join("; "),X=M.formErrors.join("; "),J=[Y,X].filter(Boolean).join("; ");l.status(400).send(J);}else l.status(500).send(d instanceof Error?d.message:String(d));}}),Ao(n,e),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,l)=>t.handler(a,l)),process.on("unhandledRejection",(a,l)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",l);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=ko.createServer(n),i=Q()?.provider;i&&i.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{h$1("Application started",{source:"app"}),console.log(`
15
15
  Application started on http://localhost:${s}
16
- `);});}async function ko(t){let e=C.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=C.object({screenWidth:C.number(),screenHeight:C.number(),windowWidth:C.number(),windowHeight:C.number(),pixelRatio:C.number(),orientation:C.string().nullable()}).parse(t.body.clientInfo),r={ip:Io(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!$()){let{session:i,user:s,roles:a}=await j(e);return {clientInfo:o,connectionInfo:r,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:B()}}function Io(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function jo({modules:t=[],roles:e$1={},defaultRoles:o={},server:r=Et,migrations:n=[],email:i={},auth:s={},websocket:a={}}){Dt.config(),Dt.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,h=process.env.MODELENCE_CRON_ENABLED==="true";Ko().then(()=>{}).catch(()=>{});let b=[et,Ie,lt,wt,yt],d=[...b,...t];e(),Uo(b),$o(t),Pe(e$1,o);let O=Wo(d);d$1(O);let M=No(d),Y=zo(d);h&&qo(d);let X=Jo(d);if(Ze(X),l){let{configs:A,environmentId:ee,appAlias:Ot,environmentAlias:Mt,telemetry:Tt}=await tt({configSchema:O,cronJobsMetadata:h?ct():void 0,stores:M});c$1(A),f$1({environmentId:ee,appAlias:Ot,environmentAlias:Mt,telemetry:Tt});}else c$1(Ho(O));Je(i),Fe(s),vt({...a,provider:a.provider||Ue});let J=$();if(J&&(await $e(),Bo(M)),h&&await gt(n),J)for(let A of M)A.createIndexes();l&&(await g$1(),nt()),h&&at().catch(console.error),await Rt(r,{combinedModules:d,channels:Y});}function $o(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))ue(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))dt(`${e.name}.${o}`,r);}}function Uo(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))mt(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))ut(`${e.name}.${o}`,r);}}function No(t){return t.flatMap(e=>e.stores)}function zo(t){return t.flatMap(e=>e.channels)}function Jo(t){return t.flatMap(e=>e.rateLimits)}function Wo(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=n;}return e}function qo(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))st(`${e.name}.${o}`,r);}function Bo(t){let e=F();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Fo={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Vo(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Ho(t){let e=[];for(let[o,r]of Object.entries(Fo)){let n=process.env[o],i=t[r];if(n){let s=i?.type??"string";e.push({key:r,type:s,value:Vo(n,s)});}}return e}async function Ko(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await Go(),n=await import('./package-R4BMS5HW.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:so.hostname(),environmentId:o})});}}async function Go(){try{let t=pe.join(process.cwd(),"package.json"),e=await Ao.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var ye=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let r=Q().provider;if(!r){i("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:e,data:o});}};function Zo(t){if(!f().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email-configuration for more details.");return f().provider?.sendEmail(t)}
17
- export{w as Module,ye as ServerChannel,g as Store,j as authenticate,R as consumeRateLimit,ue as createQuery,u as dbUsers,c as schema,Zo as sendEmail,jo as startApp};//# sourceMappingURL=server.js.map
16
+ `);});}async function ge(t){let e=S.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=S.object({screenWidth:S.number(),screenHeight:S.number(),windowWidth:S.number(),windowHeight:S.number(),pixelRatio:S.number(),orientation:S.string().nullable()}).parse(t.body.clientInfo),n={ip:Po(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!U()){let{session:i,user:s,roles:a}=await j(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:B()}}function Po(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function $o({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Et,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Ot.config(),Ot.config({path:".modelence.env"});let l=!!process.env.MODELENCE_SERVICE_ENDPOINT,p=process.env.MODELENCE_CRON_ENABLED==="true";Zo().then(()=>{}).catch(()=>{});let b=[tt,Ae,dt,yt,bt],d=[...b,...t];e(),zo(b),No(t),Le(e$1,o);let C=Bo(d);d$1(C);let M=Jo(d),Y=Wo(d);p&&Fo(d);let X=qo(d);if(Qe(X),l){let{configs:A,environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t}=await ot({configSchema:C,cronJobsMetadata:p?lt():void 0,stores:M});c$1(A),f({environmentId:ee,appAlias:Mt,environmentAlias:Tt,telemetry:_t});}else c$1(Go(C));We(i),Ve(s),Rt({...a,provider:a.provider||Ne});let J=U();if(J&&(await $e(),Vo(M)),p&&await wt(r),J)for(let A of M)A.createIndexes();l&&(await g$1(),it()),p&&ct().catch(console.error),await Dt(n,{combinedModules:d,channels:Y});}function No(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))me(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ut(`${e.name}.${o}`,n);}}function zo(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))mt(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))pt(`${e.name}.${o}`,n);}}function Jo(t){return t.flatMap(e=>e.stores)}function Wo(t){return t.flatMap(e=>e.channels)}function qo(t){return t.flatMap(e=>e.rateLimits)}function Bo(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function Fo(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))at(`${e.name}.${o}`,n);}function Vo(t){let e=F();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var Ho={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function Ko(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Go(t){let e=[];for(let[o,n]of Object.entries(Ho)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:Ko(r,s)});}}return e}async function Zo(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Qo(),r=await import('./package-5ZEGPCTP.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:ao.hostname(),environmentId:o})});}}async function Qo(){try{let t=pe.join(process.cwd(),"package.json"),e=await Lo.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}var be=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=Q().provider;if(!n){i("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Yo(t){if(!g().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return g().provider?.sendEmail(t)}
17
+ export{y as Module,be as ServerChannel,w as Store,j as authenticate,D as consumeRateLimit,me as createQuery,m as dbUsers,c as schema,Yo as sendEmail,$o as startApp};//# sourceMappingURL=server.js.map
18
18
  //# sourceMappingURL=server.js.map