UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

445 lines 16.2 kB
var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = mod => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var useLoader_exports = {}; __export(useLoader_exports, { getLoaderTimingHistory: () => getLoaderTimingHistory, refetchLoader: () => refetchLoader, refetchMatchLoader: () => refetchMatchLoader, resetLoaderState: () => resetLoaderState, setSSRLoaderData: () => import_ssrLoaderData2.setSSRLoaderData, useLoader: () => useLoader, useLoaderState: () => useLoaderState }); module.exports = __toCommonJS(useLoader_exports); var import_react = require("react"); var import_registry = require("./devtools/registry.cjs"); var import_hooks = require("./hooks.cjs"); var import_notFoundState = require("./notFoundState.cjs"); var import_Route = require("./router/Route.cjs"); var import_matchers = require("./router/matchers.cjs"); var import_imperative_api = require("./router/imperative-api.cjs"); var import_router = require("./router/router.cjs"); var import_ssrLoaderData = require("./server/ssrLoaderData.cjs"); var import_useMatches = require("./useMatches.cjs"); var import_cleanUrl = require("./utils/cleanUrl.cjs"); require("./constants.cjs"); var import_dynamicImport = require("./utils/dynamicImport.cjs"); var import_weakKey = require("./utils/weakKey.cjs"); var import_one_server_only = require("./vite/one-server-only.cjs"); var import_ssrLoaderData2 = require("./server/ssrLoaderData.cjs"); process.env.ONE_LOADER_TIMEOUT_MS && +process.env.ONE_LOADER_TIMEOUT_MS; const loaderTimingHistory = []; const MAX_TIMING_HISTORY = 50; const recordLoaderTiming = process.env.NODE_ENV === "development" ? entry => { loaderTimingHistory.unshift(entry); if (loaderTimingHistory.length > MAX_TIMING_HISTORY) loaderTimingHistory.pop(); if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") { window.dispatchEvent(new CustomEvent("one-loader-timing", { detail: entry })); if (entry.error) window.dispatchEvent(new CustomEvent("one-error", { detail: { error: { message: entry.error, name: "LoaderError" }, route: { pathname: entry.path }, timestamp: Date.now(), type: "loader" } })); } } : void 0; function getLoaderTimingHistory() { return loaderTimingHistory; } (0, import_registry.registerDevtoolsFunction)("getLoaderTimingHistory", getLoaderTimingHistory); (0, import_registry.registerDevtoolsFunction)("recordLoaderTiming", recordLoaderTiming); const loaderState = {}; const subscribers = /* @__PURE__ */new Set(); const LOADER_STATE_MAX = 200; const loaderStateKeys = []; function setBoundedLoaderState(path, entry) { if (!(path in loaderState)) { loaderStateKeys.push(path); if (loaderStateKeys.length > LOADER_STATE_MAX) { const oldest = loaderStateKeys.shift(); delete loaderState[oldest]; } } loaderState[path] = entry; } function updateState(path, updates) { setBoundedLoaderState(path, { ...loaderState[path], ...updates }); subscribers.forEach(callback => { callback(); }); } function subscribe(callback) { subscribers.add(callback); return () => subscribers.delete(callback); } function getLoaderState(path, preloadedData) { if (!(path in loaderState)) setBoundedLoaderState(path, { data: preloadedData, error: void 0, promise: void 0, state: "idle", hasLoadedOnce: !!preloadedData }); return loaderState[path]; } async function refetchLoader(pathname) { const startTime = performance.now(); updateState(pathname, { state: "loading", error: null }); try { const cacheBust = `${Date.now()}`; const loaderJSUrl = (0, import_cleanUrl.getLoaderPath)(pathname, true, cacheBust); const moduleLoadStart = performance.now(); const module2 = await (0, import_dynamicImport.dynamicImport)(loaderJSUrl)?.catch(() => null); const moduleLoadTime = performance.now() - moduleLoadStart; if (!module2?.loader) { updateState(pathname, { data: void 0, state: "idle", hasLoadedOnce: true }); return; } const executionStart = performance.now(); const result = await module2.loader(); const executionTime = performance.now() - executionStart; const totalTime = performance.now() - startTime; if (result?.__oneRedirect) { recordLoaderTiming?.({ path: pathname, startTime, moduleLoadTime, executionTime, totalTime, source: "refetch" }); updateState(pathname, { data: void 0, state: "idle", hasLoadedOnce: true }); import_imperative_api.router.replace(result.__oneRedirect); return; } if (result?.__oneError === 404) { recordLoaderTiming?.({ path: pathname, startTime, moduleLoadTime, executionTime, totalTime, source: "refetch" }); const notFoundRoute = (0, import_notFoundState.findNearestNotFoundRoute)(pathname, import_router.routeNode); (0, import_notFoundState.setNotFoundState)({ notFoundPath: result.__oneNotFoundPath || "/+not-found", notFoundRouteNode: notFoundRoute || void 0, originalPath: pathname }); return; } updateState(pathname, { data: result, state: "idle", timestamp: Date.now(), hasLoadedOnce: true }); const currentMatches = (0, import_useMatches.getClientMatchesSnapshot)(); const pageMatch = currentMatches[currentMatches.length - 1]; const normalizedPathname = pathname.replace(/\/$/, "") || "/"; const normalizedMatchPathname = (pageMatch?.pathname || "").replace(/\/$/, "") || "/"; if (pageMatch && normalizedMatchPathname === normalizedPathname) (0, import_useMatches.updateMatchLoaderData)(pageMatch.routeId, result); recordLoaderTiming?.({ path: pathname, startTime, moduleLoadTime, executionTime, totalTime, source: "refetch" }); } catch (err) { const totalTime = performance.now() - startTime; updateState(pathname, { error: err, state: "idle" }); recordLoaderTiming?.({ path: pathname, startTime, totalTime, error: err instanceof Error ? err.message : String(err), source: "refetch" }); throw err; } } if (process.env.NODE_ENV === "development" && typeof window !== "undefined") window.__oneRefetchLoader = refetchLoader; async function refetchMatchLoader(routeId, currentPath) { const cacheBust = `${Date.now()}`; const loaderJSUrl = (0, import_cleanUrl.getLoaderPath)(currentPath, true, cacheBust); const module2 = await (0, import_dynamicImport.dynamicImport)(loaderJSUrl)?.catch(() => null); if (!module2?.loader) return; const result = await module2.loader(); if (result?.__oneRedirect || result?.__oneError) return; (0, import_useMatches.updateMatchLoaderData)(routeId, result); } function useLoaderState(loader) { const { loaderProps: loaderPropsFromServerContext, loaderData: loaderDataFromServerContext } = (0, import_one_server_only.useServerContext)() || {}; const params = (0, import_hooks.useParams)(); const pathname = (0, import_hooks.usePathname)(); const currentPath = pathname.replace(/\/index$/, "").replace(/\/$/, "") || "/"; if (typeof window === "undefined") { if (loader) { if (import_ssrLoaderData.ssrLoaderData.has(loader)) return { data: import_ssrLoaderData.ssrLoaderData.get(loader), refetch: async () => {}, state: "idle" }; const serverContext = (0, import_one_server_only.useServerContext)(); if (serverContext?.matches) { const contextKey = (0, import_Route.useContextKey)(); const match = serverContext.matches.find(m => (0, import_matchers.getContextKey)(m.routeId) === contextKey); if (match && match.loaderData !== void 0) return { data: match.loaderData, refetch: async () => {}, state: "idle" }; } return { data: useAsyncFn(loader, loaderPropsFromServerContext || { path: pathname, params }), refetch: async () => {}, state: "idle" }; } if (loaderDataFromServerContext !== void 0) return { data: loaderDataFromServerContext, refetch: async () => {}, state: "idle" }; } const matchRouteId = loader ? (() => { const result = loader(); return typeof result === "string" && result.startsWith("./") ? result : null; })() : null; const clientMatches = (0, import_react.useSyncExternalStore)(import_useMatches.subscribeToClientMatches, import_useMatches.getClientMatchesSnapshot, import_useMatches.getClientMatchesSnapshot); const preloadedData = loaderPropsFromServerContext?.path === currentPath ? loaderDataFromServerContext : void 0; const loaderStateEntry = (0, import_react.useSyncExternalStore)(subscribe, () => getLoaderState(currentPath, preloadedData), () => getLoaderState(currentPath, preloadedData)); const refetch = (0, import_react.useCallback)(() => refetchLoader(currentPath), [currentPath]); if (matchRouteId) { const match = clientMatches.find(m => m.routeId === matchRouteId); const isPageMatch = clientMatches.length > 0 && clientMatches[clientMatches.length - 1]?.routeId === matchRouteId; const matchPathNormalized = (match?.pathname || "").replace(/\/$/, "") || "/"; const matchPathFresh = !isPageMatch || matchPathNormalized === currentPath; if (match && match.loaderData != null && matchPathFresh) return { data: match.loaderData, refetch: async () => { await refetchLoader(currentPath); const fresh = loaderState[currentPath]; if (fresh?.data != null) (0, import_useMatches.updateMatchLoaderData)(matchRouteId, fresh.data); }, state: loaderStateEntry.state }; } if (!loader) return { refetch, state: loaderStateEntry.state }; if (!loaderStateEntry.data && !loaderStateEntry.promise && !loaderStateEntry.hasLoadedOnce) { const resolvedPreloadData = import_router.preloadedLoaderData[currentPath]; if (resolvedPreloadData != null) { delete import_router.preloadedLoaderData[currentPath]; delete import_router.preloadingLoader[currentPath]; loaderStateEntry.data = resolvedPreloadData; loaderStateEntry.hasLoadedOnce = true; } else if (import_router.preloadingLoader[currentPath]) loaderStateEntry.promise = import_router.preloadingLoader[currentPath].then(val => { delete import_router.preloadingLoader[currentPath]; delete import_router.preloadedLoaderData[currentPath]; if (val != null) updateState(currentPath, { data: val, hasLoadedOnce: true, promise: void 0 });else updateState(currentPath, { promise: void 0 }); }).catch(err => { console.error(`Error running loader()`, err); delete import_router.preloadingLoader[currentPath]; updateState(currentPath, { error: err, promise: void 0 }); });else { const loadData = async () => { const startTime = performance.now(); try { const loaderJSUrl = (0, import_cleanUrl.getLoaderPath)(currentPath, true); const moduleLoadStart = performance.now(); const module2 = await (0, import_dynamicImport.dynamicImport)(loaderJSUrl)?.catch(() => null); const moduleLoadTime = performance.now() - moduleLoadStart; if (!module2?.loader) { updateState(currentPath, { data: void 0, hasLoadedOnce: true, promise: void 0 }); return; } const executionStart = performance.now(); const result = await module2.loader(); const executionTime = performance.now() - executionStart; const totalTime = performance.now() - startTime; if (result?.__oneRedirect) { recordLoaderTiming?.({ path: currentPath, startTime, moduleLoadTime, executionTime, totalTime, source: "initial" }); updateState(currentPath, { data: void 0, hasLoadedOnce: true, promise: void 0 }); import_imperative_api.router.replace(result.__oneRedirect); return; } if (result?.__oneError === 404) { recordLoaderTiming?.({ path: currentPath, startTime, moduleLoadTime, executionTime, totalTime, source: "initial" }); const notFoundRoute = (0, import_notFoundState.findNearestNotFoundRoute)(currentPath, import_router.routeNode); (0, import_notFoundState.setNotFoundState)({ notFoundPath: result.__oneNotFoundPath || "/+not-found", notFoundRouteNode: notFoundRoute || void 0, originalPath: currentPath }); return; } updateState(currentPath, { data: result, hasLoadedOnce: true, promise: void 0 }); recordLoaderTiming?.({ path: currentPath, startTime, moduleLoadTime, executionTime, totalTime, source: "initial" }); } catch (err) { const totalTime = performance.now() - startTime; updateState(currentPath, { error: err, promise: void 0 }); recordLoaderTiming?.({ path: currentPath, startTime, totalTime, error: err instanceof Error ? err.message : String(err), source: "initial" }); } }; loaderStateEntry.promise = loadData(); } } if (loaderStateEntry.error && !loaderStateEntry.hasLoadedOnce) throw loaderStateEntry.error; if (loaderStateEntry.data === void 0 && loaderStateEntry.promise && !loaderStateEntry.hasLoadedOnce) throw loaderStateEntry.promise; return { data: loaderStateEntry.data, refetch, state: loaderStateEntry.state }; } function useLoader(loader) { const { data } = useLoaderState(loader); return data; } const results = /* @__PURE__ */new Map(); const started = /* @__PURE__ */new Map(); const USE_ASYNC_FN_CACHE_MAX = 100; function setBoundedResults(key, value) { if (results.size >= USE_ASYNC_FN_CACHE_MAX && !results.has(key)) { const firstKey = results.keys().next().value; if (firstKey !== void 0) { results.delete(firstKey); started.delete(firstKey); } } results.set(key, value); } function resetLoaderState() { results.clear(); started.clear(); } function useAsyncFn(val, props) { const key = (val ? (0, import_weakKey.weakKey)(val) : "") + JSON.stringify(props); if (val) { if (!started.get(key)) { started.set(key, true); let next = val(props); if (next instanceof Promise) next = next.then(final => { setBoundedResults(key, final); }).catch(err => { console.error(`Error running loader()`, err); setBoundedResults(key, void 0); }); setBoundedResults(key, next); } } const current = results.get(key); if (current instanceof Promise) throw current; return current; }