retrex-extensibles-core 2.0.7 → 2.0.9
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/core/hooks/useEvents.cjs +7 -2
- package/dist/core/hooks/useEvents.cjs.map +1 -1
- package/dist/core/hooks/useEvents.js +7 -2
- package/dist/core/hooks/useEvents.js.map +1 -1
- package/dist/core/hooks/useRoutes.cjs.map +1 -1
- package/dist/core/hooks/useRoutes.js.map +1 -1
- package/dist/core/hooks/useUtils.cjs +7 -2
- package/dist/core/hooks/useUtils.cjs.map +1 -1
- package/dist/core/hooks/useUtils.js +7 -2
- package/dist/core/hooks/useUtils.js.map +1 -1
- package/dist/index.cjs +14 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +14 -4
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -35,7 +35,6 @@ __export(useEvents_exports, {
|
|
|
35
35
|
module.exports = __toCommonJS(useEvents_exports);
|
|
36
36
|
var import_promises = __toESM(require("fs/promises"), 1);
|
|
37
37
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
38
|
-
var import_url = require("url");
|
|
39
38
|
var import_chalk = __toESM(require("chalk"), 1);
|
|
40
39
|
|
|
41
40
|
// src/core/hooks/useSettings.ts
|
|
@@ -106,6 +105,12 @@ var useSettings = {
|
|
|
106
105
|
// src/core/hooks/useEvents.ts
|
|
107
106
|
var events = [];
|
|
108
107
|
var logPrefix;
|
|
108
|
+
function toFileUrl(filePath) {
|
|
109
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
110
|
+
if (normalized.startsWith("file://")) return normalized;
|
|
111
|
+
const prefix = normalized.startsWith("/") ? "file://" : "file:///";
|
|
112
|
+
return `${prefix}${encodeURI(normalized)}`;
|
|
113
|
+
}
|
|
109
114
|
var useEvents = {
|
|
110
115
|
setPrefix: (prefix) => {
|
|
111
116
|
logPrefix = prefix;
|
|
@@ -139,7 +144,7 @@ var useEvents = {
|
|
|
139
144
|
const fullPath = import_node_path2.default.resolve(eventsDir, file);
|
|
140
145
|
if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
|
|
141
146
|
try {
|
|
142
|
-
const imported = await import((
|
|
147
|
+
const imported = await import(toFileUrl(fullPath));
|
|
143
148
|
const controller = imported.default || imported[Object.keys(imported)[0]];
|
|
144
149
|
if (!controller || !controller.onRegister && !controller.onEvent) {
|
|
145
150
|
console.warn(logPrefix + import_chalk.default.yellow(`\u26A0\uFE0F Skipping non-controller file: ${file}`));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/hooks/useEvents.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'url';\nimport { Server as SocketIOServer, Socket } from 'socket.io';\nimport chalk from 'chalk';\nimport { useSettings } from './useSettings';\n\ninterface EventController {\n label: string;\n onRegister?: (io: SocketIOServer) => void;\n onEvent?: (socket: Socket, event: any) => void;\n}\n\nlet events: EventController[] = [];\nlet logPrefix: any;\n\nexport const useEvents = {\n setPrefix: (prefix: any) => {\n logPrefix = prefix;\n },\n register: async (io: SocketIOServer) => {\n const { modules, services, events: appEventsPath } = useSettings.getPaths();\n\n const sources = [\n { type: 'module', root: modules },\n { type: 'service', root: services },\n { type: 'app', root: appEventsPath },\n ];\n\n for (const source of sources) {\n try {\n const dirs = await fs.readdir(source.root, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (!dir.isDirectory()) continue;\n\n const basePath = path.join(source.root, dir.name);\n const eventsDir = source.type === 'app' ? basePath : path.join(basePath, 'events');\n\n let eventFiles: string[] = [];\n try {\n console.log(logPrefix + chalk.blue(`🔍 Searching for events in: ${eventsDir}`));\n eventFiles = await fs.readdir(eventsDir);\n console.log(logPrefix + chalk.blue(`🔍 Found events in: ${eventsDir}`));\n console.log(logPrefix + chalk.gray(`📂 Directory: ${eventsDir}`))\n console.log(logPrefix + chalk.gray(`📄 Files: ${eventFiles.join(', ')} [${eventFiles.length}]`));\n } catch {\n console.warn(logPrefix + chalk.gray(`⚠️ No events directory found: ${eventsDir}`));\n continue;\n }\n\n for (const file of eventFiles) {\n const fullPath = path.resolve(eventsDir, file);\n if (!file.endsWith('.ts') && !file.endsWith('.js')) continue;\n\n try {\n const imported = await import(pathToFileURL(fullPath).href);\n const controller: EventController = imported.default || imported[Object.keys(imported)[0]];\n\n if (!controller || (!controller.onRegister && !controller.onEvent)) {\n console.warn(logPrefix + chalk.yellow(`⚠️ Skipping non-controller file: ${file}`));\n continue;\n }\n\n const label = controller.label || file.replace(/\\.(ts|js)$/, '');\n\n if (controller.onRegister) {\n controller.onRegister(io);\n }\n\n events.push({\n label,\n onRegister: controller.onRegister,\n onEvent: controller.onEvent,\n });\n\n console.log(logPrefix + chalk.green(`✅ Registered event: ${label}`));\n\n if (controller.onEvent) {\n io.on('connection', (socket) => {\n socket.on(label, (data: any) => controller.onEvent!(socket, data));\n });\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to import event file: ${fullPath}`));\n console.error(logPrefix + err);\n }\n }\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to load events from source: ${source.root}`));\n console.error(logPrefix + err);\n }\n }\n },\n\n load: async (io: SocketIOServer) => {\n await useEvents.register(io);\n },\n\n get: async (): Promise<EventController[]> => {\n if (events.length === 0) {\n console.warn(logPrefix + 'No events loaded yet. Did you call useEvents.load(io)?');\n }\n return events;\n }\n};\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath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AA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,KAAK,YAAY,aAAAA,QAAM,IAAI,6CAAwC,OAAO,IAAI,EAAE,CAAC;AACzF,gBAAQ,MAAM,YAAY,GAAG;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,OAAuB;AAClC,UAAM,UAAU,SAAS,EAAE;AAAA,EAC7B;AAAA,EAEA,KAAK,YAAwC;AAC3C,QAAI,OAAO,WAAW,GAAG;AACvB,cAAQ,KAAK,YAAY,wDAAwD;AAAA,IACnF;AACA,WAAO;AAAA,EACT;AACF;","names":["import_node_path","import_node_fs","fs","fs","fs","path","chalk"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/hooks/useEvents.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { Server as SocketIOServer, Socket } from 'socket.io';\nimport chalk from 'chalk';\nimport { useSettings } from './useSettings';\n\ninterface EventController {\n label: string;\n onRegister?: (io: SocketIOServer) => void;\n onEvent?: (socket: Socket, event: any) => void;\n}\n\nlet events: EventController[] = [];\nlet logPrefix: any;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport const useEvents = {\n setPrefix: (prefix: any) => {\n logPrefix = prefix;\n },\n register: async (io: SocketIOServer) => {\n const { modules, services, events: appEventsPath } = useSettings.getPaths();\n\n const sources = [\n { type: 'module', root: modules },\n { type: 'service', root: services },\n { type: 'app', root: appEventsPath },\n ];\n\n for (const source of sources) {\n try {\n const dirs = await fs.readdir(source.root, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (!dir.isDirectory()) continue;\n\n const basePath = path.join(source.root, dir.name);\n const eventsDir = source.type === 'app' ? basePath : path.join(basePath, 'events');\n\n let eventFiles: string[] = [];\n try {\n console.log(logPrefix + chalk.blue(`🔍 Searching for events in: ${eventsDir}`));\n eventFiles = await fs.readdir(eventsDir);\n console.log(logPrefix + chalk.blue(`🔍 Found events in: ${eventsDir}`));\n console.log(logPrefix + chalk.gray(`📂 Directory: ${eventsDir}`))\n console.log(logPrefix + chalk.gray(`📄 Files: ${eventFiles.join(', ')} [${eventFiles.length}]`));\n } catch {\n console.warn(logPrefix + chalk.gray(`⚠️ No events directory found: ${eventsDir}`));\n continue;\n }\n\n for (const file of eventFiles) {\n const fullPath = path.resolve(eventsDir, file);\n if (!file.endsWith('.ts') && !file.endsWith('.js')) continue;\n\n try {\n const imported = await import(toFileUrl(fullPath));\n const controller: EventController = imported.default || imported[Object.keys(imported)[0]];\n\n if (!controller || (!controller.onRegister && !controller.onEvent)) {\n console.warn(logPrefix + chalk.yellow(`⚠️ Skipping non-controller file: ${file}`));\n continue;\n }\n\n const label = controller.label || file.replace(/\\.(ts|js)$/, '');\n\n if (controller.onRegister) {\n controller.onRegister(io);\n }\n\n events.push({\n label,\n onRegister: controller.onRegister,\n onEvent: controller.onEvent,\n });\n\n console.log(logPrefix + chalk.green(`✅ Registered event: ${label}`));\n\n if (controller.onEvent) {\n io.on('connection', (socket) => {\n socket.on(label, (data: any) => controller.onEvent!(socket, data));\n });\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to import event file: ${fullPath}`));\n console.error(logPrefix + err);\n }\n }\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to load events from source: ${source.root}`));\n console.error(logPrefix + err);\n }\n }\n },\n\n load: async (io: SocketIOServer) => {\n await useEvents.register(io);\n },\n\n get: async (): Promise<EventController[]> => {\n if (events.length === 0) {\n console.warn(logPrefix + 'No events loaded yet. Did you call useEvents.load(io)?');\n }\n return events;\n }\n};\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath}:`, err);\n// }\n// }\n// }\n// }\n// }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,sBAAe;AACf,IAAAA,oBAAiB;AAEjB,mBAAkB;;;ACAlB,IAAAC,kBAAe;;;ACDf,qBAAe;AACf,uBAAiB;AAiBV,SAAS,SAAS,UAAuB;AAC9C,MAAI,CAAC,eAAAC,QAAG,WAAW,QAAQ,EAAG,QAAO;AACrC,SAAO,KAAK,MAAM,eAAAA,QAAG,aAAa,UAAU,OAAO,CAAC;AACtD;AAEO,SAAS,SAAS,UAAkB,MAAW;AACpD,iBAAAA,QAAG,cAAc,UAAU,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG,OAAO;AACnE;;;ADnBA,IAAM,eAAgC;AAAA,EACpC,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WAAW;AACb;AAEA,IAAI,kBAAmC,EAAE,GAAG,aAAa;AACzD,IAAM,WAAW,OAAO,WAAW;AAG5B,IAAM,cAAc;AAAA,EACzB,WAA4B;AAC1B,QAAI,UAAU;AACZ,YAAM,OAAO,SAAS,4BAA4B;AAClD,UAAI,KAAM,mBAAkB;AAAA,IAC9B;AAEA,QAAI,UAAU;AACZ,iBAAW,OAAO,OAAO,KAAK,YAAY,GAAmC;AAC3E,cAAM,YAAY,gBAAgB,GAAG;AACrC,YAAI,CAAC,aAAa,CAAC,gBAAAC,QAAG,WAAW,SAAS,GAAG;AAC3C,0BAAgB,GAAG,IAAI,aAAa,GAAG;AAAA,QACzC;AAAA,M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AAAA,cACtB,CAAC;AAED,sBAAQ,IAAI,YAAY,aAAAA,QAAM,MAAM,4BAAuB,KAAK,EAAE,CAAC;AAEnE,kBAAI,WAAW,SAAS;AACtB,mBAAG,GAAG,cAAc,CAAC,WAAW;AAC9B,yBAAO,GAAG,OAAO,CAAC,SAAc,WAAW,QAAS,QAAQ,IAAI,CAAC;AAAA,gBACnE,CAAC;AAAA,cACH;AAAA,YACF,SAAS,KAAK;AACZ,sBAAQ,KAAK,YAAY,aAAAA,QAAM,IAAI,uCAAkC,QAAQ,EAAE,CAAC;AAChF,sBAAQ,MAAM,YAAY,GAAG;AAAA,YAC/B;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,KAAK,YAAY,aAAAA,QAAM,IAAI,6CAAwC,OAAO,IAAI,EAAE,CAAC;AACzF,gBAAQ,MAAM,YAAY,GAAG;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,OAAuB;AAClC,UAAM,UAAU,SAAS,EAAE;AAAA,EAC7B;AAAA,EAEA,KAAK,YAAwC;AAC3C,QAAI,OAAO,WAAW,GAAG;AACvB,cAAQ,KAAK,YAAY,wDAAwD;AAAA,IACnF;AACA,WAAO;AAAA,EACT;AACF;","names":["import_node_path","import_node_fs","fs","fs","fs","path","chalk"]}
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// src/core/hooks/useEvents.ts
|
|
2
2
|
import fs3 from "fs/promises";
|
|
3
3
|
import path2 from "path";
|
|
4
|
-
import { pathToFileURL } from "url";
|
|
5
4
|
import chalk from "chalk";
|
|
6
5
|
|
|
7
6
|
// src/core/hooks/useSettings.ts
|
|
@@ -72,6 +71,12 @@ var useSettings = {
|
|
|
72
71
|
// src/core/hooks/useEvents.ts
|
|
73
72
|
var events = [];
|
|
74
73
|
var logPrefix;
|
|
74
|
+
function toFileUrl(filePath) {
|
|
75
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
76
|
+
if (normalized.startsWith("file://")) return normalized;
|
|
77
|
+
const prefix = normalized.startsWith("/") ? "file://" : "file:///";
|
|
78
|
+
return `${prefix}${encodeURI(normalized)}`;
|
|
79
|
+
}
|
|
75
80
|
var useEvents = {
|
|
76
81
|
setPrefix: (prefix) => {
|
|
77
82
|
logPrefix = prefix;
|
|
@@ -105,7 +110,7 @@ var useEvents = {
|
|
|
105
110
|
const fullPath = path2.resolve(eventsDir, file);
|
|
106
111
|
if (!file.endsWith(".ts") && !file.endsWith(".js")) continue;
|
|
107
112
|
try {
|
|
108
|
-
const imported = await import(
|
|
113
|
+
const imported = await import(toFileUrl(fullPath));
|
|
109
114
|
const controller = imported.default || imported[Object.keys(imported)[0]];
|
|
110
115
|
if (!controller || !controller.onRegister && !controller.onEvent) {
|
|
111
116
|
console.warn(logPrefix + chalk.yellow(`\u26A0\uFE0F Skipping non-controller file: ${file}`));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/hooks/useEvents.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { pathToFileURL } from 'url';\nimport { Server as SocketIOServer, Socket } from 'socket.io';\nimport chalk from 'chalk';\nimport { useSettings } from './useSettings';\n\ninterface EventController {\n label: string;\n onRegister?: (io: SocketIOServer) => void;\n onEvent?: (socket: Socket, event: any) => void;\n}\n\nlet events: EventController[] = [];\nlet logPrefix: any;\n\nexport const useEvents = {\n setPrefix: (prefix: any) => {\n logPrefix = prefix;\n },\n register: async (io: SocketIOServer) => {\n const { modules, services, events: appEventsPath } = useSettings.getPaths();\n\n const sources = [\n { type: 'module', root: modules },\n { type: 'service', root: services },\n { type: 'app', root: appEventsPath },\n ];\n\n for (const source of sources) {\n try {\n const dirs = await fs.readdir(source.root, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (!dir.isDirectory()) continue;\n\n const basePath = path.join(source.root, dir.name);\n const eventsDir = source.type === 'app' ? basePath : path.join(basePath, 'events');\n\n let eventFiles: string[] = [];\n try {\n console.log(logPrefix + chalk.blue(`🔍 Searching for events in: ${eventsDir}`));\n eventFiles = await fs.readdir(eventsDir);\n console.log(logPrefix + chalk.blue(`🔍 Found events in: ${eventsDir}`));\n console.log(logPrefix + chalk.gray(`📂 Directory: ${eventsDir}`))\n console.log(logPrefix + chalk.gray(`📄 Files: ${eventFiles.join(', ')} [${eventFiles.length}]`));\n } catch {\n console.warn(logPrefix + chalk.gray(`⚠️ No events directory found: ${eventsDir}`));\n continue;\n }\n\n for (const file of eventFiles) {\n const fullPath = path.resolve(eventsDir, file);\n if (!file.endsWith('.ts') && !file.endsWith('.js')) continue;\n\n try {\n const imported = await import(pathToFileURL(fullPath).href);\n const controller: EventController = imported.default || imported[Object.keys(imported)[0]];\n\n if (!controller || (!controller.onRegister && !controller.onEvent)) {\n console.warn(logPrefix + chalk.yellow(`⚠️ Skipping non-controller file: ${file}`));\n continue;\n }\n\n const label = controller.label || file.replace(/\\.(ts|js)$/, '');\n\n if (controller.onRegister) {\n controller.onRegister(io);\n }\n\n events.push({\n label,\n onRegister: controller.onRegister,\n onEvent: controller.onEvent,\n });\n\n console.log(logPrefix + chalk.green(`✅ Registered event: ${label}`));\n\n if (controller.onEvent) {\n io.on('connection', (socket) => {\n socket.on(label, (data: any) => controller.onEvent!(socket, data));\n });\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to import event file: ${fullPath}`));\n console.error(logPrefix + err);\n }\n }\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to load events from source: ${source.root}`));\n console.error(logPrefix + err);\n }\n }\n },\n\n load: async (io: SocketIOServer) => {\n await useEvents.register(io);\n },\n\n get: async (): Promise<EventController[]> => {\n if (events.length === 0) {\n console.warn(logPrefix + 'No events loaded yet. Did you call useEvents.load(io)?');\n }\n return events;\n }\n};\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath}:`, err);\n// }\n// }\n// }\n// }\n// }\n"],"mappings":";AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AACjB,SAAS,qBAAqB;AAE9B,OAAO,WAAW;;;ACDlB,OAAOC,SAAQ;;;ACDf,OAAO,QAAQ;AACf,OAAO,UAAU;AAiBV,SAAS,SAAS,UAAuB;AAC9C,MAAI,CAAC,GAAG,WAAW,QAAQ,EAAG,QAAO;AACrC,SAAO,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;AACtD;AAEO,SAAS,SAAS,UAAkB,MAAW;AACpD,KAAG,cAAc,UAAU,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG,OAAO;AACnE;;;ADnBA,IAAM,eAAgC;AAAA,EACpC,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WAAW;AACb;AAEA,IAAI,kBAAmC,EAAE,GAAG,aAAa;AACzD,IAAM,WAAW,OAAO,WAAW;AAG5B,IAAM,cAAc;AAAA,EACzB,WAA4B;AAC1B,QAAI,UAAU;AACZ,YAAM,OAAO,SAAS,4BAA4B;AAClD,UAAI,KAAM,mBAAkB;AAAA,IAC9B;AAEA,QAAI,UAAU;AACZ,iBAAW,OAAO,OAAO,KAAK,YAAY,GAAmC;AAC3E,cAAM,YAAY,gBAAgB,GAAG;AACrC,YAAI,CAAC,aAAa,CAACC,IAAG,WAAW,SAAS,GAAG;AAC3C,0BAAgB,GAAG,IAAI,aAAa,GAAG;AAAA,QACzC;AAAA,MACF;AAAA,IACF;AAEA,sBAAkB;AAAA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E,CAAC;AAChF,sBAAQ,MAAM,YAAY,GAAG;AAAA,YAC/B;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,KAAK,YAAY,MAAM,IAAI,6CAAwC,OAAO,IAAI,EAAE,CAAC;AACzF,gBAAQ,MAAM,YAAY,GAAG;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,OAAuB;AAClC,UAAM,UAAU,SAAS,EAAE;AAAA,EAC7B;AAAA,EAEA,KAAK,YAAwC;AAC3C,QAAI,OAAO,WAAW,GAAG;AACvB,cAAQ,KAAK,YAAY,wDAAwD;AAAA,IACnF;AACA,WAAO;AAAA,EACT;AACF;","names":["fs","path","fs","fs","fs","path"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/hooks/useEvents.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { Server as SocketIOServer, Socket } from 'socket.io';\nimport chalk from 'chalk';\nimport { useSettings } from './useSettings';\n\ninterface EventController {\n label: string;\n onRegister?: (io: SocketIOServer) => void;\n onEvent?: (socket: Socket, event: any) => void;\n}\n\nlet events: EventController[] = [];\nlet logPrefix: any;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport const useEvents = {\n setPrefix: (prefix: any) => {\n logPrefix = prefix;\n },\n register: async (io: SocketIOServer) => {\n const { modules, services, events: appEventsPath } = useSettings.getPaths();\n\n const sources = [\n { type: 'module', root: modules },\n { type: 'service', root: services },\n { type: 'app', root: appEventsPath },\n ];\n\n for (const source of sources) {\n try {\n const dirs = await fs.readdir(source.root, { withFileTypes: true });\n\n for (const dir of dirs) {\n if (!dir.isDirectory()) continue;\n\n const basePath = path.join(source.root, dir.name);\n const eventsDir = source.type === 'app' ? basePath : path.join(basePath, 'events');\n\n let eventFiles: string[] = [];\n try {\n console.log(logPrefix + chalk.blue(`🔍 Searching for events in: ${eventsDir}`));\n eventFiles = await fs.readdir(eventsDir);\n console.log(logPrefix + chalk.blue(`🔍 Found events in: ${eventsDir}`));\n console.log(logPrefix + chalk.gray(`📂 Directory: ${eventsDir}`))\n console.log(logPrefix + chalk.gray(`📄 Files: ${eventFiles.join(', ')} [${eventFiles.length}]`));\n } catch {\n console.warn(logPrefix + chalk.gray(`⚠️ No events directory found: ${eventsDir}`));\n continue;\n }\n\n for (const file of eventFiles) {\n const fullPath = path.resolve(eventsDir, file);\n if (!file.endsWith('.ts') && !file.endsWith('.js')) continue;\n\n try {\n const imported = await import(toFileUrl(fullPath));\n const controller: EventController = imported.default || imported[Object.keys(imported)[0]];\n\n if (!controller || (!controller.onRegister && !controller.onEvent)) {\n console.warn(logPrefix + chalk.yellow(`⚠️ Skipping non-controller file: ${file}`));\n continue;\n }\n\n const label = controller.label || file.replace(/\\.(ts|js)$/, '');\n\n if (controller.onRegister) {\n controller.onRegister(io);\n }\n\n events.push({\n label,\n onRegister: controller.onRegister,\n onEvent: controller.onEvent,\n });\n\n console.log(logPrefix + chalk.green(`✅ Registered event: ${label}`));\n\n if (controller.onEvent) {\n io.on('connection', (socket) => {\n socket.on(label, (data: any) => controller.onEvent!(socket, data));\n });\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to import event file: ${fullPath}`));\n console.error(logPrefix + err);\n }\n }\n }\n } catch (err) {\n console.warn(logPrefix + chalk.red(`❌ Failed to load events from source: ${source.root}`));\n console.error(logPrefix + err);\n }\n }\n },\n\n load: async (io: SocketIOServer) => {\n await useEvents.register(io);\n },\n\n get: async (): Promise<EventController[]> => {\n if (events.length === 0) {\n console.warn(logPrefix + 'No events loaded yet. Did you call useEvents.load(io)?');\n }\n return events;\n }\n};\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath}:`, err);\n// }\n// }\n// }\n// }\n// }\n"],"mappings":";AAAA,OAAOA,SAAQ;AACf,OAAOC,WAAU;AAEjB,OAAO,WAAW;;;ACAlB,OAAOC,SAAQ;;;ACDf,OAAO,QAAQ;AACf,OAAO,UAAU;AAiBV,SAAS,SAAS,UAAuB;AAC9C,MAAI,CAAC,GAAG,WAAW,QAAQ,EAAG,QAAO;AACrC,SAAO,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;AACtD;AAEO,SAAS,SAAS,UAAkB,MAAW;AACpD,KAAG,cAAc,UAAU,KAAK,UAAU,MAAM,MAAM,CAAC,GAAG,OAAO;AACnE;;;ADnBA,IAAM,eAAgC;AAAA,EACpC,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WAAW;AACb;AAEA,IAAI,kBAAmC,EAAE,GAAG,aAAa;AACzD,IAAM,WAAW,OAAO,WAAW;AAG5B,IAAM,cAAc;AAAA,EACzB,WAA4B;AAC1B,QAAI,UAAU;AACZ,YAAM,OAAO,SAAS,4BAA4B;AAClD,UAAI,KAAM,mBAAkB;AAAA,IAC9B;AAEA,QAAI,UAAU;AACZ,iBAAW,OAAO,OAAO,KAAK,YAAY,GAAmC;AAC3E,cAAM,YAAY,gBAAgB,GAAG;AACrC,YAAI,CAAC,aAAa,CAACC,IAAG,WAAW,SAAS,GAAG;AAC3C,0BAAgB,GAAG,IAAI,aAAa,GAAG;AAAA,QACzC;AAAA,MACF;AAAA,IACF;AAEA,sBAAkB;AAA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B,mBAAG,GAAG,cAAc,CAAC,WAAW;AAC9B,yBAAO,GAAG,OAAO,CAAC,SAAc,WAAW,QAAS,QAAQ,IAAI,CAAC;AAAA,gBACnE,CAAC;AAAA,cACH;AAAA,YACF,SAAS,KAAK;AACZ,sBAAQ,KAAK,YAAY,MAAM,IAAI,uCAAkC,QAAQ,EAAE,CAAC;AAChF,sBAAQ,MAAM,YAAY,GAAG;AAAA,YAC/B;AAAA,UACF;AAAA,QACF;AAAA,MACF,SAAS,KAAK;AACZ,gBAAQ,KAAK,YAAY,MAAM,IAAI,6CAAwC,OAAO,IAAI,EAAE,CAAC;AACzF,gBAAQ,MAAM,YAAY,GAAG;AAAA,MAC/B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,MAAM,OAAO,OAAuB;AAClC,UAAM,UAAU,SAAS,EAAE;AAAA,EAC7B;AAAA,EAEA,KAAK,YAAwC;AAC3C,QAAI,OAAO,WAAW,GAAG;AACvB,cAAQ,KAAK,YAAY,wDAAwD;AAAA,IACnF;AACA,WAAO;AAAA,EACT;AACF;","names":["fs","path","fs","fs","fs","path"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/hooks/useRoutes.ts"],"sourcesContent":["// packages/retrex-extensibles-core/useRoutes.ts\nimport { Application, Request, Response, NextFunction } from 'express';\
|
|
1
|
+
{"version":3,"sources":["../../../src/core/hooks/useRoutes.ts"],"sourcesContent":["// packages/retrex-extensibles-core/useRoutes.ts\nimport { Application, Request, Response, NextFunction } from 'express';\n// import type { LoaderFunctionArgs, ActionFunctionArgs } from '@remix-run/node';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport fs from 'node:fs';\nimport { RouteDefinition } from '../types/index'; // Adjust the import path as necessary\nimport { useServices } from './useServices';\nimport { useSettings } from './useSettings';\n\n// Registry for dynamically added routes\nconst Prefix = chalk.white('[') + chalk.cyan('Routes Manager | Info') + chalk.white('] ');\nconst ErrorPrefix = chalk.white('[') + chalk.red('Routes Manager | Error') + chalk.white('] ');\nconst registeredRoutes: RouteDefinition[] = [];\nexport const routesManager = {\n /**\n * Register a dynamic route from a module/service.\n */\n registerRoute(def: RouteDefinition): void {\n registeredRoutes.push(def);\n },\n\n /**\n * Return all registered dynamic routes.\n */\n getRegisteredRoutes(): RouteDefinition[] {\n return registeredRoutes;\n },\n\n /**\n * Loads and mounts all registered dynamic routes into an Express app.\n */\n async mountRegisteredRoutes(app: Application, debug: boolean): Promise<{ success: boolean, message?: string }> {\n let fullSuccess = false;\n try {\n for (const route of registeredRoutes) {\n try {\n if (debug) {\n console.log(Prefix + chalk.cyan(`Mounting route: [Label: ${route.label} | Path: ${route.path} -> File: ${route.filePath}]`));\n }\n\n const routeFile = fs.existsSync(route.filePath);\n // fs.readdirSync(route.filePath); // Ensure the file exists\n if (routeFile) {\n if (debug) {\n console.warn(ErrorPrefix + chalk.yellow(`⚠️ No files found in route directory: ${route.filePath}`));\n }\n continue; // Skip empty directories\n }\n console.log(Prefix + chalk.green(`✓ Found route file: ${route.filePath}`));\n \n if (debug) {\n console.log(Prefix + chalk.green(`✓ Mounted route: ${route.label.toUpperCase()} ${route.path}`));\n }\n } catch (err: any) {\n if (debug) {\n console.error(ErrorPrefix + chalk.red(`Failed to mount route ${route.path}: ${err?.message}`));\n console.error(ErrorPrefix + chalk.red(`Route definition: ${JSON.stringify(route, null, 2)}`));\n console.error(ErrorPrefix + chalk.red(`File path: ${route.filePath}`));\n console.error(ErrorPrefix + chalk.red(`Error details: ${err}`));\n }\n fullSuccess = false;\n continue; // Skip this route if it fails\n }\n }\n if (fullSuccess) {\n return { success: true }\n }\n return { success: fullSuccess, message: 'Some routes failed to mount, check logs for details.' };\n } catch (error: any) {\n if (debug) {\n console.error(ErrorPrefix + 'Error mounting registered routes:', error.message);\n console.error(ErrorPrefix + 'Stack trace:', error.stack);\n console.error(ErrorPrefix + 'Registered routes:', JSON.stringify(registeredRoutes, null, 2));\n // Optionally rethrow the error if you want to stop the server startup \n // throw new Error(`Failed to mount registered routes: ${error.message}`);\n // Or you can just log it and continue\n console.error(ErrorPrefix + 'Continuing without mounting routes due to error.');\n }\n // Optionally, you can throw an error here if you want to stop the server startup\n return { success: fullSuccess, message: `Failed to mount dynamic routes: ${error.message}` };\n // throw new Error(`Failed to mount dynamic routes: ${error.message}`);\n }\n },\n\n async getMountedRoutes(): Promise<RouteDefinition[]> {\n try {\n return registeredRoutes;\n } catch (error: any) {\n console.error(ErrorPrefix + 'Error getting mounted routes:', error.message);\n console.error(ErrorPrefix + 'Stack trace:', error.stack);\n throw new Error(`Failed to get mounted routes: ${error.message}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,mBAAkB;AAClB,qBAAe;AAMf,IAAM,SAAS,aAAAA,QAAM,MAAM,GAAG,IAAI,aAAAA,QAAM,KAAK,uBAAuB,IAAI,aAAAA,QAAM,MAAM,IAAI;AACxF,IAAM,cAAc,aAAAA,QAAM,MAAM,GAAG,IAAI,aAAAA,QAAM,IAAI,wBAAwB,IAAI,aAAAA,QAAM,MAAM,IAAI;AAC7F,IAAM,mBAAsC,CAAC;AACtC,IAAM,gBAAgB;AAAA;AAAA;AAAA;AAAA,EAI3B,cAAc,KAA4B;AACxC,qBAAiB,KAAK,GAAG;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,sBAAyC;AACvC,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,sBAAsB,KAAkB,OAAiE;AAC7G,QAAI,cAAc;AAClB,QAAI;AACF,iBAAW,SAAS,kBAAkB;AACpC,YAAI;AACF,cAAI,OAAO;AACT,oBAAQ,IAAI,SAAS,aAAAA,QAAM,KAAK,2BAA2B,MAAM,KAAK,YAAY,MAAM,IAAI,aAAa,MAAM,QAAQ,GAAG,CAAC;AAAA,UAC7H;AAEA,gBAAM,YAAY,eAAAC,QAAG,WAAW,MAAM,QAAQ;AAE9C,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,EACF;AAAA,EAEA,MAAM,mBAA+C;AACnD,QAAI;AACF,aAAO;AAAA,IACT,SAAS,OAAY;AACnB,cAAQ,MAAM,cAAc,iCAAiC,MAAM,OAAO;AAC1E,cAAQ,MAAM,cAAc,gBAAgB,MAAM,KAAK;AACvD,YAAM,IAAI,MAAM,iCAAiC,MAAM,OAAO,EAAE;AAAA,IAClE;AAAA,EACF;AACF;","names":["chalk","fs"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/hooks/useRoutes.ts"],"sourcesContent":["// packages/retrex-extensibles-core/useRoutes.ts\nimport { Application, Request, Response, NextFunction } from 'express';\
|
|
1
|
+
{"version":3,"sources":["../../../src/core/hooks/useRoutes.ts"],"sourcesContent":["// packages/retrex-extensibles-core/useRoutes.ts\nimport { Application, Request, Response, NextFunction } from 'express';\n// import type { LoaderFunctionArgs, ActionFunctionArgs } from '@remix-run/node';\nimport path from 'node:path';\nimport chalk from 'chalk';\nimport fs from 'node:fs';\nimport { RouteDefinition } from '../types/index'; // Adjust the import path as necessary\nimport { useServices } from './useServices';\nimport { useSettings } from './useSettings';\n\n// Registry for dynamically added routes\nconst Prefix = chalk.white('[') + chalk.cyan('Routes Manager | Info') + chalk.white('] ');\nconst ErrorPrefix = chalk.white('[') + chalk.red('Routes Manager | Error') + chalk.white('] ');\nconst registeredRoutes: RouteDefinition[] = [];\nexport const routesManager = {\n /**\n * Register a dynamic route from a module/service.\n */\n registerRoute(def: RouteDefinition): void {\n registeredRoutes.push(def);\n },\n\n /**\n * Return all registered dynamic routes.\n */\n getRegisteredRoutes(): RouteDefinition[] {\n return registeredRoutes;\n },\n\n /**\n * Loads and mounts all registered dynamic routes into an Express app.\n */\n async mountRegisteredRoutes(app: Application, debug: boolean): Promise<{ success: boolean, message?: string }> {\n let fullSuccess = false;\n try {\n for (const route of registeredRoutes) {\n try {\n if (debug) {\n console.log(Prefix + chalk.cyan(`Mounting route: [Label: ${route.label} | Path: ${route.path} -> File: ${route.filePath}]`));\n }\n\n const routeFile = fs.existsSync(route.filePath);\n // fs.readdirSync(route.filePath); // Ensure the file exists\n if (routeFile) {\n if (debug) {\n console.warn(ErrorPrefix + chalk.yellow(`⚠️ No files found in route directory: ${route.filePath}`));\n }\n continue; // Skip empty directories\n }\n console.log(Prefix + chalk.green(`✓ Found route file: ${route.filePath}`));\n \n if (debug) {\n console.log(Prefix + chalk.green(`✓ Mounted route: ${route.label.toUpperCase()} ${route.path}`));\n }\n } catch (err: any) {\n if (debug) {\n console.error(ErrorPrefix + chalk.red(`Failed to mount route ${route.path}: ${err?.message}`));\n console.error(ErrorPrefix + chalk.red(`Route definition: ${JSON.stringify(route, null, 2)}`));\n console.error(ErrorPrefix + chalk.red(`File path: ${route.filePath}`));\n console.error(ErrorPrefix + chalk.red(`Error details: ${err}`));\n }\n fullSuccess = false;\n continue; // Skip this route if it fails\n }\n }\n if (fullSuccess) {\n return { success: true }\n }\n return { success: fullSuccess, message: 'Some routes failed to mount, check logs for details.' };\n } catch (error: any) {\n if (debug) {\n console.error(ErrorPrefix + 'Error mounting registered routes:', error.message);\n console.error(ErrorPrefix + 'Stack trace:', error.stack);\n console.error(ErrorPrefix + 'Registered routes:', JSON.stringify(registeredRoutes, null, 2));\n // Optionally rethrow the error if you want to stop the server startup \n // throw new Error(`Failed to mount registered routes: ${error.message}`);\n // Or you can just log it and continue\n console.error(ErrorPrefix + 'Continuing without mounting routes due to error.');\n }\n // Optionally, you can throw an error here if you want to stop the server startup\n return { success: fullSuccess, message: `Failed to mount dynamic routes: ${error.message}` };\n // throw new Error(`Failed to mount dynamic routes: ${error.message}`);\n }\n },\n\n async getMountedRoutes(): Promise<RouteDefinition[]> {\n try {\n return registeredRoutes;\n } catch (error: any) {\n console.error(ErrorPrefix + 'Error getting mounted routes:', error.message);\n console.error(ErrorPrefix + 'Stack trace:', error.stack);\n throw new Error(`Failed to get mounted routes: ${error.message}`);\n }\n }\n}\n"],"mappings":";AAIA,OAAO,WAAW;A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M,CAAC,CAAC,EAAE,CAAC;AAC5F,oBAAQ,MAAM,cAAc,MAAM,IAAI,cAAc,MAAM,QAAQ,EAAE,CAAC;AACrE,oBAAQ,MAAM,cAAc,MAAM,IAAI,kBAAkB,GAAG,EAAE,CAAC;AAAA,UAChE;AACA,wBAAc;AACd;AAAA,QACF;AAAA,MACF;AACA,UAAI,aAAa;AACf,eAAO,EAAE,SAAS,KAAK;AAAA,MACzB;AACA,aAAO,EAAE,SAAS,aAAa,SAAS,uDAAuD;AAAA,IACjG,SAAS,OAAY;AACnB,UAAI,OAAO;AACT,gBAAQ,MAAM,cAAc,qCAAqC,MAAM,OAAO;AAC9E,gBAAQ,MAAM,cAAc,gBAAgB,MAAM,KAAK;AACvD,gBAAQ,MAAM,cAAc,sBAAsB,KAAK,UAAU,kBAAkB,MAAM,CAAC,CAAC;AAI3F,gBAAQ,MAAM,cAAc,kDAAkD;AAAA,MAChF;AAEA,aAAO,EAAE,SAAS,aAAa,SAAS,mCAAmC,MAAM,OAAO,GAAG;AAAA,IAE7F;AAAA,EACF;AAAA,EAEA,MAAM,mBAA+C;AACnD,QAAI;AACF,aAAO;AAAA,IACT,SAAS,OAAY;AACnB,cAAQ,MAAM,cAAc,iCAAiC,MAAM,OAAO;AAC1E,cAAQ,MAAM,cAAc,gBAAgB,MAAM,KAAK;AACvD,YAAM,IAAI,MAAM,iCAAiC,MAAM,OAAO,EAAE;AAAA,IAClE;AAAA,EACF;AACF;","names":[]}
|
|
@@ -34,7 +34,6 @@ __export(useUtils_exports, {
|
|
|
34
34
|
});
|
|
35
35
|
module.exports = __toCommonJS(useUtils_exports);
|
|
36
36
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
37
|
-
var import_url = require("url");
|
|
38
37
|
var import_node_fs3 = __toESM(require("fs"), 1);
|
|
39
38
|
|
|
40
39
|
// src/core/hooks/useSettings.ts
|
|
@@ -103,6 +102,12 @@ var useSettings = {
|
|
|
103
102
|
};
|
|
104
103
|
|
|
105
104
|
// src/core/hooks/useUtils.ts
|
|
105
|
+
function toFileUrl(filePath) {
|
|
106
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
107
|
+
if (normalized.startsWith("file://")) return normalized;
|
|
108
|
+
const prefix = normalized.startsWith("/") ? "file://" : "file:///";
|
|
109
|
+
return `${prefix}${encodeURI(normalized)}`;
|
|
110
|
+
}
|
|
106
111
|
var useUtils = {
|
|
107
112
|
async loadThemeComponent(componentName, options) {
|
|
108
113
|
const { search = {}, theme } = options;
|
|
@@ -248,7 +253,7 @@ var useUtils = {
|
|
|
248
253
|
for (const filePath of possiblePaths) {
|
|
249
254
|
if (await import_node_fs3.default.existsSync(filePath)) {
|
|
250
255
|
try {
|
|
251
|
-
const mod = await import((
|
|
256
|
+
const mod = await import(toFileUrl(filePath));
|
|
252
257
|
if (mod.default) return mod.default;
|
|
253
258
|
} catch (err) {
|
|
254
259
|
console.error(`Error loading component at ${filePath}:`, err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/core/hooks/useUtils.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["// packages/retrex-extensibles-core/hooks/useUtils.ts\nimport path from 'node:path';\nimport { pathToFileURL } from 'url';\nimport fs from 'node:fs';\nimport { useSettings } from './useSettings';\n\nexport const useUtils = {\n async loadThemeComponent(\n componentName: string,\n options: {\n theme: {\n name: string;\n type: 'admin' | 'client' | 'portal' | 'email';\n };\n search?: {\n themes?: boolean;\n modules?: boolean;\n services?: boolean;\n };\n }\n ): Promise<React.ComponentType<any> | null> {\n const { search = {}, theme } = options;\n const searchThemes = search.themes ?? true;\n const searchModules = search.modules ?? true;\n const searchServices = search.services ?? true;\n\n const possiblePaths: string[] = [];\n\n console.log(`Searching for component \"${componentName}\" in theme \"${theme.name}\" of type \"${theme.type}\"...`);\n\n try {\n if (searchThemes) {\n const templatesRoot = path.resolve(useSettings.getPaths().templates);\n possiblePaths.push(\n path.resolve(\n templatesRoot,\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n \n if (searchModules) {\n const modulesRoot = path.resolve(useSettings.getPaths().modules);\n if (fs.existsSync(modulesRoot)) {\n const moduleDirs = await fs.readdirSync(modulesRoot);\n for (const mod of moduleDirs) {\n possiblePaths.push(\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n }\n }\n \n if (searchServices) {\n const servicesRoot = path.resolve(useSettings.getPaths().services);\n if (fs.existsSync(servicesRoot)) {\n const serviceDirs = await fs.readdirSync(servicesRoot);\n for (const svc of serviceDirs) {\n possiblePaths.push(\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n }\n }\n \n for (const filePath of possiblePaths) {\n if (await fs.existsSync(filePath)) {\n try {\n const mod = await import(pathToFileURL(filePath).toString());\n if (mod.default) return mod.default;\n } catch (err) {\n console.error(`Error loading component at ${filePath}:`, err);\n }\n }\n }\n \n console.warn(`Component \"${componentName}\" not found in theme \"${theme.name}\" of type \"${theme.type}\".`);\n return null;\n } catch (err) {\n console.error(`Error searching for component \"${componentName}\":`, err);\n console.warn(`Component \"${componentName}\" not found in theme \"${theme.name}\" of type \"${theme.type}\".`);\n console.warn(`Searched paths:`, possiblePaths);\n console.warn(`Ensure the component exists in the specified theme and type.`);\n console.warn(`If the component is in a module or service, ensure the theme structure is correct.`);\n console.warn(`If you are using a custom theme, module, or service, ensure it is properly configured and registered in the settings.`);\n return null;\n }\n }\n}\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath}:`, err);\n// }\n// }\n// }\n// }\n// }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAAA,oBAAiB;AACjB,iBAA8B;AAC9B,IAAAC,kBAAe;;;ACAf,IAAAC,kBAAe;;;ACDf,qBAAe;AACf,uBAAiB;AAiBV,SAAS,SAAS,UAAuB;AAC9C,MAAI,CAAC,eAAAC,QAAG,WAAW,QAAQ,EAAG,QAAO;AACrC,SAAO,KAAK,MAAM,eAAAA,QAAG,aAAa,UAAU,OAAO,CAAC;AACtD;AAEO,SAAS,SAAS,UAAkB,MAAW;AACpD,iBAAAA,QAAG,cAAc,UAAU,KAAK,U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C,QAAG,WAAW,QAAQ,GAAG;AACjC,cAAI;AACF,kBAAM,MAAM,MAAM,WAAO,0BAAc,QAAQ,EAAE,SAAS;AAC1D,gBAAI,IAAI,QAAS,QAAO,IAAI;AAAA,UAC9B,SAAS,KAAK;AACZ,oBAAQ,MAAM,8BAA8B,QAAQ,KAAK,GAAG;AAAA,UAC9D;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,KAAK,cAAc,aAAa,yBAAyB,MAAM,IAAI,cAAc,MAAM,IAAI,IAAI;AACvG,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,cAAQ,MAAM,kCAAkC,aAAa,MAAM,GAAG;AACtE,cAAQ,KAAK,cAAc,aAAa,yBAAyB,MAAM,IAAI,cAAc,MAAM,IAAI,IAAI;AACvG,cAAQ,KAAK,mBAAmB,aAAa;AAC7C,cAAQ,KAAK,8DAA8D;AAC3E,cAAQ,KAAK,oFAAoF;AACjG,cAAQ,KAAK,uHAAuH;AACpI,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["import_node_path","import_node_fs","import_node_fs","fs","fs","path","fs"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/core/hooks/useUtils.ts","../../../src/core/hooks/useSettings.ts","../../../src/core/hooks/useExtensibles.ts"],"sourcesContent":["// packages/retrex-extensibles-core/hooks/useUtils.ts\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { useSettings } from './useSettings';\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport const useUtils = {\n async loadThemeComponent(\n componentName: string,\n options: {\n theme: {\n name: string;\n type: 'admin' | 'client' | 'portal' | 'email';\n };\n search?: {\n themes?: boolean;\n modules?: boolean;\n services?: boolean;\n };\n }\n ): Promise<React.ComponentType<any> | null> {\n const { search = {}, theme } = options;\n const searchThemes = search.themes ?? true;\n const searchModules = search.modules ?? true;\n const searchServices = search.services ?? true;\n\n const possiblePaths: string[] = [];\n\n console.log(`Searching for component \"${componentName}\" in theme \"${theme.name}\" of type \"${theme.type}\"...`);\n\n try {\n if (searchThemes) {\n const templatesRoot = path.resolve(useSettings.getPaths().templates);\n possiblePaths.push(\n path.resolve(\n templatesRoot,\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n templatesRoot,\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n \n if (searchModules) {\n const modulesRoot = path.resolve(useSettings.getPaths().modules);\n if (fs.existsSync(modulesRoot)) {\n const moduleDirs = await fs.readdirSync(modulesRoot);\n for (const mod of moduleDirs) {\n possiblePaths.push(\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n modulesRoot,\n mod,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n }\n }\n \n if (searchServices) {\n const servicesRoot = path.resolve(useSettings.getPaths().services);\n if (fs.existsSync(servicesRoot)) {\n const serviceDirs = await fs.readdirSync(servicesRoot);\n for (const svc of serviceDirs) {\n possiblePaths.push(\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n theme.name,\n 'components',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'routes',\n `${componentName}.tsx`\n ),\n path.resolve(\n servicesRoot,\n svc,\n 'resources',\n 'themes',\n theme.type,\n 'default',\n 'components',\n `${componentName}.tsx`\n )\n );\n }\n }\n }\n \n for (const filePath of possiblePaths) {\n if (await fs.existsSync(filePath)) {\n try {\n const mod = await import(toFileUrl(filePath));\n if (mod.default) return mod.default;\n } catch (err) {\n console.error(`Error loading component at ${filePath}:`, err);\n }\n }\n }\n \n console.warn(`Component \"${componentName}\" not found in theme \"${theme.name}\" of type \"${theme.type}\".`);\n return null;\n } catch (err) {\n console.error(`Error searching for component \"${componentName}\":`, err);\n console.warn(`Component \"${componentName}\" not found in theme \"${theme.name}\" of type \"${theme.type}\".`);\n console.warn(`Searched paths:`, possiblePaths);\n console.warn(`Ensure the component exists in the specified theme and type.`);\n console.warn(`If the component is in a module or service, ensure the theme structure is correct.`);\n console.warn(`If you are using a custom theme, module, or service, ensure it is properly configured and registered in the settings.`);\n return null;\n }\n }\n}\n","// src/hooks/useSettings.ts\n\nimport path from 'node:path';\nimport fs from 'node:fs';\n\nimport { loadJSON, saveJSON } from './useExtensibles';\nimport type { ExtensiblePaths } from '../types'; // Adjust the import path as necessary\n\nconst defaultPaths: ExtensiblePaths = {\n modules: './app/modules',\n templates: './app/resources/themes',\n services: './app/services',\n events: './app/events',\n langs: './public/langs',\n providers: './app/providers',\n};\n\nlet extensiblePaths: ExtensiblePaths = { ...defaultPaths };\nconst isServer = typeof window === 'undefined';\n\n\nexport const useSettings = {\n getPaths(): ExtensiblePaths {\n if (isServer) {\n const json = loadJSON('./app/extensiblePaths.json');\n if (json) extensiblePaths = json;\n }\n\n if (isServer) {\n for (const key of Object.keys(defaultPaths) as Array<keyof ExtensiblePaths>) {\n const candidate = extensiblePaths[key];\n if (!candidate || !fs.existsSync(candidate)) {\n extensiblePaths[key] = defaultPaths[key];\n }\n }\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n langs: './langs',\n };\n // extensiblePaths = loadJSON(\"./app/extensiblePaths.json\");\n return extensiblePaths;\n },\n\n setPaths(paths: Partial<ExtensiblePaths>): void {\n if (isServer) {\n saveJSON('./app/extensiblePaths.json', {\n ...extensiblePaths,\n ...paths,\n });\n }\n\n extensiblePaths = {\n ...extensiblePaths,\n ...paths,\n };\n },\n \n getKeyValue(key: string): string {\n return 'Coming Soon'\n },\n setKeyValue(key: string, value: string): void {\n return;\n },\n};\n","// src/hooks/useExtensibles.ts\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { useSettings } from './useSettings';\nimport type { TemplateType, ExtensibleMeta, ExtensiblePaths } from '../types';\n\nlet paths: ExtensiblePaths;\n\nfunction toFileUrl(filePath: string): string {\n const normalized = filePath.replace(/\\\\/g, '/');\n if (normalized.startsWith('file://')) return normalized;\n const prefix = normalized.startsWith('/') ? 'file://' : 'file:///';\n return `${prefix}${encodeURI(normalized)}`;\n}\n\nexport function registerExtensibles(extensiblePaths: ExtensiblePaths) {\n paths = extensiblePaths;\n}\n\nexport function loadJSON(filePath: string): any {\n if (!fs.existsSync(filePath)) return null;\n return JSON.parse(fs.readFileSync(filePath, 'utf-8'));\n}\n\nexport function saveJSON(filePath: string, data: any) {\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n// --- MODULES ---\n\nexport function getModules(): ExtensibleMeta[] {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().modules)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().modules, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().modules, dir, 'module.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isModuleEnabled(name: string) {\n const modules = getModules();\n return modules.find((m) => m.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleModule(name: string, enabled: boolean) {\n const modules = getModules();\n const mod = modules.find((m) => m.lowerName === name.toLowerCase());\n if (!mod) throw new Error(`Module ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().modules, mod.lowerName, 'module.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onModuleEnabled(mod.name);\n else onModuleDisabled(mod.name);\n}\n\n// --- SERVICES ---\n\nexport function getServices(): ExtensibleMeta[] {\n if (!useSettings.getPaths().services) throw new Error('Services path not registered.');\n\n const dirs = fs\n .readdirSync(useSettings.getPaths().services)\n .filter((d: any) => fs.statSync(path.join(useSettings.getPaths().services, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(useSettings.getPaths().services, dir, 'service.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: meta.lowerName || dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isServiceEnabled(name: string) {\n const services = getServices();\n return services.find((s) => s.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\nexport function toggleService(name: string, enabled: boolean) {\n const services = getServices();\n const svc = services.find((s) => s.lowerName === name.toLowerCase());\n if (!svc) throw new Error(`Service ${name} not found`);\n\n const metaPath = path.join(useSettings.getPaths().services, svc.lowerName, 'service.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = enabled;\n saveJSON(metaPath, meta);\n\n if (enabled) onServiceEnabled(svc.name);\n else onServiceDisabled(svc.name);\n}\n\n// --- TEMPLATES ---\n\n// Helper to get base path for a template type\nfunction getTemplateBasePath(type: TemplateType): string {\n if (!useSettings.getPaths().templates) throw new Error('Templates path not registered.');\n switch (type) {\n case 'admin-theme':\n case 'client-theme':\n return path.join(useSettings.getPaths().templates, 'themes');\n case 'portal':\n return path.join(useSettings.getPaths().templates, 'portals');\n case 'email':\n return path.join(useSettings.getPaths().templates, 'emails');\n default:\n throw new Error(`Unknown template type: ${type}`);\n }\n}\n\nexport function getTemplates(type: TemplateType): ExtensibleMeta[] {\n const basePath = getTemplateBasePath(type);\n if (!fs.existsSync(basePath)) return [];\n\n const dirs = fs\n .readdirSync(basePath)\n .filter((d: any) => fs.statSync(path.join(basePath, d)).isDirectory());\n\n return dirs.map((dir: any) => {\n const meta = loadJSON(path.join(basePath, dir, 'template.json')) || {};\n return {\n name: meta.name || dir,\n lowerName: dir.toLowerCase(),\n version: meta.version,\n description: meta.description,\n author: meta.author,\n icon: meta.icon,\n enabled: meta.enabled ?? false,\n };\n });\n}\n\nexport function isTemplateActive(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n return templates.find((t) => t.lowerName === name.toLowerCase())?.enabled ?? false;\n}\n\n// Toggle templates: only 1 active per type allowed\nexport function toggleTemplate(type: TemplateType, name: string) {\n const templates = getTemplates(type);\n\n templates.forEach((tpl) => {\n const metaPath = path.join(getTemplateBasePath(type), tpl.lowerName, 'template.json');\n const meta = loadJSON(metaPath) || {};\n meta.enabled = tpl.lowerName === name.toLowerCase();\n saveJSON(metaPath, meta);\n });\n\n onTemplateSelect(type, name);\n}\n\n// --- EVENTS (replace with your event system integration) ---\n\nexport function onModuleEnabled(name: string) {\n console.log(`Module enabled: ${name}`);\n // emit event or custom logic here\n}\n\nexport function onModuleDisabled(name: string) {\n console.log(`Module disabled: ${name}`);\n}\n\nexport function onServiceEnabled(name: string) {\n console.log(`Service enabled: ${name}`);\n}\n\nexport function onServiceDisabled(name: string) {\n console.log(`Service disabled: ${name}`);\n}\n\nexport function onTemplateSelect(type: TemplateType, name: string) {\n console.log(`Template selected: type=${type}, name=${name}`);\n}\n\n// --- REGISTER HOOKS FOR MODULES ---\n\nexport async function registerEvents() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const eventsFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'events.server.js');\n if (fs.existsSync(eventsFile)) {\n const modEvents = await import(eventsFile);\n if (modEvents?.registerEvents) await modEvents.registerEvents();\n }\n }\n}\n\nexport async function registerMiddleware() {\n if (!useSettings.getPaths().modules) throw new Error('Modules path not registered.');\n const modules = getModules().filter((m) => m.enabled);\n for (const mod of modules) {\n const middlewareFile = path.join(useSettings.getPaths().modules, mod.lowerName, 'middleware.server.js');\n if (fs.existsSync(middlewareFile)) {\n const modMiddleware = await import(middlewareFile);\n if (modMiddleware?.registerMiddleware) await modMiddleware.registerMiddleware();\n }\n }\n}\n\n/**\n * Registers routes given a path to routes folder (for pages and API routes)\n * @param routesFolderPath string - path to module/service routes folder\n */\nexport async function registerRoutes(routesFolderPath: string) {\n if (!fs.existsSync(routesFolderPath)) return;\n\n const routeFiles = fs.readdirSync(routesFolderPath).filter((f: any) => /\\.(js|ts|jsx|tsx)$/.test(f));\n for (const file of routeFiles) {\n const routeModule = await import(path.join(routesFolderPath, file));\n if (routeModule?.registerRoute) {\n await routeModule.registerRoute();\n }\n }\n}\n\nexport async function loadProviders() {\n const paths = useSettings.getPaths();\n\n const all = [\n { type: 'module', list: getModules(), basePath: paths.modules },\n { type: 'service', list: getServices(), basePath: paths.services },\n ];\n\n for (const { type, list, basePath } of all) {\n for (const item of list) {\n if (!item.enabled) continue;\n\n const metaPath = path.join(path.resolve(basePath), item.lowerName, `${type}.json`);\n const meta = loadJSON(metaPath);\n if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n for (const providerRelPath of meta.providers) {\n try {\n let providerAbsPath = path.join(path.resolve(basePath), item.lowerName, providerRelPath);\n\n // Try .js fallback if file is .ts or .tsx\n const ext = path.extname(providerAbsPath);\n if (ext === '.ts' || ext === '.tsx') {\n const jsPath = providerAbsPath.replace(/\\.(ts|tsx)$/, '.js');\n try {\n await fs.accessSync(jsPath); // Check if compiled JS file exists\n providerAbsPath = jsPath;\n } catch {\n throw new Error(`Compiled JS version not found for provider: ${providerRelPath}`);\n }\n }\n\n const providerUrl = toFileUrl(providerAbsPath);\n const providerModule = await import(providerUrl);\n\n if (typeof providerModule.default === 'function') {\n await providerModule.default();\n console.log(`[${type}] ✅ Provider loaded: ${providerRelPath}`);\n } else {\n console.warn(`[${type}] ⚠️ Provider ${providerRelPath} has no default export.`);\n }\n } catch (err) {\n console.error(`[${type}] ❌ Failed to load provider ${providerRelPath}:`, err);\n }\n }\n }\n }\n}\n\n\n// export async function loadProviders() {\n// paths = {\n// modules: useSettings.getPaths().modules,\n// templates: useSettings.getPaths().templates,\n// services: useSettings.getPaths().services,\n// events: useSettings.getPaths().events,\n// }\n// const all = [\n// { type: 'module', list: getModules(), basePath: useSettings.getPaths().modules },\n// { type: 'service', list: getServices(), basePath: useSettings.getPaths().services },\n// ];\n\n// for (const { type, list, basePath } of all) {\n// for (const item of list) {\n// if (!item.enabled) continue;\n\n// const metaPath = path.join(basePath, item.lowerName, `${type}.json`);\n// const meta = loadJSON(metaPath);\n// if (!meta?.providers || !Array.isArray(meta.providers)) continue;\n\n// for (const providerRelPath of meta.providers) {\n// try {\n// const providerPath = path.join(basePath, item.lowerName, providerRelPath);\n// const providerModule = await import(providerPath);\n// if (typeof providerModule.default === 'function') {\n// await providerModule.default(); // Call provider\n// console.log(`[${type}] Provider loaded: ${providerRelPath}`);\n// } else {\n// console.warn(`[${type}] Provider ${providerRelPath} has no default export.`);\n// }\n// } catch (err) {\n// console.error(`[${type}] Failed to load provider ${providerRelPath}:`, err);\n// }\n// }\n// }\n// }\n// }\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AACA,IAAAA,oBAAiB;AACjB,IAAAC,kBAAe;;;ACCf,IAAAC,kBAAe;;;ACDf,qBAAe;AACf,uBAAiB;AAiBV,SAAS,SAAS,UAAuB;AAC9C,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AAA,cAClB;AAAA,cACA,kBAAAA,QAAK;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA,MAAM;AAAA,gBACN;AAAA,gBACA;AAAA,gBACA,GAAG,aAAa;AAAA,cAClB;AAAA,cACA,kBAAAA,QAAK;AAAA,gBACH;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA;AAAA,gBACA,MAAM;AAAA,gBACN;AAAA,gBACA;AAAA,gBACA,GAAG,aAAa;AAAA,cAClB;AAAA,YACF;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAEA,iBAAW,YAAY,eAAe;AACpC,YAAI,MAAM,gBAAAC,QAAG,WAAW,QAAQ,GAAG;AACjC,cAAI;AACF,kBAAM,MAAM,MAAM,OAAO,UAAU,QAAQ;AAC3C,gBAAI,IAAI,QAAS,QAAO,IAAI;AAAA,UAC9B,SAAS,KAAK;AACZ,oBAAQ,MAAM,8BAA8B,QAAQ,KAAK,GAAG;AAAA,UAC9D;AAAA,QACF;AAAA,MACF;AAEA,cAAQ,KAAK,cAAc,aAAa,yBAAyB,MAAM,IAAI,cAAc,MAAM,IAAI,IAAI;AACvG,aAAO;AAAA,IACT,SAAS,KAAK;AACZ,cAAQ,MAAM,kCAAkC,aAAa,MAAM,GAAG;AACtE,cAAQ,KAAK,cAAc,aAAa,yBAAyB,MAAM,IAAI,cAAc,MAAM,IAAI,IAAI;AACvG,cAAQ,KAAK,mBAAmB,aAAa;AAC7C,cAAQ,KAAK,8DAA8D;AAC3E,cAAQ,KAAK,oFAAoF;AACjG,cAAQ,KAAK,uHAAuH;AACpI,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["import_node_path","import_node_fs","import_node_fs","fs","fs","path","fs"]}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
// src/core/hooks/useUtils.ts
|
|
2
2
|
import path2 from "path";
|
|
3
|
-
import { pathToFileURL } from "url";
|
|
4
3
|
import fs3 from "fs";
|
|
5
4
|
|
|
6
5
|
// src/core/hooks/useSettings.ts
|
|
@@ -69,6 +68,12 @@ var useSettings = {
|
|
|
69
68
|
};
|
|
70
69
|
|
|
71
70
|
// src/core/hooks/useUtils.ts
|
|
71
|
+
function toFileUrl(filePath) {
|
|
72
|
+
const normalized = filePath.replace(/\\/g, "/");
|
|
73
|
+
if (normalized.startsWith("file://")) return normalized;
|
|
74
|
+
const prefix = normalized.startsWith("/") ? "file://" : "file:///";
|
|
75
|
+
return `${prefix}${encodeURI(normalized)}`;
|
|
76
|
+
}
|
|
72
77
|
var useUtils = {
|
|
73
78
|
async loadThemeComponent(componentName, options) {
|
|
74
79
|
const { search = {}, theme } = options;
|
|
@@ -214,7 +219,7 @@ var useUtils = {
|
|
|
214
219
|
for (const filePath of possiblePaths) {
|
|
215
220
|
if (await fs3.existsSync(filePath)) {
|
|
216
221
|
try {
|
|
217
|
-
const mod = await import(
|
|
222
|
+
const mod = await import(toFileUrl(filePath));
|
|
218
223
|
if (mod.default) return mod.default;
|
|
219
224
|
} catch (err) {
|
|
220
225
|
console.error(`Error loading component at ${filePath}:`, err);
|