modelence 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-DIWBKGBL.js +3 -0
- package/dist/chunk-DIWBKGBL.js.map +1 -0
- package/dist/{chunk-BTLFMWYE.js → chunk-S7LR4K37.js} +3 -3
- package/dist/{chunk-BTLFMWYE.js.map → chunk-S7LR4K37.js.map} +1 -1
- package/dist/client.d.ts +65 -2
- package/dist/client.js +1 -1
- package/dist/client.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/{package-KT24PVKP.js → package-D325NQFE.js} +2 -2
- package/dist/{package-KT24PVKP.js.map → package-D325NQFE.js.map} +1 -1
- package/dist/server.d.ts +48 -6
- package/dist/server.js +8 -8
- package/dist/server.js.map +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/{types-BkwhamTw.d.ts → types-BtENzxGq.d.ts} +1 -1
- package/dist/{types-D4VeJMYX.d.ts → types-CSQ5Qjb4.d.ts} +69 -1
- package/dist/types-DLDzAym7.d.ts +8 -0
- package/dist/types.d.ts +2 -2
- package/package.json +1 -1
- package/dist/chunk-PB6WQQ4L.js +0 -3
- package/dist/chunk-PB6WQQ4L.js.map +0 -1
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import N from'elastic-apm-node';import A from'winston';import {ElasticsearchTransport}from'winston-elasticsearch';import c from'process';var g={},L={},x=false;function p(t){return L[t]?.value??g[t]?.default}function G(){if(!x)throw new Error("Config is not initialized: an attempt was made to access configs before they were loaded");return Object.fromEntries(Object.entries(g).filter(([t,e])=>e.isPublic).map(([t,e])=>[t,{key:t,type:e.type,value:L[t]?.value??e.default}]))}function V(t){t.forEach(({key:e,type:o,value:r})=>{!e.toLowerCase().startsWith("_system.")&&!g[e]||(L[e]={key:e,type:o,value:r});}),x=true;}function $(){return g}function F(t){Object.entries(t).forEach(([e,o])=>{let{type:r,isPublic:n}=o;if(r==="secret"&&n)throw new Error(`Config ${e} with type "secret" cannot be public`)}),g=t;}var i={stdout:[{log:"",timestamp:null}],stderr:[{log:"",timestamp:null}]},z=1;function S({elasticCloudId:t,elasticApiKey:e}){let o=c.stdout.write,r=c.stderr.write;c.stdout.write=function(n,...s){return h(n.toString(),i.stdout),o.call(c.stdout,n,...s)},c.stderr.write=function(n,...s){return h(n.toString(),i.stderr),r.call(c.stderr,n,...s)},I();}function h(t,e){if(t.length===0)return;let o=new Date;for(let r=0;r<t.length;r++){let n=e[e.length-1];n.timestamp||(n.timestamp=o,n.sequenceId=z++),t[r]===`
|
|
2
|
+
`?e.push({log:"",timestamp:null}):n.log+=t[r];}}async function O(){let t=i.stdout.slice(0,-1);i.stdout=[i.stdout[i.stdout.length-1]];let e=i.stderr.slice(0,-1);i.stderr=[i.stderr[i.stderr.length-1]],t.forEach(({log:o,timestamp:r,sequenceId:n})=>{v(o,{timestamp:r,source:"console",sequenceId:n});}),e.forEach(({log:o,timestamp:r,sequenceId:n})=>{b(o,{timestamp:r,source:"console",sequenceId:n});});}function I(){setTimeout(()=>{O(),I();},1e3);}var l=null;function Y(){}function Z(t){l=Object.assign({},l,t);}function T(){return l?.environmentId}function K(){return l?.appAlias}function M(){return l?.environmentAlias}function j(){return l?.telemetry?.serviceName}function a(){return !!l?.telemetry?.isEnabled}var R=false,d=null,m=null,st=async()=>{if(R)throw new Error('Metrics are already initialized, duplicate "initMetrics" call received');R=true,a()&&await D();};async function D(){let t=p("_system.elastic.apmEndpoint"),e=p("_system.elastic.cloudId"),o=p("_system.elastic.apiKey"),r=K()??"unknown",n=M()??"unknown",s=T()??"unknown",f=j();d=N.start({serviceName:f,apiKey:o,serverUrl:t,transactionSampleRate:1,centralConfig:false,globalLabels:{modelenceEnv:"dev",appEnv:"dev",environmentId:s,appAlias:r,environmentAlias:n}});let u=new ElasticsearchTransport({apm:d,level:"debug",clientOpts:{cloud:{id:e},auth:{apiKey:o},requestTimeout:1e4,tls:{rejectUnauthorized:false}},bufferLimit:1e3,silent:false});u.on("error",_=>{console.error("Elasticsearch Transport Error:",_);}),m=A.createLogger({level:"debug",defaultMeta:{serviceName:f},format:A.format.combine(A.format.json()),transports:[u]}),S({elasticCloudId:e,elasticApiKey:o});}function C(){if(!d)throw new Error("APM is not initialized");return d}function E(){return m!==null}function y(){if(!m)throw new Error("Logger is not initialized");return m}function w(){let t="";return a()||(t="info"),process.env.MODELENCE_LOG_LEVEL||t}function W(t,e){a()&&E()&&y().debug(t,e),w()==="debug"&&console.debug(t,e);}function v(t,e){a()&&E()&&y().info(t,e),["debug","info"].includes(w())&&console.info(t,e);}function b(t,e){a()&&E()&&y().error(t,e),["debug","info","error"].includes(w())&&console.error(t,e);}function q(t,e,o){if(!a())return {end:()=>{},setContext:()=>{}};let r=C(),n=r.startTransaction(e,t);return o&&r.setCustomContext(o),{end:(s,{endTime:f,context:u}={})=>{u&&r.setCustomContext(u),n.end(s,f);},setContext:s=>{r.setCustomContext(s);}}}function U(t){if(!a()){console.error(t);return}C().captureError(t);}export{p as a,G as b,V as c,$ as d,F as e,Y as f,Z as g,st as h,W as i,v as j,b as k,q as l,U as m};//# sourceMappingURL=chunk-DIWBKGBL.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-DIWBKGBL.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/config/server.ts","../src/app/loggerProcess.ts","../src/app/state.ts","../src/app/metrics.ts","../src/telemetry/index.ts"],"names":["configSchema","config","isInitialized","getConfig","key","getPublicConfigs","_","schema","loadConfigs","configs","type","value","getSchema","setSchema","isPublic","buffer","sequenceId","startLoggerProcess","_elasticCloudId","_elasticApiKey","originalStdoutWrite","process","originalStderrWrite","chunk","args","addToBuffer","loopSendLogs","timestamp","i","current","sendLogs","stdoutLogs","stderrLogs","log","logInfo","logError","metadata","markAppStarted","setMetadata","_metadata","getEnvironmentId","getAppAlias","getEnvironmentAlias","getTelemetryServiceName","isTelemetryEnabled","apm","logger","initMetrics","initElasticApm","elasticApmEndpoint","elasticCloudId","elasticApiKey","appAlias","environmentAlias","environmentId","serviceName","elasticApm","esTransport","ElasticsearchTransport","error","winston","getApm","isLoggerReady","getLogger","getLogLevel","defaultLoglevel","logDebug","message","startTransaction","name","context","transaction","result","endTime","captureError"],"mappings":"yIAEA,IAAIA,CAAAA,CAA6B,EAAC,CAC9BC,CAAAA,CAAuC,EAAC,CACxCC,CAAAA,CAAgB,KAAA,CAsCb,SAASC,EAAUC,CAAAA,CAAgB,CACxC,OAAOH,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAAA,EAASJ,CAAAA,CAAaI,CAAG,GAAG,OAClD,CAEO,SAASC,CAAAA,EAAmB,CACjC,GAAI,CAACH,CAAAA,CACH,MAAM,IAAI,KAAA,CACR,0FACF,CAAA,CAGF,OAAO,MAAA,CAAO,WAAA,CACZ,MAAA,CAAO,OAAA,CAAQF,CAAY,CAAA,CACxB,MAAA,CAAO,CAAC,CAACM,EAAGC,CAAM,CAAA,GAAMA,CAAAA,CAAO,QAAQ,EACvC,GAAA,CAAI,CAAC,CAACH,CAAAA,CAAKG,CAAM,CAAA,GACT,CACLH,CAAAA,CACA,CACE,IAAAA,CAAAA,CACA,IAAA,CAAMG,CAAAA,CAAO,IAAA,CACb,MAAON,CAAAA,CAAOG,CAAG,CAAA,EAAG,KAAA,EAASG,CAAAA,CAAO,OACtC,CACF,CACD,CACL,CACF,CAEO,SAASC,CAAAA,CAAYC,EAAsB,CAChDA,CAAAA,CAAQ,OAAA,CAAQ,CAAC,CAAE,GAAA,CAAAL,CAAAA,CAAK,IAAA,CAAAM,CAAAA,CAAM,MAAAC,CAAM,CAAA,GAAM,CAGpC,CAFmBP,EAAI,WAAA,EAAY,CAAE,UAAA,CAAW,UAAU,GAEvC,CAACJ,CAAAA,CAAaI,CAAG,CAAA,GAKxCH,EAAOG,CAAG,CAAA,CAAI,CACZ,GAAA,CAAAA,CAAAA,CACA,IAAA,CAAAM,CAAAA,CACA,KAAA,CAAAC,CACF,CAAA,EACF,CAA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,CAAG,CACzB,OAAA,CAAQ,KAAA,CAAMe,CAAK,CAAA,CACnB,MACF,CAEAE,CAAAA,EAAO,CAAE,YAAA,CAAaF,CAAK,EAC7B","file":"chunk-DIWBKGBL.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) {\n return config[key]?.value ?? configSchema[key]?.default;\n}\n\nexport function getPublicConfigs() {\n if (!isInitialized) {\n throw new Error(\n 'Config is not initialized: an attempt was made to access configs before they were loaded'\n );\n }\n\n return Object.fromEntries(\n Object.entries(configSchema)\n .filter(([_, schema]) => schema.isPublic)\n .map(([key, schema]) => {\n return [\n key,\n {\n key,\n type: schema.type,\n value: config[key]?.value ?? schema.default,\n },\n ];\n })\n );\n}\n\nexport function loadConfigs(configs: AppConfig[]) {\n configs.forEach(({ key, type, value }) => {\n const isSystemConfig = key.toLowerCase().startsWith('_system.');\n\n if (!isSystemConfig && !configSchema[key]) {\n // Ignore unknown configs\n return;\n }\n\n config[key] = {\n key,\n type,\n value,\n };\n });\n\n isInitialized = true;\n}\n\nexport function getSchema() {\n return configSchema;\n}\n\nexport function setSchema(schema: ConfigSchema) {\n // TODO: more validation on the schema structure\n Object.entries(schema).forEach(([key, value]) => {\n const { type, isPublic } = value;\n\n if (type === 'secret' && isPublic) {\n throw new Error(`Config ${key} with type \"secret\" cannot be public`);\n }\n });\n\n configSchema = schema;\n}\n","// import { spawn } from 'child_process';\n// import { fileURLToPath } from 'url';\n// import { dirname, join } from 'path';\nimport { logInfo, logError } from '@/telemetry';\nimport process from 'process';\n\ntype LogEntry = { log: string; timestamp: Date | null; sequenceId?: number };\ntype LogBuffer = LogEntry[];\n\nconst buffer: { stdout: LogBuffer; stderr: LogBuffer } = {\n stdout: [{ log: '', timestamp: null }],\n stderr: [{ log: '', timestamp: null }],\n};\n\nlet sequenceId = 1;\n\nexport function startLoggerProcess({\n elasticCloudId: _elasticCloudId,\n elasticApiKey: _elasticApiKey,\n}: {\n elasticCloudId: string;\n elasticApiKey: string;\n}) {\n const originalStdoutWrite = process.stdout.write;\n const originalStderrWrite = process.stderr.write;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stdout.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stdout);\n return originalStdoutWrite.call(process.stdout, chunk, ...args);\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n process.stderr.write = function (chunk: string | Uint8Array, ...args: any[]) {\n addToBuffer(chunk.toString(), buffer.stderr);\n return originalStderrWrite.call(process.stderr, chunk, ...args);\n };\n\n loopSendLogs();\n\n // const currentFilePath = fileURLToPath(import.meta.url);\n // const projectRoot = dirname(dirname(currentFilePath));\n // const loggerPath = join(projectRoot, 'bin', 'modelence-logger', 'index.js');\n // const logger = spawn(process.execPath, [loggerPath], {\n // env: {\n // NODE_ENV: process.env.NODE_ENV,\n // ELASTIC_CLOUD_ID: elasticCloudId,\n // ELASTIC_API_KEY: elasticApiKey\n // },\n // stdio: ['pipe', 'inherit', 'inherit'],\n // detached: true\n // });\n\n // const originalStdoutWrite = process.stdout.write;\n // const originalStderrWrite = process.stderr.write;\n\n // process.stdout.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStdoutWrite.apply(process.stdout, [chunk, ...args]);\n // };\n\n // process.stderr.write = function(chunk: any, ...args: any[]) {\n // logger.stdin.write(chunk);\n // return originalStderrWrite.apply(process.stderr, [chunk, ...args]);\n // };\n\n // process.on('exit', () => {\n // process.stdout.write = originalStdoutWrite;\n // process.stderr.write = originalStderrWrite;\n // });\n\n // logger.unref();\n}\n\nfunction addToBuffer(chunk: string, buffer: LogBuffer) {\n if (chunk.length === 0) {\n return;\n }\n\n const timestamp = new Date();\n\n for (let i = 0; i < chunk.length; i++) {\n const current = buffer[buffer.length - 1];\n if (!current.timestamp) {\n current.timestamp = timestamp;\n current.sequenceId = sequenceId++;\n }\n\n if (chunk[i] === '\\n') {\n buffer.push({ log: '', timestamp: null });\n } else {\n current.log += chunk[i];\n }\n }\n}\n\nasync function sendLogs() {\n const stdoutLogs = buffer.stdout.slice(0, -1);\n buffer.stdout = [buffer.stdout[buffer.stdout.length - 1]];\n\n const stderrLogs = buffer.stderr.slice(0, -1);\n buffer.stderr = [buffer.stderr[buffer.stderr.length - 1]];\n\n stdoutLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logInfo(log, { timestamp, source: 'console', sequenceId });\n });\n stderrLogs.forEach(({ log, timestamp, sequenceId }: LogEntry) => {\n logError(log, { timestamp, source: 'console', sequenceId });\n });\n}\n\nfunction loopSendLogs() {\n setTimeout(() => {\n sendLogs();\n loopSendLogs();\n }, 1000);\n}\n","type AppMetadata = {\n environmentId: string;\n appAlias: string;\n environmentAlias: string;\n telemetry: {\n isEnabled: boolean;\n serviceName: string;\n };\n};\n\nlet appStarted = false;\nlet metadata: AppMetadata | null = null;\n\nexport function markAppStarted() {\n appStarted = true;\n}\n\nexport function isAppStarted() {\n return appStarted;\n}\n\nexport function setMetadata(_metadata: AppMetadata) {\n metadata = Object.assign({}, metadata, _metadata);\n}\n\nexport function getEnvironmentId() {\n return metadata?.environmentId;\n}\n\nexport function getAppAlias() {\n return metadata?.appAlias;\n}\n\nexport function getEnvironmentAlias() {\n return metadata?.environmentAlias;\n}\n\nexport function getTelemetryServiceName() {\n return metadata?.telemetry?.serviceName;\n}\n\nexport function isTelemetryEnabled() {\n return Boolean(metadata?.telemetry?.isEnabled);\n}\n","import elasticApm from 'elastic-apm-node';\nimport winston from 'winston';\nimport { ElasticsearchTransport } from 'winston-elasticsearch';\n\nimport { getConfig } from '../config/server';\nimport { startLoggerProcess } from './loggerProcess';\nimport {\n getAppAlias,\n getEnvironmentAlias,\n getEnvironmentId,\n getTelemetryServiceName,\n isTelemetryEnabled,\n} from './state';\n\nlet isInitialized = false;\nlet apm: typeof elasticApm | null = null;\nlet logger: winston.Logger | null = null;\n\nexport const initMetrics = async () => {\n if (isInitialized) {\n throw new Error('Metrics are already initialized, duplicate \"initMetrics\" call received');\n }\n\n isInitialized = true;\n\n if (isTelemetryEnabled()) {\n await initElasticApm();\n }\n};\n\nasync function initElasticApm() {\n const elasticApmEndpoint = getConfig('_system.elastic.apmEndpoint') as string;\n const elasticCloudId = getConfig('_system.elastic.cloudId') as string;\n const elasticApiKey = getConfig('_system.elastic.apiKey') as string;\n\n const appAlias = getAppAlias() ?? 'unknown';\n const environmentAlias = getEnvironmentAlias() ?? 'unknown';\n const environmentId = getEnvironmentId() ?? 'unknown';\n const serviceName = getTelemetryServiceName();\n\n apm = elasticApm.start({\n serviceName,\n apiKey: elasticApiKey,\n serverUrl: elasticApmEndpoint,\n // environment: 'dev',\n transactionSampleRate: 1.0,\n centralConfig: false,\n globalLabels: {\n modelenceEnv: 'dev',\n appEnv: 'dev',\n environmentId,\n appAlias,\n environmentAlias,\n },\n // logLevel: 'debug'\n });\n\n const esTransport = new ElasticsearchTransport({\n apm,\n level: 'debug',\n clientOpts: {\n cloud: {\n id: elasticCloudId,\n },\n auth: {\n apiKey: elasticApiKey,\n },\n requestTimeout: 10000,\n tls: {\n rejectUnauthorized: false,\n },\n },\n bufferLimit: 1000,\n silent: false,\n });\n\n esTransport.on('error', (error) => {\n console.error('Elasticsearch Transport Error:', error);\n });\n\n logger = winston.createLogger({\n level: 'debug',\n defaultMeta: {\n serviceName,\n },\n format: winston.format.combine(winston.format.json()),\n transports: [\n // new winston.transports.Console(), // TODO: remove, just for debugging\n esTransport,\n ],\n });\n\n startLoggerProcess({\n elasticCloudId,\n elasticApiKey,\n });\n}\n\nexport function getApm() {\n if (!apm) {\n throw new Error('APM is not initialized');\n }\n return apm;\n}\n\nexport function isLoggerReady() {\n return logger !== null;\n}\n\nexport function getLogger() {\n if (!logger) {\n throw new Error('Logger is not initialized');\n }\n return logger;\n}\n","import { getLogger, getApm, isLoggerReady } from '@/app/metrics';\nimport { isTelemetryEnabled } from '@/app/state';\n\ntype LogLevel = 'error' | 'info' | 'debug' | '';\n\n/**\n * Gets the logging level for console logs based on the MODELENCE_LOG_LEVEL environment variable.\n *\n * @returns The log level ('error' | 'info' | 'debug' | '')\n *\n * Behavior:\n * - If MODELENCE_LOG_LEVEL is set, returns that value\n * - If telemetry is disabled and MODELENCE_LOG_LEVEL is not set, defaults to 'info'\n * - If telemetry is enabled and MODELENCE_LOG_LEVEL is not set, returns '' (no console logging)\n */\nfunction getLogLevel(): LogLevel {\n let defaultLoglevel: LogLevel = '';\n if (!isTelemetryEnabled()) {\n defaultLoglevel = 'info';\n }\n\n return (process.env.MODELENCE_LOG_LEVEL as LogLevel) || defaultLoglevel;\n}\n\nexport function logDebug(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().debug(message, args);\n }\n if (getLogLevel() === 'debug') {\n console.debug(message, args);\n }\n}\n\nexport function logInfo(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().info(message, args);\n }\n if (['debug', 'info'].includes(getLogLevel())) {\n console.info(message, args);\n }\n}\n\nexport function logError(message: string, args: object) {\n if (isTelemetryEnabled() && isLoggerReady()) {\n getLogger().error(message, args);\n }\n if (['debug', 'info', 'error'].includes(getLogLevel())) {\n console.error(message, args);\n }\n}\n\ninterface WrappedTransaction {\n end(result?: string, context?: Record<string, unknown>): void;\n setContext(context: Record<string, unknown>): void;\n}\n\nexport function startTransaction(\n type: 'method' | 'cron' | 'ai' | 'custom' | 'route',\n name: string,\n context?: Record<string, unknown>\n): WrappedTransaction {\n if (!isTelemetryEnabled()) {\n return {\n end: () => {\n // do nothing\n },\n setContext: () => {\n // do nothing\n },\n };\n }\n\n const apm = getApm();\n const transaction = apm.startTransaction(name, type);\n if (context) {\n apm.setCustomContext(context);\n }\n\n return {\n end: (\n result?: string,\n { endTime, context }: { endTime?: number; context?: Record<string, unknown> } = {}\n ) => {\n if (context) {\n apm.setCustomContext(context);\n }\n transaction.end(result, endTime);\n },\n setContext: (context: Record<string, unknown>) => {\n apm.setCustomContext(context);\n },\n };\n}\n\nexport function captureError(error: Error) {\n if (!isTelemetryEnabled()) {\n console.error(error);\n return;\n }\n\n getApm().captureError(error);\n}\n"]}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var s="module",i="modelence",r="0.
|
|
2
|
-
export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
var s="module",i="modelence",r="0.14.0",o="The Node.js Framework for Real-Time MongoDB Apps",n="dist/index.js",p="dist/global.d.ts",c={".":"./dist/index.js","./client":"./dist/client.js","./server":"./dist/server.js","./telemetry":"./dist/telemetry.js","./mongodb":"./dist/mongo.js","./types":{types:"./dist/types.d.ts",default:"./dist/types.js"}},d=["dist","dist/bin"],l={modelence:"./dist/bin/modelence.js"},a={build:"tsup",dev:"tsup --watch",format:'prettier --write "src/**/*.{ts,tsx,js,jsx,json,css,md}"',"format:check":'prettier --check "src/**/*.{ts,tsx,js,jsx,json,css,md}"',lint:"eslint src --ext .ts,.tsx --fix","lint:check":"eslint src --ext .ts,.tsx",prepublishOnly:"npm run build",test:"NODE_OPTIONS=--experimental-vm-modules jest","test:watch":"NODE_OPTIONS=--experimental-vm-modules jest --watch","test:coverage":"NODE_OPTIONS=--experimental-vm-modules jest --coverage",postversion:"git push && git push --tags",prepare:"cd ../.. && git config core.hooksPath .husky"},m={type:"git",url:"git+https://github.com/modelence/modelence.git"},y="Modelence",u="SEE LICENSE IN LICENSE",j={url:"https://github.com/modelence/modelence/issues"},g="https://modelence.com",h={"@types/archiver":"^6.0.3","@types/bcrypt":"^6.0.0","@types/cookie-parser":"^1.4.9","@types/express":"^5.0.0","@types/fs-extra":"^11.0.4","@types/jest":"^30.0.0","@types/node":"^22.5.1","@types/react":"^19.0.0","@types/react-dom":"^19.0.1","@types/socket.io":"^3.0.1","@typescript-eslint/eslint-plugin":"^8.17.0","@typescript-eslint/parser":"^8.17.0",eslint:"^9.37.0",husky:"^9.1.7",jest:"^30.2.0","lint-staged":"^16.2.7",prettier:"^3.6.2",react:"^19.0.0","react-dom":"^19.0.0","ts-jest":"^29.4.5","ts-node":"^10.9.2"},x={"@socket.io/mongo-adapter":"^0.4.0","@vitejs/plugin-react":"^4.3.4",archiver:"^7.0.1",bcrypt:"^6.0.0",commander:"^12.0.0","cookie-parser":"^1.4.7",dotenv:"^16.4.5","elastic-apm-node":"^4.15.0",express:"^4.21.0","fs-extra":"^11.2.0",jiti:"^2.4.2",mongodb:"^6.8.1",open:"^10.1.0","socket.io":"^4.8.1","socket.io-client":"^4.8.1",tsup:"^8.3.6",tsx:"^4.19.3",typescript:"^5.7.2",vite:"^6.0.3","vite-plugin-eslint":"^1.8.1",winston:"^3.15.0","winston-elasticsearch":"^0.19.0",zod:"^3.23.8",zustand:"^5.0.2"},v={react:">=18.0.0","react-dom":">=18.0.0"},b={type:s,name:i,version:r,description:o,main:n,types:p,exports:c,files:d,bin:l,scripts:a,"lint-staged":{"src/**/*.{ts,tsx,js,jsx,json,css,md}":"prettier --write"},repository:m,author:y,license:u,bugs:j,homepage:g,devDependencies:h,dependencies:x,peerDependencies:v};
|
|
2
|
+
export{s as a,i as b,r as c,o as d,n as e,p as f,c as g,d as h,l as i,a as j,m as k,y as l,u as m,j as n,g as o,h as p,x as q,v as r,b as s};//# sourceMappingURL=chunk-S7LR4K37.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-S7LR4K37.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,SACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,IAAA,CAAQ,iCAAA,CACR,YAAA,CAAc,2BAAA,CACd,cAAA,CAAkB,gBAClB,IAAA,CAAQ,6CAAA,CACR,YAAA,CAAc,qDAAA,CACd,eAAA,CAAiB,wDAAA,CACjB,YAAe,6BAAA,CACf,OAAA,CAAW,8CACb,CAAA,CAIAC,CAAAA,CAAc,CACZ,KAAQ,KAAA,CACR,GAAA,CAAO,gDACT,CAAA,CACAC,CAAAA,CAAU,WAAA,CACVC,CAAAA,CAAW,wBAAA,CACXC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a,UACf,EAxGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAcA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../package.json"],"names":["type","name","version","description","main","types","exports","files","bin","scripts","repository","author","license","bugs","homepage","devDependencies","dependencies","peerDependencies","package_default"],"mappings":"AACE,IAAAA,CAAAA,CAAQ,QAAA,CACRC,CAAAA,CAAQ,WAAA,CACRC,CAAAA,CAAW,SACXC,CAAAA,CAAe,kDAAA,CACfC,CAAAA,CAAQ,eAAA,CACRC,CAAAA,CAAS,kBAAA,CACTC,EAAW,CACT,GAAA,CAAK,iBAAA,CACL,UAAA,CAAY,kBAAA,CACZ,UAAA,CAAY,kBAAA,CACZ,aAAA,CAAe,qBAAA,CACf,WAAA,CAAa,iBAAA,CACb,SAAA,CAAW,CACT,KAAA,CAAS,oBACT,OAAA,CAAW,iBACb,CACF,CAAA,CACAC,CAAAA,CAAS,CACP,MAAA,CACA,UACF,CAAA,CACAC,CAAAA,CAAO,CACL,SAAA,CAAa,yBACf,CAAA,CACAC,EAAW,CACT,KAAA,CAAS,MAAA,CACT,GAAA,CAAO,cAAA,CACP,MAAA,CAAU,yDAAA,CACV,cAAA,CAAgB,yDAAA,CAChB,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A,CACR,YAAa,QAAA,CACb,kBAAA,CAAoB,QAAA,CACpB,IAAA,CAAQ,QAAA,CACR,GAAA,CAAO,SAAA,CACP,UAAA,CAAc,QAAA,CACd,IAAA,CAAQ,QAAA,CACR,oBAAA,CAAsB,QAAA,CACtB,OAAA,CAAW,UACX,uBAAA,CAAyB,SAAA,CACzB,GAAA,CAAO,SAAA,CACP,OAAA,CAAW,QACb,EACAC,CAAAA,CAAoB,CAClB,KAAA,CAAS,UAAA,CACT,WAAA,CAAa,UACf,EAxGFC,CAAAA,CAAA,CACE,IAAA,CAAAlB,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,QAAAC,CAAAA,CAWA,KAAA,CAAAC,CAAAA,CAIA,GAAA,CAAAC,CAAAA,CAGA,OAAA,CAAAC,CAAAA,CAcA,aAAA,CAAe,CACb,sCAAA,CAAwC,kBAC1C,CAAA,CACA,UAAA,CAAAC,CAAAA,CAIA,OAAAC,CAAAA,CACA,OAAA,CAAAC,CAAAA,CACA,IAAA,CAAAC,CAAAA,CAGA,QAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAuBA,YAAA,CAAAC,CAAAA,CA0BA,gBAAA,CAAAC,CAIF","file":"chunk-S7LR4K37.js","sourcesContent":["{\n \"type\": \"module\",\n \"name\": \"modelence\",\n \"version\": \"0.14.0\",\n \"description\": \"The Node.js Framework for Real-Time MongoDB Apps\",\n \"main\": \"dist/index.js\",\n \"types\": \"dist/global.d.ts\",\n \"exports\": {\n \".\": \"./dist/index.js\",\n \"./client\": \"./dist/client.js\",\n \"./server\": \"./dist/server.js\",\n \"./telemetry\": \"./dist/telemetry.js\",\n \"./mongodb\": \"./dist/mongo.js\",\n \"./types\": {\n \"types\": \"./dist/types.d.ts\",\n \"default\": \"./dist/types.js\"\n }\n },\n \"files\": [\n \"dist\",\n \"dist/bin\"\n ],\n \"bin\": {\n \"modelence\": \"./dist/bin/modelence.js\"\n },\n \"scripts\": {\n \"build\": \"tsup\",\n \"dev\": \"tsup --watch\",\n \"format\": \"prettier --write \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"format:check\": \"prettier --check \\\"src/**/*.{ts,tsx,js,jsx,json,css,md}\\\"\",\n \"lint\": \"eslint src --ext .ts,.tsx --fix\",\n \"lint:check\": \"eslint src --ext .ts,.tsx\",\n \"prepublishOnly\": \"npm run build\",\n \"test\": \"NODE_OPTIONS=--experimental-vm-modules jest\",\n \"test:watch\": \"NODE_OPTIONS=--experimental-vm-modules jest --watch\",\n \"test:coverage\": \"NODE_OPTIONS=--experimental-vm-modules jest --coverage\",\n \"postversion\": \"git push && git push --tags\",\n \"prepare\": \"cd ../.. && git config core.hooksPath .husky\"\n },\n \"lint-staged\": {\n \"src/**/*.{ts,tsx,js,jsx,json,css,md}\": \"prettier --write\"\n },\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/modelence/modelence.git\"\n },\n \"author\": \"Modelence\",\n \"license\": \"SEE LICENSE IN LICENSE\",\n \"bugs\": {\n \"url\": \"https://github.com/modelence/modelence/issues\"\n },\n \"homepage\": \"https://modelence.com\",\n \"devDependencies\": {\n \"@types/archiver\": \"^6.0.3\",\n \"@types/bcrypt\": \"^6.0.0\",\n \"@types/cookie-parser\": \"^1.4.9\",\n \"@types/express\": \"^5.0.0\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/jest\": \"^30.0.0\",\n \"@types/node\": \"^22.5.1\",\n \"@types/react\": \"^19.0.0\",\n \"@types/react-dom\": \"^19.0.1\",\n \"@types/socket.io\": \"^3.0.1\",\n \"@typescript-eslint/eslint-plugin\": \"^8.17.0\",\n \"@typescript-eslint/parser\": \"^8.17.0\",\n \"eslint\": \"^9.37.0\",\n \"husky\": \"^9.1.7\",\n \"jest\": \"^30.2.0\",\n \"lint-staged\": \"^16.2.7\",\n \"prettier\": \"^3.6.2\",\n \"react\": \"^19.0.0\",\n \"react-dom\": \"^19.0.0\",\n \"ts-jest\": \"^29.4.5\",\n \"ts-node\": \"^10.9.2\"\n },\n \"dependencies\": {\n \"@socket.io/mongo-adapter\": \"^0.4.0\",\n \"@vitejs/plugin-react\": \"^4.3.4\",\n \"archiver\": \"^7.0.1\",\n \"bcrypt\": \"^6.0.0\",\n \"commander\": \"^12.0.0\",\n \"cookie-parser\": \"^1.4.7\",\n \"dotenv\": \"^16.4.5\",\n \"elastic-apm-node\": \"^4.15.0\",\n \"express\": \"^4.21.0\",\n \"fs-extra\": \"^11.2.0\",\n \"jiti\": \"^2.4.2\",\n \"mongodb\": \"^6.8.1\",\n \"open\": \"^10.1.0\",\n \"socket.io\": \"^4.8.1\",\n \"socket.io-client\": \"^4.8.1\",\n \"tsup\": \"^8.3.6\",\n \"tsx\": \"^4.19.3\",\n \"typescript\": \"^5.7.2\",\n \"vite\": \"^6.0.3\",\n \"vite-plugin-eslint\": \"^1.8.1\",\n \"winston\": \"^3.15.0\",\n \"winston-elasticsearch\": \"^0.19.0\",\n \"zod\": \"^3.23.8\",\n \"zustand\": \"^5.0.2\"\n },\n \"peerDependencies\": {\n \"react\": \">=18.0.0\",\n \"react-dom\": \">=18.0.0\"\n }\n}\n"]}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { b as ConfigKey, a as WebsocketClientProvider, c as ClientChannel } from './types-
|
|
1
|
+
import { b as ConfigKey, a as WebsocketClientProvider, c as ClientChannel } from './types-CSQ5Qjb4.js';
|
|
2
2
|
import React from 'react';
|
|
3
|
+
import { F as FileVisibility } from './types-DLDzAym7.js';
|
|
3
4
|
import 'http';
|
|
4
5
|
import 'mongodb';
|
|
5
6
|
|
|
@@ -36,6 +37,9 @@ type User = {
|
|
|
36
37
|
roles: string[];
|
|
37
38
|
hasRole: (role: string) => boolean;
|
|
38
39
|
requireRole: (role: string) => void;
|
|
40
|
+
firstName?: string;
|
|
41
|
+
lastName?: string;
|
|
42
|
+
avatarUrl?: string;
|
|
39
43
|
};
|
|
40
44
|
/**
|
|
41
45
|
* `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.
|
|
@@ -60,6 +64,9 @@ type UserInfo = {
|
|
|
60
64
|
roles: string[];
|
|
61
65
|
hasRole: (role: string) => boolean;
|
|
62
66
|
requireRole: (role: string) => void;
|
|
67
|
+
firstName?: string;
|
|
68
|
+
lastName?: string;
|
|
69
|
+
avatarUrl?: string;
|
|
63
70
|
};
|
|
64
71
|
/**
|
|
65
72
|
* Sign up a new user with an email and password.
|
|
@@ -67,13 +74,22 @@ type UserInfo = {
|
|
|
67
74
|
* @example
|
|
68
75
|
* ```ts
|
|
69
76
|
* await signupWithPassword({ email: 'test@example.com', password: '12345678' });
|
|
77
|
+
* await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });
|
|
70
78
|
* ```
|
|
71
79
|
* @param options.email - The email of the user.
|
|
72
80
|
* @param options.password - The password of the user.
|
|
81
|
+
* @param options.handle - Optional custom handle. If omitted, one is derived from the email.
|
|
82
|
+
* @param options.firstName - Optional first name.
|
|
83
|
+
* @param options.lastName - Optional last name.
|
|
84
|
+
* @param options.avatarUrl - Optional avatar URL.
|
|
73
85
|
*/
|
|
74
86
|
declare function signupWithPassword(options: {
|
|
75
87
|
email: string;
|
|
76
88
|
password: string;
|
|
89
|
+
handle?: string;
|
|
90
|
+
firstName?: string;
|
|
91
|
+
lastName?: string;
|
|
92
|
+
avatarUrl?: string;
|
|
77
93
|
}): Promise<void>;
|
|
78
94
|
/**
|
|
79
95
|
* Login a user with an email and password.
|
|
@@ -94,6 +110,36 @@ declare function loginWithPassword(options: {
|
|
|
94
110
|
roles: string[];
|
|
95
111
|
hasRole: (role: string) => boolean;
|
|
96
112
|
requireRole: (role: string) => void;
|
|
113
|
+
firstName?: string;
|
|
114
|
+
lastName?: string;
|
|
115
|
+
avatarUrl?: string;
|
|
116
|
+
} | null>;
|
|
117
|
+
/**
|
|
118
|
+
* Update the current user's profile.
|
|
119
|
+
*
|
|
120
|
+
* @example
|
|
121
|
+
* ```ts
|
|
122
|
+
* await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });
|
|
123
|
+
* ```
|
|
124
|
+
* @param options.firstName - The first name of the user.
|
|
125
|
+
* @param options.lastName - The last name of the user.
|
|
126
|
+
* @param options.avatarUrl - The avatar URL of the user.
|
|
127
|
+
* @param options.handle - The handle of the user.
|
|
128
|
+
*/
|
|
129
|
+
declare function updateProfile(options: {
|
|
130
|
+
firstName?: string;
|
|
131
|
+
lastName?: string;
|
|
132
|
+
avatarUrl?: string;
|
|
133
|
+
handle?: string;
|
|
134
|
+
}): Promise<{
|
|
135
|
+
id: string;
|
|
136
|
+
handle: string;
|
|
137
|
+
roles: string[];
|
|
138
|
+
hasRole: (role: string) => boolean;
|
|
139
|
+
requireRole: (role: string) => void;
|
|
140
|
+
firstName?: string;
|
|
141
|
+
lastName?: string;
|
|
142
|
+
avatarUrl?: string;
|
|
97
143
|
} | null>;
|
|
98
144
|
/**
|
|
99
145
|
* Verify user's email with a verification token.
|
|
@@ -154,6 +200,23 @@ declare function startWebsockets(props?: {
|
|
|
154
200
|
|
|
155
201
|
declare function getLocalStorageSession(): any;
|
|
156
202
|
|
|
203
|
+
type UploadFileParams = {
|
|
204
|
+
filePath: string;
|
|
205
|
+
contentType: string;
|
|
206
|
+
visibility: FileVisibility;
|
|
207
|
+
};
|
|
208
|
+
type UploadFileResult = {
|
|
209
|
+
filePath: string;
|
|
210
|
+
};
|
|
211
|
+
declare function uploadFile(file: File | Blob, { filePath, contentType, visibility }: UploadFileParams): Promise<UploadFileResult>;
|
|
212
|
+
declare function deleteFile(filePath: string): Promise<void>;
|
|
213
|
+
declare function downloadFile(filePath: string): Promise<{
|
|
214
|
+
downloadUrl: string;
|
|
215
|
+
}>;
|
|
216
|
+
declare function getFileUrl(filePath: string): Promise<{
|
|
217
|
+
url: string;
|
|
218
|
+
}>;
|
|
219
|
+
|
|
157
220
|
declare const AppProvider: any;
|
|
158
221
|
|
|
159
|
-
export { AppProvider, ClientChannel, type MethodArgs, MethodError, type UserInfo, callMethod, getConfig, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, useSession, verifyEmail };
|
|
222
|
+
export { AppProvider, ClientChannel, type MethodArgs, MethodError, type UserInfo, callMethod, deleteFile, downloadFile, getConfig, getFileUrl, getLocalStorageSession, getWebsocketClientProvider, loginWithPassword, logout, renderApp, resendEmailVerification, resetPassword, sendResetPasswordToken, setWebsocketClientProvider, signupWithPassword, startWebsockets, subscribeLiveQuery, updateProfile, uploadFile, useSession, verifyEmail };
|
package/dist/client.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {b as b$1}from'./chunk-3S2FFBNS.js';import {a}from'./chunk-DO5TZLF5.js';import q,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import
|
|
1
|
+
import {b as b$1}from'./chunk-3S2FFBNS.js';import {a}from'./chunk-DO5TZLF5.js';import q,{useState,useEffect}from'react';import {create}from'zustand';import {z as z$1}from'zod';import {jsx}from'react/jsx-runtime';import ue from'react-dom/client';import pe from'socket.io-client';function C(){let e=localStorage.getItem("modelence.session");try{return e?JSON.parse(e):null}catch(t){return console.error("Error parsing session from localStorage",t),null}}function R(e){localStorage.setItem("modelence.session",JSON.stringify(e));}async function V(e){let{email:t,password:r,handle:n,firstName:o,lastName:s,avatarUrl:l}=e;await i("_system.user.signupWithPassword",{email:t,password:r,...n!==void 0?{handle:n}:{},...o!==void 0?{firstName:o}:{},...s!==void 0?{lastName:s}:{},...l!==void 0?{avatarUrl:l}:{}});}async function J(e){let{email:t,password:r}=e,{user:n}=await i("_system.user.loginWithPassword",{email:t,password:r});return v(n)}async function B(e){let{firstName:t,lastName:r,avatarUrl:n,handle:o}=e,{user:s}=await i("_system.user.updateProfile",{...t!==void 0?{firstName:t}:{},...r!==void 0?{lastName:r}:{},...n!==void 0?{avatarUrl:n}:{},...o!==void 0?{handle:o}:{}});return v(s)}async function K(e){let{token:t}=e;await i("_system.user.verifyEmail",{token:t});}async function G(e){let{email:t}=e;await i("_system.user.resendEmailVerification",{email:t});}async function X(){await i("_system.user.logout"),v(null);}async function Y(e){let{email:t}=e;await i("_system.user.sendResetPasswordToken",{email:t});}async function Z(e){let{token:t,password:r}=e;await i("_system.user.resetPassword",{token:t,password:r});}function f(){return C()?.authToken}function p(){return {screenWidth:window.screen.width,screenHeight:window.screen.height,windowWidth:window.innerWidth,windowHeight:window.innerHeight,pixelRatio:window.devicePixelRatio,orientation:window.screen.orientation?.type??null}}var N=(e,t)=>{console.error(`Error calling method '${t}':`,e);};function I(e){N=e;}function A(e,t){return N(e,t)}var b=class extends Error{constructor(t,r){super(t),this.name="MethodError",this.status=r;}};async function i(e,t={},r={}){try{return await ee(`/api/_internal/method/${e}`,t)}catch(n){throw (r.errorHandler??A)(n,e),n}}async function ee(e,t){let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({args:t,authToken:f(),clientInfo:p()})});if(!r.ok){let s=await r.text();throw new b(s,r.status)}let n=await r.text(),o=n?JSON.parse(n):void 0;if(!o)throw new Error("Invalid response from server");return b$1(o.data,o.typeMap)}var W={};function te(e){return W[e]?.value}function M(e){W=e;}var P=create(e=>({user:null,setUser:t=>e({user:t})})),L=false,ne=a.seconds(30),ie=z$1.object({id:z$1.string(),handle:z$1.string(),roles:z$1.array(z$1.string()),firstName:z$1.string().optional(),lastName:z$1.string().optional(),avatarUrl:z$1.string().optional()});function F(e){if(!e)return null;let t=ie.safeParse(e);if(!t.success)return console.error("Session Error: Invalid user payload",t.error),null;let r=t.data;return Object.freeze({...r,firstName:r.firstName??void 0,lastName:r.lastName??void 0,avatarUrl:r.avatarUrl??void 0,hasRole:n=>r.roles.includes(n),requireRole:n=>{if(!r.roles.includes(n))throw new Error(`Access denied - role '${n}' required`)}})}async function H(){if(L)return;L=true;let{configs:e,session:t,user:r}=await i("_system.session.init");M(e),R(t),P.getState().setUser(F(r)),await _();}async function _(){try{await i("_system.session.heartbeat",{},{errorHandler:()=>{}});}catch{}setTimeout(_,ne);}function v(e){let t=F(e);return P.getState().setUser(t),t}function se(){return {user:P(t=>t.user)}}var O=false;function x({children:e,loadingElement:t}){let[r,n]=useState(true);return useEffect(()=>{async function o(){O||(O=true,await H(),n(false));}o();},[]),r?t??jsx("div",{children:"Loading..."}):e}function fe({loadingElement:e,routesElement:t,favicon:r,errorHandler:n}){if(n&&I(n),window.addEventListener("unload",()=>{}),ue.createRoot(document.getElementById("root")).render(jsx(q.StrictMode,{children:jsx(Q,{loadingElement:e,children:t})})),r){let o=document.querySelector("link[rel~='icon']");if(o)o.href=r;else {let s=document.createElement("link");s.rel="icon",s.href=r,document.head.appendChild(s);}}}var g=null,m=new Map;function h(){if(!g)throw new Error("WebSocket not initialized. Call startWebsockets() first.");return g}function ge(){let e=f(),t=p();for(let r of m.values())g?.emit("subscribeLiveQuery",{subscriptionId:r.subscriptionId,method:r.method,args:r.args,authToken:e,clientInfo:t});}function me(e){g=pe("/",{transports:["websocket"],auth:{token:f()}}),g.on("connect",()=>{m.size>0&&(console.log(`[Modelence] WebSocket reconnected, re-subscribing to ${m.size} live queries`),ge());}),e.channels?.forEach(t=>t.init());}function he({category:e,listener:t}){h().on(e,t);}function ye({category:e,listener:t}){h().once(e,t);}function we({category:e,listener:t}){h().off(e,t);}function S({eventName:e,category:t,id:r}){h().emit(e,`${t}:${r}`);}function ve({category:e,id:t}){S({eventName:"joinChannel",category:e,id:t});}function be({category:e,id:t}){S({eventName:"leaveChannel",category:e,id:t});}var ke=0;function $(e,t,r,n){let o=`sub-${++ke}-${Date.now()}`,s=({subscriptionId:d,data:u,typeMap:k})=>{d===o&&r(b$1(u,k));},l=({subscriptionId:d,error:u})=>{d===o&&(console.error(`[Modelence] Live query error for ${e}:`,u),n?.(u));},a=h();return a.on("liveQueryData",s),a.on("liveQueryError",l),m.set(o,{subscriptionId:o,method:e,args:t}),a.connected&&a.emit("subscribeLiveQuery",{subscriptionId:o,method:e,args:t,authToken:f(),clientInfo:p()}),()=>{m.delete(o),a.emit("unsubscribeLiveQuery",{subscriptionId:o}),a.off("liveQueryData",s),a.off("liveQueryError",l);}}var Ce={init:me,on:he,once:ye,off:we,emit:S,joinChannel:ve,leaveChannel:be},j=Ce;var T=null;function z(e){T=e;}function y(){return T}function Pe(e){if(T){console.warn("WebSocket already initialized. Skipping initialization.");return}let t=e?.provider||j;t.init({channels:e?.channels}),z(t);}var U=class{constructor(t,r){this.category=t,this.onMessage=r;}init(){y()?.on({category:this.category,listener:this.onMessage});}joinChannel(t){y()?.joinChannel({category:this.category,id:t});}leaveChannel(t){y()?.leaveChannel({category:this.category,id:t});}};async function xe(e,{filePath:t,contentType:r,visibility:n}){let{url:o,fields:s,filePath:l}=await i("_system.files.getUploadUrl",{filePath:t,contentType:r,visibility:n}),a=new FormData;for(let[u,k]of Object.entries(s))a.append(u,k);a.append("file",e);let d=await fetch(o,{method:"POST",body:a});if(!d.ok)throw new Error(`Failed to upload file: HTTP status: ${d.status}`);return {filePath:l}}async function Se(e){await i("_system.files.deleteFile",{filePath:e});}async function Te(e){return i("_system.files.downloadFile",{filePath:e})}async function Ue(e){return i("_system.files.getFileUrl",{filePath:e})}var Q="useClient"in q?q.useClient(x):x;export{Q as AppProvider,U as ClientChannel,b as MethodError,i as callMethod,Se as deleteFile,Te as downloadFile,te as getConfig,Ue as getFileUrl,C as getLocalStorageSession,y as getWebsocketClientProvider,J as loginWithPassword,X as logout,fe as renderApp,G as resendEmailVerification,Z as resetPassword,Y as sendResetPasswordToken,z as setWebsocketClientProvider,V as signupWithPassword,Pe as startWebsockets,$ as subscribeLiveQuery,B as updateProfile,xe as uploadFile,se as useSession,K as verifyEmail};//# sourceMappingURL=client.js.map
|
|
2
2
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/localStorage.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","signupWithPassword","options","email","password","callMethod","loginWithPassword","user","setCurrentUser","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","getAuthToken","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,YAAA,CAAa,OAAA,CAAQ,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,KAAK,KAAA,CAAMA,CAAW,CAAA,CAAI,IACjD,OAASC,CAAAA,CAAG,CACV,O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A,EAAO,CACLH,GAA2B,EAAG,EAAA,CAAG,CAC/B,QAAA,CAAU,KAAK,QAAA,CACf,QAAA,CAAU,IAAA,CAAK,SACjB,CAAC,EACH,CAEA,WAAA,CAAYnB,CAAAA,CAAY,CACtBmB,CAAAA,EAA2B,EAAG,WAAA,CAAY,CACxC,SAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CAEA,YAAA,CAAaA,CAAAA,CAAY,CACvBmB,CAAAA,EAA2B,EAAG,YAAA,CAAa,CACzC,SAAU,IAAA,CAAK,QAAA,CACf,EAAA,CAAAnB,CACF,CAAC,EACH,CACF,ECzBO,IAAMlC,EACX,WAAA,GAAea,CAAAA,CAEXA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { ClientInfo } from '@/methods/types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function signupWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n await callMethod('_system.user.signupWithPassword', { email, password });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n\n constructor(message: string, status: number) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\nexport async function callMethod<T = unknown>(\n methodName: string,\n args: MethodArgs = {},\n options: CallMethodOptions = {}\n): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new MethodError(error, response.status);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const parsedData = userSchema.parse(user);\n\n return Object.freeze({\n ...parsedData,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object;\n user: object;\n }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n socketClient = io('/', {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n provider.init({\n channels: props?.channels,\n });\n setWebsocketClientProvider(provider);\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/localStorage.ts","../src/auth/client/index.ts","../src/client/errorHandler.ts","../src/client/method.ts","../src/config/client.ts","../src/client/session.ts","../src/client/AppProvider.tsx","../src/client/renderApp.tsx","../src/websocket/socketio/client.ts","../src/websocket/client.ts","../src/websocket/clientChannel.ts","../src/files/client.ts","../src/client.ts"],"names":["getLocalStorageSession","sessionJson","e","setLocalStorageSession","session","signupWithPassword","options","email","password","handle","firstName","lastName","avatarUrl","callMethod","loginWithPassword","user","setCurrentUser","updateProfile","verifyEmail","token","resendEmailVerification","logout","sendResetPasswordToken","resetPassword","getAuthToken","getClientInfo","errorHandler","error","methodName","setErrorHandler","handler","handleError","MethodError","message","status","args","call","endpoint","response","text","result","reviveResponseTypes","config","getConfig","key","_setConfig","configs","useSessionStore","create","set","isInitialized","SESSION_HEARTBEAT_INTERVAL","time","userSchema","z","parseUser","parsedData","role","initSession","loopSessionHeartbeat","enrichedUser","useSession","state","AppProvider","children","loadingElement","isLoading","setIsLoading","useState","useEffect","initConfig","jsx","renderApp","routesElement","favicon","ReactDOM","React","link","newLink","socketClient","activeLiveSubscriptions","getSocket","resubscribeAll","authToken","clientInfo","sub","init","props","io","channel","on","category","listener","once","off","emit","eventName","id","joinChannel","leaveChannel","liveQueryCounter","subscribeLiveQuery","method","onData","onError","subscriptionId","handleData","sid","data","typeMap","socket","websocketProvider","client_default","websocketClientProvider","setWebsocketClientProvider","provider","getWebsocketClientProvider","startWebsockets","ClientChannel","onMessage","uploadFile","file","filePath","contentType","visibility","url","fields","resolvedFilePath","formData","value","uploadResponse","deleteFile","downloadFile","getFileUrl"],"mappings":"sRAAO,SAASA,CAAAA,EAAyB,CACvC,IAAMC,CAAAA,CAAc,aAAa,OAAA,CAAQ,mBAAmB,EAC5D,GAAI,CACF,OAAOA,CAAAA,CAAc,IAAA,CAAK,MAAMA,CAAW,CAAA,CAAI,IACjD,CAAA,MAASC,CAAAA,CAAG,CACV,OAAA,OAAA,CAAQ,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,CAAI,MAAMlH,EAA+B,4BAAA,CAA8B,CACrE,SAAA6G,CAAAA,CACA,WAAA,CAAAC,EACA,UAAA,CAAAC,CACF,CAAC,CAAA,CAEKI,CAAAA,CAAW,IAAI,QAAA,CACrB,IAAA,GAAW,CAACpF,CAAAA,CAAKqF,CAAK,IAAK,MAAA,CAAO,OAAA,CAAQH,CAAM,CAAA,CAC9CE,CAAAA,CAAS,OAAOpF,CAAAA,CAAKqF,CAAK,EAE5BD,CAAAA,CAAS,MAAA,CAAO,OAAQP,CAAI,CAAA,CAE5B,IAAMS,CAAAA,CAAiB,MAAM,MAAML,CAAAA,CAAK,CACtC,OAAQ,MAAA,CACR,IAAA,CAAMG,CACR,CAAC,CAAA,CAED,GAAI,CAACE,CAAAA,CAAe,GAClB,MAAM,IAAI,MAAM,CAAA,oCAAA,EAAuCA,CAAAA,CAAe,MAAM,CAAA,CAAE,CAAA,CAGhF,OAAO,CAAE,QAAA,CAAUH,CAAiB,CACtC,CAEA,eAAsBI,EAAAA,CAAWT,CAAAA,CAAiC,CAChE,MAAM7G,CAAAA,CAAW,2BAA4B,CAAE,QAAA,CAAA6G,CAAS,CAAC,EAC3D,CAEA,eAAsBU,EAAAA,CAAaV,EAAoD,CACrF,OAAO7G,EAAW,4BAAA,CAA8B,CAAE,SAAA6G,CAAS,CAAC,CAC9D,CAEA,eAAsBW,GAAWX,CAAAA,CAA4C,CAC3E,OAAO7G,CAAAA,CAAW,0BAAA,CAA4B,CAAE,QAAA,CAAA6G,CAAS,CAAC,CAC5D,KCjDa3D,CAAAA,CACX,WAAA,GAAea,EAEXA,CAAAA,CAAM,SAAA,CAAUb,CAAmB,CAAA,CACnCA","file":"client.js","sourcesContent":["export function getLocalStorageSession() {\n const sessionJson = localStorage.getItem('modelence.session');\n try {\n return sessionJson ? JSON.parse(sessionJson) : null;\n } catch (e) {\n console.error('Error parsing session from localStorage', e);\n return null;\n }\n}\n\nexport function setLocalStorageSession(session: object) {\n localStorage.setItem('modelence.session', JSON.stringify(session));\n}\n","import { setCurrentUser } from '@/client/session';\nimport { callMethod } from '@/client/method';\nimport { getLocalStorageSession } from '@/client/localStorage';\nimport { ClientInfo } from '@/methods/types';\n\nexport type UserInfo = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype RawUserData = {\n id: string;\n handle: string;\n roles: string[];\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\n/**\n * Sign up a new user with an email and password.\n *\n * @example\n * ```ts\n * await signupWithPassword({ email: 'test@example.com', password: '12345678' });\n * await signupWithPassword({ email: 'test@example.com', password: '12345678', handle: 'myhandle', firstName: 'John' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n * @param options.handle - Optional custom handle. If omitted, one is derived from the email.\n * @param options.firstName - Optional first name.\n * @param options.lastName - Optional last name.\n * @param options.avatarUrl - Optional avatar URL.\n */\nexport async function signupWithPassword(options: {\n email: string;\n password: string;\n handle?: string;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n}) {\n const { email, password, handle, firstName, lastName, avatarUrl } = options;\n await callMethod('_system.user.signupWithPassword', {\n email,\n password,\n ...(handle !== undefined ? { handle } : {}),\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n });\n}\n\n/**\n * Login a user with an email and password.\n *\n * @example\n * ```ts\n * await loginWithPassword({ email: 'test@example.com', password: '12345678' });\n * ```\n * @param options.email - The email of the user.\n * @param options.password - The password of the user.\n */\nexport async function loginWithPassword(options: { email: string; password: string }) {\n const { email, password } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.loginWithPassword', {\n email,\n password,\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Update the current user's profile.\n *\n * @example\n * ```ts\n * await updateProfile({ firstName: 'Atul', lastName: 'Yadav', avatarUrl: 'https://example.com/avatar.jpg', handle: 'atulyadav' });\n * ```\n * @param options.firstName - The first name of the user.\n * @param options.lastName - The last name of the user.\n * @param options.avatarUrl - The avatar URL of the user.\n * @param options.handle - The handle of the user.\n */\nexport async function updateProfile(options: {\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n handle?: string;\n}) {\n const { firstName, lastName, avatarUrl, handle } = options;\n const { user } = await callMethod<{ user: RawUserData }>('_system.user.updateProfile', {\n ...(firstName !== undefined ? { firstName } : {}),\n ...(lastName !== undefined ? { lastName } : {}),\n ...(avatarUrl !== undefined ? { avatarUrl } : {}),\n ...(handle !== undefined ? { handle } : {}),\n });\n const enrichedUser = setCurrentUser(user);\n return enrichedUser;\n}\n\n/**\n * Verify user's email with a verification token.\n *\n * @example\n * ```ts\n * await verifyEmail({ token: 'verification-token' });\n * ```\n * @param options.token - The email verification token.\n */\nexport async function verifyEmail(options: { token: string }) {\n const { token } = options;\n await callMethod<{ user: RawUserData }>('_system.user.verifyEmail', { token });\n}\n\n/**\n * Resend the verification email for a given email address.\n * The email is only sent if the address is registered and not yet verified.\n * A generic response is always returned to avoid leaking account information.\n *\n * @example\n * ```ts\n * await resendEmailVerification({ email: 'user@example.com' });\n * ```\n * @param options.email - The email address to resend verification to.\n */\nexport async function resendEmailVerification(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.resendEmailVerification', { email });\n}\n\n/**\n * Logout the current user.\n *\n */\nexport async function logout() {\n await callMethod('_system.user.logout');\n setCurrentUser(null);\n}\n\n/**\n * Send reset password token.\n * @param options.email - The email of the user.\n */\nexport async function sendResetPasswordToken(options: { email: string }) {\n const { email } = options;\n await callMethod('_system.user.sendResetPasswordToken', {\n email,\n });\n}\n\n/**\n * Reset password.\n * @param options.token - The password reset token.\n * @param options.password - The new password.\n */\nexport async function resetPassword(options: { token: string; password: string }) {\n const { token, password } = options;\n await callMethod('_system.user.resetPassword', {\n token,\n password,\n });\n}\n\n/**\n * Get the current auth token associated with the current session.\n * @returns The auth token or undefined if not authenticated.\n */\nexport function getAuthToken(): string | undefined {\n return getLocalStorageSession()?.authToken;\n}\n\nexport function getClientInfo(): ClientInfo {\n return {\n screenWidth: window.screen.width,\n screenHeight: window.screen.height,\n windowWidth: window.innerWidth,\n windowHeight: window.innerHeight,\n pixelRatio: window.devicePixelRatio,\n orientation: window.screen.orientation?.type ?? null,\n };\n}\n","export type ErrorHandler = (error: Error, methodName: string) => void;\n\nlet errorHandler: ErrorHandler = (error, methodName) => {\n console.error(`Error calling method '${methodName}':`, error);\n};\n\nexport function setErrorHandler(handler: ErrorHandler) {\n errorHandler = handler;\n}\n\nexport function handleError(error: Error, methodName: string) {\n return errorHandler(error, methodName);\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { handleError } from '@/client/errorHandler';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nexport class MethodError extends Error {\n status: number;\n\n constructor(message: string, status: number) {\n super(message);\n this.name = 'MethodError';\n this.status = status;\n }\n}\n\nexport type MethodArgs = Record<string, unknown>;\n\nexport type CallMethodOptions = {\n errorHandler?: (error: Error, methodName: string) => void;\n};\n\nexport async function callMethod<T = unknown>(\n methodName: string,\n args: MethodArgs = {},\n options: CallMethodOptions = {}\n): Promise<T> {\n try {\n return await call<T>(`/api/_internal/method/${methodName}`, args);\n } catch (error) {\n const handler = options.errorHandler ?? handleError;\n handler(error as Error, methodName);\n throw error;\n }\n}\n\nasync function call<T = unknown>(endpoint: string, args: MethodArgs): Promise<T> {\n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new MethodError(error, response.status);\n }\n\n const text = await response.text();\n const result = text ? JSON.parse(text) : undefined;\n if (!result) {\n throw new Error('Invalid response from server');\n }\n\n return reviveResponseTypes(result.data, result.typeMap);\n}\n","import { AppConfig, ConfigKey, Configs } from './types';\n\nlet config: Record<ConfigKey, AppConfig> = {};\n\n/**\n * @sidebarTitle getConfig (client)\n *\n * @param key\n * @returns\n */\nexport function getConfig(key: ConfigKey) {\n return config[key]?.value;\n}\n\nexport function _setConfig(configs: Configs) {\n config = configs;\n}\n","import { create } from 'zustand';\nimport { z } from 'zod';\nimport { callMethod } from './method';\nimport { _setConfig } from '../config/client';\nimport { setLocalStorageSession } from './localStorage';\nimport { time } from '../time';\nimport { Configs } from '../config/types';\n\ntype User = {\n id: string;\n handle: string;\n roles: string[];\n hasRole: (role: string) => boolean;\n requireRole: (role: string) => void;\n firstName?: string;\n lastName?: string;\n avatarUrl?: string;\n};\n\ntype SessionStore = {\n user: User | null;\n setUser: (user: User | null) => void;\n};\n\nexport const useSessionStore = create<SessionStore>((set) => ({\n user: null,\n setUser: (user) => set({ user }),\n}));\n\nlet isInitialized = false;\nconst SESSION_HEARTBEAT_INTERVAL = time.seconds(30);\nlet heartbeatTimer: ReturnType<typeof setTimeout> | null = null;\n\nconst userSchema = z.object({\n id: z.string(),\n handle: z.string(),\n roles: z.array(z.string()),\n firstName: z.string().optional(),\n lastName: z.string().optional(),\n avatarUrl: z.string().optional(),\n});\n\nfunction parseUser(user: unknown): User | null {\n if (!user) {\n return null;\n }\n\n const result = userSchema.safeParse(user);\n\n if (!result.success) {\n console.error('Session Error: Invalid user payload', result.error);\n return null;\n }\n\n const parsedData = result.data;\n\n return Object.freeze({\n ...parsedData,\n firstName: parsedData.firstName ?? undefined,\n lastName: parsedData.lastName ?? undefined,\n avatarUrl: parsedData.avatarUrl ?? undefined,\n hasRole: (role: string) => parsedData.roles.includes(role),\n requireRole: (role: string) => {\n if (!parsedData.roles.includes(role)) {\n throw new Error(`Access denied - role '${role}' required`);\n }\n },\n });\n}\n\nexport async function initSession() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n const { configs, session, user } = await callMethod<{\n configs: Configs;\n session: object;\n user: object;\n }>('_system.session.init');\n _setConfig(configs);\n setLocalStorageSession(session);\n\n useSessionStore.getState().setUser(parseUser(user));\n\n await loopSessionHeartbeat();\n}\n\nasync function loopSessionHeartbeat() {\n try {\n await callMethod('_system.session.heartbeat', {}, { errorHandler: () => {} });\n } catch {\n // Silently ignore heartbeat errors - they're expected during HMR/reconnects\n }\n heartbeatTimer = setTimeout(loopSessionHeartbeat, SESSION_HEARTBEAT_INTERVAL);\n}\n\nexport function setCurrentUser(user: unknown) {\n const enrichedUser = parseUser(user);\n useSessionStore.getState().setUser(enrichedUser);\n return enrichedUser;\n}\n\nexport function getHeartbeatTimer() {\n return heartbeatTimer;\n}\n\nexport function stopHeartbeatTimer() {\n if (heartbeatTimer) {\n clearTimeout(heartbeatTimer);\n heartbeatTimer = null;\n }\n}\n\n/**\n * `useSession` is a hook that returns the current user, and in the future will also return other details about the current session.\n *\n * @example\n * ```ts\n * import { useSession } from 'modelence/client';\n *\n * function MyComponent() {\n * const { user } = useSession();\n * return <div>{user?.handle}</div>;\n * }\n * ```\n */\nexport function useSession() {\n const user = useSessionStore((state) => state.user);\n return { user };\n}\n","/*\n The \"use client\" directive is specifically for the Next.js layout component, which is rendered on the server by default.\n Because of this, we are explicitly marking it as a client component, so we can render this component on the client\n and properly initialize config on the client side.\n \n While this is specific to Next.js, it is simply ignored outside of Next.js and should not cause errors.\n*/\n'use client';\n\nimport React, { useState, useEffect, ReactNode } from 'react';\nimport { initSession } from './session';\n\ninterface AppProviderProps {\n children: ReactNode;\n loadingElement?: ReactNode;\n}\n\nlet isInitialized = false;\n\nexport function AppProvider({ children, loadingElement }: AppProviderProps) {\n const [isLoading, setIsLoading] = useState(true);\n\n useEffect(() => {\n async function initConfig() {\n if (isInitialized) {\n return;\n }\n\n isInitialized = true;\n\n await initSession();\n setIsLoading(false);\n }\n\n initConfig();\n }, []);\n\n if (isLoading) {\n return loadingElement ?? <div>Loading...</div>;\n }\n\n return children;\n}\n","import React from 'react';\nimport ReactDOM from 'react-dom/client';\nimport { AppProvider } from '../client';\nimport { setErrorHandler, ErrorHandler } from './errorHandler';\n\nexport function renderApp({\n loadingElement,\n routesElement,\n favicon,\n errorHandler,\n}: {\n loadingElement: React.ReactNode;\n routesElement: React.ReactNode;\n favicon?: string;\n errorHandler?: ErrorHandler;\n}) {\n if (errorHandler) {\n setErrorHandler(errorHandler);\n }\n\n window.addEventListener('unload', () => {\n // The presence of any 'unload' event handler, even empty,\n // prevents bfcache in most browsers\n });\n\n ReactDOM.createRoot(document.getElementById('root')!).render(\n <React.StrictMode>\n <AppProvider loadingElement={loadingElement}>{routesElement}</AppProvider>\n </React.StrictMode>\n );\n\n if (favicon) {\n const link = document.querySelector(\"link[rel~='icon']\") as HTMLLinkElement;\n if (!link) {\n const newLink = document.createElement('link');\n newLink.rel = 'icon';\n newLink.href = favicon;\n document.head.appendChild(newLink);\n } else {\n link.href = favicon;\n }\n }\n}\n","import io, { Socket } from 'socket.io-client';\nimport { WebsocketClientProvider } from '../types';\nimport { ClientChannel } from '../clientChannel';\nimport { getAuthToken, getClientInfo } from '@/auth/client';\nimport { reviveResponseTypes } from '@/methods/serialize';\n\nlet socketClient: Socket | null = null;\n\ninterface ActiveLiveSubscription {\n subscriptionId: string;\n method: string;\n args: Record<string, unknown>;\n}\nconst activeLiveSubscriptions = new Map<string, ActiveLiveSubscription>();\n\nfunction getSocket(): Socket {\n if (!socketClient) {\n throw new Error('WebSocket not initialized. Call startWebsockets() first.');\n }\n return socketClient;\n}\n\nfunction resubscribeAll() {\n const authToken = getAuthToken();\n const clientInfo = getClientInfo();\n for (const sub of activeLiveSubscriptions.values()) {\n socketClient?.emit('subscribeLiveQuery', {\n subscriptionId: sub.subscriptionId,\n method: sub.method,\n args: sub.args,\n authToken,\n clientInfo,\n });\n }\n}\n\nfunction init(props: { channels?: ClientChannel<unknown>[] }) {\n socketClient = io('/', {\n transports: ['websocket'],\n auth: {\n token: getAuthToken(),\n },\n });\n\n // Subscribe to all live queries on connect/reconnect\n socketClient.on('connect', () => {\n if (activeLiveSubscriptions.size > 0) {\n console.log(\n `[Modelence] WebSocket reconnected, re-subscribing to ${activeLiveSubscriptions.size} live queries`\n );\n resubscribeAll();\n }\n });\n\n props.channels?.forEach((channel) => channel.init());\n}\n\nfunction on<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().on(category, listener);\n}\n\nfunction once<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().once(category, listener);\n}\n\nfunction off<T = unknown>({\n category,\n listener,\n}: {\n category: string;\n listener: (data: T) => void;\n}) {\n getSocket().off(category, listener);\n}\n\nfunction emit({ eventName, category, id }: { eventName: string; category: string; id: string }) {\n getSocket().emit(eventName, `${category}:${id}`);\n}\n\nfunction joinChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'joinChannel',\n category,\n id,\n });\n}\n\nfunction leaveChannel({ category, id }: { category: string; id: string }) {\n emit({\n eventName: 'leaveChannel',\n category,\n id,\n });\n}\n\nlet liveQueryCounter = 0;\n\nexport function subscribeLiveQuery<T = unknown>(\n method: string,\n args: Record<string, unknown>,\n onData: (data: T) => void,\n onError?: (error: string) => void\n): () => void {\n const subscriptionId = `sub-${++liveQueryCounter}-${Date.now()}`;\n\n const handleData = ({\n subscriptionId: sid,\n data,\n typeMap,\n }: {\n subscriptionId: string;\n data: T;\n typeMap?: Record<string, unknown>;\n }) => {\n if (sid === subscriptionId) {\n onData(reviveResponseTypes(data, typeMap));\n }\n };\n\n const handleError = ({\n subscriptionId: sid,\n error,\n }: {\n subscriptionId: string;\n error: string;\n }) => {\n if (sid === subscriptionId) {\n console.error(`[Modelence] Live query error for ${method}:`, error);\n onError?.(error);\n }\n };\n\n const socket = getSocket();\n socket.on('liveQueryData', handleData);\n socket.on('liveQueryError', handleError);\n\n activeLiveSubscriptions.set(subscriptionId, { subscriptionId, method, args });\n\n // Only emit if already connected; otherwise the connect handler will handle it\n if (socket.connected) {\n socket.emit('subscribeLiveQuery', {\n subscriptionId,\n method,\n args,\n authToken: getAuthToken(),\n clientInfo: getClientInfo(),\n });\n }\n\n // Return unsubscribe function\n return () => {\n activeLiveSubscriptions.delete(subscriptionId);\n socket.emit('unsubscribeLiveQuery', { subscriptionId });\n socket.off('liveQueryData', handleData);\n socket.off('liveQueryError', handleError);\n };\n}\n\nconst websocketProvider: WebsocketClientProvider = {\n init,\n on,\n once,\n off,\n emit,\n joinChannel,\n leaveChannel,\n};\n\nexport default websocketProvider;\n","import { ClientChannel } from './clientChannel';\nimport websocketProvider, { subscribeLiveQuery } from './socketio/client';\nimport { WebsocketClientProvider } from './types';\n\nexport { subscribeLiveQuery };\n\nlet websocketClientProvider: WebsocketClientProvider | null = null;\n\nexport function setWebsocketClientProvider(provider: WebsocketClientProvider) {\n websocketClientProvider = provider;\n}\n\nexport function getWebsocketClientProvider() {\n return websocketClientProvider;\n}\n\nexport function startWebsockets(props?: {\n provider?: WebsocketClientProvider;\n channels?: ClientChannel[];\n}) {\n if (websocketClientProvider) {\n console.warn('WebSocket already initialized. Skipping initialization.');\n return;\n }\n\n const provider = props?.provider || websocketProvider;\n provider.init({\n channels: props?.channels,\n });\n setWebsocketClientProvider(provider);\n}\n","import { getWebsocketClientProvider } from './client';\n\nexport class ClientChannel<T = unknown> {\n public readonly category: string;\n private readonly onMessage: (data: T) => void;\n\n constructor(category: string, onMessage: (data: T) => void) {\n this.category = category;\n this.onMessage = onMessage;\n }\n\n init() {\n getWebsocketClientProvider()?.on({\n category: this.category,\n listener: this.onMessage,\n });\n }\n\n joinChannel(id: string) {\n getWebsocketClientProvider()?.joinChannel({\n category: this.category,\n id,\n });\n }\n\n leaveChannel(id: string) {\n getWebsocketClientProvider()?.leaveChannel({\n category: this.category,\n id,\n });\n }\n}\n","import { callMethod } from '../client/method';\nimport type { FileVisibility, GetUploadUrlResult } from './types';\n\ntype UploadFileParams = {\n filePath: string;\n contentType: string;\n visibility: FileVisibility;\n};\n\ntype UploadFileResult = {\n filePath: string;\n};\n\nexport async function uploadFile(\n file: File | Blob,\n { filePath, contentType, visibility }: UploadFileParams\n): Promise<UploadFileResult> {\n const {\n url,\n fields,\n filePath: resolvedFilePath,\n } = await callMethod<GetUploadUrlResult>('_system.files.getUploadUrl', {\n filePath,\n contentType,\n visibility,\n });\n\n const formData = new FormData();\n for (const [key, value] of Object.entries(fields)) {\n formData.append(key, value);\n }\n formData.append('file', file);\n\n const uploadResponse = await fetch(url, {\n method: 'POST',\n body: formData,\n });\n\n if (!uploadResponse.ok) {\n throw new Error(`Failed to upload file: HTTP status: ${uploadResponse.status}`);\n }\n\n return { filePath: resolvedFilePath };\n}\n\nexport async function deleteFile(filePath: string): Promise<void> {\n await callMethod('_system.files.deleteFile', { filePath });\n}\n\nexport async function downloadFile(filePath: string): Promise<{ downloadUrl: string }> {\n return callMethod('_system.files.downloadFile', { filePath });\n}\n\nexport async function getFileUrl(filePath: string): Promise<{ url: string }> {\n return callMethod('_system.files.getFileUrl', { filePath });\n}\n","import React from 'react';\n\nimport { AppProvider as OriginalAppProvider } from './client/AppProvider';\n\nexport { getConfig } from './config/client';\n\nexport const AppProvider =\n 'useClient' in React\n ? // @ts-ignore: React.useClient only exists in Next.js\n React.useClient(OriginalAppProvider)\n : OriginalAppProvider;\n\nexport { renderApp } from './client/renderApp';\nexport { callMethod, MethodError, type MethodArgs } from './client/method';\nexport { useSession } from './client/session';\nexport {\n signupWithPassword,\n loginWithPassword,\n verifyEmail,\n updateProfile,\n resendEmailVerification,\n logout,\n sendResetPasswordToken,\n resetPassword,\n type UserInfo,\n} from './auth/client';\nexport {\n getWebsocketClientProvider,\n setWebsocketClientProvider,\n startWebsockets,\n subscribeLiveQuery,\n} from './websocket/client';\nexport { ClientChannel } from './websocket/clientChannel';\nexport { getLocalStorageSession } from './client/localStorage';\nexport { uploadFile, deleteFile, downloadFile, getFileUrl } from './files/client';\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { C as ConfigSchema, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-
|
|
1
|
+
export { C as ConfigSchema, a as WebsocketClientProvider, W as WebsocketServerProvider } from './types-CSQ5Qjb4.js';
|
|
2
2
|
export { M as ModelenceConfig } from './index-CwdohC5n.js';
|
|
3
3
|
import 'http';
|
|
4
4
|
import 'mongodb';
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-
|
|
2
|
-
//# sourceMappingURL=package-
|
|
1
|
+
export{l as author,i as bin,n as bugs,s as default,q as dependencies,d as description,p as devDependencies,g as exports,h as files,o as homepage,m as license,e as main,b as name,r as peerDependencies,k as repository,j as scripts,a as type,f as types,c as version}from'./chunk-S7LR4K37.js';//# sourceMappingURL=package-D325NQFE.js.map
|
|
2
|
+
//# sourceMappingURL=package-D325NQFE.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"package-D325NQFE.js"}
|
package/dist/server.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { A as AppServer } from './index-CwdohC5n.js';
|
|
2
|
-
import { M as MethodDefinition, C as ConfigSchema, S as ServerChannel, A as AuthSuccessProps,
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
import { M as MethodDefinition, C as ConfigSchema, S as ServerChannel, d as SignupProps, U as UpdateProfileProps, A as AuthSuccessProps, e as AuthErrorProps, f as User, W as WebsocketServerProvider, R as RoleDefinition, b as ConfigKey, g as AppConfig, h as Session, i as UserInfo, j as Role } from './types-CSQ5Qjb4.js';
|
|
3
|
+
export { k as ConfigType } from './types-CSQ5Qjb4.js';
|
|
4
|
+
import { S as Store, R as RouteDefinition, C as CronJobInputParams, a as RateLimitRule, E as EmailProvider, I as InferDocumentType, b as RateLimitType, c as EmailPayload } from './types-BtENzxGq.js';
|
|
5
|
+
export { H as HttpMethod, d as RouteHandler, e as RouteParams, f as RouteResponse, s as schema } from './types-BtENzxGq.js';
|
|
5
6
|
import { ObjectId as ObjectId$1 } from 'mongodb';
|
|
6
7
|
export { ObjectId } from 'mongodb';
|
|
7
8
|
import * as zod from 'zod';
|
|
9
|
+
import { F as FileVisibility, G as GetUploadUrlResult } from './types-DLDzAym7.js';
|
|
8
10
|
import 'express';
|
|
9
11
|
import 'http';
|
|
10
12
|
|
|
@@ -107,6 +109,11 @@ type EmailConfig = {
|
|
|
107
109
|
emailVerifiedRedirectUrl?: string;
|
|
108
110
|
};
|
|
109
111
|
|
|
112
|
+
type GenerateHandleProps = {
|
|
113
|
+
email: string;
|
|
114
|
+
firstName?: string;
|
|
115
|
+
lastName?: string;
|
|
116
|
+
};
|
|
110
117
|
/**
|
|
111
118
|
* Callback options for authentication operations
|
|
112
119
|
*/
|
|
@@ -125,6 +132,12 @@ type AuthOption = {
|
|
|
125
132
|
*
|
|
126
133
|
* startApp({
|
|
127
134
|
* auth: {
|
|
135
|
+
* validateSignup: ({ email, firstName, lastName, password, handle, avatarUrl }) => {
|
|
136
|
+
* // Validating the signup data
|
|
137
|
+
* if (!email || !password) {
|
|
138
|
+
* throw new Error('Email and password are required');
|
|
139
|
+
* }
|
|
140
|
+
* },
|
|
128
141
|
* onAfterLogin: ({ user }) => {
|
|
129
142
|
* console.log('User logged in:', user.name);
|
|
130
143
|
* // Redirect to dashboard
|
|
@@ -139,18 +152,26 @@ type AuthOption = {
|
|
|
139
152
|
* },
|
|
140
153
|
* onSignupError: ({ error }) => {
|
|
141
154
|
* console.error('Signup failed:', error.message);
|
|
142
|
-
* }
|
|
155
|
+
* },
|
|
156
|
+
* generateHandle: ({ email }) => {
|
|
157
|
+
* console.log('Generating handle for:', email);
|
|
158
|
+
* // Generate handle
|
|
159
|
+
* return 'user123';
|
|
160
|
+
* },
|
|
143
161
|
* }
|
|
144
162
|
* });
|
|
145
163
|
* ```
|
|
146
164
|
*/
|
|
147
165
|
type AuthConfig = {
|
|
166
|
+
validateSignup?: (props: SignupProps) => void | Promise<void>;
|
|
167
|
+
validateProfileUpdate?: (props: UpdateProfileProps) => void | Promise<void>;
|
|
148
168
|
onAfterLogin?: (props: AuthSuccessProps) => void;
|
|
149
169
|
onLoginError?: (props: AuthErrorProps) => void;
|
|
150
170
|
onAfterSignup?: (props: AuthSuccessProps) => void;
|
|
151
171
|
onSignupError?: (props: AuthErrorProps) => void;
|
|
152
172
|
onAfterEmailVerification?: (props: AuthSuccessProps) => void;
|
|
153
173
|
onEmailVerificationError?: (props: AuthErrorProps) => void;
|
|
174
|
+
generateHandle?: (props: GenerateHandleProps) => Promise<string> | string;
|
|
154
175
|
/** deprecated: use onAfterLogin and onLoginError */
|
|
155
176
|
login?: AuthOption;
|
|
156
177
|
/** deprecated: user onAfterSignup and onSignupError */
|
|
@@ -458,6 +479,9 @@ declare const usersCollection: Store<{
|
|
|
458
479
|
verified: boolean;
|
|
459
480
|
}>, "many">>;
|
|
460
481
|
status: zod.ZodOptional<zod.ZodEnum<["active", "disabled", "deleted"]>>;
|
|
482
|
+
firstName: zod.ZodOptional<zod.ZodString>;
|
|
483
|
+
lastName: zod.ZodOptional<zod.ZodString>;
|
|
484
|
+
avatarUrl: zod.ZodOptional<zod.ZodString>;
|
|
461
485
|
createdAt: zod.ZodDate;
|
|
462
486
|
disabledAt: zod.ZodOptional<zod.ZodDate>;
|
|
463
487
|
deletedAt: zod.ZodOptional<zod.ZodDate>;
|
|
@@ -518,6 +542,9 @@ declare const usersCollection: Store<{
|
|
|
518
542
|
verified: boolean;
|
|
519
543
|
}>, "many">>;
|
|
520
544
|
status: zod.ZodOptional<zod.ZodEnum<["active", "disabled", "deleted"]>>;
|
|
545
|
+
firstName: zod.ZodOptional<zod.ZodString>;
|
|
546
|
+
lastName: zod.ZodOptional<zod.ZodString>;
|
|
547
|
+
avatarUrl: zod.ZodOptional<zod.ZodString>;
|
|
521
548
|
createdAt: zod.ZodDate;
|
|
522
549
|
disabledAt: zod.ZodOptional<zod.ZodDate>;
|
|
523
550
|
deletedAt: zod.ZodOptional<zod.ZodDate>;
|
|
@@ -565,7 +592,7 @@ declare const usersCollection: Store<{
|
|
|
565
592
|
hash: string;
|
|
566
593
|
} | undefined;
|
|
567
594
|
}>;
|
|
568
|
-
}>, "handle" | "emails" | "status" | "createdAt" | "disabledAt" | "deletedAt" | "roles" | "authMethods"> & {
|
|
595
|
+
}>, "handle" | "emails" | "status" | "firstName" | "lastName" | "avatarUrl" | "createdAt" | "disabledAt" | "deletedAt" | "roles" | "authMethods"> & {
|
|
569
596
|
_id: ObjectId;
|
|
570
597
|
}, ...args: any[]) => any>>;
|
|
571
598
|
|
|
@@ -657,4 +684,19 @@ declare function authenticate(authToken: string | null): Promise<{
|
|
|
657
684
|
|
|
658
685
|
declare function sendEmail(payload: EmailPayload): Promise<void> | undefined;
|
|
659
686
|
|
|
660
|
-
|
|
687
|
+
type DownloadFileResult = {
|
|
688
|
+
downloadUrl: string;
|
|
689
|
+
};
|
|
690
|
+
type GetFileUrlResult = {
|
|
691
|
+
url: string;
|
|
692
|
+
};
|
|
693
|
+
declare function getUploadUrl({ filePath, contentType, visibility, }: {
|
|
694
|
+
filePath: string;
|
|
695
|
+
contentType: string;
|
|
696
|
+
visibility: FileVisibility;
|
|
697
|
+
}): Promise<GetUploadUrlResult>;
|
|
698
|
+
declare function deleteFile(filePath: string): Promise<void>;
|
|
699
|
+
declare function downloadFile(filePath: string): Promise<DownloadFileResult>;
|
|
700
|
+
declare function getFileUrl(filePath: string): Promise<GetFileUrlResult>;
|
|
701
|
+
|
|
702
|
+
export { type AppOptions, type AuthConfig, type AuthOption, type CloudBackendConnectResponse, ConfigSchema, CronJobInputParams, FileVisibility, LiveData, type LiveDataConfig, type LiveQueryCleanup, type LiveQueryPublish, type LiveQueryWatch, Module, RateLimitRule, RateLimitType, RoleDefinition, RouteDefinition, type SecurityConfig, ServerChannel, Store, UserInfo, authenticate, consumeRateLimit, createQuery, usersCollection as dbUsers, deleteFile, deleteUser, disableUser, downloadFile, getConfig, getFileUrl, getUploadUrl, sendEmail, startApp };
|