@blinkk/root 1.0.0-alpha.28 → 1.0.0-alpha.29

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.
@@ -43,14 +43,33 @@ function Head(props) {
43
43
  return null;
44
44
  }
45
45
 
46
- // src/core/components/script.ts
46
+ // src/core/components/html.ts
47
47
  import { createContext as createContext2 } from "preact";
48
48
  import { useContext as useContext2 } from "preact/hooks";
49
- var SCRIPT_CONTEXT = createContext2([]);
49
+ var HTML_CONTEXT = createContext2({ attrs: {} });
50
+ function Html({ children, ...attrs }) {
51
+ let context;
52
+ try {
53
+ context = useContext2(HTML_CONTEXT);
54
+ context.attrs = attrs;
55
+ } catch (err) {
56
+ console.log(err);
57
+ throw new Error(
58
+ "<Html> component is not supported in the browser, or during suspense renders.",
59
+ { cause: err }
60
+ );
61
+ }
62
+ return children;
63
+ }
64
+
65
+ // src/core/components/script.ts
66
+ import { createContext as createContext3 } from "preact";
67
+ import { useContext as useContext3 } from "preact/hooks";
68
+ var SCRIPT_CONTEXT = createContext3([]);
50
69
  function Script(props) {
51
70
  let context;
52
71
  try {
53
- context = useContext2(SCRIPT_CONTEXT);
72
+ context = useContext3(SCRIPT_CONTEXT);
54
73
  } catch (err) {
55
74
  throw new Error(
56
75
  "<Script> component is not supported in the browser, or during suspense renders.",
@@ -63,9 +82,9 @@ function Script(props) {
63
82
 
64
83
  // src/core/i18n.ts
65
84
  import path from "node:path";
66
- import { createContext as createContext3 } from "preact";
67
- import { useContext as useContext3 } from "preact/hooks";
68
- var I18N_CONTEXT = createContext3(null);
85
+ import { createContext as createContext4 } from "preact";
86
+ import { useContext as useContext4 } from "preact/hooks";
87
+ var I18N_CONTEXT = createContext4(null);
69
88
  function getTranslations(locale) {
70
89
  const translations = {};
71
90
  const translationsFiles = import.meta.glob(["/translations/*.json"], {
@@ -82,7 +101,7 @@ function getTranslations(locale) {
82
101
  return translations[locale] || {};
83
102
  }
84
103
  function useI18nContext() {
85
- const context = useContext3(I18N_CONTEXT);
104
+ const context = useContext4(I18N_CONTEXT);
86
105
  if (!context) {
87
106
  throw new Error("could not find i18n context");
88
107
  }
@@ -105,11 +124,11 @@ function useTranslations() {
105
124
  }
106
125
 
107
126
  // src/core/request-context.ts
108
- import { createContext as createContext4 } from "preact";
109
- import { useContext as useContext4 } from "preact/hooks";
110
- var REQUEST_CONTEXT = createContext4(null);
127
+ import { createContext as createContext5 } from "preact";
128
+ import { useContext as useContext5 } from "preact/hooks";
129
+ var REQUEST_CONTEXT = createContext5(null);
111
130
  function useRequestContext() {
112
- const context = useContext4(REQUEST_CONTEXT);
131
+ const context = useContext5(REQUEST_CONTEXT);
113
132
  if (!context) {
114
133
  throw new Error("could not find request context");
115
134
  }
@@ -120,6 +139,8 @@ export {
120
139
  ErrorPage,
121
140
  HEAD_CONTEXT,
122
141
  Head,
142
+ HTML_CONTEXT,
143
+ Html,
123
144
  SCRIPT_CONTEXT,
124
145
  Script,
125
146
  I18N_CONTEXT,
@@ -129,4 +150,4 @@ export {
129
150
  REQUEST_CONTEXT,
130
151
  useRequestContext
131
152
  };
132
- //# sourceMappingURL=chunk-5FVR2OXQ.js.map
153
+ //# sourceMappingURL=chunk-ACIQKW7Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/components/error-page.tsx","../src/core/components/head.ts","../src/core/components/html.ts","../src/core/components/script.ts","../src/core/i18n.ts","../src/core/request-context.ts"],"sourcesContent":["export interface ErrorPageProps {\n error: unknown;\n}\n\nexport function ErrorPage(props: ErrorPageProps) {\n const error = props.error;\n\n let message = undefined;\n if (import.meta.env.DEV) {\n if (error instanceof Error) {\n message = error.stack;\n } else {\n message = String(error);\n }\n }\n\n return (\n <div>\n <div>\n <p>An error occured during route handling or page rendering.</p>\n {message && <pre>{message}</pre>}\n </div>\n </div>\n );\n}\n","import {ComponentChildren, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const HEAD_CONTEXT = createContext<ComponentChildren[]>([]);\n\nexport interface HeadProps {\n children?: ComponentChildren;\n}\n\n/**\n * The <Head> component can be used for injecting elements into the HTML head\n * tag from any part of a page.\n */\nexport function Head(props: HeadProps) {\n let context: ComponentChildren[];\n try {\n context = useContext(HEAD_CONTEXT);\n } catch (err) {\n console.log(err);\n throw new Error(\n '<Head> component is not supported in the browser, or during suspense renders.',\n {cause: err}\n );\n }\n context.push(props.children);\n return null;\n}\n","import {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport interface HtmlContextValue {\n attrs: Record<string, string>;\n}\n\nexport const HTML_CONTEXT = createContext<HtmlContextValue>({attrs: {}});\n\nexport type HtmlProps = {\n [key: string]: string;\n} & preact.JSX.HTMLAttributes<HTMLHtmlElement>;\n\n/**\n * The <Html> component can be used to update attrs used in the <html> tag.\n *\n * Usage:\n *\n * import {Html} from '@blinkk/root';\n *\n * export default function Page() {\n * return (\n * <Html lang={locale}>\n * <h1>Hello world</h1>\n * </Html>\n * );\n * }\n */\nexport function Html({children, ...attrs}: HtmlProps) {\n let context: Record<string, any>;\n try {\n context = useContext(HTML_CONTEXT);\n context.attrs = attrs;\n } catch (err) {\n console.log(err);\n throw new Error(\n '<Html> component is not supported in the browser, or during suspense renders.',\n {cause: err}\n );\n }\n return children;\n}\n","import {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const SCRIPT_CONTEXT = createContext<ScriptProps[]>([]);\n\nexport interface ScriptProps {\n src: string;\n type?: string;\n}\n\n/**\n * The <Script> component is used for rendering any custom script modules. At\n * the moment, the system only pre-renders and bundles files that are in the\n * `/bundles` folder at the root of the project.\n */\nexport function Script(props: ScriptProps) {\n let context: ScriptProps[];\n try {\n context = useContext(SCRIPT_CONTEXT);\n } catch (err) {\n throw new Error(\n '<Script> component is not supported in the browser, or during suspense renders.',\n {cause: err}\n );\n }\n context.push(props);\n return null;\n}\n","import path from 'node:path';\nimport {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const I18N_CONTEXT = createContext<I18nContext | null>(null);\n\nexport interface I18nContext {\n locale: string;\n translations: Record<string, string>;\n}\n\nexport function getTranslations(locale: string): Record<string, string> {\n const translations: Record<string, Record<string, string>> = {};\n const translationsFiles = import.meta.glob(['/translations/*.json'], {\n eager: true,\n }) as Record<string, {default?: Record<string, string>}>;\n Object.keys(translationsFiles).forEach((translationPath) => {\n const parts = path.parse(translationPath);\n const locale = parts.name;\n const module = translationsFiles[translationPath];\n if (module && module.default) {\n translations[locale] = module.default;\n }\n });\n return translations[locale] || {};\n}\n\nexport function useI18nContext() {\n const context = useContext(I18N_CONTEXT);\n if (!context) {\n throw new Error('could not find i18n context');\n }\n return context;\n}\n\nexport function useTranslations() {\n const context = useI18nContext();\n const translations = context.translations || {};\n const t = (str: string, params?: Record<string, string>) => {\n let translation = translations[str] || str || '';\n if (params) {\n for (const key of Object.keys(params)) {\n const val = String(params[key] || '');\n translation = translation.replaceAll(`{${key}}`, val);\n }\n }\n return translation;\n };\n return t;\n}\n","import {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {Route} from '../render/router';\n\nexport interface RequestContext {\n /** The route file. */\n route: Route;\n /**\n * Route param values. E.g. for a route like `routes/blog/[slug].tsx`,\n * visiting `/blog/foo` will pass {slug: 'foo'} here.\n */\n routeParams: Record<string, string>;\n /** Props passed to the route's server component. */\n props: any;\n /** The current locale. */\n locale: string;\n /** Translations map for the current locale. */\n translations: Record<string, string>;\n}\n\nexport const REQUEST_CONTEXT = createContext<RequestContext | null>(null);\n\nexport function useRequestContext() {\n const context = useContext(REQUEST_CONTEXT);\n if (!context) {\n throw new Error('could not find request context');\n }\n return context;\n}\n"],"mappings":";AAkBM,SACE,KADF;AAdC,SAAS,UAAU,OAAuB;AAC/C,QAAM,QAAQ,MAAM;AAEpB,MAAI,UAAU;AACd,MAAI,YAAY,IAAI,KAAK;AACvB,QAAI,iBAAiB,OAAO;AAC1B,gBAAU,MAAM;AAAA,IAClB,OAAO;AACL,gBAAU,OAAO,KAAK;A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,gCAAgC;AAAA,EAClD;AACA,SAAO;AACT;","names":["createContext","useContext","createContext","useContext","createContext","useContext","locale","createContext","useContext"]}
package/dist/core.d.ts CHANGED
@@ -20,6 +20,30 @@ interface HeadProps {
20
20
  */
21
21
  declare function Head(props: HeadProps): null;
22
22
 
23
+ interface HtmlContextValue {
24
+ attrs: Record<string, string>;
25
+ }
26
+ declare const HTML_CONTEXT: preact.Context<HtmlContextValue>;
27
+ declare type HtmlProps = {
28
+ [key: string]: string;
29
+ } & preact.JSX.HTMLAttributes<HTMLHtmlElement>;
30
+ /**
31
+ * The <Html> component can be used to update attrs used in the <html> tag.
32
+ *
33
+ * Usage:
34
+ *
35
+ * import {Html} from '@blinkk/root';
36
+ *
37
+ * export default function Page() {
38
+ * return (
39
+ * <Html lang={locale}>
40
+ * <h1>Hello world</h1>
41
+ * </Html>
42
+ * );
43
+ * }
44
+ */
45
+ declare function Html({ children, ...attrs }: HtmlProps): preact.ComponentChildren;
46
+
23
47
  declare const SCRIPT_CONTEXT: preact.Context<ScriptProps[]>;
24
48
  interface ScriptProps {
25
49
  src: string;
@@ -59,4 +83,4 @@ interface RequestContext {
59
83
  declare const REQUEST_CONTEXT: preact.Context<RequestContext | null>;
60
84
  declare function useRequestContext(): RequestContext;
61
85
 
62
- export { ErrorPage, ErrorPageProps, HEAD_CONTEXT, Head, HeadProps, I18N_CONTEXT, I18nContext, REQUEST_CONTEXT, RequestContext, SCRIPT_CONTEXT, Script, ScriptProps, getTranslations, useI18nContext, useRequestContext, useTranslations };
86
+ export { ErrorPage, ErrorPageProps, HEAD_CONTEXT, HTML_CONTEXT, Head, HeadProps, Html, HtmlContextValue, HtmlProps, I18N_CONTEXT, I18nContext, REQUEST_CONTEXT, RequestContext, SCRIPT_CONTEXT, Script, ScriptProps, getTranslations, useI18nContext, useRequestContext, useTranslations };
package/dist/core.js CHANGED
@@ -5,7 +5,9 @@ import {
5
5
  import {
6
6
  ErrorPage,
7
7
  HEAD_CONTEXT,
8
+ HTML_CONTEXT,
8
9
  Head,
10
+ Html,
9
11
  I18N_CONTEXT,
10
12
  REQUEST_CONTEXT,
11
13
  SCRIPT_CONTEXT,
@@ -14,7 +16,7 @@ import {
14
16
  useI18nContext,
15
17
  useRequestContext,
16
18
  useTranslations
17
- } from "./chunk-5FVR2OXQ.js";
19
+ } from "./chunk-ACIQKW7Y.js";
18
20
 
19
21
  // src/core/config.ts
20
22
  function defineConfig(config) {
@@ -23,7 +25,9 @@ function defineConfig(config) {
23
25
  export {
24
26
  ErrorPage,
25
27
  HEAD_CONTEXT,
28
+ HTML_CONTEXT,
26
29
  Head,
30
+ Html,
27
31
  I18N_CONTEXT,
28
32
  REQUEST_CONTEXT,
29
33
  SCRIPT_CONTEXT,
package/dist/core.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/config.ts"],"sourcesContent":["import {Request, Response, NextFunction} from './types';\nimport {Plugin} from './plugin';\nimport {UserConfig as ViteUserConfig} from 'vite';\n\nexport interface RootUserConfig {\n /**\n * Config for auto-injecting custom element dependencies.\n */\n elements?: {\n /**\n * A list of directories to use to look for custom elements. The dir path\n * should be relative to the project dir, e.g. \"path/to/elements\" or\n * \"node_modules/my-package\".\n */\n include?: string[];\n\n /**\n * A list of RegEx patterns to exclude. The string passed to the RegEx is\n * the file URL relative to the project root, e.g. \"/elements/foo/foo.ts\".\n */\n exclude?: RegExp[];\n };\n\n /**\n * Config options for localization and internationalization.\n */\n i18n?: RootI18nConfig;\n\n /**\n * Config options for the Root.js express server.\n */\n server?: RootServerConfig;\n\n /**\n * Vite config.\n * @see {@link https://vitejs.dev/config/} for more information.\n */\n vite?: ViteUserConfig;\n\n /**\n * Whether to automatically minify HTML output. This is enabled by default,\n * in order to disable, pass `minifyHtml: false` to root.config.ts.\n */\n minifyHtml?: boolean;\n\n /**\n * Whether to include a sitemap.xml file to the build output.\n */\n sitemap?: boolean;\n\n /**\n * Plugins.\n */\n plugins?: Plugin[];\n}\n\nexport type RootConfig = RootUserConfig & {\n rootDir: string;\n};\n\nexport interface RootI18nConfig {\n /**\n * Locales enabled for the site.\n */\n locales?: string[];\n\n /**\n * The default locale to use. Defaults is `en`.\n */\n defaultLocale?: string;\n\n /**\n * URL format for localized content. Default is `/{locale}/{path}`.\n */\n urlFormat?: string;\n}\n\nexport interface RootServerConfig {\n /**\n * An array of middleware to add to the express server. These middleware are\n * added to the beginning of the express app.\n */\n middlewares?: Array<\n (req: Request, res: Response, next: NextFunction) => void | Promise<void>\n >;\n}\n\nexport function defineConfig(config: RootUserConfig): RootUserConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAuFO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../src/core/config.ts"],"sourcesContent":["import {Request, Response, NextFunction} from './types';\nimport {Plugin} from './plugin';\nimport {UserConfig as ViteUserConfig} from 'vite';\n\nexport interface RootUserConfig {\n /**\n * Config for auto-injecting custom element dependencies.\n */\n elements?: {\n /**\n * A list of directories to use to look for custom elements. The dir path\n * should be relative to the project dir, e.g. \"path/to/elements\" or\n * \"node_modules/my-package\".\n */\n include?: string[];\n\n /**\n * A list of RegEx patterns to exclude. The string passed to the RegEx is\n * the file URL relative to the project root, e.g. \"/elements/foo/foo.ts\".\n */\n exclude?: RegExp[];\n };\n\n /**\n * Config options for localization and internationalization.\n */\n i18n?: RootI18nConfig;\n\n /**\n * Config options for the Root.js express server.\n */\n server?: RootServerConfig;\n\n /**\n * Vite config.\n * @see {@link https://vitejs.dev/config/} for more information.\n */\n vite?: ViteUserConfig;\n\n /**\n * Whether to automatically minify HTML output. This is enabled by default,\n * in order to disable, pass `minifyHtml: false` to root.config.ts.\n */\n minifyHtml?: boolean;\n\n /**\n * Whether to include a sitemap.xml file to the build output.\n */\n sitemap?: boolean;\n\n /**\n * Plugins.\n */\n plugins?: Plugin[];\n}\n\nexport type RootConfig = RootUserConfig & {\n rootDir: string;\n};\n\nexport interface RootI18nConfig {\n /**\n * Locales enabled for the site.\n */\n locales?: string[];\n\n /**\n * The default locale to use. Defaults is `en`.\n */\n defaultLocale?: string;\n\n /**\n * URL format for localized content. Default is `/{locale}/{path}`.\n */\n urlFormat?: string;\n}\n\nexport interface RootServerConfig {\n /**\n * An array of middleware to add to the express server. These middleware are\n * added to the beginning of the express app.\n */\n middlewares?: Array<\n (req: Request, res: Response, next: NextFunction) => void | Promise<void>\n >;\n}\n\nexport function defineConfig(config: RootUserConfig): RootUserConfig {\n return config;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAuFO,SAAS,aAAa,QAAwC;AACnE,SAAO;AACT;","names":[]}
package/dist/render.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  ErrorPage,
3
3
  HEAD_CONTEXT,
4
+ HTML_CONTEXT,
4
5
  I18N_CONTEXT,
5
6
  REQUEST_CONTEXT,
6
7
  SCRIPT_CONTEXT,
7
8
  getTranslations
8
- } from "./chunk-5FVR2OXQ.js";
9
+ } from "./chunk-ACIQKW7Y.js";
9
10
 
10
11
  // src/render/render.tsx
11
12
  import renderToString from "preact-render-to-string";
@@ -385,16 +386,20 @@ var Renderer = class {
385
386
  };
386
387
  const headComponents = [];
387
388
  const userScripts = [];
389
+ const htmlContext = { attrs: {} };
388
390
  const vdom = /* @__PURE__ */ jsx2(REQUEST_CONTEXT.Provider, {
389
391
  value: ctx,
390
392
  children: /* @__PURE__ */ jsx2(I18N_CONTEXT.Provider, {
391
393
  value: { locale, translations },
392
- children: /* @__PURE__ */ jsx2(SCRIPT_CONTEXT.Provider, {
393
- value: userScripts,
394
+ children: /* @__PURE__ */ jsx2(HTML_CONTEXT.Provider, {
395
+ value: htmlContext,
394
396
  children: /* @__PURE__ */ jsx2(HEAD_CONTEXT.Provider, {
395
397
  value: headComponents,
396
- children: /* @__PURE__ */ jsx2(Component, {
397
- ...props
398
+ children: /* @__PURE__ */ jsx2(SCRIPT_CONTEXT.Provider, {
399
+ value: userScripts,
400
+ children: /* @__PURE__ */ jsx2(Component, {
401
+ ...props
402
+ })
398
403
  })
399
404
  })
400
405
  })
@@ -431,7 +436,12 @@ var Renderer = class {
431
436
  src: jsUrls
432
437
  }));
433
438
  });
434
- const html = await this.renderHtml({ mainHtml, locale, headComponents });
439
+ const htmlLang = htmlContext.attrs.lang || locale;
440
+ const html = await this.renderHtml({
441
+ mainHtml,
442
+ locale: htmlLang,
443
+ headComponents
444
+ });
435
445
  return { html };
436
446
  }
437
447
  async getSitemap() {
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/render/render.tsx","../src/render/router.ts","../src/render/route-trie.ts","../src/core/components/dev-not-found-page.tsx"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport {ComponentChildren} from 'preact';\nimport renderToString from 'preact-render-to-string';\nimport {getRoutes, Route, getAllPathsForRoute} from './router';\nimport {HEAD_CONTEXT} from '../core/components/head';\nimport {ErrorPage} from '../core/components/error-page';\nimport {getTranslations, I18N_CONTEXT} from '../core/i18n';\nimport {ScriptProps, SCRIPT_CONTEXT} from '../core/components/script';\nimport {AssetMap} from './asset-map/asset-map';\nimport {RootConfig} from '../core/config';\nimport {RouteTrie} from './route-trie';\nimport {elementsMap} from 'virtual:root-elements';\nimport {DevNotFoundPage} from '../core/components/dev-not-found-page';\nimport {RequestContext, REQUEST_CONTEXT} from '../core/request-context';\n\ninterface RenderHtmlOptions {\n mainHtml: string;\n locale: string;\n headComponents?: ComponentChildren[];\n}\n\nexport class Renderer {\n private rootConfig: RootConfig;\n private routes: RouteTrie<Route>;\n private assetMap: AssetMap;\n\n constructor(rootConfig: RootConfig, options: {assetMap: AssetMap}) {\n this.rootConfig = rootConfig;\n this.routes = getRoutes(this.rootConfig);\n this.assetMap = options.assetMap;\n }\n\n async render(url: string): Promise<{html?: string; notFound?: boolean}> {\n const [route, routeParams] = this.routes.get(url);\n if (route && route.module && route.module.default) {\n return await this.renderRoute(route, {routeParams});\n }\n return {notFound: true};\n }\n\n async renderRoute(\n route: Route,\n options: {routeParams: Record<string, string>}\n ): Promise<{html?: string; notFound?: boolean}> {\n const routeParams = options.routeParams;\n const assetMap = this.assetMap;\n const Component = route.module.default;\n if (!Component) {\n throw new Error(\n 'unable to render route. the route should have a default export that renders a jsx component.'\n );\n }\n let props = {};\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n params: routeParams,\n });\n if (propsData.notFound) {\n return this.render404();\n }\n if (propsData.props) {\n props = propsData.props;\n }\n }\n\n const locale = route.locale;\n const translations = getTranslations(locale);\n const ctx: RequestContext = {\n route,\n props,\n routeParams,\n locale,\n translations,\n };\n const headComponents: ComponentChildren[] = [];\n const userScripts: ScriptProps[] = [];\n const vdom = (\n <REQUEST_CONTEXT.Provider value={ctx}>\n <I18N_CONTEXT.Provider value={{locale, translations}}>\n <SCRIPT_CONTEXT.Provider value={userScripts}>\n <HEAD_CONTEXT.Provider value={headComponents}>\n <Component {...props} />\n </HEAD_CONTEXT.Provider>\n </SCRIPT_CONTEXT.Provider>\n </I18N_CONTEXT.Provider>\n </REQUEST_CONTEXT.Provider>\n );\n const mainHtml = renderToString(vdom);\n\n const jsDeps = new Set<string>();\n const cssDeps = new Set<string>();\n\n // Walk the page's dependency tree for CSS dependencies that are added via\n // `import 'foo.scss'` or `import 'foo.module.scss'`.\n const pageAsset = await assetMap.get(route.src);\n if (pageAsset) {\n const pageCssDeps = await pageAsset.getCssDeps();\n pageCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n\n // Parse the HTML for custom elements that are found within the project\n // and automatically inject the script deps for them.\n await this.collectElementDeps(mainHtml, jsDeps, cssDeps);\n\n // Add user defined scripts added via the `<Script>` component.\n await Promise.all(\n userScripts.map(async (scriptDep) => {\n const scriptAsset = await assetMap.get(scriptDep.src.slice(1));\n if (scriptAsset) {\n jsDeps.add(scriptAsset.assetUrl);\n const scriptJsDeps = await scriptAsset.getJsDeps();\n scriptJsDeps.forEach((dep) => jsDeps.add(dep));\n }\n })\n );\n\n cssDeps.forEach((cssUrl) => {\n headComponents.push(<link rel=\"stylesheet\" href={cssUrl} />);\n });\n jsDeps.forEach((jsUrls) => {\n headComponents.push(<script type=\"module\" src={jsUrls} />);\n });\n\n const html = await this.renderHtml({mainHtml, locale, headComponents});\n return {html};\n }\n\n async getSitemap(): Promise<\n Record<string, {route: Route; params: Record<string, string>}>\n > {\n const sitemap: Record<\n string,\n {route: Route; params: Record<string, string>}\n > = {};\n await this.routes.walk(async (urlPath: string, route: Route) => {\n const routePaths = await getAllPathsForRoute(urlPath, route);\n routePaths.forEach((routePath) => {\n sitemap[routePath.urlPath] = {\n route,\n params: routePath.params,\n };\n });\n });\n return sitemap;\n }\n\n private async renderHtml(options: RenderHtmlOptions) {\n const page = (\n <html lang={options.locale}>\n <head>\n <meta charSet=\"utf-8\" />\n {options.headComponents}\n </head>\n <body dangerouslySetInnerHTML={{__html: options.mainHtml}} />\n </html>\n );\n const html = `<!doctype html>\\n${renderToString(page)}\\n`;\n return html;\n }\n\n async render404() {\n return {\n html: '<!doctype html><html><title>404 Not Found</title><h1>404 Not Found</h1>',\n notFound: true,\n };\n }\n\n async renderError(error: unknown) {\n const mainHtml = renderToString(<ErrorPage error={error} />);\n const html = await this.renderHtml({mainHtml, locale: 'en'});\n return {html};\n }\n\n async renderDevServer404() {\n const sitemap = await this.getSitemap();\n const mainHtml = renderToString(<DevNotFoundPage sitemap={sitemap} />);\n const html = await this.renderHtml({\n mainHtml,\n locale: 'en',\n headComponents: [<title>404: Not Found</title>],\n });\n return {html};\n }\n\n /**\n * Parses rendered HTML for custom element tags used on the page and\n * automatically adds the JS/CSS deps to the page.\n */\n private async collectElementDeps(\n html: string,\n jsDeps: Set<string>,\n cssDeps: Set<string>,\n ): Promise<{jsDeps: Set<string>; cssDeps: Set<string>}> {\n const assetMap = this.assetMap;\n\n const re = /<(\\w[\\w-]+\\w)/g;\n const matches = Array.from(html.matchAll(re));\n await Promise.all(\n matches.map(async (match) => {\n const tagName = match[1];\n // Custom elements require a dash.\n if (tagName && tagName.includes('-') && tagName in elementsMap) {\n const elementModule = elementsMap[tagName];\n const asset = await assetMap.get(elementModule.src);\n if (!asset) {\n return;\n }\n const assetJsDeps = await asset.getJsDeps();\n assetJsDeps.forEach((dep) => jsDeps.add(dep));\n const assetCssDeps = await asset.getCssDeps();\n assetCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n })\n );\n\n return {jsDeps, cssDeps};\n }\n}\n","import path from 'node:path';\nimport {ComponentType} from 'preact';\nimport {RootConfig} from '../core/config';\nimport {GetStaticPaths, GetStaticProps} from '../core/types';\nimport {RouteTrie} from './route-trie';\n\nexport interface RouteModule {\n default?: ComponentType<unknown>;\n getStaticPaths?: GetStaticPaths;\n getStaticProps?: GetStaticProps;\n}\n\nexport interface Route {\n /** The relative path to the route file, e.g. `routes/index.tsx`. */\n src: string;\n\n /** The imported route module. */\n module: RouteModule;\n\n /** The locale used for the route. */\n locale: string;\n\n /**\n * The mapped URL path for the route, e.g.:\n *\n * routes/index.tsx => `/`.\n * routes/events.tsx => `/events`.\n * routes/blog/[slug].tsx => `/blog/[slug]`.\n *\n * Per the example above, this value may contain placeholder params.\n */\n routePath: string;\n\n /**\n * The localized URL path for the route, e.g. `/[locale]/blog/[slug]`.\n * Per the example above, this value contains placeholder params.\n */\n localeRoutePath: string;\n}\n\nexport function getRoutes(config: RootConfig) {\n const locales = config.i18n?.locales || [];\n const i18nUrlFormat = config.i18n?.urlFormat || '/{locale}/{path}';\n const defaultLocale = config.i18n?.defaultLocale || 'en';\n\n const routes = import.meta.glob(\n ['/routes/*.ts', '/routes/**/*.ts', '/routes/*.tsx', '/routes/**/*.tsx'],\n {\n eager: true,\n }\n );\n const trie = new RouteTrie<Route>();\n Object.keys(routes).forEach((modulePath) => {\n const src = modulePath.slice(1);\n let routePath = modulePath.replace(/^\\/routes/, '');\n const parts = path.parse(routePath);\n if (parts.name.startsWith('_')) {\n return;\n }\n if (parts.name === 'index') {\n routePath = parts.dir;\n } else {\n routePath = path.join(parts.dir, parts.name);\n }\n\n const localeRoutePath = i18nUrlFormat\n .replace('{locale}', '[locale]')\n .replace('{path}', routePath.replace(/^\\/*/, ''));\n\n trie.add(routePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: defaultLocale,\n routePath,\n localeRoutePath,\n });\n\n // At the moment, all routes are assumed to use the site-wide i18n config.\n // TODO(stevenle): provide routes with a way to override the default\n // i18n serving behavior.\n locales.forEach((locale) => {\n const localePath = localeRoutePath.replace('[locale]', locale);\n if (localePath !== routePath) {\n trie.add(localePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: locale,\n routePath,\n localeRoutePath,\n });\n }\n });\n });\n return trie;\n}\n\nexport async function getAllPathsForRoute(\n urlPathFormat: string,\n route: Route\n): Promise<Array<{urlPath: string; params: Record<string, string>}>> {\n const routeModule = route.module;\n if (!routeModule.default) {\n return [];\n }\n\n const urlPaths: Array<{urlPath: string; params: Record<string, string>}> = [];\n if (routeModule.getStaticPaths) {\n const staticPaths = await routeModule.getStaticPaths();\n if (staticPaths.paths) {\n staticPaths.paths.forEach(\n (pathParams: {params: Record<string, string>}) => {\n const urlPath = replaceParams(urlPathFormat, pathParams.params || {});\n if (pathContainsPlaceholders(urlPath)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, double check getStaticPaths() and ensure all params are returned. more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({\n urlPath: replaceParams(urlPathFormat, pathParams.params),\n params: pathParams.params || {},\n });\n }\n }\n );\n }\n } else if (pathContainsPlaceholders(urlPathFormat)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, did you forget to define getStaticPaths()? more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({urlPath: urlPathFormat, params: {}});\n }\n return urlPaths;\n}\n\nexport function replaceParams(\n urlPathFormat: string,\n params: Record<string, string>\n) {\n const urlPath = urlPathFormat.replaceAll(\n /\\[(\\.\\.\\.)?([\\w\\-_]*)\\]/g,\n (match: string, _wildcard: string, key: string) => {\n const val = params[key];\n if (!val) {\n throw new Error(`unreplaced param ${match} in url: ${urlPathFormat}`);\n }\n return val;\n }\n );\n return urlPath;\n}\n\nfunction pathContainsPlaceholders(urlPath: string) {\n const segments = urlPath.split('/');\n return segments.some((segment) => {\n return segment.startsWith('[') && segment.endsWith(']');\n });\n}\n","/**\n * A trie data structure that stores routes. The trie supports `:param` and\n * `*wildcard` values.\n */\nexport class RouteTrie<T> {\n private children: Record<string, RouteTrie<T>> = {};\n private paramChild?: ParamChild<T>;\n private wildcardChild?: WildcardChild<T>;\n private route?: T;\n\n /**\n * Adds a route to the trie.\n */\n add(path: string, route: T) {\n path = this.normalizePath(path);\n\n // If the end was reached, save the value to the node.\n if (path === '') {\n this.route = route;\n return;\n }\n\n const [head, tail] = this.splitPath(path);\n if (head.startsWith('[...') && head.endsWith(']')) {\n const paramName = head.slice(4, -1);\n this.wildcardChild = new WildcardChild(paramName, route);\n return;\n }\n\n let nextNode: RouteTrie<T>;\n if (head.startsWith('[') && head.endsWith(']')) {\n if (!this.paramChild) {\n const paramName = head.slice(1, -1);\n this.paramChild = new ParamChild(paramName);\n }\n nextNode = this.paramChild.trie;\n } else {\n nextNode = this.children[head];\n if (!nextNode) {\n nextNode = new RouteTrie();\n this.children[head] = nextNode;\n }\n }\n nextNode.add(tail, route);\n }\n\n /**\n * Returns a route mapped to the given path and any parameter values from the\n * URL.\n */\n get(path: string): [T | undefined, Record<string, string>] {\n const params = {};\n const route = this.getRoute(path, params);\n return [route, params];\n }\n\n /**\n * Walks the route trie and calls a callback function for each route.\n */\n walk(cb: (urlPath: string, route: T) => Promise<void> | void): Promise<void> {\n const promises: Array<Promise<void>> = [];\n const addPromise = (promise: Promise<void> | void) => {\n if (promise) {\n promises.push(promise);\n }\n };\n if (this.route) {\n addPromise(cb('/', this.route));\n }\n if (this.paramChild) {\n const param = `[${this.paramChild.name}]`;\n this.paramChild.trie.walk((childPath: string, route: T) => {\n const paramUrlPath = `/${param}${childPath}`;\n addPromise(cb(paramUrlPath, route));\n });\n }\n if (this.wildcardChild) {\n const wildcardUrlPath = `/[...${this.wildcardChild.name}]`;\n addPromise(cb(wildcardUrlPath, this.wildcardChild.route));\n }\n for (const subpath of Object.keys(this.children)) {\n const childTrie = this.children[subpath];\n childTrie.walk((childPath: string, childRoute: T) => {\n addPromise(cb(`/${subpath}${childPath}`, childRoute));\n });\n }\n return Promise.all(promises).then(() => {});\n }\n\n /**\n * Removes all routes from the trie.\n */\n clear() {\n this.children = {};\n this.paramChild = undefined;\n this.wildcardChild = undefined;\n this.route = undefined;\n }\n\n private getRoute(\n urlPath: string,\n params: Record<string, string>\n ): T | undefined {\n urlPath = this.normalizePath(urlPath);\n if (urlPath === '') {\n return this.route;\n }\n\n const [head, tail] = this.splitPath(urlPath);\n\n const child = this.children[head];\n if (child) {\n const route = child.getRoute(tail, params);\n if (route) {\n return route;\n }\n }\n\n if (this.paramChild) {\n const route = this.paramChild.trie.getRoute(tail, params);\n if (route) {\n params[this.paramChild.name] = head;\n return route;\n }\n }\n\n if (this.wildcardChild) {\n params[this.wildcardChild.name] = urlPath;\n return this.wildcardChild.route;\n }\n\n return undefined;\n }\n\n /**\n * Normalizes a path for inclusion into the route trie.\n */\n private normalizePath(path: string) {\n // Remove leading slashes.\n return path.replace(/^\\/+/g, '');\n }\n\n /**\n * Splits the parent directory from its children, e.g.:\n *\n * splitPath(\"foo/bar/baz\") -> [\"foo\", \"bar/baz\"]\n */\n private splitPath(path: string): [string, string] {\n const i = path.indexOf('/');\n if (i === -1) {\n return [path, ''];\n }\n return [path.slice(0, i), path.slice(i + 1)];\n }\n}\n\n/**\n * A node in the RouteTrie for a :param child.\n */\nclass ParamChild<T> {\n readonly name: string;\n readonly trie: RouteTrie<T> = new RouteTrie();\n\n constructor(name: string) {\n this.name = name;\n }\n}\n\n/**\n * A node in the RouteTrie for a *wildcard child.\n */\nclass WildcardChild<T> {\n readonly name: string;\n readonly route: T;\n\n constructor(name: string, route: T) {\n this.name = name;\n this.route = route;\n }\n}\n","import {Route} from '../../render/router';\n\nconst STYLES = `\nbody {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;\n}\n\nh1 {\n margin-bottom: 40px;\n}\n\n.route-list {\n display: grid;\n grid-template-columns: auto 1fr;\n align-items: center;\n column-gap: 24px;\n row-gap: 8px;\n padding: 0 40px;\n}\n\n.route-module {\n text-align: right;\n}\n\nhr {\n margin: 60px 0;\n}\n`;\n\ninterface DevNotFoundPageProps {\n sitemap: Record<string, {route: Route; params: Record<string, string>}>;\n}\n\nexport function DevNotFoundPage(props: DevNotFoundPageProps) {\n const routesList: Array<Route & {urlPath: string}> = [];\n Object.keys(props.sitemap).forEach((urlPath) => {\n const route = props.sitemap[urlPath].route;\n routesList.push(Object.assign({}, route, {urlPath}));\n });\n return (\n <>\n <style dangerouslySetInnerHTML={{__html: STYLES}}></style>\n <div>\n <h1>\n <strong>404:</strong> Not Found\n </h1>\n {routesList.length > 0 ? (\n <>\n <h2>Routes found in the project:</h2>\n <div class=\"route-list\">\n {routesList.map((route) => (\n <>\n <div class=\"route-module\">{route.modulePath}</div>\n <a class=\"route-url\" href={route.urlPath}>\n {route.urlPath}\n </a>\n </>\n ))}\n </div>\n </>\n ) : (\n <>\n <h2>No routes found in the project</h2>\n <p>\n Add your first route at <code>/routes/index.tsx</code>\n </p>\n </>\n )}\n <hr />\n <p>\n Note: This page could use some love! If you're interested in helping\n to style this page, please reach out to the root.js developers!\n </p>\n </div>\n </>\n );\n}\n"],"mappings":";;;;;;;;;;AAEA,OAAO,oBAAoB;;;ACF3B,OAAO,UAAU;;;ACIV,IAAM,YAAN,MAAmB;AAAA,EAAnB;AACL,SAAQ,WAAyC,CAAC;AAAA;AAAA,EAQlD,IAAIA,OAAc,OAAU;AAC1B,IAAAA,QAAO,KAAK,cAAcA,KAAI;AAG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path","jsx","jsxs"]}
1
+ {"version":3,"sources":["../src/render/render.tsx","../src/render/router.ts","../src/render/route-trie.ts","../src/core/components/dev-not-found-page.tsx"],"sourcesContent":["// eslint-disable-next-line @typescript-eslint/no-unused-vars\nimport {ComponentChildren} from 'preact';\nimport renderToString from 'preact-render-to-string';\nimport {getRoutes, Route, getAllPathsForRoute} from './router';\nimport {HEAD_CONTEXT} from '../core/components/head';\nimport {ErrorPage} from '../core/components/error-page';\nimport {getTranslations, I18N_CONTEXT} from '../core/i18n';\nimport {ScriptProps, SCRIPT_CONTEXT} from '../core/components/script';\nimport {AssetMap} from './asset-map/asset-map';\nimport {RootConfig} from '../core/config';\nimport {RouteTrie} from './route-trie';\nimport {elementsMap} from 'virtual:root-elements';\nimport {DevNotFoundPage} from '../core/components/dev-not-found-page';\nimport {RequestContext, REQUEST_CONTEXT} from '../core/request-context';\nimport {HtmlContextValue, HTML_CONTEXT} from '../core/components/html';\n\ninterface RenderHtmlOptions {\n mainHtml: string;\n locale: string;\n headComponents?: ComponentChildren[];\n}\n\nexport class Renderer {\n private rootConfig: RootConfig;\n private routes: RouteTrie<Route>;\n private assetMap: AssetMap;\n\n constructor(rootConfig: RootConfig, options: {assetMap: AssetMap}) {\n this.rootConfig = rootConfig;\n this.routes = getRoutes(this.rootConfig);\n this.assetMap = options.assetMap;\n }\n\n async render(url: string): Promise<{html?: string; notFound?: boolean}> {\n const [route, routeParams] = this.routes.get(url);\n if (route && route.module && route.module.default) {\n return await this.renderRoute(route, {routeParams});\n }\n return {notFound: true};\n }\n\n async renderRoute(\n route: Route,\n options: {routeParams: Record<string, string>}\n ): Promise<{html?: string; notFound?: boolean}> {\n const routeParams = options.routeParams;\n const assetMap = this.assetMap;\n const Component = route.module.default;\n if (!Component) {\n throw new Error(\n 'unable to render route. the route should have a default export that renders a jsx component.'\n );\n }\n let props = {};\n if (route.module.getStaticProps) {\n const propsData = await route.module.getStaticProps({\n params: routeParams,\n });\n if (propsData.notFound) {\n return this.render404();\n }\n if (propsData.props) {\n props = propsData.props;\n }\n }\n\n const locale = route.locale;\n const translations = getTranslations(locale);\n const ctx: RequestContext = {\n route,\n props,\n routeParams,\n locale,\n translations,\n };\n const headComponents: ComponentChildren[] = [];\n const userScripts: ScriptProps[] = [];\n const htmlContext: HtmlContextValue = {attrs: {}};\n const vdom = (\n <REQUEST_CONTEXT.Provider value={ctx}>\n <I18N_CONTEXT.Provider value={{locale, translations}}>\n <HTML_CONTEXT.Provider value={htmlContext}>\n <HEAD_CONTEXT.Provider value={headComponents}>\n <SCRIPT_CONTEXT.Provider value={userScripts}>\n <Component {...props} />\n </SCRIPT_CONTEXT.Provider>\n </HEAD_CONTEXT.Provider>\n </HTML_CONTEXT.Provider>\n </I18N_CONTEXT.Provider>\n </REQUEST_CONTEXT.Provider>\n );\n const mainHtml = renderToString(vdom);\n\n const jsDeps = new Set<string>();\n const cssDeps = new Set<string>();\n\n // Walk the page's dependency tree for CSS dependencies that are added via\n // `import 'foo.scss'` or `import 'foo.module.scss'`.\n const pageAsset = await assetMap.get(route.src);\n if (pageAsset) {\n const pageCssDeps = await pageAsset.getCssDeps();\n pageCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n\n // Parse the HTML for custom elements that are found within the project\n // and automatically inject the script deps for them.\n await this.collectElementDeps(mainHtml, jsDeps, cssDeps);\n\n // Add user defined scripts added via the `<Script>` component.\n await Promise.all(\n userScripts.map(async (scriptDep) => {\n const scriptAsset = await assetMap.get(scriptDep.src.slice(1));\n if (scriptAsset) {\n jsDeps.add(scriptAsset.assetUrl);\n const scriptJsDeps = await scriptAsset.getJsDeps();\n scriptJsDeps.forEach((dep) => jsDeps.add(dep));\n }\n })\n );\n\n cssDeps.forEach((cssUrl) => {\n headComponents.push(<link rel=\"stylesheet\" href={cssUrl} />);\n });\n jsDeps.forEach((jsUrls) => {\n headComponents.push(<script type=\"module\" src={jsUrls} />);\n });\n\n const htmlLang = htmlContext.attrs.lang || locale;\n const html = await this.renderHtml({\n mainHtml,\n locale: htmlLang,\n headComponents,\n });\n return {html};\n }\n\n async getSitemap(): Promise<\n Record<string, {route: Route; params: Record<string, string>}>\n > {\n const sitemap: Record<\n string,\n {route: Route; params: Record<string, string>}\n > = {};\n await this.routes.walk(async (urlPath: string, route: Route) => {\n const routePaths = await getAllPathsForRoute(urlPath, route);\n routePaths.forEach((routePath) => {\n sitemap[routePath.urlPath] = {\n route,\n params: routePath.params,\n };\n });\n });\n return sitemap;\n }\n\n private async renderHtml(options: RenderHtmlOptions) {\n const page = (\n <html lang={options.locale}>\n <head>\n <meta charSet=\"utf-8\" />\n {options.headComponents}\n </head>\n <body dangerouslySetInnerHTML={{__html: options.mainHtml}} />\n </html>\n );\n const html = `<!doctype html>\\n${renderToString(page)}\\n`;\n return html;\n }\n\n async render404() {\n return {\n html: '<!doctype html><html><title>404 Not Found</title><h1>404 Not Found</h1>',\n notFound: true,\n };\n }\n\n async renderError(error: unknown) {\n const mainHtml = renderToString(<ErrorPage error={error} />);\n const html = await this.renderHtml({mainHtml, locale: 'en'});\n return {html};\n }\n\n async renderDevServer404() {\n const sitemap = await this.getSitemap();\n const mainHtml = renderToString(<DevNotFoundPage sitemap={sitemap} />);\n const html = await this.renderHtml({\n mainHtml,\n locale: 'en',\n headComponents: [<title>404: Not Found</title>],\n });\n return {html};\n }\n\n /**\n * Parses rendered HTML for custom element tags used on the page and\n * automatically adds the JS/CSS deps to the page.\n */\n private async collectElementDeps(\n html: string,\n jsDeps: Set<string>,\n cssDeps: Set<string>\n ): Promise<{jsDeps: Set<string>; cssDeps: Set<string>}> {\n const assetMap = this.assetMap;\n\n const re = /<(\\w[\\w-]+\\w)/g;\n const matches = Array.from(html.matchAll(re));\n await Promise.all(\n matches.map(async (match) => {\n const tagName = match[1];\n // Custom elements require a dash.\n if (tagName && tagName.includes('-') && tagName in elementsMap) {\n const elementModule = elementsMap[tagName];\n const asset = await assetMap.get(elementModule.src);\n if (!asset) {\n return;\n }\n const assetJsDeps = await asset.getJsDeps();\n assetJsDeps.forEach((dep) => jsDeps.add(dep));\n const assetCssDeps = await asset.getCssDeps();\n assetCssDeps.forEach((dep) => cssDeps.add(dep));\n }\n })\n );\n\n return {jsDeps, cssDeps};\n }\n}\n","import path from 'node:path';\nimport {ComponentType} from 'preact';\nimport {RootConfig} from '../core/config';\nimport {GetStaticPaths, GetStaticProps} from '../core/types';\nimport {RouteTrie} from './route-trie';\n\nexport interface RouteModule {\n default?: ComponentType<unknown>;\n getStaticPaths?: GetStaticPaths;\n getStaticProps?: GetStaticProps;\n}\n\nexport interface Route {\n /** The relative path to the route file, e.g. `routes/index.tsx`. */\n src: string;\n\n /** The imported route module. */\n module: RouteModule;\n\n /** The locale used for the route. */\n locale: string;\n\n /**\n * The mapped URL path for the route, e.g.:\n *\n * routes/index.tsx => `/`.\n * routes/events.tsx => `/events`.\n * routes/blog/[slug].tsx => `/blog/[slug]`.\n *\n * Per the example above, this value may contain placeholder params.\n */\n routePath: string;\n\n /**\n * The localized URL path for the route, e.g. `/[locale]/blog/[slug]`.\n * Per the example above, this value contains placeholder params.\n */\n localeRoutePath: string;\n}\n\nexport function getRoutes(config: RootConfig) {\n const locales = config.i18n?.locales || [];\n const i18nUrlFormat = config.i18n?.urlFormat || '/{locale}/{path}';\n const defaultLocale = config.i18n?.defaultLocale || 'en';\n\n const routes = import.meta.glob(\n ['/routes/*.ts', '/routes/**/*.ts', '/routes/*.tsx', '/routes/**/*.tsx'],\n {\n eager: true,\n }\n );\n const trie = new RouteTrie<Route>();\n Object.keys(routes).forEach((modulePath) => {\n const src = modulePath.slice(1);\n let routePath = modulePath.replace(/^\\/routes/, '');\n const parts = path.parse(routePath);\n if (parts.name.startsWith('_')) {\n return;\n }\n if (parts.name === 'index') {\n routePath = parts.dir;\n } else {\n routePath = path.join(parts.dir, parts.name);\n }\n\n const localeRoutePath = i18nUrlFormat\n .replace('{locale}', '[locale]')\n .replace('{path}', routePath.replace(/^\\/*/, ''));\n\n trie.add(routePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: defaultLocale,\n routePath,\n localeRoutePath,\n });\n\n // At the moment, all routes are assumed to use the site-wide i18n config.\n // TODO(stevenle): provide routes with a way to override the default\n // i18n serving behavior.\n locales.forEach((locale) => {\n const localePath = localeRoutePath.replace('[locale]', locale);\n if (localePath !== routePath) {\n trie.add(localePath, {\n src,\n module: routes[modulePath] as RouteModule,\n locale: locale,\n routePath,\n localeRoutePath,\n });\n }\n });\n });\n return trie;\n}\n\nexport async function getAllPathsForRoute(\n urlPathFormat: string,\n route: Route\n): Promise<Array<{urlPath: string; params: Record<string, string>}>> {\n const routeModule = route.module;\n if (!routeModule.default) {\n return [];\n }\n\n const urlPaths: Array<{urlPath: string; params: Record<string, string>}> = [];\n if (routeModule.getStaticPaths) {\n const staticPaths = await routeModule.getStaticPaths();\n if (staticPaths.paths) {\n staticPaths.paths.forEach(\n (pathParams: {params: Record<string, string>}) => {\n const urlPath = replaceParams(urlPathFormat, pathParams.params || {});\n if (pathContainsPlaceholders(urlPath)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, double check getStaticPaths() and ensure all params are returned. more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({\n urlPath: replaceParams(urlPathFormat, pathParams.params),\n params: pathParams.params || {},\n });\n }\n }\n );\n }\n } else if (pathContainsPlaceholders(urlPathFormat)) {\n console.warn(\n `path contains placeholders: ${urlPathFormat}, did you forget to define getStaticPaths()? more info: https://rootjs.dev/guide/routes#getStaticPaths`\n );\n } else {\n urlPaths.push({urlPath: urlPathFormat, params: {}});\n }\n return urlPaths;\n}\n\nexport function replaceParams(\n urlPathFormat: string,\n params: Record<string, string>\n) {\n const urlPath = urlPathFormat.replaceAll(\n /\\[(\\.\\.\\.)?([\\w\\-_]*)\\]/g,\n (match: string, _wildcard: string, key: string) => {\n const val = params[key];\n if (!val) {\n throw new Error(`unreplaced param ${match} in url: ${urlPathFormat}`);\n }\n return val;\n }\n );\n return urlPath;\n}\n\nfunction pathContainsPlaceholders(urlPath: string) {\n const segments = urlPath.split('/');\n return segments.some((segment) => {\n return segment.startsWith('[') && segment.endsWith(']');\n });\n}\n","/**\n * A trie data structure that stores routes. The trie supports `:param` and\n * `*wildcard` values.\n */\nexport class RouteTrie<T> {\n private children: Record<string, RouteTrie<T>> = {};\n private paramChild?: ParamChild<T>;\n private wildcardChild?: WildcardChild<T>;\n private route?: T;\n\n /**\n * Adds a route to the trie.\n */\n add(path: string, route: T) {\n path = this.normalizePath(path);\n\n // If the end was reached, save the value to the node.\n if (path === '') {\n this.route = route;\n return;\n }\n\n const [head, tail] = this.splitPath(path);\n if (head.startsWith('[...') && head.endsWith(']')) {\n const paramName = head.slice(4, -1);\n this.wildcardChild = new WildcardChild(paramName, route);\n return;\n }\n\n let nextNode: RouteTrie<T>;\n if (head.startsWith('[') && head.endsWith(']')) {\n if (!this.paramChild) {\n const paramName = head.slice(1, -1);\n this.paramChild = new ParamChild(paramName);\n }\n nextNode = this.paramChild.trie;\n } else {\n nextNode = this.children[head];\n if (!nextNode) {\n nextNode = new RouteTrie();\n this.children[head] = nextNode;\n }\n }\n nextNode.add(tail, route);\n }\n\n /**\n * Returns a route mapped to the given path and any parameter values from the\n * URL.\n */\n get(path: string): [T | undefined, Record<string, string>] {\n const params = {};\n const route = this.getRoute(path, params);\n return [route, params];\n }\n\n /**\n * Walks the route trie and calls a callback function for each route.\n */\n walk(cb: (urlPath: string, route: T) => Promise<void> | void): Promise<void> {\n const promises: Array<Promise<void>> = [];\n const addPromise = (promise: Promise<void> | void) => {\n if (promise) {\n promises.push(promise);\n }\n };\n if (this.route) {\n addPromise(cb('/', this.route));\n }\n if (this.paramChild) {\n const param = `[${this.paramChild.name}]`;\n this.paramChild.trie.walk((childPath: string, route: T) => {\n const paramUrlPath = `/${param}${childPath}`;\n addPromise(cb(paramUrlPath, route));\n });\n }\n if (this.wildcardChild) {\n const wildcardUrlPath = `/[...${this.wildcardChild.name}]`;\n addPromise(cb(wildcardUrlPath, this.wildcardChild.route));\n }\n for (const subpath of Object.keys(this.children)) {\n const childTrie = this.children[subpath];\n childTrie.walk((childPath: string, childRoute: T) => {\n addPromise(cb(`/${subpath}${childPath}`, childRoute));\n });\n }\n return Promise.all(promises).then(() => {});\n }\n\n /**\n * Removes all routes from the trie.\n */\n clear() {\n this.children = {};\n this.paramChild = undefined;\n this.wildcardChild = undefined;\n this.route = undefined;\n }\n\n private getRoute(\n urlPath: string,\n params: Record<string, string>\n ): T | undefined {\n urlPath = this.normalizePath(urlPath);\n if (urlPath === '') {\n return this.route;\n }\n\n const [head, tail] = this.splitPath(urlPath);\n\n const child = this.children[head];\n if (child) {\n const route = child.getRoute(tail, params);\n if (route) {\n return route;\n }\n }\n\n if (this.paramChild) {\n const route = this.paramChild.trie.getRoute(tail, params);\n if (route) {\n params[this.paramChild.name] = head;\n return route;\n }\n }\n\n if (this.wildcardChild) {\n params[this.wildcardChild.name] = urlPath;\n return this.wildcardChild.route;\n }\n\n return undefined;\n }\n\n /**\n * Normalizes a path for inclusion into the route trie.\n */\n private normalizePath(path: string) {\n // Remove leading slashes.\n return path.replace(/^\\/+/g, '');\n }\n\n /**\n * Splits the parent directory from its children, e.g.:\n *\n * splitPath(\"foo/bar/baz\") -> [\"foo\", \"bar/baz\"]\n */\n private splitPath(path: string): [string, string] {\n const i = path.indexOf('/');\n if (i === -1) {\n return [path, ''];\n }\n return [path.slice(0, i), path.slice(i + 1)];\n }\n}\n\n/**\n * A node in the RouteTrie for a :param child.\n */\nclass ParamChild<T> {\n readonly name: string;\n readonly trie: RouteTrie<T> = new RouteTrie();\n\n constructor(name: string) {\n this.name = name;\n }\n}\n\n/**\n * A node in the RouteTrie for a *wildcard child.\n */\nclass WildcardChild<T> {\n readonly name: string;\n readonly route: T;\n\n constructor(name: string, route: T) {\n this.name = name;\n this.route = route;\n }\n}\n","import {Route} from '../../render/router';\n\nconst STYLES = `\nbody {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', sans-serif;\n}\n\nh1 {\n margin-bottom: 40px;\n}\n\n.route-list {\n display: grid;\n grid-template-columns: auto 1fr;\n align-items: center;\n column-gap: 24px;\n row-gap: 8px;\n padding: 0 40px;\n}\n\n.route-module {\n text-align: right;\n}\n\nhr {\n margin: 60px 0;\n}\n`;\n\ninterface DevNotFoundPageProps {\n sitemap: Record<string, {route: Route; params: Record<string, string>}>;\n}\n\nexport function DevNotFoundPage(props: DevNotFoundPageProps) {\n const routesList: Array<Route & {urlPath: string}> = [];\n Object.keys(props.sitemap).forEach((urlPath) => {\n const route = props.sitemap[urlPath].route;\n routesList.push(Object.assign({}, route, {urlPath}));\n });\n return (\n <>\n <style dangerouslySetInnerHTML={{__html: STYLES}}></style>\n <div>\n <h1>\n <strong>404:</strong> Not Found\n </h1>\n {routesList.length > 0 ? (\n <>\n <h2>Routes found in the project:</h2>\n <div class=\"route-list\">\n {routesList.map((route) => (\n <>\n <div class=\"route-module\">{route.modulePath}</div>\n <a class=\"route-url\" href={route.urlPath}>\n {route.urlPath}\n </a>\n </>\n ))}\n </div>\n </>\n ) : (\n <>\n <h2>No routes found in the project</h2>\n <p>\n Add your first route at <code>/routes/index.tsx</code>\n </p>\n </>\n )}\n <hr />\n <p>\n Note: This page could use some love! If you're interested in helping\n to style this page, please reach out to the root.js developers!\n </p>\n </div>\n </>\n );\n}\n"],"mappings":";;;;;;;;;;;AAEA,OAAO,oBAAoB;;;ACF3B,OAAO,UAAU;;;ACIV,IAAM,YAAN,MAAmB;AAAA,EAAnB;AACL,SAAQ,WAAyC,CAAC;AAAA;AAAA,EAQlD,IAAIA,OAAc,OAAU;AAC1B,IAAAA,QAAO,KAAK,cAAcA,KAAI;AAG9B,QAAIA,UAAS,IAAI;AACf,WAAK,QAAQ;AACb;AAAA,IACF;AAEA,UAAM,CAAC,MAAM,IAAI,IAAI,KAAK,UAAUA,KAAI;AACxC,QAAI,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IACH;AAEA,WAAO,EAAC,QAAQ,QAAO;AAAA,EACzB;AACF;","names":["path","jsx","jsxs"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blinkk/root",
3
- "version": "1.0.0-alpha.28",
3
+ "version": "1.0.0-alpha.29",
4
4
  "author": "s@blinkk.com",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/components/error-page.tsx","../src/core/components/head.ts","../src/core/components/script.ts","../src/core/i18n.ts","../src/core/request-context.ts"],"sourcesContent":["export interface ErrorPageProps {\n error: unknown;\n}\n\nexport function ErrorPage(props: ErrorPageProps) {\n const error = props.error;\n\n let message = undefined;\n if (import.meta.env.DEV) {\n if (error instanceof Error) {\n message = error.stack;\n } else {\n message = String(error);\n }\n }\n\n return (\n <div>\n <div>\n <p>An error occured during route handling or page rendering.</p>\n {message && <pre>{message}</pre>}\n </div>\n </div>\n );\n}\n","import {ComponentChildren, createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const HEAD_CONTEXT = createContext<ComponentChildren[]>([]);\n\nexport interface HeadProps {\n children?: ComponentChildren;\n}\n\n/**\n * The <Head> component can be used for injecting elements into the HTML head\n * tag from any part of a page.\n */\nexport function Head(props: HeadProps) {\n let context: ComponentChildren[];\n try {\n context = useContext(HEAD_CONTEXT);\n } catch (err) {\n console.log(err);\n throw new Error(\n '<Head> component is not supported in the browser, or during suspense renders.',\n {cause: err}\n );\n }\n context.push(props.children);\n return null;\n}\n","import {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const SCRIPT_CONTEXT = createContext<ScriptProps[]>([]);\n\nexport interface ScriptProps {\n src: string;\n type?: string;\n}\n\n/**\n * The <Script> component is used for rendering any custom script modules. At\n * the moment, the system only pre-renders and bundles files that are in the\n * `/bundles` folder at the root of the project.\n */\nexport function Script(props: ScriptProps) {\n let context: ScriptProps[];\n try {\n context = useContext(SCRIPT_CONTEXT);\n } catch (err) {\n throw new Error(\n '<Script> component is not supported in the browser, or during suspense renders.',\n {cause: err}\n );\n }\n context.push(props);\n return null;\n}\n","import path from 'node:path';\nimport {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\n\nexport const I18N_CONTEXT = createContext<I18nContext | null>(null);\n\nexport interface I18nContext {\n locale: string;\n translations: Record<string, string>;\n}\n\nexport function getTranslations(locale: string): Record<string, string> {\n const translations: Record<string, Record<string, string>> = {};\n const translationsFiles = import.meta.glob(['/translations/*.json'], {\n eager: true,\n }) as Record<string, {default?: Record<string, string>}>;\n Object.keys(translationsFiles).forEach((translationPath) => {\n const parts = path.parse(translationPath);\n const locale = parts.name;\n const module = translationsFiles[translationPath];\n if (module && module.default) {\n translations[locale] = module.default;\n }\n });\n return translations[locale] || {};\n}\n\nexport function useI18nContext() {\n const context = useContext(I18N_CONTEXT);\n if (!context) {\n throw new Error('could not find i18n context');\n }\n return context;\n}\n\nexport function useTranslations() {\n const context = useI18nContext();\n const translations = context.translations || {};\n const t = (str: string, params?: Record<string, string>) => {\n let translation = translations[str] || str || '';\n if (params) {\n for (const key of Object.keys(params)) {\n const val = String(params[key] || '');\n translation = translation.replaceAll(`{${key}}`, val);\n }\n }\n return translation;\n };\n return t;\n}\n","import {createContext} from 'preact';\nimport {useContext} from 'preact/hooks';\nimport {Route} from '../render/router';\n\nexport interface RequestContext {\n /** The route file. */\n route: Route;\n /**\n * Route param values. E.g. for a route like `routes/blog/[slug].tsx`,\n * visiting `/blog/foo` will pass {slug: 'foo'} here.\n */\n routeParams: Record<string, string>;\n /** Props passed to the route's server component. */\n props: any;\n /** The current locale. */\n locale: string;\n /** Translations map for the current locale. */\n translations: Record<string, string>;\n}\n\nexport const REQUEST_CONTEXT = createContext<RequestContext | null>(null);\n\nexport function useRequestContext() {\n const context = useContext(REQUEST_CONTEXT);\n if (!context) {\n throw new Error('could not find request context');\n }\n return context;\n}\n"],"mappings":";AAkBM,SACE,KADF;AAdC,SAAS,UAAU,OAAuB;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