modelence 0.21.0 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/chunk-4L4E6PFO.js +3 -0
  2. package/dist/chunk-4L4E6PFO.js.map +1 -0
  3. package/dist/chunk-AMJHJA2V.js +2 -0
  4. package/dist/chunk-AMJHJA2V.js.map +1 -0
  5. package/dist/chunk-BCUSVRAY.js +2 -0
  6. package/dist/chunk-BCUSVRAY.js.map +1 -0
  7. package/dist/chunk-OFRRQZVE.js +37 -0
  8. package/dist/chunk-OFRRQZVE.js.map +1 -0
  9. package/dist/chunk-OJ3LMWVQ.js +2 -0
  10. package/dist/{chunk-TBGXZXAA.js.map → chunk-OJ3LMWVQ.js.map} +1 -1
  11. package/dist/{chunk-SNADMLAT.js → chunk-PJRYLKYW.js} +2 -2
  12. package/dist/{chunk-SNADMLAT.js.map → chunk-PJRYLKYW.js.map} +1 -1
  13. package/dist/chunk-VF4RU7MF.js +3 -0
  14. package/dist/chunk-VF4RU7MF.js.map +1 -0
  15. package/dist/chunk-YOJ4ZP5D.js +4 -0
  16. package/dist/chunk-YOJ4ZP5D.js.map +1 -0
  17. package/dist/client.d.ts +89 -4
  18. package/dist/client.js +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/{package-BVTS5E5V.js → package-RFIDFU5I.js} +2 -2
  21. package/dist/{package-BVTS5E5V.js.map → package-RFIDFU5I.js.map} +1 -1
  22. package/dist/render-CBIFY4DG.js +2 -0
  23. package/dist/render-CBIFY4DG.js.map +1 -0
  24. package/dist/renderApp-J347DR2B.js +2 -0
  25. package/dist/{renderApp-QYMNQ3KS.js.map → renderApp-J347DR2B.js.map} +1 -1
  26. package/dist/server-LA5VRAGR.js +2 -0
  27. package/dist/{server-KAHRRRDU.js.map → server-LA5VRAGR.js.map} +1 -1
  28. package/dist/server.d.ts +53 -8
  29. package/dist/server.js +1 -1
  30. package/dist/telemetry.d.ts +6 -1
  31. package/dist/telemetry.js +1 -1
  32. package/dist/transport-C7DEK6NV.js +2 -0
  33. package/dist/{transport-W6JIYZKZ.js.map → transport-C7DEK6NV.js.map} +1 -1
  34. package/dist/{types-B_R3eHmq.d.ts → types-B8uEAj0y.d.ts} +1 -1
  35. package/dist/{types-_BTBqn8b.d.ts → types-D_70a365.d.ts} +47 -2
  36. package/dist/types.d.ts +2 -2
  37. package/package.json +4 -6
  38. package/dist/chunk-3SGMDISS.js +0 -29
  39. package/dist/chunk-3SGMDISS.js.map +0 -1
  40. package/dist/chunk-7LPSX5A6.js +0 -3
  41. package/dist/chunk-7LPSX5A6.js.map +0 -1
  42. package/dist/chunk-KZZYA5HP.js +0 -3
  43. package/dist/chunk-KZZYA5HP.js.map +0 -1
  44. package/dist/chunk-SD3ERG2G.js +0 -3
  45. package/dist/chunk-SD3ERG2G.js.map +0 -1
  46. package/dist/chunk-TBGXZXAA.js +0 -2
  47. package/dist/chunk-YLLX26A4.js +0 -2
  48. package/dist/chunk-YLLX26A4.js.map +0 -1
  49. package/dist/chunk-YRR32LTF.js +0 -2
  50. package/dist/chunk-YRR32LTF.js.map +0 -1
  51. package/dist/render-STDR67WK.js +0 -2
  52. package/dist/render-STDR67WK.js.map +0 -1
  53. package/dist/renderApp-QYMNQ3KS.js +0 -2
  54. package/dist/server-KAHRRRDU.js +0 -2
  55. package/dist/transport-W6JIYZKZ.js +0 -2
@@ -0,0 +1,2 @@
1
+ import {a,d,g,n}from'./chunk-BCUSVRAY.js';import {w,y,s,z,D}from'./chunk-AMJHJA2V.js';import A from'react';import E from'react-dom/client';import {jsx}from'react/jsx-runtime';function c(t){return {getConfig(e){return y(`${t}.${e}`)},query(e,...r){let o=r[0]??{};return {queryKey:[t,e,o],queryFn:()=>w(`${t}.${e}`,o)}},mutation(e){return {mutationFn:r=>w(`${t}.${e}`,r)}},infiniteQuery(e,r){return {queryKey:[t,e,"infinite",r(void 0)],initialPageParam:void 0,queryFn:({pageParam:o})=>w(`${t}.${e}`,r(o))}}}}var _=c("_system");var u=class{constructor(e,r){this.category=e,this.onMessage=r;}init(){d()?.on({category:this.category,listener:this.onMessage});}joinChannel(e){d()?.joinChannel({category:this.category,id:e});}leaveChannel(e){d()?.leaveChannel({category:this.category,id:e});}};var C="useClient"in A?A.useClient(a):a;var K="__MODELENCE_STATE__";function Q(){return typeof document>"u"?false:document.getElementById(K)!==null}function W(){if(typeof document>"u")return null;let t=document.getElementById(K);if(!t)return null;try{return JSON.parse(t.textContent??"")}catch(e){return console.error("Modelence: failed to parse SSR state",e),null}}var v="__modelence_ssr_snapshot__";function H(t){globalThis[v]=t;}function De(){return globalThis[v]??null}function q(t){if(typeof window>"u"){H(t);return}let{loadingElement:e,routesElement:r,favicon:o,errorHandler:f,router:y}=t;f&&s(f),window.addEventListener("unload",()=>{});let k=Q(),g$1=W();g$1?.session&&(z(g$1.session),D());let m=document.getElementById("root"),b=window.location.pathname+window.location.search,h=y?y({children:r,location:b}):r,O=g()?h:jsx(n,{children:h}),M=jsx(A.StrictMode,{children:jsx(C,{loadingElement:e,children:O})});if(k?E.hydrateRoot(m,M):E.createRoot(m).render(M),o){let T=document.querySelector("link[rel~='icon']");if(T)T.href=o;else {let s=document.createElement("link");s.rel="icon",s.href=o,document.head.appendChild(s);}}}export{c as a,_ as b,De as c,q as d,u as e,C as f};//# sourceMappingURL=chunk-OJ3LMWVQ.js.map
2
+ //# sourceMappingURL=chunk-OJ3LMWVQ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setErrorHandler","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"6LAuFO,SAASA,CAAAA,CAA8CC,GAAAA,CAAoB,CAChF,OAAO,CACL,UACEC,CAAAA,CACqD,CAErD,OAAOC,GAAAA,CAAiB,CAAA,EAAGF,GAAU,CAAA,CAAA,EAAIC,CAAG,CAAA,CAAE,CAChD,CAAA,CAEA,KAAA,CACEE,KACGC,CAAAA,CAGH,CACA,IAAMC,CAAAA,CAAQD,CAAAA,CAAK,CAAC,CAAA,EAAK,EAAC,CAC1B,OAAO,CACL,QAAA,CAAU,CAACJ,GAAAA,CAAYG,CAAAA,CAAME,CAAI,CAAA,CACjC,OAAA,CAAS,IACPC,CAAAA,CACE,CAAA,EAAGN,GAAU,IAAIG,CAAI,CAAA,CAAA,CACrBE,CACF,CACJ,CACF,EAEA,QAAA,CAAwDF,CAAAA,CAAS,CAC/D,OAAO,CACL,UAAA,CACEE,GAEAC,CAAAA,CACE,CAAA,EAAGN,GAAU,CAAA,CAAA,EAAIG,CAAI,GACrBE,CACF,CACJ,CACF,CAAA,CAUA,aAAA,CACEF,CAAAA,CACAI,EACA,CACA,OAAO,CACL,QAAA,CAAU,CAACP,IAAYG,CAAAA,CAAM,UAAA,CAAYI,CAAAA,CAAQ,MAAS,CAAC,CAAA,CAE3D,iBAAkB,MAAA,CAClB,OAAA,CAAS,CAAC,CACR,SAAA,CAAAC,CACF,IAGEF,CAAAA,CACE,CAAA,EAAGN,GAAU,CAAA,CAAA,EAAIG,CAAI,CAAA,CAAA,CACrBI,EAAQC,CAAS,CACnB,CACJ,CACF,CACF,CACF,CCtJO,IAAMC,CAAAA,CAAeV,CAAAA,CAAwC,SAAS,MCDhEW,CAAAA,CAAN,KAAiC,CAItC,WAAA,CAAYC,CAAAA,CAAkBC,EAA8B,CAC1D,IAAA,CAAK,QAAA,CAAWD,CAAAA,CAChB,IA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QAAA,CAAS,aAAA,CAAc,mBAAmB,EACvD,GAAKA,CAAAA,CAMHA,EAAK,IAAA,CAAOjB,CAAAA,CAAAA,KANH,CACT,IAAMkB,CAAAA,CAAU,QAAA,CAAS,aAAA,CAAc,MAAM,CAAA,CAC7CA,EAAQ,GAAA,CAAM,MAAA,CACdA,CAAAA,CAAQ,IAAA,CAAOlB,CAAAA,CACf,QAAA,CAAS,KAAK,WAAA,CAAYkB,CAAO,EACnC,CAGF,CACF","file":"chunk-TBGXZXAA.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport { hydrateSession, startSessionHeartbeat, type SessionInitPayload } from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Empty 'unload' handler prevents bfcache in most browsers.\n window.addEventListener('unload', () => {});\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{appTree}</AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/client/module.ts","../src/system/client.ts","../src/websocket/clientChannel.ts","../src/client.ts","../src/client/renderApp.tsx"],"names":["createClientModule","moduleName","key","getConfig","name","rest","args","callMethod","getArgs","pageParam","systemConfig","ClientChannel","category","onMessage","getWebsocketClientProvider","id","AppProvider","React","SSR_STATE_SCRIPT_ID","hasSsrMarker","readSsrState","node","SNAPSHOT_KEY","setSnapshot","snapshot","_getSsrSnapshot","renderApp","options","loadingElement","routesElement","favicon","errorHandler","router","setErrorHandler","isHydrating","ssrState","hydrateSession","startSessionHeartbeat","container","location","routedTree","appTree","hasConnectedQueryClient","jsx","ModelenceQueryProvider","tree","ReactDOM","link","newLink"],"mappings":"+KAuFO,SAASA,CAAAA,CAA8CC,CAAAA,CAAoB,CAChF,OAAO,CACL,UACEC,CAAAA,CACqD,CAErD,OAAOC,CAAAA,CAAiB,CAAA,EAAGF,CAAU,CAAA,C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AAK,WAAA,CAAYkB,CAAO,EACnC,CAGF,CACF","file":"chunk-OJ3LMWVQ.js","sourcesContent":["'use client';\n\nimport type { ObjectId } from 'mongodb';\nimport type { ConfigParams, ConfigType, ValueType } from '../config/types';\nimport { callMethod, type MethodArgs } from './method';\nimport type { AnyMethodShape } from '../methods/types';\n\n// Pulls the config store value without importing server-side code\nimport { getConfig as _getClientConfig } from '../config/client';\n\n// ── type helpers ─────────────────────────────────────────────────────────────\n\n/**\n * Recursively maps ObjectId → string to match the sanitized runtime values\n * sent over the wire. Dates are preserved (revived via typeMap on the client).\n */\ntype Sanitized<T> = T extends ObjectId\n ? string\n : T extends Date\n ? Date\n : T extends (infer U)[]\n ? Sanitized<U>[]\n : T extends object\n ? { [K in keyof T]: Sanitized<T[K]> }\n : T;\n\ntype ExtractArgs<M> = M extends (args: infer A, ...rest: any[]) => any // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : M extends { handler: (args: infer A, ...rest: any[]) => any } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? A\n : MethodArgs;\n\ntype ExtractResult<M> = M extends (...args: any[]) => Promise<infer R> // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : M extends { handler: (...args: any[]) => Promise<infer R> } // eslint-disable-line @typescript-eslint/no-explicit-any\n ? Sanitized<R>\n : unknown;\n\ntype PublicKeyOf<TSchema extends Record<string, ConfigParams>> = {\n [K in keyof TSchema as TSchema[K] extends ConfigParams<ConfigType, true>\n ? string & K\n : never]: ValueType<TSchema[K]['type']>;\n};\n\ntype AnyModule = {\n name: string;\n configSchema: Record<string, ConfigParams>;\n queries: Record<string, AnyMethodShape>;\n mutations: Record<string, AnyMethodShape>;\n};\n\n// ── createClientModule ────────────────────────────────────────────────────────\n\n/**\n * Creates a typed client accessor for a module's public configs, queries, and mutations.\n *\n * Use `import type` to reference the module so no server code is bundled on the client.\n * Arg and return types for queries and mutations are inferred automatically from the\n * server-side handler signatures.\n *\n * @param moduleName - The module's name as passed to `new Module(name, ...)`.\n *\n * @example\n * ```ts\n * // src/client/payments.ts\n * import type paymentsModule from '../server/payments';\n * import { createClientModule } from 'modelence/client';\n *\n * export const payments = createClientModule<typeof paymentsModule>('payments');\n * ```\n *\n * ```ts\n * // src/components/Checkout.tsx\n * import { useQuery, useMutation } from '@tanstack/react-query';\n * import { payments } from '../client/payments';\n *\n * // Typed config — public keys only, private and secret keys excluded:\n * const currency = payments.getConfig('currency'); // string | undefined\n *\n * // Typed query — pass directly to useQuery:\n * const { data: products } = useQuery(payments.query('getProducts', { page: 1 }));\n *\n * // Typed mutation — pass directly to useMutation:\n * const { mutate: charge } = useMutation(payments.mutation('charge'));\n * charge({ amount: 100 }); // args typed from handler signature\n * ```\n */\nexport function createClientModule<TModule extends AnyModule>(moduleName: string) {\n return {\n getConfig<K extends keyof PublicKeyOf<TModule['configSchema']> & string>(\n key: K\n ): PublicKeyOf<TModule['configSchema']>[K] | undefined {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return _getClientConfig(`${moduleName}.${key}`) as any;\n },\n\n query<K extends keyof TModule['queries'] & string>(\n name: K,\n ...rest: {} extends ExtractArgs<TModule['queries'][K]>\n ? [args?: ExtractArgs<TModule['queries'][K]>]\n : [args: ExtractArgs<TModule['queries'][K]>]\n ) {\n const args = (rest[0] ?? {}) as ExtractArgs<TModule['queries'][K]>;\n return {\n queryKey: [moduleName, name, args] as const,\n queryFn: (): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n mutation<K extends keyof TModule['mutations'] & string>(name: K) {\n return {\n mutationFn: (\n args: ExtractArgs<TModule['mutations'][K]>\n ): Promise<ExtractResult<TModule['mutations'][K]>> =>\n callMethod<ExtractResult<TModule['mutations'][K]>>(\n `${moduleName}.${name}`,\n args as MethodArgs\n ),\n };\n },\n\n /**\n * Returns options for `useInfiniteQuery`. The `getArgs` callback receives the\n * current `pageParam` and returns the args to pass to the query handler.\n * Spread the result into `useInfiniteQuery` alongside `getNextPageParam`.\n *\n * Annotate the `pageParam` type in the callback so TypeScript can infer the\n * page param type — no manual generic needed on `useInfiniteQuery`.\n */\n infiniteQuery<K extends keyof TModule['queries'] & string, TPageParam = unknown>(\n name: K,\n getArgs: (pageParam: TPageParam | undefined) => ExtractArgs<TModule['queries'][K]>\n ) {\n return {\n queryKey: [moduleName, name, 'infinite', getArgs(undefined)] as const,\n // Included so TanStack infers TPageParam from the callback type, not from a bare `undefined`.\n initialPageParam: undefined as TPageParam | undefined,\n queryFn: ({\n pageParam,\n }: {\n pageParam: TPageParam | undefined;\n }): Promise<ExtractResult<TModule['queries'][K]>> =>\n callMethod<ExtractResult<TModule['queries'][K]>>(\n `${moduleName}.${name}`,\n getArgs(pageParam) as MethodArgs\n ),\n };\n },\n };\n}\n","import type systemModule from './index';\nimport { createClientModule } from '../client/module';\n\nexport const systemConfig = createClientModule<typeof systemModule>('_system');\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { configureClient, type ClientConfig } from './client/clientConfig';\nexport { getConfig } from './config/client';\nexport { createClientModule } from './client/module';\nexport type { ValueType } from './config/types';\nexport { systemConfig } from './system/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { ModelenceQueryProvider } from './client/queryProvider';\nexport {\n modelenceQuery,\n modelenceLiveQuery,\n modelenceMutation,\n createQueryKey,\n connectModelenceQueryClient,\n disconnectModelenceQueryClient,\n ModelenceQueryClient,\n type ModelenceQueryKey,\n} from './client/query';\nexport { callMethod, MethodError, type MethodArgs, type CallMethodOptions } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n sendMagicLink,\n loginWithMagicLink,\n loginWithOneTimeCode,\n linkOAuthProvider,\n unlinkOAuthProvider,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\nimport { hydrateSession, startSessionHeartbeat, type SessionInitPayload } from './session';\nimport { ModelenceQueryProvider } from './queryProvider';\nimport { hasConnectedQueryClient } from './query';\n\nconst SSR_STATE_SCRIPT_ID = '__MODELENCE_STATE__';\n\ntype SsrState = {\n session?: SessionInitPayload;\n};\n\nfunction hasSsrMarker(): boolean {\n if (typeof document === 'undefined') {\n return false;\n }\n return document.getElementById(SSR_STATE_SCRIPT_ID) !== null;\n}\n\nfunction readSsrState(): SsrState | null {\n if (typeof document === 'undefined') {\n return null;\n }\n\n const node = document.getElementById(SSR_STATE_SCRIPT_ID);\n if (!node) {\n return null;\n }\n\n try {\n return JSON.parse(node.textContent ?? '') as SsrState;\n } catch (e) {\n // Caller must still hydrate (marker presence drives that, not parsed payload).\n console.error('Modelence: failed to parse SSR state', e);\n return null;\n }\n}\n\nexport type SsrRouter = (props: {\n children: React.ReactNode;\n location?: string;\n}) => React.ReactElement;\n\nexport interface RenderAppOptions {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n router?: SsrRouter;\n}\n\n// Shared via globalThis: ssrLoadModule loads the user's entry in a separate\n// module graph from the framework runtime.\nconst SNAPSHOT_KEY = '__modelence_ssr_snapshot__';\n\ntype GlobalWithSnapshot = typeof globalThis & {\n [SNAPSHOT_KEY]?: RenderAppOptions | null;\n};\n\nfunction setSnapshot(snapshot: RenderAppOptions | null) {\n (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] = snapshot;\n}\n\n/** @internal Used by the SSR runtime after evaluating the user's entry. */\nexport function _getSsrSnapshot(): RenderAppOptions | null {\n return (globalThis as GlobalWithSnapshot)[SNAPSHOT_KEY] ?? null;\n}\n\nexport function renderApp(options: RenderAppOptions) {\n if (typeof window === 'undefined') {\n setSnapshot(options);\n return;\n }\n\n const { loadingElement, routesElement, favicon, errorHandler, router } = options;\n\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n // Empty 'unload' handler prevents bfcache in most browsers.\n window.addEventListener('unload', () => {});\n\n // Hydrate session BEFORE building the tree so `isSessionInitialized()` is\n // true on the first render and matches the server output. Hydration mode\n // tracks marker presence (not parse success): a parse failure still leaves\n // server-rendered DOM that must be hydrated, not replaced.\n const isHydrating = hasSsrMarker();\n const ssrState = readSsrState();\n if (ssrState?.session) {\n hydrateSession(ssrState.session);\n // Fire-and-forget: the heartbeat loop runs in the background.\n void startSessionHeartbeat();\n }\n\n const container = document.getElementById('root')!;\n // Pass the same location the server used (req.originalUrl == path + search;\n // the hash is never sent to the server) so a location-driven router (e.g. a\n // static router) resolves the same route on hydration as it did during SSR,\n // avoiding hydration mismatches.\n const location = window.location.pathname + window.location.search;\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n\n // If the app already connected its own QueryClient (the documented\n // bring-your-own-provider pattern connects before calling renderApp), don't\n // inject ours. A second provider would shadow the user's client: useQuery\n // would read the inner client while live-query updates write to the outer\n // one, so real-time queries would never update.\n const appTree = hasConnectedQueryClient() ? (\n routedTree\n ) : (\n <ModelenceQueryProvider>{routedTree}</ModelenceQueryProvider>\n );\n\n const tree = (\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{appTree}</AppProvider>\n </React.StrictMode>\n );\n\n if (isHydrating) {\n ReactDOM.hydrateRoot(container, tree);\n } else {\n ReactDOM.createRoot(container).render(tree);\n }\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n"]}
@@ -1,2 +1,2 @@
1
- import {B}from'./chunk-SD3ERG2G.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await B(t,e,u)),a$1=b(n),y=JSON.parse(JSON.stringify(n));return c(y,a$1??void 0)}var p=new AsyncLocalStorage;function g(t,e){return p.run(t,e)}function d(){return p.getStore()}export{x as a,g as b,d as c};//# sourceMappingURL=chunk-SNADMLAT.js.map
2
- //# sourceMappingURL=chunk-SNADMLAT.js.map
1
+ import {D}from'./chunk-YOJ4ZP5D.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await D(t,e,u)),a$1=b(n),y=JSON.parse(JSON.stringify(n));return c(y,a$1??void 0)}var p=new AsyncLocalStorage;function g(t,e){return p.run(t,e)}function d(){return p.getStore()}export{x as a,g as b,d as c};//# sourceMappingURL=chunk-PJRYLKYW.js.map
2
+ //# sourceMappingURL=chunk-PJRYLKYW.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-SNADMLAT.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n// Invoke a method in-process and round-trip through the same JSON pipeline\n// as the HTTP transport so SSR output matches the dehydrated query cache.\n// The JSON.stringify/parse step is load-bearing: strips `undefined` props.\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n const jsonRoundTripped = JSON.parse(JSON.stringify(sanitized));\n return reviveResponseTypes(jsonRoundTripped, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/callInProcess.ts","../src/ssr/context.ts"],"names":["callInProcessMethod","methodName","args","context","sanitized","sanitizeResult","runMethod","typeMap","getResponseTypeMap","jsonRoundTripped","reviveResponseTypes","storage","AsyncLocalStorage","runWithSsrContext","ctx","fn","getSsrContext"],"mappings":"wHAOA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAMC,CAAAA,CAAYC,CAAAA,CAAe,MAAMC,CAAAA,CAAUL,CAAAA,CAAYC,CAAAA,CAAMC,CAAO,CAAC,CAAA,CACrEI,GAAAA,CAAUC,CAAAA,CAAmBJ,CAAS,CAAA,CACtCK,CAAAA,CAAmB,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAUL,CAAS,CAAC,CAAA,CAC7D,OAAOM,CAAAA,CAAoBD,CAAAA,CAAkBF,GAAAA,EAAW,MAAS,CACnE,CCAA,IAAMI,CAAAA,CAAU,IAAIC,iBAAAA,CAEb,SAASC,CAAAA,CAAqBC,CAAAA,CAAwBC,CAAAA,CAAgB,CAC3E,OAAOJ,CAAAA,CAAQ,GAAA,CAAIG,CAAAA,CAAKC,CAAE,CAC5B,CAEO,SAASC,CAAAA,EAA+C,CAC7D,OAAOL,CAAAA,CAAQ,QAAA,EACjB","file":"chunk-PJRYLKYW.js","sourcesContent":["import { runMethod } from '../methods';\nimport { sanitizeResult, getResponseTypeMap, reviveResponseTypes } from '../methods/serialize';\nimport type { Context, Args } from '../methods/types';\n\n// Invoke a method in-process and round-trip through the same JSON pipeline\n// as the HTTP transport so SSR output matches the dehydrated query cache.\n// The JSON.stringify/parse step is load-bearing: strips `undefined` props.\nexport async function callInProcessMethod<T = unknown>(\n methodName: string,\n args: Args,\n context: Context\n): Promise<T> {\n const sanitized = sanitizeResult(await runMethod(methodName, args, context));\n const typeMap = getResponseTypeMap(sanitized);\n const jsonRoundTripped = JSON.parse(JSON.stringify(sanitized));\n return reviveResponseTypes(jsonRoundTripped, typeMap ?? undefined) as T;\n}\n","import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { QueryClient } from '@tanstack/react-query';\nimport type { Context } from '../methods/types';\nimport type { Configs } from '../config/types';\n\nexport type SsrSessionSnapshot = {\n user: unknown;\n configs: Configs;\n};\n\nexport type SsrRequestContext = {\n callContext: Context;\n queryClient: QueryClient;\n session: SsrSessionSnapshot;\n};\n\nconst storage = new AsyncLocalStorage<SsrRequestContext>();\n\nexport function runWithSsrContext<T>(ctx: SsrRequestContext, fn: () => T): T {\n return storage.run(ctx, fn);\n}\n\nexport function getSsrContext(): SsrRequestContext | undefined {\n return storage.getStore();\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import P from'elastic-apm-node';import v from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import l from'process';var f={},L={},S=false;function d(t){return L[t]?.value??f[t]?.default}function G(){if(!S)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(f).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:L[t]?.value??e.default}]))}function Y(t){t.forEach(({key:e,type:o,value:n})=>{!e.toLowerCase().startsWith("_system.")&&!f[e]||(L[e]={key:e,type:o,value:n});}),S=true;}function $(){return f}function F(t){Object.entries(t).forEach(([e,o])=>{let{type:n,isPublic:r}=o;if(n==="secret"&&r)throw new Error(`Config ${e} with type "secret" cannot be public`)}),f=t;}var s={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function I({elasticCloudId:t,elasticApiKey:e}){let o=l.stdout.write,n=l.stderr.write;l.stdout.write=function(r,...i){return h(r.toString(),s.stdout),o.call(l.stdout,r,...i)},l.stderr.write=function(r,...i){return h(r.toString(),s.stderr),n.call(l.stderr,r,...i)},T();}function h(t,e){if(t.length===0)return;let o=new Date;for(let n=0;n<t.length;n++){let r=e[e.length-1];r.timestamp||(r.timestamp=o,r.sequenceId=z++),t[n]===`
2
+ `?e.push({log:"",timestamp:null}):r.log+=t[n];}}async function N(){let t=s.stdout.slice(0,-1);s.stdout=[s.stdout[s.stdout.length-1]];let e=s.stderr.slice(0,-1);s.stderr=[s.stderr[s.stderr.length-1]],t.forEach(({log:o,timestamp:n,sequenceId:r})=>{b(o,{timestamp:n,source:"console",sequenceId:r});}),e.forEach(({log:o,timestamp:n,sequenceId:r})=>{w(o,{timestamp:n,source:"console",sequenceId:r});});}function T(){setTimeout(()=>{N(),T();},1e3);}var c=null;function Z(){}function tt(t){c=Object.assign({},c,t);}function j(){return c?.environmentId}function K(){return c?.appAlias}function R(){return c?.environmentAlias}function M(){return c?.telemetry?.serviceName}function a(){return !!c?.telemetry?.isEnabled}var _=false,p=null,m=null,ct=async()=>{if(_)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');_=true,a()&&await W();};async function W(){let t=d("_system.elastic.apmEndpoint"),e=d("_system.elastic.cloudId"),o=d("_system.elastic.apiKey"),n=K()??"unknown",r=R()??"unknown",i=j()??"unknown",g=M();p=P.start({serviceName:g,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:i,appAlias:n,environmentAlias:r}});let u=new ElasticsearchTransport({apm:p,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",O=>{console.error("Elasticsearch Transport Error:",O);}),m=v.createLogger({level:"debug",defaultMeta:{serviceName:g},format:v.format.combine(v.format.json()),transports:[u]}),I({elasticCloudId:e,elasticApiKey:o});}function A(){if(!p)throw new Error("APM is not initialized");return p}function y(){return m!==null}function E(){if(!m)throw new Error("Logger is not initialized");return m}var k=["token","password","secret","nonce","code"];function C(t){if(!t||typeof t!="object")return t;if(Array.isArray(t))return t.map(C);let e={};for(let[o,n]of Object.entries(t)){let r=k.some(i=>o.toLowerCase().includes(i));e[o]=r?"[redacted]":C(n);}return e}function x(){let t="";return a()||(t="info"),process.env.MODELENCE_LOG_LEVEL||t}function q(t,e){a()&&y()&&E().debug(t,e),x()==="debug"&&console.debug(t,e);}function b(t,e){a()&&y()&&E().info(t,e),["debug","info"].includes(x())&&console.info(t,e);}function w(t,e){a()&&y()&&E().error(t,e),["debug","info","error"].includes(x())&&console.error(t,e);}function U(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let n=A(),r=n.startTransaction(e,t);return o&&n.setCustomContext(o),{end:(i,{endTime:g,context:u}={})=>{u&&n.setCustomContext(u),r.end(i,g);},setContext:i=>{n.setCustomContext(i);}}}function V(t){if(!a()){console.error(t);return}A().captureError(t);}export{d as a,G as b,Y as c,$ as d,F as e,Z as f,tt as g,ct as h,C as i,q as j,b as k,w as l,U as m,V as n};//# sourceMappingURL=chunk-VF4RU7MF.js.map
3
+ //# sourceMappingURL=chunk-VF4RU7MF.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","getSchema","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","isLoggerReady","getLogger","SENSITIVE_KEYS","redactSensitive","result","val","isSensitive","k","getLogLevel","defaultLoglevel","logDebug","message","startTransaction","name","context","transaction","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,EAAUC,CAAAA,CAAuD,CAC/E,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAAA,EAASJ,CAAAA,CAAaI,CAAG,GAAG,OAClD,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAAA,CAGF,OAAO,MAAA,CAAO,WAAA,CACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CACxB,MAAA,CAAO,CAAC,CAACM,EAAGC,CAAM,CAAA,GAAMA,CAAAA,CAAO,QAAQ,EACvC,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKG,CAAM,CAAA,GACT,CACLH,CAAAA,CACA,CACE,IAAAA,CAAAA,CACA,IAAA,CAAMG,CAAAA,CAAO,IAAA,CACb,MAAON,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAAA,EAASG,CAAAA,CAAO,OACtC,CACF,CACD,CACL,CACF,CAEO,SAASC,CAAAA,CAAYC,EAAsB,CAChDA,CAAAA,CAAQ,OAAA,CAAQ,CAAC,CAAE,GAAA,CAAAL,CAAAA,CAAK,IAAA,CAAAM,CAAAA,CAAM,MAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBP,EAAI,WAAA,EAAY,CAAE,UAAA,CAAW,UAAU,GAEvC,CAACJ,CAAAA,CAAaI,CAAG,CAAA,GAKxCH,EAAOG,CAAG,CAAA,CAAI,CAC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GF,IAAMC,CAAAA,CAAMgB,GAAO,CACbgB,CAAAA,CAAchC,CAAAA,CAAI,gBAAA,CAAiB8B,EAAMjE,CAAI,CAAA,CACnD,OAAIkE,CAAAA,EACF/B,EAAI,gBAAA,CAAiB+B,CAAO,CAAA,CAGvB,CACL,IAAK,CACHV,CAAAA,CACA,CAAE,OAAA,CAAAY,EAAS,OAAA,CAAAF,CAAQ,CAAA,CAA6D,KAC7E,CACCA,CAAAA,EACF/B,CAAAA,CAAI,gBAAA,CAAiB+B,CAAO,CAAA,CAE9BC,CAAAA,CAAY,GAAA,CAAIX,CAAAA,CAAQY,CAAO,EACjC,CAAA,CACA,UAAA,CAAaF,CAAAA,EAAqC,CAChD/B,CAAAA,CAAI,gBAAA,CAAiB+B,CAAO,EAC9B,CACF,CACF,CAEO,SAASG,CAAAA,CAAapB,EAAc,CACzC,GAAI,CAACf,CAAAA,GAAsB,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,EACnB,MACF,CAEAE,GAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-VF4RU7MF.js","sourcesContent":["import { AppConfig, ConfigKey, ConfigSchema } from './types';\n\nlet configSchema: ConfigSchema = {};\nlet config: Record<ConfigKey, AppConfig> = {};\nlet isInitialized = false;\n\n/**\n * @sidebarTitle getConfig (server)\n *\n * @param key - The configuration key to retrieve\n * @returns The configuration value (string, number, or boolean)\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the site URL\n * const siteUrl = getConfig('_system.site.url');\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_URL=https://myapp.com\n * ```\n *\n * @example\n * ```ts\n * import { getConfig } from 'modelence/server';\n *\n * // Get the current environment (e.g., 'development', 'staging', 'production')\n * const env = getConfig('_system.env');\n *\n * if (env === 'production') {\n * // Enable production features\n * }\n * ```\n *\n * Set via environment variable:\n * ```bash\n * MODELENCE_SITE_ENV=production\n * ```\n */\nexport function getConfig(key: ConfigKey): string | number | boolean | undefined {\n return config[key]?.value ?? configSchema[key]?.default;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function getSchema() {\n return configSchema;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\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 // eslint-disable-next-line @typescript-eslint/no-explicit-any\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\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 void sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [esTransport],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function isLoggerReady() {\n return logger !== null;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm, isLoggerReady } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\ntype LogLevel = 'error' | 'info' | 'debug' | '';\n\n// Secret-bearing keys to scrub before request args/query/body reach the APM sink.\n// Matched case-insensitively as a substring (`authToken` matches `token`).\nconst SENSITIVE_KEYS = ['token', 'password', 'secret', 'nonce', 'code'];\n\n/**\n * Deep-copies `value`, replacing any {@link SENSITIVE_KEYS} match with\n * `'[redacted]'`. Non-object values pass through unchanged.\n */\nexport function redactSensitive(value: unknown): unknown {\n if (!value || typeof value !== 'object') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(redactSensitive);\n }\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n const isSensitive = SENSITIVE_KEYS.some((k) => key.toLowerCase().includes(k));\n result[key] = isSensitive ? '[redacted]' : redactSensitive(val);\n }\n return result;\n}\n\n/**\n * Gets the logging level for console logs based on the MODELENCE_LOG_LEVEL environment variable.\n *\n * @returns The log level ('error' | 'info' | 'debug' | '')\n *\n * Behavior:\n * - If MODELENCE_LOG_LEVEL is set, returns that value\n * - If telemetry is disabled and MODELENCE_LOG_LEVEL is not set, defaults to 'info'\n * - If telemetry is enabled and MODELENCE_LOG_LEVEL is not set, returns '' (no console logging)\n */\nfunction getLogLevel(): LogLevel {\n let defaultLoglevel: LogLevel = '';\n if (!isTelemetryEnabled()) {\n defaultLoglevel = 'info';\n }\n\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || defaultLoglevel;\n}\n\nexport function logDebug(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().debug(message, args);\n }\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().info(message, args);\n }\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().error(message, args);\n }\n if (['debug', 'info', 'error'].includes(getLogLevel())) {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
@@ -0,0 +1,4 @@
1
+ import {a,b as b$1,m,i}from'./chunk-VF4RU7MF.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
+ `)}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-YOJ4ZP5D.js.map
4
+ //# sourceMappingURL=chunk-YOJ4ZP5D.js.map