modelence 0.23.0-setup.dev.3 → 0.23.0-setup.dev.5

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 (31) hide show
  1. package/dist/bin/modelence.js +5 -5
  2. package/dist/bin/modelence.js.map +1 -1
  3. package/dist/{chunk-JQ7HKLQZ.js → chunk-7FIQ2GMI.js} +3 -3
  4. package/dist/chunk-7FIQ2GMI.js.map +1 -0
  5. package/dist/chunk-JGU3ZVX3.js +40 -0
  6. package/dist/chunk-JGU3ZVX3.js.map +1 -0
  7. package/dist/{chunk-QMKQ7DUD.js → chunk-KDOTVIEY.js} +3 -3
  8. package/dist/{chunk-QMKQ7DUD.js.map → chunk-KDOTVIEY.js.map} +1 -1
  9. package/dist/{chunk-UHER7BLC.js → chunk-UJ2WYHH7.js} +2 -2
  10. package/dist/{chunk-UHER7BLC.js.map → chunk-UJ2WYHH7.js.map} +1 -1
  11. package/dist/chunk-UW37F3GV.js +2 -0
  12. package/dist/chunk-UW37F3GV.js.map +1 -0
  13. package/dist/{package-A4RGADVP.js → package-H4HEZ37S.js} +2 -2
  14. package/dist/{package-A4RGADVP.js.map → package-H4HEZ37S.js.map} +1 -1
  15. package/dist/{render-V4SWSKPW.js → render-FRLQDLXI.js} +2 -2
  16. package/dist/{render-V4SWSKPW.js.map → render-FRLQDLXI.js.map} +1 -1
  17. package/dist/server-KDERUGRC.js +2 -0
  18. package/dist/{server-D7FBXWTW.js.map → server-KDERUGRC.js.map} +1 -1
  19. package/dist/server.d.ts +50 -0
  20. package/dist/server.js +1 -1
  21. package/dist/telemetry.js +1 -1
  22. package/dist/transport-LWVQ4TUY.js +2 -0
  23. package/dist/{transport-OSL4EWWD.js.map → transport-LWVQ4TUY.js.map} +1 -1
  24. package/package.json +1 -3
  25. package/dist/chunk-7XZDALJZ.js +0 -37
  26. package/dist/chunk-7XZDALJZ.js.map +0 -1
  27. package/dist/chunk-B5WLEHNH.js +0 -3
  28. package/dist/chunk-B5WLEHNH.js.map +0 -1
  29. package/dist/chunk-JQ7HKLQZ.js.map +0 -1
  30. package/dist/server-D7FBXWTW.js +0 -2
  31. package/dist/transport-OSL4EWWD.js +0 -2
@@ -1,2 +1,2 @@
1
- import {E}from'./chunk-QMKQ7DUD.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await E(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-UHER7BLC.js.map
2
- //# sourceMappingURL=chunk-UHER7BLC.js.map
1
+ import {E}from'./chunk-KDOTVIEY.js';import {a,b,c}from'./chunk-5M6FUMUK.js';import {AsyncLocalStorage}from'async_hooks';async function x(t,e,u){let n=a(await E(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-UJ2WYHH7.js.map
2
+ //# sourceMappingURL=chunk-UJ2WYHH7.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-UHER7BLC.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-UJ2WYHH7.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,2 @@
1
+ import S from'elastic-apm-node';var a={},l={},E=false;function p(e){return l[e]?.value??a[e]?.default}function R(){if(!E)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(a).filter(([e,t])=>t.isPublic).map(([e,t])=>[e,{key:e,type:t.type,value:l[e]?.value??t.default}]))}function K(e){e.forEach(({key:t,type:r,value:n})=>{!t.toLowerCase().startsWith("_system.")&&!a[t]||(l[t]={key:t,type:r,value:n});}),E=true;}function N(){return a}function O(e){Object.entries(e).forEach(([t,r])=>{let{type:n,isPublic:o}=r;if(n==="secret"&&o)throw new Error(`Config ${t} with type "secret" cannot be public`)}),a=e;}var s=null;function z(){}function P(e){s=Object.assign({},s,e);}function b(){return s?.environmentId}function v(){return s?.appAlias}function A(){return s?.environmentAlias}function C(){return s?.telemetry?.serviceName}function c(){return !!s?.telemetry?.isEnabled}var x=false,f=null,G=async()=>{if(x)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');x=true,c()&&L();};function L(){let e=p("_system.elastic.apmEndpoint"),t=p("_system.elastic.apiKey"),r=v()??"unknown",n=A()??"unknown",o=b()??"unknown",i=C();f=S.start({serviceName:i,apiKey:t,serverUrl:e,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:o,appAlias:r,environmentAlias:n}});}function u(){if(!f)throw new Error("APM is not initialized");return f}var h=["token","password","secret","nonce","code"];function g(e){if(!e||typeof e!="object")return e;if(Array.isArray(e))return e.map(g);let t={};for(let[r,n]of Object.entries(e)){let o=h.some(i=>r.toLowerCase().includes(i));t[r]=o?"[redacted]":g(n);}return t}function m(){return process.env.MODELENCE_LOG_LEVEL||"info"}function T(e,t){m()==="debug"&&console.debug(e,t);}function I(e,t){["debug","info"].includes(m())&&console.info(e,t);}function j(e,t){["debug","info","error"].includes(m())&&console.error(e,t);}function k(e,t,r){if(!c())return {end:()=>{},setContext:()=>{}};let n=u(),o=n.startTransaction(t,e);return r&&n.setCustomContext(r),{end:(i,{endTime:y,context:d}={})=>{d&&n.setCustomContext(d),o.end(i,y);},setContext:i=>{n.setCustomContext(i);}}}function M(e){if(!c()){console.error(e);return}u().captureError(e);}export{p as a,R as b,K as c,N as d,O as e,z as f,P as g,b as h,G as i,g as j,T as k,I as l,j as m,k as n,M as o};//# sourceMappingURL=chunk-UW37F3GV.js.map
2
+ //# sourceMappingURL=chunk-UW37F3GV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/server.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","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","initMetrics","initElasticApm","elasticApmEndpoint","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","getApm","SENSITIVE_KEYS","redactSensitive","result","val","isSensitive","k","getLogLevel","logDebug","message","args","logInfo","logError","startTransaction","name","context","transaction","endTime","captureError","error"],"mappings":"gCAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,EAAUC,CAAAA,CAAuD,CAC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,CAEO,SAASG,CAAAA,CAAaC,CAAAA,CAAc,CACzC,GAAI,CAAC9B,CAAAA,EAAmB,CAAG,CACzB,QAAQ,KAAA,CAAM8B,CAAK,CAAA,CACnB,MACF,CAEAnB,CAAAA,EAAO,CAAE,YAAA,CAAamB,CAAK,EAC7B","file":"chunk-UW37F3GV.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","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';\n\nimport { getConfig } from '../config/server';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | 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 initElasticApm();\n }\n};\n\nfunction initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') 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 transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n","import { getApm } 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 * Logs go to stdout/stderr only, where the hosting infrastructure (e.g. CloudWatch\n * via the container log driver) picks them up.\n *\n * @returns The log level ('error' | 'info' | 'debug'), defaulting to 'info'\n */\nfunction getLogLevel(): LogLevel {\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || 'info';\n}\n\nexport function logDebug(message: string, args: object) {\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\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"]}
@@ -1,2 +1,2 @@
1
- export{m as author,i as bin,o as bugs,t as default,r as dependencies,d as description,q as devDependencies,j as engines,g as exports,h as files,p as homepage,n as license,e as main,b as name,s as peerDependencies,l as repository,k as scripts,a as type,f as types,c as version}from'./chunk-JQ7HKLQZ.js';//# sourceMappingURL=package-A4RGADVP.js.map
2
- //# sourceMappingURL=package-A4RGADVP.js.map
1
+ export{m as author,i as bin,o as bugs,t as default,r as dependencies,d as description,q as devDependencies,j as engines,g as exports,h as files,p as homepage,n as license,e as main,b as name,s as peerDependencies,l as repository,k as scripts,a as type,f as types,c as version}from'./chunk-7FIQ2GMI.js';//# sourceMappingURL=package-H4HEZ37S.js.map
2
+ //# sourceMappingURL=package-H4HEZ37S.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"package-A4RGADVP.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"package-H4HEZ37S.js"}
@@ -1,2 +1,2 @@
1
- import {a,b,c}from'./chunk-UHER7BLC.js';import'./chunk-QMKQ7DUD.js';import'./chunk-B5WLEHNH.js';import {a as a$1,n}from'./chunk-NCJCE4XN.js';import {m,a as a$2,n as n$1}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?n$1(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){m(J),a$2(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-V4SWSKPW.js.map
2
- //# sourceMappingURL=render-V4SWSKPW.js.map
1
+ import {a,b,c}from'./chunk-UJ2WYHH7.js';import'./chunk-KDOTVIEY.js';import'./chunk-UW37F3GV.js';import {a as a$1,n}from'./chunk-NCJCE4XN.js';import {m,a as a$2,n as n$1}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';import {renderToPipeableStream}from'react-dom/server';import {Writable}from'stream';import {QueryClient,dehydrate}from'@tanstack/react-query';import {jsx}from'react/jsx-runtime';var J=()=>{let r=c();return r?n$1(r.session.user):null},M=r=>{let n=c();if(n)return n.session.configs[r]?.value};function D(){m(J),a$2(M);}async function X(r){let{callContext:n$1,loadingElement:C,routesElement:S,router:u,location:x,onShellReady:E,onError:b$1}=r;D();let l=await a("_system.session.init",{},n$1),i=new QueryClient({defaultOptions:{queries:{retry:false,gcTime:0}}}),O=u?u({children:S,location:x}):S,Q=jsx(a$1,{loadingElement:C,children:jsx(n,{client:i,children:O})}),a$2=null;await new Promise((s,m)=>{b({callContext:n$1,queryClient:i,session:{user:l.user,configs:l.configs??{}}},()=>{let e=renderToPipeableStream(Q,{onShellReady(){a$2=e,E?.(),s(e);},onShellError(t){m(t);},onError(t){b$1?.(t);}});return e});});let d=null,_=s=>new Promise((m,e)=>{if(!a$2){e(new Error("SSR stream was not initialized"));return}let t=new Writable({write(o,c,I){s.write(o,N=>I(N??void 0));},final(o){try{let c=dehydrate(i);d=JSON.stringify(c);}finally{i.clear();}o(),m();}});t.on("error",o=>{s.destroy(o),e(o);}),s.on("error",e),a$2.pipe(t);});return {sessionState:JSON.stringify({session:l}),pipe:_,getQueryState:()=>{if(d===null)throw new Error("getQueryState() called before stream finished");return d}}}export{X as renderSsrTreeStream};//# sourceMappingURL=render-FRLQDLXI.js.map
2
+ //# sourceMappingURL=render-FRLQDLXI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","que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GACF,CACF,CAAC,CAAA,CAEDS,CAAAA,CAAY,EAAA,CAAG,OAAA,CAAUK,GAAQ,CAC/BN,CAAAA,CAAY,QAAQM,CAAG,CAAA,CACvBb,EAAOa,CAAG,EACZ,CAAC,CAAA,CACDN,EAAY,EAAA,CAAG,OAAA,CAASP,CAAM,CAAA,CAE9BF,IAAU,IAAA,CAAKU,CAAW,EAC5B,CAAC,EAGH,OAAO,CACL,YAAA,CAAc,IAAA,CAAK,UAAU,CAAE,OAAA,CAASnB,CAAe,CAAC,EACxD,IAAA,CAAAiB,CAAAA,CACA,aAAA,CAAe,IAAM,CACnB,GAAID,CAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,KAAA,CAAM,+CAA+C,EAEjE,OAAOA,CACT,CACF,CACF","file":"render-V4SWSKPW.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', (err) => {\n destination.destroy(err);\n reject(err);\n });\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/render.tsx"],"names":["sessionResolver","ctx","getSsrContext","_parseSessionUser","configResolver","key","ensureSsrResolversInstalled","_setSsrSessionResolver","_setSsrConfigResolver","renderSsrTreeStream","options","callContext","loadingElement","routesElement","router","location","onShellReady","onError","sessionPayload","callInProcessMethod","queryClient","QueryClient","routedTree","tree","jsx","AppProvider","ModelenceQueryProvider","streamRef","resolve","reject","runWithSsrContext","stream","renderToPipeableStream","error","queryStateJson","pipe","destination","passthrough","Writable","chunk","_encoding","callback","err","dehydratedState","dehydrate"],"mappings":"6aAkBA,IAAMA,CAAAA,CAAkB,IAAM,CAC5B,IAAMC,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,OAAKD,EAGEE,GAAAA,CAAkBF,CAAAA,CAAI,OAAA,CAAQ,IAAI,EAFhC,IAGX,CAAA,CAEMG,EAAkBC,CAAAA,EAAmB,CACzC,IAAMJ,CAAAA,CAAMC,CAAAA,EAAc,CAC1B,GAAKD,EAGL,OAAOA,CAAAA,CAAI,OAAA,CAAQ,OAAA,C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Ae,IAAM,CACnB,GAAID,CAAAA,GAAmB,IAAA,CACrB,MAAM,IAAI,KAAA,CAAM,+CAA+C,EAEjE,OAAOA,CACT,CACF,CACF","file":"render-FRLQDLXI.js","sourcesContent":["import React from 'react';\nimport { renderToPipeableStream, type PipeableStream } from 'react-dom/server';\nimport { Writable } from 'node:stream';\nimport { QueryClient, dehydrate, type DehydratedState } from '@tanstack/react-query';\nimport { AppProvider } from '../client/AppProvider';\nimport { ModelenceQueryProvider } from '../client/queryProvider';\nimport { getSsrContext, runWithSsrContext } from './context';\nimport { callInProcessMethod } from './callInProcess';\nimport type { Context } from '../methods/types';\nimport {\n _parseSessionUser,\n _setSsrSessionResolver,\n type SessionInitPayload,\n} from '../client/session';\nimport { _setSsrConfigResolver } from '../config/client';\nimport type { ConfigKey, Configs } from '../config/types';\nimport type { SsrRouter } from '../client/renderApp';\n\nconst sessionResolver = () => {\n const ctx = getSsrContext();\n if (!ctx) {\n return null;\n }\n return _parseSessionUser(ctx.session.user);\n};\n\nconst configResolver = (key: ConfigKey) => {\n const ctx = getSsrContext();\n if (!ctx) {\n return undefined;\n }\n return ctx.session.configs[key]?.value;\n};\n\nfunction ensureSsrResolversInstalled() {\n _setSsrSessionResolver(sessionResolver);\n _setSsrConfigResolver(configResolver);\n}\n\nexport type SsrRenderOptions = {\n callContext: Context;\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n router?: SsrRouter;\n location?: string;\n};\n\nexport type SsrStreamHandle = {\n /** Session bootstrap payload — inline before the shell flushes. */\n sessionState: string;\n /** Pipe React's HTML into `destination`. Resolves when streaming finishes. */\n pipe: (destination: Writable) => Promise<void>;\n /** Dehydrated query state. Only call after `pipe()` resolves. */\n getQueryState: () => string;\n};\n\nexport type SsrStreamOptions = SsrRenderOptions & {\n /** Fires when the shell is flushed; caller writes prelude + state here. */\n onShellReady?: () => void;\n /** Non-fatal SSR errors (Suspense fallbacks, etc.). */\n onError?: (error: unknown) => void;\n};\n\nexport async function renderSsrTreeStream(options: SsrStreamOptions): Promise<SsrStreamHandle> {\n const { callContext, loadingElement, routesElement, router, location, onShellReady, onError } =\n options;\n\n ensureSsrResolversInstalled();\n\n const sessionPayload = await callInProcessMethod<SessionInitPayload>(\n '_system.session.init',\n {},\n callContext\n );\n\n const queryClient = new QueryClient({\n defaultOptions: {\n queries: {\n retry: false,\n gcTime: 0,\n },\n },\n });\n\n const routedTree = router ? router({ children: routesElement, location }) : routesElement;\n const tree = (\n <AppProvider loadingElement={loadingElement}>\n <ModelenceQueryProvider client={queryClient}>{routedTree}</ModelenceQueryProvider>\n </AppProvider>\n );\n\n let streamRef: PipeableStream | null = null;\n // Resolves with the stream once React renders above-fallback content;\n // rejects on shell errors so the caller can fall back to a static response.\n const shellReady = new Promise<PipeableStream>((resolve, reject) => {\n // Run the render inside the SSR context so components can resolve\n // session/config/query state from the per-request scope.\n runWithSsrContext(\n {\n callContext,\n queryClient,\n session: {\n user: sessionPayload.user,\n configs: (sessionPayload.configs as Configs) ?? {},\n },\n },\n () => {\n const stream = renderToPipeableStream(tree, {\n onShellReady() {\n streamRef = stream;\n onShellReady?.();\n resolve(stream);\n },\n onShellError(error) {\n reject(error);\n },\n onError(error) {\n onError?.(error);\n },\n });\n return stream;\n }\n );\n });\n\n // Await so shell errors surface before the caller starts piping.\n await shellReady;\n\n let queryStateJson: string | null = null;\n\n const pipe = (destination: Writable): Promise<void> => {\n return new Promise((resolve, reject) => {\n if (!streamRef) {\n reject(new Error('SSR stream was not initialized'));\n return;\n }\n\n // react-dom calls `destination.end()` when done. The caller still needs\n // to write the epilogue + query state, so wrap with a passthrough whose\n // `final()` resolves the pipe promise without closing the response.\n const passthrough = new Writable({\n write(chunk, _encoding, callback) {\n destination.write(chunk, (err) => callback(err ?? undefined));\n },\n final(callback) {\n try {\n const dehydratedState: DehydratedState = dehydrate(queryClient);\n queryStateJson = JSON.stringify(dehydratedState);\n } finally {\n queryClient.clear();\n }\n callback();\n resolve();\n },\n });\n\n passthrough.on('error', (err) => {\n destination.destroy(err);\n reject(err);\n });\n destination.on('error', reject);\n\n streamRef.pipe(passthrough);\n });\n };\n\n return {\n sessionState: JSON.stringify({ session: sessionPayload }),\n pipe,\n getQueryState: () => {\n if (queryStateJson === null) {\n throw new Error('getQueryState() called before stream finished');\n }\n return queryStateJson;\n },\n };\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export{g as getCallContext,f as startServer}from'./chunk-JGU3ZVX3.js';import'./chunk-7FIQ2GMI.js';import'./chunk-KDOTVIEY.js';import'./chunk-VYR7VQMQ.js';import'./chunk-UW37F3GV.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server-KDERUGRC.js.map
2
+ //# sourceMappingURL=server-KDERUGRC.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"server-D7FBXWTW.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"server-KDERUGRC.js"}
package/dist/server.d.ts CHANGED
@@ -234,6 +234,27 @@ type GenerateHandleProps = {
234
234
  firstName?: string;
235
235
  lastName?: string;
236
236
  };
237
+ /**
238
+ * The password-setting flow that invoked {@link AuthConfig.validatePassword}.
239
+ *
240
+ * Every path that writes a password hash passes one of these, so a policy can
241
+ * be uniform by default while still special-casing a flow if it needs to.
242
+ */
243
+ type PasswordContext = 'signup' | 'reset';
244
+ /**
245
+ * Props passed to {@link AuthConfig.validatePassword}.
246
+ */
247
+ type ValidatePasswordProps = {
248
+ /** The candidate plaintext password, after the built-in length checks. */
249
+ password: string;
250
+ /**
251
+ * Lowercased email address of the account the password is being set on.
252
+ * Useful for rejecting passwords that contain the local-part.
253
+ */
254
+ email: string;
255
+ /** Which flow is setting the password. */
256
+ context: PasswordContext;
257
+ };
237
258
  /**
238
259
  * Props passed to {@link AuthConfig.onBeforeSignup}.
239
260
  *
@@ -310,6 +331,35 @@ type AuthConfig = {
310
331
  * `firstName`, `lastName`, `avatarUrl`, `handle`). May be async.
311
332
  */
312
333
  validateSignup?: (props: SignupProps) => void | Promise<void>;
334
+ /**
335
+ * Password policy hook. Runs on **every** path that sets a password — signup
336
+ * and password reset today, plus any future change-password flow — after the
337
+ * built-in length checks (`MIN_PASSWORD_LENGTH`..`MAX_PASSWORD_LENGTH`) and
338
+ * before the password is hashed. Throw to reject the password; the thrown
339
+ * message is surfaced to the client.
340
+ *
341
+ * Prefer this over {@link AuthConfig.validateSignup} for password rules.
342
+ * `validateSignup` only runs at signup, so a policy enforced there alone can
343
+ * be bypassed by signing up with a compliant password and immediately
344
+ * resetting to a weaker one.
345
+ *
346
+ * Receives `{ password, email, context }`, where `context` is the flow that
347
+ * triggered the check (`'signup'` or `'reset'`). May be async.
348
+ *
349
+ * @example Enforce a 12-character minimum everywhere.
350
+ * ```typescript
351
+ * startApp({
352
+ * auth: {
353
+ * validatePassword: ({ password }) => {
354
+ * if (password.length < 12) {
355
+ * throw new Error('Password must be at least 12 characters');
356
+ * }
357
+ * },
358
+ * },
359
+ * });
360
+ * ```
361
+ */
362
+ validatePassword?: (props: ValidatePasswordProps) => void | Promise<void>;
313
363
  /**
314
364
  * Pre-update validation hook. Runs before a user's profile fields
315
365
  * (`firstName`, `lastName`, `avatarUrl`, `handle`) are written.
package/dist/server.js CHANGED
@@ -1,2 +1,2 @@
1
- export{m as ObjectId,k as ServerChannel,a as consumeRateLimit,c as deleteFile,j as deleteUser,i as disableUser,d as downloadFile,e as getFileUrl,b as getUploadUrl,l as sendEmail,h as startApp}from'./chunk-7XZDALJZ.js';import'./chunk-JQ7HKLQZ.js';export{y as LiveData,a as Module,c as Store,x as authenticate,k as clearSessionUser,A as createQuery,m as createSession,h as dbSessions,q as dbUsers,l as invalidateAllUserSessions,i as obtainSession,d as schema,n as setAuthTokenCookie,j as setSessionUser}from'./chunk-QMKQ7DUD.js';import'./chunk-VYR7VQMQ.js';export{a as getConfig,h as getEnvironmentId}from'./chunk-B5WLEHNH.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server.js.map
1
+ export{m as ObjectId,k as ServerChannel,a as consumeRateLimit,c as deleteFile,j as deleteUser,i as disableUser,d as downloadFile,e as getFileUrl,b as getUploadUrl,l as sendEmail,h as startApp}from'./chunk-JGU3ZVX3.js';import'./chunk-7FIQ2GMI.js';export{y as LiveData,a as Module,c as Store,x as authenticate,k as clearSessionUser,A as createQuery,m as createSession,h as dbSessions,q as dbUsers,l as invalidateAllUserSessions,i as obtainSession,d as schema,n as setAuthTokenCookie,j as setSessionUser}from'./chunk-KDOTVIEY.js';import'./chunk-VYR7VQMQ.js';export{a as getConfig,h as getEnvironmentId}from'./chunk-UW37F3GV.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';//# sourceMappingURL=server.js.map
2
2
  //# sourceMappingURL=server.js.map
package/dist/telemetry.js CHANGED
@@ -1,2 +1,2 @@
1
- export{o as captureError,k as logDebug,m as logError,l as logInfo,j as redactSensitive,n as startTransaction}from'./chunk-B5WLEHNH.js';//# sourceMappingURL=telemetry.js.map
1
+ export{o as captureError,k as logDebug,m as logError,l as logInfo,j as redactSensitive,n as startTransaction}from'./chunk-UW37F3GV.js';//# sourceMappingURL=telemetry.js.map
2
2
  //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1,2 @@
1
+ import {c,a}from'./chunk-UJ2WYHH7.js';import'./chunk-KDOTVIEY.js';import'./chunk-UW37F3GV.js';import {H,G}from'./chunk-MTG3OZWX.js';import'./chunk-5M6FUMUK.js';import'./chunk-DO5TZLF5.js';function d(){return H(async(t,r)=>{let o=c();return o?a(t,r,o.callContext):G(t,r)})}export{d as installSsrCallMethodTransport};//# sourceMappingURL=transport-LWVQ4TUY.js.map
2
+ //# sourceMappingURL=transport-LWVQ4TUY.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ssr/transport.ts"],"names":["installSsrCallMethodTransport","setCallMethodTransport","methodName","args","ssrCtx","getSsrContext","callInProcessMethod","defaultCallMethodTransport"],"mappings":"4LAcO,SAASA,CAAAA,EAA4C,CAC1D,OAAOC,CAAAA,CAAuB,MAAUC,EAAoBC,CAAAA,GAAqB,CAC/E,IAAMC,CAAAA,CAASC,CAAAA,EAAc,CAC7B,OAAKD,CAAAA,CAIEE,CAAAA,CAAuBJ,CAAAA,CAAYC,CAAAA,CAAMC,CAAAA,CAAO,WAAW,CAAA,CAHzDG,CAAAA,CAA8BL,CAAAA,CAAYC,CAAI,CAIzD,CAAC,CACH","file":"transport-OSL4EWWD.js","sourcesContent":["import {\n setCallMethodTransport,\n defaultCallMethodTransport,\n type MethodArgs,\n} from '../client/method';\nimport { callInProcessMethod } from './callInProcess';\nimport { getSsrContext } from './context';\n\n/**\n * Routes `callMethod` through `runMethod` in-process during an active SSR\n * render. Outside a render (e.g. server-side `callMethod` from jobs or other\n * non-render code) there is no request context, so it falls back to the\n * default HTTP transport — installing SSR must not break those call sites.\n */\nexport function installSsrCallMethodTransport(): () => void {\n return setCallMethodTransport(async <T>(methodName: string, args: MethodArgs) => {\n const ssrCtx = getSsrContext();\n if (!ssrCtx) {\n return defaultCallMethodTransport<T>(methodName, args);\n }\n\n return callInProcessMethod<T>(methodName, args, ssrCtx.callContext);\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/ssr/transport.ts"],"names":["installSsrCallMethodTransport","setCallMethodTransport","methodName","args","ssrCtx","getSsrContext","callInProcessMethod","defaultCallMethodTransport"],"mappings":"4LAcO,SAASA,CAAAA,EAA4C,CAC1D,OAAOC,CAAAA,CAAuB,MAAUC,EAAoBC,CAAAA,GAAqB,CAC/E,IAAMC,CAAAA,CAASC,CAAAA,EAAc,CAC7B,OAAKD,CAAAA,CAIEE,CAAAA,CAAuBJ,CAAAA,CAAYC,CAAAA,CAAMC,CAAAA,CAAO,WAAW,CAAA,CAHzDG,CAAAA,CAA8BL,CAAAA,CAAYC,CAAI,CAIzD,CAAC,CACH","file":"transport-LWVQ4TUY.js","sourcesContent":["import {\n setCallMethodTransport,\n defaultCallMethodTransport,\n type MethodArgs,\n} from '../client/method';\nimport { callInProcessMethod } from './callInProcess';\nimport { getSsrContext } from './context';\n\n/**\n * Routes `callMethod` through `runMethod` in-process during an active SSR\n * render. Outside a render (e.g. server-side `callMethod` from jobs or other\n * non-render code) there is no request context, so it falls back to the\n * default HTTP transport — installing SSR must not break those call sites.\n */\nexport function installSsrCallMethodTransport(): () => void {\n return setCallMethodTransport(async <T>(methodName: string, args: MethodArgs) => {\n const ssrCtx = getSsrContext();\n if (!ssrCtx) {\n return defaultCallMethodTransport<T>(methodName, args);\n }\n\n return callInProcessMethod<T>(methodName, args, ssrCtx.callContext);\n });\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "modelence",
4
- "version": "0.23.0-setup.dev.3",
4
+ "version": "0.23.0-setup.dev.5",
5
5
  "description": "The Node.js Framework for Real-Time MongoDB Apps",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/global.d.ts",
@@ -97,8 +97,6 @@
97
97
  "typescript": "^5.7.2",
98
98
  "vite": "^6.0.3",
99
99
  "vite-plugin-eslint": "^1.8.1",
100
- "winston": "^3.15.0",
101
- "winston-elasticsearch": "^0.19.0",
102
100
  "zod": "^3.23.8",
103
101
  "zustand": "^5.0.2"
104
102
  },
@@ -1,37 +0,0 @@
1
- import {t as t$1}from'./chunk-JQ7HKLQZ.js';import {a,b as b$1,c,d,q,r,s,t,u,m,n,e,z as z$2,l,k,o,j,p,v as v$1,A,B,C as C$1,D,f as f$1,E,x as x$1,w as w$1,g as g$1,H,F as F$1,G}from'./chunk-QMKQ7DUD.js';import {c as c$1,b as b$2,d as d$1,a as a$4}from'./chunk-VYR7VQMQ.js';import {a as a$2,f,e as e$1,g,c as c$2,i,m as m$1,l as l$1,d as d$2,k as k$1,n as n$1,j as j$1,o as o$1}from'./chunk-B5WLEHNH.js';import {a as a$3,b as b$3}from'./chunk-5M6FUMUK.js';import {a as a$1}from'./chunk-DO5TZLF5.js';import ar from'dotenv';import Tn from'fs/promises';import Yr from'os';import Q from'path';import {Server}from'socket.io';import {createAdapter}from'@socket.io/mongo-adapter';import {MongoServerError,MongoClient,MongoError,ObjectId}from'mongodb';export{ObjectId as m}from'mongodb';import xr from'bcrypt';import V,{z as z$1}from'zod';import {randomBytes,randomInt,randomUUID}from'crypto';import {createServer,defineConfig,loadConfigFromFile,mergeConfig}from'vite';import hn from'@vitejs/plugin-react';import Le from'fs';import B$1,{Router}from'express';import gi from'cookie-parser';import hi from'http';var le=new a("_system",{queries:{setupStatus:async()=>({setupRequired:b$1()})},configSchema:{mongodbUri:{type:"secret",isPublic:false,default:""},mongodbPoolSize:{type:"number",isPublic:false,default:10},"env.type":{type:"string",isPublic:true,default:""},"site.url":{type:"string",isPublic:true,default:""},multiInstance:{type:"boolean",isPublic:false,default:false}}});var F=null;async function qt(){if(F)return F;let e=N();if(!e)throw new Error("MongoDB URI is not set");let t=le.getConfig("mongodbPoolSize");F=new MongoClient(e,{driverInfo:{name:"Modelence",version:t$1.version},ignoreUndefined:true,maxPoolSize:t});try{return await F.connect(),await F.db("admin").command({ping:1}),console.log("Pinged your deployment. You successfully connected to MongoDB!"),F}catch(o){throw console.error(o),F=null,o}}function N(){return le.getConfig("mongodbUri")||void 0}function ve(){return F}var de=null,vr="_modelenceSocketio",zt=60;async function kr({httpServer:e,channels:t}){let o=ve(),r=!!a$2("_system.multiInstance");console.log("Initializing Socket.IO server...");let n=null;if(r&&o){n=o.db().collection(vr);try{await n.createIndex({createdAt:1},{expireAfterSeconds:zt,background:!0});}catch(i){if(i instanceof Error&&"code"in i&&i.code===85)try{await n.dropIndex("createdAt_1"),await n.createIndex({createdAt:1},{expireAfterSeconds:zt,background:!0});}catch(s){console.error("Failed to recreate index on MongoDB collection for Socket.IO:",s);}else console.error("Failed to create index on MongoDB collection for Socket.IO:",i);}}de=new Server(e,{cors:{origin:"*",methods:["GET","POST"]},adapter:n?createAdapter(n):void 0,transports:["websocket"],perMessageDeflate:false}),de.on("error",i=>{console.error("Socket.IO error:",i);}),de.use(async(i,s)=>{let a=i.handshake.auth.token;try{i.data=await x$1(a),s();}catch(c){s(c instanceof Error?c:new Error(String(c)));}}),de.on("connection",i=>{i.on("disconnect",()=>{H(i);}),i.on("joinChannel",async s=>{let[a]=s.split(":"),c=false;for(let l of t)if(l.category===a){(!l.canAccessChannel||await l.canAccessChannel(i.data))&&(i.join(s),c=true,i.emit("joinedChannel",s));break}c||i.emit("joinError",{channel:s,error:"Access denied"});}),i.on("leaveChannel",s=>{i.leave(s),console.log(`User ${i.id} left channel ${s}`),i.emit("leftChannel",s);}),i.on("subscribeLiveQuery",s=>F$1(i,s)),i.on("unsubscribeLiveQuery",s=>G(i,s));}),console.log("Socket.IO server initialized");}function Cr({category:e,id:t,data:o}){de?.to(`${e}:${t}`).emit(e,o);}var Wt={init:kr,broadcast:Cr};async function ke(e){let t=e.toLowerCase().trim().split("@");if(t.length!==2)return false;let o=t[1];return !!await r.findOne({domain:o})}var Jt={interval:a$1.days(1),async handler(){let e=await fetch("https://disposable.github.io/disposable-email-domains/domains.txt");if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);let o=(await e.text()).split(`
2
- `).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0),r$1=new Date,n=500;for(let i=0;i<o.length;i+=n){let s=o.slice(i,i+n);try{await r.insertMany(s.map(a=>({domain:a,addedAt:r$1})));}catch(a){a&&typeof a=="object"&&"name"in a&&a.name;}}}};var Ce=3,z=50,Kt=8,Yt=128,Qt=254,Xt=e=>z$1.string().trim().min(e.min??1,{message:`must be at least ${e.min??1} characters`}).max(e.max,{message:`must be at most ${e.max} characters`}),Fe=e=>z$1.string().trim().max(e.max,{message:`must be at most ${e.max} characters`}).transform(t=>t===""?void 0:t).optional(),Sr=z$1.object({firstName:Fe({max:50}),lastName:Fe({max:50}),avatarUrl:Fe({max:400}),handle:Xt({min:Ce,max:z})}).strict();function Se(e){let t=Sr.partial().safeParse(e);if(!t.success){let o=t.error.issues[0],r=o.path.join("."),n=r?`${r}: ${o.message}`:o.message;throw new Error(n)}return t.data}function Ae(e){return z$1.string().min(Kt,{message:`Password must contain at least ${Kt} characters`}).max(Yt,{message:`Password must be at most ${Yt} characters`}).parse(e)}function O(e){return z$1.string().max(Qt,{message:`Email must be at most ${Qt} characters`}).email({message:"Invalid email address"}).parse(e).toLowerCase()}function Zt(e){return Xt({min:Ce,max:z}).parse(e)}function Re(e){return e instanceof MongoServerError&&e.code===11e3&&typeof e.keyPattern=="object"&&e.keyPattern!==null&&"emails.address"in e.keyPattern}function xe(e,t){return t?t.startsWith("http://")||t.startsWith("https://")?t:`${e}${t.startsWith("/")?"":"/"}${t}`:e}function ee(e){return {id:e._id,handle:e.handle,roles:e.roles||[],firstName:e.firstName??void 0,lastName:e.lastName??void 0,avatarUrl:e.avatarUrl??void 0}}async function eo(e){let t=e.slice(0,z);try{if(!await q.findOne({handle:t},{collation:{locale:"en",strength:2}}))return t}catch(n){throw new Error(`Database error while checking handle availability: ${n}`)}let o=51;for(let n=2;n<=o;n++){let i=`_${n}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}let r=10;for(let n=0;n<r;n++){let i=`_${randomBytes(3).toString("hex")}`,s=`${t.slice(0,z-i.length)}${i}`;try{if(!await q.findOne({handle:s},{collation:{locale:"en",strength:2}}))return s}catch(a){throw new Error(`Database error while checking handle "${s}": ${a}`)}}throw new Error(`Could not generate a unique handle for base "${e}" after exhausting all attempts.`)}async function L(e,t,{throwOnConflict:o=true}={}){if(e!=null&&String(e).trim()!==""){let n=Zt(String(e).trim());if(o){if(await q.findOne({handle:n},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");return n}return eo(n)}let r=t.split("@")[0].padEnd(Ce,"_").slice(0,z);return eo(r)}var Ve=Object.freeze({});function Be(e){Ve=Object.freeze(Object.assign({},Ve,e));}function w(){return Ve}var qe=Object.freeze({});function to(e){qe=Object.freeze(Object.assign({},qe,e));}function b(){return qe}function _r(){return w()?.provider?!!a$2("_system.user.auth.email.verification"):false}async function ro(e,{user:t,session:o,connectionInfo:r,res:n$1}){try{if(!o)throw new Error("Session is not initialized");if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let i=r?.ip;i&&await C({bucket:"signin",type:"ip",value:i});let s=O(e.email),a=z$1.string().parse(e.password),c=await q.findOne({"emails.address":s,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}}),l=c?.authMethods?.password?.hash;if(!l)throw oo();if(!c.emails?.find(f=>f.address.toLowerCase()===s)?.verified&&_r())throw new b$2("Your email address hasn't been verified yet. Please check your inbox for the verification email.","EMAIL_NOT_VERIFIED");if(!await xr.compare(a,l))throw oo();return await j(o.authToken,c._id),n$1&&n(n$1,o.authToken),b().onAfterLogin?.({provider:"email",user:c,session:o,connectionInfo:r}),b().login?.onSuccess?.(c),{user:ee(c),session:{authToken:o.authToken}}}catch(i){throw i instanceof Error&&(b().onLoginError?.({provider:"email",error:i,session:o,connectionInfo:r}),b().login?.onError?.(i)),i}}async function no(e,{session:t,res:o$1}){if(!t)throw new Error("Session is not initialized");await k(t.authToken),o$1&&o(o$1);}function oo(){return new Error("Incorrect email/password combination")}async function io(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id);return {handle:o.handle,emails:o.emails,authMethods:Object.keys(o.authMethods||{}),firstName:o.firstName??void 0,lastName:o.lastName??void 0,avatarUrl:o.avatarUrl??void 0}}async function so(e,{user:t}){if(!t)throw new Error("Not authenticated");let o=await q.requireById(t.id),r=Se(e);if(await b().validateProfileUpdate?.(r),"handle"in r&&r.handle!==void 0&&await q.findOne({handle:r.handle,_id:{$ne:o._id}},{collation:{locale:"en",strength:2}}))throw new Error("Handle already taken.");if(Object.keys(r).length>0){let n={},i={};for(let[a,c]of Object.entries(r))c===void 0?i[a]="":n[a]=c;let s={};Object.keys(n).length>0&&(s.$set=n),Object.keys(i).length>0&&(s.$unset=i);try{await q.updateOne({_id:o._id},s);let a=Object.fromEntries(Object.keys(i).map(c=>[c,void 0]));o={...o,...n,...a};}catch(a){throw a instanceof Error&&"code"in a&&a.code===11e3?new Error("Handle already taken."):a}}return {user:ee(o)}}var ze=["google","github"];async function ao({provider:e},{user:t}){if(!t)throw new Error("You must be signed in to unlink a provider.");if(typeof e!="string"||!ze.includes(e))throw new Error(`Invalid provider. Supported providers are: ${ze.join(", ")}.`);let o=await q.requireById(t.id),r=o.authMethods??{};if(!r[e])throw new Error(`${e} is not linked to your account.`);if(Object.values(r).filter(Boolean).length<=1)throw new Error("Cannot unlink your only authentication method. Please add another method first.");let s=Object.keys(r).filter(l=>l!==e&&r[l]),a=s.length>0?{$or:s.map(l=>({[`authMethods.${l}`]:{$exists:true}}))}:{};if((await q.updateOne({_id:o._id,...a},{$unset:{[`authMethods.${e}`]:""}})).matchedCount===0)throw new Error("Cannot unlink your only authentication method. Please add another method first.")}var me=new c("_modelenceRateLimits",{schema:{bucket:d.string(),type:d.enum(["ip","user","email"]),value:d.string(),windowMs:d.number(),windowStart:d.date(),windowCount:d.number(),prevWindowCount:d.number(),expiresAt:d.date()},indexes:[{key:{bucket:1,type:1,value:1,windowMs:1},unique:true},{key:{expiresAt:1},expireAfterSeconds:0}]});var We=[];function co(e){if(We.length>0)throw new Error("Duplicate call to initRateLimits - already initialized");We=e;}async function C(e){let{bucket:t,type:o,value:r,message:n}=e,i=We.filter(a=>a.bucket===t&&a.type===o),s=n?()=>new d$1(n):void 0;for(let a of i)await Lr(a,r,s);}async function Lr(e,t,o){let r=()=>o?o():new d$1(`Rate limit exceeded for ${e.bucket}`),n=await me.findOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window}),i=Date.now(),s=Math.floor(i/e.window)*e.window,{count:a,modifier:c}=n?Tr(n,s,i):{count:0,modifier:{$setOnInsert:{windowStart:new Date(s),windowCount:1,prevWindowCount:0,expiresAt:new Date(s+e.window+e.window)}}};if(a>=e.limit)throw r();await me.upsertOne({bucket:e.bucket,type:e.type,value:t,windowMs:e.window},c);}function Tr(e,t,o){let r=t-e.windowMs;if(e.windowStart.getTime()===t){let n=e.windowCount,i=e.prevWindowCount,s=1-(o-t)/e.windowMs;return {count:Math.round(n+i*s),modifier:{$inc:{windowCount:1},$setOnInsert:{windowStart:new Date(t),prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}if(e.windowStart.getTime()===r){let n=1-(o-t)/e.windowMs;return {count:Math.round(e.windowCount*n),modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:e.windowCount,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}return {count:0,modifier:{$set:{windowStart:new Date(t),windowCount:1,prevWindowCount:0,expiresAt:new Date(t+e.windowMs+e.windowMs)}}}}function lo({name:e,email:t,verificationUrl:o}){return `
3
- <p>Hi${e?` ${e}`:""},</p>
4
- <p>Please verify your email address ${t} by clicking the link below:</p>
5
- <p><a href="${o}">${o}</a></p>
6
- <p>If you did not request this, please ignore this email.</p>
7
- `}async function Ir(e){let t=await s.findOne({token:e,expiresAt:{$gt:new Date}});if(!t)throw new Error("Invalid or expired verification token");if(!await q.findOne({_id:t.userId,status:{$nin:["deleted","disabled"]}}))throw new Error("User not found");let r=t.email;if(!r)throw new Error("Email not found in token");let n=await q.findOneAndUpdate({_id:t.userId,status:{$nin:["deleted","disabled"]},"emails.address":r,"emails.verified":{$ne:true}},{$set:{"emails.$.verified":true}},{returnDocument:"after"});if(!n)throw await q.findOne({_id:t.userId,"emails.address":r})?new Error("Email is already verified"):new Error("Email address not found for this user");return await s.deleteOne({_id:t._id}),{userDoc:n,email:r}}async function uo(e){let t=a$2("_system.site.url"),o=w().verification?.redirectUrl||w().emailVerifiedRedirectUrl||t||"/";try{let r=z$1.string().parse(e.query.token),{userDoc:n$1}=await Ir(r);b().onAfterEmailVerification?.({provider:"email",user:n$1,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}});let{authToken:s}=await m(n$1._id);return n(e.res,s),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=verified`}}catch(r){let n=r instanceof Error?r.message:"An unexpected error occurred";return r instanceof Error&&(b().onEmailVerificationError?.({provider:"email",error:r,session:null,connectionInfo:{baseUrl:t,ip:e.req.ip||e.req.socket.remoteAddress,userAgent:e.headers["user-agent"],acceptLanguage:e.headers["accept-language"],referrer:e.headers.referer}}),console.error("Error verifying email:",r)),{status:301,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent(n)}`}}}async function Ke({userId:e,email:t,baseUrl:o}){let r=a$2("_system.site.url")||o;if(w().provider){let n=w().provider,i=randomBytes(32).toString("hex"),s$1=new Date(Date.now()+a$1.hours(24));await s.insertOne({userId:e,email:t,token:i,createdAt:new Date,expiresAt:s$1});let a=`${r}/api/_internal/auth/verify-email?token=${i}`,l=(w()?.verification?.template||lo)({name:"",email:t,verificationUrl:a}),d=z$2(l);await n?.sendEmail({to:t,from:w()?.from||"noreply@modelence.com",subject:w()?.verification?.subject||"Verify your email address",text:d,html:l});}}var Je={success:true,message:"If that email is registered and not yet verified, a verification email has been sent"};async function mo(e,{connectionInfo:t}){let o=O(e.email),r=await q.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!r)return Je;let n=r.emails?.find(i=>i.address.toLowerCase()===o);if(!n||n.verified)return Je;if(!w().provider)throw new Error("Email provider is not configured");return await C({bucket:"verification",type:"user",value:r._id.toString(),message:"Please wait at least 60 seconds before requesting another verification email"}),await Ke({userId:r._id,email:o,baseUrl:t?.baseUrl}),Je}async function po(e,{user:t,session:o,connectionInfo:r}){let n=b();try{if(t)throw new c$1("User is already authenticated","ALREADY_AUTHENTICATED");let i=e,{firstName:s,lastName:a,avatarUrl:c,handle:l}=i,d=O(i.email),m=Ae(i.password),f=r?.ip;if(f&&await C({bucket:"signupAttempt",type:"ip",value:f}),!n.allowDisposableEmails&&await ke(d))throw new Error("Please use a permanent email address");let h=await q.findOne({"emails.address":d},{collation:{locale:"en",strength:2}});if(h){let _=h.emails?.find(D=>D.address.toLowerCase()===d);throw h.status==="disabled"?new Error("User is marked for deletion, please contact support if you want to restore the account."):new Error(`User with email already exists: ${_?.address}`)}await n.onBeforeSignup?.({email:d,firstName:s,lastName:a,handle:l,provider:"email",connectionInfo:r}),f&&await C({bucket:"signup",type:"ip",value:f});let y=Se({firstName:s,lastName:a,avatarUrl:c,handle:l});await n.validateSignup?.({email:d,password:m,...y});let k;if(y.handle)k=await L(y.handle,d);else if(n.generateHandle){let _=await n.generateHandle({email:d,firstName:y.firstName,lastName:y.lastName});k=await L(_,d,{throwOnConflict:!1});}else k=await L(void 0,d);let P=await xr.hash(m,10),M;try{M=await q.insertOne({handle:k,status:"active",emails:[{address:d,verified:!1}],createdAt:new Date,authMethods:{password:{hash:P}},...y.firstName!==void 0&&{firstName:y.firstName},...y.lastName!==void 0&&{lastName:y.lastName},...y.avatarUrl!==void 0&&{avatarUrl:y.avatarUrl}});}catch(_){throw Re(_)?new Error(`User with email already exists: ${d}`):_}let S=await q.findOne({_id:M.insertedId},{readPreference:"primary"});if(!S)throw new Error("User not found");return await Ke({userId:M?.insertedId,email:d,baseUrl:r?.baseUrl}),n.onAfterSignup?.({provider:"email",user:S,session:o,connectionInfo:r}),n.signup?.onSuccess?.(S),M.insertedId}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:"email",error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}var Ye="resetPasswordToken",$r="/api/_internal/",wo={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:$r};async function yo(e$1){return t.findOne({token:e(e$1)})}async function fo(e){return t.findOneAndDelete({_id:e})}function jr({email:e,resetUrl:t}){return `
8
- <p>Hi,</p>
9
- <p>We received a request to reset your password for ${e}.</p>
10
- <p>Click the link below to reset your password:</p>
11
- <p><a href="${t}">${t}</a></p>
12
- <p>This link will expire in 1 hour.</p>
13
- <p>If you did not request this password reset, please ignore this email.</p>
14
- `}var go={success:true,message:"If an account with that email exists, a password reset link has been sent"};async function Eo(e$1,{connectionInfo:t$1}){let o=O(e$1.email),r=t$1?.ip;r&&await C({bucket:"passwordReset",type:"ip",value:r}),await C({bucket:"passwordReset",type:"email",value:o});let n=await q.findOne({"emails.address":o,status:{$nin:["deleted","disabled"]}},{collation:{locale:"en",strength:2}});if(!n)return go;let i=w().provider;if(!i)throw new Error("Email provider is not configured");let s=randomBytes(32).toString("hex"),a=Date.now(),c=new Date(a),l=new Date(a+a$1.hours(1));await t.insertOne({userId:n._id,email:o,token:e(s),createdAt:c,expiresAt:l});let d=a$2("_system.site.url")||t$1?.baseUrl;if(!d)throw new Error("Unable to build password reset link: set _system.site.url (MODELENCE_SITE_URL)");let m=`${d}/api/_internal/auth/reset-password?token=${s}`,h=(w()?.passwordReset?.template||jr)({email:o,resetUrl:m,name:""}),y=z$2(h);return await i.sendEmail({to:o,from:w()?.from||"noreply@modelence.com",subject:w()?.passwordReset?.subject||"Reset your password",text:y,html:h}),go}async function bo(e){let t=a$2("_system.site.url")||`${e.req.protocol}://${e.req.get("host")}`,o=xe(t,w().passwordReset?.redirectUrl);try{let r=z$1.string().parse(e.query.token),n=await yo(r);if(!n||n.expiresAt<new Date)throw new Error("This password reset link is invalid or has expired.");return e.res.cookie(Ye,r,{...wo,maxAge:a$1.hours(1)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling password reset landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This password reset link is invalid or has expired.")}`}}}async function vo(e,t){let o=t.req?.cookies?.[Ye];!o&&e.token&&console.warn("[modelence] resetPassword received a token via request args instead of the httpOnly cookie. This path is deprecated and will be removed; ensure password reset emails link to /api/_internal/auth/reset-password so the token is exchanged server-side.");let r=z$1.string().parse(o??e.token),n=Ae(e.password),i=()=>{t.res?.clearCookie(Ye,wo);},s=await yo(r);if(!s)throw i(),new Error("Invalid or expired reset token");if(s.expiresAt<new Date)throw await fo(s._id),i(),new Error("Reset token has expired");let a=await q.findOne({_id:s.userId});if(!a)throw new Error("User not found");let c=await xr.hash(n,10);if(!await fo(s._id))throw i(),new Error("Invalid or expired reset token");await q.updateOne({_id:a._id},{$set:{"authMethods.password.hash":c}}),s.email&&await q.updateOne({_id:a._id,"emails.address":s.email},{$set:{"emails.$.verified":true}},{collation:{locale:"en",strength:2}}),await l(a._id);let d=Array.from(new Set((a.emails??[]).map(m=>m.address?.toLowerCase()).filter(m=>!!m)));return d.length>0&&await u.deleteMany({email:{$in:d}}),i(),{success:true,message:"Password has been reset successfully"}}function ko({name:e,email:t,magicLinkUrl:o,code:r}){return `
15
- <p>Hi${e?` ${e}`:""},</p>
16
- <p>Click the link below to sign in as ${t}:</p>
17
- <p><a href="${o}">${o}</a></p>
18
- <p>Or enter this one-time code in the app:</p>
19
- <p><strong style="font-size: 24px; letter-spacing: 4px;">${r}</strong></p>
20
- <p>The link and code can only be used once and will expire in 15 minutes.</p>
21
- <p>If you did not request this, please ignore this email.</p>
22
- `}var Ze="magicLinkToken",Fr="/api/_internal/",So={httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:Fr},Ao=15,Co=6,Vr=5;function Oe(e,t){try{Promise.resolve(t?.()).catch(o=>{console.error(`Error in ${e} hook:`,o);});}catch(o){console.error(`Error in ${e} hook:`,o);}}function ot(){return !!b().magicLink?.enabled}function Ro(){return !!b().magicLink?.allowSignup}async function xo(e$1){return u.findOne({token:e(e$1)})}async function rt(e){return u.findOneAndDelete({_id:e})}async function Qe(e){try{await u.insertOne(e);}catch(t){console.error("Failed to restore a magic link token after a failed signup:",t);}}var Xe={success:true,message:"If this email can be used to sign in, a link has been sent"};async function Oo(e$1,{connectionInfo:t}){if(!ot())throw new Error("Magic link authentication is not enabled");let o=O(e$1.email),r=t?.ip;r&&await C({bucket:"magicLink",type:"ip",value:r}),await C({bucket:"magicLink",type:"email",value:o});let n=w().provider;if(!n)throw new Error("Email provider is not configured");let i=w().from;if(!i)throw new Error("Email `from` address is not configured");let s=a$2("_system.site.url");if(!s)throw new Error("Unable to build magic link: set _system.site.url (MODELENCE_SITE_URL)");if(!b().allowDisposableEmails&&await ke(o))throw new Error("Please use a permanent email address");let a=await q.findOne({"emails.address":o},{collation:{locale:"en",strength:2}});if(a&&(a.status==="disabled"||a.status==="deleted")||!a&&!Ro())return Xe;let c=randomBytes(32).toString("hex"),l=randomInt(0,10**Co).toString().padStart(Co,"0"),d=Date.now(),m=new Date(d),f=new Date(d+a$1.minutes(Ao));await u.insertOne({email:o,token:e(c),code:e(l),attempts:0,createdAt:m,expiresAt:f});let h=`${s}/api/_internal/auth/magic-link?token=${c}`,k=(w()?.magicLink?.template||ko)({email:o,magicLinkUrl:h,code:l,name:""}),P=z$2(k);return await n.sendEmail({to:o,from:i,subject:w()?.magicLink?.subject||"Your sign-in link",text:P,html:k}),Xe}async function _o(e){let t=a$2("_system.site.url")||"",o=xe(t,w().magicLink?.redirectUrl)||"/";try{let r=z$1.string().parse(e.query.token),n=await xo(r);if(!n||n.expiresAt<new Date)throw new Error("This sign-in link is invalid or has expired.");return e.res.cookie(Ze,r,{...So,maxAge:a$1.minutes(Ao)}),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:o}}catch(r){return console.error("Error handling magic link landing:",r),{status:302,headers:{"Referrer-Policy":"no-referrer"},redirect:`${o}?status=error&message=${encodeURIComponent("This sign-in link is invalid or has expired.")}`}}}var et={locale:"en",strength:2};async function Lo(e){let{tokenDoc:t,session:o,connectionInfo:r,res:n$1,clearCookie:i}=e,s=t.email,a=b(),c=Ro(),l=false;try{let d=await rt(t._id);if(!d)throw i(),new Error("Invalid or expired code or magic link");let m;if(c)try{if(!await q.findOne({"emails.address":s},{collation:et})){l=!0,await a.onBeforeSignup?.({email:s,provider:"magicLink",connectionInfo:r});let _=r?.ip;_&&await C({bucket:"signup",type:"ip",value:_}),m=a.generateHandle?await L(await a.generateHandle({email:s}),s,{throwOnConflict:!1}):await L(void 0,s);}}catch(S){throw await Qe(d),S}let f;try{f=await Br(s,m,c);}catch(S){throw await Qe(d),S}let{userDoc:h,isNew:y}=f;if(!h)throw await Qe(d),i(),c&&!l?new Error("User account is not active"):(l=!0,new Error("Sign up with magic link is not enabled"));if(l=y,h.status==="disabled"||h.status==="deleted")throw i(),new Error("User account is not active");let k=h,P=h.emails?.find(S=>S.address.toLowerCase()===s),M=!y&&!P?.verified;return M&&(k=await q.findOneAndUpdate({_id:h._id,"emails.address":s},{$set:{"emails.$.verified":!0}},{collation:et,returnDocument:"after"})??h),await j(o.authToken,k._id),n$1&&n(n$1,o.authToken),y?Oe("onAfterSignup",()=>a.onAfterSignup?.({provider:"magicLink",user:k,session:o,connectionInfo:r})):(M&&Oe("onAfterEmailVerification",()=>a.onAfterEmailVerification?.({provider:"magicLink",user:k,session:o,connectionInfo:r})),Oe("onAfterLogin",()=>a.onAfterLogin?.({provider:"magicLink",user:k,session:o,connectionInfo:r}))),i(),{user:ee(k),session:{authToken:o.authToken}}}catch(d){if(d instanceof Error){let m=l?"onSignupError":"onLoginError",f=l?a.onSignupError:a.onLoginError;Oe(m,()=>f?.({provider:"magicLink",error:d,session:o,connectionInfo:r}));}throw d}}async function Br(e,t,o){let r=o&&t!==void 0,n=()=>q.findOneAndUpsert({emails:{$elemMatch:{address:e}}},{$setOnInsert:{handle:t,status:"active",emails:[{address:e,verified:true}],createdAt:new Date,authMethods:{}}},{upsert:r,collation:et});try{let{doc:i,isNew:s}=await n();return {userDoc:i,isNew:s}}catch(i){if(!Re(i))throw i;let{doc:s}=await n();return {userDoc:s,isNew:false}}}async function To(e,t){let{session:o,connectionInfo:r,res:n,req:i}=t;if(!o)throw new Error("Session is not initialized");if(!ot())throw new Error("Magic link authentication is not enabled");let s=z$1.string().parse(i?.cookies?.[Ze]),a=()=>{n?.clearCookie(Ze,So);},c=await xo(s);if(!c)throw a(),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await rt(c._id),a(),new Error("Code or magic link has expired");return Lo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:a})}async function Po(e$1,t){let{session:o,connectionInfo:r,res:n}=t;if(!o)throw new Error("Session is not initialized");if(!ot())throw new Error("Magic link authentication is not enabled");let i=O(e$1.email),s=z$1.string().parse(e$1.code).replace(/[\s-]/g,""),a=r?.ip;a&&await C({bucket:"oneTimeCode",type:"ip",value:a}),await C({bucket:"oneTimeCode",type:"email",value:i});let c=await u.findOne({email:i,code:e(s),attempts:{$lt:Vr}});if(!c)throw await u.updateMany({email:i},{$inc:{attempts:1}}),new Error("Invalid or expired code or magic link");if(c.expiresAt<new Date)throw await rt(c._id),new Error("Code or magic link has expired");return Lo({tokenDoc:{_id:c._id,email:c.email},session:o,connectionInfo:r,res:n,clearCookie:()=>{}})}function Mo(e){return `${e.bucket}
23
- ${e.type}
24
- ${e.window}`}function qr(){return [{bucket:"signup",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"signup",type:"ip",window:a$1.days(1),limit:200},{bucket:"signupAttempt",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signupAttempt",type:"ip",window:a$1.days(1),limit:500},{bucket:"signin",type:"ip",window:a$1.minutes(15),limit:50},{bucket:"signin",type:"ip",window:a$1.days(1),limit:500},{bucket:"verification",type:"user",window:a$1.seconds(60),limit:1},{bucket:"verification",type:"user",window:a$1.days(1),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"passwordReset",type:"ip",window:a$1.days(1),limit:100},{bucket:"passwordReset",type:"email",window:a$1.hours(1),limit:5},{bucket:"passwordReset",type:"email",window:a$1.days(1),limit:10},{bucket:"magicLink",type:"ip",window:a$1.minutes(15),limit:10},{bucket:"magicLink",type:"ip",window:a$1.days(1),limit:100},{bucket:"magicLink",type:"email",window:a$1.hours(1),limit:5},{bucket:"magicLink",type:"email",window:a$1.days(1),limit:10},{bucket:"oneTimeCode",type:"ip",window:a$1.minutes(15),limit:20},{bucket:"oneTimeCode",type:"ip",window:a$1.days(1),limit:100},{bucket:"oneTimeCode",type:"email",window:a$1.hours(1),limit:10},{bucket:"oneTimeCode",type:"email",window:a$1.days(1),limit:20}]}function zr(e){let t=[],o=["signup","signupAttempt","signin","verification","passwordReset","magicLink","oneTimeCode"];for(let r of o){let n=e[r];if(n!==void 0)for(let i of n)t.push({bucket:r,...i});}return t}function nt(e={}){let t=qr(),o=zr(e),r=new Map;for(let s of o)r.set(Mo(s),s);let n=[],i=new Set;for(let s of t){let a=Mo(s),c=r.get(a);c!==void 0?(n.push(c),i.add(a)):n.push(s);}for(let[s,a]of r)i.has(s)||n.push(a);return n}var it=new a("_system.user",{stores:[q,r,s,t,u],queries:{getOwnProfile:io},mutations:{signupWithPassword:po,loginWithPassword:ro,logout:no,resendEmailVerification:mo,sendResetPasswordToken:Eo,resetPassword:vo,sendMagicLink:Oo,loginWithMagicLink:To,loginWithOneTimeCode:Po,updateProfile:so,unlinkOAuthProvider:ao},cronJobs:{updateDisposableEmailList:Jt},rateLimits:nt(),configSchema:{"auth.email.enabled":{type:"boolean",isPublic:true,default:true},"auth.email.from":{type:"string",isPublic:false,default:""},"auth.email.verification":{type:"boolean",isPublic:true,default:true},"auth.google.enabled":{type:"boolean",isPublic:true,default:false},"auth.google.clientId":{type:"string",isPublic:false,default:""},"auth.google.clientSecret":{type:"secret",isPublic:false,default:""},"auth.github.enabled":{type:"boolean",isPublic:true,default:false},"auth.github.clientId":{type:"string",isPublic:false,default:""},"auth.github.clientSecret":{type:"secret",isPublic:false,default:""}},routes:[{path:"/api/_internal/auth/verify-email",handlers:{get:uo}},{path:"/api/_internal/auth/reset-password",handlers:{get:bo}},{path:"/api/_internal/auth/magic-link",handlers:{get:_o}}]});var Wr={withoutRemoteServer:{MONGODB_URI:"_system.mongodbUri",MONGODB_POOL_SIZE:"_system.mongodbPoolSize",MODELENCE_AUTH_GOOGLE_ENABLED:"_system.user.auth.google.enabled",MODELENCE_AUTH_GOOGLE_CLIENT_ID:"_system.user.auth.google.clientId",MODELENCE_AUTH_GOOGLE_CLIENT_SECRET:"_system.user.auth.google.clientSecret",MODELENCE_AUTH_GITHUB_ENABLED:"_system.user.auth.github.enabled",MODELENCE_AUTH_GITHUB_CLIENT_ID:"_system.user.auth.github.clientId",MODELENCE_AUTH_GITHUB_CLIENT_SECRET:"_system.user.auth.github.clientSecret",MODELENCE_AUTH_GITHUB_CLIENT_SCOPES:"_system.user.auth.github.scopes",MODELENCE_EMAIL_RESEND_API_KEY:"_system.email.resend.apiKey",MODELENCE_EMAIL_AWS_SES_REGION:"_system.email.awsSes.region",MODELENCE_EMAIL_AWS_SES_ACCESS_KEY_ID:"_system.email.awsSes.accessKeyId",MODELENCE_EMAIL_AWS_SES_SECRET_ACCESS_KEY:"_system.email.awsSes.secretAccessKey",MODELENCE_EMAIL_SMTP_HOST:"_system.email.smtp.host",MODELENCE_EMAIL_SMTP_PORT:"_system.email.smtp.port",MODELENCE_EMAIL_SMTP_USER:"_system.email.smtp.user",MODELENCE_EMAIL_SMTP_PASS:"_system.email.smtp.pass",MODELENCE_SITE_URL:"_system.site.url",MODELENCE_ENV_TYPE:"_system.env.type",MODELENCE_MULTI_INSTANCE:"_system.multiInstance",MODELENCE_ENV:"_system.env",GOOGLE_AUTH_ENABLED:"_system.user.auth.google.enabled",GOOGLE_AUTH_CLIENT_ID:"_system.user.auth.google.clientId",GOOGLE_AUTH_CLIENT_SECRET:"_system.user.auth.google.clientSecret"},withRemoteServer:{MODELENCE_SITE_URL:"_system.site.url"}};function Jr(e,t){if(t==="number"){let o=Number(e);if(isNaN(o))throw new Error(`Invalid number value for config: ${e}`);return o}if(t==="boolean"){if(e.toLowerCase()==="true")return true;if(e.toLowerCase()==="false")return false;throw new Error(`Invalid boolean value for config: ${e}`)}return e}function Kr(e,t){let o=[];for(let[r,n]of Object.entries(e)){let i=process.env[r],s=t[n];if(i){let a=s?.type??"string";o.push({key:n,type:a,value:Jr(i,a)});}}return o}function _e(e,t="withoutRemoteServer"){let o=Wr[t];return Kr(o,e)}async function Io({configSchema:e,cronJobsMetadata:t,stores:o,roles:r}){let n=process.env.MODELENCE_CONTAINER_ID;if(!n)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_CONTAINER_ID is not set");try{let i=(o??[]).map(a=>({name:a.getName(),schema:a.getSerializedSchema(),collections:[a.getName()],version:2,indexes:a.getIndexes(),searchIndexes:a.getSearchIndexes(),indexCreationMode:a.getIndexCreationMode()})),s=await T("/api/connect","POST",{hostname:Yr.hostname(),containerId:n,dataModels:i,configSchema:e,cronJobsMetadata:t,roles:r});if(s.status==="error")throw new Error(s.error);return console.log("Successfully connected to Modelence Cloud"),s}catch(i){throw console.error("Unable to connect to Modelence Cloud:",i),i}}async function Uo(){return T("/api/configs","GET")}async function No(){return await T("/api/sync","POST",{containerId:process.env.MODELENCE_CONTAINER_ID})}async function T(e,t,o){let{MODELENCE_SERVICE_ENDPOINT:r,MODELENCE_SERVICE_TOKEN:n}=process.env;if(!r)throw new Error("Unable to connect to Modelence Cloud: MODELENCE_SERVICE_ENDPOINT is not set");let i=await fetch(`${r}${e}`,{method:t,headers:{Authorization:`Bearer ${n}`,...o?{"Content-Type":"application/json"}:{}},body:o?JSON.stringify(o):void 0});if(!i.ok){let s=await i.text(),a,c=s;try{a=JSON.parse(s);let d=a.error;if(typeof d=="string")c=d;else if(d&&typeof d=="object"){let m=d.message;typeof m=="string"&&(c=m);}}catch{}let l=new Error(`Unable to connect to Modelence Cloud: HTTP status: ${i.status}, ${c}`);throw a!==void 0&&(l.responseBody=a),l.status=i.status,l}if(!(i.status===204||i.headers?.get("content-length")==="0"))return await i.json()}var st=false,Qr=a$1.seconds(10);function Do(){setInterval(async()=>{if(!st){st=true;try{await No();}catch(e){console.error("Error syncing status",e);}try{await Xr();}catch(e){console.error("Error syncing config",e);}st=false;}},Qr);}function at(e){c$2(e),c$2(_e(d$2(),"withRemoteServer"));}async function Xr(){let{configs:e}=await Uo();at(e);}var W=new c("_modelenceLocks",{schema:{_id:d.string(),instanceId:d.string(),acquiredAt:d.date(),resource:d.string()},indexes:[{key:{resource:1},unique:true},{key:{resource:1,instanceId:1}},{key:{resource:1,acquiredAt:1}}],indexCreationMode:"blocking"});var J={},$o=a$1.seconds(10),Fo=randomBytes(32).toString("base64url"),tn=a$1.seconds(30),te=new Map,ct=e=>e instanceof MongoError&&e.code===11e3,jo=(e,t)=>typeof e.keyPattern=="object"&&e.keyPattern!==null&&Object.prototype.hasOwnProperty.call(e.keyPattern,t),on=async({error:e,resource:t})=>{if(jo(e,"resource"))return true;if(jo(e,"_id"))return false;let o=await W.findOne({resource:t});return !!o&&o._id!==t},Ho=async({resource:e,staleThresholdDate:t,instanceId:o})=>{let r=await W.upsertOne({_id:e,$or:[{instanceId:o},{acquiredAt:{$lt:t}}]},{$set:{resource:e,instanceId:o,acquiredAt:new Date},$setOnInsert:{_id:e}});return r.upsertedCount>0||r.modifiedCount>0},Vo=async({resource:e,instanceId:t,staleThresholdDate:o})=>{let r=o?{resource:e,_id:{$ne:e},$or:[{instanceId:t},{acquiredAt:{$lt:o}}]}:{resource:e,instanceId:t};return (await W.deleteOne(r)).deletedCount>0},rn=e=>{let t=e,o=te.get(t);o&&(o.stopRequested=true,o.timer&&(clearTimeout(o.timer),o.timer=null),te.delete(t));},Go=({resource:e,lockDuration:t,instanceId:o})=>{let r=Math.floor(t/3),n=e,i=te.get(n);if(i&&!i.stopRequested&&i.heartbeatInterval===r&&i.lockDuration===t)return;i&&(i.stopRequested=true,i.timer&&(clearTimeout(i.timer),i.timer=null),te.delete(n));let s={timer:null,stopRequested:false,lockDuration:t,heartbeatInterval:r},a=()=>{s.timer=setTimeout(()=>{K(e,{lockDuration:t,bypassCache:true,instanceId:o}).then(c=>{c||(s.stopRequested=true,k$1(`Lost lock while refreshing heartbeat: ${e}`,{source:"lock",resource:e,instanceId:o}));}).finally(()=>{if(s.stopRequested){te.delete(n);return}a();});},r);};te.set(n,s),a();};async function K(e,{lockDuration:t=tn,successfulLockCacheDuration:o=$o,failedLockCacheDuration:r=$o,heartbeat:n,bypassCache:i,instanceId:s=Fo}={}){let a=Date.now();if(!i&&J[e]&&a<J[e].expiresAt)return J[e].value&&n&&Go({resource:e,lockDuration:t,instanceId:s}),J[e].value;let c=new Date(a-t);k$1(`Attempting to acquire lock: ${e}`,{source:"lock",resource:e,instanceId:s});try{let l=await nn({resource:e,staleThresholdDate:c,instanceId:s});return J[e]={value:l,expiresAt:a+(l?o:r)},l?(n&&Go({resource:e,lockDuration:t,instanceId:s}),k$1(`Lock acquired: ${e}`,{source:"lock",resource:e,instanceId:s})):k$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),l}catch{return J[e]={value:false,expiresAt:a+r},k$1(`Failed to acquire lock (already held): ${e}`,{source:"lock",resource:e,instanceId:s}),false}}var nn=async({resource:e,staleThresholdDate:t,instanceId:o})=>{try{return await Ho({resource:e,staleThresholdDate:t,instanceId:o})}catch(r){if(ct(r)&&await on({error:r,resource:e})){if(!await Vo({resource:e,staleThresholdDate:t,instanceId:o}))return false;try{return await Ho({resource:e,staleThresholdDate:t,instanceId:o})}catch(i){if(ct(i))return false;throw i}}if(ct(r))return false;throw r}};async function pe(e,{instanceId:t=Fo}={}){rn(e);try{let o=await W.deleteOne({_id:e,instanceId:t});return o.deletedCount===0?await Vo({resource:e,instanceId:t}):o.deletedCount>0}catch{return false}finally{delete J[e];}}var Y={},lt=null,dt=new c("_modelenceCronJobs",{schema:{alias:d.string(),lastStartDate:d.date().optional()},indexes:[{key:{alias:1},unique:true,background:true}]});function qo(e,{description:t="",interval:o,timeout:r=Math.min(Math.max(o,a$1.minutes(1)),a$1.days(1)),handler:n}){if(Y[e])throw new Error(`Duplicate cron job declaration: '${e}' already exists`);if(lt)throw new Error(`Unable to add a cron job - cron jobs have already been initialized: [${e}]`);if(o<a$1.seconds(5))throw new Error(`Cron job interval should not be less than 5 second [${e}]`);if(r>a$1.days(1))throw new Error(`Cron job timeout should not be longer than 1 day [${e}]`);Y[e]={alias:e,params:{description:t,interval:o,timeout:r},handler:n,state:{isRunning:false}};}async function zo(){if(lt)throw new Error("Cron jobs already started");let e=Object.keys(Y);if(e.length>0){if(!N()){console.log("MongoDB URI is not configured. Skipping cron jobs.");return}let t={alias:{$in:e}},o=await dt.fetch(t),r=Date.now();o.forEach(n=>{let i=Y[n.alias];i&&(i.state.scheduledRunTs=n.lastStartDate?n.lastStartDate.getTime()+i.params.interval:r);}),Object.values(Y).forEach(n=>{n.state.scheduledRunTs||(n.state.scheduledRunTs=r);}),lt=setInterval(sn,a$1.seconds(1));}}async function sn(){let e=Date.now();await K("cron",{successfulLockCacheDuration:a$1.seconds(10),failedLockCacheDuration:a$1.seconds(30)})&&Object.values(Y).forEach(async o=>{let{params:r,state:n}=o;if(n.isRunning){n.startTs&&n.startTs+r.timeout<e&&(n.isRunning=false);return}n.scheduledRunTs&&n.scheduledRunTs<=e&&await an(o);});}async function an(e){let{alias:t,params:o,handler:r,state:n}=e;n.isRunning=true,n.startTs=Date.now(),await dt.upsertOne({alias:t},{$set:{lastStartDate:new Date(n.startTs)},$setOnInsert:{alias:t}});let i=n$1("cron",`cron:${t}`);try{await r(),Bo(n,o),i.end("success");}catch(s){Bo(n,o);let a=s instanceof Error?s:new Error(String(s));o$1(a),i.end("error"),console.error(`Error in cron job '${t}':`,s);}}function Bo(e,t){e.scheduledRunTs=e.startTs?e.startTs+t.interval:Date.now(),e.startTs=void 0,e.isRunning=false;}function Wo(){return Object.values(Y).map(({alias:e,params:t})=>({alias:e,description:t.description,interval:t.interval,timeout:t.timeout}))}var Jo=new a("_system.cron",{stores:[dt]});function Ko(e){let t=[...new Set(e)],o=new Map;for(let i of t){let s=i.getChainRoot();o.set(s,s.getChainTail());}let r=[...new Set(o.values())],n=new Map;for(let[i,s]of o){let a=s.getName(),c=n.get(a);if(c!==void 0&&c!==i)throw new Error(`Store collision: multiple unrelated stores use collection name '${a}'. Use .extend() to create a single extension chain instead of independent stores.`);n.set(a,i);}return {storesToInit:t,effectiveStores:r}}var ut=new a("_system.lock",{stores:[W]});var fe=new c("_modelenceMigrations",{schema:{version:d.number(),status:d.enum(["completed","failed"]),description:d.string().optional(),output:d.string().optional(),appliedAt:d.date()},indexes:[{key:{version:1},unique:true},{key:{version:1,status:1}}]});async function mt(e,{lockMode:t="acquire"}={}){if(e.length!==0){if(t==="acquire"&&!await K("migrations")){l$1("Another instance is running migrations. Skipping migration run.",{source:"migrations"});return}try{let o=e.map(({version:s})=>s),r=await fe.fetch({version:{$in:o}}),n=new Set(r.map(({version:s})=>s)),i=e.filter(({version:s})=>!n.has(s));if(i.length===0)return;l$1(`Running migrations (${i.length})...`,{source:"migrations"});for(let{version:s,description:a,handler:c}of i){l$1(`Running migration v${s}: ${a}`,{source:"migrations"});try{let d=(await c()||"").toString().trim(),m=15*1024*1024,f=d.length>m?d.slice(0,m)+`
25
- [Output truncated - exceeded size limit]`:d;await fe.upsertOne({version:s},{$set:{version:s,status:"completed",description:a,output:f,appliedAt:new Date}}),l$1(`Migration v${s} complete`,{source:"migrations"});}catch(l){l instanceof Error&&(await fe.upsertOne({version:s},{$set:{version:s,status:"failed",description:a,output:l.message||"",appliedAt:new Date}}),l$1(`Migration v${s} is failed: ${l.message}`,{source:"migrations"}));}}}finally{t==="acquire"&&await pe("migrations");}}}function Yo(e){setTimeout(()=>{mt(e).catch(t=>{console.error("Error running migrations:",t);});},0);}var Qo=new a("_system.migration",{stores:[fe]});var Xo=new a("_system.rateLimit",{stores:[me]});async function cn({filePath:e,contentType:t,visibility:o}){return await T("/api/files/upload","POST",{filePath:e,contentType:t,visibility:o})}async function ln(e){await T("/api/files/delete","POST",{filePath:e});}async function dn(e){return await T("/api/files/download","POST",{filePath:e})}async function un(e){return await T("/api/files/url","POST",{filePath:e})}var Zo=new a("_system.files",{});function pt(e){return e.replace(/[<>&\u2028\u2029]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}var ge="./.modelence/build/client".replace(/\\/g,"/"),tr="./.modelence/build/ssr".replace(/\\/g,"/"),or="/index.tsx",wn=/(<div\b[^>]*\bid\s*=\s*["']root["'][^>]*>)\s*<\/div>/i,yn="</head>",ft=class{constructor(){this.ssrEnabled=false;this.ssrTransportInstalled=false;this.prodEntryLoaded=false;}enableSsr(){this.ssrEnabled=true;}async init({httpServer:t}){if(this.config=await An(this.isDev()?t:void 0,{ssr:this.ssrEnabled}),this.isDev())console.log("Starting Vite dev server..."),this.viteServer=await createServer(this.config);else if(this.ssrEnabled){let o=Q.resolve(process.cwd(),tr,"index.mjs");if(!Le.existsSync(o))throw new Error(`Modelence: SSR is enabled (startApp({ ssr: true })) but the SSR bundle is missing at ${o}.
26
-
27
- This usually means \`postBuildCommand\` is set in modelence.config.ts, which replaces the default Vite client build (and the SSR build along with it). Either:
28
- \u2022 remove \`postBuildCommand\` so Modelence builds the SSR bundle, or
29
- \u2022 remove \`ssr: true\` from startApp() if your custom toolchain handles SSR itself.`)}if(this.ssrEnabled&&!this.ssrTransportInstalled){let{installSsrCallMethodTransport:o}=await import('./transport-OSL4EWWD.js');o(),this.ssrTransportInstalled=true;}}middlewares(){if(this.isDev())return this.viteServer?.middlewares??[];let t=this.ssrEnabled?{index:false}:void 0,o=[B$1.static(ge,t)];return this.config?.publicDir&&o.push(B$1.static(this.config.publicDir,t)),o}async handler(t,o){if(this.ssrEnabled&&En(t)){if(t.method==="HEAD"){o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200).end();return}try{await this.handleSsr(t,o);}catch(r){if(this.isDev()&&this.viteServer&&r instanceof Error&&this.viteServer.ssrFixStacktrace(r),console.error("SSR render error:",{url:t.originalUrl,method:t.method,userAgent:t.get("user-agent"),error:r}),o.headersSent){o.end();return}this.serveStaticShell(o);}return}if(this.ssrEnabled){o.status(404).end();return}this.serveStaticShell(o);}async handleSsr(t,o){let r=await this.getTemplate(t.originalUrl),n=await this.captureSsrSnapshot();if(!n)throw new Error("Modelence SSR is enabled but no SSR snapshot was captured. Make sure 'src/client/index.tsx' calls renderApp(...) from 'modelence/client'.");let[{renderSsrTreeStream:i},{getCallContext:s},a]=await Promise.all([import('./render-V4SWSKPW.js'),import('./server-D7FBXWTW.js'),import('./collectCss-4YETFI7P.js')]),c=await s(t,o),l=this.collectCssAssets(a);kn(o,a.buildEarlyHintsLink(l));let{sessionState:d,pipe:m,getQueryState:f}=await i({callContext:c,loadingElement:n.loadingElement,routesElement:n.routesElement,router:n.router,location:t.originalUrl}),{prelude:h,rootOpenTag:y,epilogue:k}=bn(r),P=vn(h,a.renderStylesheetLinks(l));o.setHeader("Content-Type","text/html; charset=utf-8"),o.setHeader("Cache-Control","no-store"),o.status(200),o.write(P),o.write(`<script id="__MODELENCE_STATE__" type="application/json">${pt(d)}</script>`),o.write(y),await m(o),o.write("</div>"),o.write(`<script id="__MODELENCE_QUERY_STATE__" type="application/json">${pt(f())}</script>`),o.end(k);}collectCssAssets(t){return this.isDev()?this.viteServer?t.collectDevCssAssets(this.viteServer,or):{hrefs:[],source:"dev"}:(this.prodCssAssetsCache||(this.prodCssAssetsCache=t.loadProdCssAssets(ge)),this.prodCssAssetsCache)}async getTemplate(t){if(this.isDev()){let o=Q.resolve(process.cwd(),"src/client/index.html"),r=Le.readFileSync(o,"utf-8");return this.viteServer&&(r=await this.viteServer.transformIndexHtml(t,r)),r}if(!this.prodTemplateCache){let o=Q.resolve(process.cwd(),ge,"index.html");this.prodTemplateCache=Le.readFileSync(o,"utf-8");}return this.prodTemplateCache}async captureSsrSnapshot(){let{_getSsrSnapshot:t}=await import('./renderApp-YNRUDPRK.js');if(this.isDev()){if(!this.viteServer)throw new Error("Vite dev server not initialized");return await this.viteServer.ssrLoadModule(or),t()}return this.prodEntryLoaded||(await import(Q.resolve(process.cwd(),tr,"index.mjs")),this.prodEntryLoaded=true),t()}serveStaticShell(t){if(this.isDev())try{t.setHeader("Cache-Control","no-store"),t.sendFile("index.html",{root:"./src/client"});}catch(o){console.error("Error serving index.html:",o),t.status(500).send("Internal Server Error");}else t.sendFile("index.html",{root:ge});}isDev(){return process.env.NODE_ENV!=="production"}};function En(e){if(e.method!=="GET"&&e.method!=="HEAD")return false;let t=e.get("accept")??"";if(t&&!t.includes("text/html")&&!t.includes("*/*"))return false;let o=(e.path??e.url??"").split("?")[0];if(o.startsWith("/api/"))return false;let r=o.split("/").pop()??"",n=r.lastIndexOf(".");if(n>0){let i=r.slice(n).toLowerCase();if(i!==".html"&&i!==".htm")return false}return true}function bn(e){let t=e.match(wn);if(!t||t.index===void 0)throw new Error('SSR template is missing the expected `<div id="root"></div>` placeholder.');let o=e.slice(0,t.index),r=e.slice(t.index+t[0].length);return {prelude:o,rootOpenTag:t[1],epilogue:r}}function vn(e,t){if(!t)return e;let o=e.lastIndexOf(yn);return o===-1?t+e:e.slice(0,o)+t+e.slice(o)}function kn(e,t){if(t.length===0)return;let o=e;if(typeof o.writeEarlyHints=="function")try{o.writeEarlyHints({link:t});}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Modelence SSR: writeEarlyHints failed",r);}}async function Cn(){let e=process.cwd();try{return (await loadConfigFromFile({command:"serve",mode:"development"},void 0,e))?.config||{}}catch(t){return console.warn("Could not load vite config:",t),{}}}function Sn(e,t){let o=mergeConfig(e,t);if(o.plugins&&Array.isArray(o.plugins)){let r=new Set;o.plugins=o.plugins.flat().filter(n=>{if(!n||typeof n!="object"||Array.isArray(n))return true;let i=n.name;return !i||r.has(i)?false:(r.add(i),true)}).reverse(),o.plugins.reverse();}return o}async function An(e,t={}){let o=process.cwd(),r=await Cn(),n=[".eslintrc.js",".eslintrc.json",".eslintrc","eslint.config.js",".eslintrc.yml",".eslintrc.yaml"].find(a=>Le.existsSync(Q.join(o,a))),i=[hn(),Rn()];if(n){let a=(await import('vite-plugin-eslint')).default;i.push(a({failOnError:false,include:["src/**/*.js","src/**/*.jsx","src/**/*.ts","src/**/*.tsx"],cwd:o,overrideConfigFile:Q.resolve(o,n)}));}let s=defineConfig({plugins:i,build:{outDir:ge,emptyOutDir:true},server:{middlewareMode:true,hmr:e?{server:e}:void 0},appType:t.ssr?"custom":"spa",root:"./src/client",resolve:{alias:{"@":Q.resolve(o,"src").replace(/\\/g,"/")}}});return Sn(s,r)}function Rn(){return {name:"modelence-asset-handler",async transform(e,t){if(/\.(png|jpe?g|gif|svg|mpwebm|ogg|mp3|wav|flac|aac)$/.test(t))return process.env.NODE_ENV==="development",e}}}var Te=new ft;function xn(e){return e?e.match(/^\s*"?([^"<]+?)"?\s*<[^>]+>\s*$/)?.[1]?.trim():void 0}function On(e){if(e)return Array.isArray(e)?e:[e]}function _n(e){return {to:Array.isArray(e.to)?e.to:[e.to],subject:e.subject,html:e.html,text:e.text,fromName:xn(e.from),replyTo:On(e.replyTo)}}function Ln(e){if(!(e instanceof Error))return new Error("Managed email send failed");let t=e.responseBody,o=t?.error?.code,r=t?.error?.message;return o&&r?new Error(`Managed email rejected (${o}): ${r}`):e}var rr={async sendEmail(e){if(e.cc||e.bcc||e.attachments||e.headers)throw new Error("Modelence managed email does not support cc, bcc, attachments, or custom headers in v1. Configure your own provider (Resend, SES, SMTP) to use these features. See https://docs.modelence.com/email/managed.");try{await T("/api/email/send","POST",_n(e));}catch(t){throw Ln(t)}}};var gt=Object.freeze({});function nr(e){gt=Object.freeze(Object.assign({},gt,e));}function ir(){return gt}var ht=Object.freeze({});function sr(e){ht=Object.freeze(Object.assign({},ht,e));}function Pe(){return ht}async function In({modules:e=[],roles:t={},defaultRoles:o={},server:r=Te,migrations:n=[],email:i$1={},auth:s={},security:a={},websocket:c={},ssr:l=false}){l&&r===Te&&Te.enableSsr(),ar.config(),ar.config({path:".modelence.env"});let d=!!process.env.MODELENCE_SERVICE_ENDPOINT;qn().then(()=>{}).catch(()=>{});for(let D of e)if(D.name.toLowerCase().startsWith("_system."))throw new Error(`Invalid module name: '${D.name}'
30
-
31
- The '_system.' prefix is reserved for internal use and cannot be used in user-defined modules.
32
-
33
- Rename your module to something that does not start with '_system.'`);let m=[it,p,Jo,Qo,Xo,le,ut,Zo],f$1=[...m,...e];f(),Nn(m),Un(e),v$1(t,o);let h=Fn(f$1);e$1(h);let y=Dn(f$1),k=$n(f$1);Vn(f$1),it.rateLimits=nt(s.rateLimits);let P=jn(f$1);co(P);let{storesToInit:M,effectiveStores:S}=Ko(y);if(d){let{configs:D,environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr}=await Io({configSchema:h,cronJobsMetadata:Wo(),stores:S,roles:t});at(D),g({environmentId:fr,appAlias:gr,environmentAlias:hr,telemetry:wr});}else c$2(_e(h));if(d&&!i$1.provider?Be({...i$1,provider:rr}):Be(i$1),to(s),nr(a),sr({...c,provider:c.provider||Wt}),N()){await qt();let D=[...new Set([...M,...S])];Bn(D),await Gn(S,n);}else Yo(n);d&&(await i(),Do()),zo().catch(console.error),await cr(r,{combinedModules:f$1,channels:k});}function Un(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))A(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))B(`${t.name}.${o}`,r);}}function Nn(e){for(let t of e){for(let[o,r]of Object.entries(t.queries))C$1(`${t.name}.${o}`,r);for(let[o,r]of Object.entries(t.mutations))D(`${t.name}.${o}`,r);}}function Dn(e){return e.flatMap(t=>t.stores)}function $n(e){return e.flatMap(t=>t.channels)}function jn(e){return e.flatMap(t=>t.rateLimits)}function Hn(e,t){console.warn(`Failed to create indexes for store '${e}'. Continuing startup.`,t);}var wt="migrations";async function Gn(e,t){if(!await K(wt,{lockDuration:a$1.seconds(30),heartbeat:true}))return;let r,n;try{r=e.filter(a=>a.getIndexCreationMode()==="blocking"),n=e.filter(a=>a.getIndexCreationMode()==="background");for(let a of r)await yt(a,"full");for(let a of n)await yt(a,"drop-only");}catch(a){throw await pe(wt),a}let i=(async()=>{for(let a of n)await yt(a,"create-only");})(),s=mt(t,{lockMode:"skip"});Promise.allSettled([i,s]).then(([a,c])=>{a.status==="rejected"&&console.error("Error creating background indexes:",a.reason),c.status==="rejected"&&console.error("Error running migrations:",c.reason);}).finally(async()=>{await pe(wt);});}async function yt(e,t="full"){let o=e.getName();try{await e.createIndexes(t);}catch(r){Hn(o,r);}}function Fn(e){let t={};for(let o of e)for(let[r,n]of Object.entries(o.configSchema)){let i=`${o.name}.${r}`;if(i in t)throw new Error(`Duplicate config schema key: ${i} (${o.name})`);t[i]=n;}return t}function Vn(e){for(let t of e)for(let[o,r]of Object.entries(t.cronJobs))qo(`${t.name}.${o}`,r);}function Bn(e){let t=ve();if(!t)throw new Error("Failed to initialize stores: MongoDB client not initialized");for(let o of e)o.init(t);}async function qn(){if(process.env.MODELENCE_TRACKING_ENABLED!=="false"){let t=process.env.MODELENCE_SERVICE_ENDPOINT??"https://cloud.modelence.com",o=process.env.MODELENCE_ENVIRONMENT_ID,r=await zn(),n=await import('./package-A4RGADVP.js');await fetch(`${t}/api/track/app-start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({projectName:r.name,version:n.default.version,localHostname:Yr.hostname(),environmentId:o})});}}async function zn(){try{let e=Q.join(process.cwd(),"package.json"),t=await Tn.readFile(e,"utf-8");return {name:JSON.parse(t).name||"unknown"}}catch{return {name:"unknown"}}}async function lr(e){await s.deleteMany({userId:e}),await t.deleteMany({userId:e});let t$1=await q.findOne({_id:e}),o=Array.from(new Set((t$1?.emails??[]).map(r=>r.address?.toLowerCase()).filter(r=>!!r)));o.length>0&&await u.deleteMany({email:{$in:o}});}async function Jn(e){await lr(e),await q.updateOne(e,{$set:{status:"disabled",disabledAt:new Date}});}async function Kn(e){await lr(e),await q.updateOne({_id:e},{$set:{handle:`deleted-${e}-${randomUUID()}`,status:"deleted",deletedAt:new Date,authMethods:{},emails:[]}});}var Et=class{constructor(t,o){this.category=t,this.canAccessChannel=o||null;}broadcast(t,o){let r=Pe().provider;if(!r){m$1("Websockets provider should be added to startApp",{});return}r.broadcast({category:this.category,id:t,data:o});}};function Yn(e){if(!w().provider)throw new Error("Email provider is not configured, see https://docs.modelence.com/email for more details.");return w().provider?.sendEmail(e)}async function Me(e){return !e||typeof e!="string"?null:g$1(e)}function v(e,t,o){let r=b(),n=e.status(t);if(r.errorComponent)try{let i=r.errorComponent({error:o,statusCode:t});if(i)return n.send(i)}catch(i){console.error("Unhandled error in authConfig.errorComponent:",i);}return n.json({error:o})}async function bt(e,t){let{authToken:o}=await m(t);n(e,o),e.status(302),e.redirect("/");}async function Xn(e,t,o,r,n){let i=b();try{if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}let s={};o.firstName===void 0&&t.firstName&&(s.firstName=t.firstName),o.lastName===void 0&&t.lastName&&(s.lastName=t.lastName),o.avatarUrl===void 0&&t.avatarUrl&&(s.avatarUrl=t.avatarUrl);let a=o;Object.keys(s).length>0&&(await q.updateOne({_id:o._id},{$set:s}),a={...o,...s}),await bt(e,o._id),i.onAfterLogin?.({provider:t.providerName,user:a,session:r,connectionInfo:n}),i.login?.onSuccess?.(a);}catch(s){throw s instanceof Error&&(i.login?.onError?.(s),i.onLoginError?.({provider:t.providerName,error:s,session:r,connectionInfo:n})),s}}async function Zn(e,t,o,r,n){let i=b();if((i.oauthAccountLinking??"manual")==="auto"&&t.emailVerified){if(o.status==="disabled"||o.status==="deleted"){v(e,400,"User account is not active.");return}if(!o.emails?.find(c=>c.address.toLowerCase()===t.email.toLowerCase())?.verified){v(e,400,"User with this email already exists. Please log in instead.");return}try{let c={...o.firstName===void 0&&t.firstName&&{firstName:t.firstName},...o.lastName===void 0&&t.lastName&&{lastName:t.lastName},...o.avatarUrl===void 0&&t.avatarUrl&&{avatarUrl:t.avatarUrl}};if(!((await q.updateOne({_id:o._id,status:{$nin:["deleted","disabled"]},$or:[{[`authMethods.${t.providerName}.id`]:{$exists:!1}},{[`authMethods.${t.providerName}.id`]:t.id}]},{$set:{[`authMethods.${t.providerName}.id`]:t.id,...c}})).matchedCount>0)){v(e,400,"User with this email already exists. Please log in instead.");return}await bt(e,o._id);let m={...o,...c,authMethods:{...o.authMethods,[t.providerName]:{id:t.id}}};i.onAfterLogin?.({provider:t.providerName,user:m,session:r,connectionInfo:n}),i.login?.onSuccess?.(m);return}catch(c){throw c instanceof Error&&(i.login?.onError?.(c),i.onLoginError?.({provider:t.providerName,error:c,session:r,connectionInfo:n})),c}}v(e,400,"User with this email already exists. Please log in instead.");}async function ei(e,t,o,r){let n=b();try{let i;if(n.generateHandle){let l=await n.generateHandle({email:t.email,firstName:t.firstName,lastName:t.lastName});i=await L(l,t.email,{throwOnConflict:!1});}else i=await L(void 0,t.email);let s={handle:i,status:"active",emails:[{address:t.email,verified:t.emailVerified}],createdAt:new Date,authMethods:{[t.providerName]:{id:t.id}},...t.firstName!==void 0&&{firstName:t.firstName},...t.lastName!==void 0&&{lastName:t.lastName},...t.avatarUrl!==void 0&&{avatarUrl:t.avatarUrl}},a=await q.insertOne(s);await bt(e,a.insertedId);let c=await q.findOne({_id:a.insertedId},{readPreference:"primary"});c&&(n.onAfterSignup?.({provider:t.providerName,user:c,session:o,connectionInfo:r}),n.signup?.onSuccess?.(c));}catch(i){throw i instanceof Error&&(n.onSignupError?.({provider:t.providerName,error:i,session:o,connectionInfo:r}),n.signup?.onError?.(i)),i}}function re(e){return `${a$2("_system.site.url")}/api/_internal/auth/${e}/callback`}async function Ie(e,t,o){let r=await q.findOne({[`authMethods.${o.providerName}.id`]:o.id}),{session:n,connectionInfo:i}=await ne(e,t);if(r)return Xn(t,o,r,n,i);if(!o.email){v(t,400,`Email address is required for ${o.providerName} authentication.`);return}let s;try{s=await q.findOne({"emails.address":o.email,status:{$ne:"deleted"}},{collation:{locale:"en",strength:2}});}catch(a){if(a instanceof Error){let c=b();c.onSignupError?.({provider:o.providerName,error:a,session:n,connectionInfo:i}),c.signup?.onError?.(a);}throw a}return s?Zn(t,o,s,n,i):ei(t,o,n,i)}function x(e){e.cookie("oauthLinkToken","",{httpOnly:true,maxAge:0,path:"/api/_internal/auth/",sameSite:"lax",secure:process.env.NODE_ENV==="production"});}function oe(e){if(e)try{e();}catch(t){console.error("Error executing OAuth hook:",t);}}function Ue(e,t,o){let r=e.query.state,n=e.cookies[o],[i,s,a]=(n||"").split(":");return !r||!n||r!==i?(v(t,400,"Invalid OAuth state - possible CSRF attack"),null):(t.clearCookie(o),{mode:s||"login",...a?{linkedUserId:a}:{}})}async function Ne(e,t,o,r){let n=b(),{session:i,connectionInfo:s}=await ne(e,t),a=null;if(r){if(!ObjectId.isValid(r)){x(t),v(t,400,"Invalid OAuth linking state.");return}a=new ObjectId(r);}else a=i?.userId??null;if(!a){x(t),v(t,401,"You must be signed in to link a provider.");return}let c=a;try{let l=`authMethods.${o.providerName}.id`;if((await q.updateOne({_id:c,status:{$nin:["deleted","disabled"]},$or:[{[l]:{$exists:!1}},{[l]:o.id}]},{$set:{[l]:o.id}})).matchedCount===0){let f=await q.findOne({_id:c});if(!f||f.status==="deleted"||f.status==="disabled"){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error("User account not found or not active"),session:i,connectionInfo:s})),x(t),v(t,400,"User account is not active.");return}let h=f?.authMethods?.[o.providerName]?.id;if(h&&h!==o.id){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`User already has a different ${o.providerName} account linked`),session:i,connectionInfo:s})),x(t),v(t,400,`You have already linked a different ${o.providerName} account.`);return}oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:new Error(`Unexpected OAuth linking state for ${o.providerName}`),session:i,connectionInfo:s})),x(t),v(t,400,`Unable to link ${o.providerName} account.`);return}let m=await q.findOne({_id:c},{readPreference:"primary"});m&&oe(()=>n.onAfterOAuthLink?.({provider:o.providerName,user:m,session:i,connectionInfo:s})),x(t),t.status(302).redirect("/");}catch(l){if(l instanceof MongoServerError&&l.code===11e3){oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),v(t,400,`This ${o.providerName} account is already linked to a different user.`);return}if(l instanceof Error&&oe(()=>n.onOAuthLinkError?.({provider:o.providerName,error:l,session:i,connectionInfo:s})),x(t),!t.headersSent)throw l}}function De(e){return !e||typeof e!="string"?null:e}async function ri(e,t,o,r){let n=await fetch("https://oauth2.googleapis.com/token",{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({code:e,client_id:t,client_secret:o,redirect_uri:r,grant_type:"authorization_code"})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function ni(e){let t=await fetch("https://www.googleapis.com/oauth2/v2/userinfo",{headers:{Authorization:`Bearer ${e}`}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ii(e,t){let o=De(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ue(e,t,"authStateGoogle");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret")),c=re("google");try{let l=await ri(o,s,a,c),d=await ni(l.access_token),m={id:d.id,email:d.email,emailVerified:d.verified_email,providerName:"google",firstName:d.given_name||void 0,lastName:d.family_name||void 0,avatarUrl:d.picture||void 0};n==="link"?await Ne(e,t,m,i):await Ie(e,t,m);}catch(l){console.error("Google OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function si(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.google.enabled"),s=String(a$2("_system.user.auth.google.clientId")),a=String(a$2("_system.user.auth.google.clientSecret"));if(!i||!s||!a){v(r,503,"Google authentication is not configured");return}n();};return e.get("/api/_internal/auth/google",t,async(o,r)=>{let n=String(a$2("_system.user.auth.google.clientId")),i=re("google"),s=randomBytes(32).toString("hex"),a=o.query.mode==="link"?"link":"login",c=null;if(a==="link"&&o.query.linkNonce&&(c=await Me(o.query.linkNonce),!c)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let l=c?`${s}:${a}:${c}`:`${s}:${a}`;r.cookie("authStateGoogle",l,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let d=new URL("https://accounts.google.com/o/oauth2/v2/auth");d.searchParams.append("client_id",n),d.searchParams.append("redirect_uri",i),d.searchParams.append("response_type","code"),d.searchParams.append("scope","profile email"),d.searchParams.append("access_type","online"),d.searchParams.append("state",s),r.redirect(d.toString());}),e.get("/api/_internal/auth/google/callback",t,ii),e}var ur=si;async function li(e,t,o,r){let n=await fetch("https://github.com/login/oauth/access_token",{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({client_id:t,client_secret:o,code:e,redirect_uri:r})});if(!n.ok)throw new Error(`Failed to exchange code for token: ${n.statusText}`);return n.json()}async function di(e){let t=await fetch("https://api.github.com/user",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user info: ${t.statusText}`);return t.json()}async function ui(e){let t=await fetch("https://api.github.com/user/emails",{headers:{Authorization:`Bearer ${e}`,Accept:"application/vnd.github.v3+json"}});if(!t.ok)throw new Error(`Failed to fetch user emails: ${t.statusText}`);return t.json()}async function mi(e,t){return e.email?e.email:(await ui(t)).find(r=>r.primary&&r.verified)?.email??null}async function pi(e,t){let o=De(e.query.code);if(!o){v(t,400,"Missing authorization code");return}let r=Ue(e,t,"authStateGithub");if(!r)return;let{mode:n,linkedUserId:i}=r,s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret")),c=re("github");try{let l=await li(o,s,a,c),d=await di(l.access_token),m=await mi(d,l.access_token);if(!m){n==="link"&&x(t),v(t,400,"Unable to retrieve a primary verified email from GitHub. Please ensure your GitHub account has a verified email set as primary.");return}let f=d.name?d.name.trim().split(/\s+/):[],h=f[0]||void 0,y=f.length>1?f.slice(1).join(" "):void 0,k={id:String(d.id),email:m,emailVerified:!0,providerName:"github",firstName:h,lastName:y,avatarUrl:d.avatar_url||void 0};n==="link"?await Ne(e,t,k,i):await Ie(e,t,k);}catch(l){console.error("GitHub OAuth error:",l),n==="link"&&x(t),v(t,500,"Authentication failed");}}function fi(){let e=Router(),t=(o,r,n)=>{let i=!!a$2("_system.user.auth.github.enabled"),s=String(a$2("_system.user.auth.github.clientId")),a=String(a$2("_system.user.auth.github.clientSecret"));if(!i||!s||!a){v(r,503,"GitHub authentication is not configured");return}n();};return e.get("/api/_internal/auth/github",t,async(o,r)=>{let n=String(a$2("_system.user.auth.github.clientId")),i=re("github"),s=a$2("_system.user.auth.github.scopes"),a=s?String(s).split(",").map(h=>h.trim()).join(" "):"user:email",c=randomBytes(32).toString("hex"),l=o.query.mode==="link"?"link":"login",d=null;if(l==="link"&&o.query.linkNonce&&(d=await Me(o.query.linkNonce),!d)){v(r,401,"Invalid or expired link nonce for OAuth linking.");return}let m=d?`${c}:${l}:${d}`:`${c}:${l}`;r.cookie("authStateGithub",m,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",maxAge:a$1.minutes(10)});let f=new URL("https://github.com/login/oauth/authorize");f.searchParams.append("client_id",n),f.searchParams.append("redirect_uri",i),f.searchParams.append("scope",a),f.searchParams.append("state",c),r.redirect(f.toString());}),e.get("/api/_internal/auth/github/callback",t,pi),e}var mr=fi;function pr(e,t,o){return async(r,n,i)=>{let s=r.headers["x-modelence-auth-token"],a={session:null,user:null};if(typeof s=="string"&&N())try{let{session:l,user:d}=await x$1(s);a={session:l,user:d};}catch{}let c=n$1("route",`route:${e.toLowerCase()}:${t}`,{method:e,path:t,query:j$1(r.query),body:j$1(r.body),params:j$1(r.params)});try{let l=await o({query:r.query,body:r.body,params:r.params,headers:r.headers,cookies:r.cookies,rawBody:Buffer.isBuffer(r.body)?r.body:void 0,req:r,res:n,next:i},a);c.end(),l&&(n.status(l.status||200),l.contentType&&n.setHeader("Content-Type",l.contentType),l.headers&&Object.entries(l.headers).forEach(([d,m])=>{n.setHeader(d,m);}),l.redirect?n.redirect(l.redirect):n.send(l.data));}catch(l){c.end("error"),l instanceof a$4?n.status(l.status).send(l.message):(console.error(`Error in route handler: ${r.path}`),console.error(l),n.status(500).send(String(l)));}}}function wi(e){let t=[];if(!e)return t.push(B$1.json({limit:"16mb"})),t.push(B$1.urlencoded({extended:true,limit:"16mb"})),t;if(e.json!==false){let o=typeof e.json=="object"?e.json:{limit:"16mb"};t.push(B$1.json(o));}if(e.urlencoded!==false){let o=typeof e.urlencoded=="object"?e.urlencoded:{extended:true,limit:"16mb"};t.push(B$1.urlencoded(o));}if(e.raw){let o=typeof e.raw=="object"?e.raw:{},r={limit:o.limit||"16mb",type:o.type||"*/*"};t.push(B$1.raw(r));}return t}function yi(e,t){for(let o of t)for(let r of o.routes){let{path:n,handlers:i,body:s}=r,a=wi(s);Object.entries(i).forEach(([c,l])=>{e[c](n,...a,pr(c,n,l));});}}async function cr(e,{combinedModules:t,channels:o}){let r=B$1();r.use(gi()),r.use(vi()),yi(r,t),r.use(B$1.json({limit:"16mb"})),r.use(B$1.urlencoded({extended:true,limit:"16mb"})),r.use(ur()),r.use(mr()),r.post("/api/_internal/auth/set-link-cookie",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}c.cookie("oauthLinkToken",l.authToken,{httpOnly:true,secure:process.env.NODE_ENV==="production",sameSite:"lax",path:"/api/_internal/auth/",maxAge:10*60*1e3}),c.json({ok:true});}),r.post("/api/_internal/auth/issue-link-nonce",async(a,c)=>{let{session:l}=await ne(a,c);if(!l?.userId){c.status(401).json({error:"Not authenticated"});return}let d=await f$1(String(l.userId));c.json({nonce:d});}),r.post("/api/_internal/method/:methodName(*)",async(a,c)=>{let l=a.params.methodName,d=await ne(a,c);try{let m=a$3(await E(l,a.body.args,d));c.json({data:m,typeMap:b$3(m)});}catch(m){Ei(c,l,m);}});let n=hi.createServer(r);await e.init({httpServer:n}),e.middlewares&&r.use(e.middlewares()),r.all("*",(a,c,l)=>{Promise.resolve(e.handler(a,c)).catch(l);}),process.on("unhandledRejection",(a,c)=>{console.error("Unhandled Promise Rejection:"),console.error(a instanceof Error?a.stack:a),console.error("Promise:",c);}),process.on("uncaughtException",a=>{console.error("Uncaught Exception:"),console.error(a.stack),console.trace("Full application stack:");});let i=Pe()?.provider;i&&i.init({httpServer:n,channels:o});let s=process.env.MODELENCE_PORT||process.env.PORT||3e3;n.listen(s,()=>{l$1("Application started",{source:"app"});let a=a$2("_system.site.url")||`http://localhost:${s}`;console.log(`
34
- Application started on ${a}
35
- `),b$1()&&console.log("This project is not connected to a backend yet, so the app serves setup instructions instead of its UI.\nTo connect it to Modelence Cloud, run `npx modelence setup` and restart the dev server.\n");});}async function ne(e,t=null){let o=(e.path??e.url??"").split("?")[0],r=o.startsWith("/api/_internal/auth/")&&o.endsWith("/callback"),n=e.body??{},i=V.string().nullish().transform(l=>l??null).parse(e.cookies.authToken||(r?e.cookies.oauthLinkToken:null)||n.authToken),s=V.object({screenWidth:V.number(),screenHeight:V.number(),windowWidth:V.number(),windowHeight:V.number(),pixelRatio:V.number(),orientation:V.string().nullable()}).nullish().parse(n.clientInfo)??{screenWidth:0,screenHeight:0,windowWidth:0,windowHeight:0,pixelRatio:1,orientation:null},a={ip:Ci(e),userAgent:e.get("user-agent"),acceptLanguage:e.get("accept-language"),referrer:e.get("referrer"),baseUrl:ki(e)};if(!!N()){let{session:l,user:d,roles:m}=await x$1(i);return {clientInfo:s,connectionInfo:a,session:l,user:d,roles:m,req:e,res:t}}return {clientInfo:s,connectionInfo:a,session:null,user:null,roles:w$1(),req:e,res:t}}function Ei(e,t,o){if(o instanceof a$4){o.status>=500&&o.status<600&&console.error(`Error calling ${t}:`,o),o.code&&e.setHeader("X-Modelence-Error-Code",o.code),e.status(o.status).send(o.message);return}if(o instanceof Error&&o?.constructor?.name==="ZodError"&&"errors"in o){let r="";try{r=bi(o);}catch(n){console.error(`Error parsing Zod error in ${t}:`,n),r="Validation failed";}e.status(400).send(r);return}console.error(`Error calling ${t}:`,o),e.status(500).send(o instanceof Error?o.message:String(o));}function bi(e){let t=e.flatten(),o=Object.entries(t.fieldErrors).map(([i,s])=>`${i}: ${(s??[]).join(", ")}`),r=t.formErrors;return [...o,...r].filter(Boolean).join("; ")}function vi(){let{frameAncestors:e}=ir(),t=e&&e.length>0,o=t?["'self'",...e].join(" "):"'self'";return (r,n,i)=>{n.setHeader("Content-Security-Policy",`frame-ancestors ${o}`),t||n.setHeader("X-Frame-Options","SAMEORIGIN"),i();}}function ki(e){let t=e.headers["x-forwarded-host"],o=(Array.isArray(t)?t[0]:t?.split(",")[0])?.trim()||e.get("host"),r=e.headers["x-forwarded-proto"];return `${(Array.isArray(r)?r[0]:r?.split(",")[0])?.trim()||e.protocol}://${o}`}function Ci(e){let t=e.headers["x-forwarded-for"];if(t)return (Array.isArray(t)?t[0]:t.split(",")[0]).trim();let o=e.ip||e.socket?.remoteAddress;if(o)return o.startsWith("::ffff:")?o.substring(7):o}
36
- export{C as a,cn as b,ln as c,dn as d,un as e,cr as f,ne as g,In as h,Jn as i,Kn as j,Et as k,Yn as l};//# sourceMappingURL=chunk-7XZDALJZ.js.map
37
- //# sourceMappingURL=chunk-7XZDALJZ.js.map