@devlusoft/devix 0.4.1-beta.3 → 0.4.1-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/dist/cli/build.d.ts +1 -0
  2. package/dist/cli/build.js +10 -9
  3. package/dist/cli/build.js.map +2 -2
  4. package/dist/cli/dev-server.d.ts +1 -0
  5. package/dist/cli/dev-server.js +8 -7
  6. package/dist/cli/dev-server.js.map +2 -2
  7. package/dist/cli/dev.d.ts +1 -0
  8. package/dist/cli/generate.d.ts +1 -0
  9. package/dist/cli/generate.js +9 -8
  10. package/dist/cli/generate.js.map +2 -2
  11. package/dist/cli/index.d.ts +2 -0
  12. package/dist/cli/index.js +30 -29
  13. package/dist/cli/index.js.map +2 -2
  14. package/dist/cli/start.d.ts +1 -0
  15. package/dist/config.d.ts +22 -0
  16. package/dist/runtime/api-context.d.ts +24 -0
  17. package/dist/runtime/client-router.d.ts +13 -0
  18. package/dist/runtime/context.d.ts +32 -0
  19. package/dist/runtime/create-handler.d.ts +10 -0
  20. package/dist/runtime/error-boundary.d.ts +19 -0
  21. package/dist/runtime/fetch.d.ts +39 -0
  22. package/dist/runtime/head.d.ts +7 -0
  23. package/dist/runtime/index.d.ts +14 -0
  24. package/dist/runtime/index.js +1 -1
  25. package/dist/runtime/index.js.map +3 -3
  26. package/dist/runtime/link.d.ts +8 -0
  27. package/dist/runtime/metadata.d.ts +10 -0
  28. package/dist/runtime/router-provider.d.ts +25 -0
  29. package/dist/runtime/router-provider.js +1 -1
  30. package/dist/runtime/router-provider.js.map +3 -3
  31. package/dist/runtime/server-app.d.ts +15 -0
  32. package/dist/server/api-router.d.ts +22 -0
  33. package/dist/server/api.d.ts +2 -0
  34. package/dist/server/collect-css.d.ts +2 -0
  35. package/dist/server/handler-store.d.ts +10 -0
  36. package/dist/server/index.d.ts +6 -0
  37. package/dist/server/pages-router.d.ts +21 -0
  38. package/dist/server/public-index.d.ts +1 -0
  39. package/dist/server/render.d.ts +62 -0
  40. package/dist/server/routes.d.ts +11 -0
  41. package/dist/server/types.d.ts +52 -0
  42. package/dist/types.d.ts +42 -0
  43. package/dist/utils/async.d.ts +1 -0
  44. package/dist/utils/banner.d.ts +1 -0
  45. package/dist/utils/banner.js +1 -1
  46. package/dist/utils/cookies.d.ts +12 -0
  47. package/dist/utils/duration.d.ts +1 -0
  48. package/dist/utils/env.d.ts +1 -0
  49. package/dist/utils/html.d.ts +2 -0
  50. package/dist/utils/patterns.d.ts +1 -0
  51. package/dist/utils/response.d.ts +19 -0
  52. package/dist/vite/codegen/api.d.ts +6 -0
  53. package/dist/vite/codegen/client-routes.d.ts +6 -0
  54. package/dist/vite/codegen/context.d.ts +1 -0
  55. package/dist/vite/codegen/entry-client.d.ts +5 -0
  56. package/dist/vite/codegen/entry-client.js +7 -6
  57. package/dist/vite/codegen/entry-client.js.map +2 -2
  58. package/dist/vite/codegen/extract-methods.d.ts +4 -0
  59. package/dist/vite/codegen/render.d.ts +6 -0
  60. package/dist/vite/codegen/routes-dts.d.ts +10 -0
  61. package/dist/vite/codegen/scan-api.d.ts +2 -0
  62. package/dist/vite/codegen/write-routes-dts.d.ts +1 -0
  63. package/dist/vite/index.d.ts +3 -0
  64. package/dist/vite/index.js +8 -7
  65. package/dist/vite/index.js.map +2 -2
  66. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/cli/dev.ts", "../../src/vite/codegen/entry-client.ts", "../../src/vite/codegen/client-routes.ts", "../../src/vite/codegen/render.ts", "../../src/vite/codegen/api.ts", "../../src/utils/patterns.ts", "../../src/server/pages-router.ts", "../../src/server/api-router.ts", "../../src/vite/codegen/context.ts", "../../src/vite/codegen/extract-methods.ts", "../../src/vite/codegen/routes-dts.ts", "../../src/vite/codegen/scan-api.ts", "../../src/vite/codegen/write-routes-dts.ts", "../../src/vite/index.ts", "../../src/utils/duration.ts", "../../src/cli/build.ts", "../../src/cli/generate.ts", "../../src/server/routes.ts", "../../src/utils/env.ts", "../../src/cli/start.ts", "../../src/cli/index.ts"],
4
- "sourcesContent": ["import { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nwhile (true) {\n const result = spawnSync(process.execPath, [resolve(__dirname, 'dev-server.js')], {\n stdio: 'inherit',\n env: process.env,\n })\n if (result.status !== 75) break\n}\n\nexport { }", "interface EntryClientOptions {\n cssUrls: string[]\n}\n\nexport function generateEntryClient({ cssUrls }: EntryClientOptions): string {\n const cssImports = cssUrls.map(u => `import '${u}'`).join('\\n')\n\n return `\n${cssImports}\nimport \"@vitejs/plugin-react/preamble\"\nimport React from \"react\"\nimport {hydrateRoot, createRoot} from 'react-dom/client'\nimport {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'\nimport {RouterProvider} from '@devlusoft/devix'\n\nconst root = document.getElementById('devix-root')\n\nif (!window.__DEVIX__) {\n const ErrorPage = getDefaultErrorPage()\n createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))\n} else {\n const {metadata, viewport, clientEntry} = window.__DEVIX__\n const loaderData = window.__LOADER_DATA__\n const layoutsData = window.__LAYOUTS_DATA__ ?? []\n\n const matched = matchClientRoute(window.location.pathname)\n\n if (matched) {\n const [pageMod, ...layoutMods] = await Promise.all([\n matched.load(),\n ...matched.loadLayouts.map(l => l()),\n ])\n hydrateRoot(\n root,\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: loaderData,\n initialParams: matched.params,\n initialPage: pageMod.default,\n initialLayouts: layoutMods.map(m => m.default),\n initialLayoutsData: layoutsData,\n initialMeta: metadata,\n initialViewport: viewport,\n })\n )\n\n if (window.location.hash) {\n const id = window.location.hash.slice(1)\n requestAnimationFrame(() => {\n document.getElementById(id)?.scrollIntoView()\n })\n }\n } else {\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialLayouts: [],\n initialLayoutsData: [],\n initialMeta: null,\n initialError: {statusCode: 404, message: 'Not found'},\n initialErrorPage: ErrorPage,\n })\n )\n }\n}\n`\n}", "interface ClientRoutesOptions {\n pagesDir: string\n matcherPath: string\n}\n\nexport function generateClientRoutes({pagesDir, matcherPath}: ClientRoutesOptions) {\n return `\nimport React from 'react'\nimport { createMatcher } from '${matcherPath}'\nconst pageFiles = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst layoutFiles = import.meta.glob('/${pagesDir}/**/layout.tsx')\nconst errorFiles = import.meta.glob('/${pagesDir}/**/error.tsx')\n\nexport const matchClientRoute = createMatcher(pageFiles, layoutFiles)\n\nexport async function loadErrorPage() {\n const key = Object.keys(errorFiles)[0]\n if (!key) return null\n const mod = await errorFiles[key]()\n return mod?.default ?? null\n}\n\nexport function getDefaultErrorPage() {\n return function DefaultError({ statusCode, message }) {\n return React.createElement('main', {\n style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column', \n alignItems: 'center', justifyContent: 'center', gap: '8px',\n fontFamily: 'system-ui, sans-serif' }\n },\n React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),\n React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),\n )\n }\n}\n`\n}", "interface RenderOptions {\n pagesDir: string\n renderPath: string\n}\n\nexport function generateRender({pagesDir, renderPath}: RenderOptions): string {\n return `\nimport { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${renderPath}'\n\nconst _pages = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst _layouts = import.meta.glob('/${pagesDir}/**/layout.tsx')\n\nconst _glob = {\n pages: _pages,\n layouts: _layouts,\n pagesDir: '/${pagesDir}',\n}\n\nexport function render(url, request, options) {\n return _render(url, request, _glob, options)\n}\n\nexport function runLoader(url, request, options) {\n return _runLoader(url, request, _glob, options)\n}\n\nexport function getStaticRoutes() {\n return _getStaticRoutes(_glob)\n}\n`\n}\n", "interface ApiOptions {\n apiPath: string\n appDir: string\n}\n\nexport function generateApi({apiPath, appDir}: ApiOptions): string {\n return `\nimport { handleApiRequest as _handleApiRequest } from '${apiPath}'\n\nconst _routes = import.meta.glob(['/${appDir}/api/**/*.ts', '!**/middleware.ts'])\nconst _middlewares = import.meta.glob('/${appDir}/api/**/middleware.ts')\n\nconst _glob = {\n routes: _routes,\n middlewares: _middlewares,\n apiDir: '/${appDir}/api',\n}\n\nexport function handleApiRequest(url, request) {\n return _handleApiRequest(url, request, _glob)\n}\n`\n}\n", "export function routePattern(rel: string): string {\n return rel\n .replace(/\\.(tsx|ts|jsx|js)$/, '')\n .replace(/\\(.*?\\)\\//g, '')\n .replace(/^index$|\\/index$/, '')\n .replace(/\\[([^\\]]+)]/g, ':$1')\n || '/'\n}", "import {routePattern} from \"../utils/patterns\";\n\nexport interface Page {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface Layout {\n dir: string\n key: string\n}\n\nexport interface PagesResult {\n pages: Page[]\n layouts: Layout[]\n}\n\nfunction keyToRoutePattern(key: string, pagesDir: string): string {\n const rel = key.slice(pagesDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === \"/\" ? \"/\" : `/${pattern}`\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nlet cache: PagesResult | null = null\n\nexport function invalidatePagesCache() {\n cache = null\n}\n\nexport function buildPages(pageKeys: string[], layoutKeys: string[], pagesDir: string): PagesResult {\n if (cache) return cache\n\n const pages: Page[] = []\n const layouts: Layout[] = []\n\n for (const key of layoutKeys) {\n layouts.push({dir: keyToDir(key), key})\n }\n\n for (const key of pageKeys) {\n const pattern = keyToRoutePattern(key, pagesDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n pages.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n\n pages.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n cache = {pages, layouts}\n return cache\n}\n\nexport function collectLayoutChain(pageKey: string, layouts: Layout[]): Layout[] {\n const pageDir = keyToDir(pageKey)\n\n return layouts\n .filter(layout => pageDir.startsWith(layout.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchPage(pathname: string, pages: Page[]): {\n page: Page\n params: Record<string, string>\n} | null {\n for (const page of pages) {\n const match = pathname.match(page.regex)\n if (match) {\n const params: Record<string, string> = {}\n page.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {page, params}\n }\n }\n return null\n}\n", "import {routePattern} from \"../utils/patterns\";\n\nexport interface ApiRoute {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface ApiMiddleware {\n dir: string\n key: string\n}\n\nexport interface ApiResult {\n routes: ApiRoute[]\n middlewares: ApiMiddleware[]\n}\n\nexport function keyToRoutePattern(key: string, apiDir: string): string {\n const rel = key.slice(apiDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === '/' ? '/api' : `/api/${pattern}`.replace('/api//', '/api/')\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nlet cache: ApiResult | null = null\n\nexport function invalidateApiCache() {\n cache = null\n}\n\nexport function buildRoutes(routeKeys: string[], middlewareKeys: string[], apiDir: string): ApiResult {\n if (cache) return cache\n\n const routes: ApiRoute[] = []\n const middlewares: ApiMiddleware[] = []\n\n for (const key of middlewareKeys) {\n middlewares.push({dir: keyToDir(key), key})\n }\n\n for (const key of routeKeys) {\n const pattern = keyToRoutePattern(key, apiDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n routes.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n routes.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n cache = {routes, middlewares}\n return cache\n}\n\nexport function collectMiddlewareChain(routeKey: string, middlewares: ApiMiddleware[]): ApiMiddleware[] {\n const routeDir = keyToDir(routeKey)\n\n return middlewares\n .filter(mw => routeDir.startsWith(mw.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchRoute(\n pathname: string,\n routes: ApiRoute[]\n): {route: ApiRoute; params: Record<string, string>} | null {\n for (const route of routes) {\n const match = pathname.match(route.regex)\n if (match) {\n const params: Record<string, string> = {}\n route.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {route, params}\n }\n }\n return null\n}\n", "export function generateContext(): string {\n return `\nexport {RouterContext} from '@devlusoft/devix/runtime/context'\n`\n}", "const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nconst METHOD_EXPORT_RE = /export\\s+(?:const|async\\s+function|function)\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/g\n\nfunction stripComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/.*$/gm, '')\n}\n\nexport function extractHttpMethods(content: string): HttpMethod[] {\n const found = new Set<HttpMethod>()\n for (const match of stripComments(content).matchAll(METHOD_EXPORT_RE)) {\n found.add(match[1] as HttpMethod)\n }\n return [...found]\n}\n", "import { keyToRoutePattern } from '../../server/api-router'\nimport type { HttpMethod } from './extract-methods'\n\nexport interface RouteEntry {\n filePath: string\n urlPattern: string\n identifier: string\n methods: HttpMethod[]\n}\n\nexport function filePathToIdentifier(filePath: string, apiDir: string): string {\n return '_api_' + filePath\n .slice(`${apiDir}/`.length)\n .replace(/\\.(ts|tsx)$/, '')\n .replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nexport function buildRouteEntry(filePath: string, apiDir: string, methods: HttpMethod[]): RouteEntry {\n return {\n filePath,\n urlPattern: keyToRoutePattern(filePath, apiDir),\n identifier: filePathToIdentifier(filePath, apiDir),\n methods,\n }\n}\n\nexport function generateRoutesDts(entries: RouteEntry[], apiDir: string): string {\n if (entries.length === 0) {\n return `// auto-generado por devix \u2014 no editar\\ndeclare module '@devlusoft/devix' {\\n interface ApiRoutes {}\\n}\\n`\n }\n\n const imports = entries\n .map(e => {\n const importPath = '../' + e.filePath.replace(/\\.(ts|tsx)$/, '')\n return `import type * as ${e.identifier} from '${importPath}'`\n })\n .join('\\n')\n\n const routeLines = entries.flatMap(e =>\n e.methods.map(m =>\n ` '${m} ${e.urlPattern}': InferRoute<(typeof ${e.identifier})['${m}']>`\n )\n ).join('\\n')\n\n return `// auto-generado por devix \u2014 no editar\n${imports}\n\ntype JsonResponse<T> = Response & { readonly __body: T }\ntype UnwrapJson<T> = T extends JsonResponse<infer U> ? U : never\ntype InferFnReturn<T> = T extends (...args: any[]) => any\n ? UnwrapJson<Awaited<ReturnType<T>>> | Exclude<Awaited<ReturnType<T>>, JsonResponse<any> | null | void | undefined>\n : never\ntype InferRoute<T> =\n T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }\n ? {\n __body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>\n __response: InferFnReturn<() => TReturn>\n }\n : InferFnReturn<T>\n\ndeclare module '@devlusoft/devix' {\n interface ApiRoutes {\n${routeLines}\n }\n}\n`\n}\n", "import {readFileSync, readdirSync, statSync} from 'node:fs'\nimport {join, relative} from 'node:path'\nimport {extractHttpMethods} from './extract-methods'\nimport {buildRouteEntry} from './routes-dts'\nimport type {RouteEntry} from './routes-dts'\n\nfunction walkDir(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkDir(full, root))\n } else if (/\\.(ts|tsx)$/.test(name)) {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport function scanApiFiles(appDir: string, projectRoot: string): RouteEntry[] {\n const apiDir = join(projectRoot, appDir, 'api')\n\n let files: string[]\n try {\n files = walkDir(apiDir, projectRoot)\n } catch {\n return []\n }\n\n return files\n .filter(f => !f.endsWith('middleware.ts') && !f.endsWith('middleware.tsx'))\n .flatMap(filePath => {\n try {\n const content = readFileSync(join(projectRoot, filePath), 'utf-8')\n const methods = extractHttpMethods(content)\n if (methods.length === 0) return []\n return [buildRouteEntry(filePath, `${appDir}/api`, methods)]\n } catch {\n return []\n }\n })\n}\n", "import {mkdirSync, readFileSync, writeFileSync, existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nexport function writeRoutesDts(content: string, projectRoot: string): boolean {\n const devixDir = join(projectRoot, '.devix')\n const outPath = join(devixDir, 'routes.d.ts')\n\n mkdirSync(devixDir, {recursive: true})\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) {\n return false\n }\n\n writeFileSync(outPath, content, 'utf-8')\n return true\n}\n", "import { UserConfig, Plugin, mergeConfig } from 'vite'\nimport type { DevixConfig } from '../config'\nimport react from '@vitejs/plugin-react'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\nimport { generateEntryClient } from './codegen/entry-client'\nimport { generateClientRoutes } from './codegen/client-routes'\nimport { generateRender } from './codegen/render'\nimport { generateApi } from './codegen/api'\nimport { invalidatePagesCache } from \"../server/pages-router\";\nimport { invalidateApiCache } from \"../server/api-router\";\nimport { generateContext } from \"./codegen/context\";\nimport { scanApiFiles } from \"./codegen/scan-api\";\nimport { generateRoutesDts } from \"./codegen/routes-dts\";\nimport { writeRoutesDts } from \"./codegen/write-routes-dts\";\nimport { parseSync } from 'oxc-parser'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst VIRTUAL_ENTRY_CLIENT = 'virtual:devix/entry-client'\nconst VIRTUAL_CLIENT_ROUTES = 'virtual:devix/client-routes'\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\nconst VIRTUAL_CONTEXT = 'virtual:devix/context'\n\nconst SERVER_EXPORTS = new Set(['loader', 'guard', 'generateStaticParams', 'headers'])\n\nexport function devix(config: DevixConfig): UserConfig {\n const appDir = config.appDir ?? 'app'\n const pagesDir = `${appDir}/pages`\n const cssUrls = (config.css ?? []).map(u => u.startsWith('/') ? u : `/${u.replace(/^\\.\\//, '')}`)\n\n const renderPath = resolve(__dirname, '../server/render.js').replace(/\\\\/g, '/')\n const apiPath = resolve(__dirname, '../server/api.js').replace(/\\\\/g, '/')\n const matcherPath = resolve(__dirname, '../runtime/client-router.js').replace(/\\\\/g, '/')\n\n const virtualPlugin: Plugin = {\n name: 'devix',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ENTRY_CLIENT) return `\\0${VIRTUAL_ENTRY_CLIENT}`\n if (id === VIRTUAL_CLIENT_ROUTES) return `\\0${VIRTUAL_CLIENT_ROUTES}`\n if (id === VIRTUAL_RENDER) return `\\0${VIRTUAL_RENDER}`\n if (id === VIRTUAL_API) return `\\0${VIRTUAL_API}`\n if (id === VIRTUAL_CONTEXT) return `\\0${VIRTUAL_CONTEXT}`\n },\n\n load(id) {\n if (id === `\\0${VIRTUAL_ENTRY_CLIENT}`)\n return generateEntryClient({ cssUrls })\n if (id === `\\0${VIRTUAL_CLIENT_ROUTES}`)\n return generateClientRoutes({ pagesDir, matcherPath })\n if (id === `\\0${VIRTUAL_RENDER}`)\n return generateRender({ pagesDir, renderPath })\n if (id === `\\0${VIRTUAL_API}`)\n return generateApi({ apiPath, appDir })\n if (id === `\\0${VIRTUAL_CONTEXT}`)\n return generateContext()\n },\n\n\n transform(code, id, options) {\n if (options?.ssr) return\n\n const resolvedPagesDir = resolve(process.cwd(), pagesDir)\n if (!id.startsWith(resolvedPagesDir)) return\n\n const ast = parseSync(id, code, { sourceType: 'module' })\n\n const replacements: { start: number; end: number; name: string }[] = []\n\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration' || !node.declaration) continue\n\n const decl = node.declaration\n\n if (decl.type === 'FunctionDeclaration' && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n replacements.push({ start: node.start, end: node.end, name: decl.id.name })\n }\n\n if (decl.type === 'VariableDeclaration') {\n const seen = new Set<number>()\n for (const declarator of decl.declarations) {\n if (declarator.id.type === 'Identifier' && SERVER_EXPORTS.has(declarator.id.name)) {\n if (!seen.has(node.start)) {\n seen.add(node.start)\n replacements.push({ start: node.start, end: node.end, name: declarator.id.name })\n }\n }\n }\n }\n }\n\n if (replacements.length === 0) return\n\n replacements.sort((a, b) => b.start - a.start)\n\n let result = code\n for (const { start, end, name } of replacements) {\n result = result.slice(0, start) + `export const ${name} = undefined` + result.slice(end)\n }\n\n return { code: result, map: null }\n },\n\n buildStart() {\n const root = process.cwd()\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n },\n\n configureServer(server) {\n const root = process.cwd()\n\n const regenerateDts = () => {\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n }\n\n server.watcher.add(resolve(root, 'devix.config.ts'))\n server.watcher.on('change', (file) => {\n if (file === resolve(root, 'devix.config.ts')) {\n console.log('[devix] Config changed, restarting...')\n process.exit(75)\n }\n })\n\n server.watcher.on('add', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('change', (file) => {\n if (file.includes(`${appDir}/api`) && !file.endsWith('middleware.ts')) {\n regenerateDts()\n }\n })\n },\n }\n\n const base: UserConfig = {\n plugins: [react(), virtualPlugin],\n publicDir: resolve(process.cwd(), config.publicDir ?? 'public'),\n ssr: { noExternal: ['@devlusoft/devix'] },\n ...(config.envPrefix ? { envPrefix: config.envPrefix } : {}),\n }\n\n return mergeConfig(base, config.vite ?? {})\n}", "export function parseDuration(value: number | string): number {\n if (typeof value === 'number') return value\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/)\n if (!match) throw new Error(`[devix] Invalid duration: \"${value}\". Use a number (ms) or a string like \"5s\", \"2m\", \"500ms\".`)\n const n = parseFloat(match[1])\n switch (match[2]) {\n case 'h': return n * 3_600_000\n case 'm': return n * 60_000\n case 's': return n * 1_000\n case 'ms':\n default: return n\n }\n}\n", "import {writeFileSync} from 'node:fs'\nimport {resolve} from 'node:path'\nimport {build} from 'vite'\nimport type {DevixConfig} from '../config'\nimport {devix} from '../vite'\nimport {parseDuration} from '../utils/duration'\n\nconst config: DevixConfig = (await import(`${process.cwd()}/devix.config.ts`)).default\nconst baseConfig = devix(config)\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n outDir: 'dist/client',\n manifest: true,\n rolldownOptions: {\n input: 'virtual:devix/entry-client',\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n copyPublicDir: false,\n rolldownOptions: {\n input: {\n render: 'virtual:devix/render',\n api: 'virtual:devix/api',\n },\n },\n },\n})\n\nconst runtimeConfig = {\n port: config.port ?? 3000,\n host: config.host ?? false,\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n output: config.output ?? 'server',\n}\n\nwriteFileSync(\n resolve(process.cwd(), 'dist/devix.config.json'),\n JSON.stringify(runtimeConfig, null, 2),\n 'utf-8'\n)\n\n\nexport {}", "import {readFileSync, mkdirSync, writeFileSync} from 'node:fs'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport type {DevixConfig} from '../config'\n\nconst userConfig: DevixConfig = (await import(`${process.cwd()}/devix.config.ts`)).default\nif (userConfig.output !== 'static') {\n console.warn('[devix] Tip: set output: \"static\" in devix.config.ts to skip the SSR server at runtime.')\n}\n\nawait import('./build.js')\n\nconst t = Date.now()\nconst renderModule = await import(resolve(process.cwd(), 'dist/server/render.js') + `?t=${t}`)\n\nconst manifest: Manifest = JSON.parse(\n readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8')\n)\n\nconst urls: string[] = await renderModule.getStaticRoutes()\n\nconsole.log(`[devix] Generating ${urls.length} static page${urls.length === 1 ? '' : 's'}...`)\n\nfor (const url of urls) {\n const fullUrl = `http://localhost${url}`\n const {html, statusCode} = await renderModule.render(fullUrl, new Request(fullUrl), {manifest})\n\n if (statusCode !== 200) {\n console.warn(`[devix] Skipping ${url} \u2014 status ${statusCode}`)\n continue\n }\n\n const outPath = url === '/'\n ? join(process.cwd(), 'dist/client/index.html')\n : join(process.cwd(), 'dist/client', url, 'index.html')\n\n mkdirSync(join(outPath, '..'), {recursive: true})\n writeFileSync(outPath, `<!DOCTYPE html>${html}`, 'utf-8')\n console.log(` \u2713 ${url}`)\n}\n\nconsole.log('[devix] Generation complete.')\n\nexport {}\n", "import type {Hono} from 'hono'\nimport type {Manifest} from 'vite'\n\ninterface ServerOptions {\n renderModule: any\n apiModule: any\n manifest?: Manifest\n loaderTimeout?: number\n}\n\nexport function registerApiRoutes(app: Hono, {apiModule, renderModule, loaderTimeout}: ServerOptions) {\n app.all('/api/*', async (c) => {\n try {\n return await apiModule.handleApiRequest(c.req.url, c.req.raw)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal error'}, 500)\n }\n })\n\n app.get('/_data/*', async (c) => {\n try {\n const {pathname, search} = new URL(c.req.url, 'http://localhost')\n const url = pathname.replace(/^\\/_data/, '') + search\n\n const data = await renderModule.runLoader(url, c.req.raw, {loaderTimeout})\n if (data.error) return c.json({error: 'internal error'}, 500)\n return c.json(data)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal error'}, 500)\n }\n })\n}\n\nexport function registerSsrRoute(app: Hono, {renderModule, manifest, loaderTimeout}: ServerOptions) {\n app.get('*', async (c) => {\n try {\n const {html, statusCode, headers} = await renderModule.render(c.req.url, c.req.raw, {manifest, loaderTimeout})\n const res = c.html(`<!DOCTYPE html>${html}`, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n })\n}", "import {loadEnv} from 'vite'\n\nexport function loadDotenv(mode: string) {\n const env = loadEnv(mode, process.cwd(), '')\n for (const [key, value] of Object.entries(env)) {\n if (process.env[key] === undefined) {\n process.env[key] = value\n }\n }\n}\n", "import {readFileSync} from 'node:fs'\nimport {serve} from '@hono/node-server'\nimport {serveStatic} from '@hono/node-server/serve-static'\nimport {Hono} from 'hono'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport {registerApiRoutes, registerSsrRoute} from '../server/routes'\nimport {loadDotenv} from '../utils/env'\n\nloadDotenv('production')\n\nlet renderModule: any\nlet apiModule: any\nlet manifest: Manifest\nlet runtimeConfig: { port: number, host: string | boolean, loaderTimeout: number, output: 'server' | 'static' }\n\ntry {\n runtimeConfig = JSON.parse(readFileSync(resolve(process.cwd(), 'dist/devix.config.json'), 'utf-8'))\n if (runtimeConfig.output !== 'static') {\n renderModule = await import(resolve(process.cwd(), 'dist/server/render.js'))\n apiModule = await import(resolve(process.cwd(), 'dist/server/api.js'))\n }\n manifest = JSON.parse(readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8'))\n} catch {\n console.error('[devix] Build not found. Run \"devix build\" first.')\n process.exit(1)\n}\n\nconst port = Number(process.env.PORT) || runtimeConfig!.port || 3000\nconst host = typeof runtimeConfig!.host === 'string'\n ? runtimeConfig!.host\n : runtimeConfig!.host ? '0.0.0.0' : (process.env.HOST || '0.0.0.0')\n\nconst app = new Hono()\n\nconst clientRoot = join(process.cwd(), 'dist/client')\n\napp.use('/*', serveStatic({\n root: clientRoot,\n onFound: (_path, c) => {\n c.header('Cache-Control', _path.includes('/assets/')\n ? 'public, immutable, max-age=31536000'\n : 'no-cache')\n }\n}))\n\nif (runtimeConfig!.output === 'static') {\n console.log('[devix] Static mode \u2014 serving pre-generated files from dist/client')\n} else {\n registerApiRoutes(app, {renderModule, apiModule, manifest})\n registerSsrRoute(app, {renderModule, apiModule, manifest, loaderTimeout: runtimeConfig!.loaderTimeout})\n}\n\nserve({fetch: app.fetch, port, hostname: host}, (info) => console.log(`http://${info.address}:${info.port}`))\n\nexport {}", "#!/usr/bin/env node\ndeclare const __DEVIX_VERSION__: string\n\nconst command = process.argv[2]\n\nswitch (command) {\n case 'dev':\n await import(\"./dev.js\")\n break\n case \"build\":\n await import(\"./build.js\")\n break\n case \"generate\":\n await import(\"./generate.js\")\n break\n case \"start\":\n await import(\"./start.js\")\n break\n case '--version':\n case '-v': {\n console.log(__DEVIX_VERSION__)\n break\n }\n case '--help':\n case '-h':\n console.log(`\ndevix \u2014 a lightweight SSR framework\n\nUsage:\n devix dev Start development server\n devix build Build for production\n devix generate Build and generate static HTML (SSG)\n devix start Start production server\n\nOptions:\n -v, --version Show version\n -h, --help Show this help\n\nOutput modes (set in devix.config.ts):\n output: \"server\" SSR mode \u2014 devix start handles requests dynamically (default)\n output: \"static\" SSG mode \u2014 devix generate pre-renders all pages; devix start serves static files only\n `.trim())\n break\n default:\n console.error(`Unknown command: ${command}`)\n console.error('Usage: devix <dev|build|generate|start>')\n process.exit(1)\n}\n\nexport {}"],
5
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,SAAUC,EAAI,EAAIY,GAAS,QAAQ,IAAI,UAAUA,EAAK,OAAO,IAAIA,EAAK,IAAI,EAAE,CAAC,IClD5G,IAAMC,GAAU,QAAQ,KAAK,CAAC,EAE9B,OAAQA,GAAS,CACb,IAAK,MACD,KAAM,sCACN,MACJ,IAAK,QACD,KAAM,kBACN,MACJ,IAAK,WACD,KAAM,mBACN,MACJ,IAAK,QACD,KAAM,mBACN,MACJ,IAAK,YACL,IAAK,KAAM,CACP,QAAQ,IAAI,cAAiB,EAC7B,KACJ,CACA,IAAK,SACL,IAAK,KACD,QAAQ,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,UAgBV,KAAK,CAAC,EACR,MACJ,QACI,QAAQ,MAAM,oBAAoBA,EAAO,EAAE,EAC3C,QAAQ,MAAM,yCAAyC,EACvD,QAAQ,KAAK,CAAC,CACtB",
4
+ "sourcesContent": ["import { spawnSync } from 'node:child_process'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nwhile (true) {\n const result = spawnSync(process.execPath, [resolve(__dirname, 'dev-server.js')], {\n stdio: 'inherit',\n env: process.env,\n })\n if (result.status !== 75) break\n}\n\nexport { }", "interface EntryClientOptions {\n cssUrls: string[]\n}\n\nexport function generateEntryClient({ cssUrls }: EntryClientOptions): string {\n const cssImports = cssUrls.map(u => `import '${u}'`).join('\\n')\n\n return `\n${cssImports}\nimport \"@vitejs/plugin-react/preamble\"\nimport React from \"react\"\nimport {hydrateRoot, createRoot} from 'react-dom/client'\nimport {matchClientRoute, loadErrorPage, getDefaultErrorPage} from 'virtual:devix/client-routes'\nimport {RouterProvider} from '@devlusoft/devix'\n\nconst root = document.getElementById('devix-root')\n\nif (!window.__DEVIX__) {\n const ErrorPage = getDefaultErrorPage()\n createRoot(root).render(React.createElement(ErrorPage, {statusCode: 500, message: 'Server error'}))\n} else {\n const {metadata, viewport, clientEntry} = window.__DEVIX__\n const loaderData = window.__LOADER_DATA__\n const layoutsData = window.__LAYOUTS_DATA__ ?? []\n\n const matched = matchClientRoute(window.location.pathname)\n\n if (matched) {\n const [pageMod, ...layoutMods] = await Promise.all([\n matched.load(),\n ...matched.loadLayouts.map(l => l()),\n ])\n hydrateRoot(\n root,\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: loaderData,\n initialParams: matched.params,\n initialPage: pageMod.default,\n initialLayouts: layoutMods.map(m => m.default),\n initialLayoutsData: layoutsData,\n initialMeta: metadata,\n initialViewport: viewport,\n })\n )\n\n if (window.location.hash) { \n const id = window.location.hash.slice(1) \n const scrollBehavior = getComputedStyle(document.documentElement).scrollBehavior \n requestAnimationFrame(() => { \n document.getElementById(id)?.scrollIntoView({ behavior: scrollBehavior }) \n }) \n } \n } else {\n const ErrorPage = await loadErrorPage() ?? getDefaultErrorPage()\n createRoot(root).render(\n React.createElement(RouterProvider, {\n clientEntry,\n initialData: null,\n initialParams: {},\n initialPage: () => null,\n initialLayouts: [],\n initialLayoutsData: [],\n initialMeta: null,\n initialError: {statusCode: 404, message: 'Not found'},\n initialErrorPage: ErrorPage,\n })\n )\n }\n}\n`\n}", "interface ClientRoutesOptions {\n pagesDir: string\n matcherPath: string\n}\n\nexport function generateClientRoutes({pagesDir, matcherPath}: ClientRoutesOptions) {\n return `\nimport React from 'react'\nimport { createMatcher } from '${matcherPath}'\nconst pageFiles = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst layoutFiles = import.meta.glob('/${pagesDir}/**/layout.tsx')\nconst errorFiles = import.meta.glob('/${pagesDir}/**/error.tsx')\n\nexport const matchClientRoute = createMatcher(pageFiles, layoutFiles)\n\nexport async function loadErrorPage() {\n const key = Object.keys(errorFiles)[0]\n if (!key) return null\n const mod = await errorFiles[key]()\n return mod?.default ?? null\n}\n\nexport function getDefaultErrorPage() {\n return function DefaultError({ statusCode, message }) {\n return React.createElement('main', {\n style: { minHeight: '100dvh', display: 'flex', flexDirection: 'column', \n alignItems: 'center', justifyContent: 'center', gap: '8px',\n fontFamily: 'system-ui, sans-serif' }\n },\n React.createElement('h1', {style: {fontSize: '4rem', fontWeight: 700}}, statusCode),\n React.createElement('p', {style: {color: '#666'}}, message ?? 'An unexpected error occurred'),\n )\n }\n}\n`\n}", "interface RenderOptions {\n pagesDir: string\n renderPath: string\n}\n\nexport function generateRender({pagesDir, renderPath}: RenderOptions): string {\n return `\nimport { render as _render, runLoader as _runLoader, getStaticRoutes as _getStaticRoutes } from '${renderPath}'\n\nconst _pages = import.meta.glob(['/${pagesDir}/**/*.tsx', '!**/error.tsx', '!**/layout.tsx'])\nconst _layouts = import.meta.glob('/${pagesDir}/**/layout.tsx')\n\nconst _glob = {\n pages: _pages,\n layouts: _layouts,\n pagesDir: '/${pagesDir}',\n}\n\nexport function render(url, request, options) {\n return _render(url, request, _glob, options)\n}\n\nexport function runLoader(url, request, options) {\n return _runLoader(url, request, _glob, options)\n}\n\nexport function getStaticRoutes() {\n return _getStaticRoutes(_glob)\n}\n`\n}\n", "interface ApiOptions {\n apiPath: string\n appDir: string\n}\n\nexport function generateApi({apiPath, appDir}: ApiOptions): string {\n return `\nimport { handleApiRequest as _handleApiRequest } from '${apiPath}'\n\nconst _routes = import.meta.glob(['/${appDir}/api/**/*.ts', '!**/middleware.ts'])\nconst _middlewares = import.meta.glob('/${appDir}/api/**/middleware.ts')\n\nconst _glob = {\n routes: _routes,\n middlewares: _middlewares,\n apiDir: '/${appDir}/api',\n}\n\nexport function handleApiRequest(url, request) {\n return _handleApiRequest(url, request, _glob)\n}\n`\n}\n", "export function routePattern(rel: string): string {\n return rel\n .replace(/\\.(tsx|ts|jsx|js)$/, '')\n .replace(/\\(.*?\\)\\//g, '')\n .replace(/^index$|\\/index$/, '')\n .replace(/\\[([^\\]]+)]/g, ':$1')\n || '/'\n}", "import {routePattern} from \"../utils/patterns\";\n\nexport interface Page {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface Layout {\n dir: string\n key: string\n}\n\nexport interface PagesResult {\n pages: Page[]\n layouts: Layout[]\n}\n\nfunction keyToRoutePattern(key: string, pagesDir: string): string {\n const rel = key.slice(pagesDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === \"/\" ? \"/\" : `/${pattern}`\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nlet cache: PagesResult | null = null\n\nexport function invalidatePagesCache() {\n cache = null\n}\n\nexport function buildPages(pageKeys: string[], layoutKeys: string[], pagesDir: string): PagesResult {\n if (cache) return cache\n\n const pages: Page[] = []\n const layouts: Layout[] = []\n\n for (const key of layoutKeys) {\n layouts.push({dir: keyToDir(key), key})\n }\n\n for (const key of pageKeys) {\n const pattern = keyToRoutePattern(key, pagesDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n pages.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n\n pages.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n cache = {pages, layouts}\n return cache\n}\n\nexport function collectLayoutChain(pageKey: string, layouts: Layout[]): Layout[] {\n const pageDir = keyToDir(pageKey)\n\n return layouts\n .filter(layout => pageDir.startsWith(layout.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchPage(pathname: string, pages: Page[]): {\n page: Page\n params: Record<string, string>\n} | null {\n for (const page of pages) {\n const match = pathname.match(page.regex)\n if (match) {\n const params: Record<string, string> = {}\n page.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {page, params}\n }\n }\n return null\n}\n", "import {routePattern} from \"../utils/patterns\";\n\nexport interface ApiRoute {\n path: string\n key: string\n params: string[]\n regex: RegExp\n}\n\nexport interface ApiMiddleware {\n dir: string\n key: string\n}\n\nexport interface ApiResult {\n routes: ApiRoute[]\n middlewares: ApiMiddleware[]\n}\n\nexport function keyToRoutePattern(key: string, apiDir: string): string {\n const rel = key.slice(apiDir.length + 1).replace(/\\\\/g, '/')\n const pattern = routePattern(rel)\n return pattern === '/' ? '/api' : `/api/${pattern}`.replace('/api//', '/api/')\n}\n\nfunction keyToDir(key: string): string {\n return key.slice(0, key.lastIndexOf('/'))\n}\n\nlet cache: ApiResult | null = null\n\nexport function invalidateApiCache() {\n cache = null\n}\n\nexport function buildRoutes(routeKeys: string[], middlewareKeys: string[], apiDir: string): ApiResult {\n if (cache) return cache\n\n const routes: ApiRoute[] = []\n const middlewares: ApiMiddleware[] = []\n\n for (const key of middlewareKeys) {\n middlewares.push({dir: keyToDir(key), key})\n }\n\n for (const key of routeKeys) {\n const pattern = keyToRoutePattern(key, apiDir)\n const params = [...pattern.matchAll(/:([^/]+)/g)].map(m => m[1])\n const regexStr = pattern\n .replace(/:[^/]+/g, '([^/]+)')\n .replace(/\\//g, '\\\\/')\n routes.push({path: pattern, key, params, regex: new RegExp(`^${regexStr}$`)})\n }\n routes.sort((a, b) => {\n const aScore = (a.path.match(/:/g) || []).length\n const bScore = (b.path.match(/:/g) || []).length\n if (aScore !== bScore) return aScore - bScore\n return b.path.length - a.path.length\n })\n\n cache = {routes, middlewares}\n return cache\n}\n\nexport function collectMiddlewareChain(routeKey: string, middlewares: ApiMiddleware[]): ApiMiddleware[] {\n const routeDir = keyToDir(routeKey)\n\n return middlewares\n .filter(mw => routeDir.startsWith(mw.dir))\n .sort((a, b) => a.dir.split('/').length - b.dir.split('/').length)\n}\n\nexport function matchRoute(\n pathname: string,\n routes: ApiRoute[]\n): {route: ApiRoute; params: Record<string, string>} | null {\n for (const route of routes) {\n const match = pathname.match(route.regex)\n if (match) {\n const params: Record<string, string> = {}\n route.params.forEach((name, i) => {\n params[name] = decodeURIComponent(match[i + 1])\n })\n return {route, params}\n }\n }\n return null\n}\n", "export function generateContext(): string {\n return `\nexport {RouterContext} from '@devlusoft/devix/runtime/context'\n`\n}", "const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'] as const\nexport type HttpMethod = (typeof HTTP_METHODS)[number]\n\nconst METHOD_EXPORT_RE = /export\\s+(?:const|async\\s+function|function)\\s+(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\\b/g\n\nfunction stripComments(content: string): string {\n return content\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n .replace(/\\/\\/.*$/gm, '')\n}\n\nexport function extractHttpMethods(content: string): HttpMethod[] {\n const found = new Set<HttpMethod>()\n for (const match of stripComments(content).matchAll(METHOD_EXPORT_RE)) {\n found.add(match[1] as HttpMethod)\n }\n return [...found]\n}\n", "import { keyToRoutePattern } from '../../server/api-router'\nimport type { HttpMethod } from './extract-methods'\n\nexport interface RouteEntry {\n filePath: string\n urlPattern: string\n identifier: string\n methods: HttpMethod[]\n}\n\nexport function filePathToIdentifier(filePath: string, apiDir: string): string {\n return '_api_' + filePath\n .slice(`${apiDir}/`.length)\n .replace(/\\.(ts|tsx)$/, '')\n .replace(/[^a-zA-Z0-9]/g, '_')\n}\n\nexport function buildRouteEntry(filePath: string, apiDir: string, methods: HttpMethod[]): RouteEntry {\n return {\n filePath,\n urlPattern: keyToRoutePattern(filePath, apiDir),\n identifier: filePathToIdentifier(filePath, apiDir),\n methods,\n }\n}\n\nexport function generateRoutesDts(entries: RouteEntry[], apiDir: string): string {\n if (entries.length === 0) {\n return `// auto-generado por devix \u2014 no editar\\ndeclare module '@devlusoft/devix' {\\n interface ApiRoutes {}\\n}\\n`\n }\n\n const imports = entries\n .map(e => {\n const importPath = '../' + e.filePath.replace(/\\.(ts|tsx)$/, '')\n return `import type * as ${e.identifier} from '${importPath}'`\n })\n .join('\\n')\n\n const routeLines = entries.flatMap(e =>\n e.methods.map(m =>\n ` '${m} ${e.urlPattern}': InferRoute<(typeof ${e.identifier})['${m}']>`\n )\n ).join('\\n')\n\n return `// auto-generado por devix \u2014 no editar\n${imports}\n\ntype JsonResponse<T> = Response & { readonly __body: T }\ntype UnwrapJson<T> = T extends JsonResponse<infer U> ? U : never\ntype InferFnReturn<T> = T extends (...args: any[]) => any\n ? UnwrapJson<Awaited<ReturnType<T>>> | Exclude<Awaited<ReturnType<T>>, JsonResponse<any> | null | void | undefined>\n : never\ntype InferRoute<T> =\n T extends { readonly __return?: infer TReturn; readonly __body?: infer TBody }\n ? {\n __body: [TBody] extends [undefined] ? never : Exclude<TBody, undefined>\n __response: InferFnReturn<() => TReturn>\n }\n : InferFnReturn<T>\n\ndeclare module '@devlusoft/devix' {\n interface ApiRoutes {\n${routeLines}\n }\n}\n`\n}\n", "import {readFileSync, readdirSync, statSync} from 'node:fs'\nimport {join, relative} from 'node:path'\nimport {extractHttpMethods} from './extract-methods'\nimport {buildRouteEntry} from './routes-dts'\nimport type {RouteEntry} from './routes-dts'\n\nfunction walkDir(dir: string, root: string): string[] {\n const entries: string[] = []\n for (const name of readdirSync(dir)) {\n const full = join(dir, name)\n if (statSync(full).isDirectory()) {\n entries.push(...walkDir(full, root))\n } else if (/\\.(ts|tsx)$/.test(name)) {\n entries.push(relative(root, full).replace(/\\\\/g, '/'))\n }\n }\n return entries\n}\n\nexport function scanApiFiles(appDir: string, projectRoot: string): RouteEntry[] {\n const apiDir = join(projectRoot, appDir, 'api')\n\n let files: string[]\n try {\n files = walkDir(apiDir, projectRoot)\n } catch {\n return []\n }\n\n return files\n .filter(f => !f.endsWith('middleware.ts') && !f.endsWith('middleware.tsx'))\n .flatMap(filePath => {\n try {\n const content = readFileSync(join(projectRoot, filePath), 'utf-8')\n const methods = extractHttpMethods(content)\n if (methods.length === 0) return []\n return [buildRouteEntry(filePath, `${appDir}/api`, methods)]\n } catch {\n return []\n }\n })\n}\n", "import {mkdirSync, readFileSync, writeFileSync, existsSync} from 'node:fs'\nimport {join} from 'node:path'\n\nexport function writeRoutesDts(content: string, projectRoot: string): boolean {\n const devixDir = join(projectRoot, '.devix')\n const outPath = join(devixDir, 'routes.d.ts')\n\n mkdirSync(devixDir, {recursive: true})\n\n if (existsSync(outPath) && readFileSync(outPath, 'utf-8') === content) {\n return false\n }\n\n writeFileSync(outPath, content, 'utf-8')\n return true\n}\n", "import { UserConfig, Plugin, mergeConfig } from 'vite'\nimport type { DevixConfig } from '../config'\nimport react from '@vitejs/plugin-react'\nimport { fileURLToPath } from 'node:url'\nimport { dirname, resolve } from 'node:path'\nimport { generateEntryClient } from './codegen/entry-client'\nimport { generateClientRoutes } from './codegen/client-routes'\nimport { generateRender } from './codegen/render'\nimport { generateApi } from './codegen/api'\nimport { invalidatePagesCache } from \"../server/pages-router\";\nimport { invalidateApiCache } from \"../server/api-router\";\nimport { generateContext } from \"./codegen/context\";\nimport { scanApiFiles } from \"./codegen/scan-api\";\nimport { generateRoutesDts } from \"./codegen/routes-dts\";\nimport { writeRoutesDts } from \"./codegen/write-routes-dts\";\nimport { parseSync } from 'oxc-parser'\n\nconst __dirname = dirname(fileURLToPath(import.meta.url))\n\nconst VIRTUAL_ENTRY_CLIENT = 'virtual:devix/entry-client'\nconst VIRTUAL_CLIENT_ROUTES = 'virtual:devix/client-routes'\nconst VIRTUAL_RENDER = 'virtual:devix/render'\nconst VIRTUAL_API = 'virtual:devix/api'\nconst VIRTUAL_CONTEXT = 'virtual:devix/context'\n\nconst SERVER_EXPORTS = new Set(['loader', 'guard', 'generateStaticParams', 'headers'])\n\nexport function devix(config: DevixConfig): UserConfig {\n const appDir = config.appDir ?? 'app'\n const pagesDir = `${appDir}/pages`\n const cssUrls = (config.css ?? []).map(u => u.startsWith('/') ? u : `/${u.replace(/^\\.\\//, '')}`)\n\n const renderPath = resolve(__dirname, '../server/render.js').replace(/\\\\/g, '/')\n const apiPath = resolve(__dirname, '../server/api.js').replace(/\\\\/g, '/')\n const matcherPath = resolve(__dirname, '../runtime/client-router.js').replace(/\\\\/g, '/')\n\n const virtualPlugin: Plugin = {\n name: 'devix',\n enforce: 'pre',\n\n resolveId(id) {\n if (id === VIRTUAL_ENTRY_CLIENT) return `\\0${VIRTUAL_ENTRY_CLIENT}`\n if (id === VIRTUAL_CLIENT_ROUTES) return `\\0${VIRTUAL_CLIENT_ROUTES}`\n if (id === VIRTUAL_RENDER) return `\\0${VIRTUAL_RENDER}`\n if (id === VIRTUAL_API) return `\\0${VIRTUAL_API}`\n if (id === VIRTUAL_CONTEXT) return `\\0${VIRTUAL_CONTEXT}`\n },\n\n load(id) {\n if (id === `\\0${VIRTUAL_ENTRY_CLIENT}`)\n return generateEntryClient({ cssUrls })\n if (id === `\\0${VIRTUAL_CLIENT_ROUTES}`)\n return generateClientRoutes({ pagesDir, matcherPath })\n if (id === `\\0${VIRTUAL_RENDER}`)\n return generateRender({ pagesDir, renderPath })\n if (id === `\\0${VIRTUAL_API}`)\n return generateApi({ apiPath, appDir })\n if (id === `\\0${VIRTUAL_CONTEXT}`)\n return generateContext()\n },\n\n\n transform(code, id, options) {\n if (options?.ssr) return\n\n const resolvedPagesDir = resolve(process.cwd(), pagesDir)\n if (!id.startsWith(resolvedPagesDir)) return\n\n const ast = parseSync(id, code, { sourceType: 'module' })\n\n const replacements: { start: number; end: number; name: string }[] = []\n\n for (const node of ast.program.body) {\n if (node.type !== 'ExportNamedDeclaration' || !node.declaration) continue\n\n const decl = node.declaration\n\n if (decl.type === 'FunctionDeclaration' && decl.id && SERVER_EXPORTS.has(decl.id.name)) {\n replacements.push({ start: node.start, end: node.end, name: decl.id.name })\n }\n\n if (decl.type === 'VariableDeclaration') {\n const seen = new Set<number>()\n for (const declarator of decl.declarations) {\n if (declarator.id.type === 'Identifier' && SERVER_EXPORTS.has(declarator.id.name)) {\n if (!seen.has(node.start)) {\n seen.add(node.start)\n replacements.push({ start: node.start, end: node.end, name: declarator.id.name })\n }\n }\n }\n }\n }\n\n if (replacements.length === 0) return\n\n replacements.sort((a, b) => b.start - a.start)\n\n let result = code\n for (const { start, end, name } of replacements) {\n result = result.slice(0, start) + `export const ${name} = undefined` + result.slice(end)\n }\n\n return { code: result, map: null }\n },\n\n buildStart() {\n const root = process.cwd()\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n },\n\n configureServer(server) {\n const root = process.cwd()\n\n const regenerateDts = () => {\n const entries = scanApiFiles(appDir, root)\n writeRoutesDts(generateRoutesDts(entries, `${appDir}/api`), root)\n }\n\n server.watcher.add(resolve(root, 'devix.config.ts'))\n server.watcher.on('change', (file) => {\n if (file === resolve(root, 'devix.config.ts')) {\n console.log('[devix] Config changed, restarting...')\n process.exit(75)\n }\n })\n\n server.watcher.on('add', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('unlink', (file) => {\n if (file.startsWith(resolve(root, pagesDir))) invalidatePagesCache()\n if (file.includes(`${appDir}/api`)) { invalidateApiCache(); regenerateDts() }\n })\n server.watcher.on('change', (file) => {\n if (file.includes(`${appDir}/api`) && !file.endsWith('middleware.ts')) {\n regenerateDts()\n }\n })\n },\n }\n\n const base: UserConfig = {\n plugins: [react(), virtualPlugin],\n publicDir: resolve(process.cwd(), config.publicDir ?? 'public'),\n ssr: { noExternal: ['@devlusoft/devix'] },\n ...(config.envPrefix ? { envPrefix: config.envPrefix } : {}),\n }\n\n return mergeConfig(base, config.vite ?? {})\n}", "export function parseDuration(value: number | string): number {\n if (typeof value === 'number') return value\n const match = value.trim().match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)?$/)\n if (!match) throw new Error(`[devix] Invalid duration: \"${value}\". Use a number (ms) or a string like \"5s\", \"2m\", \"500ms\".`)\n const n = parseFloat(match[1])\n switch (match[2]) {\n case 'h': return n * 3_600_000\n case 'm': return n * 60_000\n case 's': return n * 1_000\n case 'ms':\n default: return n\n }\n}\n", "import {writeFileSync} from 'node:fs'\nimport {resolve} from 'node:path'\nimport {build} from 'vite'\nimport type {DevixConfig} from '../config'\nimport {devix} from '../vite'\nimport {parseDuration} from '../utils/duration'\n\nconst config: DevixConfig = (await import(`${process.cwd()}/devix.config.ts`)).default\nconst baseConfig = devix(config)\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n outDir: 'dist/client',\n manifest: true,\n rolldownOptions: {\n input: 'virtual:devix/entry-client',\n },\n },\n})\n\nawait build({\n ...baseConfig,\n configFile: false,\n build: {\n ssr: true,\n outDir: 'dist/server',\n copyPublicDir: false,\n rolldownOptions: {\n input: {\n render: 'virtual:devix/render',\n api: 'virtual:devix/api',\n },\n },\n },\n})\n\nconst runtimeConfig = {\n port: config.port ?? 3000,\n host: config.host ?? false,\n loaderTimeout: parseDuration(config.loaderTimeout ?? 10_000),\n output: config.output ?? 'server',\n}\n\nwriteFileSync(\n resolve(process.cwd(), 'dist/devix.config.json'),\n JSON.stringify(runtimeConfig, null, 2),\n 'utf-8'\n)\n\n\nexport {}", "import {readFileSync, mkdirSync, writeFileSync} from 'node:fs'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport type {DevixConfig} from '../config'\n\nconst userConfig: DevixConfig = (await import(`${process.cwd()}/devix.config.ts`)).default\nif (userConfig.output !== 'static') {\n console.warn('[devix] Tip: set output: \"static\" in devix.config.ts to skip the SSR server at runtime.')\n}\n\nawait import('./build.js')\n\nconst t = Date.now()\nconst renderModule = await import(resolve(process.cwd(), 'dist/server/render.js') + `?t=${t}`)\n\nconst manifest: Manifest = JSON.parse(\n readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8')\n)\n\nconst urls: string[] = await renderModule.getStaticRoutes()\n\nconsole.log(`[devix] Generating ${urls.length} static page${urls.length === 1 ? '' : 's'}...`)\n\nfor (const url of urls) {\n const fullUrl = `http://localhost${url}`\n const {html, statusCode} = await renderModule.render(fullUrl, new Request(fullUrl), {manifest})\n\n if (statusCode !== 200) {\n console.warn(`[devix] Skipping ${url} \u2014 status ${statusCode}`)\n continue\n }\n\n const outPath = url === '/'\n ? join(process.cwd(), 'dist/client/index.html')\n : join(process.cwd(), 'dist/client', url, 'index.html')\n\n mkdirSync(join(outPath, '..'), {recursive: true})\n writeFileSync(outPath, `<!DOCTYPE html>${html}`, 'utf-8')\n console.log(` \u2713 ${url}`)\n}\n\nconsole.log('[devix] Generation complete.')\n\nexport {}\n", "import type {Hono} from 'hono'\nimport type {Manifest} from 'vite'\n\ninterface ServerOptions {\n renderModule: any\n apiModule: any\n manifest?: Manifest\n loaderTimeout?: number\n}\n\nexport function registerApiRoutes(app: Hono, {apiModule, renderModule, loaderTimeout}: ServerOptions) {\n app.all('/api/*', async (c) => {\n try {\n return await apiModule.handleApiRequest(c.req.url, c.req.raw)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal error'}, 500)\n }\n })\n\n app.get('/_data/*', async (c) => {\n try {\n const {pathname, search} = new URL(c.req.url, 'http://localhost')\n const url = pathname.replace(/^\\/_data/, '') + search\n\n const data = await renderModule.runLoader(url, c.req.raw, {loaderTimeout})\n if (data.error) return c.json({error: 'internal error'}, 500)\n return c.json(data)\n } catch (e) {\n console.error(e)\n return c.json({error: 'internal error'}, 500)\n }\n })\n}\n\nexport function registerSsrRoute(app: Hono, {renderModule, manifest, loaderTimeout}: ServerOptions) {\n app.get('*', async (c) => {\n try {\n const {html, statusCode, headers} = await renderModule.render(c.req.url, c.req.raw, {manifest, loaderTimeout})\n const res = c.html(`<!DOCTYPE html>${html}`, statusCode)\n for (const [key, value] of Object.entries(headers as Record<string, string>)) {\n res.headers.set(key, value)\n }\n return res\n } catch (e) {\n console.error(e)\n return c.text('Internal Server Error', 500)\n }\n })\n}", "import {loadEnv} from 'vite'\n\nexport function loadDotenv(mode: string) {\n const env = loadEnv(mode, process.cwd(), '')\n for (const [key, value] of Object.entries(env)) {\n if (process.env[key] === undefined) {\n process.env[key] = value\n }\n }\n}\n", "import {readFileSync} from 'node:fs'\nimport {serve} from '@hono/node-server'\nimport {serveStatic} from '@hono/node-server/serve-static'\nimport {Hono} from 'hono'\nimport {resolve, join} from 'node:path'\nimport type {Manifest} from 'vite'\nimport {registerApiRoutes, registerSsrRoute} from '../server/routes'\nimport {loadDotenv} from '../utils/env'\n\nloadDotenv('production')\n\nlet renderModule: any\nlet apiModule: any\nlet manifest: Manifest\nlet runtimeConfig: { port: number, host: string | boolean, loaderTimeout: number, output: 'server' | 'static' }\n\ntry {\n runtimeConfig = JSON.parse(readFileSync(resolve(process.cwd(), 'dist/devix.config.json'), 'utf-8'))\n if (runtimeConfig.output !== 'static') {\n renderModule = await import(resolve(process.cwd(), 'dist/server/render.js'))\n apiModule = await import(resolve(process.cwd(), 'dist/server/api.js'))\n }\n manifest = JSON.parse(readFileSync(resolve(process.cwd(), 'dist/client/.vite/manifest.json'), 'utf-8'))\n} catch {\n console.error('[devix] Build not found. Run \"devix build\" first.')\n process.exit(1)\n}\n\nconst port = Number(process.env.PORT) || runtimeConfig!.port || 3000\nconst host = typeof runtimeConfig!.host === 'string'\n ? runtimeConfig!.host\n : runtimeConfig!.host ? '0.0.0.0' : (process.env.HOST || '0.0.0.0')\n\nconst app = new Hono()\n\nconst clientRoot = join(process.cwd(), 'dist/client')\n\napp.use('/*', serveStatic({\n root: clientRoot,\n onFound: (_path, c) => {\n c.header('Cache-Control', _path.includes('/assets/')\n ? 'public, immutable, max-age=31536000'\n : 'no-cache')\n }\n}))\n\nif (runtimeConfig!.output === 'static') {\n console.log('[devix] Static mode \u2014 serving pre-generated files from dist/client')\n} else {\n registerApiRoutes(app, {renderModule, apiModule, manifest})\n registerSsrRoute(app, {renderModule, apiModule, manifest, loaderTimeout: runtimeConfig!.loaderTimeout})\n}\n\nserve({fetch: app.fetch, port, hostname: host}, (info) => console.log(`http://${info.address}:${info.port}`))\n\nexport {}", "#!/usr/bin/env node\ndeclare const __DEVIX_VERSION__: string\n\nconst command = process.argv[2]\n\nswitch (command) {\n case 'dev':\n await import(\"./dev.js\")\n break\n case \"build\":\n await import(\"./build.js\")\n break\n case \"generate\":\n await import(\"./generate.js\")\n break\n case \"start\":\n await import(\"./start.js\")\n break\n case '--version':\n case '-v': {\n console.log(__DEVIX_VERSION__)\n break\n }\n case '--help':\n case '-h':\n console.log(`\ndevix \u2014 a lightweight SSR framework\n\nUsage:\n devix dev Start development server\n devix build Build for production\n devix generate Build and generate static HTML (SSG)\n devix start Start production server\n\nOptions:\n -v, --version Show version\n -h, --help Show this help\n\nOutput modes (set in devix.config.ts):\n output: \"server\" SSR mode \u2014 devix start handles requests dynamically (default)\n output: \"static\" SSG mode \u2014 devix generate pre-renders all pages; devix start serves static files only\n `.trim())\n break\n default:\n console.error(`Unknown command: ${command}`)\n console.error('Usage: devix <dev|build|generate|start>')\n process.exit(1)\n}\n\nexport {}"],
5
+ "mappings": ";mCAAA,IAAAA,GAAA,UAAS,aAAAC,OAAiB,qBAC1B,OAAS,iBAAAC,OAAqB,WAC9B,OAAS,WAAAC,GAAS,WAAAC,OAAe,YAFjC,IAIMC,GAJNC,EAAAC,EAAA,kBAIMF,GAAYF,GAAQD,GAAc,YAAY,GAAG,CAAC,EAExD,KACmBD,GAAU,QAAQ,SAAU,CAACG,GAAQC,GAAW,eAAe,CAAC,EAAG,CAC9E,MAAO,UACP,IAAK,QAAQ,GACjB,CAAC,EACU,SAAW,IAAtB,ICPG,SAASG,EAAoB,CAAE,QAAAC,CAAQ,EAA+B,CAGzE,MAAO;AAAA,EAFYA,EAAQ,IAAIC,GAAK,WAAWA,CAAC,GAAG,EAAE,KAAK;AAAA,CAAI,CAGtD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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", "dirname", "resolve", "__dirname", "init_dev", "__esmMin", "generateEntryClient", "cssUrls", "u", "init_entry_client", "__esmMin", "generateClientRoutes", "pagesDir", "matcherPath", "init_client_routes", "__esmMin", "generateRender", "pagesDir", "renderPath", "init_render", "__esmMin", "generateApi", "apiPath", "appDir", "init_api", "__esmMin", "routePattern", "rel", "init_patterns", "__esmMin", "invalidatePagesCache", "cache", "init_pages_router", "__esmMin", "init_patterns", "keyToRoutePattern", "key", "apiDir", "rel", "pattern", "routePattern", "invalidateApiCache", "cache", "init_api_router", "__esmMin", "init_patterns", "generateContext", "init_context", "__esmMin", "stripComments", "content", "extractHttpMethods", "found", "match", "METHOD_EXPORT_RE", "init_extract_methods", "__esmMin", "filePathToIdentifier", "filePath", "apiDir", "buildRouteEntry", "methods", "keyToRoutePattern", "generateRoutesDts", "entries", "imports", "e", "importPath", "routeLines", "m", "init_routes_dts", "__esmMin", "init_api_router", "readFileSync", "readdirSync", "statSync", "join", "relative", "walkDir", "dir", "root", "entries", "name", "full", "scanApiFiles", "appDir", "projectRoot", "apiDir", "files", "f", "filePath", "content", "methods", "extractHttpMethods", "buildRouteEntry", "init_scan_api", "__esmMin", "init_extract_methods", "init_routes_dts", "mkdirSync", "readFileSync", "writeFileSync", "existsSync", "join", "writeRoutesDts", "content", "projectRoot", "devixDir", "outPath", "init_write_routes_dts", "__esmMin", "mergeConfig", "react", "fileURLToPath", "dirname", "resolve", "parseSync", "devix", "config", "appDir", "pagesDir", "cssUrls", "u", "renderPath", "__dirname", "apiPath", "matcherPath", "virtualPlugin", "id", "VIRTUAL_ENTRY_CLIENT", "VIRTUAL_CLIENT_ROUTES", "VIRTUAL_RENDER", "VIRTUAL_API", "VIRTUAL_CONTEXT", "generateEntryClient", "generateClientRoutes", "generateRender", "generateApi", "generateContext", "code", "options", "resolvedPagesDir", "ast", "replacements", "node", "decl", "SERVER_EXPORTS", "seen", "declarator", "a", "b", "result", "start", "end", "name", "root", "entries", "scanApiFiles", "writeRoutesDts", "generateRoutesDts", "server", "regenerateDts", "file", "invalidatePagesCache", "invalidateApiCache", "base", "init_vite", "__esmMin", "init_entry_client", "init_client_routes", "init_render", "init_api", "init_pages_router", "init_api_router", "init_context", "init_scan_api", "init_routes_dts", "init_write_routes_dts", "parseDuration", "value", "match", "n", "init_duration", "__esmMin", "build_exports", "writeFileSync", "resolve", "build", "config", "baseConfig", "runtimeConfig", "init_build", "__esmMin", "init_vite", "init_duration", "devix", "parseDuration", "generate_exports", "readFileSync", "mkdirSync", "writeFileSync", "resolve", "join", "userConfig", "t", "renderModule", "manifest", "urls", "init_generate", "__esmMin", "url", "fullUrl", "html", "statusCode", "outPath", "registerApiRoutes", "app", "apiModule", "renderModule", "loaderTimeout", "c", "e", "pathname", "search", "url", "data", "registerSsrRoute", "manifest", "html", "statusCode", "headers", "res", "key", "value", "init_routes", "__esmMin", "loadEnv", "loadDotenv", "mode", "env", "key", "value", "init_env", "__esmMin", "start_exports", "readFileSync", "serve", "serveStatic", "Hono", "resolve", "join", "renderModule", "apiModule", "manifest", "runtimeConfig", "port", "host", "app", "clientRoot", "init_start", "__esmMin", "init_routes", "init_env", "loadDotenv", "_path", "c", "registerApiRoutes", "registerSsrRoute", "info", "command"]
7
7
  }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,22 @@
1
+ import type { UserConfig } from "vite";
2
+ export interface DevixConfig {
3
+ port?: number;
4
+ host?: string | boolean;
5
+ css?: string[];
6
+ appDir?: string;
7
+ publicDir?: string;
8
+ envPrefix?: string | string[];
9
+ html?: {
10
+ lang?: string;
11
+ };
12
+ vite?: UserConfig;
13
+ loaderTimeout?: number | string;
14
+ output?: 'server' | 'static';
15
+ }
16
+ export interface ResolvedDirs {
17
+ appDir: string;
18
+ pagesDir: string;
19
+ apiDir: string;
20
+ }
21
+ export declare function defineConfig(config: DevixConfig): DevixConfig;
22
+ export declare function resolveDirs(config: DevixConfig): ResolvedDirs;
@@ -0,0 +1,24 @@
1
+ import type { DevixHandler } from './create-handler';
2
+ export declare class RouteContext {
3
+ readonly params: Record<string, string>;
4
+ private _state;
5
+ constructor(params?: Record<string, string>);
6
+ set<T>(key: string, value: T): void;
7
+ get<T>(key: string): T | undefined;
8
+ }
9
+ export type RouteResult = Response | Record<string, unknown> | unknown[] | null | void;
10
+ export type RouteHandler = (ctx: RouteContext, req: Request) => Promise<RouteResult> | RouteResult;
11
+ export interface MiddlewareModule {
12
+ middleware: (ctx: RouteContext, req: Request) => Promise<Response | null> | Response | null;
13
+ }
14
+ type AnyHandler = RouteHandler | DevixHandler<any, any>;
15
+ export interface RouteModule {
16
+ GET?: AnyHandler;
17
+ POST?: AnyHandler;
18
+ PUT?: AnyHandler;
19
+ PATCH?: AnyHandler;
20
+ DELETE?: AnyHandler;
21
+ HEAD?: AnyHandler;
22
+ OPTIONS?: AnyHandler;
23
+ }
24
+ export {};
@@ -0,0 +1,13 @@
1
+ import { ComponentType } from "react";
2
+ export interface ClientMatch {
3
+ load: () => Promise<{
4
+ default: ComponentType<any>;
5
+ }>;
6
+ loadLayouts: Array<() => Promise<{
7
+ default: ComponentType<any>;
8
+ }>>;
9
+ params: Record<string, string>;
10
+ }
11
+ type GlobMap = Record<string, () => Promise<any>>;
12
+ export declare function createMatcher(pageFiles: GlobMap, layoutFiles: GlobMap): (pathname: string) => ClientMatch | null;
13
+ export {};
@@ -0,0 +1,32 @@
1
+ import { Context, ComponentType } from "react";
2
+ import { Metadata, Viewport } from "../types";
3
+ import { LayoutProps, PageProps } from "../server/types";
4
+ export interface NavigateOptions {
5
+ replace?: boolean;
6
+ viewTransition?: boolean;
7
+ }
8
+ export interface RouterContextValue {
9
+ pathname: string;
10
+ params: Record<string, string>;
11
+ loaderData: unknown;
12
+ layoutsData: unknown[];
13
+ Page: ComponentType<PageProps>;
14
+ layouts: ComponentType<LayoutProps>[];
15
+ metadata: Metadata | null;
16
+ viewport?: Viewport;
17
+ navigate: (to: string, options?: NavigateOptions) => Promise<void>;
18
+ revalidate: () => Promise<void>;
19
+ isNavigating: boolean;
20
+ }
21
+ export interface PageMetaContextValue {
22
+ metadata: Metadata | null;
23
+ viewport?: Viewport;
24
+ clientEntry?: string;
25
+ }
26
+ export interface RouteDataContextValue {
27
+ loaderData: unknown;
28
+ params: Record<string, string>;
29
+ }
30
+ export declare const RouterContext: Context<RouterContextValue | null>;
31
+ export declare const PageMetaContext: Context<PageMetaContextValue | null>;
32
+ export declare const RouteDataContext: Context<RouteDataContextValue | null>;
@@ -0,0 +1,10 @@
1
+ export declare const HANDLER_BRAND: "__devix_handler__";
2
+ export interface DevixHandler<TBody = undefined, TReturn = unknown> {
3
+ readonly [HANDLER_BRAND]: true;
4
+ readonly fn: (...args: any[]) => any;
5
+ readonly __body: TBody;
6
+ readonly __return: TReturn;
7
+ }
8
+ type ExtractBody<TFn> = TFn extends (body: infer B) => any ? B : undefined;
9
+ export declare function createHandler<TFn extends (...args: any[]) => any>(fn: TFn): DevixHandler<ExtractBody<TFn>, Awaited<ReturnType<TFn>>>;
10
+ export {};
@@ -0,0 +1,19 @@
1
+ import { Component, ComponentType, ReactNode } from "react";
2
+ import { ErrorProps } from "../server/types";
3
+ interface Props {
4
+ ErrorPage?: ComponentType<ErrorProps>;
5
+ children: ReactNode;
6
+ }
7
+ interface State {
8
+ error: ErrorProps | null;
9
+ }
10
+ export declare class DevixErrorBoundary extends Component<Props, State> {
11
+ state: State;
12
+ static getDerivedStateFromError(err: unknown): State;
13
+ render(): string | number | bigint | boolean | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import("react").ReactPortal | import("react").ReactElement<unknown, string | import("react").JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | import("react/jsx-runtime").JSX.Element | null | undefined;
14
+ }
15
+ export declare class DevixError extends Error {
16
+ statusCode: number;
17
+ constructor(statusCode: number, message: string);
18
+ }
19
+ export {};
@@ -0,0 +1,39 @@
1
+ export interface ApiRoutes {
2
+ }
3
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
4
+ type ApiKey<M extends HttpMethod, P extends string> = `${M} ${P}`;
5
+ type RouteData<M extends HttpMethod, P extends string> = ApiKey<M, P> extends keyof ApiRoutes ? ApiRoutes[ApiKey<M, P>] : unknown;
6
+ type AllApiPaths = {
7
+ [K in keyof ApiRoutes]: K extends `${HttpMethod} ${infer P}` ? P : never;
8
+ }[keyof ApiRoutes];
9
+ type ApiPath = [AllApiPaths] extends [never] ? string : AllApiPaths | (string & {});
10
+ type ExtractBody<D> = D extends {
11
+ __body: infer B;
12
+ } ? B : never;
13
+ type UnwrapReturn<R> = R extends {
14
+ __body: infer B;
15
+ } ? B : R extends void | undefined ? never : R;
16
+ type ExtractResponse<D> = D extends {
17
+ __return: infer R;
18
+ } ? UnwrapReturn<R> : D extends {
19
+ __response: infer R;
20
+ } ? R : D;
21
+ type InferBody<M extends HttpMethod, P extends string> = ExtractBody<RouteData<M, P>>;
22
+ type InferResult<M extends HttpMethod, P extends string> = ExtractResponse<RouteData<M, P>>;
23
+ type BodyOption<M extends HttpMethod, P extends string> = [
24
+ InferBody<M, P>
25
+ ] extends [never] ? unknown : InferBody<M, P>;
26
+ export interface FetchOptions<M extends HttpMethod = 'GET', P extends string = string> {
27
+ method?: M;
28
+ body?: BodyOption<M, P>;
29
+ headers?: HeadersInit;
30
+ signal?: AbortSignal;
31
+ }
32
+ export declare class FetchError extends Error {
33
+ readonly status: number;
34
+ readonly statusText: string;
35
+ readonly response: Response;
36
+ constructor(status: number, statusText: string, response: Response);
37
+ }
38
+ export declare function $fetch<P extends ApiPath = ApiPath, M extends HttpMethod = 'GET'>(path: P, options?: FetchOptions<M, P>): Promise<InferResult<M, P>>;
39
+ export {};
@@ -0,0 +1,7 @@
1
+ import { Metadata, Viewport } from "../types";
2
+ import { ReactNode } from "react";
3
+ export declare function HeadSlot({ metadata, viewport }: {
4
+ metadata: Metadata | null;
5
+ viewport?: Viewport;
6
+ }): import("react/jsx-runtime").JSX.Element | null;
7
+ export declare function buildHeadNodes(metadata: Metadata, viewport?: Viewport): ReactNode;
@@ -0,0 +1,14 @@
1
+ export { useRouter, useNavigate, useRevalidate, useParams, useLoaderData, RouterProvider } from "./router-provider";
2
+ export { Link } from "./link";
3
+ export type { Metadata, Viewport, LoaderContext, LoaderContextWithGuard, LoaderFunction, GuardFunction } from '../types';
4
+ export type { NavigateOptions } from './context';
5
+ export type { PageProps, LayoutProps, PageModule, LayoutModule, ErrorProps } from '../server/types';
6
+ export type { RouteHandler, RouteResult } from './api-context';
7
+ export { getCookie, setCookie, deleteCookie } from '../utils/cookies';
8
+ export type { CookieOptions } from '../utils/cookies';
9
+ export { json, text, redirect } from '../utils/response';
10
+ export type { JsonResponse, Redirect, RedirectOptions } from '../utils/response';
11
+ export { $fetch, FetchError } from './fetch';
12
+ export type { ApiRoutes, FetchOptions } from './fetch';
13
+ export { createHandler } from './create-handler';
14
+ export type { DevixHandler } from './create-handler';
@@ -1,2 +1,2 @@
1
- import{useCallback as V,useContext as T,useEffect as Z,useRef as ee,useState as K}from"react";import{RouterContext as b}from"virtual:devix/context";import{getDefaultErrorPage as U,loadErrorPage as G,matchClientRoute as te}from"virtual:devix/client-routes";import{Fragment as I,jsx as P}from"react/jsx-runtime";function Q(e,t){let r=[];e.title&&r.push({tag:"title",children:e.title}),e.description&&r.push({tag:"meta",name:"description",content:e.description}),e.keywords?.length&&r.push({tag:"meta",name:"keywords",content:e.keywords.join(", ")});let n=e.og?.title??e.title;n&&r.push({tag:"meta",property:"og:title",content:n});let a=e.og?.description??e.description;a&&r.push({tag:"meta",property:"og:description",content:a}),e.og?.image&&r.push({tag:"meta",property:"og:image",content:e.og.image}),e.og?.type&&r.push({tag:"meta",property:"og:type",content:e.og.type}),e.og?.url&&r.push({tag:"meta",property:"og:url",content:e.og.url});let s=e.twitter?.title??e.title;s&&r.push({tag:"meta",name:"twitter:title",content:s});let y=e.twitter?.description??e.description;if(y&&r.push({tag:"meta",name:"twitter:description",content:y}),e.twitter?.card&&r.push({tag:"meta",name:"twitter:card",content:e.twitter.card}),e.twitter?.image&&r.push({tag:"meta",name:"twitter:image",content:e.twitter.image}),e.twitter?.creator&&r.push({tag:"meta",name:"twitter:creator",content:e.twitter.creator}),e.canonical&&r.push({tag:"link",rel:"canonical",href:e.canonical}),e.robots&&r.push({tag:"meta",name:"robots",content:e.robots}),e.alternates)for(let[c,u]of Object.entries(e.alternates))r.push({tag:"link",rel:"alternate",href:u,hrefLang:c});if(t){let c=[];t.width!==void 0&&c.push(`width=${t.width}`),t.initialScale!==void 0&&c.push(`initial-scale=${t.initialScale}`),t.maximumScale!==void 0&&c.push(`maximum-scale=${t.maximumScale}`),t.userScalable!==void 0&&c.push(`user-scalable=${t.userScalable?"yes":"no"}`),c.length&&r.push({tag:"meta",name:"viewport",content:c.join(", ")}),t.themeColor&&r.push({tag:"meta",name:"theme-color",content:t.themeColor})}return r}function O({metadata:e,viewport:t}){return typeof window>"u"||!e?null:P(I,{children:X(e,t)})}function X(e,t){let r=Q(e,t);return P(I,{children:r.map((n,a)=>n.tag==="title"?P("title",{children:n.children},a):n.tag==="link"?P("link",{rel:n.rel,href:n.href,hrefLang:n.hrefLang},a):P("meta",{name:n.name,property:n.property,content:n.content},a))})}import{createContext as H}from"react";var w=globalThis;w.__devix_RouterContext__??=H(null);var Ae=w.__devix_RouterContext__;w.__devix_PageMetaContext__??=H(null);w.__devix_RouteDataContext__??=H(null);var F=w.__devix_PageMetaContext__,C=w.__devix_RouteDataContext__;import{Component as Y}from"react";import{jsx as j}from"react/jsx-runtime";var M=class extends Y{state={error:null};static getDerivedStateFromError(t){return t instanceof N?{error:{statusCode:t.statusCode,message:t.message}}:{error:{statusCode:500,message:t instanceof Error?t.message:"Unknown error"}}}render(){return this.state.error&&this.props.ErrorPage?j(this.props.ErrorPage,{...this.state.error}):this.state.error?j("h1",{children:this.state.error.statusCode}):this.props.children}},N=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t}};import{jsx as m,jsxs as de}from"react/jsx-runtime";function re(){return T(b)}var ne=()=>Promise.resolve(),oe=()=>Promise.resolve();function ae(){return T(b)?.navigate??ne}function ie(){return T(b)?.revalidate??oe}function se(){let e=T(C);if(!e)throw new Error("useParams must be used within a route or layout");return e.params}function pe(){let e=T(C);if(!e)throw new Error("useLoaderData must be used within a route or layout");return e.loaderData}function le({initialData:e,initialParams:t,initialPage:r,initialLayouts:n=[],initialLayoutsData:a=[],initialMeta:s,initialViewport:y,initialError:c,initialErrorPage:u,clientEntry:h}){let[o,E]=K({pathname:window.location.pathname,params:t,loaderData:e,layoutsData:a,Page:r,layouts:n,metadata:s??null,viewport:y,pendingError:c,ErrorPage:u}),v=ee(null),[q,B]=K(!1),R=V(async(p,l)=>{let d=p.split("?")[0].split("#")[0],i=te(d);if(!i){let g=await G()??U();E(S=>({...S,pathname:d,pendingError:{statusCode:404,message:"Not found"},ErrorPage:g??void 0}));return}let[x,...L]=await Promise.all([i.load(),...i.loadLayouts.map(g=>g())]);if(l.signal.aborted||!x.default)return;let D=await fetch(`/_data${p}`,{headers:{Accept:"application/json"},signal:l.signal});if(l.signal.aborted)return;if(!D.ok){if(D.status===404){window.location.href=p;return}let g=await G()??U();E(S=>({...S,pathname:d,pendingError:{statusCode:D.status,message:"Server error"},ErrorPage:g??void 0}));return}let f=await D.json();if(f.redirect){f.redirectReplace?window.history.replaceState(null,"",f.redirect):window.history.pushState(null,"",f.redirect),await R(f.redirect,l);return}E({pathname:d,params:f.params??{},loaderData:f.loaderData,layoutsData:(f.layouts??[]).map(g=>g.loaderData),Page:x.default,layouts:L.map(g=>g.default),metadata:f.metadata??null,viewport:f.viewport});let $=p.includes("#")?p.split("#")[1]:null;$?requestAnimationFrame(()=>{document.getElementById($)?.scrollIntoView()}):window.scrollTo(0,0)},[]),_=V(async(p,l)=>{v.current?.abort();let d=new AbortController;v.current=d,B(!0);let i=async()=>{window.history[l?.replace?"replaceState":"pushState"](null,"",p),await R(p,d)};try{l?.viewTransition&&"startViewTransition"in document?await document.startViewTransition(i).finished:await i()}finally{d.signal.aborted||B(!1)}},[R]),z=V(async()=>{let p=window.location.pathname+window.location.search,l=new AbortController,d=await fetch(`/_data${p}`,{headers:{Accept:"application/json"},signal:l.signal});if(!d.ok)return;let i=await d.json();if(i.redirect){await _(i.redirect,{replace:i.redirectReplace});return}E(x=>({...x,loaderData:i.loaderData,layoutsData:(i.layouts??[]).map(L=>L.loaderData),params:i.params??x.params,metadata:i.metadata??x.metadata,viewport:i.viewport??x.viewport}))},[_]);Z(()=>{let p=()=>{v.current?.abort();let l=new AbortController;v.current=l;let d=window.location.pathname+window.location.search;R(d,l).catch(i=>{i.name!=="AbortError"&&console.error("[router] popstate error:",i)})};return window.addEventListener("popstate",p),()=>window.removeEventListener("popstate",p)},[R]);let A;if(o.pendingError)A=o.ErrorPage?m(o.ErrorPage,{...o.pendingError}):m("h1",{children:o.pendingError.statusCode});else{let p=m(C,{value:{loaderData:o.loaderData,params:o.params},children:m(o.Page,{data:o.loaderData,params:o.params,url:o.pathname})});for(let l=o.layouts.length-1;l>=0;l--){let d=o.layouts[l],i=o.layoutsData[l];p=m(C,{value:{loaderData:i,params:o.params},children:m(d,{data:i,params:o.params,children:p})})}A=m(M,{ErrorPage:o.ErrorPage,children:p},o.pathname)}return de(F,{value:{metadata:o.metadata,viewport:o.viewport,clientEntry:h},children:[m(O,{metadata:o.metadata,viewport:o.viewport}),m(b,{value:{...o,isNavigating:q,navigate:_,revalidate:z},children:A})]})}import{useCallback as ue,useContext as ce}from"react";import{matchClientRoute as fe}from"virtual:devix/client-routes";import{RouterContext as ge}from"virtual:devix/context";import{jsx as ye}from"react/jsx-runtime";function J(e){if(e.startsWith("/")||e.startsWith("http"))return e;let t=window.location.pathname.endsWith("/")?window.location.href:window.location.href+"/",r=new URL(e,t).pathname;return r.length>1?r.replace(/\/$/,""):r}function me({href:e,prefetch:t=!1,viewTransition:r=!1,children:n,...a}){let s=ce(ge),y=ue(()=>{if(!t)return;let u=J(e),h=u.split("?")[0].split("#")[0],o=fe(h);o&&(o.load().catch(()=>{}),fetch(`/_data${u}`,{headers:{Accept:"application/json"}}).catch(()=>{}))},[e,t]);return ye("a",{href:e,onClick:u=>{if(s&&!u.ctrlKey&&!u.metaKey&&!u.shiftKey&&u.button===0){u.preventDefault();let h=J(e);r&&typeof document.startViewTransition=="function"?document.startViewTransition(()=>s.navigate(h)):s.navigate(h)}},onMouseEnter:y,...a,children:n})}function xe(e,t){let r=e.headers.get("cookie");if(r)for(let n of r.split(";")){let[a,...s]=n.trim().split("=");if(a.trim()===t)return decodeURIComponent(s.join("="))}}function W(e,t,r,n={}){let a=`${t}=${encodeURIComponent(r)}; Path=${n.path??"/"}`;n.domain&&(a+=`; Domain=${n.domain}`),n.maxAge!==void 0&&(a+=`; Max-Age=${n.maxAge}`),n.expires&&(a+=`; Expires=${n.expires.toUTCString()}`),n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.sameSite&&(a+=`; SameSite=${n.sameSite}`),e.append("Set-Cookie",a)}function he(e,t,r={}){W(e,t,"",{...r,maxAge:0,expires:new Date(0)})}var we=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}}),Re=(e,t=200)=>new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8"}}),Pe=Symbol("devix.redirect");function Ce(e,t){let r=typeof t=="number"?t:t?.status??302,n=typeof t=="object"?t?.replace??!1:!1;return{[Pe]:!0,url:e,status:r,replace:n}}var k=class extends Error{constructor(r,n,a){super(`HTTP ${r}: ${n}`);this.status=r;this.statusText=n;this.response=a;this.name="FetchError"}};async function Te(e,t){let r=t?.method??"GET",n=new Headers(t?.headers),a;t?.body!==void 0&&(a=JSON.stringify(t.body),n.has("Content-Type")||n.set("Content-Type","application/json"));let s=await fetch(e,{method:r,headers:n,body:a,signal:t?.signal});if(!s.ok)throw new k(s.status,s.statusText,s);return(s.headers.get("Content-Type")??"").includes("application/json")?s.json():s.text()}var Ee="__devix_handler__";function ve(e){return{[Ee]:!0,fn:e}}export{Te as $fetch,k as FetchError,me as Link,le as RouterProvider,ve as createHandler,he as deleteCookie,xe as getCookie,we as json,Ce as redirect,W as setCookie,Re as text,pe as useLoaderData,ae as useNavigate,se as useParams,ie as useRevalidate,re as useRouter};
1
+ import{useCallback as B,useContext as v,useEffect as ee,useRef as te,useState as U}from"react";import{RouterContext as b}from"virtual:devix/context";import{getDefaultErrorPage as G,loadErrorPage as J,matchClientRoute as re}from"virtual:devix/client-routes";import{Fragment as F,jsx as P}from"react/jsx-runtime";function X(e,t){let r=[];e.title&&r.push({tag:"title",children:e.title}),e.description&&r.push({tag:"meta",name:"description",content:e.description}),e.keywords?.length&&r.push({tag:"meta",name:"keywords",content:e.keywords.join(", ")});let o=e.og?.title??e.title;o&&r.push({tag:"meta",property:"og:title",content:o});let a=e.og?.description??e.description;a&&r.push({tag:"meta",property:"og:description",content:a}),e.og?.image&&r.push({tag:"meta",property:"og:image",content:e.og.image}),e.og?.type&&r.push({tag:"meta",property:"og:type",content:e.og.type}),e.og?.url&&r.push({tag:"meta",property:"og:url",content:e.og.url});let s=e.twitter?.title??e.title;s&&r.push({tag:"meta",name:"twitter:title",content:s});let y=e.twitter?.description??e.description;if(y&&r.push({tag:"meta",name:"twitter:description",content:y}),e.twitter?.card&&r.push({tag:"meta",name:"twitter:card",content:e.twitter.card}),e.twitter?.image&&r.push({tag:"meta",name:"twitter:image",content:e.twitter.image}),e.twitter?.creator&&r.push({tag:"meta",name:"twitter:creator",content:e.twitter.creator}),e.canonical&&r.push({tag:"link",rel:"canonical",href:e.canonical}),e.robots&&r.push({tag:"meta",name:"robots",content:e.robots}),e.alternates)for(let[c,u]of Object.entries(e.alternates))r.push({tag:"link",rel:"alternate",href:u,hrefLang:c});if(t){let c=[];t.width!==void 0&&c.push(`width=${t.width}`),t.initialScale!==void 0&&c.push(`initial-scale=${t.initialScale}`),t.maximumScale!==void 0&&c.push(`maximum-scale=${t.maximumScale}`),t.userScalable!==void 0&&c.push(`user-scalable=${t.userScalable?"yes":"no"}`),c.length&&r.push({tag:"meta",name:"viewport",content:c.join(", ")}),t.themeColor&&r.push({tag:"meta",name:"theme-color",content:t.themeColor})}return r}function I({metadata:e,viewport:t}){return typeof window>"u"||!e?null:P(F,{children:Y(e,t)})}function Y(e,t){let r=X(e,t);return P(F,{children:r.map((o,a)=>o.tag==="title"?P("title",{children:o.children},a):o.tag==="link"?P("link",{rel:o.rel,href:o.href,hrefLang:o.hrefLang},a):P("meta",{name:o.name,property:o.property,content:o.content},a))})}import{createContext as H}from"react";var w=globalThis;w.__devix_RouterContext__??=H(null);var Le=w.__devix_RouterContext__;w.__devix_PageMetaContext__??=H(null);w.__devix_RouteDataContext__??=H(null);var j=w.__devix_PageMetaContext__,C=w.__devix_RouteDataContext__;import{Component as Z}from"react";import{jsx as K}from"react/jsx-runtime";var M=class extends Z{state={error:null};static getDerivedStateFromError(t){return t instanceof N?{error:{statusCode:t.statusCode,message:t.message}}:{error:{statusCode:500,message:t instanceof Error?t.message:"Unknown error"}}}render(){return this.state.error&&this.props.ErrorPage?K(this.props.ErrorPage,{...this.state.error}):this.state.error?K("h1",{children:this.state.error.statusCode}):this.props.children}},N=class extends Error{statusCode;constructor(t,r){super(r),this.statusCode=t}};import{jsx as m,jsxs as ue}from"react/jsx-runtime";function oe(){return v(b)}var ne=()=>Promise.resolve(),ae=()=>Promise.resolve();function ie(){return v(b)?.navigate??ne}function se(){return v(b)?.revalidate??ae}function pe(){let e=v(C);if(!e)throw new Error("useParams must be used within a route or layout");return e.params}function le(){let e=v(C);if(!e)throw new Error("useLoaderData must be used within a route or layout");return e.loaderData}function de({initialData:e,initialParams:t,initialPage:r,initialLayouts:o=[],initialLayoutsData:a=[],initialMeta:s,initialViewport:y,initialError:c,initialErrorPage:u,clientEntry:h}){let[n,T]=U({pathname:window.location.pathname,params:t,loaderData:e,layoutsData:a,Page:r,layouts:o,metadata:s??null,viewport:y,pendingError:c,ErrorPage:u}),E=te(null),[z,V]=U(!1),R=B(async(p,l)=>{let d=p.split("?")[0].split("#")[0],i=re(d);if(!i){let g=await J()??G();T(S=>({...S,pathname:d,pendingError:{statusCode:404,message:"Not found"},ErrorPage:g??void 0}));return}let[x,...L]=await Promise.all([i.load(),...i.loadLayouts.map(g=>g())]);if(l.signal.aborted||!x.default)return;let D=await fetch(`/_data${p}`,{headers:{Accept:"application/json"},signal:l.signal});if(l.signal.aborted)return;if(!D.ok){if(D.status===404){window.location.href=p;return}let g=await J()??G();T(S=>({...S,pathname:d,pendingError:{statusCode:D.status,message:"Server error"},ErrorPage:g??void 0}));return}let f=await D.json();if(f.redirect){f.redirectReplace?window.history.replaceState(null,"",f.redirect):window.history.pushState(null,"",f.redirect),await R(f.redirect,l);return}T({pathname:d,params:f.params??{},loaderData:f.loaderData,layoutsData:(f.layouts??[]).map(g=>g.loaderData),Page:x.default,layouts:L.map(g=>g.default),metadata:f.metadata??null,viewport:f.viewport});let $=p.includes("#")?p.split("#")[1]:null,O=getComputedStyle(document.documentElement).scrollBehavior;$?requestAnimationFrame(()=>{document.getElementById($)?.scrollIntoView({behavior:O})}):window.scrollTo({top:0,behavior:O})},[]),_=B(async(p,l)=>{E.current?.abort();let d=new AbortController;E.current=d,V(!0);let i=async()=>{window.history[l?.replace?"replaceState":"pushState"](null,"",p),await R(p,d)};try{l?.viewTransition&&"startViewTransition"in document?await document.startViewTransition(i).finished:await i()}finally{d.signal.aborted||V(!1)}},[R]),Q=B(async()=>{let p=window.location.pathname+window.location.search,l=new AbortController,d=await fetch(`/_data${p}`,{headers:{Accept:"application/json"},signal:l.signal});if(!d.ok)return;let i=await d.json();if(i.redirect){await _(i.redirect,{replace:i.redirectReplace});return}T(x=>({...x,loaderData:i.loaderData,layoutsData:(i.layouts??[]).map(L=>L.loaderData),params:i.params??x.params,metadata:i.metadata??x.metadata,viewport:i.viewport??x.viewport}))},[_]);ee(()=>{let p=()=>{E.current?.abort();let l=new AbortController;E.current=l;let d=window.location.pathname+window.location.search;R(d,l).catch(i=>{i.name!=="AbortError"&&console.error("[router] popstate error:",i)})};return window.addEventListener("popstate",p),()=>window.removeEventListener("popstate",p)},[R]);let A;if(n.pendingError)A=n.ErrorPage?m(n.ErrorPage,{...n.pendingError}):m("h1",{children:n.pendingError.statusCode});else{let p=m(C,{value:{loaderData:n.loaderData,params:n.params},children:m(n.Page,{data:n.loaderData,params:n.params,url:n.pathname})});for(let l=n.layouts.length-1;l>=0;l--){let d=n.layouts[l],i=n.layoutsData[l];p=m(C,{value:{loaderData:i,params:n.params},children:m(d,{data:i,params:n.params,children:p})})}A=m(M,{ErrorPage:n.ErrorPage,children:p},n.pathname)}return ue(j,{value:{metadata:n.metadata,viewport:n.viewport,clientEntry:h},children:[m(I,{metadata:n.metadata,viewport:n.viewport}),m(b,{value:{...n,isNavigating:z,navigate:_,revalidate:Q},children:A})]})}import{useCallback as ce,useContext as fe}from"react";import{matchClientRoute as ge}from"virtual:devix/client-routes";import{RouterContext as me}from"virtual:devix/context";import{jsx as xe}from"react/jsx-runtime";function W(e){if(e.startsWith("/")||e.startsWith("http"))return e;let t=window.location.pathname.endsWith("/")?window.location.href:window.location.href+"/",r=new URL(e,t).pathname;return r.length>1?r.replace(/\/$/,""):r}function ye({href:e,prefetch:t=!1,viewTransition:r=!1,children:o,...a}){let s=fe(me),y=ce(()=>{if(!t)return;let u=W(e),h=u.split("?")[0].split("#")[0],n=ge(h);n&&(n.load().catch(()=>{}),fetch(`/_data${u}`,{headers:{Accept:"application/json"}}).catch(()=>{}))},[e,t]);return xe("a",{href:e,onClick:u=>{if(s&&!u.ctrlKey&&!u.metaKey&&!u.shiftKey&&u.button===0){u.preventDefault();let h=W(e);r&&typeof document.startViewTransition=="function"?document.startViewTransition(()=>s.navigate(h)):s.navigate(h)}},onMouseEnter:y,...a,children:o})}function he(e,t){let r=e.headers.get("cookie");if(r)for(let o of r.split(";")){let[a,...s]=o.trim().split("=");if(a.trim()===t)return decodeURIComponent(s.join("="))}}function q(e,t,r,o={}){let a=`${t}=${encodeURIComponent(r)}; Path=${o.path??"/"}`;o.domain&&(a+=`; Domain=${o.domain}`),o.maxAge!==void 0&&(a+=`; Max-Age=${o.maxAge}`),o.expires&&(a+=`; Expires=${o.expires.toUTCString()}`),o.httpOnly&&(a+="; HttpOnly"),o.secure&&(a+="; Secure"),o.sameSite&&(a+=`; SameSite=${o.sameSite}`),e.append("Set-Cookie",a)}function we(e,t,r={}){q(e,t,"",{...r,maxAge:0,expires:new Date(0)})}var Re=(e,t=200)=>new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}}),Pe=(e,t=200)=>new Response(e,{status:t,headers:{"Content-Type":"text/plain; charset=utf-8"}}),Ce=Symbol("devix.redirect");function ve(e,t){let r=typeof t=="number"?t:t?.status??302,o=typeof t=="object"?t?.replace??!1:!1;return{[Ce]:!0,url:e,status:r,replace:o}}var k=class extends Error{constructor(r,o,a){super(`HTTP ${r}: ${o}`);this.status=r;this.statusText=o;this.response=a;this.name="FetchError"}};async function Te(e,t){let r=t?.method??"GET",o=new Headers(t?.headers),a;t?.body!==void 0&&(a=JSON.stringify(t.body),o.has("Content-Type")||o.set("Content-Type","application/json"));let s=await fetch(e,{method:r,headers:o,body:a,signal:t?.signal});if(!s.ok)throw new k(s.status,s.statusText,s);return(s.headers.get("Content-Type")??"").includes("application/json")?s.json():s.text()}var Ee="__devix_handler__";function De(e){return{[Ee]:!0,fn:e}}export{Te as $fetch,k as FetchError,ye as Link,de as RouterProvider,De as createHandler,we as deleteCookie,he as getCookie,Re as json,ve as redirect,q as setCookie,Pe as text,le as useLoaderData,ie as useNavigate,pe as useParams,se as useRevalidate,oe as useRouter};
2
2
  //# sourceMappingURL=index.js.map