modelence 0.1.9 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.js CHANGED
@@ -1,2 +1,2 @@
1
- import {b as b$1}from'./chunk-O2JTQHZP.js';import {a}from'./chunk-GDI7FXAT.js';import U,{useMemo,useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx,Fragment}from'react/jsx-runtime';import q from'react-dom/client';function h(){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 w(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var S=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function y(e){S=e;}function E(e,r){return S(e,r)}async function i(e,r={}){try{return await O(`/api/_internal/method/${e}`,r)}catch(t){throw E(t,e),t}}async function O(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:h()?.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(!t.ok){let s=await t.text();throw new Error(s)}let o=await t.text(),n=o?JSON.parse(o):undefined;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}function _(e,r={}){let{result:t,triggerMethod:o}=A(e,r,{enabled:true});return {...t,refetch:n=>o(n)}}function W(e,r={}){let{result:t,triggerMethod:o}=A(e,r,{enabled:false});return {...t,mutate:n=>o(n),mutateAsync:o}}function A(e,r={},t){let o=useMemo(()=>r,[JSON.stringify(r)]),[n,s]=useState({isFetching:t.enabled,error:null,data:null}),p=async(k=o)=>{s({isFetching:true,error:null,data:n.data});try{let a=await i(e,k);return s({isFetching:!1,error:null,data:a}),a}catch(a){throw s({isFetching:false,error:a,data:null}),a}};return useEffect(()=>{t.enabled&&p();},[e,o]),{result:n,triggerMethod:p}}var l={};function J(e){if(!(e in l))throw new Error(`Unknown config: ${e}`);return l[e]?.value}function x(e){l=e;}var u=create(e=>({user:null,setUser:r=>e({user:r})})),T=false,j=a.seconds(30);async function R(){if(T)return;T=true;let{configs:e,session:r,user:t}=await i("_system.session.init");x(e),w(r);let o=t?Object.freeze(z$1.object({id:z$1.string(),handle:z$1.string()}).parse(t)):null;u.getState().setUser(o),await M();}async function M(){await i("_system.session.heartbeat"),setTimeout(M,j);}function d(e){u.getState().setUser(e);}function z(){return {user:u(r=>r.user)}}var P=false;function g({children:e,loadingElement:r}){let[t,o]=useState(true);return useEffect(()=>{async function n(){P||(P=true,await R(),o(false));}n();},[]),t?r??jsx("div",{children:"Loading..."}):jsx(Fragment,{children:e})}function D({loadingElement:e,routesElement:r,favicon:t,errorHandler:o}){if(o&&y(o),window.addEventListener("unload",()=>{}),q.createRoot(document.getElementById("root")).render(jsx(U.StrictMode,{children:jsx(b,{loadingElement:e,children:r})})),t){let n=document.querySelector("link[rel~='icon']");if(n)n.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}async function V({email:e,password:r}){await i("_system.user.signupWithPassword",{email:e,password:r}),await H({email:e,password:r});}async function H({email:e,password:r}){let{user:t}=await i("_system.user.loginWithPassword",{email:e,password:r});return d(t),t}async function G(){await i("_system.user.logout"),d(null);}var b="useClient"in U?U.useClient(g):g;export{b as AppProvider,i as callMethod,J as getConfig,H as loginWithPassword,G as logout,D as renderApp,V as signupWithPassword,W as useMutation,_ as useQuery,z as useSession};//# sourceMappingURL=client.js.map
1
+ import {b as b$1}from'./chunk-O2JTQHZP.js';import {a}from'./chunk-GDI7FXAT.js';import U,{useState,useEffect,useMemo}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx,Fragment}from'react/jsx-runtime';import q from'react-dom/client';function h(){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 w(e){localStorage.setItem("modelence.session",JSON.stringify(e));}var S=(e,r)=>{throw new Error(`Error calling method '${r}': ${e.toString()}`)};function y(e){S=e;}function E(e,r){return S(e,r)}async function i(e,r={}){try{return await O(`/api/_internal/method/${e}`,r)}catch(t){throw E(t,e),t}}async function O(e,r){let t=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:r,authToken:h()?.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(!t.ok){let s=await t.text();throw new Error(s)}let o=await t.text(),n=o?JSON.parse(o):undefined;if(!n)throw new Error("Invalid response from server");return b$1(n.data,n.typeMap)}function _(e,r={}){let{result:t,triggerMethod:o}=A(e,r,{enabled:true});return {...t,refetch:n=>o(n)}}function W(e,r={}){let{result:t,triggerMethod:o}=A(e,r,{enabled:false});return {...t,mutate:n=>o(n),mutateAsync:o}}function A(e,r={},t){let o=useMemo(()=>r,[JSON.stringify(r)]),[n,s]=useState({isFetching:t.enabled,error:null,data:null}),p=async(k=o)=>{s({isFetching:true,error:null,data:n.data});try{let a=await i(e,k);return s({isFetching:!1,error:null,data:a}),a}catch(a){throw s({isFetching:false,error:a,data:null}),a}};return useEffect(()=>{t.enabled&&p();},[e,o]),{result:n,triggerMethod:p}}var l={};function J(e){if(!(e in l))throw new Error(`Unknown config: ${e}`);return l[e]?.value}function x(e){l=e;}var u=create(e=>({user:null,setUser:r=>e({user:r})})),T=false,j=a.seconds(30);async function R(){if(T)return;T=true;let{configs:e,session:r,user:t}=await i("_system.session.init");x(e),w(r);let o=t?Object.freeze(z$1.object({id:z$1.string(),handle:z$1.string()}).parse(t)):null;u.getState().setUser(o),await M();}async function M(){await i("_system.session.heartbeat"),setTimeout(M,j);}function d(e){u.getState().setUser(e);}function z(){return {user:u(r=>r.user)}}var P=false;function g({children:e,loadingElement:r}){let[t,o]=useState(true);return useEffect(()=>{async function n(){P||(P=true,await R(),o(false));}n();},[]),t?r??jsx("div",{children:"Loading..."}):jsx(Fragment,{children:e})}function D({loadingElement:e,routesElement:r,favicon:t,errorHandler:o}){if(o&&y(o),window.addEventListener("unload",()=>{}),q.createRoot(document.getElementById("root")).render(jsx(U.StrictMode,{children:jsx(b,{loadingElement:e,children:r})})),t){let n=document.querySelector("link[rel~='icon']");if(n)n.href=t;else {let s=document.createElement("link");s.rel="icon",s.href=t,document.head.appendChild(s);}}}async function V({email:e,password:r}){await i("_system.user.signupWithPassword",{email:e,password:r}),await H({email:e,password:r});}async function H({email:e,password:r}){let{user:t}=await i("_system.user.loginWithPassword",{email:e,password:r});return d(t),t}async function G(){await i("_system.user.logout"),d(null);}var b="useClient"in U?U.useClient(g):g;export{b as AppProvider,i as callMethod,J as getConfig,H as loginWithPassword,G as logout,D as renderApp,V as signupWithPassword,W as useMutation,_ as useQuery,z as useSession};//# sourceMappingURL=client.js.map
2
2
  //# sourceMappingURL=client.js.map
package/dist/server.js CHANGED
@@ -1,4 +1,4 @@
1
- import {a as a$2}from'./chunk-O2JTQHZP.js';import {a as a$1}from'./chunk-GDI7FXAT.js';import Ut from'dotenv';import Tt from'http';import q from'express';import b,{z}from'zod';import Ge from'elastic-apm-node';import U from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import S from'process';import {ObjectId,MongoClient,ServerApiVersion}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import dt from'bcrypt';import {createServer,defineConfig}from'vite';import gt from'@vitejs/plugin-react';import yt from'vite-plugin-eslint';import J from'path';import wt from'fs';import Rt from'os';function He(){return typeof window!="object"}function E(){if(!He())throw new Error("This function can only be called on the server")}var j={},P={},Z=false;function y(t){return P[t]?.value}function Q(){if(!Z)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(P).filter(([t])=>j[t]?.isPublic))}function D(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!j[e]||(P[e]={key:e,type:o,value:r});}),Z=true;}function G(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),j=t;}function I(t,e){!!process.env.MODELENCE_SERVICE_ENDPOINT&&N().info(t,e);}function Y(t,e){!!process.env.MODELENCE_SERVICE_ENDPOINT&&N().error(t,e);}var m={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},Ze=1;function ee({elasticCloudId:t,elasticApiKey:e}){let o=S.stdout.write,r=S.stderr.write;S.stdout.write=function(n,...s){return X(n.toString(),m.stdout),o.call(S.stdout,n,...s)},S.stderr.write=function(n,...s){return X(n.toString(),m.stderr),r.call(S.stderr,n,...s)},te();}function X(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=Ze++),t[r]===`
2
- `?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function Qe(){let t=m.stdout.slice(0,-1);m.stdout=[m.stdout[m.stdout.length-1]];let e=m.stderr.slice(0,-1);m.stderr=[m.stderr[m.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{I(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{Y(o,{timestamp:r,source:"console",sequenceId:n});});}function te(){setTimeout(()=>{Qe(),te();},1e3);}var oe=false,C=null,$=null,re=async()=>{if(oe)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');oe=true,await Xe();};async function Xe(){let t=y("_system.elastic.apmEndpoint"),e=y("_system.elastic.secretToken"),o=y("_system.elastic.cloudId"),r=y("_system.elastic.apiKey");C=Ge.start({serviceName:"typesonic",secretToken:e,serverUrl:t,environment:"dev",transactionSampleRate:1,centralConfig:false});let n=new ElasticsearchTransport({apm:C,level:"debug",clientOpts:{cloud:{id:o},auth:{apiKey:r},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});n.on("error",s=>{console.error("Elasticsearch Transport Error:",s);}),$=U.createLogger({level:"debug",format:U.format.combine(U.format.json()),transports:[n]}),ee({elasticCloudId:o,elasticApiKey:r});}function _(t,e,o){if(!!!process.env.MODELENCE_SERVICE_ENDPOINT)return {end:()=>{}};if(!C)throw new Error("startTransaction: Elastic APM is not initialized");let n=C.startTransaction(e,t);return o&&C.setCustomContext(o),n}function ne(t){if(!C)throw new Error("captureError: Elastic APM is not initialized");C.captureError(t);}function N(){if(!$)throw new Error("Logger is not initialized");return $}var se=new Map,T={authenticated:null,unauthenticated:null};function ie(t,e){T.authenticated=e.authenticated,T.unauthenticated=e.unauthenticated;for(let[o,r]of Object.entries(t))se.set(o,r);}function v(){return T.unauthenticated?[T.unauthenticated]:[]}function ae(){return T.authenticated?[T.authenticated]:[]}function ce(t,e){let o=e.find(r=>!et(t,r));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function et(t,e){for(let o of t){let r=se.get(o);if(r&&r.permissions.includes(e))return true}return false}var L={};function k(t,e){return E(),me(t),A("query",t,e)}function le(t,e){return E(),me(t),A("mutation",t,e)}function ue(t,e){return E(),fe(t),A("query",t,e)}function de(t,e){return E(),fe(t),A("mutation",t,e)}function me(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function fe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function A(t,e,o){if(E(),L[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof o=="function"?o:o.handler,n=typeof o=="function"?[]:o.permissions??[];L[e]={type:t,name:e,handler:r,permissions:n};}async function pe(t,e,o){E();let r=L[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:s}=r,i=_("method",`method:${t}`,{type:n,args:e}),c;try{ce(o.roles,r.permissions),c=await s(e,o);}catch(g){throw i.end("error"),g}return i.end(),c}var f=class{constructor(e,{stores:o=[],queries:r={},mutations:n={},routes:s=[],cronJobs:i={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=r,this.mutations=n,this.routes=s,this.cronJobs=i,this.configSchema=c;}};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}provision(e){this.collection||(this.collection=e.db().collection(this.name),this.indexes.length>0&&this.collection.createIndexes(this.indexes));}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}async findOne(e,o){let r=await this.requireCollection().findOne(e,o);return r?this.wrapDocument(r):null}async requireOne(e,o,r){let n=await this.findOne(e,o);if(!n)throw r?r():new Error(`Record not found in ${this.name}`);return n}find(e,o){let r=this.requireCollection().find(e);return o?.sort&&r.sort(o.sort),r}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let r=await this.findById(e);if(!r)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return r}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let r=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(r,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o){return await this.requireCollection().updateMany(e,o)}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)}};var tt=z.string.bind(z),ot=z.number.bind(z),rt=z.date.bind(z),nt=z.boolean.bind(z),st=z.array.bind(z),it=z.object.bind(z),at=z.enum.bind(z),a={string:tt,number:ot,date:rt,boolean:nt,array:st,object:it,enum:at,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 ge(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 lt()}async function ye(t,e){await M.updateOne({authToken:t},{$set:{userId:e}});}async function we(t){await M.updateOne({authToken:t},{$set:{userId:null}});}async function lt(){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 ut(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 be=new f("_system.session",{stores:[M],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:Q()}},heartbeat:async function(t,{session:e}){e&&await ut(e);}}});async function Ce(t,{user:e}){let o=z.string().email().parse(t.email),r=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),n=await h.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(n){let c=n.emails?.find(g=>g.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let s=await dt.hash(r,10);return (await h.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:s}}})).insertedId}async function Te(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let r=z.string().email().parse(t.email),n=z.string().parse(t.password),s=await h.findOne({"emails.address":r},{collation:{locale:"en",strength:2}}),i=s?.authMethods?.password?.hash;if(!s||!i||!await dt.compare(n,i))throw Se();return await ye(o.authToken,s._id),{user:{id:s._id,handle:s.handle}}}async function Me(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await we(o.authToken);}function Se(){return new Error("Incorrect email/password combination")}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}}]});var De=new f("_system.user",{stores:[h],mutations:{signupWithPassword:Ce,loginWithPassword:Te,logout:Me}});async function Re(t){let e=await ge(t),o=e.userId?await h.findOne({_id:new ObjectId(e.userId)}):null,r=o?{id:o._id.toString(),handle:o.handle}:null,n=r?ae():v();return {user:r,session:e,roles:n}}async function Oe(t,e){if(e){console.log("Starting Vite dev server...");let o=await createServer({...defineConfig(await Et()),server:{middlewareMode:true},root:"./src/client"});t.use(o.middlewares),t.use("*",async(r,n)=>{try{n.sendFile("index.html",{root:"./src/client"});}catch(s){console.error("Error serving index.html:",s),n.status(500).send("Internal Server Error");}});}else t.use(q.static(".modelence/client")),t.get("*",(o,r)=>{r.sendFile("index.html",{root:".modelence/client"});});}async function Et(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(r=>wt.existsSync(J.join(t,r))),o=[gt(),Ct()];return e&&o.push(yt({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:J.resolve(t,e)})),{plugins:o,root:t,build:{outDir:".modelence/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:{"@":J.resolve(t,"src")}}}}function Ct(){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){}}}function Ie(t){return async(e,o)=>{try{let r=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies});o.status(r.status||200),r.headers&&Object.entries(r.headers).forEach(([n,s])=>{o.setHeader(n,s);}),o.send(r.data);}catch(r){o.status(500).send(String(r));}}}var w=null;async function _e(){if(w)return w;let t=R();if(!t)throw new Error("MongoDB URI is not set");w=new MongoClient(t,{serverApi:{version:ServerApiVersion.v1,strict:true,deprecationErrors:true},maxPoolSize:20});try{return await w.connect(),await w.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),w}catch(e){throw console.error(e),w=null,e}}function R(){let t=y("_system.mongodbUri");return t?String(t):undefined}function ve(){return w}function Mt(t,e){for(let o of e)for(let r of o.routes){let{path:n,handlers:s}=r;Object.entries(s).forEach(([i,c])=>{t[i](n,Ie(c));});}}async function Ae({combinedModules:t}){let e=q(),o=process.env.NODE_ENV!=="production";e.use(q.json()),e.use(q.urlencoded({extended:true})),e.post("/api/_internal/method/:methodName",async(s,i)=>{let{methodName:c}=s.params,g=await Dt(s);try{let u=await pe(c,s.body.args,g);i.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let V=u.flatten(),Be=Object.entries(V.fieldErrors).map(([We,Ve])=>`${We}: ${(Ve??[]).join(", ")}`).join("; "),Fe=V.formErrors.join("; "),Ke=[Be,Fe].filter(Boolean).join("; ");i.status(400).send(Ke);}else i.status(500).send(u instanceof Error?u.message:String(u));}}),Mt(e,t),await Oe(e,o),process.on("unhandledRejection",(s,i)=>{console.error("Unhandled Promise Rejection:"),console.error(s instanceof Error?s.stack:s),console.error("Promise:",i);}),process.on("uncaughtException",s=>{console.error("Uncaught Exception:"),console.error(s.stack),console.trace("Full application stack:");});let r=Tt.createServer(e),n=process.env.PORT||3e3;r.listen(n,()=>{I("Application started",{source:"app"}),console.log(`Application started on port ${n}`);});}async function Dt(t){let e=b.string().nullish().transform(s=>s??null).parse(t.body.authToken),o=b.object({screenWidth:b.number(),screenHeight:b.number(),windowWidth:b.number(),windowHeight:b.number(),pixelRatio:b.number(),orientation:b.string().nullable()}).parse(t.body.clientInfo),r={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!R()){let{session:s,user:i,roles:c}=await Re(e);return {clientInfo:o,connectionInfo:r,session:s,user:i,roles:c}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:v()}}async function je({configSchema:t,cronJobsMetadata:e,stores:o}){let r=process.env.MODELENCE_CONTAINER_ID;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(o).map(i=>({name:i.getName(),schema:i.getSchema(),collections:[i.getName()]})),s=await B("/api/connect","POST",{hostname:Rt.hostname(),containerId:r,dataModels:n,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),s}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function Pe(){return await B("/api/configs","GET")}async function Ne(){return await B("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function B(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let s=await fetch(`${r}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):undefined});if(!s.ok){let i=await s.text();try{let c=JSON.parse(i);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${i}`)}}return await s.json()}var F=false,Ot=a$1.seconds(10);function Ue(){setInterval(async()=>{if(!F){F=true;try{await Ne();}catch(t){console.error("Error syncing status",t);}try{await It();}catch(t){console.error("Error syncing config",t);}F=false;}},Ot);}async function It(){let{configs:t}=await Pe();D(t);}var vt=a$1.minutes(1),At=a$1.seconds(10),x={},K,O=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 ke(t,{description:e="",interval:o,timeout:r=vt,handler:n}){if(x[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(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);x[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function ze(){if(K)throw new Error("Cron jobs already started");let e={alias:{$in:Object.keys(x)}},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 jt(At);let r=await O.fetch(e),n=Date.now();r.forEach(s=>{let i=x[s.alias];i&&(i.state.scheduledRunTs=s.lastStartDate?s.lastStartDate.getTime()+i.params.interval:n);}),Object.values(x).forEach(s=>{s.state.scheduledRunTs||(s.state.scheduledRunTs=n);}),K=setInterval(Pt,a$1.seconds(1));}function jt(t){return new Promise(e=>setTimeout(e,t))}async function Pt(){let t=Date.now();Object.values(x).forEach(async e=>{let{params:o,state:r}=e;if(r.isRunning){r.startTs&&r.startTs+o.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await Nt(e);});}async function Nt(t){let{alias:e,params:o,handler:r,state:n}=t;n.isRunning=true,n.startTs=Date.now();let s=_("cron",`cron:${e}`);r().then(()=>{Le(n,o),s.end("success");}).catch(i=>{Le(n,o),ne(i),s.end("error"),console.error(`Error in cron job '${e}':`,i);}),await O.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});}function Le(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=undefined,t.isRunning=false;}function Je(){return Object.values(x).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qe=new f("_system.cron",{stores:[O]});async function $t({modules:t=[],roles:e={},defaultRoles:o={}}={}){Ut.config();let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,n=!!Number(process.env.MODELENCE_CRON_INSTANCE),s=[De,be,qe],i=[...s,...t];kt(s),Lt(t),ie(e,o);let c=Jt(i);G(c);let g=zt(i);if(n&&qt(i),r){let{configs:W}=await je({configSchema:c,cronJobsMetadata:n?Je():undefined,stores:g});D(W);}else D(Ft());R()&&(await _e(),Bt(g)),r&&(await re(),Ue()),n&&ze().catch(console.error),await Ae({combinedModules:i});}function Lt(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))k(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))le(`${e.name}.${o}`,r);}}function kt(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))ue(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))de(`${e.name}.${o}`,r);}}function zt(t){return t.flatMap(e=>e.stores)}function Jt(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let s=`${o.name}.${r}`;if(s in e)throw new Error(`Duplicate config schema key: ${s} (${o.name})`);e[s]=n;}return e}function qt(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))ke(`${e.name}.${o}`,r);}async function Bt(t){let e=ve();if(!e)throw new Error("Failed to provision stores: MongoDB client not initialized");for(let o of t)o.provision(e);}function Ft(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}
3
- export{f as Module,p as Store,k as createQuery,h as dbUsers,y as getConfig,a as schema,$t as startApp};//# sourceMappingURL=server.js.map
1
+ import {a as a$2}from'./chunk-O2JTQHZP.js';import {a as a$1}from'./chunk-GDI7FXAT.js';import Nt from'dotenv';import St from'http';import q from'express';import b,{z}from'zod';import Ge from'elastic-apm-node';import U from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import S from'process';import {ObjectId,MongoClient,ServerApiVersion}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes}from'crypto';import dt from'bcrypt';import {createServer,defineConfig}from'vite';import gt from'@vitejs/plugin-react';import J from'path';import yt from'fs';import Dt from'os';function He(){return typeof window!="object"}function E(){if(!He())throw new Error("This function can only be called on the server")}var j={},P={},Z=false;function y(t){return P[t]?.value}function Q(){if(!Z)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(P).filter(([t])=>j[t]?.isPublic))}function D(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!j[e]||(P[e]={key:e,type:o,value:r});}),Z=true;}function G(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(e.toLowerCase().startsWith("_system."))throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${e})`);if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),j=t;}function I(t,e){!!process.env.MODELENCE_SERVICE_ENDPOINT&&N().info(t,e);}function Y(t,e){!!process.env.MODELENCE_SERVICE_ENDPOINT&&N().error(t,e);}var m={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},Ze=1;function ee({elasticCloudId:t,elasticApiKey:e}){let o=S.stdout.write,r=S.stderr.write;S.stdout.write=function(n,...s){return X(n.toString(),m.stdout),o.call(S.stdout,n,...s)},S.stderr.write=function(n,...s){return X(n.toString(),m.stderr),r.call(S.stderr,n,...s)},te();}function X(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=Ze++),t[r]===`
2
+ `?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function Qe(){let t=m.stdout.slice(0,-1);m.stdout=[m.stdout[m.stdout.length-1]];let e=m.stderr.slice(0,-1);m.stderr=[m.stderr[m.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{I(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{Y(o,{timestamp:r,source:"console",sequenceId:n});});}function te(){setTimeout(()=>{Qe(),te();},1e3);}var oe=false,C=null,$=null,re=async()=>{if(oe)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');oe=true,await Xe();};async function Xe(){let t=y("_system.elastic.apmEndpoint"),e=y("_system.elastic.secretToken"),o=y("_system.elastic.cloudId"),r=y("_system.elastic.apiKey");C=Ge.start({serviceName:"typesonic",secretToken:e,serverUrl:t,environment:"dev",transactionSampleRate:1,centralConfig:false});let n=new ElasticsearchTransport({apm:C,level:"debug",clientOpts:{cloud:{id:o},auth:{apiKey:r},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});n.on("error",s=>{console.error("Elasticsearch Transport Error:",s);}),$=U.createLogger({level:"debug",format:U.format.combine(U.format.json()),transports:[n]}),ee({elasticCloudId:o,elasticApiKey:r});}function _(t,e,o){if(!!!process.env.MODELENCE_SERVICE_ENDPOINT)return {end:()=>{}};if(!C)throw new Error("startTransaction: Elastic APM is not initialized");let n=C.startTransaction(e,t);return o&&C.setCustomContext(o),n}function ne(t){if(!C)throw new Error("captureError: Elastic APM is not initialized");C.captureError(t);}function N(){if(!$)throw new Error("Logger is not initialized");return $}var se=new Map,T={authenticated:null,unauthenticated:null};function ie(t,e){T.authenticated=e.authenticated,T.unauthenticated=e.unauthenticated;for(let[o,r]of Object.entries(t))se.set(o,r);}function v(){return T.unauthenticated?[T.unauthenticated]:[]}function ae(){return T.authenticated?[T.authenticated]:[]}function ce(t,e){let o=e.find(r=>!et(t,r));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function et(t,e){for(let o of t){let r=se.get(o);if(r&&r.permissions.includes(e))return true}return false}var L={};function k(t,e){return E(),me(t),A("query",t,e)}function le(t,e){return E(),me(t),A("mutation",t,e)}function ue(t,e){return E(),fe(t),A("query",t,e)}function de(t,e){return E(),fe(t),A("mutation",t,e)}function me(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function fe(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function A(t,e,o){if(E(),L[e])throw new Error(`Method with name '${e}' is already defined.`);let r=typeof o=="function"?o:o.handler,n=typeof o=="function"?[]:o.permissions??[];L[e]={type:t,name:e,handler:r,permissions:n};}async function pe(t,e,o){E();let r=L[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:n,handler:s}=r,i=_("method",`method:${t}`,{type:n,args:e}),c;try{ce(o.roles,r.permissions),c=await s(e,o);}catch(g){throw i.end("error"),g}return i.end(),c}var f=class{constructor(e,{stores:o=[],queries:r={},mutations:n={},routes:s=[],cronJobs:i={},configSchema:c={}}){this.name=e,this.stores=o,this.queries=r,this.mutations=n,this.routes=s,this.cronJobs=i,this.configSchema=c;}};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}provision(e){this.collection||(this.collection=e.db().collection(this.name),this.indexes.length>0&&this.collection.createIndexes(this.indexes));}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}async findOne(e,o){let r=await this.requireCollection().findOne(e,o);return r?this.wrapDocument(r):null}async requireOne(e,o,r){let n=await this.findOne(e,o);if(!n)throw r?r():new Error(`Record not found in ${this.name}`);return n}find(e,o){let r=this.requireCollection().find(e);return o?.sort&&r.sort(o.sort),r}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let r=await this.findById(e);if(!r)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return r}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){let r=typeof e=="string"?{_id:new ObjectId(e)}:e;return await this.requireCollection().updateOne(r,o)}async upsertOne(e,o){return await this.requireCollection().updateOne(e,o,{upsert:true})}async updateMany(e,o){return await this.requireCollection().updateMany(e,o)}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)}};var tt=z.string.bind(z),ot=z.number.bind(z),rt=z.date.bind(z),nt=z.boolean.bind(z),st=z.array.bind(z),it=z.object.bind(z),at=z.enum.bind(z),a={string:tt,number:ot,date:rt,boolean:nt,array:st,object:it,enum:at,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 ge(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 lt()}async function ye(t,e){await M.updateOne({authToken:t},{$set:{userId:e}});}async function we(t){await M.updateOne({authToken:t},{$set:{userId:null}});}async function lt(){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 ut(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 be=new f("_system.session",{stores:[M],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:Q()}},heartbeat:async function(t,{session:e}){e&&await ut(e);}}});async function Ce(t,{user:e}){let o=z.string().email().parse(t.email),r=z.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t.password),n=await h.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(n){let c=n.emails?.find(g=>g.address===o);throw new Error(`User with email already exists: ${c?.address}`)}let s=await dt.hash(r,10);return (await h.insertOne({handle:o,emails:[{address:o,verified:false}],createdAt:new Date,authMethods:{password:{hash:s}}})).insertedId}async function Te(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");let r=z.string().email().parse(t.email),n=z.string().parse(t.password),s=await h.findOne({"emails.address":r},{collation:{locale:"en",strength:2}}),i=s?.authMethods?.password?.hash;if(!s||!i||!await dt.compare(n,i))throw Se();return await ye(o.authToken,s._id),{user:{id:s._id,handle:s.handle}}}async function Me(t,{user:e,session:o}){if(!o)throw new Error("Session is not initialized");await we(o.authToken);}function Se(){return new Error("Incorrect email/password combination")}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}}]});var De=new f("_system.user",{stores:[h],mutations:{signupWithPassword:Ce,loginWithPassword:Te,logout:Me}});async function Re(t){let e=await ge(t),o=e.userId?await h.findOne({_id:new ObjectId(e.userId)}):null,r=o?{id:o._id.toString(),handle:o.handle}:null,n=r?ae():v();return {user:r,session:e,roles:n}}async function Oe(t,e){if(e){console.log("Starting Vite dev server...");let o=await createServer({...defineConfig(await bt()),server:{middlewareMode:true},root:"./src/client"});t.use(o.middlewares),t.use("*",async(r,n)=>{try{n.sendFile("index.html",{root:"./src/client"});}catch(s){console.error("Error serving index.html:",s),n.status(500).send("Internal Server Error");}});}else t.use(q.static(".modelence/client")),t.get("*",(o,r)=>{r.sendFile("index.html",{root:".modelence/client"});});}async function bt(){let t=process.cwd(),e=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(r=>yt.existsSync(J.join(t,r))),o=[gt(),Et()];if(e){let r=(await import('vite-plugin-eslint')).default;o.push(r({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:J.resolve(t,e)}));}return {plugins:o,root:t,build:{outDir:".modelence/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:{"@":J.resolve(t,"src")}}}}function Et(){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){}}}function Ie(t){return async(e,o)=>{try{let r=await t({query:e.query,body:e.body,params:e.params,headers:e.headers,cookies:e.cookies});o.status(r.status||200),r.headers&&Object.entries(r.headers).forEach(([n,s])=>{o.setHeader(n,s);}),o.send(r.data);}catch(r){o.status(500).send(String(r));}}}var w=null;async function _e(){if(w)return w;let t=R();if(!t)throw new Error("MongoDB URI is not set");w=new MongoClient(t,{serverApi:{version:ServerApiVersion.v1,strict:true,deprecationErrors:true},maxPoolSize:20});try{return await w.connect(),await w.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),w}catch(e){throw console.error(e),w=null,e}}function R(){let t=y("_system.mongodbUri");return t?String(t):undefined}function ve(){return w}function Tt(t,e){for(let o of e)for(let r of o.routes){let{path:n,handlers:s}=r;Object.entries(s).forEach(([i,c])=>{t[i](n,Ie(c));});}}async function Ae({combinedModules:t}){let e=q(),o=process.env.NODE_ENV!=="production";e.use(q.json()),e.use(q.urlencoded({extended:true})),e.post("/api/_internal/method/:methodName",async(s,i)=>{let{methodName:c}=s.params,g=await Mt(s);try{let u=await pe(c,s.body.args,g);i.json({data:u,typeMap:a$2(u)});}catch(u){if(console.error(`Error in method ${c}:`,u),u instanceof Error&&u?.constructor?.name==="ZodError"&&"errors"in u){let V=u.flatten(),Be=Object.entries(V.fieldErrors).map(([We,Ve])=>`${We}: ${(Ve??[]).join(", ")}`).join("; "),Fe=V.formErrors.join("; "),Ke=[Be,Fe].filter(Boolean).join("; ");i.status(400).send(Ke);}else i.status(500).send(u instanceof Error?u.message:String(u));}}),Tt(e,t),await Oe(e,o),process.on("unhandledRejection",(s,i)=>{console.error("Unhandled Promise Rejection:"),console.error(s instanceof Error?s.stack:s),console.error("Promise:",i);}),process.on("uncaughtException",s=>{console.error("Uncaught Exception:"),console.error(s.stack),console.trace("Full application stack:");});let r=St.createServer(e),n=process.env.PORT||3e3;r.listen(n,()=>{I("Application started",{source:"app"}),console.log(`Application started on port ${n}`);});}async function Mt(t){let e=b.string().nullish().transform(s=>s??null).parse(t.body.authToken),o=b.object({screenWidth:b.number(),screenHeight:b.number(),windowWidth:b.number(),windowHeight:b.number(),pixelRatio:b.number(),orientation:b.string().nullable()}).parse(t.body.clientInfo),r={ip:t.ip||t.socket.remoteAddress,userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer")};if(!!R()){let{session:s,user:i,roles:c}=await Re(e);return {clientInfo:o,connectionInfo:r,session:s,user:i,roles:c}}return {clientInfo:o,connectionInfo:r,session:null,user:null,roles:v()}}async function je({configSchema:t,cronJobsMetadata:e,stores:o}){let r=process.env.MODELENCE_CONTAINER_ID;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let n=Object.values(o).map(i=>({name:i.getName(),schema:i.getSchema(),collections:[i.getName()]})),s=await B("/api/connect","POST",{hostname:Dt.hostname(),containerId:r,dataModels:n,configSchema:t,cronJobsMetadata:e});return console.log("Successfully connected to Modelence Cloud"),s}catch(n){throw console.error("Unable to connect to Modelence Cloud:",n),n}}async function Pe(){return await B("/api/configs","GET")}async function Ne(){return await B("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function B(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let s=await fetch(`${r}${t}`,{method:e,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):undefined});if(!s.ok){let i=await s.text();try{let c=JSON.parse(i);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${c?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${s.status}, ${i}`)}}return await s.json()}var F=false,Rt=a$1.seconds(10);function Ue(){setInterval(async()=>{if(!F){F=true;try{await Ne();}catch(t){console.error("Error syncing status",t);}try{await Ot();}catch(t){console.error("Error syncing config",t);}F=false;}},Rt);}async function Ot(){let{configs:t}=await Pe();D(t);}var _t=a$1.minutes(1),vt=a$1.seconds(10),x={},K,O=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 ke(t,{description:e="",interval:o,timeout:r=_t,handler:n}){if(x[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(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);x[t]={alias:t,params:{description:e,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function ze(){if(K)throw new Error("Cron jobs already started");let e={alias:{$in:Object.keys(x)}},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 At(vt);let r=await O.fetch(e),n=Date.now();r.forEach(s=>{let i=x[s.alias];i&&(i.state.scheduledRunTs=s.lastStartDate?s.lastStartDate.getTime()+i.params.interval:n);}),Object.values(x).forEach(s=>{s.state.scheduledRunTs||(s.state.scheduledRunTs=n);}),K=setInterval(jt,a$1.seconds(1));}function At(t){return new Promise(e=>setTimeout(e,t))}async function jt(){let t=Date.now();Object.values(x).forEach(async e=>{let{params:o,state:r}=e;if(r.isRunning){r.startTs&&r.startTs+o.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await Pt(e);});}async function Pt(t){let{alias:e,params:o,handler:r,state:n}=t;n.isRunning=true,n.startTs=Date.now();let s=_("cron",`cron:${e}`);r().then(()=>{Le(n,o),s.end("success");}).catch(i=>{Le(n,o),ne(i),s.end("error"),console.error(`Error in cron job '${e}':`,i);}),await O.updateOne({alias:e},{$set:{lastStartDate:new Date(n.startTs)}});}function Le(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=undefined,t.isRunning=false;}function Je(){return Object.values(x).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var qe=new f("_system.cron",{stores:[O]});async function Ut({modules:t=[],roles:e={},defaultRoles:o={}}={}){Nt.config();let r=!!process.env.MODELENCE_SERVICE_ENDPOINT,n=!!Number(process.env.MODELENCE_CRON_INSTANCE),s=[De,be,qe],i=[...s,...t];Lt(s),$t(t),ie(e,o);let c=zt(i);G(c??{});let g=kt(i);if(n&&Jt(i),r){let{configs:W}=await je({configSchema:c,cronJobsMetadata:n?Je():undefined,stores:g});D(W);}else D(Bt());R()&&(await _e(),qt(g)),r&&(await re(),Ue()),n&&ze().catch(console.error),await Ae({combinedModules:i});}function $t(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))k(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))le(`${e.name}.${o}`,r);}}function Lt(t){for(let e of t){for(let[o,r]of Object.entries(e.queries))ue(`${e.name}.${o}`,r);for(let[o,r]of Object.entries(e.mutations))de(`${e.name}.${o}`,r);}}function kt(t){return t.flatMap(e=>e.stores)}function zt(t){let e={};for(let o of t)for(let[r,n]of Object.entries(o.configSchema)){let s=`${o.name}.${r}`;if(s in e)throw new Error(`Duplicate config schema key: ${s} (${o.name})`);e[s]=n;}return e}function Jt(t){for(let e of t)for(let[o,r]of Object.entries(e.cronJobs))ke(`${e.name}.${o}`,r);}async function qt(t){let e=ve();if(!e)throw new Error("Failed to provision stores: MongoDB client not initialized");for(let o of t)o.provision(e);}function Bt(){let t=[];return process.env.MONGODB_URI&&t.push({key:"_system.mongodbUri",type:"string",value:process.env.MONGODB_URI}),t}
3
+ export{f as Module,p as Store,k as createQuery,h as dbUsers,y as getConfig,a as schema,Ut as startApp};//# sourceMappingURL=server.js.map
4
4
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../utils/index.ts","../config/server.ts","../app/logs.ts","../app/loggerProcess.ts","../app/metrics.ts","../auth/role.ts","../methods/index.ts","../app/module.ts","../data/store.ts","../data/types.ts","../auth/session.ts","../auth/signup.ts","../auth/login.ts","../auth/user.ts","../auth/index.ts","../viteServer.ts","../routes/handler.ts","../db/client.ts","../app/server.ts","../app/backendApi.ts","../config/sync.ts","../cron/jobs.ts","../app/index.ts"],"names":["isServer","requireServer","configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","logInfo","message","args","getLogger","logError","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticSecretToken","elasticApm","esTransport","ElasticsearchTransport","error","winston","startTransaction","name","context","transaction","captureError","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","handler","permissions","runMethod","method","response","Module","stores","queries","mutations","routes","cronJobs","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","handleSignupWithPassword","email","password","existingUser","usersCollection","existingEmail","e","hash","bcrypt","handleLoginWithPassword","userDoc","passwordHash","incorrectCredentialsError","handleLogout","user_default","authenticate","initViteServer","app","isDev","vite","createServer","defineConfig","req","res","express","appDir","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","createRouteHandler","connect","mongodbUri","getMongodbUri","MongoClient","ServerApiVersion","err","getClient","registerModuleRoutes","modules","module","route","handlers","startServer","combinedModules","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","server","http","port","val","clientInfo","connectionInfo","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","startCronJobs","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","getCronJobsMetadata","jobs_default","startApp","dotenv","hasRemoteBackend","isCronEnabled","systemModules","initSystemMethods","initCustomMethods","getConfigSchema","getStores","defineCronJobs","getLocalConfigs","provisionStores","merged","absoluteKey","cronAlias","cronJobParams"],"mappings":"0nBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,EAAAA,GACH,MAAM,IAAI,MAAM,gDAAgD,CAEpE,CCNA,IAAIE,CAAAA,CAA6B,EAC7BC,CAAAA,CAAAA,CAAuC,EACvCC,CAAAA,CAAAA,CAAgB,MAEb,SAASC,CAAAA,CAAUC,CAAgB,CAAA,CACxC,OAAOH,CAAOG,CAAAA,CAAG,GAAG,KACtB,CAEO,SAASC,CAAmB,EAAA,CACjC,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,0FAA0F,CAAA,CAG5G,OAAO,MAAO,CAAA,WAAA,CACZ,OAAO,OAAQD,CAAAA,CAAM,EAAE,MAAO,CAAA,CAAC,CAACG,CAAG,CAAA,GAAMJ,EAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,EAAYC,CAAsB,CAAA,CAChDA,EAAQ,OAAQ,CAAA,CAAC,CAAE,GAAA,CAAAH,EAAK,IAAAI,CAAAA,CAAAA,CAAM,MAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBL,CAAAA,CAAI,WAAY,EAAA,CAAE,WAAW,UAAU,CAAA,EAEvC,CAACJ,CAAaI,CAAAA,CAAG,IAKxCH,CAAOG,CAAAA,CAAG,EAAI,CACZ,GAAA,CAAAA,EACA,IAAAI,CAAAA,CAAAA,CACA,MAAAC,CACF,CAAA,EACF,CAAC,CAEDP,CAAAA,CAAAA,CAAgB,KAClB,CAEO,SAASQ,CAAUC,CAA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G9E,CAAO,CAAA,IAAI,CAAI3K,CAAAA,EAAAA,CAAG,CACzC,CAAA,CAAA,GAAIyP,CAAeD,IAAAA,CAAAA,CACjB,MAAM,IAAI,KACR,CAAA,CAAA,6BAAA,EAAgCC,CAAW,CAAA,EAAA,EAAK9E,CAAO,CAAA,IAAI,CAC7D,CAAA,CAAA,CAAA,CAGF6E,CAAOC,CAAAA,CAAW,CAAIpP,CAAAA,EACxB,CAGF,OAAOmP,CACT,CAEA,SAASH,EAAAA,CAAe3E,CAAmB,CAAA,CACzC,IAAWC,IAAAA,CAAAA,IAAUD,CACnB,CAAA,IAAA,GAAW,CAACgF,CAAAA,CAAWC,CAAa,CAAA,GAAK,MAAO,CAAA,OAAA,CAAQhF,CAAO,CAAA,QAAQ,CACrE4C,CAAAA,EAAAA,CAAc,GAAG5C,CAAO,CAAA,IAAI,CAAI+E,CAAAA,EAAAA,CAAS,CAAIC,CAAAA,CAAAA,CAAa,EAGhE,CAEA,eAAeJ,EAAAA,CAAgB1K,CAA2B,CAAA,CACxD,IAAMO,CAAAA,CAASoF,EAAU,EAAA,CACzB,GAAI,CAACpF,CACH,CAAA,MAAM,IAAI,KAAA,CAAM,4DAA4D,CAAA,CAG9E,IAAWgH,IAAAA,CAAAA,IAASvH,CAClBuH,CAAAA,CAAAA,CAAM,SAAUhH,CAAAA,CAAM,EAE1B,CAEA,SAASkK,EAAAA,EAA+B,CACtC,IAAMnP,CAAuB,CAAA,EAE7B,CAAA,OAAI,OAAQ,CAAA,GAAA,CAAI,WACdA,EAAAA,CAAAA,CAAQ,IAAK,CAAA,CACX,GAAK,CAAA,oBAAA,CACL,IAAM,CAAA,QAAA,CACN,KAAO,CAAA,OAAA,CAAQ,GAAI,CAAA,WACrB,CAAC,CAAA,CAGIA,CACT","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","import { getLogger } from './metrics';\n\nexport function logInfo(message: string, args: object) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (isTelemetryEnabled) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (isTelemetryEnabled) {\n getLogger().error(message, args);\n }\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from './logs';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","import elasticApm from 'elastic-apm-node';\nimport { Writable } from 'stream';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\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 await initElasticApm();\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticSecretToken = getConfig('_system.elastic.secretToken') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n apm = elasticApm.start({\n serviceName: 'typesonic',\n secretToken: elasticSecretToken,\n serverUrl: elasticApmEndpoint,\n environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\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 format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\nexport function startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (!isTelemetryEnabled) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n if (!apm) {\n throw new Error('startTransaction: Elastic APM is not initialized');\n }\n\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!apm) {\n throw new Error('captureError: Elastic APM is not initialized');\n }\n\n apm.captureError(error);\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '../app/metrics';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\ntype Stores = Store<any, any>[];\ntype Queries = Record<string, MethodDefinition<any>>;\ntype Mutations = Record<string, MethodDefinition<any>>;\n\nexport class Module {\n public readonly name: string;\n public readonly stores: Stores;\n public readonly queries: Queries;\n public readonly mutations: Mutations;\n public readonly routes: RouteDefinition[];\n public readonly cronJobs: Record<string, CronJobInputParams>;\n public readonly configSchema: ConfigSchema;\n\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Stores, \n queries?: Queries, \n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: InferDocumentType<TSchema> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods & Record<string, never>;\n \n readonly Doc!: this['_doc'];\n\n private readonly name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n provision(client: MongoClient) {\n if (this.collection) {\n return;\n }\n\n this.collection = client.db().collection<this['_type']>(this.name);\n if (this.indexes.length > 0) {\n this.collection.createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Optional options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\n\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n }\n});\n\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './user';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { createServer, defineConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport eslintPlugin from 'vite-plugin-eslint';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\n\nexport async function initViteServer(app: express.Application, isDev: boolean) {\n if (isDev) {\n console.log('Starting Vite dev server...');\n const vite = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n });\n \n app.use(vite.middlewares);\n \n app.use('*', async (req: express.Request, res: express.Response) => {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n });\n } else {\n app.use(express.static('.modelence/client'));\n app.get('*', (req, res) => {\n res.sendFile('index.html', { root: '.modelence/client' });\n });\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n res.status(500).send(String(error));\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n serverApi: {\n version: ServerApiVersion.v1,\n strict: true,\n deprecationErrors: true,\n },\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from './logs';\nimport { initViteServer } from '../viteServer';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from 'db/client';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer({ combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n const isDev = process.env.NODE_ENV !== 'production';\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n // res.status(500).json({ error: 'Internal server error' });\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await initViteServer(app, isDev);\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const server = http.createServer(app);\n const port = process.env.PORT || 3000;\n server.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: req.ip || req.socket.remoteAddress, // TODO: handle cases with Proxy\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\n// import passport from 'passport';\n// import session from 'express-session';\n// import { Strategy as GoogleStrategy } from 'passport-google-oauth20';\n\n// Session middleware\n// app.use(session({\n// secret: process.env.SESSION_SECRET || 'default_secret',\n// resave: false,\n// saveUninitialized: false\n// }));\n\n// Passport middleware\n// app.use(passport.initialize());\n// app.use(passport.session());\n\n// // Passport Google strategy setup\n// passport.use(new GoogleStrategy({\n// clientID: process.env.GOOGLE_CLIENT_ID || '',\n// clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',\n// callbackURL: \"/auth/google/callback\"\n// },\n// function(accessToken: string, refreshToken: string, profile: any, cb: (error: any, user?: any) => void) {\n// // Here you would typically find or create a user in your database\n// // For now, we'll just pass the profile info\n// return cb(null, profile);\n// }));\n\n// passport.serializeUser((user: Express.User, done: (err: any, id?: unknown) => void) => {\n// done(null, user);\n// });\n\n// passport.deserializeUser((user: Express.User, done: (err: any, user?: Express.User | false | null) => void) => {\n// done(null, user);\n// });\n\n// // Google Auth routes\n// app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));\n\n// app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),\n// function(req: Request, res: Response) {\n// // Successful authentication, redirect home.\n// res.redirect('/');\n// }\n// );\n\n// // Logout route\n// app.get('/logout', (req: Request, res: Response, next: NextFunction) => {\n// req.logout(function(err) {\n// if (err) { return next(err); }\n// res.redirect('/');\n// });\n// });\n\n// // Middleware to check if user is authenticated\n// function ensureAuthenticated(req: Request, res: Response, next: NextFunction) {\n// if (req.isAuthenticated()) {\n// return next();\n// }\n// res.redirect('/login');\n// }\n\n\n// app.get('/bundle.js', function (req: Request, res: Response) {\n// res.sendFile('.modelence/client/bundle.js', { root: '.' });\n// });\n\n\n// // Update your catch-all route\n// app.get('/', function (req: Request, res: Response) {\n// res.sendFile(path.join('client', 'index.html'), { root: path.join(__dirname, '..') });\n// });\n\n\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n) {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '../app/metrics';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\n// import { createStsClient } from './aws';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {} }: {\n modules?: Module[]\n roles?: Record<string, RoleDefinition>\n defaultRoles?: Record<string, string>\n } = {}\n) {\n dotenv.config();\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = Boolean(Number(process.env.MODELENCE_CRON_INSTANCE));\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n provisionStores(stores);\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer({ combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nasync function provisionStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to provision stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.provision(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n"]}
1
+ {"version":3,"sources":["../utils/index.ts","../config/server.ts","../app/logs.ts","../app/loggerProcess.ts","../app/metrics.ts","../auth/role.ts","../methods/index.ts","../app/module.ts","../data/store.ts","../data/types.ts","../auth/session.ts","../auth/signup.ts","../auth/login.ts","../auth/user.ts","../auth/index.ts","../viteServer.ts","../routes/handler.ts","../db/client.ts","../app/server.ts","../app/backendApi.ts","../config/sync.ts","../cron/jobs.ts","../app/index.ts"],"names":["isServer","requireServer","configSchema","config","isInitialized","getConfig","key","getPublicConfigs","loadConfigs","configs","type","value","setSchema","schema","isPublic","logInfo","message","args","getLogger","logError","buffer","sequenceId","startLoggerProcess","elasticCloudId","elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticSecretToken","elasticApm","esTransport","ElasticsearchTransport","error","winston","startTransaction","name","context","transaction","captureError","roleMap","defaultRoles","initRoles","roles","_defaultRoles","definition","getUnauthenticatedRoles","getDefaultAuthenticatedRoles","requireAccess","requiredPermissions","missingPermission","permission","hasPermission","role","methods","createQuery","methodDef","validateMethodName","_createMethodInternal","createMutation","_createSystemQuery","validateSystemMethodName","_createSystemMutation","handler","permissions","runMethod","method","response","Module","stores","queries","mutations","routes","cronJobs","Store","options","client","document","query","errorHandler","result","cursor","id","idSelector","ObjectId","documents","selector","update","modifiedSelector","pipeline","operations","schemaString","z","schemaNumber","schemaDate","schemaBoolean","schemaArray","schemaObject","schemaEnum","collection","sessionsCollection","obtainSession","authToken","existingSession","createSession","setSessionUser","userId","clearSessionUser","randomBytes","now","expiresAt","time","processSessionHeartbeat","session","newExpiresAt","session_default","user","handleSignupWithPassword","email","password","existingUser","usersCollection","existingEmail","e","hash","bcrypt","handleLoginWithPassword","userDoc","passwordHash","incorrectCredentialsError","handleLogout","user_default","authenticate","initViteServer","app","isDev","vite","createServer","defineConfig","req","res","express","appDir","eslintConfigFile","file","fs","path","plugins","reactPlugin","modelenceAssetPlugin","eslintPlugin","code","bundle","createRouteHandler","connect","mongodbUri","getMongodbUri","MongoClient","ServerApiVersion","err","getClient","registerModuleRoutes","modules","module","route","handlers","startServer","combinedModules","methodName","getCallContext","getResponseTypeMap","flattened","fieldMessages","errors","formMessages","allMessages","reason","promise","server","http","port","val","clientInfo","connectionInfo","connectCloudBackend","cronJobsMetadata","containerId","dataModels","store","data","callApi","os","fetchConfigs","syncStatus","endpoint","payload","MODELENCE_SERVICE_ENDPOINT","MODELENCE_SERVICE_TOKEN","json","isSyncing","SYNC_INTERVAL","startConfigSync","syncConfig","DEFAULT_TIMEOUT","LOCK_TRANSFER_DELAY","cronJobsInterval","cronJobsCollection","defineCronJob","alias","description","interval","timeout","startCronJobs","aliasSelector","existingLockedRecord","sleep","cronJobRecords","record","job","tickCronJobs","ms","resolve","params","state","startCronJob","handleCronJobCompletion","getCronJobsMetadata","jobs_default","startApp","dotenv","hasRemoteBackend","isCronEnabled","systemModules","markAppStarted","initSystemMethods","initCustomMethods","getConfigSchema","getStores","defineCronJobs","getLocalConfigs","provisionStores","merged","absoluteKey","cronAlias","cronJobParams"],"mappings":"ulBAAO,SAASA,EAAW,EAAA,CACzB,OAAO,OAAO,MAAA,EAAW,QAC3B,CAEO,SAASC,CAAgB,EAAA,CAC9B,GAAI,CAACD,EAAAA,GACH,MAAM,IAAI,MAAM,gDAAgD,CAEpE,CCNA,IAAIE,CAAAA,CAA6B,EAC7BC,CAAAA,CAAAA,CAAuC,EACvCC,CAAAA,CAAAA,CAAgB,MAEb,SAASC,CAAAA,CAAUC,CAAgB,CAAA,CACxC,OAAOH,CAAOG,CAAAA,CAAG,GAAG,KACtB,CAEO,SAASC,CAAmB,EAAA,CACjC,GAAI,CAACH,EACH,MAAM,IAAI,MAAM,0FAA0F,CAAA,CAG5G,OAAO,MAAO,CAAA,WAAA,CACZ,OAAO,OAAQD,CAAAA,CAAM,EAAE,MAAO,CAAA,CAAC,CAACG,CAAG,CAAA,GAAMJ,EAAaI,CAAG,CAAA,EAAG,QAAQ,CACtE,CACF,CAEO,SAASE,EAAYC,CAAsB,CAAA,CAChDA,EAAQ,OAAQ,CAAA,CAAC,CAAE,GAAA,CAAAH,EAAK,IAAAI,CAAAA,CAAAA,CAAM,MAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBL,CAAAA,CAAI,WAAY,EAAA,CAAE,WAAW,UAAU,CAAA,EAEvC,CAACJ,C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A+B,CACtC,IAAMpP,CAAuB,CAAA,EAE7B,CAAA,OAAI,OAAQ,CAAA,GAAA,CAAI,WACdA,EAAAA,CAAAA,CAAQ,IAAK,CAAA,CACX,GAAK,CAAA,oBAAA,CACL,IAAM,CAAA,QAAA,CACN,KAAO,CAAA,OAAA,CAAQ,GAAI,CAAA,WACrB,CAAC,CAAA,CAGIA,CACT","file":"server.js","sourcesContent":["export function isServer() {\n return typeof window !== 'object';\n}\n\nexport function requireServer() {\n if (!isServer()) {\n throw new Error('This function can only be called on the server');\n }\n}\n","import { ConfigKey, AppConfig, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error('Config is not initialized: an attempt was made to access configs before they were loaded');\n }\n\n return Object.fromEntries(\n Object.entries(config).filter(([key]) => configSchema[key]?.isPublic)\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value\n };\n });\n\n isInitialized = true;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (key.toLowerCase().startsWith('_system.')) {\n throw new Error(`Config key cannot start with a reserved prefix: '_system.' (${key})`);\n }\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","import { getLogger } from './metrics';\n\nexport function logInfo(message: string, args: object) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (isTelemetryEnabled) {\n getLogger().info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (isTelemetryEnabled) {\n getLogger().error(message, args);\n }\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from './logs';\nimport process from 'process';\n\ntype LogEntry = { log: string, timestamp: Date | null, sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer, stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }]\n}\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({ elasticCloudId, elasticApiKey }: { elasticCloudId: string, elasticApiKey: string }) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n process.stdout.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n process.stderr.write = function(chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\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 await initElasticApm();\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticSecretToken = getConfig('_system.elastic.secretToken') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n apm = elasticApm.start({\n serviceName: 'typesonic',\n secretToken: elasticSecretToken,\n serverUrl: elasticApmEndpoint,\n environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\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 format: winston.format.combine(\n winston.format.json(),\n ),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport\n ]\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey\n });\n}\n\nexport function startTransaction(type: 'method' | 'cron', name: string, context?: Record<string, any>) {\n const isTelemetryEnabled = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n\n if (!isTelemetryEnabled) {\n return {\n end: () => {\n // do nothing\n }\n };\n }\n\n if (!apm) {\n throw new Error('startTransaction: Elastic APM is not initialized');\n }\n\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n return transaction;\n}\n\nexport function captureError(error: Error) {\n if (!apm) {\n throw new Error('captureError: Elastic APM is not initialized');\n }\n\n apm.captureError(error);\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { RoleDefinition, Role, DefaultRoles, Permission } from './types';\n\nconst roleMap = new Map<Role, RoleDefinition>();\nconst defaultRoles: DefaultRoles = {\n authenticated: null,\n unauthenticated: null,\n};\n\nexport function initRoles(roles: Record<Role, RoleDefinition>, _defaultRoles: Record<string, Role>) {\n defaultRoles.authenticated = _defaultRoles.authenticated;\n defaultRoles.unauthenticated = _defaultRoles.unauthenticated;\n\n for (const [name, definition] of Object.entries(roles)) {\n roleMap.set(name, definition);\n }\n}\n\nexport function getUnauthenticatedRoles() {\n return defaultRoles.unauthenticated ? [defaultRoles.unauthenticated] : [];\n}\n\nexport function getDefaultAuthenticatedRoles() {\n return defaultRoles.authenticated ? [defaultRoles.authenticated] : [];\n}\n\nexport function hasAccess(roles: Role[], requiredPermissions: Permission[]) {\n return requiredPermissions.every(permission => hasPermission(roles, permission));\n}\n\nexport function requireAccess(roles: Role[], requiredPermissions: Permission[]) {\n const missingPermission = requiredPermissions.find(permission => !hasPermission(roles, permission));\n\n if (missingPermission) {\n throw new Error(`Access denied - missing permission: '${missingPermission}'`);\n }\n}\n\nexport function hasPermission(roles: Role[], permission: Permission) {\n for (const role of roles) {\n const definition = roleMap.get(role);\n\n if (definition && definition.permissions.includes(permission)) {\n return true;\n }\n }\n\n return false;\n}\n","import { requireServer } from '../utils';\nimport { startTransaction } from '../app/metrics';\nimport { requireAccess } from '../auth/role';\nimport { Method, MethodDefinition, MethodType, Args, Context } from './types';\n\nconst methods: Record<string, Method<any>> = {};\n\nexport function createQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function createMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nexport function _createSystemQuery<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('query', name, methodDef);\n}\n\nexport function _createSystemMutation<T extends any[]>(name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n validateSystemMethodName(name);\n return _createMethodInternal('mutation', name, methodDef);\n}\n\nfunction validateMethodName(name: string) {\n if (name.toLowerCase().startsWith('_system.')) {\n throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${name})`);\n }\n}\n\nfunction validateSystemMethodName(name: string) {\n if (!name.toLowerCase().startsWith('_system.')) {\n throw new Error(`System method name must start with a prefix: '_system.' (${name})`);\n }\n}\n\nfunction _createMethodInternal<T extends any>(type: MethodType, name: string, methodDef: MethodDefinition<T>) {\n requireServer();\n\n if (methods[name]) {\n throw new Error(`Method with name '${name}' is already defined.`);\n }\n\n const handler = typeof methodDef === 'function' ? methodDef : methodDef.handler;\n const permissions = typeof methodDef === 'function' ? [] : methodDef.permissions ?? [];\n methods[name] = { type, name, handler, permissions };\n}\n\nexport async function runMethod(name: string, args: Args, context: Context) {\n requireServer();\n\n const method = methods[name];\n if (!method) {\n throw new Error(`Method with name '${name}' is not defined.`);\n }\n const { type, handler } = method;\n\n const transaction = startTransaction('method', `method:${name}`, { type, args });\n\n let response;\n try {\n requireAccess(context.roles, method.permissions);\n response = await handler(args, context);\n } catch (error) {\n // TODO: log error and associate it with the transaction\n transaction.end('error');\n throw error;\n }\n\n transaction.end();\n\n return response;\n}\n","import { ConfigSchema } from '../config/types';\nimport { CronJobInputParams } from '../cron/types';\nimport { Store } from '../data/store';\nimport { MethodDefinition } from '../methods/types';\nimport { RouteDefinition } from '../routes/types';\n\ntype Stores = Store<any, any>[];\ntype Queries = Record<string, MethodDefinition<any>>;\ntype Mutations = Record<string, MethodDefinition<any>>;\n\nexport class Module {\n public readonly name: string;\n public readonly stores: Stores;\n public readonly queries: Queries;\n public readonly mutations: Mutations;\n public readonly routes: RouteDefinition[];\n public readonly cronJobs: Record<string, CronJobInputParams>;\n public readonly configSchema: ConfigSchema;\n\n constructor(\n name: string,\n { \n stores = [], \n queries = {}, \n mutations = {},\n routes = [],\n cronJobs = {},\n configSchema = {}\n }: { \n stores?: Stores, \n queries?: Queries, \n mutations?: Mutations,\n routes?: RouteDefinition[],\n cronJobs?: Record<string, CronJobInputParams>,\n configSchema?: ConfigSchema\n }\n ) {\n this.name = name;\n this.stores = stores;\n this.queries = queries;\n this.mutations = mutations;\n this.routes = routes;\n this.cronJobs = cronJobs;\n this.configSchema = configSchema;\n }\n}\n","import {\n AggregateOptions,\n AggregationCursor,\n Collection,\n DeleteResult,\n Document,\n IndexDescription,\n InsertOneResult,\n MongoClient,\n UpdateResult,\n Filter,\n WithId,\n OptionalUnlessRequiredId,\n FindOptions,\n UpdateFilter,\n ObjectId,\n BulkWriteResult,\n AnyBulkWriteOperation,\n InsertManyResult,\n} from 'mongodb';\n\nimport { ModelSchema, InferDocumentType } from './types';\n\n/**\n * The Store class provides a type-safe interface for MongoDB collections with built-in schema validation and helper methods.\n * \n * @category Store\n * @typeParam TSchema - The document schema type\n * @typeParam TMethods - Custom methods that will be added to documents\n * \n * @example\n * ```ts\n * const dbTodos = new Store('todos', {\n * schema: {\n * title: schema.string(),\n * completed: schema.boolean(),\n * dueDate: schema.date().optional(),\n * userId: schema.userId(),\n * },\n * methods: {\n * isOverdue() {\n * return this.dueDate < new Date();\n * }\n * }\n * });\n * ```\n */\nexport class Store<\n TSchema extends ModelSchema,\n TMethods extends Record<string, (this: InferDocumentType<TSchema> & TMethods, ...args: Parameters<any>) => any>\n> {\n /** @internal */\n readonly _type!: InferDocumentType<TSchema>;\n /** @internal */\n readonly _rawDoc!: WithId<this['_type']>;\n /** @internal */\n readonly _doc!: this['_rawDoc'] & TMethods & Record<string, never>;\n \n readonly Doc!: this['_doc'];\n\n private readonly name: string;\n private readonly schema: TSchema;\n private readonly methods?: TMethods;\n private readonly indexes: IndexDescription[];\n private collection?: Collection<this['_type']>;\n\n /**\n * Creates a new Store instance\n * \n * @param name - The collection name in MongoDB\n * @param options - Store configuration\n */\n constructor(\n name: string,\n options: {\n /** Document schema using Modelence schema types */\n schema: TSchema;\n /** Custom methods to add to documents */\n methods?: TMethods;\n /** MongoDB indexes to create */\n indexes: IndexDescription[];\n }\n ) {\n this.name = name;\n this.schema = options.schema;\n this.methods = options.methods;\n this.indexes = options.indexes;\n }\n\n getName() {\n return this.name;\n }\n\n /** @internal */\n getSchema() {\n return this.schema;\n }\n\n /** @internal */\n provision(client: MongoClient) {\n if (this.collection) {\n return;\n }\n\n this.collection = client.db().collection<this['_type']>(this.name);\n if (this.indexes.length > 0) {\n this.collection.createIndexes(this.indexes);\n }\n }\n\n private wrapDocument(document: this['_rawDoc']): this['_doc'] {\n if (!this.methods) {\n return document as this['_doc'];\n }\n\n const result = Object.create(\n null,\n Object.getOwnPropertyDescriptors({\n ...document,\n ...this.methods\n })\n );\n\n return result as this['_doc'];\n }\n\n /** @internal */\n requireCollection() {\n if (!this.collection) {\n throw new Error(`Collection ${this.name} is not provisioned`);\n }\n\n return this.collection;\n }\n\n async findOne(\n query: Filter<this['_type']>, \n options?: FindOptions\n ) {\n const document = await this.requireCollection().findOne<this['_rawDoc']>(query, options);\n return document ? this.wrapDocument(document) : null;\n }\n\n async requireOne(\n query: Filter<this['_type']>, \n options?: FindOptions,\n errorHandler?: () => Error\n ): Promise<this['_doc']> {\n \n const result = await this.findOne(query, options);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record not found in ${this.name}`);\n }\n return result;\n }\n\n private find(query: Filter<this['_type']>, options?: { sort?: Document }) {\n const cursor = this.requireCollection().find(query);\n if (options?.sort) {\n cursor.sort(options.sort);\n }\n return cursor;\n }\n\n /**\n * Fetches a single document by its ID\n * \n * @param id - The ID of the document to find\n * @returns The document, or null if not found\n */\n async findById(id: string | ObjectId): Promise<this['_doc'] | null> {\n const idSelector = typeof id === 'string' ? { _id: new ObjectId(id) } : { _id: id };\n return await this.findOne(idSelector as Filter<this['_type']>);\n }\n\n /**\n * Fetches a single document by its ID, or throws an error if not found\n * \n * @param id - The ID of the document to find\n * @param errorHandler - Optional error handler to return a custom error if the document is not found\n * @returns The document\n */\n async requireById(id: string | ObjectId, errorHandler?: () => Error): Promise<this['_doc']> {\n const result = await this.findById(id);\n if (!result) {\n throw errorHandler ? errorHandler() : new Error(`Record with id ${id} not found in ${this.name}`);\n }\n return result;\n }\n\n /**\n * Fetches multiple documents, equivalent to Node.js MongoDB driver's `find` and `toArray` methods combined.\n * \n * @param query - The query to filter documents\n * @param options - Optional options\n * @returns The documents\n */\n async fetch(query: Filter<this['_type']>, options?: { sort?: Document }): Promise<this['_doc'][]> {\n const cursor = this.find(query, options)\n return (await cursor.toArray()).map(this.wrapDocument.bind(this));\n }\n\n /**\n * Inserts a single document\n * \n * @param document - The document to insert\n * @returns The result of the insert operation\n */\n async insertOne(document: OptionalUnlessRequiredId<this['_type']>): Promise<InsertOneResult> {\n return await this.requireCollection().insertOne(document);\n }\n\n /**\n * Inserts multiple documents\n * \n * @param documents - The documents to insert\n * @returns The result of the insert operation\n */\n async insertMany(documents: OptionalUnlessRequiredId<this['_type']>[]): Promise<InsertManyResult> {\n return await this.requireCollection().insertMany(documents);\n }\n\n /**\n * Updates a single document\n * \n * @param selector - The selector to find the document to update\n * @param update - The update to apply to the document\n * @returns The result of the update operation\n */\n async updateOne(selector: Filter<this['_type']> | string, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n const modifiedSelector = typeof selector === 'string' \n ? { _id: new ObjectId(selector) } as Filter<this['_type']>\n : selector;\n return await this.requireCollection().updateOne(modifiedSelector, update);\n }\n\n /**\n * Updates a single document, or inserts it if it doesn't exist\n * \n * @param selector - The selector to find the document to update\n * @param update - The MongoDB modifier to apply to the document\n * @returns The result of the update operation\n */\n async upsertOne(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateOne(selector, update, { upsert: true });\n }\n\n /**\n * Updates multiple documents\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async updateMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update);\n }\n\n /**\n * Updates multiple documents, or inserts them if they don't exist\n * \n * @param selector - The selector to find the documents to update\n * @param update - The MongoDB modifier to apply to the documents\n * @returns The result of the update operation\n */\n async upsertMany(selector: Filter<this['_type']>, update: UpdateFilter<this['_type']>): Promise<UpdateResult> {\n return await this.requireCollection().updateMany(selector, update, { upsert: true });\n }\n\n /**\n * Deletes a single document\n * \n * @param selector - The selector to find the document to delete\n * @returns The result of the delete operation\n */\n async deleteOne(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteOne(selector);\n }\n\n /**\n * Deletes multiple documents\n * \n * @param selector - The selector to find the documents to delete\n * @returns The result of the delete operation\n */\n async deleteMany(selector: Filter<this['_type']>): Promise<DeleteResult> {\n return await this.requireCollection().deleteMany(selector);\n }\n\n /**\n * Aggregates documents using MongoDB's aggregation framework\n * \n * @param pipeline - The aggregation pipeline\n * @param options - Optional options\n * @returns The aggregation cursor\n */\n aggregate(pipeline: Document[], options?: AggregateOptions): AggregationCursor<Document> {\n return this.requireCollection().aggregate(pipeline, options);\n }\n\n /**\n * Performs a bulk write operation on the collection\n * \n * @param operations - The operations to perform\n * @returns The result of the bulk write operation\n */\n bulkWrite(operations: AnyBulkWriteOperation<this['_type']>[]): Promise<BulkWriteResult> {\n return this.requireCollection().bulkWrite(operations);\n }\n}\n","import { ObjectId } from 'mongodb';\nimport { z } from 'zod';\nimport { Store } from './store';\n\ntype ObjectTypeDefinition = {\n [key: string]: SchemaTypeDefinition;\n};\n\ntype SingularSchemaTypeDefinition = z.ZodType | ObjectTypeDefinition; // ReturnType<typeof schema[keyof typeof schema]>;\n\ntype SchemaTypeDefinition = SingularSchemaTypeDefinition | Array<SingularSchemaTypeDefinition>;\n\nexport type ModelSchema = {\n [key: string]: SchemaTypeDefinition;\n};\n\nconst schemaString: typeof z.string = z.string.bind(z);\n\nconst schemaNumber: typeof z.number = z.number.bind(z);\n\nconst schemaDate: typeof z.date = z.date.bind(z);\n\nconst schemaBoolean: typeof z.boolean = z.boolean.bind(z);\n\nconst schemaArray: typeof z.array = z.array.bind(z);\n\nconst schemaObject: typeof z.object = z.object.bind(z);\n\nconst schemaEnum: typeof z.enum = z.enum.bind(z);\n\nexport const schema = {\n string: schemaString,\n number: schemaNumber,\n date: schemaDate,\n boolean: schemaBoolean,\n array: schemaArray,\n object: schemaObject,\n enum: schemaEnum,\n objectId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n userId(): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n ref(collection: string | Store<any, any>): z.ZodType<ObjectId> {\n return z.instanceof(ObjectId);\n },\n union: z.union.bind(z),\n infer<T extends SchemaTypeDefinition>(schema: T): InferDocumentType<T> {\n return {} as InferDocumentType<T>;\n }\n} as const;\n\nexport type InferDocumentType<T extends SchemaTypeDefinition> = {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? K : never]?: (T[K] extends z.ZodType ? z.infer<T[K]> : never);\n} & {\n [K in keyof T as T[K] extends z.ZodOptional<any> ? never : K]:\n T[K] extends z.ZodType ? z.infer<T[K]> :\n T[K] extends Array<infer ElementType extends SchemaTypeDefinition> ? Array<InferDocumentType<ElementType>> :\n T[K] extends ObjectTypeDefinition ? InferDocumentType<T[K]> :\n never;\n};\n\nexport namespace schema {\n export type infer<T extends SchemaTypeDefinition> = InferDocumentType<T>;\n}\n","import { randomBytes } from 'crypto';\nimport { time } from '../time';\nimport { Session } from './types';\nimport { getPublicConfigs } from '../config/server';\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { ObjectId } from 'mongodb';\n\nexport const sessionsCollection = new Store('_modelenceSessions', {\n schema: {\n authToken: schema.string(),\n createdAt: schema.date(),\n expiresAt: schema.date(),\n userId: schema.userId().nullable(),\n },\n indexes: [\n { key: { authToken: 1 }, unique: true },\n { key: { expiresAt: 1 }},\n ]\n // TODO: add TTL index on expiresAt\n});\n\nexport async function obtainSession(authToken: string | null): Promise<Session> {\n const existingSession = authToken ? await sessionsCollection.findOne({ authToken }) : null;\n\n if (existingSession) {\n return {\n authToken: String(existingSession.authToken),\n expiresAt: new Date(existingSession.expiresAt),\n userId: existingSession.userId ?? null,\n }\n }\n\n return await createSession();\n}\n\nexport async function setSessionUser(authToken: string, userId: ObjectId) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId }\n });\n}\n\nexport async function clearSessionUser(authToken: string) {\n await sessionsCollection.updateOne({ authToken }, {\n $set: { userId: null }\n });\n}\n\nasync function createSession(): Promise<Session> {\n // TODO: add rate-limiting and captcha handling\n\n const authToken = randomBytes(32).toString('base64url');\n const now = Date.now();\n const expiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.insertOne({\n authToken,\n createdAt: new Date(now),\n expiresAt,\n userId: null,\n });\n\n return {\n authToken,\n expiresAt,\n userId: null,\n };\n}\n\nasync function processSessionHeartbeat(session: Session) {\n const now = Date.now();\n const newExpiresAt = new Date(now + time.days(7));\n\n await sessionsCollection.updateOne({ authToken: session.authToken }, {\n $set: {\n lastActiveDate: new Date(now),\n expiresAt: newExpiresAt\n }\n });\n}\n\nexport default new Module('_system.session', {\n stores: [sessionsCollection],\n mutations: {\n init: async function(args, { session, user }) {\n // TODO: mark or track app load somewhere\n \n return {\n session,\n user,\n configs: getPublicConfigs(),\n };\n },\n heartbeat: async function(args, { session }) {\n // Session might not exist if there is no database/authentication setup\n if (session) {\n await processSessionHeartbeat(session);\n }\n }\n },\n});\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\n\nexport async function handleSignupWithPassword(args: Args, { user }: Context) {\n const email = z.string().email().parse(args.email);\n const password = z.string()\n .min(8, { message: 'Password must contain at least 8 characters' })\n .parse(args.password);\n\n // TODO: block disposable email providers\n // TODO: captcha check\n // TODO: rate limiting\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const existingUser = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n if (existingUser) {\n const existingEmail = existingUser.emails?.find(e => e.address === email);\n throw new Error(`User with email already exists: ${existingEmail?.address}`);\n }\n\n // Hash password with bcrypt (salt is automatically generated)\n const hash = await bcrypt.hash(password, 10);\n\n const result = await usersCollection.insertOne({\n handle: email,\n emails: [{\n address: email,\n verified: false,\n }],\n createdAt: new Date(),\n authMethods: {\n password: {\n hash,\n }\n }\n });\n\n // TODO: send verification email\n\n return result.insertedId;\n}\n\n","import { z } from 'zod';\nimport bcrypt from 'bcrypt';\n\nimport { Args, Context } from '../methods/types';\nimport { usersCollection } from './user';\nimport { clearSessionUser, setSessionUser } from './session';\n\nexport async function handleLoginWithPassword(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n const email = z.string().email().parse(args.email);\n const password = z.string().parse(args.password);\n\n // TODO: add rate limiting by email (and perhaps IP address overall)\n\n if (user) {\n // TODO: handle cases where a user is already logged in\n }\n\n const userDoc = await usersCollection.findOne(\n { 'emails.address': email },\n { collation: { locale: 'en', strength: 2 } }\n );\n\n const passwordHash = userDoc?.authMethods?.password?.hash;\n if (!userDoc || !passwordHash) {\n throw incorrectCredentialsError();\n }\n\n const isValidPassword = await bcrypt.compare(password, passwordHash);\n if (!isValidPassword) {\n throw incorrectCredentialsError();\n }\n\n await setSessionUser(session.authToken, userDoc._id);\n\n return {\n user: {\n id: userDoc._id,\n handle: userDoc.handle,\n }\n }\n}\n\nexport async function handleLogout(args: Args, { user, session }: Context) {\n if (!session) {\n throw new Error('Session is not initialized');\n }\n\n await clearSessionUser(session.authToken);\n}\n\n/*\n It is important to return the same exact error both in case the email\n or password is incorrect so that the client cannot tell the difference,\n otherwise it would allow for an enumeration attack.\n*/\nfunction incorrectCredentialsError() {\n return new Error('Incorrect email/password combination');\n}\n","import { randomBytes } from 'crypto';\n\nimport { Module } from '../app/module';\nimport { Store } from '../data/store';\nimport { schema } from '../data/types';\nimport { handleSignupWithPassword } from './signup';\nimport { handleLoginWithPassword, handleLogout } from './login';\n\nexport const usersCollection = new Store('_modelenceUsers', {\n schema: {\n handle: schema.string(),\n emails: schema.array(schema.object({\n address: schema.string(),\n verified: schema.boolean(),\n })).optional(),\n createdAt: schema.date(),\n authMethods: schema.object({\n password: schema.object({\n hash: schema.string(),\n }).optional(),\n google: schema.object({\n id: schema.string(),\n }).optional(),\n }),\n },\n indexes: [\n {\n key: { handle: 1 },\n unique: true,\n collation: { locale: 'en', strength: 2 } // Case-insensitive\n },\n ]\n});\n\nasync function createGuestUser() {\n // TODO: add rate-limiting and captcha handling\n\n const guestId = randomBytes(9)\n .toString('base64')\n .replace(/[+/]/g, c => c === '+' ? 'a' : 'b');\n\n const handle = `guest_${guestId}`;\n // TODO: re-try on handle collision\n\n const result = await usersCollection.insertOne({\n handle,\n createdAt: new Date(),\n authMethods: {},\n });\n\n return result.insertedId;\n}\n\nexport default new Module('_system.user', {\n stores: [usersCollection],\n mutations: {\n signupWithPassword: handleSignupWithPassword,\n loginWithPassword: handleLoginWithPassword,\n logout: handleLogout,\n }\n});\n\n","import { ObjectId } from 'mongodb';\n\nimport { obtainSession } from './session';\nimport { usersCollection } from './user';\nimport { getDefaultAuthenticatedRoles, getUnauthenticatedRoles } from './role';\nimport { Role, Session, UserInfo } from './types';\n\nexport async function authenticate(authToken: string | null): Promise<{ session: Session, user: UserInfo | null, roles: Role[] }> {\n const session = await obtainSession(authToken);\n\n const userDoc = session.userId ? await usersCollection.findOne({ _id: new ObjectId(session.userId) }) : null;\n const user = userDoc ? {\n id: userDoc._id.toString(),\n handle: userDoc.handle,\n } : null;\n\n const roles = user ? getDefaultAuthenticatedRoles() : getUnauthenticatedRoles();\n\n return {\n user,\n session,\n roles,\n };\n}\n","import { createServer, defineConfig } from 'vite';\nimport reactPlugin from '@vitejs/plugin-react';\nimport path from 'path';\nimport fs from 'fs';\nimport express from 'express';\n\nexport async function initViteServer(app: express.Application, isDev: boolean) {\n if (isDev) {\n console.log('Starting Vite dev server...');\n const vite = await createServer({\n ...defineConfig(await getConfig()),\n server: {\n middlewareMode: true,\n },\n root: './src/client'\n });\n \n app.use(vite.middlewares);\n \n app.use('*', async (req: express.Request, res: express.Response) => {\n try {\n res.sendFile('index.html', { root: './src/client' });\n } catch (e) {\n console.error('Error serving index.html:', e);\n res.status(500).send('Internal Server Error');\n }\n });\n } else {\n app.use(express.static('.modelence/client'));\n app.get('*', (req, res) => {\n res.sendFile('index.html', { root: '.modelence/client' });\n });\n }\n}\n\nasync function getConfig() {\n const appDir = process.cwd();\n\n const eslintConfigFile = [\n '.eslintrc.js',\n '.eslintrc.json',\n '.eslintrc',\n 'eslint.config.js',\n '.eslintrc.yml',\n '.eslintrc.yaml'\n ].find(file => fs.existsSync(path.join(appDir, file)));\n\n const plugins = [reactPlugin(), modelenceAssetPlugin()];\n\n if (eslintConfigFile) {\n const eslintPlugin = (await import('vite-plugin-eslint')).default;\n plugins.push(\n eslintPlugin({\n failOnError: false,\n include: ['src/**/*.js', 'src/**/*.jsx', 'src/**/*.ts', 'src/**/*.tsx'],\n cwd: appDir,\n overrideConfigFile: path.resolve(appDir, eslintConfigFile)\n })\n );\n }\n\n return {\n plugins,\n root: appDir,\n build: {\n outDir: '.modelence/client',\n emptyOutDir: true\n },\n server: {\n proxy: {\n '/api': 'http://localhost:4000'\n },\n headers: {\n 'Cache-Control': 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0',\n 'Pragma': 'no-cache',\n 'Expires': '0'\n },\n hmr: {\n port: 0,\n },\n },\n resolve: {\n alias: {\n '@': path.resolve(appDir, 'src')\n }\n\n }\n };\n}\n\nfunction modelenceAssetPlugin() {\n return {\n name: 'modelence-asset-handler',\n async transform(code: string, id: string) {\n const assetRegex = /\\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/;\n if (assetRegex.test(id)) {\n if (process.env.NODE_ENV === 'development') {\n return code;\n }\n // TODO: Upload to CDN\n // return `export default \"${cdnUrl}\"`;\n return code;\n }\n },\n async generateBundle(options: any, bundle: any) {\n // Handle asset URLs in the final bundle\n }\n };\n}\n","import { Request, Response } from 'express';\nimport { RouteHandler, ExpressHandler } from './types';\n\n// TODO: Use cookies for authentication and automatically add session/user to context if accessing from browser\n\nexport function createRouteHandler(handler: RouteHandler): ExpressHandler {\n return async (req: Request, res: Response) => {\n try {\n const response = await handler({\n query: req.query as Record<string, string>,\n body: req.body,\n params: req.params,\n headers: req.headers as Record<string, string>,\n cookies: req.cookies\n });\n\n res.status(response.status || 200);\n\n if (response.headers) {\n Object.entries(response.headers).forEach(([key, value]) => {\n res.setHeader(key, value);\n });\n }\n\n res.send(response.data);\n } catch (error) {\n res.status(500).send(String(error));\n }\n };\n}\n","import { MongoClient, ServerApiVersion } from 'mongodb';\nimport { getConfig } from '../config/server';\n\nlet client: MongoClient | null = null;\n\nexport async function connect() {\n if (client) return client;\n\n const mongodbUri = getMongodbUri();\n if (!mongodbUri) {\n throw new Error('MongoDB URI is not set');\n }\n\n client = new MongoClient(mongodbUri, {\n serverApi: {\n version: ServerApiVersion.v1,\n strict: true,\n deprecationErrors: true,\n },\n maxPoolSize: 20\n });\n\n try {\n // Connect the client to the server\n await client.connect();\n // Send a ping to confirm a successful connection\n await client.db(\"admin\").command({ ping: 1 });\n console.log(\"Pinged your deployment. You successfully connected to MongoDB!\");\n return client;\n } catch (err) {\n console.error(err);\n client = null;\n throw err;\n }\n}\n\nexport function getMongodbUri() {\n const value = getConfig('_system.mongodbUri');\n return value ? String(value) : undefined;\n}\n\nexport function getClient() {\n return client;\n}\n\n// export async function closeConnection() {\n// if (client) {\n// await client.close();\n// client = null;\n// }\n// }\n","import http from 'http';\nimport express, { Request, Response } from 'express';\nimport z from 'zod';\nimport { runMethod } from '../methods';\nimport { getResponseTypeMap } from '../methods/serialize';\nimport { authenticate } from '../auth';\nimport { logInfo } from './logs';\nimport { initViteServer } from '../viteServer';\nimport { Module } from './module';\nimport { HttpMethod } from '../routes/types';\nimport { createRouteHandler } from '../routes/handler';\nimport { getUnauthenticatedRoles } from '../auth/role';\nimport { getMongodbUri } from 'db/client';\n\nfunction registerModuleRoutes(app: express.Application, modules: Module[]) {\n for (const module of modules) {\n for (const route of module.routes) {\n const { path, handlers } = route;\n\n Object.entries(handlers).forEach(([method, handler]) => {\n app[method as HttpMethod](path, createRouteHandler(handler));\n });\n }\n }\n}\n\nexport async function startServer({ combinedModules }: { combinedModules: Module[] }) {\n const app = express();\n const isDev = process.env.NODE_ENV !== 'production';\n\n app.use(express.json());\n app.use(express.urlencoded({ extended: true }));\n\n app.post('/api/_internal/method/:methodName', async (req: Request, res: Response) => {\n const { methodName } = req.params;\n const context = await getCallContext(req);\n\n try {\n const result = await runMethod(methodName, req.body.args, context);\n res.json({\n data: result,\n typeMap: getResponseTypeMap(result),\n });\n } catch (error) {\n // TODO: introduce error codes and handle them differently\n // TODO: support multiple errors\n\n // TODO: add an option to silence these error console logs, especially when Elastic logs are configured\n console.error(`Error in method ${methodName}:`, error);\n\n // res.status(500).json({ error: 'Internal server error' });\n\n if (error instanceof Error && error?.constructor?.name === 'ZodError' && 'errors' in error) {\n const zodError = error as z.ZodError;\n const flattened = zodError.flatten();\n const fieldMessages = Object.entries(flattened.fieldErrors)\n .map(([key, errors]) => `${key}: ${(errors ?? []).join(', ')}`)\n .join('; ');\n const formMessages = flattened.formErrors.join('; ');\n const allMessages = [fieldMessages, formMessages].filter(Boolean).join('; ');\n res.status(400).send(allMessages);\n } else {\n res.status(500).send(error instanceof Error ? error.message : String(error));\n }\n }\n });\n\n registerModuleRoutes(app, combinedModules);\n\n await initViteServer(app, isDev);\n\n process.on('unhandledRejection', (reason, promise) => {\n console.error('Unhandled Promise Rejection:');\n console.error(reason instanceof Error ? reason.stack : reason);\n console.error('Promise:', promise);\n });\n \n // Global uncaught exceptions\n process.on('uncaughtException', (error) => {\n console.error('Uncaught Exception:');\n console.error(error.stack); // This gives you the full stack trace\n console.trace('Full application stack:'); // Additional context\n });\n\n const server = http.createServer(app);\n const port = process.env.PORT || 3000;\n server.listen(port, () => {\n logInfo(`Application started`, { source: 'app' });\n console.log(`Application started on port ${port}`);\n });\n}\n\nasync function getCallContext(req: Request) {\n const authToken = z.string().nullish().transform(val => val ?? null).parse(req.body.authToken);\n\n const clientInfo = z.object({\n screenWidth: z.number(),\n screenHeight: z.number(),\n windowWidth: z.number(),\n windowHeight: z.number(),\n pixelRatio: z.number(),\n orientation: z.string().nullable(),\n }).parse(req.body.clientInfo);\n\n const connectionInfo = {\n ip: req.ip || req.socket.remoteAddress, // TODO: handle cases with Proxy\n userAgent: req.get('user-agent'),\n acceptLanguage: req.get('accept-language'),\n referrer: req.get('referrer'),\n };\n\n const hasDatabase = Boolean(getMongodbUri());\n if (hasDatabase) {\n const { session, user, roles } = await authenticate(authToken);\n return {\n clientInfo,\n connectionInfo,\n session,\n user,\n roles,\n };\n }\n\n return {\n clientInfo,\n connectionInfo,\n session: null,\n user: null,\n roles: getUnauthenticatedRoles(),\n };\n}\n\n// import passport from 'passport';\n// import session from 'express-session';\n// import { Strategy as GoogleStrategy } from 'passport-google-oauth20';\n\n// Session middleware\n// app.use(session({\n// secret: process.env.SESSION_SECRET || 'default_secret',\n// resave: false,\n// saveUninitialized: false\n// }));\n\n// Passport middleware\n// app.use(passport.initialize());\n// app.use(passport.session());\n\n// // Passport Google strategy setup\n// passport.use(new GoogleStrategy({\n// clientID: process.env.GOOGLE_CLIENT_ID || '',\n// clientSecret: process.env.GOOGLE_CLIENT_SECRET || '',\n// callbackURL: \"/auth/google/callback\"\n// },\n// function(accessToken: string, refreshToken: string, profile: any, cb: (error: any, user?: any) => void) {\n// // Here you would typically find or create a user in your database\n// // For now, we'll just pass the profile info\n// return cb(null, profile);\n// }));\n\n// passport.serializeUser((user: Express.User, done: (err: any, id?: unknown) => void) => {\n// done(null, user);\n// });\n\n// passport.deserializeUser((user: Express.User, done: (err: any, user?: Express.User | false | null) => void) => {\n// done(null, user);\n// });\n\n// // Google Auth routes\n// app.get('/auth/google', passport.authenticate('google', { scope: ['profile', 'email'] }));\n\n// app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }),\n// function(req: Request, res: Response) {\n// // Successful authentication, redirect home.\n// res.redirect('/');\n// }\n// );\n\n// // Logout route\n// app.get('/logout', (req: Request, res: Response, next: NextFunction) => {\n// req.logout(function(err) {\n// if (err) { return next(err); }\n// res.redirect('/');\n// });\n// });\n\n// // Middleware to check if user is authenticated\n// function ensureAuthenticated(req: Request, res: Response, next: NextFunction) {\n// if (req.isAuthenticated()) {\n// return next();\n// }\n// res.redirect('/login');\n// }\n\n\n// app.get('/bundle.js', function (req: Request, res: Response) {\n// res.sendFile('.modelence/client/bundle.js', { root: '.' });\n// });\n\n\n// // Update your catch-all route\n// app.get('/', function (req: Request, res: Response) {\n// res.sendFile(path.join('client', 'index.html'), { root: path.join(__dirname, '..') });\n// });\n\n\n","import os from 'os';\nimport { ConfigSchema } from '../config/types';\nimport { CronJobMetadata } from '../cron/types';\nimport { Store } from '../data/store';\n\nexport async function connectCloudBackend(\n { configSchema, cronJobsMetadata, stores }: { \n configSchema?: ConfigSchema, \n cronJobsMetadata?: CronJobMetadata[], \n stores: Store<any, any>[] \n }\n) {\n const containerId = process.env.MODELENCE_CONTAINER_ID;\n if (!containerId) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set');\n }\n\n try {\n const dataModels = Object.values(stores).map(store => {\n return {\n name: store.getName(),\n schema: store.getSchema(),\n collections: [store.getName()]\n };\n });\n\n const data = await callApi('/api/connect', 'POST', {\n hostname: os.hostname(),\n containerId,\n dataModels,\n configSchema,\n cronJobsMetadata,\n });\n\n console.log('Successfully connected to Modelence Cloud');\n\n return data;\n } catch (error) {\n console.error('Unable to connect to Modelence Cloud:', error);\n throw error;\n }\n}\n\nexport async function fetchConfigs() {\n const data = await callApi('/api/configs', 'GET');\n return data;\n}\n\nexport async function syncStatus() {\n const data = await callApi('/api/sync', 'POST', {\n containerId: process.env.MODELENCE_CONTAINER_ID\n });\n return data;\n}\n\nasync function callApi(endpoint: string, method: string, payload?: object) {\n const { MODELENCE_SERVICE_ENDPOINT, MODELENCE_SERVICE_TOKEN } = process.env;\n\n if (!MODELENCE_SERVICE_ENDPOINT) {\n throw new Error('Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set');\n }\n\n const response = await fetch(`${MODELENCE_SERVICE_ENDPOINT}${endpoint}`, {\n method,\n headers: {\n 'Authorization': `Bearer ${MODELENCE_SERVICE_TOKEN}`,\n ...(payload ? { 'Content-Type': 'application/json' } : {})\n },\n body: payload ? JSON.stringify(payload) : undefined\n });\n\n if (!response.ok) {\n const data = await response.text();\n try {\n const json = JSON.parse(data);\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${json?.error}`);\n } catch (error) {\n throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${response.status}, ${data}`);\n }\n }\n\n return await response.json();\n}\n","import { time } from '../time';\nimport { fetchConfigs, syncStatus } from '../app/backendApi';\nimport { loadConfigs } from './server';\n\nlet isSyncing = false;\n\nconst SYNC_INTERVAL = time.seconds(10);\n\nexport function startConfigSync() {\n setInterval(async() => {\n if (isSyncing) {\n return;\n }\n \n isSyncing = true;\n\n // TODO: move this sync outside of config\n try {\n await syncStatus();\n } catch (error) {\n console.error('Error syncing status', error);\n }\n \n try {\n await syncConfig();\n } catch (error) {\n console.error('Error syncing config', error);\n }\n \n isSyncing = false; \n }, SYNC_INTERVAL);\n}\n\nasync function syncConfig() {\n const { configs } = await fetchConfigs();\n loadConfigs(configs);\n}\n","// import { Worker, isMainThread, parentPort, workerData } from 'worker_threads';\n\nimport { time } from '../time';\nimport { CronJob, CronJobInputParams } from './types';\nimport { startTransaction, captureError } from '../app/metrics';\nimport { Module } from '../app/module';\nimport { schema } from '../data/types';\nimport { Store } from '../data/store';\n\nconst DEFAULT_TIMEOUT = time.minutes(1);\n\n/**\n * Each cron instance acquires locks for the jobs it runs. If there was a pre-existing lock,\n * the lock is transferred to the new instance, but there is a delay to give the previous instance\n * a chance to see the new lock and gracefully finish remaining jobs.\n */\nconst LOCK_TRANSFER_DELAY = time.seconds(10);\n\nconst cronJobs: Record<string, CronJob> = {};\nlet cronJobsInterval: NodeJS.Timeout;\n\nconst cronJobsCollection = new Store('_modelenceCronJobs', {\n schema: {\n alias: schema.string(),\n lastStartDate: schema.date().optional(),\n lock: schema.object({\n containerId: schema.string(),\n acquireDate: schema.date(),\n }).optional(),\n },\n indexes: [\n { key: { alias: 1 }, unique: true, background: true },\n ]\n});\n\n// TODO: allow changing interval and timeout with cron jobconfigs\nexport function defineCronJob(\n alias: CronJob['alias'],\n { description = '', interval, timeout = DEFAULT_TIMEOUT, handler }: CronJobInputParams,\n) {\n if (cronJobs[alias]) {\n throw new Error(`Duplicate cron job declaration: '${alias}' already exists`);\n }\n\n if (cronJobsInterval) {\n throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${alias}]`);\n }\n\n if (interval < time.seconds(5)) {\n throw new Error(`Cron job interval should not be less than 5 second [${alias}]`);\n }\n\n if (timeout > time.days(1)) {\n throw new Error(`Cron job timeout should not be longer than 1 day [${alias}]`);\n }\n\n cronJobs[alias] = {\n alias,\n params: { description, interval, timeout },\n handler,\n state: {\n isRunning: false,\n }\n };\n}\n\nexport async function startCronJobs() {\n if (cronJobsInterval) {\n throw new Error('Cron jobs already started');\n }\n\n const aliasList = Object.keys(cronJobs);\n const aliasSelector = { alias: { $in: aliasList } };\n\n const existingLockedRecord = await cronJobsCollection.findOne({\n ...aliasSelector,\n 'lock.containerId': { $exists: true }\n });\n\n // TODO: handle different application versions with different parameters for the same job alias\n\n await cronJobsCollection.upsertMany(\n aliasSelector,\n {\n $set: {\n lock: {\n containerId: process.env.MODELENCE_CONTAINER_ID || 'unknown',\n acquireDate: new Date(),\n }\n }\n }\n );\n\n if (existingLockedRecord) {\n await sleep(LOCK_TRANSFER_DELAY);\n }\n\n const cronJobRecords = await cronJobsCollection.fetch(aliasSelector);\n const now = Date.now();\n cronJobRecords.forEach((record) => {\n const job = cronJobs[record.alias];\n if (!job) {\n return;\n }\n job.state.scheduledRunTs = record.lastStartDate ? record.lastStartDate.getTime() + job.params.interval : now;\n });\n Object.values(cronJobs).forEach((job) => {\n if (!job.state.scheduledRunTs) {\n job.state.scheduledRunTs = now;\n }\n });\n\n cronJobsInterval = setInterval(tickCronJobs, time.seconds(1));\n}\n\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nasync function tickCronJobs() {\n // TODO: periodically check if the locks are still there\n\n const now = Date.now();\n Object.values(cronJobs).forEach(async (job) => {\n const { params, state } = job;\n if (state.isRunning) {\n if (state.startTs && state.startTs + params.timeout < now) {\n // TODO: log cron trace timeout error\n state.isRunning = false;\n }\n return;\n }\n\n // TODO: limit the number of jobs running concurrently\n\n if (state.scheduledRunTs && state.scheduledRunTs <= now) {\n await startCronJob(job);\n }\n });\n}\n\nasync function startCronJob(job: CronJob) {\n const { alias, params, handler, state } = job;\n state.isRunning = true;\n state.startTs = Date.now();\n const transaction = startTransaction('cron', `cron:${alias}`);\n // TODO: enforce job timeout\n handler().then(() => {\n handleCronJobCompletion(state, params);\n transaction.end('success');\n }).catch((err) => {\n handleCronJobCompletion(state, params);\n captureError(err);\n transaction.end('error');\n console.error(`Error in cron job '${alias}':`, err);\n });\n await cronJobsCollection.updateOne({ alias }, {\n $set: {\n lastStartDate: new Date(state.startTs),\n }\n });\n}\n\nfunction handleCronJobCompletion(state: CronJob['state'], params: CronJob['params']) {\n state.scheduledRunTs = state.startTs ? state.startTs + params.interval : Date.now();\n state.startTs = undefined;\n state.isRunning = false;\n}\n\nexport function getCronJobsMetadata() {\n return Object.values(cronJobs).map(({ alias, params }) => ({\n alias,\n description: params.description,\n interval: params.interval,\n timeout: params.timeout,\n }));\n}\n\nexport default new Module('_system.cron', {\n stores: [cronJobsCollection],\n});\n\n// const runCronJob = () => {\n// const worker = new Worker(filePath, {\n// workerData: {},\n// execArgv: ['--loader', 'tsx'],\n// });\n\n// const timeoutId = setTimeout(() => {\n// worker.terminate();\n// console.error(`Cron job '${alias}' timed out after ${timeout}ms`);\n// }, timeout);\n\n// worker.on('message', (message) => {\n// if (message === 'done') {\n// clearTimeout(timeoutId);\n// worker.terminate();\n// }\n// });\n\n// worker.on('error', (err) => {\n// clearTimeout(timeoutId);\n// console.error(`Error in cron job '${alias}':`, err);\n// });\n\n// worker.on('exit', (code) => {\n// console.error(`Cron job '${alias}' exited with code ${code}`);\n// setTimeout(runCronJob, interval);\n// });\n// };\n","import dotenv from 'dotenv';\n\nimport { startServer } from './server';\nimport { connect, getClient, getMongodbUri } from '../db/client';\nimport { loadConfigs, setSchema } from '../config/server';\nimport { startConfigSync } from '../config/sync';\nimport { connectCloudBackend } from './backendApi';\nimport { initMetrics } from './metrics';\nimport { markAppStarted } from './state';\nimport userModule from '../auth/user';\nimport sessionModule from '../auth/session';\nimport { initRoles } from '../auth/role';\nimport { startCronJobs, getCronJobsMetadata, defineCronJob } from '../cron/jobs';\nimport cronModule from '../cron/jobs';\nimport { Module } from './module';\nimport { createQuery, createMutation, _createSystemQuery, _createSystemMutation } from '../methods';\nimport { Store } from '../data/store';\nimport { AppConfig, ConfigSchema } from '../config/types';\nimport { RoleDefinition } from '../auth/types';\n\nexport async function startApp(\n { modules = [], roles = {}, defaultRoles = {} }: {\n modules?: Module[]\n roles?: Record<string, RoleDefinition>\n defaultRoles?: Record<string, string>\n } = {}\n) {\n dotenv.config();\n\n const hasRemoteBackend = Boolean(process.env.MODELENCE_SERVICE_ENDPOINT);\n const isCronEnabled = Boolean(Number(process.env.MODELENCE_CRON_INSTANCE));\n\n // TODO: verify that user modules don't start with `_system.` prefix\n const systemModules = [userModule, sessionModule, cronModule];\n const combinedModules = [...systemModules, ...modules];\n\n markAppStarted();\n\n initSystemMethods(systemModules);\n initCustomMethods(modules);\n\n initRoles(roles, defaultRoles);\n\n const configSchema = getConfigSchema(combinedModules);\n setSchema(configSchema ?? {});\n const stores = getStores(combinedModules);\n\n if (isCronEnabled) {\n defineCronJobs(combinedModules);\n }\n\n if (hasRemoteBackend) {\n const { configs } = await connectCloudBackend({\n configSchema,\n cronJobsMetadata: isCronEnabled ? getCronJobsMetadata() : undefined,\n stores\n });\n loadConfigs(configs);\n } else {\n loadConfigs(getLocalConfigs());\n }\n\n const mongodbUri = getMongodbUri();\n if (mongodbUri) {\n await connect();\n provisionStores(stores);\n }\n\n if (hasRemoteBackend) {\n await initMetrics();\n startConfigSync();\n }\n\n if (isCronEnabled) {\n startCronJobs().catch(console.error);\n }\n\n await startServer({ combinedModules });\n}\n\nfunction initCustomMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n createQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n createMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction initSystemMethods(modules: Module[]) {\n for (const module of modules) {\n for (const [key, handler] of Object.entries(module.queries)) {\n _createSystemQuery(`${module.name}.${key}`, handler);\n }\n for (const [key, handler] of Object.entries(module.mutations)) {\n _createSystemMutation(`${module.name}.${key}`, handler);\n }\n }\n}\n\nfunction getStores(modules: Module[]) {\n return modules.flatMap(module => module.stores);\n}\n\nfunction getConfigSchema(modules: Module[]): ConfigSchema {\n const merged: ConfigSchema = {};\n\n for (const module of modules) {\n for (const [key, value] of Object.entries(module.configSchema)) {\n const absoluteKey = `${module.name}.${key}`;\n if (absoluteKey in merged) {\n throw new Error(\n `Duplicate config schema key: ${absoluteKey} (${module.name})`\n );\n }\n\n merged[absoluteKey] = value;\n }\n }\n\n return merged;\n}\n\nfunction defineCronJobs(modules: Module[]) {\n for (const module of modules) {\n for (const [cronAlias, cronJobParams] of Object.entries(module.cronJobs)) {\n defineCronJob(`${module.name}.${cronAlias}`, cronJobParams);\n }\n }\n}\n\nasync function provisionStores(stores: Store<any, any>[]) {\n const client = getClient();\n if (!client) {\n throw new Error('Failed to provision stores: MongoDB client not initialized');\n }\n\n for (const store of stores) {\n store.provision(client);\n }\n}\n\nfunction getLocalConfigs(): AppConfig[] {\n const configs: AppConfig[] = [];\n\n if (process.env.MONGODB_URI) {\n configs.push({\n key: '_system.mongodbUri',\n type: 'string',\n value: process.env.MONGODB_URI\n });\n }\n\n return configs;\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.1.9",
4
+ "version": "0.1.11",
5
5
  "description": "Full-stack JavaScript framework for startups",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",
@@ -46,11 +46,7 @@
46
46
  "typescript": "^5.7.2"
47
47
  },
48
48
  "dependencies": {
49
- "@aws-sdk/client-amp": "^3.665.0",
50
- "@aws-sdk/client-sts": "^3.665.0",
51
- "@aws-sdk/types": "^3.664.0",
52
49
  "@vitejs/plugin-react": "^4.3.4",
53
- "aws-sigv4-fetch": "^4.0.1",
54
50
  "bcrypt": "^5.1.1",
55
51
  "dotenv": "^16.4.5",
56
52
  "elastic-apm-node": "^4.8.0",