@modelence/react-query 1.0.2 → 1.2.1

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.
Files changed (46) hide show
  1. package/.yalc/modelence/README.md +86 -0
  2. package/.yalc/modelence/dist/bin/modelence.js +5 -0
  3. package/.yalc/modelence/dist/bin/modelence.js.map +1 -0
  4. package/.yalc/modelence/dist/chunk-3S2FFBNS.js +2 -0
  5. package/.yalc/modelence/dist/chunk-3S2FFBNS.js.map +1 -0
  6. package/.yalc/modelence/dist/chunk-3YAV3UUU.js +3 -0
  7. package/.yalc/modelence/dist/chunk-3YAV3UUU.js.map +1 -0
  8. package/.yalc/modelence/dist/chunk-55J6XMHW.js +2 -0
  9. package/.yalc/modelence/dist/chunk-55J6XMHW.js.map +1 -0
  10. package/.yalc/modelence/dist/chunk-C3UESBRX.js +2 -0
  11. package/.yalc/modelence/dist/chunk-C3UESBRX.js.map +1 -0
  12. package/.yalc/modelence/dist/chunk-DO5TZLF5.js +2 -0
  13. package/.yalc/modelence/dist/chunk-DO5TZLF5.js.map +1 -0
  14. package/.yalc/modelence/dist/chunk-DVECB2TP.js +3 -0
  15. package/.yalc/modelence/dist/chunk-DVECB2TP.js.map +1 -0
  16. package/.yalc/modelence/dist/client.d.ts +135 -0
  17. package/.yalc/modelence/dist/client.js +2 -0
  18. package/.yalc/modelence/dist/client.js.map +1 -0
  19. package/.yalc/modelence/dist/index-CwdohC5n.d.ts +15 -0
  20. package/.yalc/modelence/dist/index.d.ts +31 -0
  21. package/.yalc/modelence/dist/index.js +2 -0
  22. package/.yalc/modelence/dist/index.js.map +1 -0
  23. package/.yalc/modelence/dist/mongo.d.ts +5 -0
  24. package/.yalc/modelence/dist/mongo.js +2 -0
  25. package/.yalc/modelence/dist/mongo.js.map +1 -0
  26. package/.yalc/modelence/dist/package-3YQBVIVQ.js +2 -0
  27. package/.yalc/modelence/dist/package-3YQBVIVQ.js.map +1 -0
  28. package/.yalc/modelence/dist/server.d.ts +569 -0
  29. package/.yalc/modelence/dist/server.js +19 -0
  30. package/.yalc/modelence/dist/server.js.map +1 -0
  31. package/.yalc/modelence/dist/telemetry.d.ts +11 -0
  32. package/.yalc/modelence/dist/telemetry.js +2 -0
  33. package/.yalc/modelence/dist/telemetry.js.map +1 -0
  34. package/.yalc/modelence/dist/types-Ds1ESQSs.d.ts +106 -0
  35. package/.yalc/modelence/dist/types-WgRbQ-tj.d.ts +645 -0
  36. package/.yalc/modelence/dist/types.d.ts +7 -0
  37. package/.yalc/modelence/dist/types.js +2 -0
  38. package/.yalc/modelence/dist/types.js.map +1 -0
  39. package/.yalc/modelence/package.json +80 -0
  40. package/.yalc/modelence/yalc.sig +1 -0
  41. package/dist/index.d.ts +68 -1
  42. package/dist/index.js +1 -1
  43. package/dist/index.js.map +1 -1
  44. package/package.json +3 -3
  45. package/src/index.ts +158 -1
  46. package/yalc.lock +10 -0
@@ -0,0 +1,19 @@
1
+ import {a as a$2}from'./chunk-3S2FFBNS.js';import {d as d$1,a as a$3}from'./chunk-C3UESBRX.js';import {a}from'./chunk-DO5TZLF5.js';import {b as b$1,e,d as d$2,c,f,g,j as j$1,a as a$1,i,k as k$1,h,l}from'./chunk-DVECB2TP.js';export{a as getConfig}from'./chunk-DVECB2TP.js';import Jt from'dotenv';import hn from'fs/promises';import Io from'os';import Re from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoError,ObjectId,MongoClient}from'mongodb';export{ObjectId}from'mongodb';import {randomBytes,randomUUID}from'crypto';import k,{z as z$1}from'zod';import xo from'bcrypt';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import Jo from'@vitejs/plugin-react';import Ho from'fs';import R,{Router}from'express';import ln from'cookie-parser';import dn from'http';var S=class{constructor(e,{stores:o=[],queries:n={},mutations:r={},routes:i=[],cronJobs:s={},configSchema:a={},rateLimits:c=[],channels:l=[]}){this.name=e,this.stores=o,this.queries=n,this.mutations=r,this.routes=i,this.cronJobs=s,this.configSchema=a,this.rateLimits=c,this.channels=l;}};function T(t){let e=t._def;if(e.typeName==="ZodString")return {type:"string"};if(e.typeName==="ZodNumber")return {type:"number"};if(e.typeName==="ZodBoolean")return {type:"boolean"};if(e.typeName==="ZodDate")return {type:"date"};if(e.typeName==="ZodArray")return {type:"array",items:T(e.type)};if(e.typeName==="ZodObject"){let n=e.shape(),r={};for(let[i,s]of Object.entries(n))r[i]=T(s);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...T(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...T(e.innerType),optional:true};if(e.typeName==="ZodEnum")return {type:"enum",items:e.values};if(e.typeName==="ZodUnion")return {type:"union",items:e.options.map(T)};if(e.typeName==="ZodEffects"){let o=e;return o.description?{type:"custom",typeName:o.description}:T(o.schema)}return {type:"custom",typeName:e.typeName}}function Y(t){let e={};for(let[o,n]of Object.entries(t))Array.isArray(n)?e[o]=n.map(r=>typeof r=="object"&&"_def"in r?T(r):Y(r)):typeof n=="object"&&"_def"in n?e[o]=T(n):e[o]=Y(n);return e}var w=class t{constructor(e,o){this.name=e,this.schema=o.schema,this.methods=o.methods,this.indexes=o.indexes,this.searchIndexes=o.searchIndexes||[];}getName(){return this.name}getSchema(){return this.schema}getSerializedSchema(){return Y(this.schema)}extend(e){let o={...this.schema,...e.schema||{}},n=[...this.indexes,...e.indexes||[]],r=[...this.searchIndexes,...e.searchIndexes||[]],i={...this.methods||{},...e.methods||{}},s=new t(this.name,{schema:o,methods:i,indexes:n,searchIndexes:r});if(this.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);return s}init(e){if(this.collection)throw new Error(`Collection ${this.name} is already initialized`);this.client=e,this.collection=this.client.db().collection(this.name);}async createIndexes(){if(this.indexes.length>0)for(let e of this.indexes)try{await this.requireCollection().createIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===86&&e.name)await this.requireCollection().dropIndex(e.name),await this.requireCollection().createIndexes([e]);else throw o}if(this.searchIndexes.length>0)for(let e of this.searchIndexes)try{await this.requireCollection().createSearchIndexes([e]);}catch(o){if(o instanceof MongoError&&o.code===68&&e.name)await this.requireCollection().dropSearchIndex(e.name),await this.requireCollection().createSearchIndexes([e]);else throw o}}wrapDocument(e){return this.methods?Object.create(null,Object.getOwnPropertyDescriptors({...e,...this.methods})):e}getSelector(e){return typeof e=="string"?{_id:new ObjectId(e)}:e instanceof ObjectId?{_id:e}:e}requireCollection(){if(!this.collection)throw new Error(`Collection ${this.name} is not provisioned`);return this.collection}requireClient(){if(!this.client)throw new Error("Database is not connected");return this.client}async findOne(e,o){let n=await this.requireCollection().findOne(e,o);return n?this.wrapDocument(n):null}async requireOne(e,o,n){let r=await this.findOne(e,o);if(!r)throw n?n():new Error(`Record not found in ${this.name}`);return r}find(e,o){let n=this.requireCollection().find(e);return o?.sort&&n.sort(o.sort),o?.limit&&n.limit(o.limit),o?.skip&&n.skip(o.skip),n}async findById(e){let o=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(o)}async requireById(e,o){let n=await this.findById(e);if(!n)throw o?o():new Error(`Record with id ${e} not found in ${this.name}`);return n}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,o){return (await this.find(e,o).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e){return await this.requireCollection().insertOne(e)}async insertMany(e){return await this.requireCollection().insertMany(e)}async updateOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o)}async upsertOne(e,o){return await this.requireCollection().updateOne(this.getSelector(e),o,{upsert:true})}async updateMany(e,o,n){return await this.requireCollection().updateMany(e,o,n)}async upsertMany(e,o){return await this.requireCollection().updateMany(e,o,{upsert:true})}async deleteOne(e){return await this.requireCollection().deleteOne(e)}async deleteMany(e){return await this.requireCollection().deleteMany(e)}aggregate(e,o){return this.requireCollection().aggregate(e,o)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,o){let n=this.getDatabase();if(!this.collection||!n)throw new Error(`Store ${this.name} is not provisioned`);if((await n.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await n.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await n.collection(e).rename(this.name,o);}async vectorSearch({field:e,embedding:o,numCandidates:n,limit:r,projection:i,indexName:s}){return this.aggregate([{$vectorSearch:{index:s||e+"VectorSearch",path:e,queryVector:o,numCandidates:n||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...i}}])}static vectorIndex({field:e,dimensions:o,similarity:n="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:o,similarity:n}]}}}};var Xt=z$1.string.bind(z$1),eo=z$1.number.bind(z$1),to=z$1.date.bind(z$1),oo=z$1.boolean.bind(z$1),no=z$1.array.bind(z$1),ro=z$1.object.bind(z$1),io=z$1.enum.bind(z$1),d={string:Xt,number:eo,date:to,boolean:oo,array:no,object:ro,enum:io,embedding(){return z$1.array(z$1.number())},objectId(){return z$1.instanceof(ObjectId).describe("ObjectId")},userId(){return z$1.instanceof(ObjectId).describe("UserId")},ref(t){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(t){return {}}};var j=new w("_modelenceSessions",{schema:{authToken:d.string(),createdAt:d.date(),expiresAt:d.date(),userId:d.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1}}]});async function We(t){let e=t?await j.findOne({authToken:t}):null;return e?{authToken:String(e.authToken),expiresAt:new Date(e.expiresAt),userId:e.userId??null}:await fe()}async function Be(t,e){await j.updateOne({authToken:t},{$set:{userId:e}});}async function Je(t){await j.updateOne({authToken:t},{$set:{userId:null}});}async function fe(t=null){let e=randomBytes(32).toString("base64url"),o=Date.now(),n=new Date(o+a.days(7));return await j.insertOne({authToken:e,createdAt:new Date(o),expiresAt:n,userId:t}),{authToken:e,expiresAt:n,userId:t}}async function ao(t){let e=Date.now(),o=new Date(e+a.days(7));await j.updateOne({authToken:t.authToken},{$set:{lastActiveDate:new Date(e),expiresAt:o}});}var He=new S("_system.session",{stores:[j],mutations:{init:async function(t,{session:e,user:o}){return {session:e,user:o,configs:b$1()}},heartbeat:async function(t,{session:e}){e&&await ao(e);}}});var m=new w("_modelenceUsers",{schema:{handle:d.string(),emails:d.array(d.object({address:d.string(),verified:d.boolean()})).optional(),status:d.enum(["active","disabled","deleted"]).optional(),createdAt:d.date(),disabledAt:d.date().optional(),deletedAt:d.date().optional(),roles:d.array(d.string()).optional(),authMethods:d.object({password:d.object({hash:d.string()}).optional(),google:d.object({id:d.string()}).optional(),github:d.object({id:d.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"authMethods.google.id":1,status:1},sparse:true},{key:{"authMethods.github.id":1,status:1},sparse:true}]}),W=new w("_modelenceDisposableEmailDomains",{schema:{domain:d.string(),addedAt:d.date()},indexes:[{key:{domain:1},unique:true}]}),v=new w("_modelenceEmailVerificationTokens",{schema:{userId:d.objectId(),email:d.string().optional(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),E=new w("_modelenceResetPasswordTokens",{schema:{userId:d.objectId(),token:d.string(),createdAt:d.date(),expiresAt:d.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Ve=new Map,$={authenticated:null,unauthenticated:null};function Qe(t,e){$.authenticated=e.authenticated,$.unauthenticated=e.unauthenticated;for(let[o,n]of Object.entries(t))Ve.set(o,n);}function X(){return $.unauthenticated?[$.unauthenticated]:[]}function Ge(){return $.authenticated?[$.authenticated]:[]}function he(t,e){let o=e.find(n=>!co(t,n));if(o)throw new Error(`Access denied - missing permission: '${o}'`)}function co(t,e){for(let o of t){let n=Ve.get(o);if(n&&n.permissions.includes(e))return true}return false}async function M(t){let e=await We(t),o=e.userId?await m.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,n=o?{id:o._id.toString(),handle:o.handle,roles:o.roles||[],hasRole:i=>(o.roles||[]).includes(i),requireRole:i=>{if(!(o.roles||[]).includes(i))throw new Error(`Access denied - role '${i}' required`)}}:null,r=n?Ge():X();return {user:n,session:e,roles:r}}var D=null;async function Ke(){if(D)return D;let t=A();if(!t)throw new Error("MongoDB URI is not set");D=new MongoClient(t,{maxPoolSize:20});try{return await D.connect(),await D.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),D}catch(e){throw console.error(e),D=null,e}}function A(){let t=a$1("_system.mongodbUri");return t?String(t):void 0}function ee(){return D}function mo(){return typeof window!="object"}function _(){if(!mo())throw new Error("This function can only be called on the server")}function te(t){return t.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var oe={};function ge(t,e){return _(),tt(t),ne("query",t,e)}function Ye(t,e){return _(),tt(t),ne("mutation",t,e)}function Xe(t,e){return _(),ot(t),ne("query",t,e)}function et(t,e){return _(),ot(t),ne("mutation",t,e)}function tt(t){if(t.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${t})`)}function ot(t){if(!t.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${t})`)}function ne(t,e,o){if(_(),oe[e])throw new Error(`Method with name '${e}' is already defined.`);let n=typeof o=="function"?o:o.handler,r=typeof o=="function"?[]:o.permissions??[];oe[e]={type:t,name:e,handler:n,permissions:r};}async function nt(t,e,o){_();let n=oe[t];if(!n)throw new Error(`Method with name '${t}' is not defined.`);let{type:r,handler:i}=n,s=k$1("method",`method:${t}`,{type:r,args:e}),a;try{he(o.roles,n.permissions),a=await i(e,o);}catch(c){throw s.end("error"),c}return s.end(),a}async function rt(t,e,o,n){_();let r=oe[t];if(!r)throw new Error(`Method with name '${t}' is not defined.`);let{type:i,handler:s}=r;if(i!=="query")throw new Error("Live methods are only supported for queries");let a=k$1("method",`method:${t}:live`,{type:i,args:e});try{he(o.roles,r.permissions);let c={...o,...n},l=await s(e,c);if(a.end(),l!==void 0&&typeof l!="function")throw new Error(`Live query handler for '${t}' must return a cleanup function or undefined, not data. Use publish() to send data to the client.`);return l||null}catch(c){throw a.end("error"),c}}var po=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({})}),fo=z$1.object({subscriptionId:z$1.string().min(1)}),B=new Map;function ho(t){let e=B.get(t.id);return e||(e=new Map,B.set(t.id,e)),e}async function ye(t,e){let o=po.safeParse(e);if(!o.success){t.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${o.error.message}`});return}let{subscriptionId:n,method:r,args:i}=o.data;try{let s=p=>{t.emit("liveQueryData",{subscriptionId:n,data:p,typeMap:a$2(p)});},a=await rt(r,i,t.data,{publish:s}),c=ho(t),l=c.get(n);if(l?.cleanup)try{l.cleanup();}catch(p){console.error("[LiveQuery] Error cleaning up existing subscription:",p);}c.set(n,{cleanup:a});}catch(s){console.error(`[LiveQuery] Error in ${r}:`,s),t.emit("liveQueryError",{subscriptionId:n,error:s instanceof Error?s.message:String(s)});}}function we(t,e){let o=fo.safeParse(e);if(!o.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${o.error.message}`);return}let{subscriptionId:n}=o.data,r=B.get(t.id);if(!r)return;let i=r.get(n);if(i){if(i.cleanup)try{i.cleanup();}catch(s){console.error("[LiveQuery] Error in cleanup:",s);}r.delete(n);}}function be(t){let e=B.get(t.id);if(e){for(let o of e.values())if(o.cleanup)try{o.cleanup();}catch(n){console.error("[LiveQuery] Error in cleanup on disconnect:",n);}B.delete(t.id);}}var J=null,wo="_modelenceSocketio";async function bo({httpServer:t,channels:e}){let o=ee();console.log("Initializing Socket.IO server...");let n=null;if(o){n=o.db().collection(wo);try{await n.createIndex({createdAt:1},{expireAfterSeconds:3600,background:!0});}catch(r){console.error("Failed to create index on MongoDB collection for Socket.IO:",r);}}J=new Server(t,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["polling","websocket"],allowUpgrades:true,perMessageDeflate:false}),J.on("error",r=>{console.error("Socket.IO error:",r);}),J.use(async(r,i)=>{let s=r.handshake.auth.token;try{r.data=await M(s);}finally{i();}}),J.on("connection",r=>{console.log("Socket.IO client connected"),r.on("disconnect",()=>{console.log("Socket.IO client disconnected"),be(r);}),r.on("joinChannel",async i=>{let[s,...a]=i.split(":"),c=a.join(":");for(let l of e)if(l.category===s){!l.canAccessChannel||await l.canAccessChannel({id:c,...r.data})?(r.join(i),r.emit("joinedChannel",i)):r.emit("channelAccessDenied",i);return}console.warn(`Unknown channel: ${s}`);}),r.on("leaveChannel",i=>{r.leave(i),console.log(`User ${r.id} left channel ${i}`),r.emit("leftChannel",i);}),r.on("subscribeLiveQuery",i=>ye(r,i)),r.on("unsubscribeLiveQuery",i=>we(r,i));}),console.log("Socket.IO server initialized");}function So({category:t,id:e,data:o}){J?.to(`${t}:${e}`).emit(t,o);}var it={init:bo,broadcast:So};async function st(t){let e=t.toLowerCase().trim().split("@");if(e.length!==2)return false;let o=e[1];return !!await W.findOne({domain:o})}var at={interval:a.days(1),async handler(){let t=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let o=(await t.text()).split(`
2
+ `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),n=new Date,r=500;for(let i=0;i<o.length;i+=r){let s=o.slice(i,i+r);try{await W.insertMany(s.map(a=>({domain:a,addedAt:n})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Se=Object.freeze({});function ct(t){Se=Object.freeze(Object.assign({},Se,t));}function b(){return Se}function lt({name:t,email:e,verificationUrl:o}){return `
3
+ <p>Hi${t?` ${t}`:""},</p>
4
+ <p>Please verify your email address ${e} by clicking the link below:</p>
5
+ <p><a href="${o}">${o}</a></p>
6
+ <p>If you did not request this, please ignore this email.</p>
7
+ `}async function dt(t){let e=process.env.MODELENCE_SITE_URL,o=b().emailVerifiedRedirectUrl||e||"/";try{let n=z$1.string().parse(t.query.token),r=await v.findOne({token:n,expiresAt:{$gt:new Date}});if(!r)throw new Error("Invalid or expired verification token");if(!await m.findOne({_id:r.userId}))throw new Error("User not found");let s=r.email;if(!s)throw new Error("Email not found in token");if((await m.updateOne({_id:r.userId,"emails.address":s,"emails.verified":{$ne:!0}},{$set:{"emails.$.verified":!0}})).matchedCount===0)throw await m.findOne({_id:r.userId,"emails.address":s})?new Error("Email is already verified"):new Error("Email address not found for this user");await v.deleteOne({_id:r._id});}catch(n){if(n instanceof Error)return console.error("Error verifying email:",n),{status:301,redirect:`${o}?status=error&message=${encodeURIComponent(n.message)}`}}return {status:301,redirect:`${o}?status=verified`}}async function re({userId:t,email:e,baseUrl:o=process.env.MODELENCE_SITE_URL}){if(b().provider){let n=b().provider,r=randomBytes(32).toString("hex"),i=new Date(Date.now()+a.hours(24));await v.insertOne({userId:t,email:e,token:r,createdAt:new Date,expiresAt:i});let s=`${o}/api/_internal/auth/verify-email?token=${r}`,c=(b()?.verification?.template||lt)({name:"",email:e,verificationUrl:s}),l=te(c);await n?.sendEmail({to:e,from:b()?.from||"noreply@modelence.com",subject:b()?.verification?.subject||"Verify your email address",text:l,html:c});}}function ie(t){return z$1.string().min(8,{message:"Password must contain at least 8 characters"}).parse(t)}function N(t){return z$1.string().email({message:"Invalid email address"}).parse(t)}var Ee=Object.freeze({});function mt(t){Ee=Object.freeze(Object.assign({},Ee,t));}function y(){return Ee}async function ft(t,{user:e,session:o,connectionInfo:n}){try{if(!o)throw new Error("Session is not initialized");let r=n?.ip;r&&await L({bucket:"signin",type:"ip",value:r});let i=N(t.email),s=z$1.string().parse(t.password),a=await m.findOne({"emails.address":i,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),c=a?.authMethods?.password?.hash;if(!c)throw pt();if(!a.emails?.find(f=>f.address===i)?.verified&&b()?.provider){if(r)try{await L({bucket:"verification",type:"user",value:a._id.toString()});}catch{throw new Error("Your email address hasn't been verified yet. Please use the verification email we've send earlier to your inbox.")}throw await re({userId:a?._id,email:i,baseUrl:n?.baseUrl}),new Error("Your email address hasn't been verified yet. We've sent a new verification email to your inbox.")}if(!await xo.compare(s,c))throw pt();return await Be(o.authToken,a._id),y().onAfterLogin?.({user:a,session:o,connectionInfo:n}),y().login?.onSuccess?.(a),{user:{id:a._id,handle:a.handle}}}catch(r){throw r instanceof Error&&(y().onLoginError?.({error:r,session:o,connectionInfo:n}),y().login?.onError?.(r)),r}}async function ht(t,{session:e}){if(!e)throw new Error("Session is not initialized");await Je(e.authToken);}function pt(){return new Error("Incorrect email/password combination")}async function gt(t,{user:e}){if(!e)throw new Error("Not authenticated");let o=await m.requireById(e.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{})}}var H=new w("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var Ce=[];function yt(t){if(Ce.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");Ce=t;}async function L(t){let{bucket:e,type:o,value:n}=t,r=Ce.filter(i=>i.bucket===e&&i.type===o);for(let i of r)await vo(i,n);}async function vo(t,e,o){let n=()=>new d$1(`Rate limit exceeded for ${t.bucket}`),r=await H.findOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window}),i=Date.now(),s=Math.floor(i/t.window)*t.window,{count:a,modifier:c}=r?Do(r,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+t.window+t.window)}}};if(a>=t.limit)throw n();await H.upsertOne({bucket:t.bucket,type:t.type,value:e,windowMs:t.window},c);}function Do(t,e,o){let n=e-t.windowMs;if(t.windowStart.getTime()===e){let r=t.windowCount,i=t.prevWindowCount,s=1-(o-e)/t.windowMs;return {count:Math.round(r+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(e),prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}if(t.windowStart.getTime()===n){let r=1-(o-e)/t.windowMs;return {count:Math.round(t.windowCount*r),modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:t.windowCount,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(e),windowCount:1,prevWindowCount:0,expiresAt:new Date(e+t.windowMs+t.windowMs)}}}}async function wt(t,{user:e,session:o,connectionInfo:n}){try{let r=N(t.email),i=ie(t.password),s=n?.ip;if(s&&await L({bucket:"signupAttempt",type:"ip",value:s}),await st(r))throw new Error("Please use a permanent email address");let a=await m.findOne({"emails.address":r},{collation:{locale:"en",strength:2}});if(a){let f=a.emails?.find(C=>C.address===r);throw a.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${f?.address}`)}s&&await L({bucket:"signup",type:"ip",value:s});let c=await xo.hash(i,10),l=await m.insertOne({handle:r,status:"active",emails:[{address:r,verified:!1}],createdAt:new Date,authMethods:{password:{hash:c}}}),p=await m.findOne({_id:l.insertedId},{readPreference:"primary"});if(!p)throw new Error("User not found");return await re({userId:l?.insertedId,email:r,baseUrl:n?.baseUrl}),y().onAfterSignup?.({user:p,session:o,connectionInfo:n}),y().signup?.onSuccess?.(p),l.insertedId}catch(r){throw r instanceof Error&&(y().onSignupError?.({error:r,session:o,connectionInfo:n}),y().signup?.onError?.(r)),r}}function Mo(t,e){return e?e.startsWith("http://")||e.startsWith("https://")?e:`${t}${e.startsWith("/")?"":"/"}${e}`:t}function Ao({email:t,resetUrl:e}){return `
8
+ <p>Hi,</p>
9
+ <p>We received a request to reset your password for ${t}.</p>
10
+ <p>Click the link below to reset your password:</p>
11
+ <p><a href="${e}">${e}</a></p>
12
+ <p>This link will expire in 1 hour.</p>
13
+ <p>If you did not request this password reset, please ignore this email.</p>
14
+ `}var xe={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function bt(t,{connectionInfo:e}){let o=N(t.email),n=await m.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n||!n.authMethods?.password)return xe;let r=b().provider;if(!r)throw new Error("Email provider is not configured");let i=randomBytes(32).toString("hex"),s=Date.now(),a$1=new Date(s),c=new Date(s+a.hours(1));await E.insertOne({userId:n._id,token:i,createdAt:a$1,expiresAt:c});let l=process.env.MODELENCE_SITE_URL||e?.baseUrl,f=`${Mo(l,b().passwordReset?.redirectUrl)}?token=${i}`,U=(b()?.passwordReset?.template||Ao)({email:o,resetUrl:f,name:""}),de=te(U);return await r.sendEmail({to:o,from:b()?.from||"noreply@modelence.com",subject:b()?.passwordReset?.subject||"Reset your password",text:de,html:U}),xe}async function St(t,{}){let e=z$1.string().parse(t.token),o=ie(t.password),n=await E.findOne({token:e});if(!n)throw new Error("Invalid or expired reset token");if(n.expiresAt<new Date)throw await E.deleteOne({token:e}),new Error("Reset token has expired");let r=await m.findOne({_id:n.userId});if(!r)throw new Error("User not found");let i=await xo.hash(o,10);return await m.updateOne({_id:r._id},{$set:{"authMethods.password.hash":i}}),await E.deleteOne({token:e}),{success:true,message:"Password has been reset successfully"}}var Et=new S("_system.user",{stores:[m,W,v,E],queries:{getOwnProfile:gt},mutations:{signupWithPassword:wt,loginWithPassword:ft,logout:ht,sendResetPasswordToken:bt,resetPassword:St},cronJobs:{updateDisposableEmailList:at},rateLimits:[{bucket:"signup",type:"ip",window:a.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a.days(1),limit:500},{bucket:"signin",type:"ip",window:a.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a.days(1),limit:500},{bucket:"verification",type:"user",window:a.minutes(15),limit:3},{bucket:"verification",type:"user",window:a.days(1),limit:10}],configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:false},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:dt}}]});async function Ct({configSchema:t,cronJobsMetadata:e,stores:o}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let r=Object.values(o).map(s=>({name:s.getName(),schema:s.getSerializedSchema(),collections:[s.getName()],version:2})),i=await Te("/api/connect","POST",{hostname:Io.hostname(),containerId:n,dataModels:r,configSchema:t,cronJobsMetadata:e});if(i.status==="error")throw new Error(i.error);return console.log("Successfully connected to Modelence Cloud"),i}catch(r){throw console.error("Unable to connect to Modelence Cloud:",r),r}}async function xt(){return await Te("/api/configs","GET")}async function Tt(){return await Te("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function Te(t,e,o){let{MODELENCE_SERVICE_ENDPOINT:n,MODELENCE_SERVICE_TOKEN:r}=process.env;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${n}${t}`,{method:e,headers:{Authorization:`Bearer ${r}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text();try{let a=JSON.parse(s);throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${a?.error}`)}catch{throw new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${s}`)}}return await i.json()}var ve=false,Lo=a.seconds(10);function vt(){setInterval(async()=>{if(!ve){ve=true;try{await Tt();}catch(t){console.error("Error syncing status",t);}try{await Po();}catch(t){console.error("Error syncing config",t);}ve=false;}},Lo);}async function Po(){let{configs:t}=await xt();c(t);}var V=new w("_modelenceLocks",{schema:{resource:d.string(),instanceId:d.string(),acquiredAt:d.date()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}]});var z={},Dt=a.seconds(10),_t=randomBytes(32).toString("base64url"),jo=a.seconds(30);async function se(t,{lockDuration:e=jo,successfulLockCacheDuration:o=Dt,failedLockCacheDuration:n=Dt,instanceId:r=_t}={}){let i=Date.now();if(z[t]&&i<z[t].expiresAt)return z[t].value;let s=new Date(i-e);h(`Attempting to acquire lock: ${t}`,{source:"lock",resource:t,instanceId:r});try{let a=await V.upsertOne({$or:[{resource:t,instanceId:r},{resource:t,acquiredAt:{$lt:s}}]},{$set:{resource:t,instanceId:r,acquiredAt:new Date}}),c=a.upsertedCount>0||a.modifiedCount>0;return z[t]={value:c,expiresAt:i+(c?o:n)},c?h(`Lock acquired: ${t}`,{source:"lock",resource:t,instanceId:r}):h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),c}catch{return z[t]={value:false,expiresAt:i+n},h(`Failed to acquire lock (already held): ${t}`,{source:"lock",resource:t,instanceId:r}),false}}async function kt(t,{instanceId:e=_t}={}){let o=await V.deleteOne({resource:t,instanceId:e});return delete z[t],o.deletedCount>0}var $o=a.minutes(1),P={},De=null,_e=new w("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function Ot(t,{description:e="",interval:o,timeout:n=$o,handler:r}){if(P[t])throw new Error(`Duplicate cron job declaration: '${t}' already exists`);if(De)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${t}]`);if(o<a.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${t}]`);if(n>a.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${t}]`);P[t]={alias:t,params:{description:e,interval:o,timeout:n},handler:r,state:{isRunning:false}};}async function Mt(){if(De)throw new Error("Cron jobs already started");let t=Object.keys(P);if(t.length>0){let e={alias:{$in:t}},o=await _e.fetch(e),n=Date.now();o.forEach(r=>{let i=P[r.alias];i&&(i.state.scheduledRunTs=r.lastStartDate?r.lastStartDate.getTime()+i.params.interval:n);}),Object.values(P).forEach(r=>{r.state.scheduledRunTs||(r.state.scheduledRunTs=n);}),De=setInterval(No,a.seconds(1));}}async function No(){let t=Date.now();await se("cron",{successfulLockCacheDuration:a.seconds(10),failedLockCacheDuration:a.seconds(30)})&&Object.values(P).forEach(async o=>{let{params:n,state:r}=o;if(r.isRunning){r.startTs&&r.startTs+n.timeout<t&&(r.isRunning=false);return}r.scheduledRunTs&&r.scheduledRunTs<=t&&await zo(o);});}async function zo(t){let{alias:e,params:o,handler:n,state:r}=t;r.isRunning=true,r.startTs=Date.now(),await _e.updateOne({alias:e},{$set:{lastStartDate:new Date(r.startTs)}});let i=k$1("cron",`cron:${e}`);try{await n(),Rt(r,o),i.end("success");}catch(s){Rt(r,o);let a=s instanceof Error?s:new Error(String(s));l(a),i.end("error"),console.error(`Error in cron job '${e}':`,s);}}function Rt(t,e){t.scheduledRunTs=t.startTs?t.startTs+e.interval:Date.now(),t.startTs=void 0,t.isRunning=false;}function At(){return Object.values(P).map(({alias:t,params:e})=>({alias:t,description:e.description,interval:e.interval,timeout:e.timeout}))}var It=new S("_system.cron",{stores:[_e]});var ke=new S("_system.lock",{stores:[V]});var Q=new w("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function qo(t){if(t.length===0)return;if(!await se("migrations")){i("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}let o=t.map(({version:s})=>s),n=await Q.fetch({version:{$in:o}}),r=new Set(n.map(({version:s})=>s)),i$1=t.filter(({version:s})=>!r.has(s));if(i$1.length!==0){i(`Running migrations (${i$1.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i$1){i(`Running migration v${s}: ${a}`,{source:"migrations"});try{let p=(await c()||"").toString().trim(),f=15*1024*1024,C=p.length>f?p.slice(0,f)+`
15
+ [Output truncated - exceeded size limit]`:p;await Q.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:C,appliedAt:new Date}}),i(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await Q.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),i(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}await kt("migrations");}}function Lt(t){setTimeout(()=>{qo(t).catch(e=>{console.error("Error running migrations:",e);});},0);}var Pt=new S("_system.migration",{stores:[Q]});var Ut=new S("_system.rateLimit",{stores:[H]});var jt=new S("_system",{configSchema:{mongodbUrl:{type:"string",isPublic:false,default:""},env:{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""}}});var Oe=class{async init(){this.config=await Go(),this.isDev()&&(console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config));}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let e=[R.static("./.modelence/build/client".replace(/\\/g,"/"))];return this.config?.publicDir&&e.push(R.static(this.config.publicDir)),e}handler(e,o){if(this.isDev())try{o.sendFile("index.html",{root:"./src/client"});}catch(n){console.error("Error serving index.html:",n),o.status(500).send("Internal Server Error");}else o.sendFile("index.html",{root:"./.modelence/build/client".replace(/\\/g,"/")});}isDev(){return process.env.NODE_ENV!=="production"}};async function Vo(){let t=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,t))?.config||{}}catch(e){return console.warn("Could not load vite config:",e),{}}}function Qo(t,e){let o=mergeConfig(t,e);if(o.plugins&&Array.isArray(o.plugins)){let n=new Set;o.plugins=o.plugins.flat().filter(r=>{if(!r||typeof r!="object"||Array.isArray(r))return true;let i=r.name;return !i||n.has(i)?false:(n.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function Go(){let t=process.cwd(),e=await Vo(),o=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(i=>Ho.existsSync(Re.join(t,i))),n=[Jo(),Ko()];if(o){let i=(await import('vite-plugin-eslint')).default;n.push(i({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:t,overrideConfigFile:Re.resolve(t,o)}));}let r=defineConfig({plugins:n,build:{outDir:".modelence/build/client".replace(/\\/g,"/"),emptyOutDir:true},server:{middlewareMode:true},root:"./src/client",resolve:{alias:{"@":Re.resolve(t,"src").replace(/\\/g,"/")}}});return Qo(r,e)}function Ko(){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}}}var Nt=new Oe;async function zt(t,e){let{authToken:o}=await fe(e);t.cookie("authToken",o,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"strict"}),t.status(301),t.redirect("/");}function q(t){return `${a$1("_system.site.url")}/api/_internal/auth/${t}/callback`}async function ae(t,e,o){let n=await m.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:r,connectionInfo:i}=await Me(t);try{if(n){await zt(e,n._id),y().onAfterLogin?.({user:n,session:r,connectionInfo:i}),y().login?.onSuccess?.(n);return}}catch(s){throw s instanceof Error&&(y().login?.onError?.(s),y().onLoginError?.({error:s,session:r,connectionInfo:i})),s}try{if(!o.email){e.status(400).json({error:`Email address is required for ${o.providerName} authentication.`});return}if(await m.findOne({"emails.address":o.email},{collation:{locale:"en",strength:2}})){e.status(400).json({error:"User with this email already exists. Please log in instead."});return}let a=await m.insertOne({handle:o.email,status:"active",emails:[{address:o.email,verified:o.emailVerified}],createdAt:new Date,authMethods:{[o.providerName]:{id:o.id}}});await zt(e,a.insertedId);let c=await m.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(y().onAfterSignup?.({user:c,session:r,connectionInfo:i}),y().signup?.onSuccess?.(c));}catch(s){throw s instanceof Error&&(y().onSignupError?.({error:s,session:r,connectionInfo:i}),y().signup?.onError?.(s)),s}}function ce(t){return !t||typeof t!="string"?null:t}async function Xo(t,e,o,n){let r=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:t,client_id:e,client_secret:o,redirect_uri:n,grant_type:"authorization_code"})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function en(t){let e=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${t}`}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function tn(t,e){let o=ce(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.google.clientId")),r=String(a$1("_system.user.auth.google.clientSecret")),i=q("google");try{let s=await Xo(o,n,r,i),a=await en(s.access_token),c={id:a.id,email:a.email,emailVerified:a.verified_email,providerName:"google"};await ae(t,e,c);}catch(s){console.error("Google OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function on(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.google.enabled"),s=String(a$1("_system.user.auth.google.clientId")),a=String(a$1("_system.user.auth.google.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"Google authentication is not configured"});return}r();};return t.get("/api/_internal/auth/google",e,(o,n)=>{let r=String(a$1("_system.user.auth.google.clientId")),i=q("google"),s=new URL("https://accounts.google.com/o/oauth2/v2/auth");s.searchParams.append("client_id",r),s.searchParams.append("redirect_uri",i),s.searchParams.append("response_type","code"),s.searchParams.append("scope","profile email"),s.searchParams.append("access_type","online"),n.redirect(s.toString());}),t.get("/api/_internal/auth/google/callback",e,tn),t}var qt=on;async function rn(t,e,o,n){let r=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:e,client_secret:o,code:t,redirect_uri:n})});if(!r.ok)throw new Error(`Failed to exchange code for token: ${r.statusText}`);return r.json()}async function sn(t){let e=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${t}`,Accept:"application/vnd.github.v3+json"}});if(!e.ok)throw new Error(`Failed to fetch user info: ${e.statusText}`);return e.json()}async function an(t,e){let o=ce(t.query.code);if(!o){e.status(400).json({error:"Missing authorization code"});return}let n=String(a$1("_system.user.auth.github.clientId")),r=String(a$1("_system.user.auth.github.clientSecret")),i=q("github");try{let s=await rn(o,n,r,i),a=await sn(s.access_token),c=a.email||"";if(!c){e.status(400).json({error:"Unable to retrieve email from GitHub. Please ensure your email is public or grant email permissions."});return}let l={id:String(a.id),email:c,emailVerified:!0,providerName:"github"};await ae(t,e,l);}catch(s){console.error("GitHub OAuth error:",s),e.status(500).json({error:"Authentication failed"});}}function cn(){let t=Router(),e=(o,n,r)=>{let i=!!a$1("_system.user.auth.github.enabled"),s=String(a$1("_system.user.auth.github.clientId")),a=String(a$1("_system.user.auth.github.clientSecret"));if(!i||!s||!a){n.status(503).json({error:"GitHub authentication is not configured"});return}r();};return t.get("/api/_internal/auth/github",e,(o,n)=>{let r=String(a$1("_system.user.auth.github.clientId")),i=q("github"),s=a$1("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(l=>l.trim()).join(" "):"user:email",c=new URL("https://github.com/login/oauth/authorize");c.searchParams.append("client_id",r),c.searchParams.append("redirect_uri",i),c.searchParams.append("scope",a),n.redirect(c.toString());}),t.get("/api/_internal/auth/github/callback",e,an),t}var Ft=cn;function Zt(t,e,o){return async(n,r,i)=>{let s=n.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&A())try{let{session:l,user:p}=await M(s);a={session:l,user:p};}catch{}let c=k$1("route",`route:${t.toLowerCase()}:${e}`,{method:t,path:e,query:n.query,body:n.body,params:n.params});try{let l=await o({query:n.query,body:n.body,params:n.params,headers:n.headers,cookies:n.cookies,rawBody:Buffer.isBuffer(n.body)?n.body:void 0,req:n,res:r,next:i},a);c.end(),l&&(r.status(l.status||200),l.redirect&&r.redirect(l.redirect),l.headers&&Object.entries(l.headers).forEach(([p,f])=>{r.setHeader(p,f);}),r.send(l.data));}catch(l){c.end("error"),l instanceof a$3?r.status(l.status).send(l.message):(console.error(`Error in route handler: ${n.path}`),console.error(l),r.status(500).send(String(l)));}}}var Ae=Object.freeze({});function Wt(t){Ae=Object.freeze(Object.assign({},Ae,t));}function le(){return Ae}function un(t){let e=[];if(!t)return e.push(R.json({limit:"16mb"})),e.push(R.urlencoded({extended:true,limit:"16mb"})),e;if(t.json!==false){let o=typeof t.json=="object"?t.json:{limit:"16mb"};e.push(R.json(o));}if(t.urlencoded!==false){let o=typeof t.urlencoded=="object"?t.urlencoded:{extended:true,limit:"16mb"};e.push(R.urlencoded(o));}if(t.raw){let o=typeof t.raw=="object"?t.raw:{},n={limit:o.limit||"16mb",type:o.type||"*/*"};e.push(R.raw(n));}return e}function mn(t,e){for(let o of e)for(let n of o.routes){let{path:r,handlers:i,body:s}=n,a=un(s);Object.entries(i).forEach(([c,l])=>{t[c](r,...a,Zt(c,r,l));});}}async function Bt(t,{combinedModules:e,channels:o}){let n=R();n.use(ln()),mn(n,e),n.use(R.json({limit:"16mb"})),n.use(R.urlencoded({extended:true,limit:"16mb"})),n.use(qt()),n.use(Ft()),n.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let{methodName:l}=a.params,p=await Me(a);try{let f=await nt(l,a.body.args,p);c.json({data:f,typeMap:a$2(f)});}catch(f){pn(c,l,f);}}),await t.init(),t.middlewares&&n.use(t.middlewares()),n.all("*",(a,c)=>t.handler(a,c)),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let r=dn.createServer(n),i$1=le()?.provider;i$1&&i$1.init({httpServer:r,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;r.listen(s,()=>{i("Application started",{source:"app"});let a=process.env.MODELENCE_SITE_URL||`http://localhost:${s}`;console.log(`
16
+ Application started on ${a}
17
+ `);});}async function Me(t){let e=k.string().nullish().transform(i=>i??null).parse(t.cookies.authToken||t.body.authToken),o=k.object({screenWidth:k.number(),screenHeight:k.number(),windowWidth:k.number(),windowHeight:k.number(),pixelRatio:k.number(),orientation:k.string().nullable()}).nullish().parse(t.body.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},n={ip:fn(t),userAgent:t.get("user-agent"),acceptLanguage:t.get("accept-language"),referrer:t.get("referrer"),baseUrl:t.protocol+"://"+t.get("host")};if(!!A()){let{session:i,user:s,roles:a}=await M(e);return {clientInfo:o,connectionInfo:n,session:i,user:s,roles:a}}return {clientInfo:o,connectionInfo:n,session:null,user:null,roles:X()}}function pn(t,e,o){if(console.error(`Error in method ${e}:`,o),o instanceof a$3)t.status(o.status).send(o.message);else if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r=o.flatten(),i=Object.entries(r.fieldErrors).map(([c,l])=>`${c}: ${(l??[]).join(", ")}`).join("; "),s=r.formErrors.join("; "),a=[i,s].filter(Boolean).join("; ");t.status(400).send(a);}else t.status(500).send(o instanceof Error?o.message:String(o));}function fn(t){let e=t.headers["x-forwarded-for"];if(e)return (Array.isArray(e)?e[0]:e.split(",")[0]).trim();let o=t.ip||t.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}async function wn({modules:t=[],roles:e$1={},defaultRoles:o={},server:n=Nt,migrations:r=[],email:i={},auth:s={},websocket:a={}}){Jt.config(),Jt.config({path:".modelence.env"});let c$1=!!process.env.MODELENCE_SERVICE_ENDPOINT,l=process.env.MODELENCE_CRON_ENABLED==="true";On().then(()=>{}).catch(()=>{});let p=[Et,He,It,Pt,Ut,jt,ke],f$1=[...p,...t];e(),Sn(p),bn(t),Qe(e$1,o);let C=Tn(f$1);d$2(C);let U=En(f$1),de=Cn(f$1);l&&vn(f$1);let Vt=xn(f$1);if(yt(Vt),c$1){let{configs:ue,environmentId:Qt,appAlias:Gt,environmentAlias:Kt,telemetry:Yt}=await Ct({configSchema:C,cronJobsMetadata:l?At():void 0,stores:U});c(ue),f({environmentId:Qt,appAlias:Gt,environmentAlias:Kt,telemetry:Yt});}else c(Rn(C));ct(i),mt(s),Wt({...a,provider:a.provider||it});let Le=A();if(Le&&(await Ke(),Dn(U)),l&&Lt(r),Le)for(let ue of U)ue.createIndexes();c$1&&(await g(),vt()),l&&Mt().catch(console.error),await Bt(n,{combinedModules:f$1,channels:de});}function bn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))ge(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))Ye(`${e.name}.${o}`,n);}}function Sn(t){for(let e of t){for(let[o,n]of Object.entries(e.queries))Xe(`${e.name}.${o}`,n);for(let[o,n]of Object.entries(e.mutations))et(`${e.name}.${o}`,n);}}function En(t){return t.flatMap(e=>e.stores)}function Cn(t){return t.flatMap(e=>e.channels)}function xn(t){return t.flatMap(e=>e.rateLimits)}function Tn(t){let e={};for(let o of t)for(let[n,r]of Object.entries(o.configSchema)){let i=`${o.name}.${n}`;if(i in e)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);e[i]=r;}return e}function vn(t){for(let e of t)for(let[o,n]of Object.entries(e.cronJobs))Ot(`${e.name}.${o}`,n);}function Dn(t){let e=ee();if(!e)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of t)o.init(e);}var _n={MONGODB_URI:"_system.mongodbUri",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"};function kn(t,e){if(e==="number"){let o=Number(t);if(isNaN(o))throw new Error(`Invalid number value for config: ${t}`);return o}if(e==="boolean"){if(t.toLowerCase()==="true")return true;if(t.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${t}`)}return t}function Rn(t){let e=[];for(let[o,n]of Object.entries(_n)){let r=process.env[o],i=t[n];if(r){let s=i?.type??"string";e.push({key:n,type:s,value:kn(r,s)});}}return e}async function On(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let e=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,n=await Mn(),r=await import('./package-3YQBVIVQ.js');await fetch(`${e}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:n.name,version:r.default.version,localHostname:Io.hostname(),environmentId:o})});}}async function Mn(){try{let t=Re.join(process.cwd(),"package.json"),e=await hn.readFile(t,"utf-8");return {name:JSON.parse(e).name||"unknown"}}catch{return {name:"unknown"}}}async function Ht(t){await v.deleteMany({userId:t}),await E.deleteMany({userId:t});}async function In(t){await Ht(t),await m.updateOne(t,{$set:{status:"disabled",disabledAt:new Date}});}async function Ln(t){await Ht(t),await m.updateOne({_id:t},{$set:{handle:`deleted-${t}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Ie=class{constructor(e,o){this.category=e,this.canAccessChannel=o||null;}broadcast(e,o){let n=le().provider;if(!n){j$1("Websockets provider should be added to startApp",{});return}n.broadcast({category:this.category,id:e,data:o});}};function Pn(t){if(!b().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return b().provider?.sendEmail(t)}
18
+ export{S as Module,Ie as ServerChannel,w as Store,M as authenticate,L as consumeRateLimit,ge as createQuery,m as dbUsers,Ln as deleteUser,In as disableUser,d as schema,Pn as sendEmail,wn as startApp};//# sourceMappingURL=server.js.map
19
+ //# sourceMappingURL=server.js.map