modelence 0.5.2 → 0.5.3-dev.0

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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  <div align="center">
2
2
  <a href="https://modelence.com">
3
3
  <picture>
4
- <source media="(prefers-color-scheme: dark)" srcset="/packages/modelence/static/modelence.png">
5
- <img alt="Modelence logo" src="/packages/modelence/static/modelence.png" height="128">
4
+ <source media="(prefers-color-scheme: dark)" srcset="/packages/modelence/static/modelence.png" />
5
+ <img alt="Modelence logo" src="/packages/modelence/static/modelence.png" height="128" />
6
6
  </picture>
7
7
  </a>
8
8
  <h1>Modelence</h1>
@@ -10,7 +10,7 @@
10
10
  [Documentation](https://docs.modelence.com) | [API Reference](https://docs.modelence.com/api-reference/intro)
11
11
 
12
12
  ![Build Status](https://github.com/modelence/modelence/actions/workflows/build.yml/badge.svg)
13
- <a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg"></a>
13
+ <a href="https://www.npmjs.com/package/modelence"><img alt="NPM version" src="https://img.shields.io/npm/v/modelence.svg" /></a>
14
14
  </div>
15
15
 
16
16
  ## Getting Started
@@ -1,3 +1,3 @@
1
1
  import _ from'elastic-apm-node';import y from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import l from'process';var g={},u={},v=false;function f(t){return u[t]?.value}function W(){if(!v)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(u).filter(([t])=>g[t]?.isPublic))}function R(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!g[e]||(u[e]={key:e,type:o,value:n});}),v=true;}function D(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:r}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(n==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),g=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function L({elasticCloudId:t,elasticApiKey:e}){let o=l.stdout.write,n=l.stderr.write;l.stdout.write=function(r,...c){return b(r.toString(),i.stdout),o.call(l.stdout,r,...c)},l.stderr.write=function(r,...c){return b(r.toString(),i.stderr),n.call(l.stderr,r,...c)},x();}function b(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let r=e[e.length-1];r.timestamp||(r.timestamp=o,r.sequenceId=z++),t[n]===`
2
- `?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function B(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{m(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{d(o,{timestamp:n,source:"console",sequenceId:r});});}function x(){setTimeout(()=>{B(),x();},1e3);}var s=null;function J(){}function Q(t){s=Object.assign({},s,t);}function S(){return s?.environmentId}function I(){return s?.appAlias}function T(){return s?.environmentAlias}function K(){return s?.telemetry?.serviceName}function a(){return !!s?.telemetry?.isEnabled}var M=false,p=null,E=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,a()&&await O();};async function O(){let t=f("_system.elastic.apmEndpoint"),e=f("_system.elastic.cloudId"),o=f("_system.elastic.apiKey"),n=I()??"unknown",r=T()??"unknown",c=S()??"unknown",C=K();p=_.start({serviceName:C,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:c,appAlias:n,environmentAlias:r}});let h=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});h.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),E=y.createLogger({level:"debug",defaultMeta:{serviceName:C},format:y.format.combine(y.format.json()),transports:[h]}),L({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function w(){if(!E)throw new Error("Logger is not initialized");return E}function m(t,e){a()&&w().info(t,e);}function d(t,e){a()&&w().error(t,e);}function q(t,e,o){if(!a())return {end:()=>{}};let n=A(),r=n.startTransaction(e,t);return o&&n.setCustomContext(o),r}function U(t){if(!a()){console.error(t);return}A().captureError(t);}export{f as a,W as b,R as c,D as d,J as e,Q as f,rt as g,m as h,d as i,q as j,U as k};//# sourceMappingURL=chunk-QN73CYII.js.map
3
- //# sourceMappingURL=chunk-QN73CYII.js.map
2
+ `?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function B(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{m(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{d(o,{timestamp:n,source:"console",sequenceId:r});});}function x(){setTimeout(()=>{B(),x();},1e3);}var s=null;function J(){}function Q(t){s=Object.assign({},s,t);}function S(){return s?.environmentId}function I(){return s?.appAlias}function T(){return s?.environmentAlias}function K(){return s?.telemetry?.serviceName}function a(){return !!s?.telemetry?.isEnabled}var M=false,p=null,E=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,a()&&await O();};async function O(){let t=f("_system.elastic.apmEndpoint"),e=f("_system.elastic.cloudId"),o=f("_system.elastic.apiKey"),n=I()??"unknown",r=T()??"unknown",c=S()??"unknown",C=K();p=_.start({serviceName:C,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:c,appAlias:n,environmentAlias:r}});let h=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});h.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),E=y.createLogger({level:"debug",defaultMeta:{serviceName:C},format:y.format.combine(y.format.json()),transports:[h]}),L({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function w(){if(!E)throw new Error("Logger is not initialized");return E}function m(t,e){a()&&w().info(t,e);}function d(t,e){a()&&w().error(t,e);}function q(t,e,o){if(!a())return {end:()=>{}};let n=A(),r=n.startTransaction(e,t);return o&&n.setCustomContext(o),r}function U(t){if(!a()){console.error(t);return}A().captureError(t);}export{f as a,W as b,R as c,D as d,J as e,Q as f,rt as g,m as h,d as i,q as j,U as k};//# sourceMappingURL=chunk-F5MTZMFH.js.map
3
+ //# sourceMappingURL=chunk-F5MTZMFH.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","appStarted","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAgB,CAAA,KAAA,CAQb,SAASC,CAAAA,CAAUC,CAAgB,CA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ACd,CACH,CAAA,MAAM,IAAI,KAAA,CAAM,wBAAwB,CAE1C,CAAA,OAAOA,CACT,CAEO,SAASe,CAAAA,EAAY,CAC1B,GAAI,CAACd,CAAAA,CACH,MAAM,IAAI,KAAM,CAAA,2BAA2B,EAE7C,OAAOA,CACT,CCzGO,SAASb,CAAQ4B,CAAAA,CAAAA,CAAiBtC,EAAc,CACjDqB,CAAAA,EACFgB,EAAAA,CAAAA,EAAY,CAAA,IAAA,CAAKC,EAAStC,CAAI,EAElC,CAEO,SAASW,CAAS2B,CAAAA,CAAAA,CAAiBtC,CAAc,CAAA,CAClDqB,CAAmB,EAAA,EACrBgB,CAAU,EAAA,CAAE,KAAMC,CAAAA,CAAAA,CAAStC,CAAI,EAEnC,CAEO,SAASuC,CAAAA,CAAiBrD,CAA2CsD,CAAAA,CAAAA,CAAcC,EAA+B,CACvH,GAAI,CAACpB,CAAAA,EACH,CAAA,OAAO,CACL,GAAK,CAAA,IAAM,EAGb,CAGF,CAAA,IAAMC,CAAMc,CAAAA,CAAAA,EACNM,CAAAA,CAAAA,CAAcpB,CAAI,CAAA,gBAAA,CAAiBkB,CAAMtD,CAAAA,CAAI,EACnD,OAAIuD,CAAAA,EACFnB,CAAI,CAAA,gBAAA,CAAiBmB,CAAO,CAAA,CAEvBC,CACT,CAEO,SAASC,CAAAA,CAAaT,CAAc,CAAA,CACzC,GAAI,CAACb,GAAsB,CAAA,CACzB,OAAQ,CAAA,KAAA,CAAMa,CAAK,CAAA,CACnB,MACF,CAEAE,CAAO,EAAA,CAAE,YAAaF,CAAAA,CAAK,EAC7B","file":"chunk-F5MTZMFH.js","sourcesContent":["import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n * \n * @param key\n * @returns \n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport { getAppAlias, getEnvironmentAlias, getEnvironmentId, getTelemetryServiceName, isTelemetryEnabled } from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false\n }\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\n\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\nexport function startTransaction(type: 'method' | 'cron' | 'ai' | 'custom', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -1,6 +1,12 @@
1
1
  import { a as ConfigKey } from './types-B7qvJJOF.js';
2
2
  import React from 'react';
3
3
 
4
+ /**
5
+ * @sidebarTitle getConfig (client)
6
+ *
7
+ * @param key
8
+ * @returns
9
+ */
4
10
  declare function getConfig(key: ConfigKey): string | number | boolean;
5
11
 
6
12
  type ErrorHandler = (error: Error, methodName: string) => void;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"oPAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAc,CAAA,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAW,EAAI,IACjD,CAAA,MAASC,CAAG,CAAA,CACV,OAAQ,OAAA,CAAA,KAAA,CAAM,yCAA2CA,CAAAA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,EAAuBC,CAAiB,CAAA,CACtD,YAAa,CAAA,OAAA,CAAQ,oBAAqB,IAAK,CAAA,SAAA,CAAUA,CAAO,CAAC,EACnE,CCVA,IAAIC,CAAAA,CAA6B,CAACC,CAAOC,CAAAA,CAAAA,GAAe,CACtD,MAAM,IAAI,KAAM,CAAA,CAAA,sBAAA,EAAyBA,CAAU,CAAA,GAAA,EAAMD,EAAM,QAAS,EAAC,CAAE,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,CACtCwB,EAAe,IAAI,EACrB,CClBO,IAAMG,EAAc,WAAea,GAAAA,CAAAA,CAEtCA,CAAM,CAAA,SAAA,CAAUb,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport async function callMethod<T = unknown>(methodName: string, args: MethodArgs = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: UserInfo }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout, type UserInfo } from './auth/client';\n"]}
1
+ {"version":3,"sources":["../src/client/localStorage.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/auth/client/index.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","errorHandler","error","methodName","setErrorHandler","handler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","user","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","initSession","parsedUser","z","loopSessionHeartbeat","setCurrentUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","signupWithPassword","email","password","loginWithPassword","logout"],"mappings":"oPAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAc,CAAA,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAc,CAAA,IAAA,CAAK,KAAMA,CAAAA,CAAW,EAAI,IACjD,CAAA,MAASC,CAAG,CAAA,CACV,OAAQ,OAAA,CAAA,KAAA,CAAM,yCAA2CA,CAAAA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,EAAuBC,CAAiB,C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M,CAAE,IAAA,CAAA7B,CAAK,CAAA,CAAI,MAAMhB,CAAAA,CAA+B,gCAAkC,CAAA,CAAE,MAAA4C,CAAO,CAAA,QAAA,CAAAC,CAAS,CAAC,EAC3G,OAAArB,CAAAA,CAAeR,CAAI,CAAA,CACZA,CACT,CAEA,eAAsB+B,CAAS,EAAA,CAC7B,MAAM/C,CAAAA,CAAW,qBAAqB,CAAA,CACtCwB,EAAe,IAAI,EACrB,CClBO,IAAMG,EAAc,WAAea,GAAAA,CAAAA,CAEtCA,CAAM,CAAA,SAAA,CAAUb,CAAmB,CACnCA,CAAAA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport { getLocalStorageSession } from './localStorage';\nimport { handleError } from './errorHandler';\nimport { reviveResponseTypes } from '../methods/serialize';\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport async function callMethod<T = unknown>(methodName: string, args: MethodArgs = {}): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n handleError(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getLocalStorageSession()?.authToken,\n clientInfo: {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type\n }\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(error);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { ConfigKey, AppConfig, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n * \n * @param key\n * @returns \n */\nexport function getConfig(key: ConfigKey) {\n if (!(key in config)) {\n throw new Error(`Unknown config: ${key}`);\n }\n\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{ configs: Configs, session: object, user: object }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n \n const parsedUser = user ? Object.freeze(z.object({\n id: z.string(),\n handle: z.string(),\n }).parse(user)) : null;\n\n useSessionStore.getState().setUser(parsedUser);\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n await callMethod('_system.session.heartbeat');\n setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: User | null) {\n useSessionStore.getState().setUser(user);\n}\n\nexport function useSession() {\n const user = useSessionStore(state => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n\"use client\";\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({ loadingElement, routesElement, favicon, errorHandler }: {\n loadingElement: React.ReactNode,\n routesElement: React.ReactNode,\n favicon?: string,\n errorHandler?: ErrorHandler\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>\n {routesElement}\n </AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import { setCurrentUser } from '../../client/session';\nimport { callMethod } from '../../client/method';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n};\n\nexport async function signupWithPassword({ email, password }: { email: string, password: string }) {\n await callMethod('_system.user.signupWithPassword', { email, password });\n\n // TODO: handle auto-login from the signup method itself to avoid a second method call\n await loginWithPassword({ email, password });\n}\n\nexport async function loginWithPassword({ email, password }: { email: string, password: string }) {\n const { user } = await callMethod<{ user: UserInfo }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider = 'useClient' in React\n // @ts-ignore: React.useClient only exists in Next.js\n ? React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport { signupWithPassword, loginWithPassword, logout, type UserInfo } from './auth/client';\n"]}
@@ -0,0 +1,3 @@
1
+ var s="module",i="modelence",n="0.5.3-dev.0",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="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/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:m,repository:a,author:u,license:y,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
+ export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-KVMVQYLF.js.map
3
+ //# sourceMappingURL=package-KVMVQYLF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,aAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,C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AAC,CAAAA,CAAAA,CACA,KAAAC,CACA,CAAA,KAAA,CAAAC,EACA,OAAAC,CAAAA,CAAAA,CAOA,KAAAC,CAAAA,CAAAA,CAIA,IAAAC,CAGA,CAAA,OAAA,CAAAC,EAOA,UAAAC,CAAAA,CAAAA,CAIA,OAAAC,CACA,CAAA,OAAA,CAAAC,EACA,IAAAC,CAAAA,CAAAA,CAGA,SAAAC,CACA,CAAA,eAAA,CAAAC,EAcA,YAAAC,CAAAA,CAAAA,CAsBA,iBAAAC,CAIF","file":"package-KVMVQYLF.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.3-dev.0\",\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/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
package/dist/server.d.ts CHANGED
@@ -141,7 +141,7 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
141
141
  * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.
142
142
  *
143
143
  * @param query - The query to filter documents
144
- * @param options - Optional options
144
+ * @param options - Options
145
145
  * @returns The documents
146
146
  */
147
147
  fetch(query: Filter<this['_type']>, options?: {
@@ -369,7 +369,7 @@ declare class Module {
369
369
  * @param options - Module configuration options
370
370
  */
371
371
  constructor(name: string, { stores, queries, mutations, routes, cronJobs, configSchema }: {
372
- stores?: Stores;
372
+ stores?: Store<any, any>[];
373
373
  queries?: Queries;
374
374
  mutations?: Mutations;
375
375
  routes?: RouteDefinition[];
@@ -538,6 +538,30 @@ declare interface ObjectIdLike {
538
538
  toHexString(): string;
539
539
  }
540
540
 
541
+ /**
542
+ * Database collection for storing user accounts with authentication methods and profile information.
543
+ *
544
+ * This is where **signupWithPassword** automatically creates new users.
545
+ *
546
+ * @example
547
+ * ```typescript
548
+ * // Create a new user
549
+ * const result = await dbUsers.insertOne({
550
+ * handle: 'john_doe',
551
+ * emails: [{ address: 'john@example.com', verified: false }],
552
+ * createdAt: new Date(),
553
+ * authMethods: {
554
+ * password: { hash: 'hashed_password' }
555
+ * }
556
+ * });
557
+ *
558
+ * // Find user by email
559
+ * const user = await dbUsers.findOne(
560
+ * { 'emails.address': 'john@example.com' }
561
+ * );
562
+ * ```
563
+ *
564
+ */
541
565
  declare const usersCollection: Store<{
542
566
  handle: zod.ZodString;
543
567
  emails: zod.ZodOptional<zod.ZodArray<zod.ZodObject<{
@@ -628,6 +652,12 @@ declare const usersCollection: Store<{
628
652
  _id: ObjectId;
629
653
  }, ...args: Parameters<any>) => any>>;
630
654
 
655
+ /**
656
+ * @sidebarTitle getConfig (server)
657
+ *
658
+ * @param key
659
+ * @returns
660
+ */
631
661
  declare function getConfig(key: ConfigKey): string | number | boolean;
632
662
 
633
663
  type CloudBackendConnectOkResponse = {
@@ -647,4 +677,4 @@ type CloudBackendConnectErrorResponse = {
647
677
  };
648
678
  type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;
649
679
 
650
- export { type CloudBackendConnectResponse, type HttpMethod, Module, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
680
+ export { type AppOptions, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
package/dist/server.js CHANGED
@@ -1,3 +1,4 @@
1
- import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g as g$1,a as a$2,h,j,k}from'./chunk-QN73CYII.js';export{a as getConfig}from'./chunk-QN73CYII.js';import ze from'dotenv';import nt from'http';import q from'express';import y,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import st from'os';import lt from'bcrypt';import {createServer,defineConfig}from'vite';import wt from'@vitejs/plugin-react';import L from'path';import bt from'fs';function Fe(){return typeof window!="object"}function w(){if(!Fe())throw new Error("This function can only be called on the server")}var oe=new Map,C={authenticated:null,unauthenticated:null};function ne(t,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))oe.set(o,n);}function v(){return C.unauthenticated?[C.unauthenticated]:[]}function re(){return C.authenticated?[C.authenticated]:[]}function ie(t,e){let o=e.find(n=>!Le(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Le(t,e){for(let o of t){let n=oe.get(o);if(n&&n.permissions.includes(e))return true}return false}var N={};function U(t,e){return w(),le(t),I("query",t,e)}function se(t,e){return w(),le(t),I("mutation",t,e)}function ae(t,e){return w(),de(t),I("query",t,e)}function ce(t,e){return w(),de(t),I("mutation",t,e)}function le(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function de(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function I(t,e,o){if(w(),N[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??[];N[e]={type:t,name:e,handler:n,permissions:i};}async function ue(t,e,o){w();let n=N[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{ie(o.roles,n.permissions),c=await r(e,o);}catch(h){throw s.end("error"),h}return s.end(),c}var p=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var We=z$1.string.bind(z$1),Ke=z$1.number.bind(z$1),Ve=z$1.date.bind(z$1),He=z$1.boolean.bind(z$1),Ze=z$1.array.bind(z$1),Qe=z$1.object.bind(z$1),Ge=z$1.enum.bind(z$1),a={string:We,number:Ke,date:Ve,boolean:He,array:Ze,object:Qe,enum:Ge,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 x=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 x.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await Xe()}async function fe(t,e){await x.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await x.updateOne({authToken:t},{$set:{userId:null}});}async function Xe(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await x.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function et(t){let e=Date.now(),o=new Date(e+a$1.days(7));await x.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new p("_system.session",{stores:[x],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 et(e);}}});var u=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}}]});async function ye(t){let e=await pe(t),o=e.userId?await u.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?re():v();return {user:n,session:e,roles:i}}function we(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||n instanceof b$2?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 g=null;async function be(){if(g)return g;let t=D();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 D(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ce(){return g}function rt(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,we(c));});}}async function xe(t,{combinedModules:e}){let o=q();o.use(q.json()),o.use(q.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,h=await it(r);try{let d=await ue(c,r.body.args,h);s.json({data:d,typeMap:a$3(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let S=d.flatten(),E=Object.entries(S.fieldErrors).map(([j,P])=>`${j}: ${(P??[]).join(", ")}`).join("; "),A=S.formErrors.join("; "),k=[E,A].filter(Boolean).join("; ");s.status(400).send(k);}else s.status(500).send(d instanceof Error?d.message:String(d));}}),rt(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=nt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function it(t){let e=y.string().nullish().transform(r=>r??null).parse(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:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!D()){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:v()}}async function Se({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 B("/api/connect","POST",{hostname:st.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 Ee(){return await B("/api/configs","GET")}async function Me(){return await B("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function B(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 z=false,at=a$1.seconds(10);function De(){setInterval(async()=>{if(!z){z=true;try{await Me();}catch(t){console.error("Error syncing status",t);}try{await ct();}catch(t){console.error("Error syncing config",t);}z=false;}},at);}async function ct(){let{configs:t}=await Ee();c(t);}async function Te(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),i=await u.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(i){let c=i.emails?.find(h=>h.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await lt.hash(n,10);return (await u.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function Ie(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 u.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await lt.compare(i,s))throw ve();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function _e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function ve(){return new Error("Incorrect email/password combination")}async function Ae(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 ke=new p("_system.user",{stores:[u],queries:{getOwnProfile:Ae},mutations:{signupWithPassword:Te,loginWithPassword:Ie,logout:_e}});var _=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function je(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await _.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 _.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Pe=new p("_system.migration",{stores:[_]});var ut=a$1.minutes(1),mt=a$1.seconds(10),b={},F,R=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 Ne(t,{description:e="",interval:o,timeout:n=ut,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(F)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 Ue(){if(F)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await R.findOne({...e,"lock.containerId":{$exists:true}});await R.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await pt(mt);let n=await R.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);}),F=setInterval(ft,a$1.seconds(1));}}function pt(t){return new Promise(e=>setTimeout(e,t))}async function ft(){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 ht(e);});}async function ht(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(()=>{$e(i,o),r.end("success");}).catch(s=>{$e(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await R.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function $e(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Je(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qe=new p("_system.cron",{stores:[R]});var W=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await xt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[q.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 xt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>bt.existsSync(L.join(t,n))),o=[wt(),St()];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:L.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:{"@":L.resolve(t,"src")}}}}function St(){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 Be=new W;async function Et({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Be,migrations:i=[]}){ze.config(),ze.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";_t().then(()=>{}).catch(()=>{});let c$1=[ke,ge,qe,Pe],h=[...c$1,...t];e(),Dt(c$1),Mt(t),ne(e$1,o);let d$1=Tt(h);d(d$1??{});let T=Rt(h);if(s&&Ot(h),r){let{configs:E,environmentId:A,appAlias:k,environmentAlias:j,telemetry:P}=await Se({configSchema:d$1,cronJobsMetadata:s?Je():void 0,stores:T});c(E),f$1({environmentId:A,appAlias:k,environmentAlias:j,telemetry:P});}else c(It());let S=D();if(S&&(await be(),vt(T)),s&&await je(i),S)for(let E of T)E.createIndexes();r&&(await g$1(),De()),s&&Ue().catch(console.error),await xe(n,{combinedModules:h});}function Mt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))U(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))se(`${e.name}.${o}`,n);}}function Dt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ae(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ce(`${e.name}.${o}`,n);}}function Rt(t){return t.flatMap(e=>e.stores)}function Tt(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 Ot(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ne(`${e.name}.${o}`,n);}function vt(t){let e=Ce();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function It(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function _t(){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 import('./package-4JN3YDAG.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:n.default.version,environmentId:o})});}}
2
- export{p as Module,f as Store,U as createQuery,u as dbUsers,a as schema,Et as startApp};//# sourceMappingURL=server.js.map
1
+ import {a as a$3}from'./chunk-DN5SVAO2.js';import {a as a$4,b as b$2}from'./chunk-EQLDF7OO.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d,c,f as f$1,g as g$1,a as a$2,h,j,k}from'./chunk-F5MTZMFH.js';export{a as getConfig}from'./chunk-F5MTZMFH.js';import Fe from'dotenv';import st from'http';import q from'express';import y,{z as z$1}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import lt from'os';import mt from'bcrypt';import {createServer,defineConfig}from'vite';import xt from'@vitejs/plugin-react';import F from'path';import Et from'fs';function We(){return typeof window!="object"}function w(){if(!We())throw new Error("This function can only be called on the server")}var oe=new Map,C={authenticated:null,unauthenticated:null};function ne(t,e){C.authenticated=e.authenticated,C.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))oe.set(o,n);}function v(){return C.unauthenticated?[C.unauthenticated]:[]}function re(){return C.authenticated?[C.authenticated]:[]}function se(t,e){let o=e.find(n=>!Ke(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Ke(t,e){for(let o of t){let n=oe.get(o);if(n&&n.permissions.includes(e))return true}return false}var N={};function U(t,e){return w(),le(t),I("query",t,e)}function ie(t,e){return w(),le(t),I("mutation",t,e)}function ae(t,e){return w(),de(t),I("query",t,e)}function ce(t,e){return w(),de(t),I("mutation",t,e)}function le(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function de(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function I(t,e,o){if(w(),N[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,s=typeof o=="function"?[]:o.permissions??[];N[e]={type:t,name:e,handler:n,permissions:s};}async function ue(t,e,o){w();let n=N[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:s,handler:r}=n,i=j("method",`method:${t}`,{type:s,args:e}),c;try{se(o.roles,n.permissions),c=await r(e,o);}catch(h){throw i.end("error"),h}return i.end(),c}var f=class{constructor(e,{stores:o=[],queries:n={},mutations:s={},routes:r=[],cronJobs:i={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=n,this.mutations=s,this.routes=r,this.cronJobs=i,this.configSchema=c;}};var m=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let s=await this.findOne(e,o);if(!s)throw n?n():new Error(`Record not found in ${this.name}`);return s}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let n=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(n,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var Ve=z$1.string.bind(z$1),He=z$1.number.bind(z$1),Ze=z$1.date.bind(z$1),Qe=z$1.boolean.bind(z$1),Ge=z$1.array.bind(z$1),Ye=z$1.object.bind(z$1),Xe=z$1.enum.bind(z$1),a={string:Ve,number:He,date:Ze,boolean:Qe,array:Ge,object:Ye,enum:Xe,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 x=new m("_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 x.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await tt()}async function fe(t,e){await x.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await x.updateOne({authToken:t},{$set:{userId:null}});}async function tt(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await x.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function ot(t){let e=Date.now(),o=new Date(e+a$1.days(7));await x.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new f("_system.session",{stores:[x],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 ot(e);}}});var p=new m("_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}}]}),ye=new m("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function we(t){let e=await pe(t),o=e.userId?await p.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,s=n?re():v();return {user:n,session:e,roles:s}}function be(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(([s,r])=>{o.setHeader(s,r);}),o.send(n.data);}catch(n){n instanceof a$4||n instanceof b$2?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 g=null;async function Ce(){if(g)return g;let t=D();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 D(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function xe(){return g}function it(t,e){for(let o of e)for(let n of o.routes){let{path:s,handlers:r}=n;Object.entries(r).forEach(([i,c])=>{t[i](s,be(c));});}}async function Ee(t,{combinedModules:e}){let o=q();o.use(q.json()),o.use(q.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,i)=>{let{methodName:c}=r.params,h=await at(r);try{let d=await ue(c,r.body.args,h);i.json({data:d,typeMap:a$3(d)});}catch(d){if(console.error(`Error in method ${c}:`,d),d instanceof Error&&d?.constructor?.name==="ZodError"&&"errors"in d){let E=d.flatten(),S=Object.entries(E.fieldErrors).map(([j,P])=>`${j}: ${(P??[]).join(", ")}`).join("; "),A=E.formErrors.join("; "),k=[S,A].filter(Boolean).join("; ");i.status(400).send(k);}else i.status(500).send(d instanceof Error?d.message:String(d));}}),it(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,i)=>t.handler(r,i)),process.on("unhandledRejection",(r,i)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",i);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=st.createServer(o),s=process.env.PORT||3e3;n.listen(s,()=>{h("Application started",{source:"app"}),console.log(`Application started on port ${s}`);});}async function at(t){let e=y.string().nullish().transform(r=>r??null).parse(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:ct(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!D()){let{session:r,user:i,roles:c}=await we(e);return {clientInfo:o,connectionInfo:n,session:r,user:i,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:v()}}function ct(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 Se({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 s=Object.values(o).map(i=>({name:i.getName(),schema:i.getSchema(),collections:[i.getName()]})),r=await B("/api/connect","POST",{hostname:lt.hostname(),containerId:n,dataModels:s,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(s){throw console.error("Unable to connect to Modelence Cloud:",s),s}}async function Me(){return await B("/api/configs","GET")}async function De(){return await B("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function B(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:s}=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 ${s}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let i=await r.text();try{let c=JSON.parse(i);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}, ${i}`)}}return await r.json()}var z=false,dt=a$1.seconds(10);function Te(){setInterval(async()=>{if(!z){z=true;try{await De();}catch(t){console.error("Error syncing status",t);}try{await ut();}catch(t){console.error("Error syncing config",t);}z=false;}},dt);}async function ut(){let{configs:t}=await Me();c(t);}async function Oe(t,{user:e}){let o=z$1.string().email().parse(t.email),n=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),s=await p.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(s){let c=s.emails?.find(h=>h.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let r=await mt.hash(n,10);return (await p.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:r}}})).insertedId}async function _e(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z$1.string().email().parse(t.email),s=z$1.string().parse(t.password),r=await p.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),i=r?.authMethods?.password?.hash;if(!r||!i||!await mt.compare(s,i))throw Ie();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Ae(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function Ie(){return new Error("Incorrect email/password combination")}async function ke(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await p.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var je={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
+ `).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,s=500;for(let r=0;r<o.length;r+=s){let i=o.slice(r,r+s);try{await ye.insertMany(i.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var Pe=new f("_system.user",{stores:[p],queries:{getOwnProfile:ke},mutations:{signupWithPassword:Oe,loginWithPassword:_e,logout:Ae},cronJobs:{updateDisposableEmailList:je}});var _=new m("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function $e(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await _.fetch({version:{$in:e}}),n=new Set(o.map(({version:r})=>r)),s=t.filter(({version:r})=>!n.has(r));if(s.length!==0){console.log(`Running migrations (${s.length})...`);for(let{version:r,description:i,handler:c}of s)console.log(`Running migration v${r}: ${i}`),await _.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Ne=new f("_system.migration",{stores:[_]});var ft=a$1.minutes(1),ht=a$1.seconds(10),b={},L,T=new m("_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 Je(t,{description:e="",interval:o,timeout:n=ft,handler:s}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(L)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:s,state:{isRunning:false}};}async function qe(){if(L)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await T.findOne({...e,"lock.containerId":{$exists:true}});await T.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await gt(ht);let n=await T.fetch(e),s=Date.now();n.forEach(r=>{let i=b[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:s);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=s);}),L=setInterval(yt,a$1.seconds(1));}}function gt(t){return new Promise(e=>setTimeout(e,t))}async function yt(){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 wt(e);});}async function wt(t){let{alias:e,params:o,handler:n,state:s}=t;s.isRunning=true,s.startTs=Date.now();let r=j("cron",`cron:${e}`);n().then(()=>{Ue(s,o),r.end("success");}).catch(i=>{Ue(s,o),k(i),r.end("error"),console.error(`Error in cron job '${e}':`,i);}),await T.updateOne({alias:e},{$set:{lastStartDate:new Date(s.startTs)}});}function Ue(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Be(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var ze=new f("_system.cron",{stores:[T]});var W=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await Mt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[q.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 Mt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>Et.existsSync(F.join(t,n))),o=[xt(),Dt()];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:F.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:{"@":F.resolve(t,"src")}}}}function Dt(){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 Le=new W;async function Tt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Le,migrations:s=[]}){Fe.config(),Fe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,i=process.env.MODELENCE_CRON_ENABLED==="true";jt().then(()=>{}).catch(()=>{});let c$1=[Pe,ge,ze,Ne],h=[...c$1,...t];e(),Ot(c$1),Rt(t),ne(e$1,o);let d$1=It(h);d(d$1??{});let R=vt(h);if(i&&_t(h),r){let{configs:S,environmentId:A,appAlias:k,environmentAlias:j,telemetry:P}=await Se({configSchema:d$1,cronJobsMetadata:i?Be():void 0,stores:R});c(S),f$1({environmentId:A,appAlias:k,environmentAlias:j,telemetry:P});}else c(kt());let E=D();if(E&&(await Ce(),At(R)),i&&await $e(s),E)for(let S of R)S.createIndexes();r&&(await g$1(),Te()),i&&qe().catch(console.error),await Ee(n,{combinedModules:h});}function Rt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))U(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ie(`${e.name}.${o}`,n);}}function Ot(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ae(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ce(`${e.name}.${o}`,n);}}function vt(t){return t.flatMap(e=>e.stores)}function It(t){let e={};for(let o of t)for(let[n,s]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]=s;}return e}function _t(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Je(`${e.name}.${o}`,n);}function At(t){let e=xe();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function kt(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function jt(){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 import('./package-KVMVQYLF.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({version:n.default.version,environmentId:o})});}}
3
+ export{f as Module,m as Store,U as createQuery,p as dbUsers,a as schema,Tt as startApp};//# sourceMappingURL=server.js.map
3
4
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/utils/index.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/auth/user.ts","../src/migration/db.ts","../src/migration/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","type","handler","permissions","runMethod","args","context","method","transaction","startTransaction","response","error","Module","stores","queries","mutations","routes","cronJobs","configSchema","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","getPublicConfigs","usersCollection","authenticate","userDoc","createRouteHandler","req","res","key","value","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getConfig","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","connectionInfo","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","handleSignupWithPassword","email","password","existingUser","existingEmail","e","hash","bcrypt","handleLoginWithPassword","passwordHash","incorrectCredentialsError","handleLogout","getOwnProfile","_args","profile","user_default","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","serviceEndpoint","packageJson"],"mappings":"ynBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAW,EAAA,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,EAAS,EAAA,CACZ,MAAM,IAAI,KAAM,CAAA,gDAAgD,CAEpE,CCNA,IAAME,EAAAA,CAAU,IAAI,GAAA,CACdC,CAA6B,CAAA,CACjC,aAAe,CAAA,IAAA,CACf,eAAiB,CAAA,IACnB,CAEO,CAAA,SAASC,EAAUC,CAAAA,CAAAA,CAAqCC,CAAqC,CAAA,CAClGH,CAAa,CAAA,aAAA,CAAgBG,CAAc,CAAA,aAAA,CAC3CH,CAAa,CAAA,eAAA,CAAkBG,CAAc,CAAA,eAAA,CAE7C,IAAW,GAAA,CAACC,CAAMC,CAAAA,CAAU,IAAK,MAAO,CAAA,OAAA,CAAQH,CAAK,CAAA,CACnDH,EAA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AAI,0BAA8B,EAAA,6BAAA,CAC5DZ,CAAgB,CAAA,OAAA,CAAQ,GAAI,CAAA,wBAAA,CAE5Ba,CAAc,CAAA,aAAa,uBAAoB,CAAA,CAErD,MAAM,KAAA,CAAM,CAAGD,EAAAA,CAAe,CAAwB,oBAAA,CAAA,CAAA,CACpD,MAAQ,CAAA,MAAA,CACR,OAAS,CAAA,CACP,cAAgB,CAAA,kBAClB,CACA,CAAA,IAAA,CAAM,IAAK,CAAA,SAAA,CAAU,CACnB,OAAA,CAASC,CAAY,CAAA,OAAA,CAAQ,OAC7B,CAAA,aAAA,CAAAb,CACF,CAAC,CACH,CAAC,EACH,CACF","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Stores,\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Optional options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from '@/telemetry';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n // res.status(500).json({ error: 'Internal server error' });\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: req.ip || req.socket.remoteAddress, // TODO: handle cases with Proxy\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\n// import passport from 'passport';\n// import session from 'express-session';\n// import { Strategy as GoogleStrategy } from 'passport-google-oauth20';\n\n// Session middleware\n// app.use(session({\n// secret: process.env.SESSION_SECRET || 'default_secret',\n// resave: false,\n// saveUninitialized: false\n// }));\n\n// Passport middleware\n// app.use(passport.initialize());\n// app.use(passport.session());\n\n// // Passport Google strategy setup\n// passport.use(new GoogleStrategy({\n// clientID: process.env.GOOGLE_CLIENT_ID || '',\n// clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',\n// callbackURL: \"/auth/google/callback\"\n// },\n// function(accessToken: string, refreshToken: string, profile: any, cb: (error: any, user?: any) => void) {\n// // Here you would typically find or create a user in your database\n// // For now, we'll just pass the profile info\n// return cb(null, profile);\n// }));\n\n// passport.serializeUser((user: Express.User, done: (err: any, id?: unknown) => void) => {\n// done(null, user);\n// });\n\n// passport.deserializeUser((user: Express.User, done: (err: any, user?: Express.User | false | null) => void) => {\n// done(null, user);\n// });\n\n// // Google Auth routes\n// app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));\n\n// app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),\n// function(req: Request, res: Response) {\n// // Successful authentication, redirect home.\n// res.redirect('/');\n// }\n// );\n\n// // Logout route\n// app.get('/logout', (req: Request, res: Response, next: NextFunction) => {\n// req.logout(function(err) {\n// if (err) { return next(err); }\n// res.redirect('/');\n// });\n// });\n\n// // Middleware to check if user is authenticated\n// function ensureAuthenticated(req: Request, res: Response, next: NextFunction) {\n// if (req.isAuthenticated()) {\n// return next();\n// }\n// res.redirect('/login');\n// }\n\n\n// app.get('/bundle.js', function (req: Request, res: Response) {\n// res.sendFile('.modelence/client/bundle.js', { root: '.' });\n// });\n\n\n// // Update your catch-all route\n// app.get('/', function (req: Request, res: Response) {\n// res.sendFile(path.join('client', 'index.html'), { root: path.join(__dirname, '..') });\n// });\n\n\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { usersCollection } from './db';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n }\n});\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\ntype AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const packageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n version: packageJson.default.version,\n environmentId\n })\n });\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/utils/index.ts","../src/auth/role.ts","../src/methods/index.ts","../src/app/module.ts","../src/data/store.ts","../src/data/types.ts","../src/auth/session.ts","../src/auth/db.ts","../src/auth/index.ts","../src/routes/handler.ts","../src/db/client.ts","../src/app/server.ts","../src/app/backendApi.ts","../src/config/sync.ts","../src/auth/signup.ts","../src/auth/login.ts","../src/auth/profile.ts","../src/auth/disposableEmails.ts","../src/auth/user.ts","../src/migration/db.ts","../src/migration/index.ts","../src/cron/jobs.ts","../src/viteServer.ts","../src/app/index.ts"],"names":["isServer","requireServer","roleMap","defaultRoles","initRoles","roles","_defaultRoles","name","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","type","handler","permissions","runMethod","args","context","method","transaction","startTransaction","response","error","Module","stores","queries","mutations","routes","cronJobs","configSchema","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","oldName","db","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","schema","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","getPublicConfigs","usersCollection","dbDisposableEmailDomains","authenticate","userDoc","createRouteHandler","req","res","key","value","AuthError","ValidationError","connect","mongodbUri","getMongodbUri","MongoClient","err","getConfig","getClient","registerModuleRoutes","app","modules","module","route","path","handlers","startServer","server","combinedModules","express","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","httpServer","http","port","logInfo","val","clientInfo","connectionInfo","getClientIp","forwardedFor","directIp","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","configs","loadConfigs","handleSignupWithPassword","email","password","existingUser","existingEmail","e","hash","bcrypt","handleLoginWithPassword","passwordHash","incorrectCredentialsError","handleLogout","getOwnProfile","_args","profile","updateDisposableEmailListCron","domains","domain","batchSize","i","batch","user_default","dbMigrations","runMigrations","migrations","versions","version","existingVersions","existingVersionSet","pendingMigrations","description","migration_default","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","interval","timeout","startCronJobs","aliasList","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","captureError","getCronJobsMetadata","jobs_default","ViteServer","createServer","defineConfig","appDir","eslintConfigFile","file","fs","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","viteServer","startApp","dotenv","hasRemoteBackend","isCronEnabled","trackAppStart","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","setSchema","getStores","defineCronJobs","environmentId","appAlias","environmentAlias","telemetry","setMetadata","getLocalConfigs","initStores","initMetrics","merged","absoluteKey","cronAlias","cronJobParams","serviceEndpoint","packageJson"],"mappings":"ynBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,EAAAA,GACH,MAAM,IAAI,MAAM,gDAAgD,CAEpE,CCNA,IAAME,EAAAA,CAAU,IAAI,GACdC,CAAAA,CAAAA,CAA6B,CACjC,aAAe,CAAA,IAAA,CACf,gBAAiB,IACnB,CAAA,CAEO,SAASC,EAAAA,CAAUC,EAAqCC,CAAqC,CAAA,CAClGH,EAAa,aAAgBG,CAAAA,CAAAA,CAAc,cAC3CH,CAAa,CAAA,eAAA,CAAkBG,CAAc,CAAA,eAAA,CAE7C,OAAW,CAACC,CAAAA,CAAMC,CAAU,CAAK,GAAA,MAAA,CAAO,QAAQH,CAAK,CAAA,CACnDH,EAAQ,CAAA,GAAA,CAAIK,EAAMC,CAAU,EAEhC,CAEO,SAASC,CAAAA,EAA0B,CACxC,OAAON,CAAAA,CAAa,gBAAkB,CAACA,CAAAA,CAAa,eAAe,CAAI,CAAA,EACzE,CAEO,SAASO,IAA+B,CAC7C,OAAO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O,IAAI,CAAIgJ,CAAAA,EAAAA,CAAS,GAAIC,CAAa,EAGhE,CAEA,SAASL,EAAAA,CAAWtN,EAA2B,CAC7C,IAAMQ,EAAS8D,EAAU,EAAA,CACzB,GAAI,CAAC9D,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,6DAA6D,CAG/E,CAAA,IAAA,IAAWkG,KAAS1G,CAClB0G,CAAAA,CAAAA,CAAM,KAAKlG,CAAM,EAErB,CAEA,SAAS6M,EAAAA,EAA+B,CACtC,IAAM5F,CAAAA,CAAuB,EAE7B,CAAA,OAAI,QAAQ,GAAI,CAAA,WAAA,EACdA,EAAQ,IAAK,CAAA,CACX,IAAK,oBACL,CAAA,IAAA,CAAM,SACN,KAAO,CAAA,OAAA,CAAQ,IAAI,WACrB,CAAC,EAGIA,CACT,CAEA,eAAe8E,EAAgB,EAAA,CAG7B,GAF0B,OAAQ,CAAA,GAAA,CAAI,6BAA+B,OAE9C,CAAA,CACrB,IAAMqB,CAAkB,CAAA,OAAA,CAAQ,IAAI,0BAA8B,EAAA,6BAAA,CAC5DZ,EAAgB,OAAQ,CAAA,GAAA,CAAI,yBAE5Ba,CAAc,CAAA,aAAa,uBAAoB,CAAA,CAErD,MAAM,KAAM,CAAA,CAAA,EAAGD,CAAe,CAAwB,oBAAA,CAAA,CAAA,CACpD,OAAQ,MACR,CAAA,OAAA,CAAS,CACP,cAAgB,CAAA,kBAClB,EACA,IAAM,CAAA,IAAA,CAAK,UAAU,CACnB,OAAA,CAASC,EAAY,OAAQ,CAAA,OAAA,CAC7B,cAAAb,CACF,CAAC,CACH,CAAC,EACH,CACF","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '@/telemetry';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\n/** Array of Store instances that will be provisioned when the module is loaded */\ntype Stores = Store<any, any>[];\n\n/** Record of query methods that can be called from the client */\ntype Queries = Record<string, MethodDefinition<any>>;\n\n/** Record of mutation methods that can be called from the client */\ntype Mutations = Record<string, MethodDefinition<any>>;\n\n/**\n * The Module class is a core building block of a Modelence application that encapsulates related functionality.\n * Modules can contain stores, queries, mutations, routes, cron jobs and configurations.\n * \n * @category Module\n * \n * @example\n * ```ts\n * const todoModule = new Module('todo', {\n * stores: [dbTodos],\n * queries: {\n * async getAll() {\n * // Fetch and return all Todo items\n * }\n * },\n * mutations: {\n * async create({ title }, { user }) {\n * // Create a new Todo item\n * }\n * }\n * });\n * ```\n */\nexport class Module {\n /** @internal */\n public readonly name: string;\n\n /** @internal */\n public readonly stores: Stores;\n\n /** @internal */\n public readonly queries: Queries;\n\n /** @internal */\n public readonly mutations: Mutations;\n\n /** @internal */\n public readonly routes: RouteDefinition[];\n\n /** @internal */\n public readonly cronJobs: Record<string, CronJobInputParams>;\n\n /** @internal */\n public readonly configSchema: ConfigSchema;\n\n /**\n * Creates a new Module instance\n * \n * @param name - The unique name of the module.\n * This name is used to namespace queries, mutations,\n * cron jobs and configuration values with a prefix (e.g. \"todo.create\")\n * \n * @param options - Module configuration options\n */\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Store<any, any>[],\n queries?: Queries,\n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n Db,\n ClientSession,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: WithId<InferDocumentType<TSchema>> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods;\n \n readonly Doc!: this['_doc'];\n\n private name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n private client?: MongoClient;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n init(client: MongoClient) {\n if (this.collection) {\n throw new Error(`Collection ${this.name} is already initialized`);\n }\n\n this.client = client;\n this.collection = this.client.db().collection<this['_type']>(this.name);\n }\n\n /** @internal */\n async createIndexes() {\n if (this.indexes.length > 0) {\n await this.requireCollection().createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as unknown as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n /** @internal */\n requireClient() {\n if (!this.client) {\n throw new Error(`Database is not connected`);\n }\n\n return this.client;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n if (options?.limit) {\n cursor.limit(options.limit);\n }\n if (options?.skip) {\n cursor.skip(options.skip);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document, limit?: number, skip?: number }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(\n selector: Filter<this['_type']>, \n update: UpdateFilter<this['_type']>, \n options?: { session?: ClientSession }\n ): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, options);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n\n /**\n * Returns the raw MongoDB database instance for advanced operations\n * @returns The MongoDB database instance\n * @throws Error if the store is not provisioned\n */\n getDatabase() {\n return this.requireClient().db();\n }\n\n /**\n * Returns the raw MongoDB collection instance for advanced operations\n * @returns The MongoDB collection instance\n * @throws Error if the store is not provisioned\n */\n rawCollection() {\n return this.requireCollection();\n }\n\n /**\n * Renames an existing collection to this store's name, used for migrations\n * @param oldName - The previous name of the collection\n * @throws Error if the old collection doesn't exist or if this store's collection already exists\n */\n async renameFrom(oldName: string, options?: { session?: ClientSession }) {\n const db = this.getDatabase();\n\n if (!this.collection || !db) {\n throw new Error(`Store ${this.name} is not provisioned`);\n }\n\n const oldCollections = await db.listCollections({ name: oldName }).toArray();\n if (oldCollections.length === 0) {\n throw new Error(`Collection ${oldName} not found`);\n }\n\n const newCollections = await db.listCollections({ name: this.name }).toArray();\n if (newCollections.length > 0) {\n throw new Error(`Collection ${this.name} already exists`);\n }\n\n const existingCollection = db.collection<this['_type']>(oldName);\n\n await existingCollection.rename(this.name, options);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { schema } from '../data/types';\nimport { Store } from '../data/store';\n\n/**\n * Database collection for storing user accounts with authentication methods and profile information.\n * \n * This is where **signupWithPassword** automatically creates new users.\n * \n * @example\n * ```typescript\n * // Create a new user\n * const result = await dbUsers.insertOne({\n * handle: 'john_doe',\n * emails: [{ address: 'john@example.com', verified: false }],\n * createdAt: new Date(),\n * authMethods: {\n * password: { hash: 'hashed_password' }\n * }\n * });\n * \n * // Find user by email\n * const user = await dbUsers.findOne(\n * { 'emails.address': 'john@example.com' }\n * );\n * ```\n * \n */\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nexport const dbDisposableEmailDomains = new Store('_modelenceDisposableEmailDomains', {\n schema: {\n domain: schema.string(),\n addedAt: schema.date(),\n },\n indexes: [\n {\n key: { domain: 1 },\n unique: true\n }\n ]\n});\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './db';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\nimport { AuthError, ValidationError } from '../error';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies,\n req,\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n if (error instanceof AuthError || error instanceof ValidationError) {\n res.status(error.status).send(error.message);\n } else {\n console.error(`Error in route handler: ${req.path}`);\n console.error(error);\n res.status(500).send(String(error));\n }\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from '@/telemetry';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from '../db/client';\nimport { AppServer } from '../../../types';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer(server: AppServer, { combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName(*)', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await server.init();\n\n if (server.middlewares) {\n app.use(server.middlewares());\n }\n\n app.all('*', (req: Request, res: Response) => {\n return server.handler(req, res);\n });\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const httpServer = http.createServer(app);\n const port = process.env.PORT || 3000;\n httpServer.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: getClientIp(req),\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\nfunction getClientIp(req: Request): string | undefined {\n // On Heroku and other proxies, X-Forwarded-For contains the real client IP\n const forwardedFor = req.headers['x-forwarded-for'];\n if (forwardedFor) {\n const firstIp = Array.isArray(forwardedFor) ? forwardedFor[0] : forwardedFor.split(',')[0];\n return firstIp.trim();\n }\n\n const directIp = req.ip || req.socket?.remoteAddress;\n if (directIp) {\n // Remove IPv6-to-IPv4 mapping prefix\n return directIp.startsWith('::ffff:') ? directIp.substring(7) : directIp;\n }\n \n return undefined;\n}\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\nimport { AppConfig } from '../config/types';\n\ntype CloudBackendConnectOkResponse = {\n status: 'ok';\n configs: AppConfig[];\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\ntype CloudBackendConnectErrorResponse = {\n status: 'error';\n error: string;\n}\n\nexport type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n): Promise<CloudBackendConnectOkResponse> {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n if (data.status === 'error') {\n throw new Error(data.error);\n }\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './db';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { usersCollection } from './db';\nimport { Args, Context } from '../methods/types';\n\nexport async function getOwnProfile(_args: Args, { user }: Context) {\n if (!user) {\n throw new Error('Not authenticated');\n }\n\n const profile = await usersCollection.requireById(user.id);\n\n return {\n handle: profile.handle,\n emails: profile.emails,\n authMethods: Object.keys(profile.authMethods || {}),\n };\n}\n","import { time } from '../time';\nimport { dbDisposableEmailDomains } from './db';\n\nexport async function isDisposableEmail(email: string): Promise<boolean> {\n const emailParts = email.toLowerCase().trim().split('@');\n if (emailParts.length !== 2) {\n return false;\n }\n \n const domain = emailParts[1];\n const result = await dbDisposableEmailDomains.findOne({ domain });\n return Boolean(result);\n}\n\nexport const updateDisposableEmailListCron = {\n interval: time.days(1),\n async handler() {\n const response = await fetch('https://disposable.github.io/disposable-email-domains/domains.txt');\n \n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n \n const domainsText = await response.text();\n \n const domains = domainsText\n .split('\\n')\n .map(domain => domain.trim().toLowerCase())\n .filter(domain => domain.length > 0);\n \n const now = new Date();\n \n // Insert domains in batches to avoid overwhelming the database\n const batchSize = 500;\n for (let i = 0; i < domains.length; i += batchSize) {\n const batch = domains.slice(i, i + batchSize);\n \n try {\n await dbDisposableEmailDomains.insertMany(\n batch.map(domain => ({\n domain,\n addedAt: now,\n }))\n );\n } catch (error: any) {\n // MongoDB throws BulkWriteError when some documents are duplicates\n if (error.name === 'MongoBulkWriteError' && error.result?.nInserted) {\n // console.warn(`Error inserting batch starting at index ${i}:`, error.message);\n }\n }\n }\n }\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\nimport { getOwnProfile } from './profile';\nimport { usersCollection } from './db';\nimport { updateDisposableEmailListCron } from './disposableEmails';\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n queries: {\n getOwnProfile,\n },\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n },\n cronJobs: {\n updateDisposableEmailList: updateDisposableEmailListCron\n }\n});\n","import { Store } from '../data/store';\nimport { schema } from '../data/types';\n\nexport const dbMigrations = new Store('_modelenceMigrations', {\n schema: {\n version: schema.number(),\n appliedAt: schema.date(),\n },\n indexes: [\n { key: { version: 1 }, unique: true },\n ],\n});\n","import { Module } from '../app/module';\nimport { dbMigrations } from './db';\n\nexport type MigrationScript = {\n version: number,\n description: string,\n handler: () => Promise<void>,\n}\n\nexport async function runMigrations(migrations: MigrationScript[]) {\n if (migrations.length === 0) {\n return;\n }\n\n const versions = migrations.map(({ version }) => version);\n\n const existingVersions = await dbMigrations.fetch({ version: { $in: versions } });\n const existingVersionSet = new Set(existingVersions.map(({ version }) => version));\n const pendingMigrations = migrations.filter(({ version }) => !existingVersionSet.has(version));\n\n if (pendingMigrations.length === 0) {\n return;\n }\n\n console.log(`Running migrations (${pendingMigrations.length})...`);\n for (const { version, description, handler } of pendingMigrations) {\n console.log(`Running migration v${version}: ${description}`);\n // TODO: adjust to handle multiple containers and race conditions\n await dbMigrations.insertOne({ version, appliedAt: new Date() });\n await handler();\n console.log(`Migration v${version} complete`);\n }\n}\n\nexport default new Module('_system.migration', {\n stores: [dbMigrations]\n});\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '@/telemetry';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n if (aliasList.length > 0) {\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n }\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import { createServer, defineConfig, ViteDevServer } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\nimport { AppServer, ExpressMiddleware } from '../../types';\n\nclass ViteServer implements AppServer {\n private viteServer?: ViteDevServer;\n\n async init() {\n if (this.isDev()) {\n console.log('Starting Vite dev server...');\n this.viteServer = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n }); \n }\n }\n\n middlewares(): ExpressMiddleware[] {\n if (this.isDev()) {\n return (this.viteServer?.middlewares ?? []) as ExpressMiddleware[];\n }\n \n return [express.static('./.modelence/build/client')];\n }\n\n handler(req: express.Request, res: express.Response) {\n if (this.isDev()) {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n } else {\n res.sendFile('index.html', { root: './.modelence/build/client' });\n }\n }\n\n private isDev() {\n return process.env.NODE_ENV !== 'production';\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/build/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n\nexport const viteServer = new ViteServer();\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted, setMetadata } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { runMigrations, MigrationScript, default as migrationModule } from '../migration';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\nimport { AppServer } from '../../../types';\nimport { viteServer } from '../viteServer';\n\nexport type AppOptions = {\n modules?: Module[],\n server?: AppServer,\n roles?: Record<string, RoleDefinition>,\n defaultRoles?: Record<string, string>,\n migrations?: Array<MigrationScript>\n}\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {}, server = viteServer, migrations = [] }: AppOptions\n) {\n dotenv.config();\n \n dotenv.config({ path: '.modelence.env' });\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = process.env.MODELENCE_CRON_ENABLED === 'true';\n\n trackAppStart().then(() => {\n // Do nothing\n }).catch(() => {\n // Silently ignore tracking errors to not disrupt app startup\n });\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule, migrationModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs, environmentId, appAlias, environmentAlias, telemetry } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n setMetadata({ environmentId, appAlias, environmentAlias, telemetry });\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n initStores(stores);\n }\n\n if (isCronEnabled) {\n await runMigrations(migrations);\n }\n\n if (mongodbUri) {\n for (const store of stores) {\n store.createIndexes();\n }\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer(server, { combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nfunction initStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to initialize stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.init(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n\nasync function trackAppStart() {\n const isTrackingEnabled = process.env.MODELENCE_TRACKING_ENABLED !== 'false';\n\n if (isTrackingEnabled) {\n const serviceEndpoint = process.env.MODELENCE_SERVICE_ENDPOINT ?? 'https://cloud.modelence.com';\n const environmentId = process.env.MODELENCE_ENVIRONMENT_ID;\n \n const packageJson = await import('../../package.json');\n \n await fetch(`${serviceEndpoint}/api/track/app-start`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify({\n version: packageJson.default.version,\n environmentId\n })\n });\n }\n}\n"]}
package/dist/telemetry.js CHANGED
@@ -1,2 +1,2 @@
1
- export{k as captureError,i as logError,h as logInfo,j as startTransaction}from'./chunk-QN73CYII.js';//# sourceMappingURL=telemetry.js.map
1
+ export{k as captureError,i as logError,h as logInfo,j as startTransaction}from'./chunk-F5MTZMFH.js';//# sourceMappingURL=telemetry.js.map
2
2
  //# sourceMappingURL=telemetry.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.5.2",
4
+ "version": "0.5.3-dev.0",
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",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","appStarted","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","getLogger","message","startTransaction","name","context","transaction","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,EAAuC,EAAC,CACxCC,CAAgB,CAAA,KAAA,CAEb,SAASC,CAAAA,CAAUC,CAAgB,CAAA,CACxC,OAAOH,CAAOG,CAAAA,CAAG,CAAG,EAAA,KACtB,CAEO,SAASC,CAAmB,EAAA,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAM,CAAA,0FAA0F,CAG5G,CAAA,OAAO,OAAO,WACZ,CAAA,MAAA,CAAO,OAAQD,CAAAA,CAAM,CAAE,CAAA,MAAA,CAAO,CAAC,CAACG,CAAG,CAAMJ,GAAAA,CAAAA,CAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,CAAYC,CAAAA,CAAAA,CAAsB,CAChDA,CAAAA,CAAQ,QAAQ,CAAC,CAAE,GAAAH,CAAAA,CAAAA,CAAK,KAAAI,CAAM,CAAA,KAAA,CAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBL,CAAI,CAAA,WAAA,GAAc,UAAW,CAAA,UAAU,CAEvC,EAAA,CAACJ,CAAaI,CAAAA,CAAG,CAKxCH,GAAAA,CAAAA,CAAOG,CAAG,CAAI,CAAA,CACZ,GAAAA,CAAAA,CAAAA,CACA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AAA,CAAcpB,CAAI,CAAA,gBAAA,CAAiBkB,CAAMtD,CAAAA,CAAI,EACnD,OAAIuD,CAAAA,EACFnB,CAAI,CAAA,gBAAA,CAAiBmB,CAAO,CAAA,CAEvBC,CACT,CAEO,SAASC,CAAAA,CAAaT,CAAc,CAAA,CACzC,GAAI,CAACb,GAAsB,CAAA,CACzB,OAAQ,CAAA,KAAA,CAAMa,CAAK,CAAA,CACnB,MACF,CAEAE,CAAO,EAAA,CAAE,YAAaF,CAAAA,CAAK,EAC7B","file":"chunk-QN73CYII.js","sourcesContent":["import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport { getAppAlias, getEnvironmentAlias, getEnvironmentId, getTelemetryServiceName, isTelemetryEnabled } from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false\n }\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\n\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled()) {\n getLogger().error(message, args);\n }\n}\n\nexport function startTransaction(type: 'method' | 'cron' | 'ai' | 'custom', name: string, context?: Record<string, any>) {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
@@ -1,3 +0,0 @@
1
- var s="module",i="modelence",n="0.5.2",o="The Node.js Framework for Real-Time MongoDB Apps",p="dist/index.js",r="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},m={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},a={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",y="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/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:n,description:o,main:p,types:r,exports:d,files:c,bin:l,scripts:m,repository:a,author:u,license:y,bugs:g,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
2
- export{u as author,l as bin,g as bugs,x as default,v as dependencies,o as description,b as devDependencies,d as exports,c as files,h as homepage,y as license,p as main,i as name,j as peerDependencies,a as repository,m as scripts,s as type,r as types,n as version};//# sourceMappingURL=package-4JN3YDAG.js.map
3
- //# sourceMappingURL=package-4JN3YDAG.js.map
@@ -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,EAAQ,QACRC,CAAAA,CAAAA,CAAQ,YACRC,CAAW,CAAA,OAAA,CACXC,EAAe,kDACfC,CAAAA,CAAAA,CAAQ,gBACRC,CAAS,CAAA,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,kBACL,UAAY,CAAA,kBAAA,CACZ,WAAY,kBACZ,CAAA,aAAA,CAAe,qBACf,CAAA,WAAA,CAAa,iBACf,CACAC,CAAAA,CAAAA,CAAS,CACP,MACA,CAAA,UACF,EACAC,CAAO,CAAA,CACL,UAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,OACT,GAAO,CAAA,cAAA,CACP,eAAkB,eAClB,CAAA,IAAA,CAAQ,2CACR,CAAA,WAAA,CAAe,6BACjB,CACAC,CAAAA,CAAAA,CAAc,CACZ,IAAQ,CAAA,KAAA,CACR,IAAO,gDACT,CAAA,CACAC,EAAU,WACVC,CAAAA,CAAAA,CAAW,yBAC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,CAsBA,iBAAAC,CAIF","file":"package-4JN3YDAG.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.2\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\"\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\",\n \"postversion\": \"git push && git push --tags\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^5.0.2\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@octokit/rest\": \"^20.0.2\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^5.1.1\",\n \"commander\": \"^12.0.0\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}