modelence 0.22.2-dev.0 → 0.22.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-PJRYLKYW.js → chunk-3AAYSVBO.js} +2 -2
- package/dist/{chunk-PJRYLKYW.js.map → chunk-3AAYSVBO.js.map} +1 -1
- package/dist/{chunk-ZFLDBA4Z.js → chunk-AV6IY6VJ.js} +13 -13
- package/dist/chunk-AV6IY6VJ.js.map +1 -0
- package/dist/{chunk-YOJ4ZP5D.js → chunk-LZBPGWJ3.js} +3 -3
- package/dist/{chunk-YOJ4ZP5D.js.map → chunk-LZBPGWJ3.js.map} +1 -1
- package/dist/chunk-MR7N4IMS.js +3 -0
- package/dist/{chunk-AVSGSBOJ.js.map → chunk-MR7N4IMS.js.map} +1 -1
- package/dist/chunk-QYRH7EHP.js +2 -0
- package/dist/chunk-QYRH7EHP.js.map +1 -0
- package/dist/{package-D46XO2RL.js → package-4ZGFPZJJ.js} +2 -2
- package/dist/{package-D46XO2RL.js.map → package-4ZGFPZJJ.js.map} +1 -1
- package/dist/{render-CBIFY4DG.js → render-5XIQVJUB.js} +2 -2
- package/dist/{render-CBIFY4DG.js.map → render-5XIQVJUB.js.map} +1 -1
- package/dist/server-A3J4ITUK.js +2 -0
- package/dist/{server-PMB4WMWG.js.map → server-A3J4ITUK.js.map} +1 -1
- package/dist/server.js +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/transport-THBSSHUH.js +2 -0
- package/dist/{transport-C7DEK6NV.js.map → transport-THBSSHUH.js.map} +1 -1
- package/package.json +1 -3
- package/dist/chunk-AVSGSBOJ.js +0 -3
- package/dist/chunk-VF4RU7MF.js +0 -3
- package/dist/chunk-VF4RU7MF.js.map +0 -1
- package/dist/chunk-ZFLDBA4Z.js.map +0 -1
- package/dist/server-PMB4WMWG.js +0 -2
- package/dist/transport-C7DEK6NV.js +0 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {a,b as b$1,m,i}from'./chunk-
|
|
1
|
+
import {a,b as b$1,m,i}from'./chunk-QYRH7EHP.js';import {a as a$2,b as b$2}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import {isDeepStrictEqual}from'util';import {MongoError,ObjectId,MongoServerError}from'mongodb';import {z as z$1}from'zod';import {createHash,randomBytes}from'crypto';var E=class{constructor(e,{stores:t=[],queries:i={},mutations:r={},routes:a=[],cronJobs:c={},configSchema:d={},rateLimits:m=[],channels:g=[]}={}){this.name=e,this.stores=t,this.queries=i,this.mutations=r,this.routes=a,this.cronJobs=c,this.configSchema=d,this.rateLimits=m,this.channels=g;}getConfig(e){return a(`${this.name}.${e}`)}};function D(n){let e=n._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:D(e.type)};if(e.typeName==="ZodObject"){let i=e.shape(),r={};for(let[a,c]of Object.entries(i))r[a]=D(c);return {type:"object",items:r}}if(e.typeName==="ZodOptional")return {...D(e.innerType),optional:true};if(e.typeName==="ZodNullable")return {...D(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(D)};if(e.typeName==="ZodEffects"){let t=e;return t.description?{type:"custom",typeName:t.description}:D(t.schema)}return {type:"custom",typeName:e.typeName}}function Z(n){let e={};for(let[t,i]of Object.entries(n))Array.isArray(i)?e[t]=i.map(r=>typeof r=="object"&&"_def"in r?D(r):Z(r)):typeof i=="object"&&"_def"in i?e[t]=D(i):e[t]=Z(i);return e}var j=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),ie=n=>j(n)&&"_def"in n,Q=n=>n._def,re=n=>{let e=Q(n);if(e.typeName==="ZodOptional"||e.typeName==="ZodNullable"||e.typeName==="ZodDefault"||e.typeName==="ZodCatch"||e.typeName==="ZodReadonly")return e.innerType;if(e.typeName==="ZodEffects")return e.schema;if(e.typeName==="ZodBranded")return e.type;if(e.typeName==="ZodPipeline")return e.out},oe=n=>{let e=Q(n);if(e.typeName==="ZodDefault")return {hasDefault:true,value:e.defaultValue()};let t=re(n);return t?oe(t):{hasDefault:false}},W=(n,e)=>{let t=Q(n);if(t.typeName==="ZodObject"&&j(e))return F(t.shape(),e);if(t.typeName==="ZodArray"&&Array.isArray(e))return e.map(r=>W(t.type,r));let i=re(n);return i?W(i,e):e},N=(n,e)=>ie(n)?W(n,e):Array.isArray(n)&&Array.isArray(e)?n.length===1?e.map(t=>N(n[0],t)):e.map((t,i)=>N(n[i],t)):j(n)&&j(e)?F(n,e):e,F=(n,e)=>{let t={...e};for(let[i,r]of Object.entries(n)){let a=t[i];if(a===void 0){if(ie(r)){let c=oe(r);c.hasDefault&&(t[i]=N(r,c.value));}continue}t[i]=N(r,a);}return t};var be="[modelence:index-error]";function se(n){return n instanceof MongoServerError?n.code===11e3||n.message.includes("E11000"):false}function ae(n,e,t){let i={problem:"unique-index-violation",collection:n,index:{name:e.name??null,key:e.key,collation:e.collation??null,partialFilterExpression:e.partialFilterExpression??null},duplicateKey:t.keyValue??null,serverError:t.errmsg??t.message},r=e.collation?{collation:e.collation}:void 0,a=`db.getCollection(${JSON.stringify(n)}).aggregate(${JSON.stringify(we(e))}`+(r?`, ${JSON.stringify(r)}`:"")+")";return [`${be} Unique index '${e.name??JSON.stringify(e.key)}' on collection '${n}' could not be created because existing documents already violate it. Until this is resolved the constraint is NOT enforced, so new duplicates can still be written.`,`Details: ${JSON.stringify(i)}`,"Find the conflicting documents with:",` ${a}`,"Fix: merge, delete, or update the conflicting documents so each indexed value is unique, then restart the app \u2014 the index build is retried on startup."].join(`
|
|
2
2
|
`)}function we(n){let e=Object.keys(n.key),t=e.flatMap(r=>De(r).map(a=>({$unwind:{path:`$${a}`,preserveNullAndEmptyArrays:true}}))),i=Object.fromEntries(e.map(r=>[r.replace(/\./g,"_"),`$${r}`]));return [...n.partialFilterExpression?[{$match:n.partialFilterExpression}]:[],...t,{$group:{_id:i,ids:{$addToSet:"$_id"}}},{$match:{$expr:{$gt:[{$size:"$ids"},1]}}},{$limit:100}]}function De(n){let e=n.split(".");return e.map((t,i)=>e.slice(0,i+1).join("."))}var Ie=["background","bits","bucketSize","collation","default_language","expireAfterSeconds","hidden","language_override","max","min","partialFilterExpression","sparse","storageEngine","textIndexVersion","unique","weights","wildcardProjection","2dsphereIndexVersion"],B=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Oe=n=>n.startsWith("_modelence_"),J=n=>{let e={};for(let t of Ie){let i=n[t];i!==void 0&&(e[t]=i);}return e},Ce=(n,e)=>{if(!B(n)||!B(e))return false;let t=Object.entries(n),i=Object.entries(e);return t.length!==i.length?false:t.every(([r,a],c)=>{let[d,m]=i[c]||[];return r===d&&isDeepStrictEqual(a,m)})},ce=(n,e)=>Ce(n.key,e.key)?isDeepStrictEqual(J(n),J(e)):false,K=n=>B(n)?Object.entries(n).map(([e,t])=>`${e}:${JSON.stringify(t)}`).join("|"):null,ke=async n=>{try{return await n.listIndexes().toArray()}catch(e){if(e instanceof MongoError&&e.code===26)return [];throw e}},Ae=n=>Object.entries(n).map(([e,t])=>`${e}_${t}`).join("_"),_e=n=>{if(n.name){let t=n.name.startsWith("_modelence_")?n.name:`_modelence_${n.name}`;return {...n,name:t}}let e=Ae(n.key);return {...n,name:`_modelence_${e}`}},f=class n{constructor(e,t){this._chainParent=null;this._chainChild=null;this.name=e,this.schema=t.schema,this.methods=t.methods,this.indexes=t.indexes.map(_e),this.searchIndexes=t.searchIndexes||[],this.indexCreationMode=t.indexCreationMode??"background";}getName(){return this.name}getIndexCreationMode(){return this.indexCreationMode}getSchema(){return this.schema}getSerializedSchema(){return Z(this.schema)}getIndexes(){return this.indexes}getSearchIndexes(){return this.searchIndexes}getChainTail(){let e=this;for(;e._chainChild;)e=e._chainChild;return e}getChainRoot(){let e=this;for(;e._chainParent;)e=e._chainParent;return e}extend(e){let t=this.getChainTail();if(this.client||t.client)throw new Error(`Store.extend() must be called before startApp(). Store '${this.name}' has already been initialized and cannot be extended.`);let i={...t.schema,...e.schema||{}},r=[...t.indexes,...e.indexes||[]],a=[...t.searchIndexes,...e.searchIndexes||[]],c={...t.methods||{},...e.methods||{}},d=new n(this.name,{schema:i,methods:c,indexes:r,searchIndexes:a,indexCreationMode:e.indexCreationMode??t.indexCreationMode});return t._chainChild=d,d._chainParent=t,d}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(e="full"){let t=this.requireCollection(),i=e!=="create-only",r=e!=="drop-only",a=await ke(t),c=new Map,d=new Map,m=new Set,g=s=>{c.set(s.name,s);let l=K(s.key);if(!l)return;let u=d.get(l);u?u.add(s.name):d.set(l,new Set([s.name]));},w=s=>{let l=c.get(s);if(!l)return;c.delete(s);let u=K(l.key);if(!u)return;let T=d.get(u);T&&(T.delete(s),T.size===0&&d.delete(u));};for(let s of a)typeof s.name=="string"&&g({...s,name:s.name});let y=async s=>{if(!(s==="_id_"||m.has(s))){try{await t.dropIndex(s);}catch(l){if(!(l instanceof MongoError&&l.code===27))throw l}m.add(s),w(s);}};if(i){let s=new Set(this.indexes.map(u=>u.name).filter(u=>typeof u=="string")),l=[...c.values()].filter(u=>Oe(u.name)&&!s.has(u.name));for(let u of l)await y(u.name);}if(this.indexes.length>0)for(let s of this.indexes){if(!s.name)continue;let l=false,u=c.get(s.name);u&&!ce(u,s)&&(i?await y(u.name):l=true);let T=K(s.key);if(T){let x=[...d.get(T)||[]];for(let O of x)O!==s.name&&(i?await y(O):l=true);}let v=c.get(s.name);if(!(!!v&&ce(v,s))&&r&&!l){try{await t.createIndexes([s]);}catch(x){throw s.unique&&se(x)&&console.error(ae(this.name,s,x)),x}g({name:s.name,key:s.key,...J(s)});}}if(r&&this.searchIndexes.length>0)for(let s of this.searchIndexes)try{await t.createSearchIndexes([s]);}catch(l){if(l instanceof MongoError&&l.code===68&&s.name)await t.dropSearchIndex(s.name),await t.createSearchIndexes([s]);else throw l}}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,t){let i=await this.requireCollection().findOne(e,t);return i?this.wrapDocument(i):null}async requireOne(e,t,i){let r=await this.findOne(e,t);if(!r)throw i?i():new Error(`Record not found in ${this.name}`);return r}find(e,t){let i=this.requireCollection().find(e,t?.projection?{projection:t.projection}:void 0);return t?.sort&&i.sort(t.sort),t?.limit&&i.limit(t.limit),t?.skip&&i.skip(t.skip),i}async findById(e){let t=typeof e=="string"?{_id:new ObjectId(e)}:{_id:e};return await this.findOne(t)}async requireById(e,t){let i=await this.findById(e);if(!i)throw t?t():new Error(`Record with id ${e} not found in ${this.name}`);return i}countDocuments(e){return this.requireCollection().countDocuments(e)}async fetch(e,t){return (await this.find(e,t).toArray()).map(this.wrapDocument.bind(this))}async insertOne(e,t){return await this.requireCollection().insertOne(e,t)}async create(e,t){let i=F(this.schema,{_id:new ObjectId,...e});return await this.requireCollection().insertOne(i,t),this.wrapDocument(i)}async insertMany(e,t){return await this.requireCollection().insertMany(e,t)}async updateOne(e,t,i){return await this.requireCollection().updateOne(this.getSelector(e),t,i)}async upsertOne(e,t,i){return await this.requireCollection().updateOne(this.getSelector(e),t,{upsert:true,...i})}async updateMany(e,t,i){return await this.requireCollection().updateMany(e,t,i)}async upsertMany(e,t,i){return await this.requireCollection().updateMany(e,t,{upsert:true,...i})}async deleteOne(e,t){return await this.requireCollection().deleteOne(this.getSelector(e),t)}async deleteMany(e,t){return await this.requireCollection().deleteMany(e,t)}async findOneAndUpdate(e,t,i){let r=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,i??{});return r?this.wrapDocument(r):null}async findOneAndUpsert(e,t,i){let r=await this.requireCollection().findOneAndUpdate(this.getSelector(e),t,{upsert:true,...i,returnDocument:"after",includeResultMetadata:true});return {doc:r.value?this.wrapDocument(r.value):null,isNew:!!r.lastErrorObject?.upserted}}async findOneAndDelete(e,t){let i=await this.requireCollection().findOneAndDelete(this.getSelector(e),t??{});return i?this.wrapDocument(i):null}async findOneAndReplace(e,t,i){let r=await this.requireCollection().findOneAndReplace(this.getSelector(e),t,i??{});return r?this.wrapDocument(r):null}async replaceOne(e,t,i){return await this.requireCollection().replaceOne(this.getSelector(e),t,i)}async distinct(e,t,i){let r=t??{};return i!==void 0?await this.requireCollection().distinct(e,r,i):await this.requireCollection().distinct(e,r)}watch(e,t){return this.requireCollection().watch(e,t)}aggregate(e,t){return this.requireCollection().aggregate(e,t)}bulkWrite(e){return this.requireCollection().bulkWrite(e)}getDatabase(){return this.requireClient().db()}rawCollection(){return this.requireCollection()}async renameFrom(e,t){let i=this.getDatabase();if(!this.collection||!i)throw new Error(`Store ${this.name} is not provisioned`);if((await i.listCollections({name:e}).toArray()).length===0)throw new Error(`Collection ${e} not found`);if((await i.listCollections({name:this.name}).toArray()).length>0)throw new Error(`Collection ${this.name} already exists`);await i.collection(e).rename(this.name,t);}async vectorSearch({field:e,embedding:t,numCandidates:i,limit:r,projection:a,indexName:c}){return this.aggregate([{$vectorSearch:{index:c||e+"VectorSearch",path:e,queryVector:t,numCandidates:i||100,limit:r||10}},{$project:{_id:1,score:{$meta:"vectorSearchScore"},...a}}])}static vectorIndex({field:e,dimensions:t,similarity:i="cosine",indexName:r}){return {type:"vectorSearch",name:r||e+"VectorSearch",definition:{fields:[{type:"vector",path:e,numDimensions:t,similarity:i}]}}}};var Me=z$1.string.bind(z$1),ve=z$1.number.bind(z$1),Re=z$1.date.bind(z$1),Ee=z$1.boolean.bind(z$1),Ze=z$1.array.bind(z$1),je=z$1.object.bind(z$1),Ne=z$1.enum.bind(z$1),o={string:Me,number:ve,date:Re,boolean:Ee,array:Ze,object:je,enum:Ne,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(n){return z$1.instanceof(ObjectId).describe("Ref")},union:z$1.union.bind(z$1),infer(n){return {}}};function C(n){return createHash("sha256").update(n).digest("hex")}var X=new f("_modelenceLinkNonces",{schema:{nonce:o.string(),userId:o.string(),expiresAt:o.date()},indexes:[{key:{nonce:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});async function Gt(n){let e=randomBytes(32).toString("hex");return await X.insertOne({nonce:e,userId:n,expiresAt:new Date(Date.now()+a$1.minutes(10))}),e}async function Yt(n){let e=await X.findOneAndDelete({nonce:n});return e?e.userId:null}var b=new f("_modelenceSessions",{schema:{authToken:o.string(),createdAt:o.date(),expiresAt:o.date(),userId:o.userId().nullable()},indexes:[{key:{authToken:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0},{key:{userId:1}}]});async function ue(n){if(n){let e=C(n),t=await b.findOne({authToken:e}),i=/^[0-9a-f]{64}$/i.test(n);if(!t&&!i&&(t=await b.findOne({authToken:n}),t&&await b.updateOne({_id:t._id},{$set:{authToken:e}})),t)return {authToken:n,expiresAt:new Date(t.expiresAt),userId:t.userId??null}}return await $e()}async function en(n,e){await b.updateOne({authToken:C(n)},{$set:{userId:e}});}async function tn(n){await b.updateOne({authToken:C(n)},{$set:{userId:null}});}async function nn(n){await b.deleteMany({userId:n});}async function $e(n=null){let e=randomBytes(32).toString("base64url"),t=Date.now(),i=new Date(t+a$1.days(7));return await b.insertOne({authToken:C(e),createdAt:new Date(t),expiresAt:i,userId:n}),{authToken:e,expiresAt:i,userId:n}}async function ze(n){let e=Date.now(),t=new Date(e+a$1.days(7));await b.updateOne({authToken:C(n.authToken)},{$set:{lastActiveDate:new Date(e),expiresAt:t}});}function Pe(n,e){n.cookie("authToken",e,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/",maxAge:a$1.days(7)});}function rn(n){n.clearCookie("authToken",{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/"});}var on=new E("_system.session",{stores:[b,X],mutations:{init:async function(n,{session:e,user:t,res:i}){return i&&e?.userId&&Pe(i,e.authToken),{session:e,user:t,configs:b$1()}},heartbeat:async function(n,{session:e}){e&&await ze(e);}}});var pe=new f("_modelenceUsers",{schema:{handle:o.string(),emails:o.array(o.object({address:o.string(),verified:o.boolean()})).optional(),status:o.enum(["active","disabled","deleted"]).optional(),firstName:o.string().optional(),lastName:o.string().optional(),avatarUrl:o.string().optional(),createdAt:o.date(),disabledAt:o.date().optional(),deletedAt:o.date().optional(),roles:o.array(o.string()).optional(),authMethods:o.object({password:o.object({hash:o.string()}).optional(),google:o.object({id:o.string()}).optional(),github:o.object({id:o.string()}).optional()})},indexes:[{key:{handle:1},unique:true,collation:{locale:"en",strength:2}},{key:{"emails.address":1,status:1}},{key:{"emails.address":1},unique:true,collation:{locale:"en",strength:2},partialFilterExpression:{"emails.address":{$exists:true}}},{key:{"authMethods.google.id":1},sparse:true,unique:true},{key:{"authMethods.github.id":1},sparse:true,unique:true}]}),dn=new f("_modelenceDisposableEmailDomains",{schema:{domain:o.string(),addedAt:o.date()},indexes:[{key:{domain:1},unique:true}]}),ln=new f("_modelenceEmailVerificationTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),un=new f("_modelenceResetPasswordTokens",{schema:{userId:o.objectId(),email:o.string().optional(),token:o.string(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]}),pn=new f("_modelenceMagicLinkTokens",{schema:{email:o.string(),token:o.string(),code:o.string(),attempts:o.number(),createdAt:o.date(),expiresAt:o.date()},indexes:[{key:{token:1},unique:true},{key:{email:1}},{key:{expiresAt:1},expireAfterSeconds:0}]});var he=new Map,k={authenticated:null,unauthenticated:null};function mn(n,e){k.authenticated=e.authenticated,k.unauthenticated=e.unauthenticated;for(let[t,i]of Object.entries(n))he.set(t,i);}function me(){return k.unauthenticated?[k.unauthenticated]:[]}function ye(){return k.authenticated?[k.authenticated]:[]}function G(n,e){let t=e.find(i=>!qe(n,i));if(t)throw new Error(`Access denied - missing permission: '${t}'`)}function qe(n,e){for(let t of n)if(he.get(t)?.permissions?.includes(e))return true;return false}async function fe(n){let e=await ue(n),t=e.userId?await pe.findOne({_id:new ObjectId(e.userId),status:{$nin:["deleted","disabled"]}}):null,i=t?{id:t._id.toString(),handle:t.handle,roles:t.roles||[],hasRole:a=>(t.roles||[]).includes(a),requireRole:a=>{if(!(t.roles||[]).includes(a))throw new Error(`Access denied - role '${a}' required`)},firstName:t.firstName??void 0,lastName:t.lastName??void 0,avatarUrl:t.avatarUrl??void 0}:null,r=i?ye():me();return {user:i,session:e,roles:r}}var _=class{constructor(e){this.fetch=e.fetch,this.watch=e.watch;}};function Ue(){return typeof window!="object"}function I(){if(!Ue())throw new Error("This function can only be called on the server")}function wn(n){return n.replace(/<[^>]*>/g,"").replace(/\s+/g," ").trim()}var M=new Map;function We(n){let e=M.get(n.id);return e||(e=new Map,M.set(n.id,e)),e}async function Qe(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1),method:z$1.string().min(1),args:z$1.record(z$1.unknown()).default({}),authToken:z$1.string().nullish(),clientInfo:z$1.object({screenWidth:z$1.number(),screenHeight:z$1.number(),windowWidth:z$1.number(),windowHeight:z$1.number(),pixelRatio:z$1.number(),orientation:z$1.string().nullable()}).optional()}).safeParse(e);if(!t.success){n.emit("liveQueryError",{subscriptionId:null,error:`Invalid payload: ${t.error.message}`});return}let{subscriptionId:i,method:r,args:a,authToken:c,clientInfo:d}=t.data,m=We(n),g=m.get(i);if(g)if(g.cleanup)try{g.cleanup();}catch(y){console.error("[LiveQuery] Error cleaning up existing subscription:",y);}else g.aborted=true;let w={cleanup:null};m.set(i,w);try{let{session:y,user:s,roles:l}=await fe(c??null),u={session:y,user:s,roles:l,clientInfo:d??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},connectionInfo:{ip:n.handshake.address,userAgent:n.handshake.headers["user-agent"]},req:null,res:null},T=await ge(r,a,u),v=async()=>{let S=a$2(await T.fetch());w.aborted||n.emit("liveQueryData",{subscriptionId:i,data:S,typeMap:b$2(S)});},R=!0,x=!1,O=()=>{w.aborted||!R||x||(R=!1,x=!0,v().catch(S=>{w.aborted||(console.error(`[LiveQuery] Error fetching data for ${r}:`,S),n.emit("liveQueryError",{subscriptionId:i,error:S instanceof Error?S.message:String(S)}));}).finally(()=>{x=!1,O();}));},q=T.watch({publish:()=>{R=!0,O();}});if(w.aborted){if(q)try{q();}catch(S){console.error("[LiveQuery] Error cleaning up after disconnect during setup:",S);}return}w.cleanup=q||null,O();}catch(y){m.delete(i),console.error(`[LiveQuery] Error in ${r}:`,y),n.emit("liveQueryError",{subscriptionId:i,error:y instanceof Error?y.message:String(y)});}}function Ke(n,e){let t=z$1.object({subscriptionId:z$1.string().min(1)}).safeParse(e);if(!t.success){console.warn(`[LiveQuery] Invalid unsubscribe payload: ${t.error.message}`);return}let{subscriptionId:i}=t.data,r=M.get(n.id);if(!r)return;let a=r.get(i);if(a){if(a.cleanup)try{a.cleanup();}catch(c){console.error("[LiveQuery] Error in cleanup:",c);}else a.aborted=true;r.delete(i);}}function Ve(n){let e=M.get(n.id);if(e){for(let t of e.values())if(t.cleanup)try{t.cleanup();}catch(i){console.error("[LiveQuery] Error in cleanup on disconnect:",i);}else t.aborted=true;M.delete(n.id);}}var z={};function Nn(n,e){return I(),Te(n),P("query",n,e)}function Fn(n,e){return I(),Te(n),P("mutation",n,e)}function $n(n,e){return I(),xe(n),P("query",n,e)}function zn(n,e){return I(),xe(n),P("mutation",n,e)}function Te(n){if(n.toLowerCase().startsWith("_system."))throw new Error(`Method name cannot start with a reserved prefix: '_system.' (${n})`)}function xe(n){if(!n.toLowerCase().startsWith("_system."))throw new Error(`System method name must start with a prefix: '_system.' (${n})`)}function P(n,e,t){if(I(),z[e])throw new Error(`Method with name '${e}' is already defined.`);let i=typeof t=="function"?t:t.handler,r=typeof t=="function"?[]:t.permissions??[];z[e]={type:n,name:e,handler:i,permissions:r};}async function Pn(n,e,t){I();let i$1=z[n];if(!i$1)throw new Error(`Method with name '${n}' is not defined.`);let{type:r,handler:a}=i$1,c=m("method",`method:${n}`,{type:r,args:i(e)}),d;try{G(t.roles,i$1.permissions),d=await a(e,t);}catch(m){throw c.end("error"),m}return c.end(),d}async function ge(n,e,t){I();let i$1=z[n];if(!i$1)throw new Error(`Method with name '${n}' is not defined.`);let{type:r,handler:a}=i$1;if(r!=="query")throw new Error("Live methods are only supported for queries");let c=m("method",`method:${n}:live`,{type:r,args:i(e)}),d;try{if(G(t.roles,i$1.permissions),d=await a(e,t),!(d instanceof _))throw new Error(`Live query handler for '${n}' must return a LiveData object with fetch and watch functions. See https://docs.modelence.com/live-queries`)}catch(m){throw c.end("error"),m}return c.end(),d}
|
|
3
|
-
export{Fn as A,$n as B,zn as C,Pn as D,Qe as E,Ke as F,Ve as G,E as a,f as b,o as c,C as d,Gt as e,Yt as f,b as g,ue as h,en as i,tn as j,nn as k,$e as l,Pe as m,rn as n,on as o,pe as p,dn as q,ln as r,un as s,pn as t,mn as u,me as v,fe as w,_ as x,wn as y,Nn as z};//# sourceMappingURL=chunk-
|
|
4
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
export{Fn as A,$n as B,zn as C,Pn as D,Qe as E,Ke as F,Ve as G,E as a,f as b,o as c,C as d,Gt as e,Yt as f,b as g,ue as h,en as i,tn as j,nn as k,$e as l,Pe as m,rn as n,on as o,pe as p,dn as q,ln as r,un as s,pn as t,mn as u,me as v,fe as w,_ as x,wn as y,Nn as z};//# sourceMappingURL=chunk-LZBPGWJ3.js.map
|
|
4
|
+
//# sourceMappingURL=chunk-LZBPGWJ3.js.map
|