@manyducks.co/dolla 3.3.0 β 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/core/context.d.ts +15 -1
- package/dist/core/debug.d.ts +2 -2
- package/dist/core/index.d.ts +2 -2
- package/dist/core/markup/nodes/view.d.ts +7 -1
- package/dist/core/root.d.ts +4 -6
- package/dist/core/signals.d.ts +11 -0
- package/dist/{core-BRSu5hVw.js β core-C4DWUGxz.js} +154 -113
- package/dist/core-C4DWUGxz.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/jsx-dev-runtime.js +1 -1
- package/dist/jsx-runtime.js +1 -1
- package/dist/router/index.d.ts +2 -3
- package/dist/router/router.d.ts +1 -1
- package/dist/router/store.d.ts +2 -2
- package/dist/router.js +193 -204
- package/dist/router.js.map +1 -1
- package/dist/translate/index.d.ts +1 -1
- package/dist/translate.js +45 -45
- package/dist/translate.js.map +1 -1
- package/package.json +1 -1
- package/dist/core-BRSu5hVw.js.map +0 -1
package/dist/router.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"router.js","names":[],"sources":["../src/router/utils.ts","../src/router/store.ts","../src/router/router.ts","../src/router/index.ts"],"sourcesContent":["import { View } from \"../types.js\";\nimport { assert, isArray, isFunction, isObject, isString, uniqueId } from \"../utils.js\";\nimport type { JourneyStep, Route, RouteLayer, Stringable } from \"./types.js\";\n\nexport interface Match {\n /**\n * The path string that triggered this match.\n */\n path: string;\n\n /**\n * The pattern satisfied by `path`.\n */\n pattern: string;\n\n /**\n * Named params as parsed from `path`.\n */\n params: Record<string, string>;\n\n /**\n * Query params as parsed from `path`.\n */\n query: Record<string, string>;\n\n /**\n * Freeform data you wish to store with this route.\n * Merged `data` from all matched layers are available on the router's `match.meta`.\n */\n meta: Record<any, any>;\n}\n\nexport interface RouteMatch extends Match {\n layers: RouteLayer[];\n redirect?: string | ((match: Match) => string) | ((match: Match) => Promise<string>);\n}\n\nexport type RoutePayload = {\n pattern: string;\n meta: Record<any, any>;\n layers?: RouteLayer[];\n redirect?: string | ((match: Match) => string) | ((match: Match) => Promise<string>);\n};\n\nexport type RouteMatchOptions = {\n willMatch?: (route: RoutePayload) => boolean;\n};\n\n/**\n * Separates a URL path into multiple fragments.\n *\n * @param path - A path string (e.g. `\"/api/users/5\"`)\n * @returns an array of fragments (e.g. `[\"api\", \"users\", \"5\"]`)\n */\nexport function splitPath(path: string): string[] {\n return path\n .split(\"/\")\n .map((f) => f.trim())\n .filter(Boolean);\n}\n\n/**\n * Joins multiple URL path fragments into a single string.\n *\n * @param parts - One or more URL fragments (e.g. `[\"api\", \"users\", 5]`)\n * @returns a joined path (e.g. `\"api/users/5\"`)\n */\n\nexport function joinPath(parts: { toString(): string }[]): string {\n const joined = parts\n .map((p) => p.toString())\n .filter(Boolean)\n .join(\"/\");\n if (!joined) return \"\";\n\n const isAbsolute = joined.startsWith(\"/\");\n const segments = joined.split(\"/\");\n const resolved: string[] = [];\n\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n // Pop the previous segment unless we're at the root, or already backing up\n if (resolved.length > 0 && resolved[resolved.length - 1] !== \"..\") {\n resolved.pop();\n } else if (!isAbsolute) {\n resolved.push(\"..\");\n }\n } else {\n resolved.push(segment);\n }\n }\n\n let result = resolved.join(\"/\");\n if (isAbsolute) result = \"/\" + result;\n\n return result || (isAbsolute ? \"/\" : \"\");\n}\n\nexport function resolvePath(base: string, part: string | null = null): string {\n if (part == null) {\n part = base;\n base = \"\";\n }\n\n // If the target is absolute, it replaces the base entirely\n if (part.startsWith(\"/\")) return joinPath([part]);\n\n // Otherwise, join them and let joinPath resolve the '.' and '..'\n return joinPath([base, part]);\n}\n\nexport function parseQueryParams(query: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(query));\n}\n\nexport function mergeQueryParams(\n previous: Record<string, string>,\n current: Record<string, Stringable | null>,\n preserve?: boolean | string[],\n) {\n const merged: Record<string, any> = {};\n\n if (preserve === true) {\n Object.assign(merged, previous);\n } else if (isArray(preserve)) {\n for (const key of preserve) {\n if (key in previous) merged[key] = previous[key];\n }\n }\n\n for (const [key, value] of Object.entries(current)) {\n if (value === null) {\n delete merged[key]; // Explicit nulls act as 'delete'\n } else {\n merged[key] = value;\n }\n }\n\n return new URLSearchParams(merged as Record<string, string>);\n}\n\nexport class RouteNode {\n staticChildren = new Map<string, RouteNode>();\n numericChild: RouteNode | null = null;\n paramChild: RouteNode | null = null;\n wildcardChild: RouteNode | null = null;\n\n // Set if this node represents the end of a valid path\n route?: RoutePayload;\n paramName?: string;\n numericName?: string;\n}\n\nexport function buildRouteTree(routes: Route[]): RouteNode {\n const root = new RouteNode();\n const redirectsToValidate: RoutePayload[] = [];\n\n function insertIntoTree(pattern: string, payload: RoutePayload) {\n const parts = splitPath(pattern);\n let current = root;\n\n for (const part of parts) {\n if (part === \"*\") {\n current = current.wildcardChild ??= new RouteNode();\n } else if (part.charCodeAt(0) === 123) {\n // {\n if (part.charCodeAt(1) === 35) {\n // #\n current = current.numericChild ??= new RouteNode();\n current.numericName = part.slice(2, -1);\n } else {\n current = current.paramChild ??= new RouteNode();\n current.paramName = part.slice(1, -1);\n }\n } else {\n const key = part.toLowerCase();\n let next = current.staticChildren.get(key);\n if (!next) current.staticChildren.set(key, (next = new RouteNode()));\n current = next;\n }\n }\n current.route = payload;\n }\n\n function parse(route: Route, parents: Route[] = [], layers: RouteLayer[] = []) {\n assert(isObject<Route>(route) && isString(route.path), \"Invalid route object\");\n\n const parentPaths = parents.map((p) => p.path);\n const parent = parents.at(-1);\n const meta = parent && route.meta ? { ...parent.meta, ...route.meta } : route.meta || {};\n\n const rawPattern = parentPaths.length ? joinPath([...parentPaths, route.path]) : route.path;\n const patterns = expandOptionalPaths(rawPattern);\n\n if (route.redirect) {\n assert(!route.routes && !route.view, \"Route cannot mix redirect with view/routes\");\n let redirect = route.redirect;\n\n if (isString(redirect)) {\n redirect = resolvePath(joinPath(parentPaths), redirect);\n if (!redirect.startsWith(\"/\")) redirect = \"/\" + redirect;\n }\n\n for (const pattern of patterns) {\n const payload: RoutePayload = { pattern, meta, redirect };\n insertIntoTree(pattern, payload);\n if (isString(redirect)) redirectsToValidate.push(payload);\n }\n\n return;\n }\n\n assert(route.view || route.routes, \"Route must have view, redirect, or routes\");\n\n let view = (route.view || ((props: any) => props.children)) as View<any>;\n if (!isFunction(view) && !(view as any)._lazy) {\n throw new TypeError(`Expected view function for ${route.path}`);\n }\n\n if (route.routes) {\n // For parent nodes, create the layer using the raw pattern and recurse\n const layer: RouteLayer = {\n id: uniqueId(),\n pattern: rawPattern,\n view,\n preload: route.preload,\n errorView: route.errorView,\n };\n for (const subroute of route.routes) parse(subroute, [...parents, route], [...layers, layer]);\n } else {\n // For leaf nodes, register every permutation as a valid endpoint\n for (const pattern of patterns) {\n const layer: RouteLayer = {\n id: uniqueId(),\n pattern, // Use the specific expanded pattern for this layer\n view,\n preload: route.preload,\n errorView: route.errorView,\n };\n insertIntoTree(pattern, { pattern, meta, layers: [...layers, layer] });\n }\n }\n }\n\n for (const route of routes) parse(route);\n\n for (const payload of redirectsToValidate) {\n assert(\n matchRoute(root, payload.redirect as string, { willMatch: (r) => r !== payload }),\n `Dead redirect: ${payload.pattern} -> ${payload.redirect}`,\n );\n }\n\n return root;\n}\n\nexport function matchRoute(rootNode: RouteNode, url: string, options: RouteMatchOptions = {}): RouteMatch | undefined {\n const [path, query] = url.split(\"?\");\n const parts = splitPath(path);\n const paramState: Record<string, string> = {}; // Reused across branches\n\n function search(node: RouteNode, index: number): RouteMatch | undefined {\n // if we've consumed all URL parts\n if (index === parts.length) {\n if (node.route && (!options.willMatch || options.willMatch(node.route))) {\n return {\n path: path || \"/\",\n pattern: node.route.pattern,\n params: { ...paramState },\n query: parseQueryParams(query || \"\"),\n meta: node.route.meta,\n layers: node.route.layers ?? [],\n redirect: node.route.redirect,\n };\n }\n\n // Allow wildcards to match zero remaining segments\n if (node.wildcardChild && node.wildcardChild.route) {\n if (!options.willMatch || options.willMatch(node.wildcardChild.route)) {\n return {\n path: path || \"/\",\n pattern: node.wildcardChild.route.pattern,\n params: { ...paramState, wildcard: \"/\" },\n query: parseQueryParams(query || \"\"),\n meta: node.wildcardChild.route.meta,\n layers: node.wildcardChild.route.layers ?? [],\n redirect: node.wildcardChild.route.redirect,\n };\n }\n }\n\n return undefined;\n }\n\n const part = parts[index];\n const lowerPart = part.toLowerCase();\n\n const staticNode = node.staticChildren.get(lowerPart);\n if (staticNode) {\n const result = search(staticNode, index + 1);\n if (result) return result;\n }\n\n if (node.numericChild && !isNaN(Number(part))) {\n paramState[node.numericChild.numericName!] = part;\n const result = search(node.numericChild, index + 1);\n if (result) return result;\n delete paramState[node.numericChild.numericName!];\n }\n\n if (node.paramChild) {\n paramState[node.paramChild.paramName!] = decodeURIComponent(part);\n const result = search(node.paramChild, index + 1);\n if (result) return result;\n delete paramState[node.paramChild.paramName!];\n }\n\n if (node.wildcardChild && node.wildcardChild.route) {\n if (!options.willMatch || options.willMatch(node.wildcardChild.route)) {\n return {\n path: path || \"/\",\n pattern: node.wildcardChild.route.pattern,\n params: { ...paramState, wildcard: \"/\" + parts.slice(index).map(decodeURIComponent).join(\"/\") },\n query: parseQueryParams(query || \"\"),\n meta: node.wildcardChild.route.meta,\n layers: node.wildcardChild.route.layers ?? [],\n redirect: node.wildcardChild.route.redirect,\n };\n }\n }\n\n return undefined;\n }\n\n return search(rootNode, 0);\n}\n\nexport interface ResolvedRoute {\n match?: RouteMatch;\n journey: JourneyStep[];\n}\n\n/**\n * Takes a URL and finds a match, following redirects.\n */\nexport async function resolveRoute(\n rootNode: RouteNode,\n path: string,\n journey: JourneyStep[] = [],\n): Promise<ResolvedRoute> {\n const match = matchRoute(rootNode, path);\n\n if (!match) return { journey: [...journey, { kind: \"miss\", message: `no match for '${path}'` }] };\n\n if (match.redirect != null) {\n let target = match.redirect;\n\n if (isString(target)) {\n target = replaceParams(target, match.params);\n } else {\n target = await target(match);\n assert(isString(target), \"Redirect function must return a path.\");\n if (!target.startsWith(\"/\")) target = resolvePath(match.path, target);\n }\n\n return resolveRoute(rootNode, target, [\n ...journey,\n { kind: \"redirect\", message: `redirecting '${match.path}' -> '${target}'` },\n ]);\n }\n\n // TODO: Data preload\n\n return { match, journey: [...journey, { kind: \"match\", message: `matched route '${match.path}'` }] };\n}\n\n/**\n * Intercepts links within the root node.\n *\n * This is adapted from https://github.com/choojs/nanohref/blob/master/index.js\n *\n * @param root - Element under which to intercept link clicks\n * @param callback - Function to call when a click event is intercepted\n * @param _window - (optional) Override for global window object\n */\nexport function catchLinks(\n root: Element,\n callback: (href: string, anchor: HTMLAnchorElement) => void,\n _window = window,\n) {\n function handler(e: MouseEvent) {\n if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) return;\n\n const anchor = (e.target as Element).closest(\"a\");\n if (!anchor || !root.contains(anchor)) return;\n\n const href = anchor.getAttribute(\"href\");\n if (!href) return;\n\n if (\n _window.location.protocol !== anchor.protocol ||\n _window.location.hostname !== anchor.hostname ||\n _window.location.port !== anchor.port ||\n anchor.hasAttribute(\"data-router-ignore\") ||\n anchor.hasAttribute(\"download\") ||\n anchor.getAttribute(\"target\") === \"_blank\" ||\n /^[\\w-_]+:/.test(href)\n ) {\n return;\n }\n\n e.preventDefault();\n callback(href, anchor);\n }\n\n root.addEventListener(\"click\", handler as any);\n return () => root.removeEventListener(\"click\", handler as any);\n}\n\nexport function expandOptionalPaths(path: string): string[] {\n const parts = splitPath(path);\n const permutations: string[][] = [[]];\n\n for (const part of parts) {\n // Strictly enforces the inside style: {param?} or {#param?}\n const isOptional = part.endsWith(\"?}\");\n const cleanPart = isOptional ? part.replace(\"?\", \"\") : part;\n\n if (isOptional) {\n const withPart = permutations.map((p) => [...p, cleanPart]);\n permutations.push(...withPart);\n } else {\n for (const p of permutations) {\n p.push(cleanPart);\n }\n }\n }\n\n return permutations.map((p) => \"/\" + p.join(\"/\")).map((p) => (p === \"/\" ? p : p.replace(/\\/$/, \"\")));\n}\n\n/**\n * Replace route pattern param placeholders with real matched values.\n */\nexport function replaceParams(path: string, params: Record<string, string | number>) {\n for (const key in params) {\n const value = String(params[key]);\n path = path\n .replace(`{${key}}`, value)\n .replace(`{#${key}}`, value)\n .replace(`{${key}?}`, value) // Handle optional string param\n .replace(`{#${key}?}`, value); // Handle optional numeric param\n }\n\n // Remove any remaining unmatched optional parameters\n path = path.replace(/\\{#?[a-zA-Z0-9_]+\\?\\}/g, \"\");\n\n // Clean up any double slashes created by the removal\n path = path.replace(/\\/+/g, \"/\");\n\n // Strip trailing slash unless the entire path is just \"/\"\n if (path.length > 1 && path.endsWith(\"/\")) {\n path = path.slice(0, -1);\n }\n\n return path;\n}\n\nexport interface HistoryAdapter {\n getPath(): string;\n getSearch(): string;\n getKey(): string;\n getIndex(): number;\n push(url: string): void;\n replace(url: string): void;\n}\n\nexport function createHistoryAdapter(useHash: boolean): HistoryAdapter {\n let currentIndex = window.history.state?.index || 0;\n\n if (window.history.state?.index === undefined) {\n window.history.replaceState({ ...window.history.state, key: Date.now().toString(), index: currentIndex }, \"\");\n }\n\n const getPath = useHash ? () => window.location.hash.slice(1).split(\"?\")[0] || \"/\" : () => window.location.pathname;\n const getSearch = useHash\n ? () => {\n const hash = window.location.hash;\n const searchIndex = hash.indexOf(\"?\");\n return searchIndex !== -1 ? hash.slice(searchIndex) : \"\";\n }\n : () => window.location.search;\n\n const getKey = () => window.history.state?.key || \"root\";\n const getIndex = () => window.history.state?.index || 0;\n\n return {\n getPath,\n getSearch,\n getKey,\n getIndex,\n push: (url) => {\n currentIndex++;\n const prefix = useHash ? \"/#\" : \"\";\n window.history.pushState({ key: uniqueId(), index: currentIndex }, \"\", prefix + url);\n },\n replace: (url) => {\n const prefix = useHash ? \"/#\" : \"\";\n window.history.replaceState({ key: getKey(), index: currentIndex }, \"\", prefix + url);\n },\n };\n}\n","import { compose, getDebug, peek, unwrap, type Context, type Getter, type MaybeGetter, type Setter } from \"../core\";\nimport type { Router } from \"./types\";\nimport { mergeQueryParams, resolvePath, type HistoryAdapter, type Match } from \"./utils\";\n\nexport interface RouterStoreProps {\n currentMatch: Getter<Match>;\n setCurrentMatch: Setter<Match>;\n progress: Getter<number>;\n history: HistoryAdapter;\n updateRoute: () => void;\n guards: Set<() => boolean | Promise<boolean>>;\n}\n\nexport function RouterStore(\n this: Context,\n { currentMatch, setCurrentMatch, progress, history, updateRoute, guards }: RouterStoreProps,\n): Router {\n this.name = \"dolla:router\";\n const debug = getDebug(this);\n\n async function navigate(path: string, replace: boolean) {\n for (const guard of guards) {\n if (await guard()) return;\n }\n\n debug.info(`πΊοΈ navigating to '${path}'${replace ? \" (replace)\" : \"\"}`);\n\n const resolved = resolvePath(history.getPath(), path);\n replace ? history.replace(resolved) : history.push(resolved);\n updateRoute();\n }\n\n return {\n path: compose(() => currentMatch().path),\n pattern: compose(() => currentMatch().pattern),\n params: compose(() => currentMatch().params),\n query: compose(() => currentMatch().query),\n meta: compose(() => currentMatch().meta),\n progress: progress,\n\n setQuery(params) {\n const m = peek(currentMatch);\n const merged = mergeQueryParams(m.query, params, true);\n const query = Object.fromEntries(merged);\n\n setCurrentMatch({ ...m, query });\n\n const queryString = merged.size ? \"?\" + merged.toString() : \"\";\n history.replace(m.path + queryString);\n\n return query;\n },\n\n back: (steps = 1) => window.history.go(-steps),\n forward: (steps = 1) => window.history.go(steps),\n\n push: (path) => navigate(path, false),\n replace: (path) => navigate(path, true),\n\n block: (guard) => {\n guards.add(guard);\n return () => guards.delete(guard);\n },\n\n isActive(path: MaybeGetter<string>, exact = false) {\n return compose(() => {\n const _path = unwrap(path);\n const target = _path === \"/\" ? \"/\" : _path.replace(/\\/$/, \"\");\n const targetSlash = target === \"/\" ? \"/\" : target + \"/\";\n\n const current = currentMatch().path;\n const normalized = current === \"/\" ? \"/\" : current.replace(/\\/$/, \"\");\n\n if (exact) return normalized === target;\n\n // Ensure segment boundaries match (prevents /app matching /apple)\n return normalized === target || normalized.startsWith(targetSlash);\n });\n },\n };\n}\n","import { addStore, Context, createContext, onCleanup, onMount } from \"../core/context.js\";\nimport { DollaPlugin, getDebug, getRootElement } from \"../core/index.js\";\nimport { DynamicNode } from \"../core/markup/nodes/dynamic.js\";\nimport { ViewNode } from \"../core/markup/nodes/view.js\";\nimport type { MarkupNode } from \"../core/markup/types.js\";\nimport { addListener, createMarkup } from \"../core/markup/utils.js\";\nimport { batch, peek, createAtom } from \"../core/signals.js\";\nimport { DEBUG } from \"../core/symbols.js\";\nimport type { View } from \"../types.js\";\nimport { assert } from \"../utils.js\";\nimport { RouterStore } from \"./store.js\";\nimport type { ActiveLayer, LazyLoader, LazyView, RouterOptions } from \"./types.js\";\nimport {\n buildRouteTree,\n catchLinks,\n createHistoryAdapter,\n type Match,\n mergeQueryParams,\n replaceParams,\n resolveRoute,\n} from \"./utils.js\";\n\nconst ROUTER_ROOT_SLOT = Symbol();\n\n/**\n * Lazy loads a view when its route is first matched.\n *\n * @example\n * {\n * path: \"/users\",\n * view: lazy(() => import(\"./views/users.js\"))\n * }\n */\nexport function lazy(load: LazyLoader): LazyView {\n return { _lazy: true, load };\n}\n\nexport function createRouterPlugin(options: RouterOptions): DollaPlugin {\n return function (context) {\n if (\"scrollRestoration\" in window.history) {\n window.history.scrollRestoration = \"manual\";\n }\n\n const history = createHistoryAdapter(!!options.hash);\n const scrollCache = new Map<string, number>();\n let currentKey = history.getKey();\n\n const [currentMatch, setCurrentMatch] = createAtom<Match>({\n path: history.getPath(),\n pattern: \"\",\n params: {},\n query: Object.fromEntries(new URLSearchParams(history.getSearch())),\n meta: {},\n });\n\n const [progress, setProgress] = createAtom(0);\n const routeTree = buildRouteTree(options.routes);\n\n const guards = new Set<() => boolean | Promise<boolean>>();\n\n const routerContext = createContext(context);\n routerContext.name = \"dolla:router\";\n\n const console = getDebug(routerContext);\n const [rootSlot, setRootSlot] = createAtom<MarkupNode>();\n\n context[ROUTER_ROOT_SLOT] = rootSlot;\n\n const rootLayer: Partial<ActiveLayer> = {\n context,\n slot: rootSlot,\n setSlot: setRootSlot,\n };\n\n const activeLayers: ActiveLayer[] = [];\n\n /**\n * Run when the location changes. Diffs and mounts new routes and updates\n * the signals accordingly.\n */\n async function updateRoute(href?: string) {\n scrollCache.set(currentKey, window.scrollY);\n\n const path = href ?? history.getPath();\n const { match, journey } = await resolveRoute(routeTree, path);\n\n if (context[DEBUG]) {\n for (let i = 0; i < journey.length; i++) {\n const step = journey[i];\n const tag = `(update ${i + 1}/${journey.length})`;\n if (step.kind === \"match\") {\n console.info(`π ${tag} ${step.message}`);\n } else if (step.kind === \"redirect\") {\n console.info(`β©οΈ ${tag} ${step.message}`);\n } else {\n console.info(`π ${tag} ${step.message}`);\n }\n }\n }\n\n if (!match) throw new Error(`Failed to match route '${path}'`);\n\n const { layers, params } = match;\n const targetKeys: string[] = [];\n let branchIndex = 0;\n\n // Compute keys and find out where mounted layers diverge from matched layers\n for (let i = 0; i < layers.length; i++) {\n const key = `${layers[i].id}:${replaceParams(layers[i].pattern, params)}`;\n targetKeys.push(key);\n if (branchIndex === i && activeLayers[i]?.key === key) branchIndex++;\n }\n\n const tasks: Promise<void>[] = [];\n const preloadedData: any[] = []; // Offsets match loop index minus divIndex\n\n // Execute preloads and lazy component fetches\n for (let i = branchIndex; i < layers.length; i++) {\n const layer = layers[i];\n\n if (layer.preload) {\n tasks.push(\n Promise.resolve(layer.preload(match)).then((data) => {\n preloadedData[i - branchIndex] = data;\n }),\n );\n }\n\n const view = layer.view as LazyView;\n if (view._lazy) {\n tasks.push(\n view.load().then((mod) => {\n layer.view = (mod as any).default ?? mod; // Overwrite with loaded module\n }),\n );\n }\n }\n\n let caughtError: Error | null = null;\n let errorIndex = -1;\n\n // Track loading progress if there are async tasks\n if (tasks.length > 0) {\n setProgress(0.1);\n let completed = 0;\n const increment = 0.8 / tasks.length;\n\n tasks.forEach((p) => p.then(() => setProgress(0.1 + ++completed * increment)).catch(() => {}));\n\n try {\n await Promise.all(tasks);\n } catch (error) {\n setProgress(0);\n if (error instanceof RedirectError) return api.replace(error.redirectPath);\n\n caughtError = error instanceof Error ? error : new Error(String(error));\n errorIndex = branchIndex;\n }\n }\n\n // Merge query params and sync URL if redirect occurred\n const query = mergeQueryParams(peek(currentMatch).query, match.query, options.preserveQuery);\n const queryString = query.toString();\n const newUrl = match.path + (queryString ? `?${queryString}` : \"\");\n\n if (newUrl !== history.getPath() + history.getSearch()) {\n history.replace(newUrl);\n }\n\n // Batch state updates and DOM mutations\n batch(() => {\n setCurrentMatch({ ...match, query: Object.fromEntries(query) });\n\n if (branchIndex === layers.length && activeLayers.length === layers.length) return;\n\n // Fast truncate arrays and drop old DOM branches\n if (activeLayers[branchIndex]) {\n activeLayers[branchIndex].node.unmount();\n activeLayers.length = branchIndex;\n }\n\n // Mount new layers\n for (let i = branchIndex; i < layers.length; i++) {\n const layer = layers[i];\n const parent = activeLayers[i - 1] ?? rootLayer;\n const [slot, setSlot] = createAtom<MarkupNode>();\n\n let viewToMount = layer.view as View<any>;\n let propsToPass: any = {\n data: preloadedData[i - branchIndex],\n children: createMarkup(DynamicNode, { args: [slot] }),\n };\n\n // Handle Error Boundaries\n if (caughtError && i === errorIndex) {\n if (!layer.errorView) throw caughtError;\n viewToMount = layer.errorView;\n propsToPass = { error: caughtError };\n }\n\n const node = new ViewNode(parent.context!, viewToMount, propsToPass);\n parent.setSlot(node);\n\n activeLayers.push({\n id: layer.id,\n key: targetKeys[i],\n node,\n context: node.context,\n slot,\n setSlot,\n });\n\n if (caughtError && i === errorIndex) break;\n }\n });\n\n setProgress(0);\n\n requestAnimationFrame(() => {\n window.scrollTo(0, scrollCache.get(history.getKey()) ?? 0);\n currentKey = history.getKey();\n });\n }\n\n const api = addStore(context, RouterStore, {\n currentMatch,\n setCurrentMatch,\n progress,\n history,\n updateRoute,\n guards,\n });\n\n onMount(context, () => {\n let isReverting = false;\n let isReplaying = false;\n let lastIndex = history.getIndex();\n\n const removePop = addListener(window, \"popstate\", async () => {\n // If this popstate is the result of us reverting the URL, ignore it.\n if (isReverting) {\n isReverting = false;\n return;\n }\n\n // If this popstate is the result of us replaying an allowed navigation, accept it.\n if (isReplaying) {\n isReplaying = false;\n lastIndex = history.getIndex();\n updateRoute();\n return;\n }\n\n const newIndex = history.getIndex();\n const delta = lastIndex - newIndex; // Positive if user clicked Back\n\n // If guards exist, revert synchronously first\n if (guards.size > 0) {\n isReverting = true;\n window.history.go(delta); // Restores the URL immediately\n\n // Run guards while the URL is back in its original state\n let blocked = false;\n for (const guard of guards) {\n if (await guard()) {\n blocked = true;\n break;\n }\n }\n\n // If guards passed, replay the intended navigation\n if (!blocked) {\n isReplaying = true;\n window.history.go(-delta);\n }\n return;\n }\n\n // Normal flow (no guards)\n lastIndex = newIndex;\n updateRoute();\n });\n\n // Block tab closure/reload if guards exist\n const removeUnload = addListener(window, \"beforeunload\", (e: BeforeUnloadEvent) => {\n if (guards.size > 0) {\n e.preventDefault();\n e.returnValue = \"\"; // Triggers the native browser warning dialog\n }\n });\n\n const removeClick = catchLinks(getRootElement(context), api.push);\n\n onCleanup(context, () => {\n removePop();\n removeUnload();\n removeClick();\n });\n\n updateRoute();\n });\n };\n}\n\n/**\n * Displays the router's content.\n */\nexport function Outlet(this: Context) {\n this.name = \"dolla:router\";\n\n const rootSlot = this[ROUTER_ROOT_SLOT];\n assert(rootSlot != null, \"Router plugin not found on root.\");\n\n return new DynamicNode(this, rootSlot);\n}\n\nexport class RedirectError extends Error {\n constructor(public redirectPath: string) {\n super(`Redirecting to ${redirectPath}`);\n this.name = \"RedirectError\";\n }\n}\n","import { Context, getStore } from \"../core\";\nimport { RouterStore } from \"./store\";\n\nexport { createRouterPlugin, lazy, Outlet, RedirectError } from \"./router\";\nexport type { RouterOptions } from \"./types\";\n\nexport function getRouter(context: Context) {\n return getStore(context, RouterStore);\n}\n"],"mappings":";;AAsDA,SAAgB,EAAU,GAAwB;AAChD,QAAO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src/router/router.ts"],"sourcesContent":["import { View } from \"../types.js\";\nimport { assert, isArray, isFunction, isObject, isString, uniqueId } from \"../utils.js\";\nimport type { JourneyStep, Route, RouteLayer, Stringable } from \"./types.js\";\n\nexport interface Match {\n /**\n * The path string that triggered this match.\n */\n path: string;\n\n /**\n * The pattern satisfied by `path`.\n */\n pattern: string;\n\n /**\n * Named params as parsed from `path`.\n */\n params: Record<string, string>;\n\n /**\n * Query params as parsed from `path`.\n */\n query: Record<string, string>;\n\n /**\n * Freeform data you wish to store with this route.\n * Merged `data` from all matched layers are available on the router's `match.meta`.\n */\n meta: Record<any, any>;\n}\n\nexport interface RouteMatch extends Match {\n layers: RouteLayer[];\n redirect?: string | ((match: Match) => string) | ((match: Match) => Promise<string>);\n}\n\nexport type RoutePayload = {\n pattern: string;\n meta: Record<any, any>;\n layers?: RouteLayer[];\n redirect?: string | ((match: Match) => string) | ((match: Match) => Promise<string>);\n};\n\nexport type RouteMatchOptions = {\n willMatch?: (route: RoutePayload) => boolean;\n};\n\n/**\n * Separates a URL path into multiple fragments.\n *\n * @param path - A path string (e.g. `\"/api/users/5\"`)\n * @returns an array of fragments (e.g. `[\"api\", \"users\", \"5\"]`)\n */\nexport function splitPath(path: string): string[] {\n return path\n .split(\"/\")\n .map((f) => f.trim())\n .filter(Boolean);\n}\n\n/**\n * Joins multiple URL path fragments into a single string.\n *\n * @param parts - One or more URL fragments (e.g. `[\"api\", \"users\", 5]`)\n * @returns a joined path (e.g. `\"api/users/5\"`)\n */\n\nexport function joinPath(parts: { toString(): string }[]): string {\n const joined = parts\n .map((p) => p.toString())\n .filter(Boolean)\n .join(\"/\");\n if (!joined) return \"\";\n\n const isAbsolute = joined.startsWith(\"/\");\n const segments = joined.split(\"/\");\n const resolved: string[] = [];\n\n for (const segment of segments) {\n if (segment === \"\" || segment === \".\") continue;\n if (segment === \"..\") {\n // Pop the previous segment unless we're at the root, or already backing up\n if (resolved.length > 0 && resolved[resolved.length - 1] !== \"..\") {\n resolved.pop();\n } else if (!isAbsolute) {\n resolved.push(\"..\");\n }\n } else {\n resolved.push(segment);\n }\n }\n\n let result = resolved.join(\"/\");\n if (isAbsolute) result = \"/\" + result;\n\n return result || (isAbsolute ? \"/\" : \"\");\n}\n\nexport function resolvePath(base: string, part: string | null = null): string {\n if (part == null) {\n part = base;\n base = \"\";\n }\n\n // If the target is absolute, it replaces the base entirely\n if (part.startsWith(\"/\")) return joinPath([part]);\n\n // Otherwise, join them and let joinPath resolve the '.' and '..'\n return joinPath([base, part]);\n}\n\nexport function parseQueryParams(query: string): Record<string, string> {\n return Object.fromEntries(new URLSearchParams(query));\n}\n\nexport function mergeQueryParams(\n previous: Record<string, string>,\n current: Record<string, Stringable | null>,\n preserve?: boolean | string[],\n) {\n const merged: Record<string, any> = {};\n\n if (preserve === true) {\n Object.assign(merged, previous);\n } else if (isArray(preserve)) {\n for (const key of preserve) {\n if (key in previous) merged[key] = previous[key];\n }\n }\n\n for (const [key, value] of Object.entries(current)) {\n if (value === null) {\n delete merged[key]; // Explicit nulls act as 'delete'\n } else {\n merged[key] = value;\n }\n }\n\n return new URLSearchParams(merged as Record<string, string>);\n}\n\nexport class RouteNode {\n staticChildren = new Map<string, RouteNode>();\n numericChild: RouteNode | null = null;\n paramChild: RouteNode | null = null;\n wildcardChild: RouteNode | null = null;\n\n // Set if this node represents the end of a valid path\n route?: RoutePayload;\n paramName?: string;\n numericName?: string;\n}\n\nexport function buildRouteTree(routes: Route[]): RouteNode {\n const root = new RouteNode();\n const redirectsToValidate: RoutePayload[] = [];\n\n function insertIntoTree(pattern: string, payload: RoutePayload) {\n const parts = splitPath(pattern);\n let current = root;\n\n for (const part of parts) {\n if (part === \"*\") {\n current = current.wildcardChild ??= new RouteNode();\n } else if (part.charCodeAt(0) === 123) {\n // {\n if (part.charCodeAt(1) === 35) {\n // #\n current = current.numericChild ??= new RouteNode();\n current.numericName = part.slice(2, -1);\n } else {\n current = current.paramChild ??= new RouteNode();\n current.paramName = part.slice(1, -1);\n }\n } else {\n const key = part.toLowerCase();\n let next = current.staticChildren.get(key);\n if (!next) current.staticChildren.set(key, (next = new RouteNode()));\n current = next;\n }\n }\n current.route = payload;\n }\n\n function parse(route: Route, parents: Route[] = [], layers: RouteLayer[] = []) {\n assert(isObject<Route>(route) && isString(route.path), \"Invalid route object\");\n\n const parentPaths = parents.map((p) => p.path);\n const parent = parents.at(-1);\n const meta = parent && route.meta ? { ...parent.meta, ...route.meta } : route.meta || {};\n\n const rawPattern = parentPaths.length ? joinPath([...parentPaths, route.path]) : route.path;\n const patterns = expandOptionalPaths(rawPattern);\n\n if (route.redirect) {\n assert(!route.routes && !route.view, \"Route cannot mix redirect with view/routes\");\n let redirect = route.redirect;\n\n if (isString(redirect)) {\n redirect = resolvePath(joinPath(parentPaths), redirect);\n if (!redirect.startsWith(\"/\")) redirect = \"/\" + redirect;\n }\n\n for (const pattern of patterns) {\n const payload: RoutePayload = { pattern, meta, redirect };\n insertIntoTree(pattern, payload);\n if (isString(redirect)) redirectsToValidate.push(payload);\n }\n\n return;\n }\n\n assert(route.view || route.routes, \"Route must have view, redirect, or routes\");\n\n let view = (route.view || ((props: any) => props.children)) as View<any>;\n if (!isFunction(view) && !(view as any)._lazy) {\n throw new TypeError(`Expected view function for ${route.path}`);\n }\n\n if (route.routes) {\n // For parent nodes, create the layer using the raw pattern and recurse\n const layer: RouteLayer = {\n id: uniqueId(),\n pattern: rawPattern,\n view,\n preload: route.preload,\n errorView: route.errorView,\n };\n for (const subroute of route.routes) parse(subroute, [...parents, route], [...layers, layer]);\n } else {\n // For leaf nodes, register every permutation as a valid endpoint\n for (const pattern of patterns) {\n const layer: RouteLayer = {\n id: uniqueId(),\n pattern, // Use the specific expanded pattern for this layer\n view,\n preload: route.preload,\n errorView: route.errorView,\n };\n insertIntoTree(pattern, { pattern, meta, layers: [...layers, layer] });\n }\n }\n }\n\n for (const route of routes) parse(route);\n\n for (const payload of redirectsToValidate) {\n assert(\n matchRoute(root, payload.redirect as string, { willMatch: (r) => r !== payload }),\n `Dead redirect: ${payload.pattern} -> ${payload.redirect}`,\n );\n }\n\n return root;\n}\n\nexport function matchRoute(rootNode: RouteNode, url: string, options: RouteMatchOptions = {}): RouteMatch | undefined {\n const [path, query] = url.split(\"?\");\n const parts = splitPath(path);\n const paramState: Record<string, string> = {}; // Reused across branches\n\n function search(node: RouteNode, index: number): RouteMatch | undefined {\n // if we've consumed all URL parts\n if (index === parts.length) {\n if (node.route && (!options.willMatch || options.willMatch(node.route))) {\n return {\n path: path || \"/\",\n pattern: node.route.pattern,\n params: { ...paramState },\n query: parseQueryParams(query || \"\"),\n meta: node.route.meta,\n layers: node.route.layers ?? [],\n redirect: node.route.redirect,\n };\n }\n\n // Allow wildcards to match zero remaining segments\n if (node.wildcardChild && node.wildcardChild.route) {\n if (!options.willMatch || options.willMatch(node.wildcardChild.route)) {\n return {\n path: path || \"/\",\n pattern: node.wildcardChild.route.pattern,\n params: { ...paramState, wildcard: \"/\" },\n query: parseQueryParams(query || \"\"),\n meta: node.wildcardChild.route.meta,\n layers: node.wildcardChild.route.layers ?? [],\n redirect: node.wildcardChild.route.redirect,\n };\n }\n }\n\n return undefined;\n }\n\n const part = parts[index];\n const lowerPart = part.toLowerCase();\n\n const staticNode = node.staticChildren.get(lowerPart);\n if (staticNode) {\n const result = search(staticNode, index + 1);\n if (result) return result;\n }\n\n if (node.numericChild && !isNaN(Number(part))) {\n paramState[node.numericChild.numericName!] = part;\n const result = search(node.numericChild, index + 1);\n if (result) return result;\n delete paramState[node.numericChild.numericName!];\n }\n\n if (node.paramChild) {\n paramState[node.paramChild.paramName!] = decodeURIComponent(part);\n const result = search(node.paramChild, index + 1);\n if (result) return result;\n delete paramState[node.paramChild.paramName!];\n }\n\n if (node.wildcardChild && node.wildcardChild.route) {\n if (!options.willMatch || options.willMatch(node.wildcardChild.route)) {\n return {\n path: path || \"/\",\n pattern: node.wildcardChild.route.pattern,\n params: { ...paramState, wildcard: \"/\" + parts.slice(index).map(decodeURIComponent).join(\"/\") },\n query: parseQueryParams(query || \"\"),\n meta: node.wildcardChild.route.meta,\n layers: node.wildcardChild.route.layers ?? [],\n redirect: node.wildcardChild.route.redirect,\n };\n }\n }\n\n return undefined;\n }\n\n return search(rootNode, 0);\n}\n\nexport interface ResolvedRoute {\n match?: RouteMatch;\n journey: JourneyStep[];\n}\n\n/**\n * Takes a URL and finds a match, following redirects.\n */\nexport async function resolveRoute(\n rootNode: RouteNode,\n path: string,\n journey: JourneyStep[] = [],\n): Promise<ResolvedRoute> {\n const match = matchRoute(rootNode, path);\n\n if (!match) return { journey: [...journey, { kind: \"miss\", message: `no match for '${path}'` }] };\n\n if (match.redirect != null) {\n let target = match.redirect;\n\n if (isString(target)) {\n target = replaceParams(target, match.params);\n } else {\n target = await target(match);\n assert(isString(target), \"Redirect function must return a path.\");\n if (!target.startsWith(\"/\")) target = resolvePath(match.path, target);\n }\n\n return resolveRoute(rootNode, target, [\n ...journey,\n { kind: \"redirect\", message: `redirecting '${match.path}' -> '${target}'` },\n ]);\n }\n\n // TODO: Data preload\n\n return { match, journey: [...journey, { kind: \"match\", message: `matched route '${match.path}'` }] };\n}\n\n/**\n * Intercepts links within the root node.\n *\n * This is adapted from https://github.com/choojs/nanohref/blob/master/index.js\n *\n * @param root - Element under which to intercept link clicks\n * @param callback - Function to call when a click event is intercepted\n * @param _window - (optional) Override for global window object\n */\nexport function catchLinks(\n root: Element,\n callback: (href: string, anchor: HTMLAnchorElement) => void,\n _window = window,\n) {\n function handler(e: MouseEvent) {\n if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.defaultPrevented) return;\n\n const anchor = (e.target as Element).closest(\"a\");\n if (!anchor || !root.contains(anchor)) return;\n\n const href = anchor.getAttribute(\"href\");\n if (!href) return;\n\n if (\n _window.location.protocol !== anchor.protocol ||\n _window.location.hostname !== anchor.hostname ||\n _window.location.port !== anchor.port ||\n anchor.hasAttribute(\"data-router-ignore\") ||\n anchor.hasAttribute(\"download\") ||\n anchor.getAttribute(\"target\") === \"_blank\" ||\n /^[\\w-_]+:/.test(href)\n ) {\n return;\n }\n\n e.preventDefault();\n callback(href, anchor);\n }\n\n root.addEventListener(\"click\", handler as any);\n return () => root.removeEventListener(\"click\", handler as any);\n}\n\nexport function expandOptionalPaths(path: string): string[] {\n const parts = splitPath(path);\n const permutations: string[][] = [[]];\n\n for (const part of parts) {\n // Strictly enforces the inside style: {param?} or {#param?}\n const isOptional = part.endsWith(\"?}\");\n const cleanPart = isOptional ? part.replace(\"?\", \"\") : part;\n\n if (isOptional) {\n const withPart = permutations.map((p) => [...p, cleanPart]);\n permutations.push(...withPart);\n } else {\n for (const p of permutations) {\n p.push(cleanPart);\n }\n }\n }\n\n return permutations.map((p) => \"/\" + p.join(\"/\")).map((p) => (p === \"/\" ? p : p.replace(/\\/$/, \"\")));\n}\n\n/**\n * Replace route pattern param placeholders with real matched values.\n */\nexport function replaceParams(path: string, params: Record<string, string | number>) {\n for (const key in params) {\n const value = String(params[key]);\n path = path\n .replace(`{${key}}`, value)\n .replace(`{#${key}}`, value)\n .replace(`{${key}?}`, value) // Handle optional string param\n .replace(`{#${key}?}`, value); // Handle optional numeric param\n }\n\n // Remove any remaining unmatched optional parameters\n path = path.replace(/\\{#?[a-zA-Z0-9_]+\\?\\}/g, \"\");\n\n // Clean up any double slashes created by the removal\n path = path.replace(/\\/+/g, \"/\");\n\n // Strip trailing slash unless the entire path is just \"/\"\n if (path.length > 1 && path.endsWith(\"/\")) {\n path = path.slice(0, -1);\n }\n\n return path;\n}\n\nexport interface HistoryAdapter {\n getPath(): string;\n getSearch(): string;\n getKey(): string;\n getIndex(): number;\n push(url: string): void;\n replace(url: string): void;\n}\n\nexport function createHistoryAdapter(useHash: boolean): HistoryAdapter {\n let currentIndex = window.history.state?.index || 0;\n\n if (window.history.state?.index === undefined) {\n window.history.replaceState({ ...window.history.state, key: Date.now().toString(), index: currentIndex }, \"\");\n }\n\n const getPath = useHash ? () => window.location.hash.slice(1).split(\"?\")[0] || \"/\" : () => window.location.pathname;\n const getSearch = useHash\n ? () => {\n const hash = window.location.hash;\n const searchIndex = hash.indexOf(\"?\");\n return searchIndex !== -1 ? hash.slice(searchIndex) : \"\";\n }\n : () => window.location.search;\n\n const getKey = () => window.history.state?.key || \"root\";\n const getIndex = () => window.history.state?.index || 0;\n\n return {\n getPath,\n getSearch,\n getKey,\n getIndex,\n push: (url) => {\n currentIndex++;\n const prefix = useHash ? \"/#\" : \"\";\n window.history.pushState({ key: uniqueId(), index: currentIndex }, \"\", prefix + url);\n },\n replace: (url) => {\n const prefix = useHash ? \"/#\" : \"\";\n window.history.replaceState({ key: getKey(), index: currentIndex }, \"\", prefix + url);\n },\n };\n}\n","import { compose, createStore, getDebug, peek, unwrap, type Getter, type MaybeGetter, type Setter } from \"../core\";\nimport type { Router } from \"./types\";\nimport { mergeQueryParams, resolvePath, type HistoryAdapter, type Match } from \"./utils\";\n\nexport interface RouterStoreProps {\n currentMatch: Getter<Match>;\n setCurrentMatch: Setter<Match>;\n progress: Getter<number>;\n history: HistoryAdapter;\n updateRoute: () => void;\n guards: Set<() => boolean | Promise<boolean>>;\n}\n\nexport const [addRouter, getRouter] = createStore<Router, RouterStoreProps>(\"dolla:router\", (c, props) => {\n const console = getDebug(c);\n\n const { currentMatch, setCurrentMatch, progress, history, updateRoute, guards } = props;\n\n async function navigate(path: string, replace: boolean) {\n for (const guard of guards) {\n if (await guard()) return;\n }\n\n console.info(`πΊοΈ navigating to '${path}'${replace ? \" (replace)\" : \"\"}`);\n\n const resolved = resolvePath(history.getPath(), path);\n replace ? history.replace(resolved) : history.push(resolved);\n updateRoute();\n }\n\n return {\n path: compose(() => currentMatch().path),\n pattern: compose(() => currentMatch().pattern),\n params: compose(() => currentMatch().params),\n query: compose(() => currentMatch().query),\n meta: compose(() => currentMatch().meta),\n progress: progress,\n\n setQuery(params) {\n const m = peek(currentMatch);\n const merged = mergeQueryParams(m.query, params, true);\n const query = Object.fromEntries(merged);\n\n setCurrentMatch({ ...m, query });\n\n const queryString = merged.size ? \"?\" + merged.toString() : \"\";\n history.replace(m.path + queryString);\n\n return query;\n },\n\n back: (steps = 1) => window.history.go(-steps),\n forward: (steps = 1) => window.history.go(steps),\n\n push: (path) => navigate(path, false),\n replace: (path) => navigate(path, true),\n\n block: (guard) => {\n guards.add(guard);\n return () => guards.delete(guard);\n },\n\n isActive(path: MaybeGetter<string>, exact = false) {\n return compose(() => {\n const _path = unwrap(path);\n const target = _path === \"/\" ? \"/\" : _path.replace(/\\/$/, \"\");\n const targetSlash = target === \"/\" ? \"/\" : target + \"/\";\n\n const current = currentMatch().path;\n const normalized = current === \"/\" ? \"/\" : current.replace(/\\/$/, \"\");\n\n if (exact) return normalized === target;\n\n // Ensure segment boundaries match (prevents /app matching /apple)\n return normalized === target || normalized.startsWith(targetSlash);\n });\n },\n };\n});\n","import { Context, onCleanup, onMount } from \"../core/context.js\";\nimport { DollaPlugin, createDebug, getRootElement } from \"../core/index.js\";\nimport { DynamicNode } from \"../core/markup/nodes/dynamic.js\";\nimport { ViewNode } from \"../core/markup/nodes/view.js\";\nimport type { MarkupNode } from \"../core/markup/types.js\";\nimport { addListener, createMarkup } from \"../core/markup/utils.js\";\nimport { batch, createAtom, peek } from \"../core/signals.js\";\nimport { DEBUG } from \"../core/symbols.js\";\nimport type { View } from \"../types.js\";\nimport { assert } from \"../utils.js\";\nimport { addRouter } from \"./store.js\";\nimport type { ActiveLayer, LazyLoader, LazyView, RouterOptions } from \"./types.js\";\nimport {\n buildRouteTree,\n catchLinks,\n createHistoryAdapter,\n mergeQueryParams,\n replaceParams,\n resolveRoute,\n type Match,\n} from \"./utils.js\";\n\nconst ROUTER_ROOT_SLOT = Symbol.for(\"$_ROUTER_ROOT_SLOT\");\n\n/**\n * Lazy loads a view when its route is first matched.\n *\n * @example\n * {\n * path: \"/users\",\n * view: lazy(() => import(\"./views/users.js\"))\n * }\n */\nexport function lazy(load: LazyLoader): LazyView {\n return { _lazy: true, load };\n}\n\nexport function createRouter(options: RouterOptions): DollaPlugin {\n return function (context) {\n if (\"scrollRestoration\" in window.history) {\n window.history.scrollRestoration = \"manual\";\n }\n\n const history = createHistoryAdapter(!!options.hash);\n const scrollCache = new Map<string, number>();\n let currentKey = history.getKey();\n\n const [currentMatch, setCurrentMatch] = createAtom<Match>({\n path: history.getPath(),\n pattern: \"\",\n params: {},\n query: Object.fromEntries(new URLSearchParams(history.getSearch())),\n meta: {},\n });\n\n const [progress, setProgress] = createAtom(0);\n const routeTree = buildRouteTree(options.routes);\n\n const guards = new Set<() => boolean | Promise<boolean>>();\n\n const console = createDebug(\"dolla:router\");\n const [rootSlot, setRootSlot] = createAtom<MarkupNode>();\n\n context[ROUTER_ROOT_SLOT] = rootSlot;\n\n const rootLayer: Partial<ActiveLayer> = {\n context,\n slot: rootSlot,\n setSlot: setRootSlot,\n };\n\n const activeLayers: ActiveLayer[] = [];\n\n /**\n * Run when the location changes. Diffs and mounts new routes and updates\n * the signals accordingly.\n */\n async function updateRoute(href?: string) {\n scrollCache.set(currentKey, window.scrollY);\n\n const path = href ?? history.getPath();\n const { match, journey } = await resolveRoute(routeTree, path);\n\n if (context[DEBUG]) {\n for (let i = 0; i < journey.length; i++) {\n const step = journey[i];\n const tag = `(update ${i + 1}/${journey.length})`;\n if (step.kind === \"match\") {\n console.info(`π ${tag} ${step.message}`);\n } else if (step.kind === \"redirect\") {\n console.info(`β©οΈ ${tag} ${step.message}`);\n } else {\n console.info(`π ${tag} ${step.message}`);\n }\n }\n }\n\n if (!match) throw new Error(`Failed to match route '${path}'`);\n\n const { layers, params } = match;\n const targetKeys: string[] = [];\n let branchIndex = 0;\n\n // Compute keys and find out where mounted layers diverge from matched layers\n for (let i = 0; i < layers.length; i++) {\n const key = `${layers[i].id}:${replaceParams(layers[i].pattern, params)}`;\n targetKeys.push(key);\n if (branchIndex === i && activeLayers[i]?.key === key) branchIndex++;\n }\n\n const tasks: Promise<void>[] = [];\n const preloadedData: any[] = []; // Offsets match loop index minus divIndex\n\n // Execute preloads and lazy component fetches\n for (let i = branchIndex; i < layers.length; i++) {\n const layer = layers[i];\n\n if (layer.preload) {\n tasks.push(\n Promise.resolve(layer.preload(match)).then((data) => {\n preloadedData[i - branchIndex] = data;\n }),\n );\n }\n\n const view = layer.view as LazyView;\n if (view._lazy) {\n tasks.push(\n view.load().then((mod) => {\n layer.view = (mod as any).default ?? mod; // Overwrite with loaded module\n }),\n );\n }\n }\n\n let caughtError: Error | null = null;\n let errorIndex = -1;\n\n // Track loading progress if there are async tasks\n if (tasks.length > 0) {\n setProgress(0.1);\n let completed = 0;\n const increment = 0.8 / tasks.length;\n\n tasks.forEach((p) => p.then(() => setProgress(0.1 + ++completed * increment)).catch(() => {}));\n\n try {\n await Promise.all(tasks);\n } catch (error) {\n setProgress(0);\n if (error instanceof RedirectError) return api.replace(error.redirectPath);\n\n caughtError = error instanceof Error ? error : new Error(String(error));\n errorIndex = branchIndex;\n }\n }\n\n // Merge query params and sync URL if redirect occurred\n const query = mergeQueryParams(peek(currentMatch).query, match.query, options.preserveQuery);\n const queryString = query.toString();\n const newUrl = match.path + (queryString ? `?${queryString}` : \"\");\n\n if (newUrl !== history.getPath() + history.getSearch()) {\n history.replace(newUrl);\n }\n\n // Batch state updates and DOM mutations\n batch(() => {\n setCurrentMatch({ ...match, query: Object.fromEntries(query) });\n\n if (branchIndex === layers.length && activeLayers.length === layers.length) return;\n\n // Fast truncate arrays and drop old DOM branches\n if (activeLayers[branchIndex]) {\n activeLayers[branchIndex].node.unmount();\n activeLayers.length = branchIndex;\n }\n\n // Mount new layers\n for (let i = branchIndex; i < layers.length; i++) {\n const layer = layers[i];\n const parent = activeLayers[i - 1] ?? rootLayer;\n const [slot, setSlot] = createAtom<MarkupNode>();\n\n let viewToMount = layer.view as View<any>;\n let propsToPass: any = {\n data: preloadedData[i - branchIndex],\n children: createMarkup(DynamicNode, { args: [slot] }),\n };\n\n // Handle Error Boundaries\n if (caughtError && i === errorIndex) {\n if (!layer.errorView) throw caughtError;\n viewToMount = layer.errorView;\n propsToPass = { error: caughtError };\n }\n\n const node = new ViewNode(parent.context!, viewToMount, propsToPass);\n parent.setSlot(node);\n\n activeLayers.push({\n id: layer.id,\n key: targetKeys[i],\n node,\n context: node.context,\n slot,\n setSlot,\n });\n\n if (caughtError && i === errorIndex) break;\n }\n });\n\n setProgress(0);\n\n requestAnimationFrame(() => {\n window.scrollTo(0, scrollCache.get(history.getKey()) ?? 0);\n currentKey = history.getKey();\n });\n }\n\n const api = addRouter(context, {\n currentMatch,\n setCurrentMatch,\n progress,\n history,\n updateRoute,\n guards,\n });\n\n onMount(context, () => {\n let isReverting = false;\n let isReplaying = false;\n let lastIndex = history.getIndex();\n\n const removePop = addListener(window, \"popstate\", async () => {\n // If this popstate is the result of us reverting the URL, ignore it.\n if (isReverting) {\n isReverting = false;\n return;\n }\n\n // If this popstate is the result of us replaying an allowed navigation, accept it.\n if (isReplaying) {\n isReplaying = false;\n lastIndex = history.getIndex();\n updateRoute();\n return;\n }\n\n const newIndex = history.getIndex();\n const delta = lastIndex - newIndex; // Positive if user clicked Back\n\n // If guards exist, revert synchronously first\n if (guards.size > 0) {\n isReverting = true;\n window.history.go(delta); // Restores the URL immediately\n\n // Run guards while the URL is back in its original state\n let blocked = false;\n for (const guard of guards) {\n if (await guard()) {\n blocked = true;\n break;\n }\n }\n\n // If guards passed, replay the intended navigation\n if (!blocked) {\n isReplaying = true;\n window.history.go(-delta);\n }\n return;\n }\n\n // Normal flow (no guards)\n lastIndex = newIndex;\n updateRoute();\n });\n\n // Block tab closure/reload if guards exist\n const removeUnload = addListener(window, \"beforeunload\", (e: BeforeUnloadEvent) => {\n if (guards.size > 0) {\n e.preventDefault();\n e.returnValue = \"\"; // Triggers the native browser warning dialog\n }\n });\n\n const removeClick = catchLinks(getRootElement(context), api.push);\n\n onCleanup(context, () => {\n removePop();\n removeUnload();\n removeClick();\n });\n\n updateRoute();\n });\n };\n}\n\n/**\n * Displays the router's content.\n */\nexport function Outlet(this: Context) {\n this.name = \"dolla:router\";\n\n const rootSlot = this[ROUTER_ROOT_SLOT];\n assert(rootSlot != null, \"Router plugin not found on root.\");\n\n return new DynamicNode(this, rootSlot);\n}\n\nexport class RedirectError extends Error {\n constructor(public redirectPath: string) {\n super(`Redirecting to ${redirectPath}`);\n this.name = \"RedirectError\";\n }\n}\n"],"mappings":";;AAsDA,SAAgB,EAAU,GAAwB;AAChD,QAAO,EACJ,MAAM,IAAI,CACV,KAAK,MAAM,EAAE,MAAM,CAAC,CACpB,OAAO,QAAQ;;AAUpB,SAAgB,EAAS,GAAyC;CAChE,IAAM,IAAS,EACZ,KAAK,MAAM,EAAE,UAAU,CAAC,CACxB,OAAO,QAAQ,CACf,KAAK,IAAI;AACZ,KAAI,CAAC,EAAQ,QAAO;CAEpB,IAAM,IAAa,EAAO,WAAW,IAAI,EACnC,IAAW,EAAO,MAAM,IAAI,EAC5B,IAAqB,EAAE;AAE7B,MAAK,IAAM,KAAW,EAChB,OAAY,MAAM,MAAY,QAC9B,MAAY,OAEV,EAAS,SAAS,KAAK,EAAS,EAAS,SAAS,OAAO,OAC3D,EAAS,KAAK,GACJ,KACV,EAAS,KAAK,KAAK,GAGrB,EAAS,KAAK,EAAQ;CAI1B,IAAI,IAAS,EAAS,KAAK,IAAI;AAG/B,QAFI,MAAY,IAAS,MAAM,IAExB,MAAW,IAAa,MAAM;;AAGvC,SAAgB,EAAY,GAAc,IAAsB,MAAc;AAU5E,QATI,MACF,IAAO,GACP,IAAO,KAIL,EAAK,WAAW,IAAI,GAAS,EAAS,CAAC,EAAK,CAAC,GAG1C,EAAS,CAAC,GAAM,EAAK,CAAC;;AAG/B,SAAgB,EAAiB,GAAuC;AACtE,QAAO,OAAO,YAAY,IAAI,gBAAgB,EAAM,CAAC;;AAGvD,SAAgB,EACd,GACA,GACA,GACA;CACA,IAAM,IAA8B,EAAE;AAEtC,KAAI,MAAa,GACf,QAAO,OAAO,GAAQ,EAAS;UACtB,EAAQ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AGxC,IAAa,IAAb,cAAmC,MAAM;CACvC,YAAY,GAA6B;AAEvC,EADA,MAAM,kBAAkB,IAAe,EADtB,KAAA,eAAA,GAEjB,KAAK,OAAO"}
|
|
@@ -65,7 +65,7 @@ export interface TranslatorOptions {
|
|
|
65
65
|
locale?: string;
|
|
66
66
|
formatters?: Record<string, Formatter>;
|
|
67
67
|
}
|
|
68
|
-
export declare function
|
|
68
|
+
export declare function createTranslate(options: TranslatorOptions): DollaPlugin;
|
|
69
69
|
export declare function getTranslate(context: Context): Translator;
|
|
70
70
|
/**
|
|
71
71
|
* Compiles an object of translated strings into a set of function templates.
|
package/dist/translate.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { F as e, O as t, R as n, k as r } from "./core-C4DWUGxz.js";
|
|
2
2
|
//#region src/translate/index.ts
|
|
3
|
-
var i = Symbol("
|
|
3
|
+
var i = Symbol.for("$_DOLLA_TRANSLATE");
|
|
4
4
|
function a(e) {
|
|
5
5
|
return async function(t) {
|
|
6
6
|
let n = s(e);
|
|
@@ -11,37 +11,37 @@ function o(e) {
|
|
|
11
11
|
if (!e[i]) throw Error("Translate plugin isn't loaded.");
|
|
12
12
|
return e[i];
|
|
13
13
|
}
|
|
14
|
-
function s(
|
|
14
|
+
function s(n) {
|
|
15
15
|
let i = /* @__PURE__ */ new Map();
|
|
16
|
-
if (i.set("number", (e, t, n) => new Intl.NumberFormat(e, n).format(Number(t))), i.set("datetime", (e, t, n) => new Intl.DateTimeFormat(e, n).format(new Date(t))), i.set("list", (e, t, n) => new Intl.ListFormat(e, n).format(t)),
|
|
17
|
-
let a, [o, s] =
|
|
16
|
+
if (i.set("number", (e, t, n) => new Intl.NumberFormat(e, n).format(Number(t))), i.set("datetime", (e, t, n) => new Intl.DateTimeFormat(e, n).format(new Date(t))), i.set("list", (e, t, n) => new Intl.ListFormat(e, n).format(t)), n.formatters) for (let e in n.formatters) i.set(e, n.formatters[e]);
|
|
17
|
+
let a, [o, s] = r("en"), l = [...Object.keys(n.translations)];
|
|
18
18
|
async function u(e) {
|
|
19
|
-
let
|
|
19
|
+
let t;
|
|
20
20
|
if (e === void 0) {
|
|
21
21
|
let e = [];
|
|
22
22
|
if (typeof navigator < "u") {
|
|
23
23
|
let t = navigator;
|
|
24
24
|
t.languages?.length > 0 ? e.push(...t.languages) : t.language ? e.push(t.language) : t.browserLanguage ? e.push(t.browserLanguage) : t.userLanguage && e.push(t.userLanguage);
|
|
25
25
|
}
|
|
26
|
-
for (let r of e) if (r in
|
|
27
|
-
|
|
26
|
+
for (let r of e) if (r in n.translations) {
|
|
27
|
+
t = r;
|
|
28
28
|
break;
|
|
29
29
|
}
|
|
30
|
-
} else e in
|
|
31
|
-
if (
|
|
32
|
-
let e = Object.keys(
|
|
33
|
-
e && (
|
|
30
|
+
} else e in n.translations && (t = e);
|
|
31
|
+
if (t == null) {
|
|
32
|
+
let e = Object.keys(n.translations).at(0);
|
|
33
|
+
e && (t = e);
|
|
34
34
|
}
|
|
35
|
-
if (!
|
|
36
|
-
a = await c(
|
|
35
|
+
if (!t || !(t in n.translations)) throw Error(`Locale '${e}' has no translation.`);
|
|
36
|
+
a = await c(t, i, n.translations[t]), s(t);
|
|
37
37
|
}
|
|
38
|
-
function d(
|
|
39
|
-
return
|
|
38
|
+
function d(e, n) {
|
|
39
|
+
return t(() => (o(), a?.(e, n) ?? e));
|
|
40
40
|
}
|
|
41
|
-
function f(
|
|
42
|
-
let s = i.get(
|
|
43
|
-
if (!s) throw Error(`Unknown format: ${
|
|
44
|
-
return
|
|
41
|
+
function f(n, r, a) {
|
|
42
|
+
let s = i.get(n);
|
|
43
|
+
if (!s) throw Error(`Unknown format: ${n}`);
|
|
44
|
+
return t(() => s(o(), e(r), a ?? {}));
|
|
45
45
|
}
|
|
46
46
|
return {
|
|
47
47
|
supportedLocales: l,
|
|
@@ -51,20 +51,20 @@ function s(t) {
|
|
|
51
51
|
format: f
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
|
-
async function c(
|
|
55
|
-
let a = l(
|
|
56
|
-
return function(
|
|
57
|
-
if (i && (i.context != null && (
|
|
58
|
-
let
|
|
59
|
-
o.has(
|
|
54
|
+
async function c(t, r, i) {
|
|
55
|
+
let a = l(n(i) ? await i() : i), o = new Map(a);
|
|
56
|
+
return function(n, i) {
|
|
57
|
+
if (i && (i.context != null && (n += "_" + i.context), i.count != null)) if (i.ordinal) {
|
|
58
|
+
let r = `${n}_ordinal_(=${i.count})`;
|
|
59
|
+
o.has(r) ? n = r : n += "_ordinal_" + new Intl.PluralRules(t, { type: "ordinal" }).select(e(i.count));
|
|
60
60
|
} else {
|
|
61
|
-
let
|
|
62
|
-
o.has(
|
|
61
|
+
let r = `${n}_(=${i.count})`;
|
|
62
|
+
o.has(r) ? n = r : n += "_" + new Intl.PluralRules(t).select(e(i.count));
|
|
63
63
|
}
|
|
64
|
-
let a = o.get(
|
|
65
|
-
if (!a) return
|
|
64
|
+
let a = o.get(n);
|
|
65
|
+
if (!a) return n;
|
|
66
66
|
let s = "";
|
|
67
|
-
for (let
|
|
67
|
+
for (let e = 0; e < a.length; e++) s += a[e](i, r, t);
|
|
68
68
|
return s;
|
|
69
69
|
};
|
|
70
70
|
}
|
|
@@ -81,14 +81,14 @@ function l(e, t = []) {
|
|
|
81
81
|
}
|
|
82
82
|
return n;
|
|
83
83
|
}
|
|
84
|
-
function u(
|
|
85
|
-
let
|
|
86
|
-
for (let
|
|
87
|
-
let i = t
|
|
84
|
+
function u(t) {
|
|
85
|
+
let n = t.split(/(\{\{.*?\}\})/g), r = [];
|
|
86
|
+
for (let t = 0; t < n.length; t++) {
|
|
87
|
+
let i = n[t];
|
|
88
88
|
if (i) if (i.startsWith("{{") && i.endsWith("}}")) {
|
|
89
|
-
let
|
|
90
|
-
for (let
|
|
91
|
-
let n = e
|
|
89
|
+
let t = i.slice(2, -2).trim().split("|").map((e) => e.trim()), n = t[0], a = [];
|
|
90
|
+
for (let e = 1; e < t.length; e++) {
|
|
91
|
+
let n = t[e], r = n.match(/^([a-zA-Z0-9_]+)(?:\((.*)\))?$/);
|
|
92
92
|
if (r) {
|
|
93
93
|
let e = r[1], t = r[2], n = {};
|
|
94
94
|
if (t) {
|
|
@@ -107,19 +107,19 @@ function u(e) {
|
|
|
107
107
|
options: {}
|
|
108
108
|
});
|
|
109
109
|
}
|
|
110
|
-
|
|
111
|
-
let o =
|
|
110
|
+
r.push((t, r, i) => {
|
|
111
|
+
let o = t ? e(t[n]) : void 0;
|
|
112
112
|
for (let e = 0; e < a.length; e++) {
|
|
113
|
-
let t = a[e],
|
|
114
|
-
|
|
113
|
+
let t = a[e], n = r.get(t.name);
|
|
114
|
+
n && (o = n(i, o, t.options));
|
|
115
115
|
}
|
|
116
116
|
return o == null ? "" : String(o);
|
|
117
117
|
});
|
|
118
|
-
} else
|
|
118
|
+
} else r.push(() => i);
|
|
119
119
|
}
|
|
120
|
-
return
|
|
120
|
+
return r;
|
|
121
121
|
}
|
|
122
122
|
//#endregion
|
|
123
|
-
export { l as compile, a as
|
|
123
|
+
export { l as compile, a as createTranslate, o as getTranslate, u as parseTemplate };
|
|
124
124
|
|
|
125
125
|
//# sourceMappingURL=translate.js.map
|
package/dist/translate.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translate.js","names":[],"sources":["../src/translate/index.ts"],"sourcesContent":["import { Context } from \"../core/context.js\";\nimport { DollaPlugin } from \"../core/root.js\";\nimport { unwrap, compose, createAtom, type Getter } from \"../core/signals.js\";\nimport { isFunction } from \"../utils.js\";\n\n// ----- Types ----- //\n\n/**\n * A JSON object of translated strings. Values can be string templates or nested objects.\n */\nexport interface LocalizedStrings extends Record<string, string | LocalizedStrings> {}\n\n/**\n * A function that returns an object of localized strings.\n */\nexport type TranslationFetchFn = () => LocalizedStrings | Promise<LocalizedStrings>;\n\nexport type TOptions = {\n /**\n *\n */\n count?: Getter<number> | number;\n\n /**\n *\n */\n context?: Getter<string> | string;\n\n [value: string]: Getter<any> | any;\n};\n\nexport type LookupFn = (selector: string, options?: TOptions) => string;\n\nexport type Formatter = (locale: string, value: any, options: Record<string, any>) => string;\n\ntype BuiltInFormatters = {\n number: [number | bigint, Intl.NumberFormatOptions?];\n datetime: [Date, Intl.DateTimeFormatOptions?];\n list: [Iterable<string>, Intl.ListFormatOptions?];\n};\n\nexport interface Translator {\n /**\n * An array of locale names for all translations the app supports.\n */\n supportedLocales: string[];\n\n /**\n * A Readable containing the currently loaded locale.\n */\n currentLocale: Getter<string>;\n\n /**\n * Updates the locale, fetching any translation files as required.\n * Returns a promise that resolves when the new locale is applied.\n *\n * If `name` is undefined the library will try to match the browser language automatically.\n */\n setLocale(name?: string): Promise<void>;\n\n /**\n * Returns a Readable of the value at `key`.\n\n * @param selector - Key to the translated value.\n * @param options - A map of `{{placeholder}}` names and the values to replace them with.\n *\n * @example\n * const value = t(\"your.key.here\", { count: 5 });\n */\n t(selector: string, options?: TOptions): Getter<string>;\n\n format<K extends keyof BuiltInFormatters, V extends BuiltInFormatters[K][0], O extends BuiltInFormatters[K][1]>(\n name: K,\n value: Getter<V> | V,\n options?: O,\n ): Getter<string>;\n\n format<V, O>(name: string, value: Getter<V> | V, options?: O): Getter<string>;\n}\n\nexport interface TranslatorOptions {\n translations: Record<string, LocalizedStrings | TranslationFetchFn>;\n\n /**\n * Default locale to load on startup. The translator will try to match the user's browser language if left undefined.\n */\n locale?: string;\n\n formatters?: Record<string, Formatter>;\n}\n\nconst TRANSLATE = Symbol(\"Dolla.Translator\");\n\nexport function createTranslatePlugin(options: TranslatorOptions): DollaPlugin {\n return async function (context) {\n const translator = createTranslator(options);\n context[TRANSLATE] = translator;\n await translator.setLocale(options.locale);\n };\n}\n\nexport function getTranslate(context: Context): Translator {\n if (!context[TRANSLATE]) throw new Error(\"Translate plugin isn't loaded.\");\n return context[TRANSLATE];\n}\n\n// ----- Code ----- //\n\nfunction createTranslator(options: TranslatorOptions): Translator {\n const formatters = new Map<string, Formatter>();\n\n formatters.set(\"number\", (locale, value, options) => {\n return new Intl.NumberFormat(locale, options).format(Number(value));\n });\n formatters.set(\"datetime\", (locale, value, options) => {\n return new Intl.DateTimeFormat(locale, options).format(new Date(value));\n });\n formatters.set(\"list\", (locale, value, options) => {\n return new Intl.ListFormat(locale, options).format(value);\n });\n\n if (options.formatters) {\n for (const key in options.formatters) {\n formatters.set(key, options.formatters[key]);\n }\n }\n\n let lookup: LookupFn | undefined;\n\n const [currentLocale, setCurrentLocale] = createAtom(\"en\");\n const supportedLocales = [...Object.keys(options.translations)];\n\n /**\n * Loads translation for the locale.\n */\n async function setLocale(name?: string) {\n let locale!: string;\n\n if (name === undefined) {\n let names = [];\n\n if (typeof navigator !== \"undefined\") {\n const nav = navigator as any;\n\n if (nav.languages?.length > 0) {\n names.push(...nav.languages);\n } else if (nav.language) {\n names.push(nav.language);\n } else if (nav.browserLanguage) {\n names.push(nav.browserLanguage);\n } else if (nav.userLanguage) {\n names.push(nav.userLanguage);\n }\n }\n\n for (const name of names) {\n if (name in options.translations) {\n // Found a matching language.\n locale = name;\n break;\n }\n }\n } else {\n // Tag is the actual tag to set.\n if (name in options.translations) {\n locale = name;\n }\n }\n\n if (locale == null) {\n const firstLanguage = Object.keys(options.translations).at(0);\n if (firstLanguage) {\n locale = firstLanguage;\n }\n }\n\n if (!locale || !(locale in options.translations)) {\n throw new Error(`Locale '${name}' has no translation.`);\n }\n\n lookup = await createLookup(locale, formatters, options.translations[locale]);\n\n // Update locale string after init so t() signals will update.\n setCurrentLocale(locale);\n }\n\n function t(selector: string, options?: TOptions): Getter<string> {\n return compose(() => {\n currentLocale(); // track locale\n return lookup?.(selector, options) ?? selector;\n });\n }\n\n function format<\n K extends keyof BuiltInFormatters,\n V extends BuiltInFormatters[K][0],\n O extends BuiltInFormatters[K][1],\n >(name: K, value: Getter<V> | V, options?: O): Getter<string>;\n\n function format<V, O>(name: string, value: Getter<V> | V, options?: O): Getter<string>;\n\n function format(name: string, value: unknown, options?: Record<string, any>): Getter<string> {\n const callback = formatters.get(name);\n if (!callback) {\n throw new Error(`Unknown format: ${name}`);\n }\n\n return compose(() => callback(currentLocale(), unwrap(value), options ?? {}));\n }\n\n return {\n supportedLocales,\n currentLocale,\n setLocale,\n t,\n format,\n };\n}\n\n/**\n * Loads the translation and produces an efficient lookup function.\n */\nasync function createLookup(\n locale: string,\n formatters: Map<string, Formatter>,\n translation: TranslationFetchFn | LocalizedStrings,\n) {\n const strings = isFunction(translation) ? await translation() : translation;\n const entries = compile(strings);\n const templates = new Map(entries);\n\n /**\n * Looks up the template and produces the output. Any reactive values in `options` are tracked when used.\n */\n return function lookup(selector: string, options?: TOptions): string {\n if (options) {\n // Handle count (pluralization) and context. Keys become \"key_context_pluralization\".\n if (options.context != null) {\n selector += \"_\" + options.context;\n }\n if (options.count != null) {\n if (options.ordinal) {\n // Try to match the exact number key if there is one (e.g. \"myExampleKey_ordinal_(=2)\" when count is 2).\n const exact = `${selector}_ordinal_(=${options.count})`;\n if (templates.has(exact)) {\n selector = exact;\n } else {\n selector += \"_ordinal_\" + new Intl.PluralRules(locale, { type: \"ordinal\" }).select(unwrap(options.count));\n }\n } else {\n // Try to match the exact number key if there is one (e.g. \"myExampleKey_(=2)\" when count is 2).\n const exact = `${selector}_(=${options.count})`;\n if (templates.has(exact)) {\n selector = exact;\n } else {\n selector += \"_\" + new Intl.PluralRules(locale).select(unwrap(options.count));\n }\n }\n }\n }\n\n const template = templates.get(selector);\n if (!template) return selector;\n\n let output = \"\";\n\n for (let i = 0; i < template.length; i++) {\n output += template[i](options, formatters, locale);\n }\n\n return output;\n };\n}\n\n/**\n * Compiles an object of translated strings into a set of function templates.\n */\nexport function compile(strings: { [key: string]: any }, path: string[] = []): [string, CompiledTemplate][] {\n const entries: [string, CompiledTemplate][] = [];\n\n for (const key in strings) {\n switch (typeof strings[key]) {\n case \"string\":\n entries.push([[...path, key].join(\".\"), parseTemplate(strings[key])]);\n break;\n case \"object\":\n entries.push(...compile(strings[key], [...path, key]));\n break;\n default:\n throw new Error(\n `Expected to find a string or object at ${[...path, key].join(\".\")}. Got: ${typeof strings[key]}`,\n );\n }\n }\n\n return entries;\n}\n\nexport type TemplateSegmentFn = (\n options: Record<string, any> | undefined,\n formatters: Map<string, Formatter>,\n locale: string,\n) => string;\n\nexport type CompiledTemplate = TemplateSegmentFn[];\n\n/**\n * Parse a string template into an array of functions that will produce each piece of the output when called.\n */\nexport function parseTemplate(template: string): CompiledTemplate {\n const tokens = template.split(/(\\{\\{.*?\\}\\})/g);\n const segments: TemplateSegmentFn[] = [];\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (!token) continue;\n\n if (token.startsWith(\"{{\") && token.endsWith(\"}}\")) {\n const inner = token.slice(2, -2).trim();\n const parts = inner.split(\"|\").map((p) => p.trim());\n\n const name = parts[0];\n const parsedFormats: { name: string; options: Record<string, string> }[] = [];\n\n // Parse formatters at build-time to prevent string splitting on every render\n for (let j = 1; j < parts.length; j++) {\n const formatStr = parts[j];\n const match = formatStr.match(/^([a-zA-Z0-9_]+)(?:\\((.*)\\))?$/);\n\n if (match) {\n const formatName = match[1];\n const optionsStr = match[2];\n const optsObj: Record<string, string> = {};\n\n if (optionsStr) {\n const pairs = optionsStr.split(\",\");\n for (let k = 0; k < pairs.length; k++) {\n const pair = pairs[k];\n const colonIndex = pair.indexOf(\":\");\n if (colonIndex > -1) {\n optsObj[pair.slice(0, colonIndex).trim()] = pair.slice(colonIndex + 1).trim();\n }\n }\n }\n parsedFormats.push({ name: formatName, options: optsObj });\n } else {\n parsedFormats.push({ name: formatStr, options: {} });\n }\n }\n\n // Push the dynamic closure\n segments.push((options, formatters, locale) => {\n // Evaluate and track the specific option at runtime.\n // This code runs in the t() computed context.\n let value = options ? unwrap(options[name]) : undefined;\n\n for (let k = 0; k < parsedFormats.length; k++) {\n const fmt = parsedFormats[k];\n const formatterFn = formatters.get(fmt.name);\n if (formatterFn) {\n value = formatterFn(locale, value, fmt.options);\n }\n }\n\n return value != null ? String(value) : \"\";\n });\n } else {\n // Push a static closure that just returns the token\n segments.push(() => token);\n }\n }\n\n return segments;\n}\n"],"mappings":";;AA2FA,IAAM,IAAY,OAAO,mBAAmB;AAE5C,SAAgB,EAAsB,GAAyC;AAC7E,QAAO,eAAgB,GAAS;EAC9B,IAAM,IAAa,EAAiB,EAAQ;AAE5C,EADA,EAAQ,KAAa,GACrB,MAAM,EAAW,UAAU,EAAQ,OAAO;;;AAI9C,SAAgB,EAAa,GAA8B;AACzD,KAAI,CAAC,EAAQ,GAAY,OAAU,MAAM,iCAAiC;AAC1E,QAAO,EAAQ;;AAKjB,SAAS,EAAiB,GAAwC;CAChE,IAAM,oBAAa,IAAI,KAAwB;AAY/C,KAVA,EAAW,IAAI,WAAW,GAAQ,GAAO,MAChC,IAAI,KAAK,aAAa,GAAQ,EAAQ,CAAC,OAAO,OAAO,EAAM,CAAC,CACnE,EACF,EAAW,IAAI,aAAa,GAAQ,GAAO,MAClC,IAAI,KAAK,eAAe,GAAQ,EAAQ,CAAC,OAAO,IAAI,KAAK,EAAM,CAAC,CACvE,EACF,EAAW,IAAI,SAAS,GAAQ,GAAO,MAC9B,IAAI,KAAK,WAAW,GAAQ,EAAQ,CAAC,OAAO,EAAM,CACzD,EAEE,EAAQ,WACV,MAAK,IAAM,KAAO,EAAQ,WACxB,GAAW,IAAI,GAAK,EAAQ,WAAW,GAAK;CAIhD,IAAI,GAEE,CAAC,GAAe,KAAoB,EAAW,KAAK,EACpD,IAAmB,CAAC,GAAG,OAAO,KAAK,EAAQ,aAAa,CAAC;CAK/D,eAAe,EAAU,GAAe;EACtC,IAAI;AAEJ,MAAI,MAAS,KAAA,GAAW;GACtB,IAAI,IAAQ,EAAE;AAEd,OAAI,OAAO,YAAc,KAAa;IACpC,IAAM,IAAM;AAEZ,IAAI,EAAI,WAAW,SAAS,IAC1B,EAAM,KAAK,GAAG,EAAI,UAAU,GACnB,EAAI,WACb,EAAM,KAAK,EAAI,SAAS,GACf,EAAI,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7C,IAAO,EAAM,IACb,IAAqE,EAAE;AAG7E,QAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK;IACrC,IAAM,IAAY,EAAM,IAClB,IAAQ,EAAU,MAAM,iCAAiC;AAE/D,QAAI,GAAO;KACT,IAAM,IAAa,EAAM,IACnB,IAAa,EAAM,IACnB,IAAkC,EAAE;AAE1C,SAAI,GAAY;MACd,IAAM,IAAQ,EAAW,MAAM,IAAI;AACnC,WAAK,IAAI,IAAI,GAAG,IAAI,EAAM,QAAQ,KAAK;OACrC,IAAM,IAAO,EAAM,IACb,IAAa,EAAK,QAAQ,IAAI;AACpC,OAAI,IAAa,OACf,EAAQ,EAAK,MAAM,GAAG,EAAW,CAAC,MAAM,IAAI,EAAK,MAAM,IAAa,EAAE,CAAC,MAAM;;;AAInF,OAAc,KAAK;MAAE,MAAM;MAAY,SAAS;MAAS,CAAC;UAE1D,GAAc,KAAK;KAAE,MAAM;KAAW,SAAS,EAAE;KAAE,CAAC;;AAKxD,KAAS,MAAM,GAAS,GAAY,MAAW;IAG7C,IAAI,IAAQ,IAAU,EAAO,EAAQ,GAAM,GAAG,KAAA;AAE9C,SAAK,IAAI,IAAI,GAAG,IAAI,EAAc,QAAQ,KAAK;KAC7C,IAAM,IAAM,EAAc,IACpB,IAAc,EAAW,IAAI,EAAI,KAAK;AAC5C,KAAI,MACF,IAAQ,EAAY,GAAQ,GAAO,EAAI,QAAQ;;AAInD,WAAO,KAAS,OAAuB,KAAhB,OAAO,EAAM;KACpC;QAGF,GAAS,WAAW,EAAM;;AAI9B,QAAO"}
|
|
1
|
+
{"version":3,"file":"translate.js","names":[],"sources":["../src/translate/index.ts"],"sourcesContent":["import { Context } from \"../core/context.js\";\nimport { DollaPlugin } from \"../core/root.js\";\nimport { unwrap, compose, createAtom, type Getter } from \"../core/signals.js\";\nimport { isFunction } from \"../utils.js\";\n\n// ----- Types ----- //\n\n/**\n * A JSON object of translated strings. Values can be string templates or nested objects.\n */\nexport interface LocalizedStrings extends Record<string, string | LocalizedStrings> {}\n\n/**\n * A function that returns an object of localized strings.\n */\nexport type TranslationFetchFn = () => LocalizedStrings | Promise<LocalizedStrings>;\n\nexport type TOptions = {\n /**\n *\n */\n count?: Getter<number> | number;\n\n /**\n *\n */\n context?: Getter<string> | string;\n\n [value: string]: Getter<any> | any;\n};\n\nexport type LookupFn = (selector: string, options?: TOptions) => string;\n\nexport type Formatter = (locale: string, value: any, options: Record<string, any>) => string;\n\ntype BuiltInFormatters = {\n number: [number | bigint, Intl.NumberFormatOptions?];\n datetime: [Date, Intl.DateTimeFormatOptions?];\n list: [Iterable<string>, Intl.ListFormatOptions?];\n};\n\nexport interface Translator {\n /**\n * An array of locale names for all translations the app supports.\n */\n supportedLocales: string[];\n\n /**\n * A Readable containing the currently loaded locale.\n */\n currentLocale: Getter<string>;\n\n /**\n * Updates the locale, fetching any translation files as required.\n * Returns a promise that resolves when the new locale is applied.\n *\n * If `name` is undefined the library will try to match the browser language automatically.\n */\n setLocale(name?: string): Promise<void>;\n\n /**\n * Returns a Readable of the value at `key`.\n\n * @param selector - Key to the translated value.\n * @param options - A map of `{{placeholder}}` names and the values to replace them with.\n *\n * @example\n * const value = t(\"your.key.here\", { count: 5 });\n */\n t(selector: string, options?: TOptions): Getter<string>;\n\n format<K extends keyof BuiltInFormatters, V extends BuiltInFormatters[K][0], O extends BuiltInFormatters[K][1]>(\n name: K,\n value: Getter<V> | V,\n options?: O,\n ): Getter<string>;\n\n format<V, O>(name: string, value: Getter<V> | V, options?: O): Getter<string>;\n}\n\nexport interface TranslatorOptions {\n translations: Record<string, LocalizedStrings | TranslationFetchFn>;\n\n /**\n * Default locale to load on startup. The translator will try to match the user's browser language if left undefined.\n */\n locale?: string;\n\n formatters?: Record<string, Formatter>;\n}\n\nconst TRANSLATE = Symbol.for(\"$_DOLLA_TRANSLATE\");\n\nexport function createTranslate(options: TranslatorOptions): DollaPlugin {\n return async function (context) {\n const translator = createTranslator(options);\n context[TRANSLATE] = translator;\n await translator.setLocale(options.locale);\n };\n}\n\nexport function getTranslate(context: Context): Translator {\n if (!context[TRANSLATE]) throw new Error(\"Translate plugin isn't loaded.\");\n return context[TRANSLATE];\n}\n\n// ----- Code ----- //\n\nfunction createTranslator(options: TranslatorOptions): Translator {\n const formatters = new Map<string, Formatter>();\n\n formatters.set(\"number\", (locale, value, options) => {\n return new Intl.NumberFormat(locale, options).format(Number(value));\n });\n formatters.set(\"datetime\", (locale, value, options) => {\n return new Intl.DateTimeFormat(locale, options).format(new Date(value));\n });\n formatters.set(\"list\", (locale, value, options) => {\n return new Intl.ListFormat(locale, options).format(value);\n });\n\n if (options.formatters) {\n for (const key in options.formatters) {\n formatters.set(key, options.formatters[key]);\n }\n }\n\n let lookup: LookupFn | undefined;\n\n const [currentLocale, setCurrentLocale] = createAtom(\"en\");\n const supportedLocales = [...Object.keys(options.translations)];\n\n /**\n * Loads translation for the locale.\n */\n async function setLocale(name?: string) {\n let locale!: string;\n\n if (name === undefined) {\n let names = [];\n\n if (typeof navigator !== \"undefined\") {\n const nav = navigator as any;\n\n if (nav.languages?.length > 0) {\n names.push(...nav.languages);\n } else if (nav.language) {\n names.push(nav.language);\n } else if (nav.browserLanguage) {\n names.push(nav.browserLanguage);\n } else if (nav.userLanguage) {\n names.push(nav.userLanguage);\n }\n }\n\n for (const name of names) {\n if (name in options.translations) {\n // Found a matching language.\n locale = name;\n break;\n }\n }\n } else {\n // Tag is the actual tag to set.\n if (name in options.translations) {\n locale = name;\n }\n }\n\n if (locale == null) {\n const firstLanguage = Object.keys(options.translations).at(0);\n if (firstLanguage) {\n locale = firstLanguage;\n }\n }\n\n if (!locale || !(locale in options.translations)) {\n throw new Error(`Locale '${name}' has no translation.`);\n }\n\n lookup = await createLookup(locale, formatters, options.translations[locale]);\n\n // Update locale string after init so t() signals will update.\n setCurrentLocale(locale);\n }\n\n function t(selector: string, options?: TOptions): Getter<string> {\n return compose(() => {\n currentLocale(); // track locale\n return lookup?.(selector, options) ?? selector;\n });\n }\n\n function format<\n K extends keyof BuiltInFormatters,\n V extends BuiltInFormatters[K][0],\n O extends BuiltInFormatters[K][1],\n >(name: K, value: Getter<V> | V, options?: O): Getter<string>;\n\n function format<V, O>(name: string, value: Getter<V> | V, options?: O): Getter<string>;\n\n function format(name: string, value: unknown, options?: Record<string, any>): Getter<string> {\n const callback = formatters.get(name);\n if (!callback) {\n throw new Error(`Unknown format: ${name}`);\n }\n\n return compose(() => callback(currentLocale(), unwrap(value), options ?? {}));\n }\n\n return {\n supportedLocales,\n currentLocale,\n setLocale,\n t,\n format,\n };\n}\n\n/**\n * Loads the translation and produces an efficient lookup function.\n */\nasync function createLookup(\n locale: string,\n formatters: Map<string, Formatter>,\n translation: TranslationFetchFn | LocalizedStrings,\n) {\n const strings = isFunction(translation) ? await translation() : translation;\n const entries = compile(strings);\n const templates = new Map(entries);\n\n /**\n * Looks up the template and produces the output. Any reactive values in `options` are tracked when used.\n */\n return function lookup(selector: string, options?: TOptions): string {\n if (options) {\n // Handle count (pluralization) and context. Keys become \"key_context_pluralization\".\n if (options.context != null) {\n selector += \"_\" + options.context;\n }\n if (options.count != null) {\n if (options.ordinal) {\n // Try to match the exact number key if there is one (e.g. \"myExampleKey_ordinal_(=2)\" when count is 2).\n const exact = `${selector}_ordinal_(=${options.count})`;\n if (templates.has(exact)) {\n selector = exact;\n } else {\n selector += \"_ordinal_\" + new Intl.PluralRules(locale, { type: \"ordinal\" }).select(unwrap(options.count));\n }\n } else {\n // Try to match the exact number key if there is one (e.g. \"myExampleKey_(=2)\" when count is 2).\n const exact = `${selector}_(=${options.count})`;\n if (templates.has(exact)) {\n selector = exact;\n } else {\n selector += \"_\" + new Intl.PluralRules(locale).select(unwrap(options.count));\n }\n }\n }\n }\n\n const template = templates.get(selector);\n if (!template) return selector;\n\n let output = \"\";\n\n for (let i = 0; i < template.length; i++) {\n output += template[i](options, formatters, locale);\n }\n\n return output;\n };\n}\n\n/**\n * Compiles an object of translated strings into a set of function templates.\n */\nexport function compile(strings: { [key: string]: any }, path: string[] = []): [string, CompiledTemplate][] {\n const entries: [string, CompiledTemplate][] = [];\n\n for (const key in strings) {\n switch (typeof strings[key]) {\n case \"string\":\n entries.push([[...path, key].join(\".\"), parseTemplate(strings[key])]);\n break;\n case \"object\":\n entries.push(...compile(strings[key], [...path, key]));\n break;\n default:\n throw new Error(\n `Expected to find a string or object at ${[...path, key].join(\".\")}. Got: ${typeof strings[key]}`,\n );\n }\n }\n\n return entries;\n}\n\nexport type TemplateSegmentFn = (\n options: Record<string, any> | undefined,\n formatters: Map<string, Formatter>,\n locale: string,\n) => string;\n\nexport type CompiledTemplate = TemplateSegmentFn[];\n\n/**\n * Parse a string template into an array of functions that will produce each piece of the output when called.\n */\nexport function parseTemplate(template: string): CompiledTemplate {\n const tokens = template.split(/(\\{\\{.*?\\}\\})/g);\n const segments: TemplateSegmentFn[] = [];\n\n for (let i = 0; i < tokens.length; i++) {\n const token = tokens[i];\n if (!token) continue;\n\n if (token.startsWith(\"{{\") && token.endsWith(\"}}\")) {\n const inner = token.slice(2, -2).trim();\n const parts = inner.split(\"|\").map((p) => p.trim());\n\n const name = parts[0];\n const parsedFormats: { name: string; options: Record<string, string> }[] = [];\n\n // Parse formatters at build-time to prevent string splitting on every render\n for (let j = 1; j < parts.length; j++) {\n const formatStr = parts[j];\n const match = formatStr.match(/^([a-zA-Z0-9_]+)(?:\\((.*)\\))?$/);\n\n if (match) {\n const formatName = match[1];\n const optionsStr = match[2];\n const optsObj: Record<string, string> = {};\n\n if (optionsStr) {\n const pairs = optionsStr.split(\",\");\n for (let k = 0; k < pairs.length; k++) {\n const pair = pairs[k];\n const colonIndex = pair.indexOf(\":\");\n if (colonIndex > -1) {\n optsObj[pair.slice(0, colonIndex).trim()] = pair.slice(colonIndex + 1).trim();\n }\n }\n }\n parsedFormats.push({ name: formatName, options: optsObj });\n } else {\n parsedFormats.push({ name: formatStr, options: {} });\n }\n }\n\n // Push the dynamic closure\n segments.push((options, formatters, locale) => {\n // Evaluate and track the specific option at runtime.\n // This code runs in the t() computed context.\n let value = options ? unwrap(options[name]) : undefined;\n\n for (let k = 0; k < parsedFormats.length; k++) {\n const fmt = parsedFormats[k];\n const formatterFn = formatters.get(fmt.name);\n if (formatterFn) {\n value = formatterFn(locale, value, fmt.options);\n }\n }\n\n return value != null ? String(value) : \"\";\n });\n } else {\n // Push a static closure that just returns the token\n segments.push(() => token);\n }\n }\n\n return segments;\n}\n"],"mappings":";;AA2FA,IAAM,IAAY,OAAO,IAAI,oBAAoB;AAEjD,SAAgB,EAAgB,GAAyC;AACvE,QAAO,eAAgB,GAAS;EAC9B,IAAM,IAAa,EAAiB,EAAQ;AAE5C,EADA,EAAQ,KAAa,GACrB,MAAM,EAAW,UAAU,EAAQ,OAAO;;;AAI9C,SAAgB,EAAa,GAA8B;AACzD,KAAI,CAAC,EAAQ,GAAY,OAAU,MAAM,iCAAiC;AAC1E,QAAO,EAAQ;;AAKjB,SAAS,EAAiB,GAAwC;CAChE,IAAM,oBAAa,IAAI,KAAwB;AAY/C,KAVA,EAAW,IAAI,WAAW,GAAQ,GAAO,MAChC,IAAI,KAAK,aAAa,GAAQ,EAAQ,CAAC,OAAO,OAAO,EAAM,CAAC,CACnE,EACF,EAAW,IAAI,aAAa,GAAQ,GAAO,MAClC,IAAI,KAAK,eAAe,GAAQ,EAAQ,CAAC,OAAO,IAAI,KAAK,EAAM,CAAC,CACvE,EACF,EAAW,IAAI,SAAS,GAAQ,GAAO,MAC9B,IAAI,KAAK,WAAW,GAAQ,EAAQ,CAAC,OAAO,EAAM,CACzD,EAEE,EAAQ,WACV,MAAK,IAAM,KAAO,EAAQ,WACxB,GAAW,IAAI,GAAK,EAAQ,WAAW,GAAK;CAIhD,IAAI,GAEE,CAAC,GAAe,KAAoB,EAAW,KAAK,EACpD,IAAmB,CAAC,GAAG,OAAO,KAAK,EAAQ,aAAa,CAAC;CAK/D,eAAe,EAAU,GAAe;EACtC,IAAI;AAEJ,MAAI,MAAS,K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