@vertesia/ui 1.3.0-dev.20260620.061059Z → 1.3.0-dev.20260621.071017Z
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/lib/router/HistoryNavigator.d.ts.map +1 -1
- package/lib/router/HistoryNavigator.js +4 -1
- package/lib/router/HistoryNavigator.js.map +1 -1
- package/lib/router/Nav.d.ts.map +1 -1
- package/lib/router/Nav.js +7 -1
- package/lib/router/Nav.js.map +1 -1
- package/lib/router/Router.d.ts.map +1 -1
- package/lib/router/Router.js +9 -4
- package/lib/router/Router.js.map +1 -1
- package/lib/router/path.d.ts +15 -0
- package/lib/router/path.d.ts.map +1 -1
- package/lib/router/path.js +43 -0
- package/lib/router/path.js.map +1 -1
- package/lib/session/UserSession.d.ts.map +1 -1
- package/lib/session/UserSession.js +15 -7
- package/lib/session/UserSession.js.map +1 -1
- package/lib/session/auth/domainRouting.d.ts +10 -0
- package/lib/session/auth/domainRouting.d.ts.map +1 -1
- package/lib/session/auth/domainRouting.js +15 -0
- package/lib/session/auth/domainRouting.js.map +1 -1
- package/lib/vertesia-ui-router.js +1 -1
- package/lib/vertesia-ui-router.js.map +1 -1
- package/lib/vertesia-ui-session.js +1 -1
- package/lib/vertesia-ui-session.js.map +1 -1
- package/package.json +6 -6
- package/src/router/HistoryNavigator.ts +4 -1
- package/src/router/Nav.tsx +7 -1
- package/src/router/Router.tsx +9 -4
- package/src/router/path.test.ts +87 -0
- package/src/router/path.ts +38 -0
- package/src/session/UserSession.ts +15 -7
- package/src/session/auth/domainRouting.test.ts +28 -1
- package/src/session/auth/domainRouting.ts +16 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vertesia-ui-router.js","sources":["router/PathWithParams.js","router/path.js","router/HistoryNavigator.js","router/FixLinks.js","router/PathMatcher.js","router/Router.js","router/Nav.js","router/RouteComponent.js","router/NestedNavigationContext.js","router/Route404.js","router/NestedRouterProvider.js","router/RouterProvider.js"],"sourcesContent":["export class PathWithParams {\n path;\n params;\n hash;\n constructor(path) {\n let i = path.lastIndexOf('#');\n if (i > -1) {\n this.hash = path.substring(i);\n path = path.substring(0, i);\n }\n else {\n this.hash = '';\n }\n i = path.indexOf('?');\n if (i > -1) {\n this.path = path.substring(0, i);\n this.params = new URLSearchParams(path.substring(i + 1));\n }\n else {\n this.path = path;\n this.params = new URLSearchParams();\n }\n }\n add(params) {\n for (const [key, value] of Object.entries(params)) {\n this.params.set(key, value);\n }\n return this;\n }\n toString() {\n return `${this.path}?${this.params.toString()}${this.hash}`;\n }\n}\n//# sourceMappingURL=PathWithParams.js.map","export function isRootPath(path) {\n return path === '/' || path === '';\n}\nexport function joinPath(path1, path2) {\n if (path1.endsWith('/') && path2.startsWith('/')) {\n path2 = path1 + path2.substring(1);\n }\n else if (path1.endsWith('/')) {\n path2 = path1 + path2;\n }\n else if (path2.startsWith('/')) {\n path2 = path1 + path2;\n }\n else {\n path2 = `${path1}/${path2}`;\n }\n return path2;\n}\nexport function getPathSegments(path) {\n if (path === '') {\n return [];\n }\n if (path === '/') {\n return [''];\n }\n let s = 0, e = path.length;\n if (path.startsWith('./')) {\n s = 2;\n }\n else if (path.startsWith('/')) {\n s = 1;\n }\n if (path.endsWith('/')) {\n e = path.length - 1;\n }\n return (s > 0 || e < path.length ? path.substring(s, e) : path).split('/');\n}\nexport function toSegments(path) {\n if (typeof path === 'string') {\n return getPathSegments(path);\n }\n else if (Array.isArray(path)) {\n return path;\n }\n else {\n throw new Error(`Unsupported path object: ${path}`);\n }\n}\n// export class Path {\n// static parse(path: string, abs = false) {\n// if (abs !== undefined) {\n// abs = path.startsWith('/');\n// }\n// return new Path(getPathSegments(path), abs);\n// }\n// constructor(public segments: string[], public isAbsolute = false) {\n// }\n// getParameters() {\n// const out = [];\n// for (const segment of this.segments) {\n// if (segment[0] === ':') {\n// out.push(segment.substring(1));\n// }\n// }\n// if (this.segments[this.segments.length - 1] === '*') {\n// out.push('_');\n// }\n// return out;\n// }\n// resolveParameters(path: string) {\n// const params: PathMatchParams = {};\n// const resolvedSegments = getPathSegments(path);\n// if (resolvedSegments.length < this.segments.length) {\n// return null;\n// }\n// const segments = this.segments;\n// for (let i = 0, l = segments.length; i < l; i++) {\n// const seg = segments[i];\n// if (seg[0] === ':') {\n// params[seg.substring(1)] = resolvedSegments[i];\n// }\n// }\n// if (resolvedSegments.length - this.segments.length) {\n// params._ = resolvedSegments.slice(this.segments.length);\n// }\n// return params;\n// }\n// match(path: string | string[] | Path) {\n// const segments = toSegments(path);\n// if (segments.length < this.segments.length) {\n// return false;\n// }\n// let params: PathMatchParams | undefined;\n// const mySegments = this.segments;\n// for (let i = 0, l = mySegments.length; i < l; i++) {\n// const segment = mySegments[i];\n// if (segment === ':') {\n// if (!params) params = {};\n// params[segment.substring(1)] = segment;\n// } else if (segment !== segments[i]) {\n// if (i === l - 1 && segment === '*') {\n// if (!params) params = {};\n// params._ = segments.slice(i);\n// return params;\n// }\n// return false;\n// }\n// }\n// return params ? params : false;\n// }\n// join(path: Path | string | string[]) {\n// const segments = toSegments(path);\n// return new Path(this.segments.concat(segments), this.isAbsolute);\n// }\n// getRelativePath(path: Path | string | string[], asAbsolute: boolean = false) {\n// const segments = toSegments(path);\n// const extraSegmentsCount = segments.length - this.segments.length;\n// if (extraSegmentsCount <= 0) {\n// return null;\n// }\n// return new Path(segments.slice(this.segments.length), asAbsolute);\n// }\n// prependSegments(segments: string[]) {\n// this.segments = segments.concat(this.segments);\n// }\n// appendSegments(segments: string[]) {\n// this.segments = this.segments.concat(segments);\n// }\n// toAbsolutePath() {\n// return '/' + this.segments.join('/');\n// }\n// toRelativePath() {\n// return this.segments.join('/');\n// }\n// toString() {\n// const path = this.segments.join('/');\n// return this.isAbsolute ? '/' + path : path;\n// }\n// }\n//# sourceMappingURL=path.js.map","import { PathWithParams } from './PathWithParams';\nimport { joinPath } from './path';\nconst BASE_PATH = Symbol('BASE_PATH');\nexport { BASE_PATH };\nexport class LocationChangeEvent {\n name;\n type;\n location;\n state;\n _canceled = false;\n constructor(name, type, location, state) {\n this.name = name;\n this.type = type;\n this.location = location;\n this.state = state;\n }\n get isPageLoad() {\n return this.type === 'initial';\n }\n get isBackForward() {\n return this.type === 'popState';\n }\n get isLinkClick() {\n return this.type === 'linkClick';\n }\n get isNavigation() {\n return this.type === 'navigate';\n }\n get isCancelable() {\n return this.name === 'beforeChange';\n }\n cancel() {\n if (this.name === 'afterChange') {\n throw new Error('Cannot cancel afterChange event');\n }\n this._canceled = true;\n }\n}\nexport class BeforeLocationChangeEvent extends LocationChangeEvent {\n constructor(type, location, state) {\n super('beforeChange', type, location, state);\n }\n}\nexport class AfterLocationChangeEvent extends LocationChangeEvent {\n constructor(type, location, state) {\n super('afterChange', type, location, state);\n }\n}\nfunction getElementHrefAsUrl(elem) {\n if (elem && elem.tagName.toLowerCase() === 'a') {\n const href = elem?.href.trim();\n if (typeof href === 'string' && href.length > 0) {\n return new URL(href);\n }\n }\n return null;\n}\nexport class HistoryNavigator {\n // params to preserve in the query string when navigating\n stickyParams;\n _popStateListener;\n _linkNavListener;\n _listeners = [];\n addListener(listener) {\n this._listeners.push(listener);\n }\n fireLocationChange(event) {\n for (const listener of this._listeners) {\n listener(event);\n }\n }\n /**\n * Should be called when the page is first loaded.\n * It will fire a location change event with type `initial` and the current window.location as the location\n */\n firePageLoad() {\n this.fireLocationChange(new AfterLocationChangeEvent('initial', new URL(window.location.href)));\n }\n addStickyParams(path) {\n if (this.stickyParams) {\n return new PathWithParams(path).add(this.stickyParams).toString();\n }\n return path;\n }\n /**\n * Rewrite the current browser URL in place so that the sticky params are present, without\n * navigating. Used on load / when the params first become known so the address bar reflects\n * the active account/project before the first navigation.\n *\n * Idempotent and side-effect-light: only calls replaceState when the URL would actually\n * change, preserves the existing history state, and never fires a location-change event\n * (so there is no route re-match or component remount).\n */\n normalizeCurrentUrl() {\n if (typeof window === 'undefined' || !this.stickyParams) {\n return;\n }\n const current = window.location.pathname + window.location.search + window.location.hash;\n const normalized = this.addStickyParams(current);\n if (normalized !== current) {\n const to = new URL(normalized, window.location.href);\n window.history.replaceState(window.history.state, '', to.href);\n }\n }\n navigate(to, options = {}) {\n if (options.stepsBack && options.stepsBack > 0) {\n this.stepBack(options.stepsBack, options);\n return;\n }\n if (options.basePath) {\n let basePath = options.basePath;\n if (!basePath.startsWith('/')) {\n basePath = `/${basePath}`;\n }\n to = joinPath(basePath, to);\n }\n to = this.addStickyParams(to);\n this._navigate(new URL(to, window.location.href), 'navigate', options);\n }\n stepBack(steps, options = {}) {\n const historyChain = window.history.state.historyChain || [];\n const to = historyChain.length >= steps\n ? new URL(historyChain[historyChain.length - steps].href, window.location.href)\n : new URL(window.location.origin, window.location.href);\n this._navigate(to, 'popState', options);\n const stateToStore = {\n from: window.location.href,\n historyChain: historyChain.slice(0, -steps),\n data: options.state || undefined,\n title: options.title || document.title,\n };\n window.history.replaceState(stateToStore, '', to.href);\n this.fireLocationChange(new AfterLocationChangeEvent('popState', to, options.state));\n }\n _navigate(to, type, options) {\n const beforeEvent = new BeforeLocationChangeEvent(type, to, options.state);\n this.fireLocationChange(beforeEvent);\n if (beforeEvent._canceled) {\n return;\n }\n // Build navigation chain by preserving previous history\n const currentState = window.history.state;\n const currentTitle = options.title || document.title;\n // Create new history chain entry\n const newChainEntry = {\n title: currentTitle,\n href: window.location.pathname + window.location.search + window.location.hash,\n };\n // Build the history chain - clear if using replace\n let historyChain = [];\n if (!options.replace && currentState?.historyChain) {\n historyChain = [...currentState.historyChain];\n }\n // Only add to chain if not replacing\n if (!options.replace) {\n historyChain.push(newChainEntry);\n // Limit chain length to prevent memory issues (keep last 10 entries)\n if (historyChain.length > 10) {\n historyChain = historyChain.slice(-10);\n }\n }\n const stateToStore = {\n from: window.location.href,\n historyChain: historyChain,\n data: options.state || undefined,\n title: options.title || document.title,\n };\n window.history[options.replace ? 'replaceState' : 'pushState'](stateToStore, '', to.href);\n this.fireLocationChange(new AfterLocationChangeEvent(type, to, options.state));\n }\n start() {\n if (typeof window === 'undefined') {\n return;\n }\n const _popStateListener = (ev) => {\n let type;\n const to = new URL(window.location.href);\n let state;\n if (ev.state) {\n type = 'popState';\n state = ev.state.data;\n }\n else {\n type = 'linkClick';\n }\n this.fireLocationChange(new AfterLocationChangeEvent(type, to, state));\n };\n const _linkNavListener = (ev) => {\n const target = ev.target;\n // Skip anchors with download attribute or blob: URLs - they are file downloads, not navigation\n if (target.tagName.toLowerCase() === 'a' &&\n (target.hasAttribute('download') ||\n target.href?.startsWith('blob:'))) {\n return;\n }\n const url = getElementHrefAsUrl(target);\n if (url && url.origin === window.location.origin) {\n ev.preventDefault();\n const to = new URL(this.addStickyParams(url.href));\n const basePath = ev[BASE_PATH] ||\n ev.target[BASE_PATH];\n if (basePath) {\n to.pathname = joinPath(basePath, to.pathname);\n }\n this._navigate(to, 'linkClick', {});\n }\n };\n this._popStateListener = _popStateListener;\n this._linkNavListener = _linkNavListener;\n window.addEventListener('popstate', _popStateListener);\n document.body.addEventListener('click', this._linkNavListener);\n }\n stop() {\n if (this._popStateListener)\n window.removeEventListener('popstate', this._popStateListener);\n if (this._linkNavListener)\n document.body.removeEventListener('click', this._linkNavListener);\n }\n}\n//# sourceMappingURL=HistoryNavigator.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useEffect, useRef } from 'react';\nimport { BASE_PATH } from './HistoryNavigator';\nexport function FixLinks({ basePath, children }) {\n const ref = useRef(null);\n useEffect(() => {\n if (ref.current) {\n const divElem = ref.current;\n const listener = (ev) => {\n const elem = ev.target;\n if (elem.tagName.toLowerCase() === 'a') {\n ev[BASE_PATH] = basePath;\n }\n };\n divElem.addEventListener('click', listener);\n return () => {\n divElem.removeEventListener('click', listener);\n };\n }\n }, [basePath]);\n return (_jsx(\"div\", { ref: ref, className: \"h-full w-full\", children: children }));\n}\n//# sourceMappingURL=FixLinks.js.map","import { getPathSegments, toSegments } from './path';\n/**\n * Path matcher which support :param and *wildcard segments.\n * The wildcard segment is only supported as the last segment\n */\nexport class PathMatcher {\n tree = new RootSegmentNode();\n loadMapping(mapping) {\n for (const [key, value] of Object.entries(mapping)) {\n this.addSegments(getPathSegments(key), value);\n }\n }\n addPath(path, value) {\n this.addSegments(getPathSegments(path), value);\n }\n addSegments(segments, value) {\n let node = this.tree;\n for (let i = 0, l = segments.length; i < l; i++) {\n const segment = segments[i];\n if (segment[0] === ':') {\n let childNode = node.wildcard;\n if (!childNode) {\n childNode = new VariableSegmentNode(segment);\n node.wildcard = childNode;\n }\n else if (!(childNode instanceof VariableSegmentNode)) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard \":\" segment will overwrite an existing wildcard segment at path: ${`/${segments.slice(0, i).join('/')}`}`);\n }\n node = childNode;\n }\n else if (segment === '*') {\n if (node.wildcard) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard \"*\" segment already exists at path: ${`/${segments.slice(0, i).join('/')}`}`);\n }\n node.wildcard = new WildcardSegmentNode(segment, value);\n if (i < l - 1) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard segment must be the last segment`);\n }\n return;\n }\n else {\n let childNode = node.children[segment];\n if (!childNode) {\n childNode = new LiteralSegmentNode(segment);\n node.children[segment] = childNode;\n } // else // a literal segment already exists\n node = childNode;\n }\n }\n if (node.value !== undefined) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A value already exists at path: ${`/${segments.join('/')}`}`);\n }\n node.value = value;\n }\n match(path) {\n const segments = toSegments(path);\n if (segments.length === 0) {\n return null;\n }\n const params = {};\n let node = this.tree;\n for (const segment of segments) {\n const match = node.match(segment, params);\n if (match) {\n node = match;\n }\n else {\n return null;\n }\n }\n if (!node.value) {\n // not a leaf node (partial match)\n if (node instanceof ParentSegmentNode) {\n if (node.wildcard instanceof WildcardSegmentNode) {\n node = node.wildcard.match('', params);\n if (!node.value) {\n throw new Error('Wildcard segment node `*` must have a value');\n }\n }\n }\n if (!node.value)\n return null; // not a leaf node, neither a trailing wildcard (partial match)\n }\n let matchedSegments, remainingSegments;\n if (params._ && params._.length > 0) {\n matchedSegments = segments.slice(0, -params._.length);\n remainingSegments = params._;\n }\n else {\n matchedSegments = segments;\n }\n return { params, matchedSegments, remainingSegments, value: node.value };\n }\n}\nclass ParentSegmentNode {\n name;\n value;\n children = {};\n wildcard;\n constructor(name, value) {\n this.name = name;\n this.value = value;\n }\n match(segment, params) {\n const node = this.children[segment];\n if (node) {\n return node;\n }\n else if (this.wildcard) {\n if (this.wildcard instanceof WildcardSegmentNode) {\n return this.wildcard.match(segment, params);\n }\n else if (this.wildcard instanceof VariableSegmentNode) {\n params[this.wildcard.paramName] = segment;\n return this.wildcard;\n }\n else {\n throw new Error(`Unknown wildcard segment node type: ${this.wildcard.constructor.name}`);\n }\n }\n else {\n return null;\n }\n }\n}\nclass RootSegmentNode extends ParentSegmentNode {\n constructor() {\n super('#root');\n }\n}\nclass LiteralSegmentNode extends ParentSegmentNode {\n}\nclass VariableSegmentNode extends ParentSegmentNode {\n paramName;\n constructor(name, value) {\n super(name, value);\n this.paramName = name.substring(1);\n }\n}\nclass WildcardSegmentNode {\n name;\n value;\n constructor(name, value) {\n this.name = name;\n this.value = value;\n }\n match(segment, params) {\n if (!params._) {\n params._ = segment ? [segment] : [];\n }\n else {\n if (segment)\n params._.push(segment);\n }\n return this;\n }\n}\n//# sourceMappingURL=PathMatcher.js.map","import { createContext, useContext, useEffect } from 'react';\nimport { HistoryNavigator } from './HistoryNavigator';\nimport { PathMatcher } from './PathMatcher';\nimport { isRootPath, joinPath } from './path';\nexport class BaseRouter {\n // the path to use when navigating to the root of the router\n index;\n matcher = new PathMatcher();\n constructor(routes, index) {\n this.index = index;\n for (const route of routes) {\n this.matcher.addPath(route.path, route);\n }\n }\n match(path) {\n const useIndex = isRootPath(path) && this.index;\n // biome-ignore lint/style/noNonNullAssertion: intentional non-null assertion; TS can't prove narrowing here\n return this.matcher.match(useIndex ? this.index : path);\n }\n}\nexport class Router extends BaseRouter {\n prompt;\n observer;\n navigator = new HistoryNavigator();\n constructor(routes, updateState) {\n super(routes);\n this.navigator.addListener((event) => {\n if (event.isCancelable && this.prompt?.when) {\n if (!window.confirm(this.prompt.message))\n return;\n }\n if (this.observer) {\n this.observer(event);\n }\n // only process afterChange events\n if (event.name === 'afterChange') {\n const match = this.match(event.location.pathname);\n if (match?.value) {\n updateState({\n ...match,\n state: event.state,\n });\n }\n else {\n updateState(null);\n }\n }\n });\n }\n getTopRouter() {\n return this;\n }\n /**\n * Subsequent navigations will preserve the given params in the query string.\n * Use null to clear the sticky params.\n * @param params\n */\n setStickyParams(params) {\n this.navigator.stickyParams = params != null ? params : undefined;\n // Reflect the params in the current URL immediately, so the address bar is correct on\n // load (not only after the first navigation).\n this.navigator.normalizeCurrentUrl();\n }\n withObserver(observer) {\n this.observer = observer;\n return this;\n }\n start() {\n this.navigator.start();\n // initialize with the current location\n this.navigator.firePageLoad();\n }\n stop() {\n this.navigator.stop();\n }\n navigate(path, options) {\n this.navigator.navigate(path, options);\n }\n}\nexport class NestedRouter extends BaseRouter {\n parent;\n basePath;\n constructor(parent, basePath, routes) {\n super(routes);\n this.parent = parent;\n this.basePath = basePath;\n }\n getTopRouter() {\n if (this.parent instanceof Router) {\n return this.parent;\n }\n else {\n return this.parent.getTopRouter();\n }\n }\n navigate(path, options) {\n // base path is nested by default in a NestedRouter unless explicitly set to false by caller\n const isBasePathNested = options?.isBasePathNested ?? true;\n let basePath;\n if (isBasePathNested) {\n const childBasePath = options?.basePath;\n // e.g. \"/store\" + \"/objects/123\" => \"/store/objects/123\"\n basePath = childBasePath ? joinPath(this.basePath, childBasePath) : this.basePath;\n this.parent.navigate(path, {\n ...options,\n basePath,\n });\n }\n else {\n // isBasePathNested === false: navigate to an absolute path without adding this router's basePath\n // Pass through to parent without adding our basePath prefix\n this.parent.navigate(path, {\n ...options,\n basePath: options?.basePath,\n });\n }\n }\n}\nconst ReactRouterContext = createContext(undefined);\nexport { ReactRouterContext };\nexport function useRouterContext() {\n const ctx = useContext(ReactRouterContext);\n if (!ctx) {\n throw new Error('useRouter must be used within a RouterProvider');\n }\n return ctx;\n}\nexport function useNavigate() {\n const { navigate } = useRouterContext();\n return navigate;\n}\nexport function useRouterBasePath() {\n const { matchedRoutePath, router } = useRouterContext();\n return router instanceof NestedRouter ? router.basePath : matchedRoutePath;\n}\nexport function useParams(arg) {\n const { params } = useRouterContext();\n if (arg) {\n return params[arg];\n }\n else {\n return params;\n }\n}\nexport function useLocation() {\n const { location } = useRouterContext();\n return location;\n}\nexport function usePageTitle(title) {\n useEffect(() => {\n const prev = document.title;\n document.title = title;\n return () => {\n document.title = prev;\n };\n }, [title]);\n}\nexport function useNavigationPrompt(prompt) {\n const { router } = useRouterContext();\n const topRouter = router.getTopRouter();\n useEffect(() => {\n topRouter.prompt = prompt;\n return () => {\n topRouter.prompt = undefined;\n };\n }, [prompt, topRouter]);\n useEffect(() => {\n if (prompt.when) {\n const doBlock = prompt.when;\n const listener = (ev) => {\n if (doBlock) {\n ev.preventDefault();\n ev.returnValue = '';\n }\n };\n window.addEventListener('beforeunload', listener);\n return () => {\n window.removeEventListener('beforeunload', listener);\n };\n }\n }, [prompt.when]);\n}\n//# sourceMappingURL=Router.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useNavigate, useRouterContext } from './Router';\nexport function Nav({ children, to, onClick, replace = true }) {\n const navigate = useNavigate();\n const _onClick = (ev) => {\n const link = ev.target.closest('a');\n const rawHref = link?.getAttribute('href');\n const target = to ?? rawHref;\n if (link && target) {\n ev.stopPropagation();\n ev.preventDefault();\n navigate(target, { replace });\n onClick?.(ev);\n }\n };\n return (_jsx(\"span\", { onClick: _onClick, children: children }));\n}\nexport function NavLink({ children, href, className, target, topLevelNav, clearBreadcrumbs = false, replace, skipStickyParams, }) {\n const { router } = useRouterContext();\n // In-app route = not an external URL, `_blank` target, or bare hash. Relative paths count too —\n // they must be routed, else the global link listener re-applies the module base path (wrong URL).\n const isAnchorOrEmpty = !href || href.startsWith('#');\n const isExternal = /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//') || (!!target && target !== '_self');\n const isInternal = !isAnchorOrEmpty && !isExternal;\n const resolvedHref = !skipStickyParams && isInternal ? router.getTopRouter().navigator.addStickyParams(href) : href;\n const _onClick = (ev) => {\n if (ev.defaultPrevented || !isInternal) {\n return;\n }\n ev.stopPropagation();\n ev.preventDefault();\n const actualRouter = topLevelNav ? router.getTopRouter() : router;\n actualRouter.navigate(href, { replace: replace ?? clearBreadcrumbs });\n };\n return (_jsx(\"a\", { href: resolvedHref, className: className, target: target, onClick: _onClick, children: children }));\n}\n//# sourceMappingURL=Nav.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useEffect, useState } from 'react';\nimport { useRouterContext } from './Router';\nexport function RouteComponent({ spinner }) {\n const ctx = useRouterContext();\n const route = ctx.route;\n if (route.Component) {\n const Component = route.Component;\n return _jsx(Component, { ...ctx.params });\n }\n else if (route.LazyComponent) {\n return _jsx(LazyRouteComponent, { route: route, spinner: spinner });\n }\n else {\n throw new Error(`Invalid route for ${route.path}. Either Component or LazyCOmponent must be specified.`);\n }\n}\nfunction LazyRouteComponent({ route, spinner }) {\n const [Component, setComponent] = useState(null);\n useEffect(() => {\n void route.LazyComponent().then((module) => {\n if (!module.default) {\n throw new Error(`Lazy module for ${route.path} does not have a default export`);\n }\n // we need to wrap the component type in an arrow function\n // otherwise the setState function will execute the function as a state update function\n setComponent(() => module.default);\n });\n }, [route]);\n return Component ? _jsx(Component, {}) : spinner || null;\n}\n//# sourceMappingURL=RouteComponent.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { FixLinks } from './FixLinks';\nimport { joinPath } from './path';\nimport { RouteComponent } from './RouteComponent';\nimport { ReactRouterContext, useRouterContext } from './Router';\nexport function NestedNavigationContext({ basePath, fixLinks = false, children }) {\n const ctx = useRouterContext();\n const wrapWithFixLinks = fixLinks\n ? (elem) => _jsx(FixLinks, { basePath: ctx.matchedRoutePath, children: elem })\n : (elem) => elem;\n return (_jsx(ReactRouterContext.Provider, { value: {\n ...ctx,\n navigate: (to, options) => {\n if (options?.isBasePathNested === false) {\n // Navigate to an absolute path without adding this context's basePath\n return ctx.navigate(to, options);\n }\n const actualBasePath = options?.basePath ? joinPath(basePath, options.basePath) : basePath;\n return ctx.navigate(to, { ...options, basePath: actualBasePath });\n },\n }, children: wrapWithFixLinks(children ? children : _jsx(RouteComponent, {})) }));\n}\n//# sourceMappingURL=NestedNavigationContext.js.map","import { jsxs as _jsxs, jsx as _jsx } from \"react/jsx-runtime\";\nimport { useRouterContext } from './Router';\nexport function Route404Component() {\n const ctx = useRouterContext();\n return _jsxs(\"div\", { children: [\"Route not found for path \", ctx.matchedRoutePath] });\n}\nexport function createRoute404() {\n return {\n params: {},\n matchedSegments: [],\n state: null,\n value: {\n path: 'virtual:404',\n Component: () => _jsx(Route404Component, {}),\n },\n };\n}\n//# sourceMappingURL=Route404.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useMemo, useRef } from 'react';\nimport { FixLinks } from './FixLinks';\nimport { createRoute404 } from './Route404';\nimport { RouteComponent } from './RouteComponent';\nimport { NestedRouter, ReactRouterContext, useRouterContext } from './Router';\nexport function NestedRouterProvider({ routes, index, children, fixLinks = false }) {\n const ctx = useRouterContext();\n // Capture basePath once at mount. When the parent router switches to a different\n // top-level route (e.g. /store -> /studio), the lazy loader briefly keeps rendering\n // this (now-stale) module with a new ctx. Keeping basePath stable lets the\n // ctx.matchedRoutePath !== nestedRouter.basePath check below detect the mismatch and\n // skip rendering instead of running match() against the wrong route table.\n const basePathRef = useRef(ctx.matchedRoutePath);\n const nestedRouter = useMemo(() => {\n if (typeof window === 'undefined')\n return null;\n const nestedRouter = new NestedRouter(ctx.router, basePathRef.current, routes);\n nestedRouter.index = index;\n return nestedRouter;\n }, [ctx.router, index, routes]);\n const nestedRouteMatch = useMemo(() => {\n if (!nestedRouter) {\n return undefined;\n }\n if (ctx.matchedRoutePath !== nestedRouter.basePath) {\n // The change belongs to another router level and will be handled there.\n return undefined;\n }\n return nestedRouter.match(ctx.remainingPath || '/') || createRoute404();\n }, [ctx.matchedRoutePath, ctx.remainingPath, nestedRouter]);\n const wrapWithFixLinks = fixLinks\n ? (elem) => _jsx(FixLinks, { basePath: ctx.matchedRoutePath, children: elem })\n : (elem) => elem;\n return (nestedRouteMatch && (_jsx(ReactRouterContext.Provider, { value: {\n ...ctx,\n // biome-ignore lint/style/noNonNullAssertion: intentional non-null assertion; TS can't prove narrowing here\n router: nestedRouter,\n route: nestedRouteMatch.value,\n params: nestedRouteMatch.params,\n matchedRoutePath: `/${nestedRouteMatch.matchedSegments.join('/')}`,\n remainingPath: nestedRouteMatch.remainingSegments\n ? `/${nestedRouteMatch.remainingSegments.join('/')}`\n : undefined,\n navigate: (to, options) => {\n if (nestedRouter) {\n return nestedRouter.navigate(to, options);\n }\n },\n }, children: wrapWithFixLinks(children ? children : _jsx(RouteComponent, {})) })));\n}\n//# sourceMappingURL=NestedRouterProvider.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useSafeLayoutEffect } from '@vertesia/ui/core';\nimport { useMemo, useState } from 'react';\nimport { createRoute404 } from './Route404';\nimport { RouteComponent } from './RouteComponent';\nimport { ReactRouterContext, Router } from './Router';\nexport function RouterProvider({ routes, index, onChange, children }) {\n const [state, setState] = useState(undefined);\n const router = useMemo(() => {\n if (typeof window === 'undefined')\n return null;\n const router = new Router(routes, (match) => {\n if (match === null) {\n match = createRoute404();\n }\n setState({\n location: window.location,\n route: match.value,\n params: match.params,\n state: match.state,\n router: router,\n matchedRoutePath: `/${match.matchedSegments.join('/')}`,\n remainingPath: match.remainingSegments ? `/${match.remainingSegments.join('/')}` : undefined,\n navigate: (to, options) => {\n return router.navigate(to, options);\n },\n });\n }).withObserver(onChange);\n router.index = index;\n return router;\n }, [index, onChange, routes]);\n useSafeLayoutEffect(() => {\n router?.start();\n return () => {\n router?.stop();\n };\n }, [router]);\n return (state && (_jsx(ReactRouterContext.Provider, { value: state, children: children ? children : _jsx(RouteComponent, {}) })));\n}\n//# sourceMappingURL=RouterProvider.js.map"],"names":["PathWithParams","path","params","hash","constructor","i","lastIndexOf","this","substring","indexOf","URLSearchParams","add","key","value","Object","entries","set","toString","isRootPath","joinPath","path1","path2","endsWith","startsWith","getPathSegments","s","e","length","split","toSegments","Array","isArray","Error","BASE_PATH","Symbol","LocationChangeEvent","name","type","location","state","_canceled","isPageLoad","isBackForward","isLinkClick","isNavigation","isCancelable","cancel","BeforeLocationChangeEvent","super","AfterLocationChangeEvent","HistoryNavigator","stickyParams","_popStateListener","_linkNavListener","_listeners","addListener","listener","push","fireLocationChange","event","firePageLoad","URL","window","href","addStickyParams","normalizeCurrentUrl","current","pathname","search","normalized","to","history","replaceState","navigate","options","stepsBack","stepBack","basePath","_navigate","steps","historyChain","origin","stateToStore","from","slice","data","undefined","title","document","beforeEvent","currentState","newChainEntry","replace","start","ev","target","tagName","toLowerCase","hasAttribute","url","elem","trim","getElementHrefAsUrl","preventDefault","addEventListener","body","stop","removeEventListener","FixLinks","children","ref","useRef","useEffect","divElem","_jsx","className","PathMatcher","tree","RootSegmentNode","loadMapping","mapping","addSegments","addPath","segments","node","l","segment","childNode","wildcard","VariableSegmentNode","join","WildcardSegmentNode","LiteralSegmentNode","match","matchedSegments","remainingSegments","ParentSegmentNode","_","paramName","BaseRouter","index","matcher","routes","route","useIndex","Router","prompt","observer","navigator","updateState","when","confirm","message","getTopRouter","setStickyParams","withObserver","NestedRouter","parent","isBasePathNested","childBasePath","ReactRouterContext","createContext","useRouterContext","ctx","useContext","useNavigate","useRouterBasePath","matchedRoutePath","router","useParams","arg","useLocation","usePageTitle","prev","useNavigationPrompt","topRouter","doBlock","returnValue","Nav","onClick","link","closest","rawHref","getAttribute","stopPropagation","NavLink","topLevelNav","clearBreadcrumbs","skipStickyParams","isAnchorOrEmpty","isExternal","test","isInternal","resolvedHref","defaultPrevented","RouteComponent","spinner","Component","LazyComponent","LazyRouteComponent","setComponent","useState","then","module","default","NestedNavigationContext","fixLinks","wrapWithFixLinks","Provider","actualBasePath","Route404Component","_jsxs","createRoute404","NestedRouterProvider","basePathRef","nestedRouter","useMemo","nestedRouteMatch","remainingPath","RouterProvider","onChange","setState","useSafeLayoutEffect"],"mappings":"sNAAO,MAAMA,EACTC,KACAC,OACAC,KACA,WAAAC,CAAYH,GACR,IAAII,EAAIJ,EAAKK,YAAY,KACrBD,GAAI,GACJE,KAAKJ,KAAOF,EAAKO,UAAUH,GAC3BJ,EAAOA,EAAKO,UAAU,EAAGH,IAGzBE,KAAKJ,KAAO,GAEhBE,EAAIJ,EAAKQ,QAAQ,KACbJ,GAAI,GACJE,KAAKN,KAAOA,EAAKO,UAAU,EAAGH,GAC9BE,KAAKL,OAAS,IAAIQ,gBAAgBT,EAAKO,UAAUH,EAAI,MAGrDE,KAAKN,KAAOA,EACZM,KAAKL,OAAS,IAAIQ,gBAE1B,CACA,GAAAC,CAAIT,GACA,IAAK,MAAOU,EAAKC,KAAUC,OAAOC,QAAQb,GACtCK,KAAKL,OAAOc,IAAIJ,EAAKC,GAEzB,OAAON,IACX,CACA,QAAAU,GACI,MAAO,GAAGV,KAAKN,QAAQM,KAAKL,OAAOe,aAAaV,KAAKJ,MACzD,EC/BG,SAASe,EAAWjB,GACvB,MAAgB,MAATA,GAAyB,KAATA,CAC3B,CACO,SAASkB,EAASC,EAAOC,GAa5B,OAXIA,EADAD,EAAME,SAAS,MAAQD,EAAME,WAAW,KAChCH,EAAQC,EAAMb,UAAU,GAE3BY,EAAME,SAAS,MAGfD,EAAME,WAAW,KAFdH,EAAQC,EAMR,GAAGD,KAASC,GAG5B,CACO,SAASG,EAAgBvB,GAC5B,GAAa,KAATA,EACA,MAAO,GAEX,GAAa,MAATA,EACA,MAAO,CAAC,IAEZ,IAAIwB,EAAI,EAAGC,EAAIzB,EAAK0B,OAUpB,OATI1B,EAAKsB,WAAW,MAChBE,EAAI,EAECxB,EAAKsB,WAAW,OACrBE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b,CAAC8D,IACIjI,GAAU2E,EAAK8C,EAAmBgD,SAAU,CAAEnM,MAAO0B,EAAOsE,SAAUA,GAAsBK,EAAKiF,EAAgB,CAAA,IAC7H"}
|
|
1
|
+
{"version":3,"file":"vertesia-ui-router.js","sources":["router/PathWithParams.js","router/path.js","router/HistoryNavigator.js","router/FixLinks.js","router/PathMatcher.js","router/Router.js","router/Nav.js","router/RouteComponent.js","router/NestedNavigationContext.js","router/Route404.js","router/NestedRouterProvider.js","router/RouterProvider.js"],"sourcesContent":["export class PathWithParams {\n path;\n params;\n hash;\n constructor(path) {\n let i = path.lastIndexOf('#');\n if (i > -1) {\n this.hash = path.substring(i);\n path = path.substring(0, i);\n }\n else {\n this.hash = '';\n }\n i = path.indexOf('?');\n if (i > -1) {\n this.path = path.substring(0, i);\n this.params = new URLSearchParams(path.substring(i + 1));\n }\n else {\n this.path = path;\n this.params = new URLSearchParams();\n }\n }\n add(params) {\n for (const [key, value] of Object.entries(params)) {\n this.params.set(key, value);\n }\n return this;\n }\n toString() {\n return `${this.path}?${this.params.toString()}${this.hash}`;\n }\n}\n//# sourceMappingURL=PathWithParams.js.map","export function isRootPath(path) {\n return path === '/' || path === '';\n}\nexport function joinPath(path1, path2) {\n if (path1.endsWith('/') && path2.startsWith('/')) {\n path2 = path1 + path2.substring(1);\n }\n else if (path1.endsWith('/')) {\n path2 = path1 + path2;\n }\n else if (path2.startsWith('/')) {\n path2 = path1 + path2;\n }\n else {\n path2 = `${path1}/${path2}`;\n }\n return path2;\n}\n/**\n * The mount base path from an explicit `<base href>` element, or `''` when there is none.\n *\n * Apps served under a deep gateway mount carry `<base href=\"/tenants/.../app/\">`, injected at serve\n * time. The router otherwise resolves absolute routes against the origin, which collapses the URL\n * off the mount (and breaks in-app links). This returns the base pathname without a trailing slash\n * so {@link withMountBasename} can keep navigation under the mount and {@link stripMountBasename}\n * can match routes app-relative. The Studio UI has no `<base>` element, so this returns `''` and\n * every caller becomes a no-op there.\n */\nexport function getMountBasename() {\n if (typeof document === 'undefined')\n return '';\n const base = document.querySelector('base[href]');\n if (!base)\n return '';\n try {\n return new URL(base.href, document.URL).pathname.replace(/\\/+$/, '');\n }\n catch {\n return '';\n }\n}\n/** Prepend the mount basename to an absolute app path (no-op when no mount, path is relative, or already prefixed). */\nexport function withMountBasename(path) {\n const base = getMountBasename();\n if (!base || !path.startsWith('/'))\n return path;\n if (path === base || path.startsWith(`${base}/`))\n return path;\n return joinPath(base, path);\n}\n/** Strip the mount basename from a browser path so route patterns match app-relative (no-op when no mount). */\nexport function stripMountBasename(path) {\n const base = getMountBasename();\n if (!base)\n return path;\n if (path === base)\n return '/';\n if (path.startsWith(`${base}/`))\n return path.slice(base.length) || '/';\n return path;\n}\nexport function getPathSegments(path) {\n if (path === '') {\n return [];\n }\n if (path === '/') {\n return [''];\n }\n let s = 0, e = path.length;\n if (path.startsWith('./')) {\n s = 2;\n }\n else if (path.startsWith('/')) {\n s = 1;\n }\n if (path.endsWith('/')) {\n e = path.length - 1;\n }\n return (s > 0 || e < path.length ? path.substring(s, e) : path).split('/');\n}\nexport function toSegments(path) {\n if (typeof path === 'string') {\n return getPathSegments(path);\n }\n else if (Array.isArray(path)) {\n return path;\n }\n else {\n throw new Error(`Unsupported path object: ${path}`);\n }\n}\n// export class Path {\n// static parse(path: string, abs = false) {\n// if (abs !== undefined) {\n// abs = path.startsWith('/');\n// }\n// return new Path(getPathSegments(path), abs);\n// }\n// constructor(public segments: string[], public isAbsolute = false) {\n// }\n// getParameters() {\n// const out = [];\n// for (const segment of this.segments) {\n// if (segment[0] === ':') {\n// out.push(segment.substring(1));\n// }\n// }\n// if (this.segments[this.segments.length - 1] === '*') {\n// out.push('_');\n// }\n// return out;\n// }\n// resolveParameters(path: string) {\n// const params: PathMatchParams = {};\n// const resolvedSegments = getPathSegments(path);\n// if (resolvedSegments.length < this.segments.length) {\n// return null;\n// }\n// const segments = this.segments;\n// for (let i = 0, l = segments.length; i < l; i++) {\n// const seg = segments[i];\n// if (seg[0] === ':') {\n// params[seg.substring(1)] = resolvedSegments[i];\n// }\n// }\n// if (resolvedSegments.length - this.segments.length) {\n// params._ = resolvedSegments.slice(this.segments.length);\n// }\n// return params;\n// }\n// match(path: string | string[] | Path) {\n// const segments = toSegments(path);\n// if (segments.length < this.segments.length) {\n// return false;\n// }\n// let params: PathMatchParams | undefined;\n// const mySegments = this.segments;\n// for (let i = 0, l = mySegments.length; i < l; i++) {\n// const segment = mySegments[i];\n// if (segment === ':') {\n// if (!params) params = {};\n// params[segment.substring(1)] = segment;\n// } else if (segment !== segments[i]) {\n// if (i === l - 1 && segment === '*') {\n// if (!params) params = {};\n// params._ = segments.slice(i);\n// return params;\n// }\n// return false;\n// }\n// }\n// return params ? params : false;\n// }\n// join(path: Path | string | string[]) {\n// const segments = toSegments(path);\n// return new Path(this.segments.concat(segments), this.isAbsolute);\n// }\n// getRelativePath(path: Path | string | string[], asAbsolute: boolean = false) {\n// const segments = toSegments(path);\n// const extraSegmentsCount = segments.length - this.segments.length;\n// if (extraSegmentsCount <= 0) {\n// return null;\n// }\n// return new Path(segments.slice(this.segments.length), asAbsolute);\n// }\n// prependSegments(segments: string[]) {\n// this.segments = segments.concat(this.segments);\n// }\n// appendSegments(segments: string[]) {\n// this.segments = this.segments.concat(segments);\n// }\n// toAbsolutePath() {\n// return '/' + this.segments.join('/');\n// }\n// toRelativePath() {\n// return this.segments.join('/');\n// }\n// toString() {\n// const path = this.segments.join('/');\n// return this.isAbsolute ? '/' + path : path;\n// }\n// }\n//# sourceMappingURL=path.js.map","import { PathWithParams } from './PathWithParams';\nimport { joinPath, withMountBasename } from './path';\nconst BASE_PATH = Symbol('BASE_PATH');\nexport { BASE_PATH };\nexport class LocationChangeEvent {\n name;\n type;\n location;\n state;\n _canceled = false;\n constructor(name, type, location, state) {\n this.name = name;\n this.type = type;\n this.location = location;\n this.state = state;\n }\n get isPageLoad() {\n return this.type === 'initial';\n }\n get isBackForward() {\n return this.type === 'popState';\n }\n get isLinkClick() {\n return this.type === 'linkClick';\n }\n get isNavigation() {\n return this.type === 'navigate';\n }\n get isCancelable() {\n return this.name === 'beforeChange';\n }\n cancel() {\n if (this.name === 'afterChange') {\n throw new Error('Cannot cancel afterChange event');\n }\n this._canceled = true;\n }\n}\nexport class BeforeLocationChangeEvent extends LocationChangeEvent {\n constructor(type, location, state) {\n super('beforeChange', type, location, state);\n }\n}\nexport class AfterLocationChangeEvent extends LocationChangeEvent {\n constructor(type, location, state) {\n super('afterChange', type, location, state);\n }\n}\nfunction getElementHrefAsUrl(elem) {\n if (elem && elem.tagName.toLowerCase() === 'a') {\n const href = elem?.href.trim();\n if (typeof href === 'string' && href.length > 0) {\n return new URL(href);\n }\n }\n return null;\n}\nexport class HistoryNavigator {\n // params to preserve in the query string when navigating\n stickyParams;\n _popStateListener;\n _linkNavListener;\n _listeners = [];\n addListener(listener) {\n this._listeners.push(listener);\n }\n fireLocationChange(event) {\n for (const listener of this._listeners) {\n listener(event);\n }\n }\n /**\n * Should be called when the page is first loaded.\n * It will fire a location change event with type `initial` and the current window.location as the location\n */\n firePageLoad() {\n this.fireLocationChange(new AfterLocationChangeEvent('initial', new URL(window.location.href)));\n }\n addStickyParams(path) {\n if (this.stickyParams) {\n return new PathWithParams(path).add(this.stickyParams).toString();\n }\n return path;\n }\n /**\n * Rewrite the current browser URL in place so that the sticky params are present, without\n * navigating. Used on load / when the params first become known so the address bar reflects\n * the active account/project before the first navigation.\n *\n * Idempotent and side-effect-light: only calls replaceState when the URL would actually\n * change, preserves the existing history state, and never fires a location-change event\n * (so there is no route re-match or component remount).\n */\n normalizeCurrentUrl() {\n if (typeof window === 'undefined' || !this.stickyParams) {\n return;\n }\n const current = window.location.pathname + window.location.search + window.location.hash;\n const normalized = this.addStickyParams(current);\n if (normalized !== current) {\n const to = new URL(normalized, window.location.href);\n window.history.replaceState(window.history.state, '', to.href);\n }\n }\n navigate(to, options = {}) {\n if (options.stepsBack && options.stepsBack > 0) {\n this.stepBack(options.stepsBack, options);\n return;\n }\n if (options.basePath) {\n let basePath = options.basePath;\n if (!basePath.startsWith('/')) {\n basePath = `/${basePath}`;\n }\n to = joinPath(basePath, to);\n }\n to = this.addStickyParams(to);\n // Keep absolute app routes under the served `<base href>` mount instead of resolving them\n // against the bare origin (which collapses the URL off the mount). No-op when origin-served.\n to = withMountBasename(to);\n this._navigate(new URL(to, window.location.href), 'navigate', options);\n }\n stepBack(steps, options = {}) {\n const historyChain = window.history.state.historyChain || [];\n const to = historyChain.length >= steps\n ? new URL(historyChain[historyChain.length - steps].href, window.location.href)\n : new URL(window.location.origin, window.location.href);\n this._navigate(to, 'popState', options);\n const stateToStore = {\n from: window.location.href,\n historyChain: historyChain.slice(0, -steps),\n data: options.state || undefined,\n title: options.title || document.title,\n };\n window.history.replaceState(stateToStore, '', to.href);\n this.fireLocationChange(new AfterLocationChangeEvent('popState', to, options.state));\n }\n _navigate(to, type, options) {\n const beforeEvent = new BeforeLocationChangeEvent(type, to, options.state);\n this.fireLocationChange(beforeEvent);\n if (beforeEvent._canceled) {\n return;\n }\n // Build navigation chain by preserving previous history\n const currentState = window.history.state;\n const currentTitle = options.title || document.title;\n // Create new history chain entry\n const newChainEntry = {\n title: currentTitle,\n href: window.location.pathname + window.location.search + window.location.hash,\n };\n // Build the history chain - clear if using replace\n let historyChain = [];\n if (!options.replace && currentState?.historyChain) {\n historyChain = [...currentState.historyChain];\n }\n // Only add to chain if not replacing\n if (!options.replace) {\n historyChain.push(newChainEntry);\n // Limit chain length to prevent memory issues (keep last 10 entries)\n if (historyChain.length > 10) {\n historyChain = historyChain.slice(-10);\n }\n }\n const stateToStore = {\n from: window.location.href,\n historyChain: historyChain,\n data: options.state || undefined,\n title: options.title || document.title,\n };\n window.history[options.replace ? 'replaceState' : 'pushState'](stateToStore, '', to.href);\n this.fireLocationChange(new AfterLocationChangeEvent(type, to, options.state));\n }\n start() {\n if (typeof window === 'undefined') {\n return;\n }\n const _popStateListener = (ev) => {\n let type;\n const to = new URL(window.location.href);\n let state;\n if (ev.state) {\n type = 'popState';\n state = ev.state.data;\n }\n else {\n type = 'linkClick';\n }\n this.fireLocationChange(new AfterLocationChangeEvent(type, to, state));\n };\n const _linkNavListener = (ev) => {\n const target = ev.target;\n // Skip anchors with download attribute or blob: URLs - they are file downloads, not navigation\n if (target.tagName.toLowerCase() === 'a' &&\n (target.hasAttribute('download') ||\n target.href?.startsWith('blob:'))) {\n return;\n }\n const url = getElementHrefAsUrl(target);\n if (url && url.origin === window.location.origin) {\n ev.preventDefault();\n const to = new URL(this.addStickyParams(url.href));\n const basePath = ev[BASE_PATH] ||\n ev.target[BASE_PATH];\n if (basePath) {\n to.pathname = joinPath(basePath, to.pathname);\n }\n this._navigate(to, 'linkClick', {});\n }\n };\n this._popStateListener = _popStateListener;\n this._linkNavListener = _linkNavListener;\n window.addEventListener('popstate', _popStateListener);\n document.body.addEventListener('click', this._linkNavListener);\n }\n stop() {\n if (this._popStateListener)\n window.removeEventListener('popstate', this._popStateListener);\n if (this._linkNavListener)\n document.body.removeEventListener('click', this._linkNavListener);\n }\n}\n//# sourceMappingURL=HistoryNavigator.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useEffect, useRef } from 'react';\nimport { BASE_PATH } from './HistoryNavigator';\nexport function FixLinks({ basePath, children }) {\n const ref = useRef(null);\n useEffect(() => {\n if (ref.current) {\n const divElem = ref.current;\n const listener = (ev) => {\n const elem = ev.target;\n if (elem.tagName.toLowerCase() === 'a') {\n ev[BASE_PATH] = basePath;\n }\n };\n divElem.addEventListener('click', listener);\n return () => {\n divElem.removeEventListener('click', listener);\n };\n }\n }, [basePath]);\n return (_jsx(\"div\", { ref: ref, className: \"h-full w-full\", children: children }));\n}\n//# sourceMappingURL=FixLinks.js.map","import { getPathSegments, toSegments } from './path';\n/**\n * Path matcher which support :param and *wildcard segments.\n * The wildcard segment is only supported as the last segment\n */\nexport class PathMatcher {\n tree = new RootSegmentNode();\n loadMapping(mapping) {\n for (const [key, value] of Object.entries(mapping)) {\n this.addSegments(getPathSegments(key), value);\n }\n }\n addPath(path, value) {\n this.addSegments(getPathSegments(path), value);\n }\n addSegments(segments, value) {\n let node = this.tree;\n for (let i = 0, l = segments.length; i < l; i++) {\n const segment = segments[i];\n if (segment[0] === ':') {\n let childNode = node.wildcard;\n if (!childNode) {\n childNode = new VariableSegmentNode(segment);\n node.wildcard = childNode;\n }\n else if (!(childNode instanceof VariableSegmentNode)) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard \":\" segment will overwrite an existing wildcard segment at path: ${`/${segments.slice(0, i).join('/')}`}`);\n }\n node = childNode;\n }\n else if (segment === '*') {\n if (node.wildcard) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard \"*\" segment already exists at path: ${`/${segments.slice(0, i).join('/')}`}`);\n }\n node.wildcard = new WildcardSegmentNode(segment, value);\n if (i < l - 1) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A wildcard segment must be the last segment`);\n }\n return;\n }\n else {\n let childNode = node.children[segment];\n if (!childNode) {\n childNode = new LiteralSegmentNode(segment);\n node.children[segment] = childNode;\n } // else // a literal segment already exists\n node = childNode;\n }\n }\n if (node.value !== undefined) {\n throw new Error(`Failed to index path segments: ${segments.join('/')}. A value already exists at path: ${`/${segments.join('/')}`}`);\n }\n node.value = value;\n }\n match(path) {\n const segments = toSegments(path);\n if (segments.length === 0) {\n return null;\n }\n const params = {};\n let node = this.tree;\n for (const segment of segments) {\n const match = node.match(segment, params);\n if (match) {\n node = match;\n }\n else {\n return null;\n }\n }\n if (!node.value) {\n // not a leaf node (partial match)\n if (node instanceof ParentSegmentNode) {\n if (node.wildcard instanceof WildcardSegmentNode) {\n node = node.wildcard.match('', params);\n if (!node.value) {\n throw new Error('Wildcard segment node `*` must have a value');\n }\n }\n }\n if (!node.value)\n return null; // not a leaf node, neither a trailing wildcard (partial match)\n }\n let matchedSegments, remainingSegments;\n if (params._ && params._.length > 0) {\n matchedSegments = segments.slice(0, -params._.length);\n remainingSegments = params._;\n }\n else {\n matchedSegments = segments;\n }\n return { params, matchedSegments, remainingSegments, value: node.value };\n }\n}\nclass ParentSegmentNode {\n name;\n value;\n children = {};\n wildcard;\n constructor(name, value) {\n this.name = name;\n this.value = value;\n }\n match(segment, params) {\n const node = this.children[segment];\n if (node) {\n return node;\n }\n else if (this.wildcard) {\n if (this.wildcard instanceof WildcardSegmentNode) {\n return this.wildcard.match(segment, params);\n }\n else if (this.wildcard instanceof VariableSegmentNode) {\n params[this.wildcard.paramName] = segment;\n return this.wildcard;\n }\n else {\n throw new Error(`Unknown wildcard segment node type: ${this.wildcard.constructor.name}`);\n }\n }\n else {\n return null;\n }\n }\n}\nclass RootSegmentNode extends ParentSegmentNode {\n constructor() {\n super('#root');\n }\n}\nclass LiteralSegmentNode extends ParentSegmentNode {\n}\nclass VariableSegmentNode extends ParentSegmentNode {\n paramName;\n constructor(name, value) {\n super(name, value);\n this.paramName = name.substring(1);\n }\n}\nclass WildcardSegmentNode {\n name;\n value;\n constructor(name, value) {\n this.name = name;\n this.value = value;\n }\n match(segment, params) {\n if (!params._) {\n params._ = segment ? [segment] : [];\n }\n else {\n if (segment)\n params._.push(segment);\n }\n return this;\n }\n}\n//# sourceMappingURL=PathMatcher.js.map","import { createContext, useContext, useEffect } from 'react';\nimport { HistoryNavigator } from './HistoryNavigator';\nimport { PathMatcher } from './PathMatcher';\nimport { getMountBasename, isRootPath, joinPath, stripMountBasename } from './path';\nexport class BaseRouter {\n // the path to use when navigating to the root of the router\n index;\n matcher = new PathMatcher();\n constructor(routes, index) {\n this.index = index;\n for (const route of routes) {\n this.matcher.addPath(route.path, route);\n }\n }\n match(path) {\n const useIndex = isRootPath(path) && this.index;\n // biome-ignore lint/style/noNonNullAssertion: intentional non-null assertion; TS can't prove narrowing here\n return this.matcher.match(useIndex ? this.index : path);\n }\n}\nexport class Router extends BaseRouter {\n prompt;\n observer;\n navigator = new HistoryNavigator();\n constructor(routes, updateState) {\n super(routes);\n this.navigator.addListener((event) => {\n if (event.isCancelable && this.prompt?.when) {\n if (!window.confirm(this.prompt.message))\n return;\n }\n if (this.observer) {\n this.observer(event);\n }\n // only process afterChange events\n if (event.name === 'afterChange') {\n // Match app-relative: strip the served `<base href>` mount prefix (no-op when origin-served).\n const match = this.match(stripMountBasename(event.location.pathname));\n if (match?.value) {\n updateState({\n ...match,\n state: event.state,\n });\n }\n else {\n updateState(null);\n }\n }\n });\n }\n getTopRouter() {\n return this;\n }\n /**\n * Subsequent navigations will preserve the given params in the query string.\n * Use null to clear the sticky params.\n * @param params\n */\n setStickyParams(params) {\n this.navigator.stickyParams = params != null ? params : undefined;\n // Reflect the params in the current URL immediately, so the address bar is correct on\n // load (not only after the first navigation).\n this.navigator.normalizeCurrentUrl();\n }\n withObserver(observer) {\n this.observer = observer;\n return this;\n }\n start() {\n this.navigator.start();\n // initialize with the current location\n this.navigator.firePageLoad();\n }\n stop() {\n this.navigator.stop();\n }\n navigate(path, options) {\n this.navigator.navigate(path, options);\n }\n}\nexport class NestedRouter extends BaseRouter {\n parent;\n basePath;\n constructor(parent, basePath, routes) {\n super(routes);\n this.parent = parent;\n this.basePath = basePath;\n }\n getTopRouter() {\n if (this.parent instanceof Router) {\n return this.parent;\n }\n else {\n return this.parent.getTopRouter();\n }\n }\n navigate(path, options) {\n // base path is nested by default in a NestedRouter unless explicitly set to false by caller\n const isBasePathNested = options?.isBasePathNested ?? true;\n let basePath;\n if (isBasePathNested) {\n const childBasePath = options?.basePath;\n // e.g. \"/store\" + \"/objects/123\" => \"/store/objects/123\"\n basePath = childBasePath ? joinPath(this.basePath, childBasePath) : this.basePath;\n this.parent.navigate(path, {\n ...options,\n basePath,\n });\n }\n else {\n // isBasePathNested === false: navigate to an absolute path without adding this router's basePath\n // Pass through to parent without adding our basePath prefix\n this.parent.navigate(path, {\n ...options,\n basePath: options?.basePath,\n });\n }\n }\n}\nconst ReactRouterContext = createContext(undefined);\nexport { ReactRouterContext };\nexport function useRouterContext() {\n const ctx = useContext(ReactRouterContext);\n if (!ctx) {\n throw new Error('useRouter must be used within a RouterProvider');\n }\n return ctx;\n}\nexport function useNavigate() {\n const { navigate } = useRouterContext();\n return navigate;\n}\nexport function useRouterBasePath() {\n const { router } = useRouterContext();\n // For a nested router the base is its mount segment within the parent. For a top-level router the\n // base is the served `<base href>` mount prefix (empty for the origin-served Studio UI) — NOT the\n // matched route, so apps can build mount-correct sibling links (e.g. `${base}/assistant`) and\n // compare them against the full `useLocation().pathname`, which carries the mount.\n return router instanceof NestedRouter ? router.basePath : getMountBasename();\n}\nexport function useParams(arg) {\n const { params } = useRouterContext();\n if (arg) {\n return params[arg];\n }\n else {\n return params;\n }\n}\nexport function useLocation() {\n const { location } = useRouterContext();\n return location;\n}\nexport function usePageTitle(title) {\n useEffect(() => {\n const prev = document.title;\n document.title = title;\n return () => {\n document.title = prev;\n };\n }, [title]);\n}\nexport function useNavigationPrompt(prompt) {\n const { router } = useRouterContext();\n const topRouter = router.getTopRouter();\n useEffect(() => {\n topRouter.prompt = prompt;\n return () => {\n topRouter.prompt = undefined;\n };\n }, [prompt, topRouter]);\n useEffect(() => {\n if (prompt.when) {\n const doBlock = prompt.when;\n const listener = (ev) => {\n if (doBlock) {\n ev.preventDefault();\n ev.returnValue = '';\n }\n };\n window.addEventListener('beforeunload', listener);\n return () => {\n window.removeEventListener('beforeunload', listener);\n };\n }\n }, [prompt.when]);\n}\n//# sourceMappingURL=Router.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { withMountBasename } from './path';\nimport { useNavigate, useRouterContext } from './Router';\nexport function Nav({ children, to, onClick, replace = true }) {\n const navigate = useNavigate();\n const _onClick = (ev) => {\n const link = ev.target.closest('a');\n const rawHref = link?.getAttribute('href');\n const target = to ?? rawHref;\n if (link && target) {\n ev.stopPropagation();\n ev.preventDefault();\n navigate(target, { replace });\n onClick?.(ev);\n }\n };\n return (_jsx(\"span\", { onClick: _onClick, children: children }));\n}\nexport function NavLink({ children, href, className, target, topLevelNav, clearBreadcrumbs = false, replace, skipStickyParams, }) {\n const { router } = useRouterContext();\n // In-app route = not an external URL, `_blank` target, or bare hash. Relative paths count too —\n // they must be routed, else the global link listener re-applies the module base path (wrong URL).\n const isAnchorOrEmpty = !href || href.startsWith('#');\n const isExternal = /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//') || (!!target && target !== '_self');\n const isInternal = !isAnchorOrEmpty && !isExternal;\n // Keep the rendered href under the served `<base href>` mount (correct middle-click / hover /\n // open-in-new-tab); the onClick navigates via the router which applies the same rule. No-op when\n // origin-served (Studio UI). Click handler below passes the raw `href` — navigate() re-bases it.\n const resolvedHref = isInternal\n ? withMountBasename(!skipStickyParams ? router.getTopRouter().navigator.addStickyParams(href) : href)\n : href;\n const _onClick = (ev) => {\n if (ev.defaultPrevented || !isInternal) {\n return;\n }\n ev.stopPropagation();\n ev.preventDefault();\n const actualRouter = topLevelNav ? router.getTopRouter() : router;\n actualRouter.navigate(href, { replace: replace ?? clearBreadcrumbs });\n };\n return (_jsx(\"a\", { href: resolvedHref, className: className, target: target, onClick: _onClick, children: children }));\n}\n//# sourceMappingURL=Nav.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useEffect, useState } from 'react';\nimport { useRouterContext } from './Router';\nexport function RouteComponent({ spinner }) {\n const ctx = useRouterContext();\n const route = ctx.route;\n if (route.Component) {\n const Component = route.Component;\n return _jsx(Component, { ...ctx.params });\n }\n else if (route.LazyComponent) {\n return _jsx(LazyRouteComponent, { route: route, spinner: spinner });\n }\n else {\n throw new Error(`Invalid route for ${route.path}. Either Component or LazyCOmponent must be specified.`);\n }\n}\nfunction LazyRouteComponent({ route, spinner }) {\n const [Component, setComponent] = useState(null);\n useEffect(() => {\n void route.LazyComponent().then((module) => {\n if (!module.default) {\n throw new Error(`Lazy module for ${route.path} does not have a default export`);\n }\n // we need to wrap the component type in an arrow function\n // otherwise the setState function will execute the function as a state update function\n setComponent(() => module.default);\n });\n }, [route]);\n return Component ? _jsx(Component, {}) : spinner || null;\n}\n//# sourceMappingURL=RouteComponent.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { FixLinks } from './FixLinks';\nimport { joinPath } from './path';\nimport { RouteComponent } from './RouteComponent';\nimport { ReactRouterContext, useRouterContext } from './Router';\nexport function NestedNavigationContext({ basePath, fixLinks = false, children }) {\n const ctx = useRouterContext();\n const wrapWithFixLinks = fixLinks\n ? (elem) => _jsx(FixLinks, { basePath: ctx.matchedRoutePath, children: elem })\n : (elem) => elem;\n return (_jsx(ReactRouterContext.Provider, { value: {\n ...ctx,\n navigate: (to, options) => {\n if (options?.isBasePathNested === false) {\n // Navigate to an absolute path without adding this context's basePath\n return ctx.navigate(to, options);\n }\n const actualBasePath = options?.basePath ? joinPath(basePath, options.basePath) : basePath;\n return ctx.navigate(to, { ...options, basePath: actualBasePath });\n },\n }, children: wrapWithFixLinks(children ? children : _jsx(RouteComponent, {})) }));\n}\n//# sourceMappingURL=NestedNavigationContext.js.map","import { jsxs as _jsxs, jsx as _jsx } from \"react/jsx-runtime\";\nimport { useRouterContext } from './Router';\nexport function Route404Component() {\n const ctx = useRouterContext();\n return _jsxs(\"div\", { children: [\"Route not found for path \", ctx.matchedRoutePath] });\n}\nexport function createRoute404() {\n return {\n params: {},\n matchedSegments: [],\n state: null,\n value: {\n path: 'virtual:404',\n Component: () => _jsx(Route404Component, {}),\n },\n };\n}\n//# sourceMappingURL=Route404.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useMemo, useRef } from 'react';\nimport { FixLinks } from './FixLinks';\nimport { createRoute404 } from './Route404';\nimport { RouteComponent } from './RouteComponent';\nimport { NestedRouter, ReactRouterContext, useRouterContext } from './Router';\nexport function NestedRouterProvider({ routes, index, children, fixLinks = false }) {\n const ctx = useRouterContext();\n // Capture basePath once at mount. When the parent router switches to a different\n // top-level route (e.g. /store -> /studio), the lazy loader briefly keeps rendering\n // this (now-stale) module with a new ctx. Keeping basePath stable lets the\n // ctx.matchedRoutePath !== nestedRouter.basePath check below detect the mismatch and\n // skip rendering instead of running match() against the wrong route table.\n const basePathRef = useRef(ctx.matchedRoutePath);\n const nestedRouter = useMemo(() => {\n if (typeof window === 'undefined')\n return null;\n const nestedRouter = new NestedRouter(ctx.router, basePathRef.current, routes);\n nestedRouter.index = index;\n return nestedRouter;\n }, [ctx.router, index, routes]);\n const nestedRouteMatch = useMemo(() => {\n if (!nestedRouter) {\n return undefined;\n }\n if (ctx.matchedRoutePath !== nestedRouter.basePath) {\n // The change belongs to another router level and will be handled there.\n return undefined;\n }\n return nestedRouter.match(ctx.remainingPath || '/') || createRoute404();\n }, [ctx.matchedRoutePath, ctx.remainingPath, nestedRouter]);\n const wrapWithFixLinks = fixLinks\n ? (elem) => _jsx(FixLinks, { basePath: ctx.matchedRoutePath, children: elem })\n : (elem) => elem;\n return (nestedRouteMatch && (_jsx(ReactRouterContext.Provider, { value: {\n ...ctx,\n // biome-ignore lint/style/noNonNullAssertion: intentional non-null assertion; TS can't prove narrowing here\n router: nestedRouter,\n route: nestedRouteMatch.value,\n params: nestedRouteMatch.params,\n matchedRoutePath: `/${nestedRouteMatch.matchedSegments.join('/')}`,\n remainingPath: nestedRouteMatch.remainingSegments\n ? `/${nestedRouteMatch.remainingSegments.join('/')}`\n : undefined,\n navigate: (to, options) => {\n if (nestedRouter) {\n return nestedRouter.navigate(to, options);\n }\n },\n }, children: wrapWithFixLinks(children ? children : _jsx(RouteComponent, {})) })));\n}\n//# sourceMappingURL=NestedRouterProvider.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\nimport { useSafeLayoutEffect } from '@vertesia/ui/core';\nimport { useMemo, useState } from 'react';\nimport { createRoute404 } from './Route404';\nimport { RouteComponent } from './RouteComponent';\nimport { ReactRouterContext, Router } from './Router';\nexport function RouterProvider({ routes, index, onChange, children }) {\n const [state, setState] = useState(undefined);\n const router = useMemo(() => {\n if (typeof window === 'undefined')\n return null;\n const router = new Router(routes, (match) => {\n if (match === null) {\n match = createRoute404();\n }\n setState({\n location: window.location,\n route: match.value,\n params: match.params,\n state: match.state,\n router: router,\n matchedRoutePath: `/${match.matchedSegments.join('/')}`,\n remainingPath: match.remainingSegments ? `/${match.remainingSegments.join('/')}` : undefined,\n navigate: (to, options) => {\n return router.navigate(to, options);\n },\n });\n }).withObserver(onChange);\n router.index = index;\n return router;\n }, [index, onChange, routes]);\n useSafeLayoutEffect(() => {\n router?.start();\n return () => {\n router?.stop();\n };\n }, [router]);\n return (state && (_jsx(ReactRouterContext.Provider, { value: state, children: children ? children : _jsx(RouteComponent, {}) })));\n}\n//# sourceMappingURL=RouterProvider.js.map"],"names":["PathWithParams","path","params","hash","constructor","i","lastIndexOf","this","substring","indexOf","URLSearchParams","add","key","value","Object","entries","set","toString","isRootPath","joinPath","path1","path2","endsWith","startsWith","getMountBasename","document","base","querySelector","URL","href","pathname","replace","withMountBasename","stripMountBasename","slice","length","getPathSegments","s","e","split","toSegments","Array","isArray","Error","BASE_PATH","Symbol","LocationChangeEvent","name","type","location","state","_canceled","isPageLoad","isBackForward","isLinkClick","isNavigation","isCancelable","cancel","BeforeLocationChangeEvent","super","AfterLocationChangeEvent","HistoryNavigator","stickyParams","_popStateListener","_linkNavListener","_listeners","addListener","listener","push","fireLocationChange","event","firePageLoad","window","addStickyParams","normalizeCurrentUrl","current","search","normalized","to","history","replaceState","navigate","options","stepsBack","stepBack","basePath","_navigate","steps","historyChain","origin","stateToStore","from","data","undefined","title","beforeEvent","currentState","newChainEntry","start","ev","target","tagName","toLowerCase","hasAttribute","url","elem","trim","getElementHrefAsUrl","preventDefault","addEventListener","body","stop","removeEventListener","FixLinks","children","ref","useRef","useEffect","divElem","_jsx","className","PathMatcher","tree","RootSegmentNode","loadMapping","mapping","addSegments","addPath","segments","node","l","segment","childNode","wildcard","VariableSegmentNode","join","WildcardSegmentNode","LiteralSegmentNode","match","matchedSegments","remainingSegments","ParentSegmentNode","_","paramName","BaseRouter","index","matcher","routes","route","useIndex","Router","prompt","observer","navigator","updateState","when","confirm","message","getTopRouter","setStickyParams","withObserver","NestedRouter","parent","isBasePathNested","childBasePath","ReactRouterContext","createContext","useRouterContext","ctx","useContext","useNavigate","useRouterBasePath","router","useParams","arg","useLocation","usePageTitle","prev","useNavigationPrompt","topRouter","doBlock","returnValue","Nav","onClick","link","closest","rawHref","getAttribute","stopPropagation","NavLink","topLevelNav","clearBreadcrumbs","skipStickyParams","isAnchorOrEmpty","isExternal","test","isInternal","resolvedHref","defaultPrevented","RouteComponent","spinner","Component","LazyComponent","LazyRouteComponent","setComponent","useState","then","module","default","NestedNavigationContext","fixLinks","wrapWithFixLinks","matchedRoutePath","Provider","actualBasePath","Route404Component","_jsxs","createRoute404","NestedRouterProvider","basePathRef","nestedRouter","useMemo","nestedRouteMatch","remainingPath","RouterProvider","onChange","setState","useSafeLayoutEffect"],"mappings":"sNAAO,MAAMA,EACTC,KACAC,OACAC,KACA,WAAAC,CAAYH,GACR,IAAII,EAAIJ,EAAKK,YAAY,KACrBD,GAAI,GACJE,KAAKJ,KAAOF,EAAKO,UAAUH,GAC3BJ,EAAOA,EAAKO,UAAU,EAAGH,IAGzBE,KAAKJ,KAAO,GAEhBE,EAAIJ,EAAKQ,QAAQ,KACbJ,GAAI,GACJE,KAAKN,KAAOA,EAAKO,UAAU,EAAGH,GAC9BE,KAAKL,OAAS,IAAIQ,gBAAgBT,EAAKO,UAAUH,EAAI,MAGrDE,KAAKN,KAAOA,EACZM,KAAKL,OAAS,IAAIQ,gBAE1B,CACA,GAAAC,CAAIT,GACA,IAAK,MAAOU,EAAKC,KAAUC,OAAOC,QAAQb,GACtCK,KAAKL,OAAOc,IAAIJ,EAAKC,GAEzB,OAAON,IACX,CACA,QAAAU,GACI,MAAO,GAAGV,KAAKN,QAAQM,KAAKL,OAAOe,aAAaV,KAAKJ,MACzD,EC/BG,SAASe,EAAWjB,GACvB,MAAgB,MAATA,GAAyB,KAATA,CAC3B,CACO,SAASkB,EAASC,EAAOC,GAa5B,OAXIA,EADAD,EAAME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analytics";import{initializeApp as r}from"firebase/app";import{getAuth as i,onAuthStateChanged as a}from"firebase/auth";import{useCallback as s,createContext as c,useContext as l,useState as u,useEffect as d,useRef as h}from"react";import{i18nInstance as g,NAMESPACE as f}from"@vertesia/ui/i18n";import{VertesiaClient as m}from"@vertesia/client";import{jsx as p}from"react/jsx-runtime";const w="composableai.lastSelectedAccountId",v="composableai.lastSelectedProjectId";let k,S,T=null,b=null,_=null;function y(){if(!T)try{if(!e.firebase)throw new Error("Firebase configuration is not available in the environment");T=r(e.firebase)}catch(e){throw console.error("Failed to initialize Firebase app:",e),new Error("Firebase initialization failed - environment may not be properly initialized",{cause:e})}return T}function j(){return b||(b=o(y())),b}function I(){return _||(_=i(y())),_}async function $(t){if(t)if(e.firebase)try{t&&console.log(`Resolving tenant ID from email: ${t}`);let o=3,n=250;for(;o>0;)try{const o=await fetch("/api/resolve-tenant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenantEmail:t}),signal:AbortSignal.timeout(5e3)});if(!o)throw new Error("No response received from tenant API");if(!o.ok){try{const e=await o.json();console.error("Failed to resolve tenant ID:",e.error)}catch{console.error(`Failed to resolve tenant ID: HTTP ${o.status}`)}if(404===o.status)return void console.warn(`Tenant not found for ${t}`);throw new Error(`HTTP error ${o.status}`)}const n=await o.json();if(n?.firebaseTenantId){const t=I();return t.tenantId=n.firebaseTenantId,e.firebase.providerType=n.provider??"oidc",console.log(`Tenant ID set to ${t.tenantId}`),n}return void console.error(`Invalid response format, missing tenantId for ${t}`)}catch(e){if(!(o>1))throw e;console.warn(`Tenant resolution failed, retrying in ${n}ms...`,e),await new Promise(e=>setTimeout(e,n)),n*=2,o--}}catch(e){console.error("Error setting Firebase tenant:",e instanceof Error?e.message:"Unknown error")}else console.log("Firebase configuration is not available in the environment");else console.log("No tenant name or email specified, skipping tenant setup")}async function E(t){const o=I().currentUser;return o?o.getIdToken(t).then(n=>(e.logger.info("Got Firebase token",{vertesia:{user_email:o.email,user_name:o.displayName,user_id:o.uid,refresh:t}}),n)).catch(n=>(e.logger.error("Failed to get Firebase token",{vertesia:{user_email:o.email,user_name:o.displayName,user_id:o.uid,refresh:t,error:n}}),console.error("Failed to get access token",n),null)):(e.logger.warn("No user found"),Promise.resolve(null))}function A(e){return e?.replace(/\/+$/,"")}function U(e){return t(e)}async function F(o,n,r,i,a=0){console.log(`Getting/refreshing composable token for account ${n} and project ${r} `),e.logger.info("Getting/refreshing composable token",{vertesia:{account_id:n,project_id:r,retry_count:a}});const s=await o();if(!s)throw console.log("No id token found - using cookie auth"),new Error("No id token found");const c=e.endpoints.sts;console.log("Using STS for token generation:",c),e.logger.info("Using STS for token generation",{vertesia:{account_id:n,project_id:r,sts_url:c}});try{const l=new URL(`${c}/token/issue`),u={type:"user",account_id:n,project_id:r,expires_at:i?Math.floor(Date.now()/1e3)+i:void 0},d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)}).catch(t=>{throw console.error("Failed to call STS endpoint",t),e.logger.error("Failed to call STS endpoint",{vertesia:{account_id:n,project_id:r,error:t}}),new O("Failed to call STS endpoint",c)});if(s&&404===d?.status){console.log("404: User not found - calling ensure-user endpoint"),e.logger.info("404: User not found - calling ensure-user endpoint",{vertesia:{account_id:n,project_id:r,status:d?.status}});const c=await fetch(`${e.endpoints.studio}/auth/ensure-user`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}});if(412===c.status){console.log("412: No invite found - signup required"),e.logger.info("412: No invite found - signup required",{vertesia:{account_id:n,project_id:r}});const o=t(s);if(!o?.email)throw e.logger.error("No email found in id token"),new Error("No email found in id token");throw new x("User not found - signup required",o.email)}if(403===c.status)throw e.logger.warn("403: Customer-domain user requires an invite to join",{vertesia:{account_id:n,project_id:r}}),new Error("Customer-domain user requires an invite to join");if(!c.ok)throw console.error("Failed to ensure user exists",c.status),e.logger.error("Failed to ensure user exists",{vertesia:{account_id:n,project_id:r,status:c.status}}),new Error("Failed to ensure user exists");return console.log("User ensured - retrying token generation"),e.logger.info("User ensured - retrying token generation",{vertesia:{account_id:n,project_id:r}}),F(o,n,r,i,a)}if(s&&412===d?.status){console.log("412: auth succeeded but user doesn't exist - signup required",d?.status),e.logger.error("412: auth succeeded but user doesn't exist - signup required",{vertesia:{account_id:n,project_id:r,status:d?.status}});const o=t(s);if(!o?.email)throw e.logger.error("No email found in id token"),new Error("No email found in id token");throw e.logger.error("User not found",{vertesia:{account_id:n,project_id:r,email:o.email}}),new x("User not found",o.email)}if(403===d.status){if(a>0)throw console.error("403: Access denied even without account scope - user may have no accounts"),e.logger.error("403: Access denied after retry - authorization failure",{vertesia:{account_id:n,project_id:r,status:d.status,retry_count:a}}),new Error("Access denied - user may not have access to any accounts");return console.log("403: Access denied - clearing cached account and retrying without account scope"),e.logger.warn("403: Access denied - clearing cached account and retrying",{vertesia:{account_id:n,project_id:r,status:d.status,retry_count:a}}),localStorage.removeItem(w),n&&localStorage.removeItem(`${v}-${n}`),F(o,void 0,void 0,i,a+1)}if(!d.ok){const t=await d.text();throw console.error("STS token generation failed:",d.status,t),e.logger.error("STS token generation failed",{vertesia:{status:d.status,error:t,account_id:n,project_id:r}}),new Error(`Failed to get token from STS: ${d.status}`)}const{token:h}=await d.json();return console.log("Successfully got token from STS"),e.logger.info("Successfully got token from STS"),h}catch(t){if(t instanceof x||t instanceof O)throw t;throw localStorage.removeItem(w),n&&localStorage.removeItem(`${v}-${n}`),console.error("Failed to get composable token from STS",t),e.logger.error("Failed to get composable token from STS",{vertesia:{account_id:n,project_id:r,error:t}}),new Error("Failed to get composable token",{cause:t})}}async function P(e,t,o){return F(E,e,t,o)}async function L(e,t,o,n){return F(()=>Promise.resolve(e),t,o,n)}function C(){return k}async function N(t,o,n,r=!1,i=!1){const a=t??localStorage.getItem(w)??void 0,s=o??localStorage.getItem(`${v}-${a}`)??void 0,c=e.isLocalDev?e.devAuthToken:void 0,l=c??n??k;if(!r&&k&&S&&S.exp>Date.now()/1e3+300)return{rawToken:k,token:S,error:!1};if(!r&&function(t){if(!t)return!1;try{return A(U(t).iss)===A(e.endpoints.sts)}catch{return!1}}(l)){if(k=l,S=U(k),!S.exp)throw new Error("Invalid composable token");return{rawToken:k,token:S,error:!1}}if(c||i||!I().currentUser?c||!n&&!k?c&&(k=c):k=await F(()=>Promise.resolve(n??k),a,s):k=await P(a,s),!k)throw e.logger.error("Cannot acquire a composable token",{vertesia:{account_id:a,project_id:s}}),new Error("Cannot acquire a composable token");if(S=U(k),!S?.exp||!k)throw console.error("Invalid composable token",S),e.logger.error("Invalid composable token",{vertesia:{account_id:a,project_id:s}}),new Error("Invalid composable token");return{rawToken:k,token:S,error:!1}}class x extends Error{email;constructor(e,t){super(e),this.name="UserNotFoundError",this.email=t}}class O extends Error{stsURL;constructor(e,t){super(e),this.name="STSError",this.stsURL=t}}const D="auth_state",R="auth_state_expiry";function z(){return{generateState:s(()=>{const e=crypto.randomUUID(),t=Date.now()+3e5;return sessionStorage.setItem(D,e),sessionStorage.setItem(R,t.toString()),e},[]),verifyState:s(e=>{if(!e)return"Missing state";const t=sessionStorage.getItem(D),o=parseInt(sessionStorage.getItem(R)||"0",10);let n;return n=t!==e?`State mismatched (${t} !== ${e})`:Date.now()>o?"State expired":void 0,n},[]),clearState:s(()=>{sessionStorage.removeItem(D),sessionStorage.removeItem(R)},[])}}function q(e){return!("firebase"===window.AUTH_MODE)}function H(){const e=new URL(document.baseURI),t=new URL(window.location.href),o=t.pathname.startsWith(e.pathname)?t:e;return o.hash="",o}class B{isLoading=!0;client;authError;authToken;setSession;lastSelectedAccount;lastSelectedProject;onboardingComplete;constructor(t,o){this.client=t||new m({serverUrl:e.endpoints.studio,storeUrl:e.endpoints.zeno,tokenServerUrl:e.endpoints.sts}),o&&(this.setSession=o),this.logout=this.logout.bind(this)}get store(){return this.client.store}get user(){return this.authToken}get account(){return this.authToken?.account}get project(){return this.authToken?.project}get accounts(){return this.authToken?.accounts}get authCallback(){return this.rawAuthToken.then(e=>`Bearer ${e}`)}get rawAuthToken(){return N().then(e=>{const o=e?.rawToken;if(!o)throw new Error("No token available");return this.authToken=t(o),o})}async refreshAuthToken(){const e=await N(void 0,void 0,void 0,!0),o=e?.rawToken;if(!o)throw new Error("No token available");return this.authToken=t(o),this.setSession?.(this.clone()),this.authToken}signOut(){this.logout()}getAccount(){return this.authToken?.account}async login(o,n={}){return this.authError=void 0,this.isLoading=!1,this.client.withAuthCallback(()=>this.authCallback),this.authToken=t(o),console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`),localStorage.setItem(w,this.authToken.account.id),localStorage.setItem(`${v}-${this.authToken.account.id}`,this.authToken.project?.id??""),e.onLogin?.(this.authToken),(n.loadOnboardingStatus??1)&&await this.fetchOnboardingStatus(),Promise.resolve()}isLoggedIn(){return!!this.authToken}logout(){if(console.log("Logging out"),q()){console.log("Using central auth logout"),this.authError=void 0,this.isLoading=!1,this.authToken=void 0,this.setSession=void 0,this.client.withAuthCallback(void 0);const e=new URL("https://internal-auth.vertesia.app/"),t=H();e.pathname="/logout",e.searchParams.set("redirect_uri",t.toString()),location.replace(e.toString())}else{console.log("Using Firebase logout");const e=!!this.authToken;this.authToken&&I().signOut(),this.authError=void 0,this.isLoading=!1,this.authToken=void 0,this.setSession=void 0,this.client.withAuthCallback(void 0),e&&location.replace("/")}}async switchAccount(e){localStorage.setItem(w,e),this&&(this.account&&this.project?localStorage.setItem(`${v}-${this.account.id}`,this.project.id):this.account&&localStorage.removeItem(`${v}-${this.account.id}`)),window.location.replace(`/?a=${e}`)}async switchProject(e){this.account&&localStorage.setItem(`${v}-${this.account.id}`,e),window.location.replace(`/?a=${this.account?.id}&p=${e}`)}async fetchAccounts(){return this.client.accounts.list().then(e=>{if(!this.authToken)throw new Error("No token available");this.authToken.accounts=e,this.setSession?.(this.clone())}).catch(e=>{throw console.error("Failed to fetch accounts",e),e})}async fetchProjects(e){return this.client.projects.list([e]).then(t=>{if(!this.authToken)throw new Error("No token available");this.authToken={...this.authToken,accounts:this.authToken.accounts?.map(o=>o.id===e?{...o,projects:t.filter(t=>t.account===e)}:o)},this.setSession?.(this.clone())}).catch(e=>{throw console.error("Failed to fetch projects",e),e})}async fetchOnboardingStatus(){if(this.onboardingComplete)return console.log("Onboarding already completed"),!1;const e=this.onboardingComplete;try{const t=await this.client.account.onboardingProgress();if(this.onboardingComplete=Object.values(t).every(e=>!0===e),e!==this.onboardingComplete)return!0;this.setSession?.(this.clone())}catch(e){console.error("Error fetching onboarding status:",e),this.onboardingComplete=!1,this.setSession?.(this.clone())}return!1}clone(){const e=new B(this.client);return e.isLoading=this.isLoading,e.authError=this.authError,e.authToken=this.authToken,e.setSession=this.setSession,e.lastSelectedAccount=this.lastSelectedAccount,e.switchAccount=this.switchAccount,e.onboardingComplete=this.onboardingComplete,e}}const G=c(void 0);function J(){const e=l(G);if(!e)throw new Error("useUserSession must be used within a UserSessionProvider");return e}function M(){const{user:e}=J(),[t,o]=u(null),[n,r]=u(!0),[i,a]=u(null);return d(()=>{(async()=>{if(!e?.email)return o(null),void r(!1);try{const t=await fetch("/api/resolve-tenant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenantEmail:e.email})});if(t.ok){const e=await t.json();o(e?{tenantKey:e.name||"unknown",name:e.label||e.name||"Unknown",domain:e.domain||[],firebaseTenantId:e.firebaseTenantId,provider:e.provider,logo:e.logo}:null)}else o(null)}catch(e){console.error("Error loading current tenant:",e),a(g.getFixedT(null,f)("errors.failedToLoadTenantConfig")),o(null)}finally{r(!1)}})()},[e?.email]),{currentTenant:t,isLoading:n,error:i}}function K({children:t,loadOnboardingStatus:o=!0}){const n=new URLSearchParams(location.hash.substring(1)),r=n.get("token"),i=n.get("state"),[s,c]=u(new B),{generateState:l,verifyState:g,clearState:f}=z(),m=h(!1),k=h(void 0),S=(t,o)=>{const n=new URL(`https://internal-auth.vertesia.app/?sts=${e.endpoints.sts??"https://sts.vertesia.io"}`),r=H();n.searchParams.set("redirect_uri",r.toString()),n.searchParams.set("state",l()),location.replace(n.toString())};return k.current=()=>{if(m.current)return void console.log("Auth: skipping duplicate auth flow initiation");m.current=!0,console.log("Auth: starting auth flow"),e.logger.info("Starting auth flow");const t=new URL(window.location.href),n=t.searchParams.get("a")??localStorage.getItem(w)??void 0,l=t.searchParams.get("p")??localStorage.getItem(`${v}-${n}`)??void 0;if(console.log("Auth: selected account",n),console.log("Auth: selected project",l),e.logger.info("Selected account and project",{vertesia:{account_id:n,project_id:l}}),e.isLocalDev&&e.devAuthToken)return s.setSession=c,void N(n,l,e.devAuthToken).then(e=>{s.login(e.rawToken).then(()=>c(s.clone()))}).catch(t=>{console.error("Failed to initialize dev auth token",t),e.logger.error("Failed to initialize dev auth token",{vertesia:{account_id:n,project_id:l,error:t}}),s.isLoading=!1,s.authError=t instanceof Error?t:new Error(String(t)),c(s.clone())});if(r&&i){s.setSession=c;const t=g(i);return t?(console.error(`Auth: invalid state: ${t}`),e.logger.error(`Invalid state: ${t}`,{vertesia:{state:i}}),S()):f(),void N(n,l,r,!1,q()).then(e=>{s.login(e.rawToken,{loadOnboardingStatus:o}).then(()=>{c(s.clone()),window.location.hash=""})}).catch(t=>t instanceof x?(console.log("User not found - will trigger signup flow",t),s.isLoading=!1,s.authError=t,void c(s.clone())):t instanceof O?(console.error("STS error during token exchange",t),e.logger.error("STS error during token exchange",{vertesia:{account_id:n,project_id:l,sts_url:t.stsURL,error:t}}),window.alert("Authentication failed due to an issue with the authentication service. Please try again later."),s.logout(),c(s.clone()),void(window.location.hash="")):(console.error("Failed to fetch user token from studio, redirecting to central auth",t),e.logger.error("Failed to fetch user token from studio, redirecting to central auth",{vertesia:{error:t}}),void S()))}let u,d=!1;const h=()=>{if(!d){if(!s.isLoggedIn()){if(console.log("Auth: not logged in & no token/state"),e.logger.info("Not logged in & no token/state",{vertesia:{account_id:n,project_id:l}}),q())return console.log("Auth: host is not in Firebase auth allowlist, redirecting to central auth with selection",n,l),e.logger.info("Redirecting to central auth with selection",{vertesia:{account_id:n,project_id:l}}),void S();console.log("Auth: host is in Firebase auth allowlist"),e.logger.info("Host is in Firebase auth allowlist",{vertesia:{account_id:n,project_id:l}})}u=a(I(),async t=>{t?(console.log("Auth: successful login with firebase"),e.logger.info("Successful login with firebase",{vertesia:{account_id:n,project_id:l}}),s.setSession=c,await N(n,l,void 0,!1,q()).then(e=>{s.login(e.rawToken,{loadOnboardingStatus:o}).then(()=>c(s.clone()))}).catch(t=>{console.error("Failed to fetch user token from studio",t),e.logger.error("Failed to fetch user token from studio",{vertesia:{account_id:n,project_id:l,error:t}}),t instanceof x||s.logout(),s.isLoading=!1,s.authError=t,c(s.clone())})):(console.log("Auth: using anonymous user"),e.logger.info("Using anonymous user",{vertesia:{account_id:n,project_id:l}}),s.client.withAuthCallback(void 0),s.logout(),c(s.clone()))})}};return e.authTokenProvider?(s.setSession=c,e.authTokenProvider().then(async e=>{if(!e)return void h();const t=await N(n,l,e,!1,q());await s.login(t.rawToken,{loadOnboardingStatus:o}),d||c(s.clone())}).catch(t=>{console.warn("Auth: failed to initialize injected auth token",t),e.logger.warn("Failed to initialize injected auth token",{vertesia:{account_id:n,project_id:l,error:t}}),h()}),()=>{d=!0,u?.()}):(h(),()=>{d=!0,u?.()})},d(()=>k.current?.(),[]),p(G.Provider,{value:s,children:t})}function W(){return{tagUserSession:async e=>{const t=window.localStorage.getItem("composableSignupData");e?t&&window.localStorage.removeItem("composableSignupData"):console.error("No user found -- skipping tagging")},trackEvent:(t,o)=>{e.isProd||console.debug("track event",t,o),n(j(),t,{...o,debug_mode:!e.isProd})}}}export{w as LastSelectedAccountId_KEY,v as LastSelectedProjectId_KEY,O as STSError,x as UserNotFoundError,B as UserSession,G as UserSessionContext,K as UserSessionProvider,F as fetchComposableToken,P as fetchComposableTokenFromFirebaseToken,L as fetchComposableTokenFromVertesiaToken,N as getComposableToken,C as getCurrentVertesiaToken,j as getFirebaseAnalytics,y as getFirebaseApp,I as getFirebaseAuth,E as getFirebaseAuthToken,$ as setFirebaseTenant,z as useAuthState,M as useCurrentTenant,W as useUXTracking,J as useUserSession};
|
|
1
|
+
import{Env as e}from"@vertesia/ui/env";import{jwtDecode as t}from"jwt-decode";import{getAnalytics as o,logEvent as n}from"firebase/analytics";import{initializeApp as r}from"firebase/app";import{getAuth as i,onAuthStateChanged as a}from"firebase/auth";import{useCallback as s,createContext as c,useContext as l,useState as u,useEffect as d,useRef as h}from"react";import{i18nInstance as g,NAMESPACE as f}from"@vertesia/ui/i18n";import{VertesiaClient as m}from"@vertesia/client";import{jsx as p}from"react/jsx-runtime";const w="composableai.lastSelectedAccountId",v="composableai.lastSelectedProjectId";let k,S,T=null,b=null,_=null;function y(){if(!T)try{if(!e.firebase)throw new Error("Firebase configuration is not available in the environment");T=r(e.firebase)}catch(e){throw console.error("Failed to initialize Firebase app:",e),new Error("Firebase initialization failed - environment may not be properly initialized",{cause:e})}return T}function j(){return b||(b=o(y())),b}function I(){return _||(_=i(y())),_}async function E(t){if(t)if(e.firebase)try{t&&console.log(`Resolving tenant ID from email: ${t}`);let o=3,n=250;for(;o>0;)try{const o=await fetch("/api/resolve-tenant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenantEmail:t}),signal:AbortSignal.timeout(5e3)});if(!o)throw new Error("No response received from tenant API");if(!o.ok){try{const e=await o.json();console.error("Failed to resolve tenant ID:",e.error)}catch{console.error(`Failed to resolve tenant ID: HTTP ${o.status}`)}if(404===o.status)return void console.warn(`Tenant not found for ${t}`);throw new Error(`HTTP error ${o.status}`)}const n=await o.json();if(n?.firebaseTenantId){const t=I();return t.tenantId=n.firebaseTenantId,e.firebase.providerType=n.provider??"oidc",console.log(`Tenant ID set to ${t.tenantId}`),n}return void console.error(`Invalid response format, missing tenantId for ${t}`)}catch(e){if(!(o>1))throw e;console.warn(`Tenant resolution failed, retrying in ${n}ms...`,e),await new Promise(e=>setTimeout(e,n)),n*=2,o--}}catch(e){console.error("Error setting Firebase tenant:",e instanceof Error?e.message:"Unknown error")}else console.log("Firebase configuration is not available in the environment");else console.log("No tenant name or email specified, skipping tenant setup")}async function $(t){const o=I().currentUser;return o?o.getIdToken(t).then(n=>(e.logger.info("Got Firebase token",{vertesia:{user_email:o.email,user_name:o.displayName,user_id:o.uid,refresh:t}}),n)).catch(n=>(e.logger.error("Failed to get Firebase token",{vertesia:{user_email:o.email,user_name:o.displayName,user_id:o.uid,refresh:t,error:n}}),console.error("Failed to get access token",n),null)):(e.logger.warn("No user found"),Promise.resolve(null))}function A(e){return e?.replace(/\/+$/,"")}function U(e){return t(e)}async function F(o,n,r,i,a=0){console.log(`Getting/refreshing composable token for account ${n} and project ${r} `),e.logger.info("Getting/refreshing composable token",{vertesia:{account_id:n,project_id:r,retry_count:a}});const s=await o();if(!s)throw console.log("No id token found - using cookie auth"),new Error("No id token found");const c=e.endpoints.sts;console.log("Using STS for token generation:",c),e.logger.info("Using STS for token generation",{vertesia:{account_id:n,project_id:r,sts_url:c}});try{const l=new URL(`${c}/token/issue`),u={type:"user",account_id:n,project_id:r,expires_at:i?Math.floor(Date.now()/1e3)+i:void 0},d=await fetch(l,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`},body:JSON.stringify(u)}).catch(t=>{throw console.error("Failed to call STS endpoint",t),e.logger.error("Failed to call STS endpoint",{vertesia:{account_id:n,project_id:r,error:t}}),new O("Failed to call STS endpoint",c)});if(s&&404===d?.status){console.log("404: User not found - calling ensure-user endpoint"),e.logger.info("404: User not found - calling ensure-user endpoint",{vertesia:{account_id:n,project_id:r,status:d?.status}});const c=await fetch(`${e.endpoints.studio}/auth/ensure-user`,{method:"POST",headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json"}});if(412===c.status){console.log("412: No invite found - signup required"),e.logger.info("412: No invite found - signup required",{vertesia:{account_id:n,project_id:r}});const o=t(s);if(!o?.email)throw e.logger.error("No email found in id token"),new Error("No email found in id token");throw new x("User not found - signup required",o.email)}if(403===c.status)throw e.logger.warn("403: Customer-domain user requires an invite to join",{vertesia:{account_id:n,project_id:r}}),new Error("Customer-domain user requires an invite to join");if(!c.ok)throw console.error("Failed to ensure user exists",c.status),e.logger.error("Failed to ensure user exists",{vertesia:{account_id:n,project_id:r,status:c.status}}),new Error("Failed to ensure user exists");return console.log("User ensured - retrying token generation"),e.logger.info("User ensured - retrying token generation",{vertesia:{account_id:n,project_id:r}}),F(o,n,r,i,a)}if(s&&412===d?.status){console.log("412: auth succeeded but user doesn't exist - signup required",d?.status),e.logger.error("412: auth succeeded but user doesn't exist - signup required",{vertesia:{account_id:n,project_id:r,status:d?.status}});const o=t(s);if(!o?.email)throw e.logger.error("No email found in id token"),new Error("No email found in id token");throw e.logger.error("User not found",{vertesia:{account_id:n,project_id:r,email:o.email}}),new x("User not found",o.email)}if(403===d.status){if(a>0)throw console.error("403: Access denied even without account scope - user may have no accounts"),e.logger.error("403: Access denied after retry - authorization failure",{vertesia:{account_id:n,project_id:r,status:d.status,retry_count:a}}),new Error("Access denied - user may not have access to any accounts");return console.log("403: Access denied - clearing cached account and retrying without account scope"),e.logger.warn("403: Access denied - clearing cached account and retrying",{vertesia:{account_id:n,project_id:r,status:d.status,retry_count:a}}),localStorage.removeItem(w),n&&localStorage.removeItem(`${v}-${n}`),F(o,void 0,void 0,i,a+1)}if(!d.ok){const t=await d.text();throw console.error("STS token generation failed:",d.status,t),e.logger.error("STS token generation failed",{vertesia:{status:d.status,error:t,account_id:n,project_id:r}}),new Error(`Failed to get token from STS: ${d.status}`)}const{token:h}=await d.json();return console.log("Successfully got token from STS"),e.logger.info("Successfully got token from STS"),h}catch(t){if(t instanceof x||t instanceof O)throw t;throw localStorage.removeItem(w),n&&localStorage.removeItem(`${v}-${n}`),console.error("Failed to get composable token from STS",t),e.logger.error("Failed to get composable token from STS",{vertesia:{account_id:n,project_id:r,error:t}}),new Error("Failed to get composable token",{cause:t})}}async function P(e,t,o){return F($,e,t,o)}async function L(e,t,o,n){return F(()=>Promise.resolve(e),t,o,n)}function C(){return k}async function N(t,o,n,r=!1,i=!1){const a=t??localStorage.getItem(w)??void 0,s=o??localStorage.getItem(`${v}-${a}`)??void 0,c=e.isLocalDev?e.devAuthToken:void 0,l=c??n??k;if(!r&&k&&S&&S.exp>Date.now()/1e3+300)return{rawToken:k,token:S,error:!1};if(!r&&function(t){if(!t)return!1;try{return A(U(t).iss)===A(e.endpoints.sts)}catch{return!1}}(l)){if(k=l,S=U(k),!S.exp)throw new Error("Invalid composable token");return{rawToken:k,token:S,error:!1}}if(c||i||!I().currentUser?c||!n&&!k?c&&(k=c):k=await F(()=>Promise.resolve(n??k),a,s):k=await P(a,s),!k)throw e.logger.error("Cannot acquire a composable token",{vertesia:{account_id:a,project_id:s}}),new Error("Cannot acquire a composable token");if(S=U(k),!S?.exp||!k)throw console.error("Invalid composable token",S),e.logger.error("Invalid composable token",{vertesia:{account_id:a,project_id:s}}),new Error("Invalid composable token");return{rawToken:k,token:S,error:!1}}class x extends Error{email;constructor(e,t){super(e),this.name="UserNotFoundError",this.email=t}}class O extends Error{stsURL;constructor(e,t){super(e),this.name="STSError",this.stsURL=t}}const R="auth_state",D="auth_state_expiry";function z(){return{generateState:s(()=>{const e=crypto.randomUUID(),t=Date.now()+3e5;return sessionStorage.setItem(R,e),sessionStorage.setItem(D,t.toString()),e},[]),verifyState:s(e=>{if(!e)return"Missing state";const t=sessionStorage.getItem(R),o=parseInt(sessionStorage.getItem(D)||"0",10);let n;return n=t!==e?`State mismatched (${t} !== ${e})`:Date.now()>o?"State expired":void 0,n},[]),clearState:s(()=>{sessionStorage.removeItem(R),sessionStorage.removeItem(D)},[])}}function q(e){return!("firebase"===window.AUTH_MODE)}function H(){const e=new URL(document.baseURI),t=new URL(window.location.href),o=t.pathname.startsWith(e.pathname)?t:e;return o.hash="",o}function B(){const e=new URL(document.baseURI);return e.hash="",e.search="",e}class G{isLoading=!0;client;authError;authToken;setSession;lastSelectedAccount;lastSelectedProject;onboardingComplete;constructor(t,o){this.client=t||new m({serverUrl:e.endpoints.studio,storeUrl:e.endpoints.zeno,tokenServerUrl:e.endpoints.sts}),o&&(this.setSession=o),this.logout=this.logout.bind(this)}get store(){return this.client.store}get user(){return this.authToken}get account(){return this.authToken?.account}get project(){return this.authToken?.project}get accounts(){return this.authToken?.accounts}get authCallback(){return this.rawAuthToken.then(e=>`Bearer ${e}`)}get rawAuthToken(){return N().then(e=>{const o=e?.rawToken;if(!o)throw new Error("No token available");return this.authToken=t(o),o})}async refreshAuthToken(){const e=await N(void 0,void 0,void 0,!0),o=e?.rawToken;if(!o)throw new Error("No token available");return this.authToken=t(o),this.setSession?.(this.clone()),this.authToken}signOut(){this.logout()}getAccount(){return this.authToken?.account}async login(o,n={}){return this.authError=void 0,this.isLoading=!1,this.client.withAuthCallback(()=>this.authCallback),this.authToken=t(o),console.log(`Logging in as ${this.authToken?.name} with account ${this.authToken?.account.name} (${this.authToken?.account.id}, and project ${this.authToken?.project?.name} (${this.authToken?.project?.id})`),localStorage.setItem(w,this.authToken.account.id),localStorage.setItem(`${v}-${this.authToken.account.id}`,this.authToken.project?.id??""),e.onLogin?.(this.authToken),(n.loadOnboardingStatus??1)&&await this.fetchOnboardingStatus(),Promise.resolve()}isLoggedIn(){return!!this.authToken}logout(){if(console.log("Logging out"),q()){console.log("Using central auth logout"),this.authError=void 0,this.isLoading=!1,this.authToken=void 0,this.setSession=void 0,this.client.withAuthCallback(void 0);const e=new URL("https://internal-auth.vertesia.app/"),t=H();e.pathname="/logout",e.searchParams.set("redirect_uri",t.toString()),location.replace(e.toString())}else{console.log("Using Firebase logout");const e=!!this.authToken;this.authToken&&I().signOut(),this.authError=void 0,this.isLoading=!1,this.authToken=void 0,this.setSession=void 0,this.client.withAuthCallback(void 0),e&&location.replace(B().toString())}}async switchAccount(e){localStorage.setItem(w,e),this&&(this.account&&this.project?localStorage.setItem(`${v}-${this.account.id}`,this.project.id):this.account&&localStorage.removeItem(`${v}-${this.account.id}`));const t=B();t.searchParams.set("a",e),window.location.replace(t.toString())}async switchProject(e){this.account&&localStorage.setItem(`${v}-${this.account.id}`,e);const t=B();this.account?.id&&t.searchParams.set("a",this.account.id),t.searchParams.set("p",e),window.location.replace(t.toString())}async fetchAccounts(){return this.client.accounts.list().then(e=>{if(!this.authToken)throw new Error("No token available");this.authToken.accounts=e,this.setSession?.(this.clone())}).catch(e=>{throw console.error("Failed to fetch accounts",e),e})}async fetchProjects(e){return this.client.projects.list([e]).then(t=>{if(!this.authToken)throw new Error("No token available");this.authToken={...this.authToken,accounts:this.authToken.accounts?.map(o=>o.id===e?{...o,projects:t.filter(t=>t.account===e)}:o)},this.setSession?.(this.clone())}).catch(e=>{throw console.error("Failed to fetch projects",e),e})}async fetchOnboardingStatus(){if(this.onboardingComplete)return console.log("Onboarding already completed"),!1;const e=this.onboardingComplete;try{const t=await this.client.account.onboardingProgress();if(this.onboardingComplete=Object.values(t).every(e=>!0===e),e!==this.onboardingComplete)return!0;this.setSession?.(this.clone())}catch(e){console.error("Error fetching onboarding status:",e),this.onboardingComplete=!1,this.setSession?.(this.clone())}return!1}clone(){const e=new G(this.client);return e.isLoading=this.isLoading,e.authError=this.authError,e.authToken=this.authToken,e.setSession=this.setSession,e.lastSelectedAccount=this.lastSelectedAccount,e.switchAccount=this.switchAccount,e.onboardingComplete=this.onboardingComplete,e}}const J=c(void 0);function M(){const e=l(J);if(!e)throw new Error("useUserSession must be used within a UserSessionProvider");return e}function K(){const{user:e}=M(),[t,o]=u(null),[n,r]=u(!0),[i,a]=u(null);return d(()=>{(async()=>{if(!e?.email)return o(null),void r(!1);try{const t=await fetch("/api/resolve-tenant",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tenantEmail:e.email})});if(t.ok){const e=await t.json();o(e?{tenantKey:e.name||"unknown",name:e.label||e.name||"Unknown",domain:e.domain||[],firebaseTenantId:e.firebaseTenantId,provider:e.provider,logo:e.logo}:null)}else o(null)}catch(e){console.error("Error loading current tenant:",e),a(g.getFixedT(null,f)("errors.failedToLoadTenantConfig")),o(null)}finally{r(!1)}})()},[e?.email]),{currentTenant:t,isLoading:n,error:i}}function W({children:t,loadOnboardingStatus:o=!0}){const n=new URLSearchParams(location.hash.substring(1)),r=n.get("token"),i=n.get("state"),[s,c]=u(new G),{generateState:l,verifyState:g,clearState:f}=z(),m=h(!1),k=h(void 0),S=(t,o)=>{const n=new URL(`https://internal-auth.vertesia.app/?sts=${e.endpoints.sts??"https://sts.vertesia.io"}`),r=H();n.searchParams.set("redirect_uri",r.toString()),n.searchParams.set("state",l()),location.replace(n.toString())};return k.current=()=>{if(m.current)return void console.log("Auth: skipping duplicate auth flow initiation");m.current=!0,console.log("Auth: starting auth flow"),e.logger.info("Starting auth flow");const t=new URL(window.location.href),n=t.searchParams.get("a")??localStorage.getItem(w)??void 0,l=t.searchParams.get("p")??localStorage.getItem(`${v}-${n}`)??void 0;if(console.log("Auth: selected account",n),console.log("Auth: selected project",l),e.logger.info("Selected account and project",{vertesia:{account_id:n,project_id:l}}),e.isLocalDev&&e.devAuthToken)return s.setSession=c,void N(n,l,e.devAuthToken).then(e=>{s.login(e.rawToken).then(()=>c(s.clone()))}).catch(t=>{console.error("Failed to initialize dev auth token",t),e.logger.error("Failed to initialize dev auth token",{vertesia:{account_id:n,project_id:l,error:t}}),s.isLoading=!1,s.authError=t instanceof Error?t:new Error(String(t)),c(s.clone())});if(r&&i){s.setSession=c;const t=g(i);return t?(console.error(`Auth: invalid state: ${t}`),e.logger.error(`Invalid state: ${t}`,{vertesia:{state:i}}),S()):f(),void N(n,l,r,!1,q()).then(e=>{s.login(e.rawToken,{loadOnboardingStatus:o}).then(()=>{c(s.clone()),window.location.hash=""})}).catch(t=>t instanceof x?(console.log("User not found - will trigger signup flow",t),s.isLoading=!1,s.authError=t,void c(s.clone())):t instanceof O?(console.error("STS error during token exchange",t),e.logger.error("STS error during token exchange",{vertesia:{account_id:n,project_id:l,sts_url:t.stsURL,error:t}}),window.alert("Authentication failed due to an issue with the authentication service. Please try again later."),s.logout(),c(s.clone()),void(window.location.hash="")):(console.error("Failed to fetch user token from studio, redirecting to central auth",t),e.logger.error("Failed to fetch user token from studio, redirecting to central auth",{vertesia:{error:t}}),void S()))}let u,d=!1;const h=()=>{if(!d){if(!s.isLoggedIn()){if(console.log("Auth: not logged in & no token/state"),e.logger.info("Not logged in & no token/state",{vertesia:{account_id:n,project_id:l}}),q())return console.log("Auth: host is not in Firebase auth allowlist, redirecting to central auth with selection",n,l),e.logger.info("Redirecting to central auth with selection",{vertesia:{account_id:n,project_id:l}}),void S();console.log("Auth: host is in Firebase auth allowlist"),e.logger.info("Host is in Firebase auth allowlist",{vertesia:{account_id:n,project_id:l}})}u=a(I(),async t=>{t?(console.log("Auth: successful login with firebase"),e.logger.info("Successful login with firebase",{vertesia:{account_id:n,project_id:l}}),s.setSession=c,await N(n,l,void 0,!1,q()).then(e=>{s.login(e.rawToken,{loadOnboardingStatus:o}).then(()=>c(s.clone()))}).catch(t=>{console.error("Failed to fetch user token from studio",t),e.logger.error("Failed to fetch user token from studio",{vertesia:{account_id:n,project_id:l,error:t}}),t instanceof x||s.logout(),s.isLoading=!1,s.authError=t,c(s.clone())})):(console.log("Auth: using anonymous user"),e.logger.info("Using anonymous user",{vertesia:{account_id:n,project_id:l}}),s.client.withAuthCallback(void 0),s.logout(),c(s.clone()))})}};return e.authTokenProvider?(s.setSession=c,e.authTokenProvider().then(async e=>{if(!e)return void h();const t=await N(n,l,e,!1,q());await s.login(t.rawToken,{loadOnboardingStatus:o}),d||c(s.clone())}).catch(t=>{console.warn("Auth: failed to initialize injected auth token",t),e.logger.warn("Failed to initialize injected auth token",{vertesia:{account_id:n,project_id:l,error:t}}),h()}),()=>{d=!0,u?.()}):(h(),()=>{d=!0,u?.()})},d(()=>k.current?.(),[]),p(J.Provider,{value:s,children:t})}function Q(){return{tagUserSession:async e=>{const t=window.localStorage.getItem("composableSignupData");e?t&&window.localStorage.removeItem("composableSignupData"):console.error("No user found -- skipping tagging")},trackEvent:(t,o)=>{e.isProd||console.debug("track event",t,o),n(j(),t,{...o,debug_mode:!e.isProd})}}}export{w as LastSelectedAccountId_KEY,v as LastSelectedProjectId_KEY,O as STSError,x as UserNotFoundError,G as UserSession,J as UserSessionContext,W as UserSessionProvider,F as fetchComposableToken,P as fetchComposableTokenFromFirebaseToken,L as fetchComposableTokenFromVertesiaToken,N as getComposableToken,C as getCurrentVertesiaToken,j as getFirebaseAnalytics,y as getFirebaseApp,I as getFirebaseAuth,$ as getFirebaseAuthToken,E as setFirebaseTenant,z as useAuthState,K as useCurrentTenant,Q as useUXTracking,M as useUserSession};
|
|
2
2
|
//# sourceMappingURL=vertesia-ui-session.js.map
|