modelence 0.5.7 → 0.5.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/modelence.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import G,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import re from'archiver';import Q from'open';var
|
|
2
|
+
import {Command}from'commander';import {promises,createWriteStream,writeFileSync}from'fs';import G,{join}from'path';import {parse}from'dotenv';import {createInterface}from'readline';import O from'fs/promises';import {createJiti}from'jiti';import {z as z$1}from'zod';import {build}from'tsup';import {loadConfigFromFile,build as build$1,mergeConfig}from'vite';import {execSync}from'child_process';import re from'archiver';import Q from'open';var C=".modelence.env";async function I(e,o){let t=await fetch(`${o}/api/setup`,{method:"GET",headers:{"X-Modelence-Setup-Token":e}});if(!t.ok){let r=await t.text();throw new Error(r||`Request failed with status ${t.status}`)}return t.json()}async function F(){let e=createInterface({input:process.stdin,output:process.stdout});return new Promise(o=>{e.question(`Warning: ${C} already exists. Do you want to overwrite it? (y/N) `,t=>{e.close(),o(t.toLowerCase()==="y");});})}function L(e){return String(e).replace(/"/g,'\\"')}async function _(e){try{let o=e.replace(".env",".backup.env");await promises.copyFile(e,o),console.log(`Backup created at ${o}`);}catch(o){console.warn("Failed to create backup file:",o);}}async function x(e){try{let o=join(process.cwd(),C),t={};try{let a=await promises.readFile(o,"utf8");t=parse(a),await _(o),await F()||(console.log("Setup canceled"),process.exit(0));}catch{}console.log("Fetching service configuration...");let r=await I(e.token,e.host),i={...t,MODELENCE_CRON_ENABLED:"true",MODELENCE_TELEMETRY_ENABLED:"false",MODELENCE_ENVIRONMENT_ID:r.environmentId,MODELENCE_SERVICE_ENDPOINT:e.host,MODELENCE_SERVICE_TOKEN:r.serviceToken,MODELENCE_CONTAINER_ID:r.containerId},s=Object.entries(i).map(([a,n])=>`${a}="${L(n)}"`).join(`
|
|
3
3
|
`);await promises.writeFile(o,s.trim()+`
|
|
4
|
-
`),console.log(`Successfully configured ${
|
|
4
|
+
`),console.log(`Successfully configured ${C} file`);}catch(o){console.error(`Setup failed: ${o instanceof Error?o.message:"Unknown error"}`),process.exit(1);}}var w=null,b=null;function z(){if(!w)throw new Error("Environment variables not loaded");return w}function k(){if(!b)throw new Error("Configuration not loaded");return b}function d(e){return `${z().MODELENCE_SERVICE_ENDPOINT||"https://cloud.modelence.com"}${e}`}function h(){let{serverDir:e,serverEntry:o}=k();return join(e,o)}function S(){return k().postBuildCommand}function D(e){let o=N("build");return o}function u(e){return join(process.cwd(),e)}function N(e){let o=u(".modelence");return e?join(o,e):o}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");b=z$1.object({serverDir:z$1.string(),serverEntry:z$1.string(),postBuildCommand:z$1.string().optional()}).parse(t);}catch(e){throw console.error(e),new Error("Unable to load modelence.config.ts")}try{let e=await O.readFile(join(process.cwd(),".modelence.env"),"utf-8");w=parse(e);}catch(e){if(e.code==="ENOENT")w={};else throw e}}async function X(){let e=S();if(e){console.log("Running post-build command..."),execSync(e);return}await Y();}async function Y(){console.log("Building client with Vite...");let e=await loadConfigFromFile({command:"build",mode:process.env.NODE_ENV||"production"}),o={build:{outDir:G.resolve(process.cwd(),".modelence/build/client"),emptyOutDir:true}};await build$1(mergeConfig(e?.config||{},o,true));}async function H(){return console.log("Building server with tsup..."),new Promise((e,o)=>{build({entry:[h()],format:"esm",sourcemap:true,minify:process.env.NODE_ENV==="production",outDir:".modelence/build",clean:true,watch:false,bundle:true,treeshake:true,skipNodeModulesBundle:false,outExtension:({format:t})=>({js:".mjs"}),onSuccess:async()=>{e(void 0);}});})}async function v(){console.log("Building Modelence project...");try{let e=D();await O.rm(e,{recursive:!0,force:!0}),await H(),await X(),console.log("Build completed successfully!");}catch(e){throw console.error(e),new Error("Build failed")}try{await O.access(N());}catch{throw new Error("Could not find the .modelence directory. Looks like something went wrong during the build.")}}async function T(){let e=await fetch(d("/api/cli/auth"),{method:"POST"});if(!e.ok)throw new Error("Failed to create CLI authentication code");let{code:o,verificationUrl:t}=await e.json();console.log(`Please visit ${t} to authenticate`),console.log(`Code: ${o}`),await Q(t);let r=await oe(o);return writeFileSync(join(process.cwd(),".modelence","auth.json"),JSON.stringify({token:r})),{token:r}}async function oe(e){let r=Date.now()+6e5;for(;Date.now()<r;){try{let i=await te(e);if(i)return i}catch(i){console.error("Error polling for CLI token:",i);}await new Promise(i=>setTimeout(i,5e3));}throw new Error("Unable to authenticate CLI - timed out. Please try again.")}async function te(e){let o=await fetch(d(`/api/cli/token?code=${e}`),{method:"GET"});if(!o.ok)throw new Error(`CLI token polling failed: ${o.statusText}`);let{token:t}=await o.json();return t}async function B(e){let o=process.cwd(),t=join(o,".modelence"),r=join(t,"tmp","bundle.zip");await v(),await ie(r);let{token:i}=await T(),{bundleName:s}=await se(e.app,e.env,r,i);await promises.unlink(r),await ae(e.app,e.env,s,join(".modelence","build","app.mjs"),i);}async function ie(e){try{await promises.unlink(e),console.log("Removed existing bundle");}catch(n){if(n.code!=="ENOENT")throw n}console.log("Creating deployment bundle..."),await promises.mkdir(join(e,".."),{recursive:true});let o=createWriteStream(e),t=re("zip",{zlib:{level:9}});t.on("warning",n=>{if(n.code==="ENOENT")console.warn("Warning:",n);else throw n}),t.on("error",n=>{throw n});let r=new Promise((n,p)=>{o.on("close",n),o.on("error",p),t.on("error",p);});t.pipe(o);let i=["package.json","next.config.js","next.config.ts","modelence.config.ts"],s=["public","server",join(".modelence","build"),".next"];for(let n of i)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.file(u(n),{name:n});for(let n of s)await promises.access(u(n)).then(()=>true).catch(()=>false)&&t.directory(u(n),n);await t.finalize(),await r;let a=await promises.stat(e);console.log(`Deployment bundle created at: ${e} (${(a.size/1024/1024).toFixed(2)} MB)`);}async function se(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),p=await fetch(s,{method:"PUT",body:n,headers:{"Content-Type":"application/zip"}});if(!p.ok)throw new Error(`Failed to upload bundle: ${p.statusText}`);return console.log("Successfully uploaded bundle to Modelence Cloud"),console.log(`Bundle name: ${a}`),{bundleName:a}}async function ae(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 P(){console.log("Starting Modelence dev server...");let e=h(),o=G.resolve("./node_modules/.bin/tsx");execSync(`"${o}" watch "${e}"`,{stdio:"inherit",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 x(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 B(e);});f.command("dev").description("Start development server").action(async()=>{await E(),P();});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","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":";wbAKA,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,EAA8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B,WAAA,CAAY,2BAA2B,EACvC,cAAA,CAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,eAAe,iBAAA,CAAmB,mBAAmB,CAAA,CACrD,MAAA,CAAO,MAAOhF,CAAAA,EAAY,CACzB,MAAMuB,CAAAA,GACN,MAAM6B,CAAAA,CAAOpD,CAAO,EACtB,CAAC,CAAA,CAEHgF,CAAAA,CACG,OAAA,CAAQ,KAAK,EACb,WAAA,CAAY,0BAA0B,CAAA,CACtC,MAAA,CAAO,SAAY,CAClB,MAAMzD,CAAAA,EAAQ,CACdsD,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 return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n } else {\n throw error;\n }\n }\n}\n","import fs from 'fs/promises';\nimport { getBuildPath, getModelencePath, getPostBuildCommand, getServerPath } from './config';\nimport { build as tsupBuild } from 'tsup';\nimport { build as viteBuild, mergeConfig, loadConfigFromFile } from 'vite';\nimport path from 'path';\nimport { execSync } from 'child_process';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { 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 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","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":";wbAKA,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,IA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MzD,CAAAA,EAAQ,CACdsD,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 return join(serverDir, serverEntry);\n}\n\nexport function getPostBuildCommand() {\n return getConfig().postBuildCommand;\n}\n\nexport function getBuildPath(subPath?: string) {\n const buildDir = getModelencePath('build');\n return subPath ? join(buildDir, subPath) : buildDir;\n}\n\nexport function getProjectPath(subPath: string) {\n return join(process.cwd(), subPath);\n}\n\nexport function getModelencePath(subPath?: string) {\n const modelenceDir = getProjectPath('.modelence');\n return subPath ? join(modelenceDir, subPath) : modelenceDir;\n}\n\nexport async function loadEnv() {\n try {\n const configPath = join(process.cwd(), 'modelence.config.ts');\n\n const jiti = createJiti(import.meta.url, {\n interopDefault: true,\n requireCache: false\n });\n \n const configModule = await jiti.import(configPath);\n if (typeof configModule !== 'object') {\n throw new Error('modelence.config.ts should export an object');\n }\n config = z.object({\n serverDir: z.string(),\n serverEntry: z.string(),\n postBuildCommand: z.string().optional()\n }).parse(configModule);\n } catch (error) {\n console.error(error);\n throw new Error('Unable to load modelence.config.ts');\n }\n\n try {\n const envContent = await fs.readFile(join(process.cwd(), '.modelence.env'), 'utf-8');\n env = parseDotenv(envContent); \n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n // .modelence.env is optional, may not exist in case of an offline setup\n // 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';\n\nasync function buildClient() {\n const postBuildCommand = getPostBuildCommand();\n if (postBuildCommand) {\n console.log('Running post-build command...');\n execSync(postBuildCommand);\n return;\n }\n\n await buildVite();\n}\n\nasync function buildVite() {\n console.log('Building client with Vite...');\n\n const userConfig = await loadConfigFromFile({\n command: 'build',\n mode: process.env.NODE_ENV || 'production',\n });\n\n const modelenceConfig = {\n build: {\n outDir: path.resolve(process.cwd(), '.modelence/build/client'),\n emptyOutDir: true\n }\n };\n\n await viteBuild(mergeConfig(\n userConfig?.config || {},\n modelenceConfig,\n true\n ));\n}\n\nasync function buildServer() {\n console.log('Building server with tsup...');\n return new Promise((resolve, reject) => {\n tsupBuild({\n entry: [getServerPath()],\n format: 'esm',\n sourcemap: true,\n minify: process.env.NODE_ENV === 'production',\n outDir: '.modelence/build',\n clean: true,\n watch: false,\n bundle: true,\n treeshake: true,\n skipNodeModulesBundle: false,\n outExtension: ({ format }) => ({\n js: '.mjs'\n }),\n onSuccess: async () => { resolve(undefined); }\n });\n });\n}\n\nexport async function build() {\n console.log('Building Modelence project...');\n\n try {\n const buildDir = getBuildPath();\n await fs.rm(buildDir, { recursive: true, force: true });\n \n await buildServer();\n await buildClient();\n\n console.log('Build completed successfully!');\n } catch (error) {\n console.error(error);\n throw new Error('Build failed');\n }\n\n\n try {\n await fs.access(getModelencePath());\n } catch (error) {\n throw new Error('Could not find the .modelence directory. Looks like something went wrong during the build.');\n }\n}\n","import { getStudioUrl } from './config';\nimport open from 'open';\nimport { writeFileSync } from 'fs';\nimport { join } from 'path';\n\nexport async function authenticateCli() {\n // TODO: check if a token already exists in .modelence/auth.json\n\n const response = await fetch(getStudioUrl('/api/cli/auth'), {\n method: 'POST',\n });\n\n if (!response.ok) {\n throw new Error('Failed to create CLI authentication code');\n }\n\n const { code, verificationUrl } = await response.json();\n\n console.log(`Please visit ${verificationUrl} to authenticate`);\n console.log(`Code: ${code}`);\n \n await open(verificationUrl);\n\n const token = await waitForAuth(code);\n\n writeFileSync(join(process.cwd(), '.modelence', 'auth.json'), JSON.stringify({ token }));\n\n return { token };\n}\n\nasync function waitForAuth(code: string): Promise<string> {\n const pollInterval = 5 * 1000; // 5 seconds\n const pollTimeout = 10 * 60 * 1000; // 10 minutes\n const pollExpireTs = Date.now() + pollTimeout;\n while (Date.now() < pollExpireTs) {\n try {\n const token = await pollForToken(code);\n if (token) {\n return token;\n }\n } catch (error) {\n console.error('Error polling for CLI token:', error);\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval));\n }\n\n throw new Error('Unable to authenticate CLI - timed out. Please try again.');\n}\n\nasync function pollForToken(code: string) {\n const response = await fetch(getStudioUrl(`/api/cli/token?code=${code}`), {\n method: 'GET',\n });\n\n if (!response.ok) {\n throw new Error(`CLI token polling failed: ${response.statusText}`);\n }\n\n const { token } = await response.json();\n return token;\n}\n","import { createWriteStream, promises as fs } from 'fs';\nimport { join } from 'path';\nimport archiver from 'archiver';\nimport { authenticateCli } from './auth';\nimport { getStudioUrl, getBuildPath, getProjectPath } from './config';\nimport { build } from './build';\n\nexport async function deploy(options: { 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 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,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",o="0.5.
|
|
2
|
-
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-
|
|
3
|
-
//# sourceMappingURL=package-
|
|
1
|
+
var s="module",i="modelence",o="0.5.8",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"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/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","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0"},v={"@modelence/types":"^1.0.3","@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",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:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-LGK45VVZ.js.map
|
|
3
|
+
//# sourceMappingURL=package-LGK45VVZ.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,mBACZ,aAAA,CAAe,qBAAA,CACf,YAAa,iBACf,CAAA,CACAC,EAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,EACAC,CAAAA,CAAW,CACT,MAAS,MAAA,CACT,GAAA,CAAO,eACP,cAAA,CAAkB,eAAA,CAClB,KAAQ,2CAAA,CACR,WAAA,CAAe,6BACjB,CAAA,CACAC,CAAAA,CAAc,CACZ,IAAA,CAAQ,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WAAA,CACVC,CAAAA,CAAW,yBACXC,CAAAA,CAAQ,CACN,IAAO,+CACT,CAAA,CACAC,EAAY,uBAAA,CACZC,CAAAA,CAAmB,CACjB,iBAAA,CAAmB,QAAA,CACnB,gBAAiB,QAAA,CACjB,sBAAA,CAAwB,SACxB,gBAAA,CAAkB,QAAA,CAClB,kBAAmB,SAAA,CACnB,aAAA,CAAe,UACf,gCAAA,CAAkC,SAAA,CAClC,eAAgB,SAAA,CAChB,kBAAA,CAAoB,UACpB,kCAAA,CAAoC,SAAA,CACpC,4BAA6B,SAAA,CAC7B,KAAA,CAAS,SAAA,CACT,WAAA,CAAa,SACf,CAAA,CACAC,EAAgB,CACd,kBAAA,CAAoB,SACpB,sBAAA,CAAwB,QAAA,CACxB,SAAY,QAAA,CACZ,MAAA,CAAU,SACV,SAAA,CAAa,SAAA,CACb,gBAAiB,QAAA,CACjB,MAAA,CAAU,UACV,kBAAA,CAAoB,QAAA,CACpB,QAAW,SAAA,CACX,UAAA,CAAY,UACZ,IAAA,CAAQ,QAAA,CACR,QAAW,QAAA,CACX,IAAA,CAAQ,UACR,QAAA,CAAY,QAAA,CACZ,0BAA2B,QAAA,CAC3B,IAAA,CAAQ,SACR,GAAA,CAAO,SAAA,CACP,WAAc,QAAA,CACd,IAAA,CAAQ,SACR,oBAAA,CAAsB,QAAA,CACtB,QAAW,SAAA,CACX,uBAAA,CAAyB,UACzB,GAAA,CAAO,SAAA,CACP,QAAW,QACb,CAAA,CACAC,EAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,EAlFFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAeA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-LGK45VVZ.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.8\",\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 },\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 \"@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 \"@modelence/types\": \"^1.0.3\",\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 \"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"]}
|
package/dist/server.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d as d$1,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$2,c,f as f$1,g as g$1,a as a$2,h as h$1,j,k}from'./chunk-2ZGVP5SA.js';export{a as getConfig}from'./chunk-2ZGVP5SA.js';import et from'dotenv';import Ft from'fs/promises';import gt from'os';import Z from'path';import {randomBytes}from'crypto';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import y,{z as z$1}from'zod';import dt from'bcrypt';import {createServer,defineConfig}from'vite';import Ot from'@vitejs/plugin-react';import Tt from'fs';import X,{Router}from'express';import Y from'passport';import {Strategy}from'passport-google-oauth20';import $t from'cookie-parser';import Ut from'http';var le=new Map,S={authenticated:null,unauthenticated:null};function ue(t,e){S.authenticated=e.authenticated,S.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))le.set(o,n);}function L(){return S.unauthenticated?[S.unauthenticated]:[]}function me(){return S.authenticated?[S.authenticated]:[]}function de(t,e){let o=e.find(n=>!ot(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function ot(t,e){for(let o of t){let n=le.get(o);if(n&&n.permissions.includes(e))return true}return false}var h=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:p=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=p;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}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 i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}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 nt=z$1.string.bind(z$1),rt=z$1.number.bind(z$1),it=z$1.date.bind(z$1),st=z$1.boolean.bind(z$1),at=z$1.array.bind(z$1),ct=z$1.object.bind(z$1),lt=z$1.enum.bind(z$1),a={string:nt,number:rt,date:it,boolean:st,array:at,object:ct,enum:lt,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 M=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function pe(t){let e=t?await M.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await B()}async function fe(t,e){await M.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await M.updateOne({authToken:t},{$set:{userId:null}});}async function B(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a$1.days(7));return await M.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function mt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await M.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new h("_system.session",{stores:[M],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await mt(e);}}});var d=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),D=new f("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function ye(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await D.findOne({domain:o})}var we={interval:a$1.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
2
|
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await D.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};async function Ce(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),i=z$1.string().parse(t.password),r=await d.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await dt.compare(i,s))throw Ee();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Se(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function Ee(){return new Error("Incorrect email/password combination")}async function Me(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await d.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var _=new f("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var z=[];function xe(t){if(z.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");z=t;}async function F(t){let{bucket:e,type:o,value:n}=t,i=z.filter(r=>r.bucket===e&&r.type===o);for(let r of i)await pt(r,n);}async function pt(t,e,o){let n=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),i=await _.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:p}=i?ft(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await _.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},p);}function ft(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*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 i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),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 De(t,{user:e,connectionInfo:o}){let n=z$1.string().email().parse(t.email),i=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password);if(await ye(n))throw new Error("Please use a permanent email address");let r=await d.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(r){let l=r.emails?.find(C=>C.address===n);throw new Error(`User with email already exists: ${l?.address}`)}let s=o?.ip;s&&await F({bucket:"signup",type:"ip",value:s});let c=await dt.hash(i,10);return (await d.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}})).insertedId}var _e=new h("_system.user",{stores:[d,D],queries:{getOwnProfile:Me},mutations:{signupWithPassword:De,loginWithPassword:Ce,logout:Se},cronJobs:{updateDisposableEmailList:we},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200}],configSchema:{"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:""}}});async function Oe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await W("/api/connect","POST",{hostname:gt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Te(){return await W("/api/configs","GET")}async function Ie(){return await W("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function W(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var H=false,yt=a$1.seconds(10);function ve(){setInterval(async()=>{if(!H){H=true;try{await Ie();}catch(t){console.error("Error syncing status",t);}try{await wt();}catch(t){console.error("Error syncing config",t);}H=false;}},yt);}async function wt(){let{configs:t}=await Te();c(t);}var bt=a$1.minutes(1),Et=a$1.seconds(10),b={},K,O=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function ke(t,{description:e="",interval:o,timeout:n=bt,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(K)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function Le(){if(K)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await O.findOne({...e,"lock.containerId":{$exists:true}});await Promise.all(t.map(r=>O.upsertOne({alias:r},{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}))),o&&await Ct(Et);let n=await O.fetch(e),i=Date.now();n.forEach(r=>{let s=b[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),K=setInterval(St,a$1.seconds(1));}}function Ct(t){return new Promise(e=>setTimeout(e,t))}async function St(){let t=Date.now();Object.values(b).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 Mt(e);});}async function Mt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Ae(i,o),r.end("success");}).catch(s=>{Ae(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await O.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function Ae(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Pe(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ne=new h("_system.cron",{stores:[O]});var g=null;async function je(){if(g)return g;let t=T();if(!t)throw new Error("MongoDB URI is not set");g=new MongoClient(t,{maxPoolSize:20});try{return await g.connect(),await g.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),g}catch(e){throw console.error(e),g=null,e}}function T(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function $e(){return g}function Rt(){return typeof window!="object"}function E(){if(!Rt())throw new Error("This function can only be called on the server")}var G={};function V(t,e){return E(),Be(t),P("query",t,e)}function Ue(t,e){return E(),Be(t),P("mutation",t,e)}function Je(t,e){return E(),ze(t),P("query",t,e)}function qe(t,e){return E(),ze(t),P("mutation",t,e)}function Be(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ze(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function P(t,e,o){if(E(),G[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];G[e]={type:t,name:e,handler:n,permissions:i};}async function Fe(t,e,o){E();let n=G[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j("method",`method:${t}`,{type:i,args:e}),c;try{de(o.roles,n.permissions),c=await r(e,o);}catch(p){throw s.end("error"),p}return s.end(),c}var N=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function We(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await N.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),i=t.filter(({version:r})=>!n.has(r));if(i.length!==0){console.log(`Running migrations (${i.length})...`);for(let{version:r,description:s,handler:c}of i)console.log(`Running migration v${r}: ${s}`),await N.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var He=new h("_system.migration",{stores:[N]});var Ke=new h("_system.rateLimit",{stores:[_]});var Q=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await vt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[X.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function vt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Tt.existsSync(Z.join(t,n))),o=[Ot(),At()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Z.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":Z.resolve(t,"src")}}}}function At(){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 Ge=new Q;async function Ve(t,e){let{authToken:o}=await B(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Pt(t,e){let o=t.user,n=await d.findOne({"authMethods.google.id":o.id});if(n){await Ve(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await d.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await d.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await Ve(e,s.insertedId);}function Nt(){let t=Router(),e=!!a$2("_system.user.auth.google.enabled"),o=String(a$2("_system.user.auth.google.clientId")),n=String(a$2("_system.user.auth.google.clientSecret"));return !e||!o||!n||(Y.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback",proxy:true},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",Y.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",Y.authenticate("google",{session:false}),Pt)),t}var Ze=Nt;function Qe(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function Ye(t){let e=await pe(t),o=e.userId?await d.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?me():L();return {user:n,session:e,roles:i}}function qt(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,Qe(c));});}}async function Xe(t,{combinedModules:e}){let o=X();o.use(X.json()),o.use(X.urlencoded({extended:true})),o.use($t()),o.use(Y.initialize()),o.use(Ze()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,p=await Bt(r);try{let l=await Fe(c,r.body.args,p);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let I=l.flatten(),v=Object.entries(I.fieldErrors).map(([$,U])=>`${$}: ${(U??[]).join(", ")}`).join("; "),x=I.formErrors.join("; "),j=[v,x].filter(Boolean).join("; ");s.status(400).send(j);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),qt(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=Ut.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`
|
|
3
3
|
Application started on http://localhost:${i}
|
|
4
|
-
`);});}async function Bt(t){let e=y.string().nullish().transform(r=>r??null).parse(t.cookies.authToken||t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:zt(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!T()){let{session:r,user:s,roles:c}=await Ye(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:L()}}function zt(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 Kt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ge,migrations:i=[]}){et.config(),et.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";ro().then(()=>{}).catch(()=>{});let c$1=[_e,ge,Ne,He,Ke],p=[...c$1,...t];e(),Vt(c$1),Gt(t),ue(e$1,o);let l=Yt(p);d$2(l);let C=Zt(p);s&&Xt(p);let I=Qt(p);if(xe(I),r){let{configs:x,environmentId:j,appAlias:$,environmentAlias:U,telemetry:tt}=await Oe({configSchema:l,cronJobsMetadata:s?Pe():void 0,stores:C});c(x),f$1({environmentId:j,appAlias:$,environmentAlias:U,telemetry:tt});}else c(no(l));let v=T();if(v&&(await je(),eo(C)),s&&await We(i),v)for(let x of C)x.createIndexes();r&&(await g$1(),ve()),s&&Le().catch(console.error),await Xe(n,{combinedModules:p});}function Gt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))V(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ue(`${e.name}.${o}`,n);}}function Vt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Je(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))qe(`${e.name}.${o}`,n);}}function Zt(t){return t.flatMap(e=>e.stores)}function Qt(t){return t.flatMap(e=>e.rateLimits)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))ke(`${e.name}.${o}`,n);}function eo(t){let e=$e();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var to={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 oo(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 no(t){let e=[];for(let[o,n]of Object.entries(to)){let i=process.env[o],r=t[n];if(i){let s=r?.type??"string";e.push({key:n,type:s,value:oo(i,s)});}}return e}async function ro(){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 io(),i=await import('./package-
|
|
4
|
+
`);});}async function Bt(t){let e=y.string().nullish().transform(r=>r??null).parse(t.cookies.authToken||t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:zt(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!T()){let{session:r,user:s,roles:c}=await Ye(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:L()}}function zt(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 Kt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ge,migrations:i=[]}){et.config(),et.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";ro().then(()=>{}).catch(()=>{});let c$1=[_e,ge,Ne,He,Ke],p=[...c$1,...t];e(),Vt(c$1),Gt(t),ue(e$1,o);let l=Yt(p);d$2(l);let C=Zt(p);s&&Xt(p);let I=Qt(p);if(xe(I),r){let{configs:x,environmentId:j,appAlias:$,environmentAlias:U,telemetry:tt}=await Oe({configSchema:l,cronJobsMetadata:s?Pe():void 0,stores:C});c(x),f$1({environmentId:j,appAlias:$,environmentAlias:U,telemetry:tt});}else c(no(l));let v=T();if(v&&(await je(),eo(C)),s&&await We(i),v)for(let x of C)x.createIndexes();r&&(await g$1(),ve()),s&&Le().catch(console.error),await Xe(n,{combinedModules:p});}function Gt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))V(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ue(`${e.name}.${o}`,n);}}function Vt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Je(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))qe(`${e.name}.${o}`,n);}}function Zt(t){return t.flatMap(e=>e.stores)}function Qt(t){return t.flatMap(e=>e.rateLimits)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))ke(`${e.name}.${o}`,n);}function eo(t){let e=$e();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var to={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 oo(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 no(t){let e=[];for(let[o,n]of Object.entries(to)){let i=process.env[o],r=t[n];if(i){let s=r?.type??"string";e.push({key:n,type:s,value:oo(i,s)});}}return e}async function ro(){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 io(),i=await import('./package-LGK45VVZ.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:i.default.version,localHostname:gt.hostname(),environmentId:o})});}}async function io(){try{let t=Z.join(process.cwd(),"package.json"),e=await Ft.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}
|
|
5
5
|
export{h as Module,f as Store,F as consumeRateLimit,V as createQuery,d as dbUsers,a as schema,Kt as startApp};//# sourceMappingURL=server.js.map
|
|
6
6
|
//# sourceMappingURL=server.js.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"type": "module",
|
|
3
3
|
"name": "modelence",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.8",
|
|
5
5
|
"description": "The Node.js Framework for Real-Time MongoDB Apps",
|
|
6
6
|
"main": "dist/index.js",
|
|
7
7
|
"types": "dist/global.d.ts",
|
|
@@ -49,8 +49,7 @@
|
|
|
49
49
|
"@typescript-eslint/eslint-plugin": "^8.17.0",
|
|
50
50
|
"@typescript-eslint/parser": "^8.17.0",
|
|
51
51
|
"react": "^19.0.0",
|
|
52
|
-
"react-dom": "^19.0.0"
|
|
53
|
-
"typescript": "^5.7.2"
|
|
52
|
+
"react-dom": "^19.0.0"
|
|
54
53
|
},
|
|
55
54
|
"dependencies": {
|
|
56
55
|
"@modelence/types": "^1.0.3",
|
|
@@ -70,6 +69,7 @@
|
|
|
70
69
|
"passport-google-oauth20": "^2.0.0",
|
|
71
70
|
"tsup": "^8.3.6",
|
|
72
71
|
"tsx": "^4.19.3",
|
|
72
|
+
"typescript": "^5.7.2",
|
|
73
73
|
"vite": "^6.0.3",
|
|
74
74
|
"vite-plugin-eslint": "^1.8.1",
|
|
75
75
|
"winston": "^3.15.0",
|
|
@@ -1 +0,0 @@
|
|
|
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,mBACZ,aAAA,CAAe,qBAAA,CACf,YAAa,iBACf,CAAA,CACAC,EAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,EACAC,CA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AAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAgBA,YAAA,CAAAC,CAAAA,CAyBA,gBAAA,CAAAC,CAIF","file":"package-JKGQ7GU7.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.7\",\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 },\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 \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@modelence/types\": \"^1.0.3\",\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 \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|