modelence 0.5.7-dev.1 → 0.5.7-dev.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-2ZGVP5SA.js +3 -0
- package/dist/chunk-2ZGVP5SA.js.map +1 -0
- package/dist/client.d.ts +39 -2
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/package-TX6LVN75.js +3 -0
- package/dist/package-TX6LVN75.js.map +1 -0
- package/dist/server.d.ts +33 -29
- package/dist/server.js +3 -3
- package/dist/server.js.map +1 -1
- package/dist/telemetry.js +1 -1
- package/package.json +6 -1
- package/dist/chunk-F5MTZMFH.js +0 -3
- package/dist/chunk-F5MTZMFH.js.map +0 -1
- package/dist/package-33KGY24M.js +0 -3
- package/dist/package-33KGY24M.js.map +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import N from'elastic-apm-node';import y from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import l from'process';var u={},g={},C=false;function p(t){return g[t]?.value}function R(){if(!C)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,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:g[t]?.value??e.default}]))}function W(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!u[e]||(g[e]={key:e,type:o,value:n});}),C=true;}function D(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:r}=o;if(n==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),u=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function h({elasticCloudId:t,elasticApiKey:e}){let o=l.stdout.write,n=l.stderr.write;l.stdout.write=function(r,...c){return L(r.toString(),i.stdout),o.call(l.stdout,r,...c)},l.stderr.write=function(r,...c){return L(r.toString(),i.stderr),n.call(l.stderr,r,...c)},x();}function L(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,f=null,E=null,rt=async()=>{if(M)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');M=true,a()&&await _();};async function _(){let t=p("_system.elastic.apmEndpoint"),e=p("_system.elastic.cloudId"),o=p("_system.elastic.apiKey"),n=I()??"unknown",r=T()??"unknown",c=S()??"unknown",w=K();f=N.start({serviceName:w,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:c,appAlias:n,environmentAlias:r}});let b=new ElasticsearchTransport({apm:f,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});b.on("error",j=>{console.error("Elasticsearch Transport Error:",j);}),E=y.createLogger({level:"debug",defaultMeta:{serviceName:w},format:y.format.combine(y.format.json()),transports:[b]}),h({elasticCloudId:e,elasticApiKey:o});}function A(){if(!f)throw new Error("APM is not initialized");return f}function v(){if(!E)throw new Error("Logger is not initialized");return E}function m(t,e){a()&&v().info(t,e);}function d(t,e){a()&&v().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{p as a,R as b,W 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-2ZGVP5SA.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-2ZGVP5SA.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","_","schema","loadConfigs","configs","type","value","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","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,CAAAA,CAAgB,KAAA,CAQb,SAASC,CAAAA,CAAUC,CAAAA,CAAgB,CACxC,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KACtB,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,0FAA0F,CAAA,CAG5G,OAAO,MAAA,CAAO,YACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CAAE,OAAO,CAAC,CAACM,CAAAA,CAAGC,CAAM,IAAMA,CAAAA,CAAO,QAAQ,CAAA,CAAE,GAAA,CAAI,CAAC,CAACH,CAAAA,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AA,EAAmB,EACrBgB,CAAAA,EAAU,CAAE,IAAA,CAAKC,EAASrC,CAAI,EAElC,CAEO,SAASW,CAAAA,CAAS0B,CAAAA,CAAiBrC,CAAAA,CAAc,CAClDoB,CAAAA,EAAmB,EACrBgB,CAAAA,EAAU,CAAE,KAAA,CAAMC,CAAAA,CAASrC,CAAI,EAEnC,CAEO,SAASsC,CAAAA,CAAiBnD,CAAAA,CAA2CoD,CAAAA,CAAcC,EAA+B,CACvH,GAAI,CAACpB,CAAAA,EAAmB,CACtB,OAAO,CACL,GAAA,CAAK,IAAM,EAGb,CAAA,CAGF,IAAMC,CAAAA,CAAMc,CAAAA,EAAO,CACbM,CAAAA,CAAcpB,CAAAA,CAAI,gBAAA,CAAiBkB,CAAAA,CAAMpD,CAAI,EACnD,OAAIqD,CAAAA,EACFnB,CAAAA,CAAI,gBAAA,CAAiBmB,CAAO,CAAA,CAEvBC,CACT,CAEO,SAASC,CAAAA,CAAaT,CAAAA,CAAc,CACzC,GAAI,CAACb,GAAmB,CAAG,CACzB,OAAA,CAAQ,KAAA,CAAMa,CAAK,CAAA,CACnB,MACF,CAEAE,CAAAA,EAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-2ZGVP5SA.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n * \n * @param key\n * @returns \n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(configSchema).filter(([_, schema]) => schema.isPublic).map(([key, schema]) => {\n return [key, {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n }];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ 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
|
@@ -25,6 +25,19 @@ type User = {
|
|
|
25
25
|
id: string;
|
|
26
26
|
handle: string;
|
|
27
27
|
};
|
|
28
|
+
/**
|
|
29
|
+
* `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.
|
|
30
|
+
*
|
|
31
|
+
* @example
|
|
32
|
+
* ```ts
|
|
33
|
+
* import { useSession } from 'modelence/client';
|
|
34
|
+
*
|
|
35
|
+
* function MyComponent() {
|
|
36
|
+
* const { user } = useSession();
|
|
37
|
+
* return <div>{user?.handle}</div>;
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
28
41
|
declare function useSession(): {
|
|
29
42
|
user: User | null;
|
|
30
43
|
};
|
|
@@ -33,14 +46,38 @@ type UserInfo = {
|
|
|
33
46
|
id: string;
|
|
34
47
|
handle: string;
|
|
35
48
|
};
|
|
36
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Sign up a new user with an email and password.
|
|
51
|
+
*
|
|
52
|
+
* @example
|
|
53
|
+
* ```ts
|
|
54
|
+
* await signupWithPassword({ email: 'test@example.com', password: '12345678' });
|
|
55
|
+
* ```
|
|
56
|
+
* @param options.email - The email of the user.
|
|
57
|
+
* @param options.password - The password of the user.
|
|
58
|
+
*/
|
|
59
|
+
declare function signupWithPassword(options: {
|
|
37
60
|
email: string;
|
|
38
61
|
password: string;
|
|
39
62
|
}): Promise<void>;
|
|
40
|
-
|
|
63
|
+
/**
|
|
64
|
+
* Login a user with an email and password.
|
|
65
|
+
*
|
|
66
|
+
* @example
|
|
67
|
+
* ```ts
|
|
68
|
+
* await loginWithPassword({ email: 'test@example.com', password: '12345678' });
|
|
69
|
+
* ```
|
|
70
|
+
* @param options.email - The email of the user.
|
|
71
|
+
* @param options.password - The password of the user.
|
|
72
|
+
*/
|
|
73
|
+
declare function loginWithPassword(options: {
|
|
41
74
|
email: string;
|
|
42
75
|
password: string;
|
|
43
76
|
}): Promise<UserInfo>;
|
|
77
|
+
/**
|
|
78
|
+
* Logout the current user.
|
|
79
|
+
*
|
|
80
|
+
*/
|
|
44
81
|
declare function logout(): Promise<void>;
|
|
45
82
|
|
|
46
83
|
declare const AppProvider: any;
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a
|
|
1
|
+
import {b as b$1}from'./chunk-DN5SVAO2.js';import {a}from'./chunk-R7MPLJMA.js';import T,{useState,useEffect}from'react';import {create}from'zustand';import {z}from'zod';import {jsx}from'react/jsx-runtime';import W from'react-dom/client';function u(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(r){return console.error("Error parsing session from localStorage",r),null}}function m(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var g=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function w(e){g=e;}function h(e,r){return g(e,r)}async function i(e,r={}){try{return await H(`/api/_internal/method/${e}`,r)}catch(o){throw h(o,e),o}}async function H(e,r){let o=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:u()?.authToken,clientInfo:{screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type}})});if(!o.ok){let s=await o.text();throw new Error(s)}let t=await o.text(),n=t?JSON.parse(t):void 0;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}var S={};function U(e){return S[e]?.value}function y(e){S=e;}var c=create(e=>({user:null,setUser:r=>e({user:r})})),E=false,M=a.seconds(30);async function x(){if(E)return;E=true;let{configs:e,session:r,user:o}=await i("_system.session.init");y(e),m(r);let t=o?Object.freeze(z.object({id:z.string(),handle:z.string()}).parse(o)):null;c.getState().setUser(t),await C();}async function C(){await i("_system.session.heartbeat"),setTimeout(C,M);}function l(e){c.getState().setUser(e);}function L(){return {user:c(r=>r.user)}}var P=false;function p({children:e,loadingElement:r}){let[o,t]=useState(true);return useEffect(()=>{async function n(){P||(P=true,await x(),t(false));}n();},[]),o?r??jsx("div",{children:"Loading..."}):e}function b({loadingElement:e,routesElement:r,favicon:o,errorHandler:t}){if(t&&w(t),window.addEventListener("unload",()=>{}),W.createRoot(document.getElementById("root")).render(jsx(T.StrictMode,{children:jsx(A,{loadingElement:e,children:r})})),o){let n=document.querySelector("link[rel~='icon']");if(n)n.href=o;else {let s=document.createElement("link");s.rel="icon",s.href=o,document.head.appendChild(s);}}}async function J(e){let{email:r,password:o}=e;await i("_system.user.signupWithPassword",{email:r,password:o}),await v({email:r,password:o});}async function v(e){let{email:r,password:o}=e,{user:t}=await i("_system.user.loginWithPassword",{email:r,password:o});return l(t),t}async function j(){await i("_system.user.logout"),l(null);}var A="useClient"in T?T.useClient(p):p;export{A as AppProvider,i as callMethod,U as getConfig,v as loginWithPassword,j as logout,b as renderApp,J as signupWithPassword,L as useSession};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.ts","../src/client/config.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","getGlobalObject","globalObject","getModelenceConfig","setModelenceConfig","config","defaultErrorHandler","error","methodName","setErrorHandler","errorHandler","handleError","callMethod","args","call","endpoint","response","text","result","reviveResponseTypes","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":"sPAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,EAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,EAAuBC,CAAAA,CAAiB,CACtD,YAAA,CA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jG,MAAM5C,CAAAA,CAAW,iCAAA,CAAmC,CAAE,MAAA2C,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAC,EAGvE,MAAMC,CAAAA,CAAkB,CAAE,KAAA,CAAAF,EAAO,QAAA,CAAAC,CAAS,CAAC,EAC7C,CAEA,eAAsBC,CAAAA,CAAkB,CAAE,KAAA,CAAAF,CAAAA,CAAO,SAAAC,CAAS,CAAA,CAAwC,CAChG,GAAM,CAAE,IAAA,CAAA7B,CAAK,CAAA,CAAI,MAAMf,EAA+B,gCAAA,CAAkC,CAAE,KAAA,CAAA2C,CAAAA,CAAO,SAAAC,CAAS,CAAC,EAC3G,OAAArB,CAAAA,CAAeR,CAAI,CAAA,CACZA,CACT,CAEA,eAAsB+B,GAAS,CAC7B,MAAM9C,CAAAA,CAAW,qBAAqB,EACtCuB,CAAAA,CAAe,IAAI,EACrB,KClBaG,CAAAA,CAAc,WAAA,GAAea,EAEtCA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","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","declare global {\n var modelenceConfig: ModelenceConfig;\n}\n\nfunction getGlobalObject() {\n if (typeof global !== 'undefined') {\n return global;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n return {\n modelenceConfig: {} as ModelenceConfig,\n };\n}\n\nconst globalObject = getGlobalObject();\n\nglobalObject.modelenceConfig = {};\n\ninterface ModelenceConfig {\n errorHandler?: (error: Error, methodName: string) => void\n}\n\nexport function getModelenceConfig() {\n return globalObject.modelenceConfig;\n}\n\nexport function setModelenceConfig(config: ModelenceConfig) {\n globalObject.modelenceConfig = {\n ...globalObject.modelenceConfig,\n ...config,\n };\n}\n","import { getModelenceConfig, setModelenceConfig } from \"./config\";\n\nexport type ErrorHandler = (error: Error, methodName: string) => void;\n\nconst defaultErrorHandler: ErrorHandler = (error, methodName) => {\n throw new Error(`Error calling method '${methodName}': ${error.toString()}`);\n};\n\nexport function setErrorHandler(errorHandler: ErrorHandler) {\n setModelenceConfig({ errorHandler });\n}\n\nexport function handleError(error: Error, methodName: string) {\n const errorHandler = getModelenceConfig().errorHandler || defaultErrorHandler;\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"]}
|
|
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","options","email","password","loginWithPassword","logout"],"mappings":"6OAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,QAAQ,mBAAmB,CAAA,CAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,KAAA,CAAMA,CAAW,EAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,KAAA,CAAM,yCAAA,CAA2CA,CAAC,EACnD,IACT,CACF,CAEO,SAASC,CAAAA,CAAuBC,CAAAA,CAAiB,CACtD,YAAA,CAAa,QAAQ,mBAAA,CAAqB,IAAA,CAAK,SAAA,CAAUA,CAAO,CAAC,EACnE,CCVA,IAAIC,EAA6B,CAACC,CAAAA,CAAOC,CAAAA,GAAe,CACtD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Ae,IAAI,EACrB,CC5CO,IAAMG,EAAc,WAAA,GAAea,CAAAA,CAEtCA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","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 { AppConfig, ConfigKey, 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 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\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n * \n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n * \n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\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\n/**\n * Sign up a new user with an email and password.\n * \n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\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\n/**\n * Login a user with an email and password.\n * \n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string, password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: UserInfo }>('_system.user.loginWithPassword', { email, password });\n setCurrentUser(user);\n return user;\n}\n\n/**\n * Logout the current user.\n * \n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\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",o="0.5.7-dev.2",p="The Node.js Framework for Real-Time MongoDB Apps",r="dist/index.js",n="dist/global.d.ts",d={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js"},c=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",prepublishOnly:"npm run build",test:'echo "Error: no test specified" && exit 1',postversion:"git push && git push --tags"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},u="Modelence",g="SEE LICENSE IN LICENSE",y={url:"https://github.com/modelence/modelence/issues"},h="https://modelence.com",b={"@types/archiver":"^6.0.3","@types/bcrypt":"^5.0.2","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/node":"^22.5.1","@types/passport-google-oauth20":"^2.0.16","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",react:"^19.0.0","react-dom":"^19.0.0",typescript:"^5.7.2"},v={"@modelence/types":"^1.0.2","@octokit/rest":"^20.0.2","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^5.1.1",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.8.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0",passport:"^0.7.0","passport-google-oauth20":"^2.0.0",tsup:"^8.3.6",tsx:"^4.19.3",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},j={react:">=18.0.0","react-dom":">=18.0.0"},x={type:s,name:i,version:o,description:p,main:r,types:n,exports:d,files:c,bin:l,scripts:a,repository:m,author:u,license:g,bugs:y,homepage:h,devDependencies:b,dependencies:v,peerDependencies:j};
|
|
2
|
+
export{u as author,l as bin,y as bugs,x as default,v as dependencies,p as description,b as devDependencies,d as exports,c as files,h as homepage,g as license,r as main,i as name,j as peerDependencies,m as repository,a as scripts,s as type,n as types,o as version};//# sourceMappingURL=package-TX6LVN75.js.map
|
|
3
|
+
//# sourceMappingURL=package-TX6LVN75.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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Z,IAAA,CAAQ,QAAA,CACR,QAAW,QAAA,CACX,IAAA,CAAQ,UACR,QAAA,CAAY,QAAA,CACZ,0BAA2B,QAAA,CAC3B,IAAA,CAAQ,SACR,GAAA,CAAO,SAAA,CACP,KAAQ,QAAA,CACR,oBAAA,CAAsB,SACtB,OAAA,CAAW,SAAA,CACX,uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,SAAA,CACP,QAAW,QACb,CAAA,CACAC,EAAoB,CAClB,KAAA,CAAS,WACT,WAAA,CAAa,UACf,EAnFFC,CAAAA,CAAA,CACE,KAAAlB,CAAAA,CACA,IAAA,CAAAC,EACA,OAAA,CAAAC,CAAAA,CACA,YAAAC,CAAAA,CACA,IAAA,CAAAC,EACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAOA,KAAA,CAAAC,EAIA,GAAA,CAAAC,CAAAA,CAGA,QAAAC,CAAAA,CAOA,UAAA,CAAAC,EAIA,MAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CACA,IAAA,CAAAC,EAGA,QAAA,CAAAC,CAAAA,CACA,gBAAAC,CAAAA,CAgBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"package-TX6LVN75.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.5.7-dev.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/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^22.5.1\",\n \"@types/passport-google-oauth20\": \"^2.0.16\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"typescript\": \"^5.7.2\"\n },\n \"dependencies\": {\n \"@modelence/types\": \"^1.0.2\",\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 \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.8.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"passport\": \"^0.7.0\",\n \"passport-google-oauth20\": \"^2.0.0\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,10 +1,25 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { AppServer } from '@modelence/types';
|
|
2
2
|
import { ObjectId as ObjectId$1, WithId, IndexDescription, MongoClient, Collection, Filter, FindOptions, Document, OptionalUnlessRequiredId, InsertOneResult, InsertManyResult, UpdateFilter, UpdateResult, ClientSession, DeleteResult, AggregateOptions, AggregationCursor, AnyBulkWriteOperation, BulkWriteResult, Db } from 'mongodb';
|
|
3
3
|
export { ObjectId } from 'mongodb';
|
|
4
|
+
import { C as ConfigSchema, a as ConfigKey, A as AppConfig } from './types-B7qvJJOF.js';
|
|
4
5
|
import * as zod from 'zod';
|
|
5
6
|
import { z } from 'zod';
|
|
6
7
|
import { Request } from 'express';
|
|
7
|
-
|
|
8
|
+
|
|
9
|
+
type UserInfo = {
|
|
10
|
+
id: string;
|
|
11
|
+
handle: string;
|
|
12
|
+
};
|
|
13
|
+
type Session = {
|
|
14
|
+
authToken: string;
|
|
15
|
+
expiresAt: Date;
|
|
16
|
+
userId: ObjectId$1 | null;
|
|
17
|
+
};
|
|
18
|
+
type Permission = string;
|
|
19
|
+
type RoleDefinition = {
|
|
20
|
+
description?: string;
|
|
21
|
+
permissions: Permission[];
|
|
22
|
+
};
|
|
8
23
|
|
|
9
24
|
type CronJobHandler = () => Promise<void>;
|
|
10
25
|
type CronJobInputParams = {
|
|
@@ -260,21 +275,6 @@ declare class Store<TSchema extends ModelSchema, TMethods extends Record<string,
|
|
|
260
275
|
}): Promise<void>;
|
|
261
276
|
}
|
|
262
277
|
|
|
263
|
-
type UserInfo = {
|
|
264
|
-
id: string;
|
|
265
|
-
handle: string;
|
|
266
|
-
};
|
|
267
|
-
type Session = {
|
|
268
|
-
authToken: string;
|
|
269
|
-
expiresAt: Date;
|
|
270
|
-
userId: ObjectId$1 | null;
|
|
271
|
-
};
|
|
272
|
-
type Permission = string;
|
|
273
|
-
type RoleDefinition = {
|
|
274
|
-
description?: string;
|
|
275
|
-
permissions: Permission[];
|
|
276
|
-
};
|
|
277
|
-
|
|
278
278
|
type ClientInfo = {
|
|
279
279
|
screenWidth: number;
|
|
280
280
|
screenHeight: number;
|
|
@@ -565,16 +565,6 @@ declare interface ObjectIdLike {
|
|
|
565
565
|
*
|
|
566
566
|
* @example
|
|
567
567
|
* ```typescript
|
|
568
|
-
* // Create a new user
|
|
569
|
-
* const result = await dbUsers.insertOne({
|
|
570
|
-
* handle: 'john_doe',
|
|
571
|
-
* emails: [{ address: 'john@example.com', verified: false }],
|
|
572
|
-
* createdAt: new Date(),
|
|
573
|
-
* authMethods: {
|
|
574
|
-
* password: { hash: 'hashed_password' }
|
|
575
|
-
* }
|
|
576
|
-
* });
|
|
577
|
-
*
|
|
578
568
|
* // Find user by email
|
|
579
569
|
* const user = await dbUsers.findOne(
|
|
580
570
|
* { 'emails.address': 'john@example.com' }
|
|
@@ -672,7 +662,21 @@ declare const usersCollection: Store<{
|
|
|
672
662
|
_id: ObjectId;
|
|
673
663
|
}, ...args: Parameters<any>) => any>>;
|
|
674
664
|
|
|
675
|
-
|
|
665
|
+
/**
|
|
666
|
+
* This function will check all rate limit rules on the specified bucket and type,
|
|
667
|
+
* throw an error if any of them are exceeded and increase the count of the rate limit record.
|
|
668
|
+
*
|
|
669
|
+
* @category Rate Limits
|
|
670
|
+
*
|
|
671
|
+
* @example
|
|
672
|
+
* ```ts
|
|
673
|
+
* await consumeRateLimit({ bucket: 'api', type: 'ip', value: '127.0.0.1' });
|
|
674
|
+
* ```
|
|
675
|
+
* @param options.bucket - The bucket for the rate limit.
|
|
676
|
+
* @param options.type - The type of the rate limit.
|
|
677
|
+
* @param options.value - The value for the rate limit.
|
|
678
|
+
*/
|
|
679
|
+
declare function consumeRateLimit(options: {
|
|
676
680
|
bucket: string;
|
|
677
681
|
type: RateLimitType;
|
|
678
682
|
value: string;
|
|
@@ -703,4 +707,4 @@ type CloudBackendConnectErrorResponse = {
|
|
|
703
707
|
};
|
|
704
708
|
type CloudBackendConnectResponse = CloudBackendConnectOkResponse | CloudBackendConnectErrorResponse;
|
|
705
709
|
|
|
706
|
-
export { type AppOptions, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RateLimitRule, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, consumeRateLimit, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
|
|
710
|
+
export { type AppOptions, type CloudBackendConnectResponse, type CronJobInputParams, type HttpMethod, Module, type RateLimitRule, type RateLimitType, type RouteDefinition, type RouteHandler, type RouteParams, type RouteResponse, Store, type UserInfo, consumeRateLimit, createQuery, usersCollection as dbUsers, getConfig, schema, startApp };
|
package/dist/server.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$1,c,f as f$1,g as g$1,a as a$2,h as h$1,j as j$1,k as k$1}from'./chunk-F5MTZMFH.js';export{a as getConfig}from'./chunk-F5MTZMFH.js';import Qe from'dotenv';import Q from'path';import $t from'fs/promises';import gt from'os';import mt from'http';import z$1 from'express';import w,{z}from'zod';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import xt from'bcrypt';import {createServer,defineConfig}from'vite';import It from'@vitejs/plugin-react';import _t from'fs';function Ye(){return typeof window!="object"}function y(){if(!Ye())throw new Error("This function can only be called on the server")}var ae=new Map,x={authenticated:null,unauthenticated:null};function ce(t,e){x.authenticated=e.authenticated,x.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))ae.set(o,n);}function k(){return x.unauthenticated?[x.unauthenticated]:[]}function le(){return x.authenticated?[x.authenticated]:[]}function de(t,e){let o=e.find(n=>!Xe(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function Xe(t,e){for(let o of t){let n=ae.get(o);if(n&&n.permissions.includes(e))return true}return false}var J={};function q(t,e){return y(),fe(t),j("query",t,e)}function ue(t,e){return y(),fe(t),j("mutation",t,e)}function me(t,e){return y(),he(t),j("query",t,e)}function pe(t,e){return y(),he(t),j("mutation",t,e)}function fe(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function he(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function j(t,e,o){if(y(),J[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??[];J[e]={type:t,name:e,handler:n,permissions:i};}async function ge(t,e,o){y();let n=J[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j$1("method",`method:${t}`,{type:i,args:e}),c;try{de(o.roles,n.permissions),c=await r(e,o);}catch(m){throw s.end("error"),m}return s.end(),c}var f=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:m=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=m;}};var p=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var et=z.string.bind(z),tt=z.number.bind(z),ot=z.date.bind(z),nt=z.boolean.bind(z),rt=z.array.bind(z),it=z.object.bind(z),st=z.enum.bind(z),a={string:et,number:tt,date:ot,boolean:nt,array:rt,object:it,enum:st,objectId(){return z.instanceof(ObjectId)},userId(){return z.instanceof(ObjectId)},ref(t){return z.instanceof(ObjectId)},union:z.union.bind(z),infer(t){return {}}};var M=new p("_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 we(t){let e=t?await M.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await ct()}async function ye(t,e){await M.updateOne({authToken:t},{$set:{userId:e}});}async function be(t){await M.updateOne({authToken:t},{$set:{userId:null}});}async function ct(){let t=randomBytes(32).toString("base64url"),e=Date.now(),o=new Date(e+a$1.days(7));return await M.insertOne({authToken:t,createdAt:new Date(e),expiresAt:o,userId:null}),{authToken:t,expiresAt:o,userId:null}}async function lt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await M.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var Ce=new f("_system.session",{stores:[M],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await lt(e);}}});var h=new p("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),D=new p("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function xe(t){let e=await we(t),o=e.userId?await h.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?le():k();return {user:n,session:e,roles:i}}function Me(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}var g=null;async function Re(){if(g)return g;let t=S();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 S(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ee(){return g}function pt(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,Me(c));});}}async function De(t,{combinedModules:e}){let o=z$1();o.use(z$1.json()),o.use(z$1.urlencoded({extended:true})),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,m=await ft(r);try{let l=await ge(c,r.body.args,m);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let O=l.flatten(),I=Object.entries(O.fieldErrors).map(([L,N])=>`${L}: ${(N??[]).join(", ")}`).join("; "),R=O.formErrors.join("; "),$=[I,R].filter(Boolean).join("; ");s.status(400).send($);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),pt(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=mt.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function ft(t){let e=w.string().nullish().transform(r=>r??null).parse(t.body.authToken),o=w.object({screenWidth:w.number(),screenHeight:w.number(),windowWidth:w.number(),windowHeight:w.number(),pixelRatio:w.number(),orientation:w.string().nullable()}).parse(t.body.clientInfo),n={ip:ht(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!S()){let{session:r,user:s,roles:c}=await xe(e);return {clientInfo:o,connectionInfo:n,session:r,user:s,roles:c}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:k()}}function ht(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 i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await W("/api/connect","POST",{hostname:gt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Te(){return await W("/api/configs","GET")}async function ve(){return await W("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function W(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var H=false,wt=a$1.seconds(10);function Oe(){setInterval(async()=>{if(!H){H=true;try{await ve();}catch(t){console.error("Error syncing status",t);}try{await yt();}catch(t){console.error("Error syncing config",t);}H=false;}},wt);}async function yt(){let{configs:t}=await Te();c(t);}async function Ie(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await D.findOne({domain:o})}var _e={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,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await D.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};var T=new p("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var K=[];function Ae(t){if(K.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");K=t;}async function V({bucket:t,type:e,value:o}){let n=K.filter(i=>i.bucket===t&&i.type===e);for(let i of n)await bt(i,o);}async function bt(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),i=await T.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:m}=i?Ct(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await T.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},m);}function Ct(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function je(t,{user:e,connectionInfo:o}){let n=z.string().email().parse(t.email),i=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password);if(await Ie(n))throw new Error("Please use a permanent email address");let r=await h.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(r){let l=r.emails?.find(C=>C.address===n);throw new Error(`User with email already exists: ${l?.address}`)}let s=o?.ip;s&&await V({bucket:"signup",type:"ip",value:s});let c=await xt.hash(i,10);return (await h.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}})).insertedId}async function Le(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let n=z.string().email().parse(t.email),i=z.string().parse(t.password),r=await h.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await xt.compare(i,s))throw $e();return await ye(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Ne(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await be(o.authToken);}function $e(){return new Error("Incorrect email/password combination")}async function Ue(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await h.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var Je=new f("_system.user",{stores:[h,D],queries:{getOwnProfile:Ue},mutations:{signupWithPassword:je,loginWithPassword:Le,logout:Ne},cronJobs:{updateDisposableEmailList:_e},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200}]});var P=new p("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function qe(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await P.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 P.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var Be=new f("_system.migration",{stores:[P]});var Fe=new f("_system.rateLimit",{stores:[T]});var Rt=a$1.minutes(1),Et=a$1.seconds(10),b={},Z,v=new p("_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 We(t,{description:e="",interval:o,timeout:n=Rt,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(Z)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 He(){if(Z)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await v.findOne({...e,"lock.containerId":{$exists:true}});await v.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await Dt(Et);let n=await v.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);}),Z=setInterval(St,a$1.seconds(1));}}function Dt(t){return new Promise(e=>setTimeout(e,t))}async function St(){let t=Date.now();Object.values(b).forEach(async e=>{let{params:o,state:n}=e;if(n.isRunning){n.startTs&&n.startTs+o.timeout<t&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=t&&await Tt(e);});}async function Tt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j$1("cron",`cron:${e}`);n().then(()=>{ze(i,o),r.end("success");}).catch(s=>{ze(i,o),k$1(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await v.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function ze(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Ke(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Ve=new f("_system.cron",{stores:[v]});var G=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await kt()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[z$1.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 kt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>_t.existsSync(Q.join(t,n))),o=[It(),jt()];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:Q.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:{"@":Q.resolve(t,"src")}}}}function jt(){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 Ze=new G;async function Nt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ze,migrations:i=[]}){Qe.config(),Qe.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";Kt().then(()=>{}).catch(()=>{});let c$1=[Je,Ce,Ve,Be,Fe],m=[...c$1,...t];e(),Jt(c$1),Ut(t),ce(e$1,o);let l=Ft(m);d$1(l??{});let C=qt(m);s&&zt(m);let O=Bt(m);if(Ae(O),r){let{configs:R,environmentId:$,appAlias:L,environmentAlias:N,telemetry:Ge}=await Se({configSchema:l,cronJobsMetadata:s?Ke():void 0,stores:C});c(R),f$1({environmentId:$,appAlias:L,environmentAlias:N,telemetry:Ge});}else c(Ht());let I=S();if(I&&(await Re(),Wt(C)),s&&await qe(i),I)for(let R of C)R.createIndexes();r&&(await g$1(),Oe()),s&&He().catch(console.error),await De(n,{combinedModules:m});}function Ut(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))q(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))ue(`${e.name}.${o}`,n);}}function Jt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))me(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))pe(`${e.name}.${o}`,n);}}function qt(t){return t.flatMap(e=>e.stores)}function Bt(t){return t.flatMap(e=>e.rateLimits)}function Ft(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 zt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))We(`${e.name}.${o}`,n);}function Wt(t){let e=Ee();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}function Ht(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}async function Kt(){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 Vt(),i=await import('./package-33KGY24M.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:i.default.version,localHostname:gt.hostname(),environmentId:o})});}}async function Vt(){try{let t=Q.join(process.cwd(),"package.json"),e=await $t.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}
|
|
3
|
-
export{
|
|
1
|
+
import {a as a$3}from'./chunk-DN5SVAO2.js';import {d,a as a$4}from'./chunk-C3UESBRX.js';import {a as a$1}from'./chunk-R7MPLJMA.js';import {b as b$1,e,d as d$1,c,f as f$1,g as g$1,a as a$2,h as h$1,j as j$1,k}from'./chunk-2ZGVP5SA.js';export{a as getConfig}from'./chunk-2ZGVP5SA.js';import et from'dotenv';import Ft from'fs/promises';import gt from'os';import Z from'path';import {randomBytes}from'crypto';import {ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import y,{z as z$1}from'zod';import mt from'bcrypt';import {createServer,defineConfig}from'vite';import Ot from'@vitejs/plugin-react';import vt from'fs';import X,{Router}from'express';import Y from'passport';import {Strategy}from'passport-google-oauth20';import Nt from'cookie-parser';import Ut from'http';var le=new Map,E={authenticated:null,unauthenticated:null};function ue(t,e){E.authenticated=e.authenticated,E.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))le.set(o,n);}function j(){return E.unauthenticated?[E.unauthenticated]:[]}function de(){return E.authenticated?[E.authenticated]:[]}function me(t,e){let o=e.find(n=>!ot(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function ot(t,e){for(let o of t){let n=le.get(o);if(n&&n.permissions.includes(e))return true}return false}var h=class{constructor(e,{stores:o=[],queries:n={},mutations:i={},routes:r=[],cronJobs:s={},configSchema:c={},rateLimits:p=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=i,this.routes=r,this.cronJobs=s,this.configSchema=c,this.rateLimits=p;}};var f=class{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes;}getName(){return this.name}getSchema(){return this.schema}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){this.indexes.length>0&&await this.requireCollection().createIndexes(this.indexes);}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let i=await this.findOne(e,o);if(!i)throw n?n():new Error(`Record not found in ${this.name}`);return i}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}};var nt=z$1.string.bind(z$1),rt=z$1.number.bind(z$1),it=z$1.date.bind(z$1),st=z$1.boolean.bind(z$1),at=z$1.array.bind(z$1),ct=z$1.object.bind(z$1),lt=z$1.enum.bind(z$1),a={string:nt,number:rt,date:it,boolean:st,array:at,object:ct,enum:lt,objectId(){return z$1.instanceof(ObjectId)},userId(){return z$1.instanceof(ObjectId)},ref(t){return z$1.instanceof(ObjectId)},union:z$1.union.bind(z$1),infer(t){return {}}};var R=new f("_modelenceSessions",{schema:{authToken:a.string(),createdAt:a.date(),expiresAt:a.date(),userId:a.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function pe(t){let e=t?await R.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await B()}async function fe(t,e){await R.updateOne({authToken:t},{$set:{userId:e}});}async function he(t){await R.updateOne({authToken:t},{$set:{userId:null}});}async function B(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a$1.days(7));return await R.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function dt(t){let e=Date.now(),o=new Date(e+a$1.days(7));await R.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var ge=new h("_system.session",{stores:[R],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 dt(e);}}});var m=new f("_modelenceUsers",{schema:{handle:a.string(),emails:a.array(a.object({address:a.string(),verified:a.boolean()})).optional(),createdAt:a.date(),authMethods:a.object({password:a.object({hash:a.string()}).optional(),google:a.object({id:a.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}}]}),D=new f("_modelenceDisposableEmailDomains",{schema:{domain:a.string(),addedAt:a.date()},indexes:[{key:{domain:1},unique:true}]});async function ye(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await D.findOne({domain:o})}var we={interval:a$1.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
|
|
2
|
+
`).map(r=>r.trim().toLowerCase()).filter(r=>r.length>0),n=new Date,i=500;for(let r=0;r<o.length;r+=i){let s=o.slice(r,r+i);try{await D.insertMany(s.map(c=>({domain:c,addedAt:n})));}catch(c){c.name==="MongoBulkWriteError"&&c.result?.nInserted;}}}};async function xe(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 m.findOne({"emails.address":n},{collation:{locale:"en",strength:2}}),s=r?.authMethods?.password?.hash;if(!r||!s||!await mt.compare(i,s))throw Ce();return await fe(o.authToken,r._id),{user:{id:r._id,handle:r.handle}}}async function Ee(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await he(o.authToken);}function Ce(){return new Error("Incorrect email/password combination")}async function Re(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var T=new f("_modelenceRateLimits",{schema:{bucket:a.string(),type:a.enum(["ip","user"]),value:a.string(),windowMs:a.number(),windowStart:a.date(),windowCount:a.number(),prevWindowCount:a.number(),expiresAt:a.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var z=[];function Se(t){if(z.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");z=t;}async function F(t){let{bucket:e,type:o,value:n}=t,i=z.filter(r=>r.bucket===e&&r.type===o);for(let r of i)await pt(r,n);}async function pt(t,e,o){let n=()=>new d(`Rate limit exceeded for ${t.bucket}`),i=await T.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),r=Date.now(),s=Math.floor(r/t.window)*t.window,{count:c,modifier:p}=i?ft(i,s,r):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(c>=t.limit)throw n();await T.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},p);}function ft(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let i=t.windowCount,r=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(i+r*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let i=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*i),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function De(t,{user:e,connectionInfo:o}){let n=z$1.string().email().parse(t.email),i=z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password);if(await ye(n))throw new Error("Please use a permanent email address");let r=await m.findOne({"emails.address":n},{collation:{locale:"en",strength:2}});if(r){let l=r.emails?.find(x=>x.address===n);throw new Error(`User with email already exists: ${l?.address}`)}let s=o?.ip;s&&await F({bucket:"signup",type:"ip",value:s});let c=await mt.hash(i,10);return (await m.insertOne({handle:n,emails:[{address:n,verified:false}],createdAt:new Date,authMethods:{password:{hash:c}}})).insertedId}var Te=new h("_system.user",{stores:[m,D],queries:{getOwnProfile:Re},mutations:{signupWithPassword:De,loginWithPassword:xe,logout:Ee},cronJobs:{updateDisposableEmailList:we},rateLimits:[{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200}],configSchema:{"_system.auth.google.enabled":{type:"boolean",isPublic:true,default:false},"_system.auth.google.clientId":{type:"string",isPublic:false,default:""},"_system.auth.google.clientSecret":{type:"secret",isPublic:false,default:""}}});async function Oe({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=Object.values(o).map(s=>({name:s.getName(),schema:s.getSchema(),collections:[s.getName()]})),r=await W("/api/connect","POST",{hostname:gt.hostname(),containerId:n,dataModels:i,configSchema:t,cronJobsMetadata:e});if(r.status==="error")throw new Error(r.error);return console.log("Successfully connected to Modelence Cloud"),r}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function ve(){return await W("/api/configs","GET")}async function Ie(){return await W("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function W(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:i}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let r=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${i}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!r.ok){let s=await r.text();try{let c=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${r.status}, ${s}`)}}return await r.json()}var H=false,yt=a$1.seconds(10);function _e(){setInterval(async()=>{if(!H){H=true;try{await Ie();}catch(t){console.error("Error syncing status",t);}try{await wt();}catch(t){console.error("Error syncing config",t);}H=false;}},yt);}async function wt(){let{configs:t}=await ve();c(t);}var bt=a$1.minutes(1),Ct=a$1.seconds(10),b={},K,O=new f("_modelenceCronJobs",{schema:{alias:a.string(),lastStartDate:a.date().optional(),lock:a.object({containerId:a.string(),acquireDate:a.date()}).optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ae(t,{description:e="",interval:o,timeout:n=bt,handler:i}){if(b[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(K)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);b[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:i,state:{isRunning:false}};}async function je(){if(K)throw new Error("Cron jobs already started");let t=Object.keys(b);if(t.length>0){let e={alias:{$in:t}},o=await O.findOne({...e,"lock.containerId":{$exists:true}});await O.upsertMany(e,{$set:{lock:{containerId:process.env.MODELENCE_CONTAINER_ID||"unknown",acquireDate:new Date}}}),o&&await xt(Ct);let n=await O.fetch(e),i=Date.now();n.forEach(r=>{let s=b[r.alias];s&&(s.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+s.params.interval:i);}),Object.values(b).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=i);}),K=setInterval(Et,a$1.seconds(1));}}function xt(t){return new Promise(e=>setTimeout(e,t))}async function Et(){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 Rt(e);});}async function Rt(t){let{alias:e,params:o,handler:n,state:i}=t;i.isRunning=true,i.startTs=Date.now();let r=j$1("cron",`cron:${e}`);n().then(()=>{ke(i,o),r.end("success");}).catch(s=>{ke(i,o),k(s),r.end("error"),console.error(`Error in cron job '${e}':`,s);}),await O.updateOne({alias:e},{$set:{lastStartDate:new Date(i.startTs)}});}function ke(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function Pe(){return Object.values(b).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var Le=new h("_system.cron",{stores:[O]});var g=null;async function $e(){if(g)return g;let t=v();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 v(){let t=a$2("_system.mongodbUri");return t?String(t):void 0}function Ne(){return g}function Mt(){return typeof window!="object"}function C(){if(!Mt())throw new Error("This function can only be called on the server")}var V={};function G(t,e){return C(),Be(t),P("query",t,e)}function Ue(t,e){return C(),Be(t),P("mutation",t,e)}function Je(t,e){return C(),ze(t),P("query",t,e)}function qe(t,e){return C(),ze(t),P("mutation",t,e)}function Be(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ze(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function P(t,e,o){if(C(),V[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,i=typeof o=="function"?[]:o.permissions??[];V[e]={type:t,name:e,handler:n,permissions:i};}async function Fe(t,e,o){C();let n=V[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:r}=n,s=j$1("method",`method:${t}`,{type:i,args:e}),c;try{me(o.roles,n.permissions),c=await r(e,o);}catch(p){throw s.end("error"),p}return s.end(),c}var L=new f("_modelenceMigrations",{schema:{version:a.number(),appliedAt:a.date()},indexes:[{key:{version:1},unique:true}]});async function We(t){if(t.length===0)return;let e=t.map(({version:r})=>r),o=await L.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 L.insertOne({version:r,appliedAt:new Date}),await c(),console.log(`Migration v${r} complete`);}}var He=new h("_system.migration",{stores:[L]});var Ke=new h("_system.rateLimit",{stores:[T]});var Q=class{async init(){this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer({...defineConfig(await _t()),server:{middlewareMode:true},root:"./src/client"}));}middlewares(){return this.isDev()?this.viteServer?.middlewares??[]:[X.static("./.modelence/build/client")]}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client"});}isDev(){return process.env.NODE_ENV!=="production"}};async function _t(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(n=>vt.existsSync(Z.join(t,n))),o=[Ot(),kt()];if(e){let n=(await import('vite-plugin-eslint')).default;o.push(n({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Z.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/build/client",emptyOutDir:true},server:{proxy:{"/api":"http://localhost:4000"},headers:{"Cache-Control":"no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",Pragma:"no-cache",Expires:"0"},hmr:{port:0}},resolve:{alias:{"@":Z.resolve(t,"src")}}}}function kt(){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 Ve=new Q;async function Ge(t,e){let{authToken:o}=await B(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}async function Pt(t,e){let o=t.user,n=await m.findOne({"authMethods.google.id":o.id});if(n){await Ge(e,n._id);return}let i=o.emails[0]&&o.emails[0]?.value;if(i||e.status(400).json({error:"Email address is required for Google authentication."}),await m.findOne({"emails.address":i},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let s=await m.insertOne({handle:i,emails:[{address:i,verified:true}],createdAt:new Date,authMethods:{google:{id:o.id}}});await Ge(e,s.insertedId);}function Lt(){let t=Router(),e=a$2("_system.auth.google.enabled")==="true",o=String(a$2("_system.auth.google.clientId")),n=String(a$2("_system.auth.google.clientSecret"));return !e||!o||!n||(Y.use(new Strategy({clientID:o,clientSecret:n,callbackURL:"/api/_internal/auth/google/callback"},(i,r,s,c)=>c(null,s))),t.get("/api/_internal/auth/google",Y.authenticate("google",{scope:["profile","email"],session:false})),t.get("/api/_internal/auth/google/callback",Y.authenticate("google",{session:false}),Pt)),t}var Ze=Lt;function Qe(t){return async(e,o)=>{try{let n=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies,req:e});o.status(n.status||200),n.headers&&Object.entries(n.headers).forEach(([i,r])=>{o.setHeader(i,r);}),o.send(n.data);}catch(n){n instanceof a$4?o.status(n.status).send(n.message):(console.error(`Error in route handler: ${e.path}`),console.error(n),o.status(500).send(String(n)));}}}async function Ye(t){let e=await pe(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId)}):null,n=o?{id:o._id.toString(),handle:o.handle}:null,i=n?de():j();return {user:n,session:e,roles:i}}function qt(t,e){for(let o of e)for(let n of o.routes){let{path:i,handlers:r}=n;Object.entries(r).forEach(([s,c])=>{t[s](i,Qe(c));});}}async function Xe(t,{combinedModules:e}){let o=X();o.use(X.json()),o.use(X.urlencoded({extended:true})),o.use(Nt()),o.use(Y.initialize()),o.use(Ze()),o.post("/api/_internal/method/:methodName(*)",async(r,s)=>{let{methodName:c}=r.params,p=await Bt(r);try{let l=await Fe(c,r.body.args,p);s.json({data:l,typeMap:a$3(l)});}catch(l){if(console.error(`Error in method ${c}:`,l),l instanceof a$4)s.status(l.status).send(l.message);else if(l instanceof Error&&l?.constructor?.name==="ZodError"&&"errors"in l){let I=l.flatten(),_=Object.entries(I.fieldErrors).map(([N,U])=>`${N}: ${(U??[]).join(", ")}`).join("; "),S=I.formErrors.join("; "),$=[_,S].filter(Boolean).join("; ");s.status(400).send($);}else s.status(500).send(l instanceof Error?l.message:String(l));}}),qt(o,e),await t.init(),t.middlewares&&o.use(t.middlewares()),o.all("*",(r,s)=>t.handler(r,s)),process.on("unhandledRejection",(r,s)=>{console.error("Unhandled Promise Rejection:"),console.error(r instanceof Error?r.stack:r),console.error("Promise:",s);}),process.on("uncaughtException",r=>{console.error("Uncaught Exception:"),console.error(r.stack),console.trace("Full application stack:");});let n=Ut.createServer(o),i=process.env.PORT||3e3;n.listen(i,()=>{h$1("Application started",{source:"app"}),console.log(`Application started on port ${i}`);});}async function Bt(t){let e=y.string().nullish().transform(r=>r??null).parse(t.cookies.authToken||t.body.authToken),o=y.object({screenWidth:y.number(),screenHeight:y.number(),windowWidth:y.number(),windowHeight:y.number(),pixelRatio:y.number(),orientation:y.string().nullable()}).parse(t.body.clientInfo),n={ip:zt(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!v()){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:j()}}function zt(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function Kt({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Ve,migrations:i=[]}){et.config(),et.config({path:".modelence.env"});let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,s=process.env.MODELENCE_CRON_ENABLED==="true";no().then(()=>{}).catch(()=>{});let c$1=[Te,ge,Le,He,Ke],p=[...c$1,...t];e(),Gt(c$1),Vt(t),ue(e$1,o);let l=Yt(p);d$1(l??{});let x=Zt(p);s&&Xt(p);let I=Qt(p);if(Se(I),r){let{configs:S,environmentId:$,appAlias:N,environmentAlias:U,telemetry:tt}=await Oe({configSchema:l,cronJobsMetadata:s?Pe():void 0,stores:x});c(S),f$1({environmentId:$,appAlias:N,environmentAlias:U,telemetry:tt});}else c(oo());let _=v();if(_&&(await $e(),eo(x)),s&&await We(i),_)for(let S of x)S.createIndexes();r&&(await g$1(),_e()),s&&je().catch(console.error),await Xe(n,{combinedModules:p});}function Vt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))G(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ue(`${e.name}.${o}`,n);}}function Gt(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Je(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))qe(`${e.name}.${o}`,n);}}function Zt(t){return t.flatMap(e=>e.stores)}function Qt(t){return t.flatMap(e=>e.rateLimits)}function Yt(t){let e={};for(let o of t)for(let[n,i]of Object.entries(o.configSchema)){let r=`${o.name}.${n}`;if(r in e)throw new Error(`Duplicate config schema key: ${r} (${o.name})`);e[r]=i;}return e}function Xt(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ae(`${e.name}.${o}`,n);}function eo(t){let e=Ne();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var to={MONGODB_URI:"_system.mongodbUri",GOOGLE_AUTH_ENABLED:"_system.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.auth.google.clientSecret"};function oo(){let t=[];for(let[e,o]of Object.entries(to)){let n=process.env[e];n&&t.push({key:o,type:"string",value:n});}return t}async function no(){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 ro(),i=await import('./package-TX6LVN75.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:i.default.version,localHostname:gt.hostname(),environmentId:o})});}}async function ro(){try{let t=Z.join(process.cwd(),"package.json"),e=await Ft.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}
|
|
3
|
+
export{h as Module,f as Store,F as consumeRateLimit,G as createQuery,m as dbUsers,a as schema,Kt as startApp};//# sourceMappingURL=server.js.map
|
|
4
4
|
//# sourceMappingURL=server.js.map
|