UNPKG

@dbs-portal/core-module-registry

Version:

Core module registry system for automatic module discovery and registration

504 lines (503 loc) 14.8 kB
var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); class BrowserPath { constructor() { __publicField(this, "sep", "/"); __publicField(this, "delimiter", ":"); } /** * Resolve path segments into an absolute path */ resolve(...paths) { let resolvedPath = ""; let resolvedAbsolute = false; for (let i = paths.length - 1; i >= -1 && !resolvedAbsolute; i--) { const path = i >= 0 ? paths[i] : this.getCurrentDirectory(); if (!path) continue; resolvedPath = path + "/" + resolvedPath; resolvedAbsolute = this.isAbsolute(path); } resolvedPath = this.normalizeArray(resolvedPath.split("/").filter(Boolean), !resolvedAbsolute).join("/"); return (resolvedAbsolute ? "/" : "") + resolvedPath || "."; } /** * Join path segments */ join(...paths) { const joined = paths.filter(Boolean).join("/"); return joined ? this.normalize(joined) : "."; } /** * Get directory name */ dirname(path) { if (!path) return "."; const normalizedPath = this.normalize(path); const lastSlash = normalizedPath.lastIndexOf("/"); if (lastSlash === -1) return "."; if (lastSlash === 0) return "/"; return normalizedPath.slice(0, lastSlash); } /** * Get base name */ basename(path, ext) { if (!path) return ""; const normalizedPath = this.normalize(path); const lastSlash = normalizedPath.lastIndexOf("/"); let base = lastSlash === -1 ? normalizedPath : normalizedPath.slice(lastSlash + 1); if (ext && base.endsWith(ext)) { base = base.slice(0, -ext.length); } return base; } /** * Get file extension */ extname(path) { if (!path) return ""; const base = this.basename(path); const lastDot = base.lastIndexOf("."); return lastDot === -1 || lastDot === 0 ? "" : base.slice(lastDot); } /** * Get relative path */ relative(from, to) { const fromParts = this.resolve(from).split("/").filter(Boolean); const toParts = this.resolve(to).split("/").filter(Boolean); let commonLength = 0; const minLength = Math.min(fromParts.length, toParts.length); for (let i = 0; i < minLength; i++) { if (fromParts[i] === toParts[i]) { commonLength++; } else { break; } } const upCount = fromParts.length - commonLength; const relativeParts = Array(upCount).fill("..").concat(toParts.slice(commonLength)); return relativeParts.join("/") || "."; } /** * Check if path is absolute */ isAbsolute(path) { return path.startsWith("/"); } /** * Normalize path */ normalize(path) { if (!path) return "."; const isAbsolute2 = this.isAbsolute(path); const trailingSlash = path.endsWith("/"); const parts = path.split("/").filter(Boolean); const normalizedParts = this.normalizeArray(parts, !isAbsolute2); let result = normalizedParts.join("/"); if (!result && !isAbsolute2) { result = "."; } if (result && trailingSlash) { result += "/"; } return (isAbsolute2 ? "/" : "") + result; } /** * Normalize path array */ normalizeArray(parts, allowAboveRoot) { const result = []; for (const part of parts) { if (part === "..") { if (result.length && result[result.length - 1] !== "..") { result.pop(); } else if (allowAboveRoot) { result.push(".."); } } else if (part !== ".") { result.push(part); } } return result; } /** * Get current directory (browser simulation) */ getCurrentDirectory() { if (typeof window !== "undefined") { return window.location.pathname; } return "/"; } } const browserPath = new BrowserPath(); browserPath.resolve.bind(browserPath); browserPath.join.bind(browserPath); browserPath.dirname.bind(browserPath); browserPath.basename.bind(browserPath); browserPath.extname.bind(browserPath); browserPath.relative.bind(browserPath); browserPath.isAbsolute.bind(browserPath); browserPath.normalize.bind(browserPath); browserPath.sep; browserPath.delimiter; const browserPath$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, BrowserPath, default: browserPath }, Symbol.toStringTag, { value: "Module" })); class BrowserFileSystem { constructor() { __publicField(this, "cache", /* @__PURE__ */ new Map()); __publicField(this, "mockFiles", /* @__PURE__ */ new Map()); } /** * Read file content * In browser environment, this will work with pre-loaded or cached content */ async readFile(path, _encoding = "utf8") { if (this.cache.has(path)) { return this.cache.get(path); } if (this.mockFiles.has(path)) { return this.mockFiles.get(path); } if (this.isUrl(path)) { try { const response = await fetch(path); if (!response.ok) { throw new Error(`Failed to fetch ${path}: ${response.statusText}`); } const content = await response.text(); this.cache.set(path, content); return content; } catch (error) { throw new Error(`ENOENT: no such file or directory, open '${path}'`); } } throw new Error(`ENOENT: no such file or directory, open '${path}' (browser environment)`); } /** * Write file content * In browser environment, this stores in memory cache */ async writeFile(path, data, _encoding = "utf8") { this.mockFiles.set(path, data); this.cache.set(path, data); } /** * Check file access */ async access(path) { if (!await this.exists(path)) { throw new Error(`ENOENT: no such file or directory, access '${path}'`); } } /** * Get file stats */ async stat(path) { if (!await this.exists(path)) { throw new Error(`ENOENT: no such file or directory, stat '${path}'`); } const content = this.mockFiles.get(path) || this.cache.get(path) || ""; const now = /* @__PURE__ */ new Date(); return { isFile: () => true, isDirectory: () => false, size: content.length, mtime: now, ctime: now }; } /** * Read directory contents */ async readdir(path) { const files = []; const dirKey = `__dir__${path}`; if (this.cache.has(dirKey)) { return this.cache.get(dirKey); } for (const [filePath] of this.mockFiles) { if (filePath.startsWith(path) && filePath !== path) { const relativePath = filePath.slice(path.length + 1); const firstSegment = relativePath.split("/")[0]; if (firstSegment && !files.includes(firstSegment)) { files.push(firstSegment); } } } return files; } /** * Create directory */ async mkdir(path, _options = {}) { const dirKey = `__dir__${path}`; this.cache.set(dirKey, []); } /** * Check if file exists */ async exists(path) { return this.cache.has(path) || this.mockFiles.has(path) || this.cache.has(`__dir__${path}`) || this.isUrl(path) && await this.checkUrlExists(path); } /** * Pre-load file content (for browser usage) */ preloadFile(path, content) { this.cache.set(path, content); } /** * Pre-load directory listing (for browser usage) */ preloadDirectory(path, files) { const dirKey = `__dir__${path}`; this.cache.set(dirKey, files); } /** * Set mock file content (for testing) */ setMockFile(path, content) { this.mockFiles.set(path, content); } /** * Clear all cached content */ clearCache() { this.cache.clear(); this.mockFiles.clear(); } /** * Check if path is a URL */ isUrl(path) { try { new URL(path); return true; } catch { return false; } } /** * Check if URL exists */ async checkUrlExists(url) { try { const response = await fetch(url, { method: "HEAD" }); return response.ok; } catch { return false; } } } const browserFs = new BrowserFileSystem(); browserFs.readFile.bind(browserFs); browserFs.writeFile.bind(browserFs); browserFs.access.bind(browserFs); browserFs.stat.bind(browserFs); browserFs.readdir.bind(browserFs); browserFs.mkdir.bind(browserFs); browserFs.exists.bind(browserFs); browserFs.preloadFile.bind(browserFs); browserFs.preloadDirectory.bind(browserFs); browserFs.setMockFile.bind(browserFs); browserFs.clearCache.bind(browserFs); const browserFs$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, BrowserFileSystem, default: browserFs }, Symbol.toStringTag, { value: "Module" })); class BrowserGlob { constructor() { __publicField(this, "fileCache", /* @__PURE__ */ new Map()); __publicField(this, "directoryCache", /* @__PURE__ */ new Map()); } /** * Main glob function - browser compatible */ async glob(pattern, options = {}) { const patterns = Array.isArray(pattern) ? pattern : [pattern]; const results = []; const cwd = options.cwd || "/"; for (const pat of patterns) { const matches = await this.matchPattern(pat, cwd, options); results.push(...matches); } const uniqueResults = [...new Set(results)]; return this.applyFilters(uniqueResults, options); } /** * Synchronous glob (limited functionality in browser) */ globSync(pattern, options = {}) { const patterns = Array.isArray(pattern) ? pattern : [pattern]; const results = []; const cwd = options.cwd || "/"; for (const pat of patterns) { const matches = this.matchPatternSync(pat, cwd, options); results.push(...matches); } const uniqueResults = [...new Set(results)]; return this.applyFilters(uniqueResults, options); } /** * Match a single pattern */ async matchPattern(pattern, cwd, options) { const allFiles = this.getAllCachedFiles(cwd); return this.filterByPattern(allFiles, pattern, options); } /** * Match a single pattern synchronously */ matchPatternSync(pattern, cwd, options) { const allFiles = this.getAllCachedFiles(cwd); return this.filterByPattern(allFiles, pattern, options); } /** * Filter files by glob pattern */ filterByPattern(files, pattern, options) { const regex = this.globToRegex(pattern); const matches = []; for (const file of files) { if (regex.test(file)) { if (options.onlyDirectories && !this.isDirectory(file)) continue; if (options.onlyFiles && this.isDirectory(file)) continue; if (!options.dot && this.isDotFile(file)) continue; if (options.ignore && this.matchesIgnorePattern(file, options.ignore)) continue; matches.push(options.absolute ? file : this.makeRelative(file, options.cwd || "/")); } } return matches; } /** * Convert glob pattern to regex */ globToRegex(pattern) { let regexPattern = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "___DOUBLESTAR___").replace(/\*/g, "[^/]*").replace(/___DOUBLESTAR___/g, ".*").replace(/\?/g, "[^/]"); regexPattern = regexPattern.replace(/\[([^\]]+)\]/g, "[$1]"); regexPattern = regexPattern.replace(/\[!([^\]]+)\]/g, "[^$1]"); regexPattern = regexPattern.replace(/\{([^}]+)\}/g, (_match, content) => { const alternatives = content.split(",").map((alt) => alt.trim()); return `(${alternatives.join("|")})`; }); return new RegExp(`^${regexPattern}$`); } /** * Get all cached files for a directory */ getAllCachedFiles(cwd) { const files = []; for (const [path, _content] of this.fileCache) { if (path.startsWith(cwd)) { files.push(path); } } for (const [path, dirFiles] of this.directoryCache) { if (path.startsWith(cwd)) { files.push(path); files.push(...dirFiles.map((f) => `${path}/${f}`)); } } return files; } /** * Apply additional filters */ applyFilters(files, options) { return files.filter((file) => { if (options.onlyDirectories && !this.isDirectory(file)) return false; if (options.onlyFiles && this.isDirectory(file)) return false; if (!options.dot && this.isDotFile(file)) return false; if (options.ignore && this.matchesIgnorePattern(file, options.ignore)) return false; return true; }); } /** * Check if path is a directory */ isDirectory(path) { return this.directoryCache.has(path) || path.endsWith("/"); } /** * Check if file is a dot file */ isDotFile(path) { const basename = path.split("/").pop() || ""; return basename.startsWith(".") && basename !== "." && basename !== ".."; } /** * Check if file matches ignore patterns */ matchesIgnorePattern(file, ignorePatterns) { return ignorePatterns.some((pattern) => { const regex = this.globToRegex(pattern); return regex.test(file); }); } /** * Make path relative to cwd */ makeRelative(path, cwd) { if (path.startsWith(cwd)) { const relative = path.slice(cwd.length); return relative.startsWith("/") ? relative.slice(1) : relative; } return path; } /** * Pre-load file list for a directory (for browser usage) */ preloadDirectory(path, files) { this.directoryCache.set(path, files); } /** * Pre-load file content (for browser usage) */ preloadFile(path) { this.fileCache.set(path, []); } /** * Set mock directory structure (for testing) */ setMockStructure(structure) { this.directoryCache.clear(); this.fileCache.clear(); for (const [dir, files] of Object.entries(structure)) { this.directoryCache.set(dir, files); files.forEach((file) => { this.fileCache.set(`${dir}/${file}`, []); }); } } /** * Clear all cached data */ clearCache() { this.fileCache.clear(); this.directoryCache.clear(); } } const browserGlob = new BrowserGlob(); browserGlob.glob.bind(browserGlob); browserGlob.globSync.bind(browserGlob); browserGlob.preloadDirectory.bind(browserGlob); browserGlob.preloadFile.bind(browserGlob); browserGlob.setMockStructure.bind(browserGlob); browserGlob.clearCache.bind(browserGlob); const browserGlob$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ __proto__: null, BrowserGlob, default: browserGlob }, Symbol.toStringTag, { value: "Module" })); export { browserFs$1 as a, browserPath$1 as b, browserGlob$1 as c }; //# sourceMappingURL=browser-compat-AuLlE_ij.js.map