heliumts 0.6.2 → 0.6.3

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.
File without changes
@@ -1 +1 @@
1
- {"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAC3C,OAAO,KAAuD,MAAM,OAAO,CAAC;AAM5E,KAAK,WAAW,GAAG,YAAY,GAAG,mBAAmB,CAAC;AACtD,KAAK,aAAa,GAAG,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,KAAK,IAAI,CAAC;AAgKhG,kDAAkD;AAClD,MAAM,WAAW,uBAAuB;IACpC,qDAAqD;IACrD,WAAW,CAAC,EAAE,OAAO,CAAC;CACzB;AAGD,KAAK,aAAa,GAAG;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;IAC1C,YAAY,EAAE,eAAe,CAAC;IAC9B,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,uBAAuB,KAAK,IAAI,CAAC;IAChE,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,uBAAuB,KAAK,IAAI,CAAC;IACnE,EAAE,EAAE,CAAC,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,aAAa,KAAK,MAAM,IAAI,CAAC;IAChE,MAAM,EAAE,GAAG,GAAG,GAAG,CAAC;IAClB,YAAY,EAAE,OAAO,CAAC;IACtB,8GAA8G;IAC9G,SAAS,EAAE,OAAO,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,aAAa,qCAAkD,CAAC;AAE7E;;;;;;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AAC;IAClB,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qDAAqD;IACrD,WAAW,CAAC,EAAE,OAAO,CAAC;CACzB,CACJ,CAAC;AA+BF;;;;;;;;;GASG;AACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,SAAS,2CA4DpC;AAGD;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;IAC9F,SAAS,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IACrC,SAAS,EAAE,UAAU,CAAC;CACzB,CAAC;AAGF,wBAAgB,SAAS,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,CAAC,EAAE,aAAa,CAAC,aAAa,CAAC,CAAA;CAAE,2CAoFlF"}
@@ -1,5 +1,6 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import React, { useMemo, useSyncExternalStore, useTransition } from "react";
3
+ import { isDevEnvironment } from "./env.js";
3
4
  import { buildRoutes } from "./routerManifest.js";
4
5
  class RouterEventEmitter {
5
6
  constructor() {
@@ -37,7 +38,7 @@ class RouterEventEmitter {
37
38
  }
38
39
  // Use a singleton that survives HMR by attaching to window in dev mode
39
40
  let routerEventEmitter;
40
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
41
+ if (typeof window !== "undefined" && isDevEnvironment()) {
41
42
  // In dev mode, reuse the same emitter instance across HMR
42
43
  const globalWindow = window;
43
44
  if (!globalWindow.__heliumRouterEmitter) {
@@ -69,7 +70,7 @@ function matchRoute(path, routes) {
69
70
  // Preserve across HMR by attaching to window in dev mode
70
71
  let currentLocation;
71
72
  let locationListeners;
72
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
73
+ if (typeof window !== "undefined" && isDevEnvironment()) {
73
74
  const globalWindow = window;
74
75
  if (!globalWindow.__heliumCurrentLocation) {
75
76
  globalWindow.__heliumCurrentLocation = getLocation();
@@ -90,7 +91,7 @@ else {
90
91
  }
91
92
  // Helper to re-extract params from path using stored routes during HMR
92
93
  function extractParamsFromPath(path) {
93
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
94
+ if (typeof window !== "undefined" && isDevEnvironment()) {
94
95
  const globalWindow = window;
95
96
  const routes = globalWindow.__heliumGlobalRoutes;
96
97
  if (routes && routes.length > 0) {
@@ -116,7 +117,7 @@ function updateLocation(isNavigating = false) {
116
117
  const newLocation = { ...getLocation(), isNavigating };
117
118
  currentLocation = newLocation;
118
119
  // Update the global reference in dev mode
119
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
120
+ if (typeof window !== "undefined" && isDevEnvironment()) {
120
121
  window.__heliumCurrentLocation = newLocation;
121
122
  }
122
123
  locationListeners.forEach((listener) => listener());
@@ -148,7 +149,7 @@ export function useRouter() {
148
149
  // During HMR in development, context might be temporarily unavailable
149
150
  // Provide a temporary fallback to prevent white screen of death
150
151
  // Re-extract params from current path using stored routes
151
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
152
+ if (typeof window !== "undefined" && isDevEnvironment()) {
152
153
  const currentPath = window.location.pathname;
153
154
  return {
154
155
  path: currentPath,
@@ -261,7 +262,7 @@ function isExternalUrl(href) {
261
262
  // Store routes globally for prefetching (set by AppRouter)
262
263
  // Preserve across HMR in dev mode
263
264
  let globalRoutes;
264
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
265
+ if (typeof window !== "undefined" && isDevEnvironment()) {
265
266
  const globalWindow = window;
266
267
  if (!globalWindow.__heliumGlobalRoutes) {
267
268
  globalWindow.__heliumGlobalRoutes = [];
@@ -331,7 +332,7 @@ export function AppRouter({ AppShell }) {
331
332
  const result = buildRoutes();
332
333
  // Store routes globally for Link prefetching
333
334
  // In dev mode, also update the global reference to survive HMR
334
- if (import.meta.env?.DEV) {
335
+ if (isDevEnvironment()) {
335
336
  const globalWindow = window;
336
337
  globalWindow.__heliumGlobalRoutes = result.routes;
337
338
  // Update the module-level reference as well
@@ -348,9 +349,9 @@ export function AppRouter({ AppShell }) {
348
349
  const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);
349
350
  const match = useMemo(() => matchRoute(state.path, routes), [state.path, routes]);
350
351
  // Use matched params, or fall back to re-extracting from path using global routes during HMR
351
- const currentParams = match?.params ?? (import.meta.env?.DEV ? extractParamsFromPath(state.path) : {});
352
+ const currentParams = match?.params ?? (isDevEnvironment() ? extractParamsFromPath(state.path) : {});
352
353
  // In dev mode, always read fresh searchParams from URL to handle HMR edge cases
353
- const currentSearchParams = import.meta.env?.DEV ? new URLSearchParams(window.location.search) : state.searchParams;
354
+ const currentSearchParams = isDevEnvironment() ? new URLSearchParams(window.location.search) : state.searchParams;
354
355
  const routerValue = {
355
356
  path: state.path,
356
357
  params: currentParams,
@@ -1 +1 @@
1
- {"version":3,"file":"Router.js","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":";AACA,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAG5E,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAMlD,MAAM,kBAAkB;IAAxB;QACY,cAAS,GAAyC,IAAI,GAAG,EAAE,CAAC;IAsCxE,CAAC;IApCG,EAAE,CAAC,KAAkB,EAAE,QAAuB;QAC1C,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,GAAG,EAAE,CAAC,CAAC;QACzC,CAAC;QACD,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAE,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAEzC,8BAA8B;QAC9B,OAAO,GAAG,EAAE;YACR,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,E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aAAa,CAAC,QAAQ,IAAC,KAAK,EAAE,WAAW,YAAG,QAAQ,CAAC,CAAC,CAAC,KAAC,QAAQ,IAAC,SAAS,EAAE,YAAY,EAAE,SAAS,EAAE,EAAE,GAAI,CAAC,CAAC,CAAC,OAAO,GAA0B,CAAC;IAC5J,CAAC;IAED,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,SAAwG,CAAC;IAClI,MAAM,SAAS,GAAG;QACd,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,YAAY,EAAE,mBAAmB;KACpC,CAAC;IAEF,uDAAuD;IACvD,MAAM,WAAW,GAAG,GAAG,EAAE;QACrB,IAAI,OAAO,GAAG,KAAC,IAAI,OAAK,SAAS,GAAI,CAAC;QACtC,+CAA+C;QAC/C,KAAK,IAAI,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YACvD,MAAM,MAAM,GAAG,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACtC,OAAO,GAAG,KAAC,MAAM,cAAE,OAAO,GAAU,CAAC;QACzC,CAAC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC,CAAC;IAEF,MAAM,YAAY,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAC,QAAQ,IAAC,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,EAAE,GAAI,CAAC,CAAC,CAAC,KAAC,WAAW,KAAG,CAAC;IAEtG,OAAO,KAAC,aAAa,CAAC,QAAQ,IAAC,KAAK,EAAE,WAAW,YAAG,YAAY,GAA0B,CAAC;AAC/F,CAAC","sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { useMemo, useSyncExternalStore, useTransition } from \"react\";\n\nimport type { RouteEntry } from \"./routerManifest.js\";\nimport { buildRoutes } from \"./routerManifest.js\";\n\n// Event emitter for router events\ntype RouterEvent = \"navigation\" | \"before-navigation\";\ntype EventListener = (event: { from: string; to: string; preventDefault?: () => void }) => void;\n\nclass RouterEventEmitter {\n private listeners: Map<RouterEvent, Set<EventListener>> = new Map();\n\n on(event: RouterEvent, listener: EventListener): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener);\n };\n }\n\n emit(event: RouterEvent, data: { from: string; to: string }): boolean {\n const eventListeners = this.listeners.get(event);\n if (!eventListeners || eventListeners.size === 0) {\n return true;\n }\n\n let prevented = false;\n const preventDefault = () => {\n prevented = true;\n };\n\n const eventData = event === \"before-navigation\" ? { ...data, preventDefault } : data;\n\n eventListeners.forEach((listener) => {\n listener(eventData);\n });\n\n return !prevented;\n }\n\n // Clear all listeners - useful for HMR\n clear() {\n this.listeners.clear();\n }\n}\n\n// Use a singleton that survives HMR by attaching to window in dev mode\nlet routerEventEmitter: RouterEventEmitter;\n\nif (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n // In dev mode, reuse the same emitter instance across HMR\n const globalWindow = window as typeof window & { __heliumRouterEmitter?: RouterEventEmitter };\n if (!globalWindow.__heliumRouterEmitter) {\n globalWindow.__heliumRouterEmitter = new RouterEventEmitter();\n }\n routerEventEmitter = globalWindow.__heliumRouterEmitter;\n} else {\n routerEventEmitter = new RouterEventEmitter();\n}\n\ntype RouterState = {\n path: string;\n searchParams: URLSearchParams;\n isNavigating: boolean;\n};\n\nfunction getLocation(): RouterState {\n const { pathname, search } = window.location;\n return {\n path: pathname,\n searchParams: new URLSearchParams(search),\n isNavigating: false,\n };\n}\n\nfunction matchRoute(path: string, routes: RouteEntry[]) {\n for (const r of routes) {\n const m = r.matcher(path);\n if (m) {\n return { params: m.params, route: r };\n }\n }\n return null;\n}\n\n// Location store for useSyncExternalStore\n// Preserve across HMR by attaching to window in dev mode\nlet currentLocation: RouterState;\nlet locationListeners: Set<() => void>;\n\nif (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n const globalWindow = window as typeof window & {\n __heliumCurrentLocation?: RouterState;\n __heliumLocationListeners?: Set<() => void>;\n };\n if (!globalWindow.__heliumCurrentLocation) {\n globalWindow.__heliumCurrentLocation = getLocation();\n }\n if (!globalWindow.__heliumLocationListeners) {\n globalWindow.__heliumLocationListeners = new Set();\n }\n currentLocation = globalWindow.__heliumCurrentLocation;\n locationListeners = globalWindow.__heliumLocationListeners;\n} else if (typeof window !== \"undefined\") {\n currentLocation = getLocation();\n locationListeners = new Set();\n} else {\n currentLocation = { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\n locationListeners = new Set();\n}\n\n// Helper to re-extract params from path using stored routes during HMR\nfunction extractParamsFromPath(path: string): Record<string, string | string[]> {\n if (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n const routes = globalWindow.__heliumGlobalRoutes;\n if (routes && routes.length > 0) {\n const match = matchRoute(path, routes);\n if (match) {\n return match.params;\n }\n }\n }\n return {};\n}\n\nfunction subscribeToLocation(callback: () => void) {\n locationListeners.add(callback);\n return () => locationListeners.delete(callback);\n}\n\nfunction getLocationSnapshot() {\n return currentLocation;\n}\n\nfunction getServerSnapshot() {\n return { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\n}\n\nfunction updateLocation(isNavigating = false) {\n const newLocation = { ...getLocation(), isNavigating };\n currentLocation = newLocation;\n // Update the global reference in dev mode\n if (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n (window as typeof window & { __heliumCurrentLocation?: RouterState }).__heliumCurrentLocation = newLocation;\n }\n locationListeners.forEach((listener) => listener());\n}\n\n// Set up global listeners once\nif (typeof window !== \"undefined\") {\n // Only set up once, survives HMR\n const globalWindow = window as typeof window & { __heliumLocationListenerSetup?: boolean };\n if (!globalWindow.__heliumLocationListenerSetup) {\n globalWindow.__heliumLocationListenerSetup = true;\n\n window.addEventListener(\"popstate\", () => updateLocation(false));\n\n // Also listen to navigation events from the emitter\n routerEventEmitter.on(\"navigation\", () => updateLocation(false));\n }\n}\n\n/** Options for push/replace navigation methods */\nexport interface RouterNavigationOptions {\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n}\n\n// Context for useRouter hook\ntype RouterContext = {\n path: string;\n params: Record<string, string | string[]>;\n searchParams: URLSearchParams;\n push: (href: string, options?: RouterNavigationOptions) => void;\n replace: (href: string, options?: RouterNavigationOptions) => void;\n on: (event: RouterEvent, listener: EventListener) => () => void;\n status: 200 | 404;\n isNavigating: boolean;\n /** Indicates content is stale (old content shown while new content renders) - React 18+ concurrent feature */\n isPending: boolean;\n};\n\nexport const RouterContext = React.createContext<RouterContext | null>(null);\n\n/**\n * Access router context inside a component tree managed by <AppRouter />.\n *\n * Provides current path, route params, URL search params and navigation helpers\n * (\\`push\\`, \\`replace\\`) as well as an \\`on\\` method to subscribe to navigation events.\n * The \\`isNavigating\\` property indicates when a navigation is in progress.\n * The \\`isPending\\` property indicates when content is stale (React concurrent features).\n * Throws when used outside of an <AppRouter /> provider.\n */\nexport function useRouter() {\n const ctx = React.useContext(RouterContext);\n if (!ctx) {\n // During HMR in development, context might be temporarily unavailable\n // Provide a temporary fallback to prevent white screen of death\n // Re-extract params from current path using stored routes\n if (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n const currentPath = window.location.pathname;\n return {\n path: currentPath,\n params: extractParamsFromPath(currentPath),\n searchParams: new URLSearchParams(window.location.search),\n push: (href: string, options?: RouterNavigationOptions) => {\n window.history.pushState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n replace: (href: string, options?: RouterNavigationOptions) => {\n window.history.replaceState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n on: () => () => {},\n status: 200 as const,\n isNavigating: false,\n isPending: false,\n };\n }\n throw new Error(\"useRouter must be used inside <AppRouter>\");\n }\n return ctx;\n}\n\n/**\n * Redirect component for declarative navigation.\n * Use this instead of calling router.push() during render.\n *\n * @example\n * \\`\\`\\`tsx\n * export default function Docs() {\n * return <Redirect to=\"/docs/getting-started\" />;\n * }\n * \\`\\`\\`\n */\nexport function Redirect({ to, replace = false }: { to: string; replace?: boolean }) {\n const hasRedirected = React.useRef(false);\n\n // Use useLayoutEffect to redirect before paint\n React.useLayoutEffect(() => {\n const targetPath = to.split(\"?\")[0];\n if (!hasRedirected.current && window.location.pathname !== targetPath) {\n hasRedirected.current = true;\n\n // Perform navigation\n if (replace) {\n window.history.replaceState(null, \"\", to);\n } else {\n window.history.pushState(null, \"\", to);\n }\n\n // Emit navigation event to update router state\n routerEventEmitter.emit(\"navigation\", {\n from: window.location.pathname,\n to: targetPath,\n });\n }\n }, [to, replace]);\n\n return null;\n}\n\n/** Options for navigation */\ninterface NavigateOptions {\n replace?: boolean;\n scrollToTop?: boolean;\n}\n\n// Navigation helper\nfunction navigate(href: string, options: NavigateOptions = {}) {\n const { replace = false, scrollToTop = true } = options;\n const from = window.location.pathname;\n const to = href.split(\"?\")[0]; // Extract pathname from href\n\n // Emit before-navigation event (can be prevented)\n const canNavigate = routerEventEmitter.emit(\"before-navigation\", { from, to });\n if (!canNavigate) {\n return; // Navigation was prevented\n }\n\n // Set navigating state to true before navigation\n currentLocation = { ...currentLocation, isNavigating: true };\n locationListeners.forEach((listener) => listener());\n\n if (replace) {\n window.history.replaceState(null, \"\", href);\n } else {\n window.history.pushState(null, \"\", href);\n }\n\n // Scroll to top immediately after pushState, before React re-renders.\n // Using instant scroll avoids race conditions where smooth scrolling\n // gets interrupted by React DOM updates, especially on Safari mobile.\n if (scrollToTop) {\n window.scrollTo({ top: 0, left: 0, behavior: \"instant\" });\n }\n\n // Update location state synchronously so there is no stale-state window\n // between pushState and the next render.\n updateLocation(false);\n\n // Emit navigation event after state is consistent\n routerEventEmitter.emit(\"navigation\", { from, to });\n}\n\nexport type LinkProps = React.PropsWithChildren<\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> & {\n href: string;\n replace?: boolean;\n /** Disable prefetching on hover (default: false - prefetch is enabled) */\n prefetch?: boolean;\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n }\n>;\n\n/**\n * Check if a URL is external (different origin).\n */\nfunction isExternalUrl(href: string): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n const url = new URL(href, window.location.origin);\n return url.origin !== window.location.origin;\n } catch {\n return false;\n }\n}\n\n// Store routes globally for prefetching (set by AppRouter)\n// Preserve across HMR in dev mode\nlet globalRoutes: RouteEntry[];\n\nif (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n if (!globalWindow.__heliumGlobalRoutes) {\n globalWindow.__heliumGlobalRoutes = [];\n }\n globalRoutes = globalWindow.__heliumGlobalRoutes;\n} else {\n globalRoutes = [];\n}\n\n/**\n * Client-side navigation link.\n *\n * Intercepts left-clicks and uses the router's navigation helpers for SPA\n * navigation. Keeps normal anchor behaviour when modifier keys are used,\n * when the link is external, or when `target` / `download` attributes\n * are present.\n *\n * Automatically prefetches page chunks on hover for faster navigation.\n */\nexport function Link(props: LinkProps) {\n const {\n children,\n href,\n className,\n prefetch: prefetchProp = true,\n scrollToTop = true,\n replace: replaceProp,\n target,\n download,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n onFocus: userOnFocus,\n ...restProps\n } = props;\n\n const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Let user's onClick run first so they can call e.preventDefault()\n userOnClick?.(e);\n\n if (\n e.defaultPrevented ||\n e.button !== 0 || // only left click\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey ||\n target || // let browser handle target=\"_blank\" etc.\n download != null || // let browser handle downloads\n isExternalUrl(href) // let browser handle external links\n ) {\n return;\n }\n e.preventDefault();\n navigate(href, { replace: replaceProp, scrollToTop });\n };\n\n const onMouseEnter = async (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Prefetch the route on hover if enabled and not external (lazy-load prefetch logic)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnMouseEnter?.(e);\n };\n\n const onFocus = async (e: React.FocusEvent<HTMLAnchorElement>) => {\n // Also prefetch on focus (keyboard navigation)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnFocus?.(e);\n };\n\n return (\n <a {...restProps} href={href} target={target} download={download} onClick={onClick} onMouseEnter={onMouseEnter} onFocus={onFocus} className={className}>\n {children}\n </a>\n );\n}\n\n// AppShell props type\n/**\n * Props passed to an optional \\`AppShell\\` wrapper component used by <AppRouter />.\n *\n * \\`Component\\` — the page component to render. \\`pageProps\\` — props provided to the page.\n */\nexport type AppShellProps<TPageProps extends Record<string, unknown> = Record<string, unknown>> = {\n Component: ComponentType<TPageProps>;\n pageProps: TPageProps;\n};\n\n// Main router component\nexport function AppRouter({ AppShell }: { AppShell?: ComponentType<AppShellProps> }) {\n // useTransition for concurrent rendering - allows React to keep UI responsive during navigation\n const [isPending, startTransition] = useTransition();\n\n // Build routes once on mount (client-side only)\n const { routes, NotFound } = useMemo(() => {\n if (typeof window === \"undefined\") {\n return { routes: [], NotFound: undefined };\n }\n const result = buildRoutes();\n // Store routes globally for Link prefetching\n // In dev mode, also update the global reference to survive HMR\n if (import.meta.env?.DEV) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n globalWindow.__heliumGlobalRoutes = result.routes;\n // Update the module-level reference as well\n globalRoutes.length = 0;\n globalRoutes.push(...result.routes);\n } else {\n globalRoutes = result.routes;\n }\n return result;\n }, []);\n\n // Use useSyncExternalStore to subscribe to location changes\n // This ensures synchronous updates when location changes\n const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);\n\n const match = useMemo(() => matchRoute(state.path, routes), [state.path, routes]);\n\n // Use matched params, or fall back to re-extracting from path using global routes during HMR\n const currentParams = match?.params ?? (import.meta.env?.DEV ? extractParamsFromPath(state.path) : {});\n\n // In dev mode, always read fresh searchParams from URL to handle HMR edge cases\n const currentSearchParams = import.meta.env?.DEV ? new URLSearchParams(window.location.search) : state.searchParams;\n\n const routerValue: RouterContext = {\n path: state.path,\n params: currentParams,\n searchParams: currentSearchParams,\n push: (href, options) => {\n // Wrap navigation in startTransition for smoother updates\n startTransition(() => {\n navigate(href, { scrollToTop: options?.scrollToTop });\n });\n },\n replace: (href, options) => {\n startTransition(() => {\n navigate(href, { replace: true, scrollToTop: options?.scrollToTop });\n });\n },\n on: (event, listener) => routerEventEmitter.on(event, listener),\n status: match ? 200 : 404,\n isNavigating: state.isNavigating,\n isPending,\n };\n\n if (!match) {\n const NotFoundComp = NotFound ?? (() => <div>Not found</div>);\n const content = <NotFoundComp />;\n\n return <RouterContext.Provider value={routerValue}>{AppShell ? <AppShell Component={NotFoundComp} pageProps={{}} /> : content}</RouterContext.Provider>;\n }\n\n const Page = match.route.Component as ComponentType<{ params: Record<string, string | string[]>; searchParams: URLSearchParams }>;\n const pageProps = {\n params: match.params,\n searchParams: currentSearchParams,\n };\n\n // Create a wrapped component that includes all layouts\n const WrappedPage = () => {\n let content = <Page {...pageProps} />;\n // Wrap page with layouts (from outer to inner)\n for (let i = match.route.layouts.length - 1; i >= 0; i--) {\n const Layout = match.route.layouts[i];\n content = <Layout>{content}</Layout>;\n }\n return content;\n };\n\n const finalContent = AppShell ? <AppShell Component={WrappedPage} pageProps={{}} /> : <WrappedPage />;\n\n return <RouterContext.Provider value={routerValue}>{finalContent}</RouterContext.Provider>;\n}\n"]}
1
+ {"version":3,"file":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AC;QACD,OAAO,OAAO,CAAC;IACnB,CAAC,CAAC;IAEF,MAAM,YAAY,GAAG,QAAQ,CAAC,CAAC,CAAC,KAAC,QAAQ,IAAC,SAAS,EAAE,WAAW,EAAE,SAAS,EAAE,EAAE,GAAI,CAAC,CAAC,CAAC,KAAC,WAAW,KAAG,CAAC;IAEtG,OAAO,KAAC,aAAa,CAAC,QAAQ,IAAC,KAAK,EAAE,WAAW,YAAG,YAAY,GAA0B,CAAC;AAC/F,CAAC","sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { useMemo, useSyncExternalStore, useTransition } from \"react\";\n\nimport { isDevEnvironment } from \"./env.js\";\nimport type { RouteEntry } from \"./routerManifest.js\";\nimport { buildRoutes } from \"./routerManifest.js\";\n\n// Event emitter for router events\ntype RouterEvent = \"navigation\" | \"before-navigation\";\ntype EventListener = (event: { from: string; to: string; preventDefault?: () => void }) => void;\n\nclass RouterEventEmitter {\n private listeners: Map<RouterEvent, Set<EventListener>> = new Map();\n\n on(event: RouterEvent, listener: EventListener): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener);\n };\n }\n\n emit(event: RouterEvent, data: { from: string; to: string }): boolean {\n const eventListeners = this.listeners.get(event);\n if (!eventListeners || eventListeners.size === 0) {\n return true;\n }\n\n let prevented = false;\n const preventDefault = () => {\n prevented = true;\n };\n\n const eventData = event === \"before-navigation\" ? { ...data, preventDefault } : data;\n\n eventListeners.forEach((listener) => {\n listener(eventData);\n });\n\n return !prevented;\n }\n\n // Clear all listeners - useful for HMR\n clear() {\n this.listeners.clear();\n }\n}\n\n// Use a singleton that survives HMR by attaching to window in dev mode\nlet routerEventEmitter: RouterEventEmitter;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n // In dev mode, reuse the same emitter instance across HMR\n const globalWindow = window as typeof window & { __heliumRouterEmitter?: RouterEventEmitter };\n if (!globalWindow.__heliumRouterEmitter) {\n globalWindow.__heliumRouterEmitter = new RouterEventEmitter();\n }\n routerEventEmitter = globalWindow.__heliumRouterEmitter;\n} else {\n routerEventEmitter = new RouterEventEmitter();\n}\n\ntype RouterState = {\n path: string;\n searchParams: URLSearchParams;\n isNavigating: boolean;\n};\n\nfunction getLocation(): RouterState {\n const { pathname, search } = window.location;\n return {\n path: pathname,\n searchParams: new URLSearchParams(search),\n isNavigating: false,\n };\n}\n\nfunction matchRoute(path: string, routes: RouteEntry[]) {\n for (const r of routes) {\n const m = r.matcher(path);\n if (m) {\n return { params: m.params, route: r };\n }\n }\n return null;\n}\n\n// Location store for useSyncExternalStore\n// Preserve across HMR by attaching to window in dev mode\nlet currentLocation: RouterState;\nlet locationListeners: Set<() => void>;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & {\n __heliumCurrentLocation?: RouterState;\n __heliumLocationListeners?: Set<() => void>;\n };\n if (!globalWindow.__heliumCurrentLocation) {\n globalWindow.__heliumCurrentLocation = getLocation();\n }\n if (!globalWindow.__heliumLocationListeners) {\n globalWindow.__heliumLocationListeners = new Set();\n }\n currentLocation = globalWindow.__heliumCurrentLocation;\n locationListeners = globalWindow.__heliumLocationListeners;\n} else if (typeof window !== \"undefined\") {\n currentLocation = getLocation();\n locationListeners = new Set();\n} else {\n currentLocation = { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\n locationListeners = new Set();\n}\n\n// Helper to re-extract params from path using stored routes during HMR\nfunction extractParamsFromPath(path: string): Record<string, string | string[]> {\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n const routes = globalWindow.__heliumGlobalRoutes;\n if (routes && routes.length > 0) {\n const match = matchRoute(path, routes);\n if (match) {\n return match.params;\n }\n }\n }\n return {};\n}\n\nfunction subscribeToLocation(callback: () => void) {\n locationListeners.add(callback);\n return () => locationListeners.delete(callback);\n}\n\nfunction getLocationSnapshot() {\n return currentLocation;\n}\n\nfunction getServerSnapshot() {\n return { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\n}\n\nfunction updateLocation(isNavigating = false) {\n const newLocation = { ...getLocation(), isNavigating };\n currentLocation = newLocation;\n // Update the global reference in dev mode\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n (window as typeof window & { __heliumCurrentLocation?: RouterState }).__heliumCurrentLocation = newLocation;\n }\n locationListeners.forEach((listener) => listener());\n}\n\n// Set up global listeners once\nif (typeof window !== \"undefined\") {\n // Only set up once, survives HMR\n const globalWindow = window as typeof window & { __heliumLocationListenerSetup?: boolean };\n if (!globalWindow.__heliumLocationListenerSetup) {\n globalWindow.__heliumLocationListenerSetup = true;\n\n window.addEventListener(\"popstate\", () => updateLocation(false));\n\n // Also listen to navigation events from the emitter\n routerEventEmitter.on(\"navigation\", () => updateLocation(false));\n }\n}\n\n/** Options for push/replace navigation methods */\nexport interface RouterNavigationOptions {\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n}\n\n// Context for useRouter hook\ntype RouterContext = {\n path: string;\n params: Record<string, string | string[]>;\n searchParams: URLSearchParams;\n push: (href: string, options?: RouterNavigationOptions) => void;\n replace: (href: string, options?: RouterNavigationOptions) => void;\n on: (event: RouterEvent, listener: EventListener) => () => void;\n status: 200 | 404;\n isNavigating: boolean;\n /** Indicates content is stale (old content shown while new content renders) - React 18+ concurrent feature */\n isPending: boolean;\n};\n\nexport const RouterContext = React.createContext<RouterContext | null>(null);\n\n/**\n * Access router context inside a component tree managed by <AppRouter />.\n *\n * Provides current path, route params, URL search params and navigation helpers\n * (\\`push\\`, \\`replace\\`) as well as an \\`on\\` method to subscribe to navigation events.\n * The \\`isNavigating\\` property indicates when a navigation is in progress.\n * The \\`isPending\\` property indicates when content is stale (React concurrent features).\n * Throws when used outside of an <AppRouter /> provider.\n */\nexport function useRouter() {\n const ctx = React.useContext(RouterContext);\n if (!ctx) {\n // During HMR in development, context might be temporarily unavailable\n // Provide a temporary fallback to prevent white screen of death\n // Re-extract params from current path using stored routes\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const currentPath = window.location.pathname;\n return {\n path: currentPath,\n params: extractParamsFromPath(currentPath),\n searchParams: new URLSearchParams(window.location.search),\n push: (href: string, options?: RouterNavigationOptions) => {\n window.history.pushState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n replace: (href: string, options?: RouterNavigationOptions) => {\n window.history.replaceState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n on: () => () => {},\n status: 200 as const,\n isNavigating: false,\n isPending: false,\n };\n }\n throw new Error(\"useRouter must be used inside <AppRouter>\");\n }\n return ctx;\n}\n\n/**\n * Redirect component for declarative navigation.\n * Use this instead of calling router.push() during render.\n *\n * @example\n * \\`\\`\\`tsx\n * export default function Docs() {\n * return <Redirect to=\"/docs/getting-started\" />;\n * }\n * \\`\\`\\`\n */\nexport function Redirect({ to, replace = false }: { to: string; replace?: boolean }) {\n const hasRedirected = React.useRef(false);\n\n // Use useLayoutEffect to redirect before paint\n React.useLayoutEffect(() => {\n const targetPath = to.split(\"?\")[0];\n if (!hasRedirected.current && window.location.pathname !== targetPath) {\n hasRedirected.current = true;\n\n // Perform navigation\n if (replace) {\n window.history.replaceState(null, \"\", to);\n } else {\n window.history.pushState(null, \"\", to);\n }\n\n // Emit navigation event to update router state\n routerEventEmitter.emit(\"navigation\", {\n from: window.location.pathname,\n to: targetPath,\n });\n }\n }, [to, replace]);\n\n return null;\n}\n\n/** Options for navigation */\ninterface NavigateOptions {\n replace?: boolean;\n scrollToTop?: boolean;\n}\n\n// Navigation helper\nfunction navigate(href: string, options: NavigateOptions = {}) {\n const { replace = false, scrollToTop = true } = options;\n const from = window.location.pathname;\n const to = href.split(\"?\")[0]; // Extract pathname from href\n\n // Emit before-navigation event (can be prevented)\n const canNavigate = routerEventEmitter.emit(\"before-navigation\", { from, to });\n if (!canNavigate) {\n return; // Navigation was prevented\n }\n\n // Set navigating state to true before navigation\n currentLocation = { ...currentLocation, isNavigating: true };\n locationListeners.forEach((listener) => listener());\n\n if (replace) {\n window.history.replaceState(null, \"\", href);\n } else {\n window.history.pushState(null, \"\", href);\n }\n\n // Scroll to top immediately after pushState, before React re-renders.\n // Using instant scroll avoids race conditions where smooth scrolling\n // gets interrupted by React DOM updates, especially on Safari mobile.\n if (scrollToTop) {\n window.scrollTo({ top: 0, left: 0, behavior: \"instant\" });\n }\n\n // Update location state synchronously so there is no stale-state window\n // between pushState and the next render.\n updateLocation(false);\n\n // Emit navigation event after state is consistent\n routerEventEmitter.emit(\"navigation\", { from, to });\n}\n\nexport type LinkProps = React.PropsWithChildren<\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> & {\n href: string;\n replace?: boolean;\n /** Disable prefetching on hover (default: false - prefetch is enabled) */\n prefetch?: boolean;\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n }\n>;\n\n/**\n * Check if a URL is external (different origin).\n */\nfunction isExternalUrl(href: string): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n const url = new URL(href, window.location.origin);\n return url.origin !== window.location.origin;\n } catch {\n return false;\n }\n}\n\n// Store routes globally for prefetching (set by AppRouter)\n// Preserve across HMR in dev mode\nlet globalRoutes: RouteEntry[];\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n if (!globalWindow.__heliumGlobalRoutes) {\n globalWindow.__heliumGlobalRoutes = [];\n }\n globalRoutes = globalWindow.__heliumGlobalRoutes;\n} else {\n globalRoutes = [];\n}\n\n/**\n * Client-side navigation link.\n *\n * Intercepts left-clicks and uses the router's navigation helpers for SPA\n * navigation. Keeps normal anchor behaviour when modifier keys are used,\n * when the link is external, or when `target` / `download` attributes\n * are present.\n *\n * Automatically prefetches page chunks on hover for faster navigation.\n */\nexport function Link(props: LinkProps) {\n const {\n children,\n href,\n className,\n prefetch: prefetchProp = true,\n scrollToTop = true,\n replace: replaceProp,\n target,\n download,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n onFocus: userOnFocus,\n ...restProps\n } = props;\n\n const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Let user's onClick run first so they can call e.preventDefault()\n userOnClick?.(e);\n\n if (\n e.defaultPrevented ||\n e.button !== 0 || // only left click\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey ||\n target || // let browser handle target=\"_blank\" etc.\n download != null || // let browser handle downloads\n isExternalUrl(href) // let browser handle external links\n ) {\n return;\n }\n e.preventDefault();\n navigate(href, { replace: replaceProp, scrollToTop });\n };\n\n const onMouseEnter = async (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Prefetch the route on hover if enabled and not external (lazy-load prefetch logic)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnMouseEnter?.(e);\n };\n\n const onFocus = async (e: React.FocusEvent<HTMLAnchorElement>) => {\n // Also prefetch on focus (keyboard navigation)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnFocus?.(e);\n };\n\n return (\n <a {...restProps} href={href} target={target} download={download} onClick={onClick} onMouseEnter={onMouseEnter} onFocus={onFocus} className={className}>\n {children}\n </a>\n );\n}\n\n// AppShell props type\n/**\n * Props passed to an optional \\`AppShell\\` wrapper component used by <AppRouter />.\n *\n * \\`Component\\` — the page component to render. \\`pageProps\\` — props provided to the page.\n */\nexport type AppShellProps<TPageProps extends Record<string, unknown> = Record<string, unknown>> = {\n Component: ComponentType<TPageProps>;\n pageProps: TPageProps;\n};\n\n// Main router component\nexport function AppRouter({ AppShell }: { AppShell?: ComponentType<AppShellProps> }) {\n // useTransition for concurrent rendering - allows React to keep UI responsive during navigation\n const [isPending, startTransition] = useTransition();\n\n // Build routes once on mount (client-side only)\n const { routes, NotFound } = useMemo(() => {\n if (typeof window === \"undefined\") {\n return { routes: [], NotFound: undefined };\n }\n const result = buildRoutes();\n // Store routes globally for Link prefetching\n // In dev mode, also update the global reference to survive HMR\n if (isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n globalWindow.__heliumGlobalRoutes = result.routes;\n // Update the module-level reference as well\n globalRoutes.length = 0;\n globalRoutes.push(...result.routes);\n } else {\n globalRoutes = result.routes;\n }\n return result;\n }, []);\n\n // Use useSyncExternalStore to subscribe to location changes\n // This ensures synchronous updates when location changes\n const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);\n\n const match = useMemo(() => matchRoute(state.path, routes), [state.path, routes]);\n\n // Use matched params, or fall back to re-extracting from path using global routes during HMR\n const currentParams = match?.params ?? (isDevEnvironment() ? extractParamsFromPath(state.path) : {});\n\n // In dev mode, always read fresh searchParams from URL to handle HMR edge cases\n const currentSearchParams = isDevEnvironment() ? new URLSearchParams(window.location.search) : state.searchParams;\n\n const routerValue: RouterContext = {\n path: state.path,\n params: currentParams,\n searchParams: currentSearchParams,\n push: (href, options) => {\n // Wrap navigation in startTransition for smoother updates\n startTransition(() => {\n navigate(href, { scrollToTop: options?.scrollToTop });\n });\n },\n replace: (href, options) => {\n startTransition(() => {\n navigate(href, { replace: true, scrollToTop: options?.scrollToTop });\n });\n },\n on: (event, listener) => routerEventEmitter.on(event, listener),\n status: match ? 200 : 404,\n isNavigating: state.isNavigating,\n isPending,\n };\n\n if (!match) {\n const NotFoundComp = NotFound ?? (() => <div>Not found</div>);\n const content = <NotFoundComp />;\n\n return <RouterContext.Provider value={routerValue}>{AppShell ? <AppShell Component={NotFoundComp} pageProps={{}} /> : content}</RouterContext.Provider>;\n }\n\n const Page = match.route.Component as ComponentType<{ params: Record<string, string | string[]>; searchParams: URLSearchParams }>;\n const pageProps = {\n params: match.params,\n searchParams: currentSearchParams,\n };\n\n // Create a wrapped component that includes all layouts\n const WrappedPage = () => {\n let content = <Page {...pageProps} />;\n // Wrap page with layouts (from outer to inner)\n for (let i = match.route.layouts.length - 1; i >= 0; i--) {\n const Layout = match.route.layouts[i];\n content = <Layout>{content}</Layout>;\n }\n return content;\n };\n\n const finalContent = AppShell ? <AppShell Component={WrappedPage} pageProps={{}} /> : <WrappedPage />;\n\n return <RouterContext.Provider value={routerValue}>{finalContent}</RouterContext.Provider>;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/client/cache.ts"],"names":[],"mappings":"AAqCA,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAEhE;AAsBD,wBAAgB,GAAG,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS,CAYjD;AAED,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,MAAM,QAM5D;AAED,wBAAgB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAYxC;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,MAAM,QAqBlD;AAED,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,IAAI,cAK1E;AAED,wBAAgB,aAAa,SAkB5B;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAE9C;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC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MAAM,GAAG,IAAI,CAEnD"}
@@ -1,8 +1,9 @@
1
+ import { isDevEnvironment } from "./env.js";
1
2
  // Preserve cache across HMR by attaching to window in dev mode
2
3
  let store;
3
4
  let listeners;
4
5
  let pendingFetches;
5
- if (typeof window !== "undefined" && import.meta.env?.DEV) {
6
+ if (typeof window !== "undefined" && isDevEnvironment()) {
6
7
  const globalWindow = window;
7
8
  if (!globalWindow.__heliumCacheStore) {
8
9
  globalWindow.__heliumCacheStore = new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/client/cache.ts"],"names":[],"mappings":"AAMA,+DAA+D;AAC/D,IAAI,KAA8B,CAAC;AACnC,IAAI,SAA0C,CAAC;AAC/C,IAAI,cAA6C,CAAC;AAElD,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC;IACxD,MAAM,YAAY,GAAG,MAIpB,CAAC;IACF,IAAI,CAAC,YAAY,CAAC,kBAAkB,EAAE,CAAC;QACnC,YAAY,CAAC,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAC;IAChD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,sBAAsB,EAAE,CAAC;QACvC,YAAY,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IACpD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,sBAAsB,EAAE,CAAC;QACvC,YAAY,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IACpD,CAAC;IACD,KAAK,GAAG,YAAY,CAAC,kBAAkB,CAAC;IACxC,SAAS,GAAG,YAAY,CAAC,sBAAsB,CAAC;IAChD,cAAc,GAAG,YAAY,CAAC,sBAAsB,CAAC;AACzD,CAAC;KAAM,CAAC;IACJ,KAAK,GAAG,IAAI,GAAG,EAAE,CAAC;IAClB,SAAS,GAAG,IAAI,GAAG,EAAE,CAAC;IACtB,cAAc,GAAG,IAAI,GAA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AI,GAAW,EAAE,OAAmB;IAC/D,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,QAAQ,EAAE,CAAC;QACX,OAAO,QAAsB,CAAC;IAClC,CAAC;IACD,cAAc,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACjC,qBAAqB;IACrB,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE;QACjB,cAAc,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAW;IACzC,cAAc,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["interface CacheEntry {\n value: unknown;\n timestamp: number;\n ttl?: number; // TTL in milliseconds\n}\n\n// Preserve cache across HMR by attaching to window in dev mode\nlet store: Map<string, CacheEntry>;\nlet listeners: Set<(methodId: string) => void>;\nlet pendingFetches: Map<string, Promise<unknown>>;\n\nif (typeof window !== \"undefined\" && import.meta.env?.DEV) {\n const globalWindow = window as typeof window & {\n __heliumCacheStore?: Map<string, CacheEntry>;\n __heliumCacheListeners?: Set<(methodId: string) => void>;\n __heliumPendingFetches?: Map<string, Promise<unknown>>;\n };\n if (!globalWindow.__heliumCacheStore) {\n globalWindow.__heliumCacheStore = new Map();\n }\n if (!globalWindow.__heliumCacheListeners) {\n globalWindow.__heliumCacheListeners = new Set();\n }\n if (!globalWindow.__heliumPendingFetches) {\n globalWindow.__heliumPendingFetches = new Map();\n }\n store = globalWindow.__heliumCacheStore;\n listeners = globalWindow.__heliumCacheListeners;\n pendingFetches = globalWindow.__heliumPendingFetches;\n} else {\n store = new Map();\n listeners = new Set();\n pendingFetches = new Map();\n}\n\nconst DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes\n\nexport function cacheKey(methodId: string, args: unknown): string {\n return JSON.stringify([methodId, args ?? null]);\n}\n\nfunction methodIdFromKey(key: string): string | undefined {\n try {\n const parsed = JSON.parse(key);\n if (!Array.isArray(parsed) || parsed.length < 1) {\n return undefined;\n }\n const [methodId] = parsed;\n return typeof methodId === \"string\" ? methodId : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isExpired(entry: CacheEntry): boolean {\n if (!entry.ttl) {\n return false;\n }\n return Date.now() - entry.timestamp > entry.ttl;\n}\n\nexport function get<T>(key: string): T | undefined {\n const entry = store.get(key);\n if (!entry) {\n return undefined;\n }\n\n if (isExpired(entry)) {\n store.delete(key);\n return undefined;\n }\n\n return entry.value as T | undefined;\n}\n\nexport function set(key: string, value: unknown, ttl?: number) {\n store.set(key, {\n value,\n timestamp: Date.now(),\n ttl: ttl ?? DEFAULT_TTL,\n });\n}\n\nexport function has(key: string): boolean {\n const entry = store.get(key);\n if (!entry) {\n return false;\n }\n\n if (isExpired(entry)) {\n store.delete(key);\n return false;\n }\n\n return true;\n}\n\nexport function invalidateByMethod(methodId: string) {\n let invalidated = false;\n for (const key of store.keys()) {\n if (methodIdFromKey(key) === methodId) {\n store.delete(key);\n invalidated = true;\n }\n }\n\n for (const key of pendingFetches.keys()) {\n if (methodIdFromKey(key) === methodId) {\n pendingFetches.delete(key);\n invalidated = true;\n }\n }\n\n if (invalidated || listeners.size) {\n for (const listener of listeners) {\n listener(methodId);\n }\n }\n}\n\nexport function subscribeInvalidations(listener: (methodId: string) => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\nexport function invalidateAll() {\n const methodIds = new Set<string>();\n for (const key of store.keys()) {\n try {\n const parsed = JSON.parse(key);\n if (Array.isArray(parsed) && parsed.length > 0) {\n methodIds.add(parsed[0]);\n }\n } catch {\n // Ignore malformed keys\n }\n }\n store.clear();\n for (const methodId of methodIds) {\n for (const listener of listeners) {\n listener(methodId);\n }\n }\n}\n\n/**\n * Check if a fetch is currently pending for a given cache key.\n */\nexport function isPending(key: string): boolean {\n return pendingFetches.has(key);\n}\n\n/**\n * Get an existing pending fetch promise, or undefined if none.\n */\nexport function getPendingFetch<T>(key: string): Promise<T> | undefined {\n return pendingFetches.get(key) as Promise<T> | undefined;\n}\n\n/**\n * Register a pending fetch. Returns the promise.\n * If a fetch for this key is already pending, returns the existing promise.\n */\nexport function setPendingFetch<T>(key: string, promise: Promise<T>): Promise<T> {\n const existing = pendingFetches.get(key);\n if (existing) {\n return existing as Promise<T>;\n }\n pendingFetches.set(key, promise);\n // Clean up when done\n promise.finally(() => {\n pendingFetches.delete(key);\n });\n return promise;\n}\n\n/**\n * Clear a pending fetch (if you need to cancel/reset).\n */\nexport function clearPendingFetch(key: string): void {\n pendingFetches.delete(key);\n}\n"]}
1
+ {"version":3,"file":"cache.js","sourceRoot":"","sources":["../../src/client/cache.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAQ5C,+DAA+D;AAC/D,IAAI,KAA8B,CAAC;AACnC,IAAI,SAA0C,CAAC;AAC/C,IAAI,cAA6C,CAAC;AAElD,IAAI,OAAO,MAAM,KAAK,WAAW,IAAI,gBAAgB,EAAE,EAAE,CAAC;IACtD,MAAM,YAAY,GAAG,MAIpB,CAAC;IACF,IAAI,CAAC,YAAY,CAAC,kBAAkB,EAAE,CAAC;QACnC,YAAY,CAAC,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAC;IAChD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,sBAAsB,EAAE,CAAC;QACvC,YAAY,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IACpD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,sBAAsB,EAAE,CAAC;QACvC,YAAY,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IACpD,CAAC;IACD,KAAK,GAAG,YAAY,CAAC,kBAAkB,CAAC;IACxC,SAAS,GAAG,YAAY,CAAC,sBAAsB,CAAC;IAChD,cAAc,GAAG,YAAY,CAA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ED;;GAEG;AACH,MAAM,UAAU,eAAe,CAAI,GAAW;IAC1C,OAAO,cAAc,CAAC,GAAG,CAAC,GAAG,CAA2B,CAAC;AAC7D,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe,CAAI,GAAW,EAAE,OAAmB;IAC/D,MAAM,QAAQ,GAAG,cAAc,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzC,IAAI,QAAQ,EAAE,CAAC;QACX,OAAO,QAAsB,CAAC;IAClC,CAAC;IACD,cAAc,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;IACjC,qBAAqB;IACrB,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE;QACjB,cAAc,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iBAAiB,CAAC,GAAW;IACzC,cAAc,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC","sourcesContent":["import { isDevEnvironment } from \"./env.js\";\n\ninterface CacheEntry {\n value: unknown;\n timestamp: number;\n ttl?: number; // TTL in milliseconds\n}\n\n// Preserve cache across HMR by attaching to window in dev mode\nlet store: Map<string, CacheEntry>;\nlet listeners: Set<(methodId: string) => void>;\nlet pendingFetches: Map<string, Promise<unknown>>;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & {\n __heliumCacheStore?: Map<string, CacheEntry>;\n __heliumCacheListeners?: Set<(methodId: string) => void>;\n __heliumPendingFetches?: Map<string, Promise<unknown>>;\n };\n if (!globalWindow.__heliumCacheStore) {\n globalWindow.__heliumCacheStore = new Map();\n }\n if (!globalWindow.__heliumCacheListeners) {\n globalWindow.__heliumCacheListeners = new Set();\n }\n if (!globalWindow.__heliumPendingFetches) {\n globalWindow.__heliumPendingFetches = new Map();\n }\n store = globalWindow.__heliumCacheStore;\n listeners = globalWindow.__heliumCacheListeners;\n pendingFetches = globalWindow.__heliumPendingFetches;\n} else {\n store = new Map();\n listeners = new Set();\n pendingFetches = new Map();\n}\n\nconst DEFAULT_TTL = 5 * 60 * 1000; // 5 minutes\n\nexport function cacheKey(methodId: string, args: unknown): string {\n return JSON.stringify([methodId, args ?? null]);\n}\n\nfunction methodIdFromKey(key: string): string | undefined {\n try {\n const parsed = JSON.parse(key);\n if (!Array.isArray(parsed) || parsed.length < 1) {\n return undefined;\n }\n const [methodId] = parsed;\n return typeof methodId === \"string\" ? methodId : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isExpired(entry: CacheEntry): boolean {\n if (!entry.ttl) {\n return false;\n }\n return Date.now() - entry.timestamp > entry.ttl;\n}\n\nexport function get<T>(key: string): T | undefined {\n const entry = store.get(key);\n if (!entry) {\n return undefined;\n }\n\n if (isExpired(entry)) {\n store.delete(key);\n return undefined;\n }\n\n return entry.value as T | undefined;\n}\n\nexport function set(key: string, value: unknown, ttl?: number) {\n store.set(key, {\n value,\n timestamp: Date.now(),\n ttl: ttl ?? DEFAULT_TTL,\n });\n}\n\nexport function has(key: string): boolean {\n const entry = store.get(key);\n if (!entry) {\n return false;\n }\n\n if (isExpired(entry)) {\n store.delete(key);\n return false;\n }\n\n return true;\n}\n\nexport function invalidateByMethod(methodId: string) {\n let invalidated = false;\n for (const key of store.keys()) {\n if (methodIdFromKey(key) === methodId) {\n store.delete(key);\n invalidated = true;\n }\n }\n\n for (const key of pendingFetches.keys()) {\n if (methodIdFromKey(key) === methodId) {\n pendingFetches.delete(key);\n invalidated = true;\n }\n }\n\n if (invalidated || listeners.size) {\n for (const listener of listeners) {\n listener(methodId);\n }\n }\n}\n\nexport function subscribeInvalidations(listener: (methodId: string) => void) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n}\n\nexport function invalidateAll() {\n const methodIds = new Set<string>();\n for (const key of store.keys()) {\n try {\n const parsed = JSON.parse(key);\n if (Array.isArray(parsed) && parsed.length > 0) {\n methodIds.add(parsed[0]);\n }\n } catch {\n // Ignore malformed keys\n }\n }\n store.clear();\n for (const methodId of methodIds) {\n for (const listener of listeners) {\n listener(methodId);\n }\n }\n}\n\n/**\n * Check if a fetch is currently pending for a given cache key.\n */\nexport function isPending(key: string): boolean {\n return pendingFetches.has(key);\n}\n\n/**\n * Get an existing pending fetch promise, or undefined if none.\n */\nexport function getPendingFetch<T>(key: string): Promise<T> | undefined {\n return pendingFetches.get(key) as Promise<T> | undefined;\n}\n\n/**\n * Register a pending fetch. Returns the promise.\n * If a fetch for this key is already pending, returns the existing promise.\n */\nexport function setPendingFetch<T>(key: string, promise: Promise<T>): Promise<T> {\n const existing = pendingFetches.get(key);\n if (existing) {\n return existing as Promise<T>;\n }\n pendingFetches.set(key, promise);\n // Clean up when done\n promise.finally(() => {\n pendingFetches.delete(key);\n });\n return promise;\n}\n\n/**\n * Clear a pending fetch (if you need to cancel/reset).\n */\nexport function clearPendingFetch(key: string): void {\n pendingFetches.delete(key);\n}\n"]}
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Detect development mode without relying on Vite-specific `import.meta.env`.
3
+ */
4
+ export declare function isDevEnvironment(): boolean;
5
+ //# sourceMappingURL=env.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.d.ts","sourceRoot":"","sources":["../../src/client/env.ts"],"names":[],"mappings":"AAUA;;GAEG;AACH,wBAAgB,gBAAgB,IAAI,OAAO,CAW1C"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Detect development mode without relying on Vite-specific `import.meta.env`.
3
+ */
4
+ export function isDevEnvironment() {
5
+ if (typeof __HELIUM_DEV__ !== "undefined") {
6
+ return __HELIUM_DEV__;
7
+ }
8
+ const nodeEnv = globalThis.process?.env?.NODE_ENV;
9
+ if (typeof nodeEnv === "string") {
10
+ return nodeEnv !== "production";
11
+ }
12
+ return false;
13
+ }
14
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../../src/client/env.ts"],"names":[],"mappings":"AAUA;;GAEG;AACH,MAAM,UAAU,gBAAgB;IAC5B,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE,CAAC;QACxC,OAAO,cAAc,CAAC;IAC1B,CAAC;IAED,MAAM,OAAO,GAAI,UAAgC,CAAC,OAAO,EAAE,GAAG,EAAE,QAAQ,CAAC;IACzE,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAC9B,OAAO,OAAO,KAAK,YAAY,CAAC;IACpC,CAAC;IAED,OAAO,KAAK,CAAC;AACjB,CAAC","sourcesContent":["declare const __HELIUM_DEV__: boolean;\n\ntype GlobalWithProcess = typeof globalThis & {\n process?: {\n env?: {\n NODE_ENV?: string;\n };\n };\n};\n\n/**\n * Detect development mode without relying on Vite-specific `import.meta.env`.\n */\nexport function isDevEnvironment(): boolean {\n if (typeof __HELIUM_DEV__ !== \"undefined\") {\n return __HELIUM_DEV__;\n }\n\n const nodeEnv = (globalThis as GlobalWithProcess).process?.env?.NODE_ENV;\n if (typeof nodeEnv === \"string\") {\n return nodeEnv !== \"production\";\n }\n\n return false;\n}"]}
@@ -0,0 +1,48 @@
1
+ import type http from "http";
2
+ /**
3
+ * Extracts the client IP address from an HTTP request, taking into account proxy configurations.
4
+ *
5
+ * When behind proxies (like Vercel, Cloudflare, AWS ALB, etc.), the X-Forwarded-For header
6
+ * contains a chain of IP addresses. The format is: "client, proxy1, proxy2, ..."
7
+ *
8
+ * @param req - The HTTP request object
9
+ * @param trustProxyDepth - Number of proxy levels to trust
10
+ * - 0: Only use req.socket.remoteAddress (no proxy trust)
11
+ * - 1: Trust 1 proxy level (get the last IP before your server)
12
+ * - 2+: Trust multiple proxy levels (for complex setups)
13
+ *
14
+ * Examples:
15
+ * - trustProxyDepth=0: Direct connection, no proxies
16
+ * X-Forwarded-For: ignored
17
+ * Result: req.socket.remoteAddress
18
+ *
19
+ * - trustProxyDepth=1: Behind one proxy (e.g., Vercel, Netlify)
20
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1"
21
+ * Result: "203.0.113.1" (client IP)
22
+ *
23
+ * - trustProxyDepth=2: Behind two proxies (e.g., Cloudflare -> Load Balancer)
24
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
25
+ * Result: "203.0.113.1" (client IP)
26
+ *
27
+ * Common configurations:
28
+ * - Vercel/Netlify/Railway: trustProxyDepth=1
29
+ * - Cloudflare -> Origin: trustProxyDepth=1 or 2 (depending on your setup)
30
+ * - AWS ALB -> EC2: trustProxyDepth=1
31
+ * - Nginx -> Node: trustProxyDepth=1
32
+ * - Cloudflare -> Nginx -> Node: trustProxyDepth=2
33
+ */
34
+ export declare function extractClientIP(req: http.IncomingMessage, trustProxyDepth?: number): string;
35
+ /**
36
+ * Alternative extraction method that works from the right (trusts the rightmost IPs).
37
+ * This is useful when you want to trust the last N proxies in the chain.
38
+ *
39
+ * @param req - The HTTP request object
40
+ * @param trustProxyDepth - Number of proxy levels to trust from the right
41
+ *
42
+ * Example:
43
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
44
+ * trustProxyDepth=1: Result is "198.51.100.1" (skip the last trusted proxy)
45
+ * trustProxyDepth=2: Result is "203.0.113.1" (skip the last 2 trusted proxies)
46
+ */
47
+ export declare function extractClientIPFromRight(req: http.IncomingMessage, trustProxyDepth?: number): string;
48
+ //# sourceMappingURL=ipExtractor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipExtractor.d.ts","sourceRoot":"","sources":["../../src/server/ipExtractor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,eAAe,GAAE,MAAU,GAAG,MAAM,CAqC9F;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,eAAe,GAAE,MAAU,GAAG,MAAM,CAsBvG"}
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Extracts the client IP address from an HTTP request, taking into account proxy configurations.
3
+ *
4
+ * When behind proxies (like Vercel, Cloudflare, AWS ALB, etc.), the X-Forwarded-For header
5
+ * contains a chain of IP addresses. The format is: "client, proxy1, proxy2, ..."
6
+ *
7
+ * @param req - The HTTP request object
8
+ * @param trustProxyDepth - Number of proxy levels to trust
9
+ * - 0: Only use req.socket.remoteAddress (no proxy trust)
10
+ * - 1: Trust 1 proxy level (get the last IP before your server)
11
+ * - 2+: Trust multiple proxy levels (for complex setups)
12
+ *
13
+ * Examples:
14
+ * - trustProxyDepth=0: Direct connection, no proxies
15
+ * X-Forwarded-For: ignored
16
+ * Result: req.socket.remoteAddress
17
+ *
18
+ * - trustProxyDepth=1: Behind one proxy (e.g., Vercel, Netlify)
19
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1"
20
+ * Result: "203.0.113.1" (client IP)
21
+ *
22
+ * - trustProxyDepth=2: Behind two proxies (e.g., Cloudflare -> Load Balancer)
23
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
24
+ * Result: "203.0.113.1" (client IP)
25
+ *
26
+ * Common configurations:
27
+ * - Vercel/Netlify/Railway: trustProxyDepth=1
28
+ * - Cloudflare -> Origin: trustProxyDepth=1 or 2 (depending on your setup)
29
+ * - AWS ALB -> EC2: trustProxyDepth=1
30
+ * - Nginx -> Node: trustProxyDepth=1
31
+ * - Cloudflare -> Nginx -> Node: trustProxyDepth=2
32
+ */
33
+ export function extractClientIP(req, trustProxyDepth = 0) {
34
+ // If not trusting any proxies, return the direct connection IP
35
+ if (trustProxyDepth === 0) {
36
+ return req.socket.remoteAddress || "unknown";
37
+ }
38
+ // Get X-Forwarded-For header
39
+ const forwardedFor = req.headers["x-forwarded-for"];
40
+ if (!forwardedFor) {
41
+ // No X-Forwarded-For header, fall back to direct connection
42
+ return req.socket.remoteAddress || "unknown";
43
+ }
44
+ // Parse X-Forwarded-For header (can be a string or array of strings)
45
+ const forwardedIPs = (Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor)
46
+ .split(",")
47
+ .map((ip) => ip.trim())
48
+ .filter((ip) => ip.length > 0);
49
+ if (forwardedIPs.length === 0) {
50
+ // Empty X-Forwarded-For, fall back to direct connection
51
+ return req.socket.remoteAddress || "unknown";
52
+ }
53
+ // The client IP is at the beginning of the chain
54
+ // We trust the chain up to trustProxyDepth levels
55
+ // Format: [clientIP, proxy1, proxy2, ..., lastProxy]
56
+ // We want the clientIP, but we need to verify we have enough trusted proxies
57
+ if (forwardedIPs.length < trustProxyDepth) {
58
+ // Not enough IPs in the chain, the chain might be incomplete or spoofed
59
+ // Fall back to direct connection for safety
60
+ return req.socket.remoteAddress || "unknown";
61
+ }
62
+ // Return the client IP (first in the chain)
63
+ return forwardedIPs[0];
64
+ }
65
+ /**
66
+ * Alternative extraction method that works from the right (trusts the rightmost IPs).
67
+ * This is useful when you want to trust the last N proxies in the chain.
68
+ *
69
+ * @param req - The HTTP request object
70
+ * @param trustProxyDepth - Number of proxy levels to trust from the right
71
+ *
72
+ * Example:
73
+ * X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
74
+ * trustProxyDepth=1: Result is "198.51.100.1" (skip the last trusted proxy)
75
+ * trustProxyDepth=2: Result is "203.0.113.1" (skip the last 2 trusted proxies)
76
+ */
77
+ export function extractClientIPFromRight(req, trustProxyDepth = 0) {
78
+ if (trustProxyDepth === 0) {
79
+ return req.socket.remoteAddress || "unknown";
80
+ }
81
+ const forwardedFor = req.headers["x-forwarded-for"];
82
+ if (!forwardedFor) {
83
+ return req.socket.remoteAddress || "unknown";
84
+ }
85
+ const forwardedIPs = (Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor)
86
+ .split(",")
87
+ .map((ip) => ip.trim())
88
+ .filter((ip) => ip.length > 0);
89
+ if (forwardedIPs.length === 0) {
90
+ return req.socket.remoteAddress || "unknown";
91
+ }
92
+ // Calculate which IP to trust by skipping the rightmost N trusted proxies
93
+ const clientIPIndex = Math.max(0, forwardedIPs.length - trustProxyDepth - 1);
94
+ return forwardedIPs[clientIPIndex];
95
+ }
96
+ //# sourceMappingURL=ipExtractor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ipExtractor.js","sourceRoot":"","sources":["../../src/server/ipExtractor.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,eAAe,CAAC,GAAyB,EAAE,kBAA0B,CAAC;IAClF,+DAA+D;IAC/D,IAAI,eAAe,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,6BAA6B;IAC7B,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACpD,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,4DAA4D;QAC5D,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,qEAAqE;IACrE,MAAM,YAAY,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;SACrF,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;SACtB,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAEnC,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,wDAAwD;QACxD,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAA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,YAAY,CAAC,MAAM,GAAG,eAAe,GAAG,CAAC,CAAC,CAAC;IAC7E,OAAO,YAAY,CAAC,aAAa,CAAC,CAAC;AACvC,CAAC"}
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=deepEqual.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepEqual.d.ts","sourceRoot":"","sources":["../../src/utils/deepEqual.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ //# sourceMappingURL=deepEqual.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"deepEqual.js","sourceRoot":"","sources":["../../src/utils/deepEqual.ts"],"names":[],"mappings":""}
@@ -0,0 +1,2 @@
1
+ export declare function formatError(err: unknown): string;
2
+ //# sourceMappingURL=formatError.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatError.d.ts","sourceRoot":"","sources":["../../src/utils/formatError.ts"],"names":[],"mappings":"AAAA,wBAAgB,WAAW,CAAC,GAAG,EAAE,OAAO,GAAG,MAAM,CAgBhD"}
@@ -0,0 +1,18 @@
1
+ export function formatError(err) {
2
+ console.log("🚀 ~ formatError ~ err:", err);
3
+ if (err instanceof Error) {
4
+ return err.message;
5
+ }
6
+ if (typeof err === "object" && err !== null) {
7
+ if ("message" in err) {
8
+ return String(err.message);
9
+ }
10
+ // Format Record<string, string> errors
11
+ return JSON.stringify(err, null, 2);
12
+ }
13
+ if (typeof err === "string") {
14
+ return err;
15
+ }
16
+ return String(err);
17
+ }
18
+ //# sourceMappingURL=formatError.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formatError.js","sourceRoot":"","sources":["../../src/utils/formatError.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,WAAW,CAAC,GAAY;IACpC,OAAO,CAAC,GAAG,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAC5C,IAAI,GAAG,YAAY,KAAK,EAAE,CAAC;QACvB,OAAO,GAAG,CAAC,OAAO,CAAC;IACvB,CAAC;IACD,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,EAAE,CAAC;QAC1C,IAAI,SAAS,IAAI,GAAG,EAAE,CAAC;YACnB,OAAO,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC;QAC/B,CAAC;QACD,uCAAuC;QACvC,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC;IACxC,CAAC;IACD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE,CAAC;QAC1B,OAAO,GAAG,CAAC;IACf,CAAC;IACD,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;AACvB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"heliumPlugin.d.ts","sourceRoot":"","sources":["../../src/vite/heliumPlugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAkBnC,MAAM,CAAC,OAAO,UAAU,MAAM,IAAI,MAAM,CAqavC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAiBrG;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAUhD"}
1
+ {"version":3,"file":"heliumPlugin.d.ts","sourceRoot":"","sources":["../../src/vite/heliumPlugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,MAAM,CAAC;AAkBnC,MAAM,CAAC,OAAO,UAAU,MAAM,IAAI,MAAM,CAsavC;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAEzD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAiBrG;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAUhD"}
@@ -103,6 +103,7 @@ export default function helium() {
103
103
  },
104
104
  define: {
105
105
  ...envDefines,
106
+ __HELIUM_DEV__: JSON.stringify(mode !== "production"),
106
107
  __HELIUM_RPC_TRANSPORT__: JSON.stringify(rpcClientConfig.transport),
107
108
  __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__: JSON.stringify(rpcClientConfig.autoHttpOnMobile),
108
109
  __HELIUM_RPC_TOKEN_VALIDITY_MS__: JSON.stringify(rpcClientConfig.tokenValidityMs),
@@ -1 +1 @@
1
- {"version":3,"file":"heliumPlugin.js","sourceRoot":"","sources":["../../src/vite/heliumPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AACzC,OAAO,EACH,iCAAiC,EACjC,gCAAgC,EAChC,mCAAmC,EACnC,UAAU,EACV,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,GAC7B,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,uBAAuB,EA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GAGG;AACH,MAAM,UAAU,cAAc,CAAC,QAA4B,EAAE,IAAY,EAAE,SAAiB;IACxF,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,CAAC,YAAY,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3C,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;IACnD,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;QACzC,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,MAAM,UAAU,GAAG,gBAAgB,CAAC,QAAQ,CAAC,CAAC;IAC9C,OAAO,UAAU,KAAK,SAAS,IAAI,UAAU,CAAC,UAAU,CAAC,GAAG,SAAS,GAAG,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACtC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;IACtD,IAAI,CAAC;QACD,IAAI,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YAC9B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,EAAE,CAAC,UAAU,CAAC,YAAY,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QAC1C,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACL,6EAA6E;IACjF,CAAC;AACL,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { Plugin } from \"vite\";\n\nimport { clearConfigCache, getRpcClientConfig, loadConfig } from \"../server/config.js\";\nimport { attachToDevServer } from \"../server/devServer.js\";\nimport { createEnvDefines, injectEnvToProcess, loadEnvFiles } from \"../utils/envLoader.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n RESOLVED_VIRTUAL_CLIENT_MODULE_ID,\n RESOLVED_VIRTUAL_ENTRY_MODULE_ID,\n RESOLVED_VIRTUAL_SERVER_MANIFEST_ID,\n SERVER_DIR,\n VIRTUAL_CLIENT_MODULE_ID,\n VIRTUAL_ENTRY_MODULE_ID,\n VIRTUAL_SERVER_MANIFEST_ID,\n} from \"./paths.js\";\nimport { checkRouteCollisions, scanServerExports } from \"./scanner.js\";\nimport { generateClientModule, generateEntryModule, generateServerManifest, generateTypeDefinitions } from \"./virtualServerModule.js\";\n\nexport default function helium(): Plugin {\n let root = process.cwd();\n const serverDir = normalizeToPosix(SERVER_DIR);\n\n return {\n name: \"vite-plugin-helium\",\n enforce: \"pre\",\n configResolved(config) {\n root = config.root;\n\n // Load and inject environment variables\n const mode = config.mode || \"development\";\n const envVars = loadEnvFiles({ root, mode });\n injectEnvToProcess(envVars);\n },\n transformIndexHtml: {\n order: \"pre\",\n handler(html, _ctx) {\n // Check if HTML already has a script tag for entry\n if (html.includes(\"src/main.tsx\") || html.includes(\"src/main.ts\")) {\n return html; // User has their own entry, don't modify\n }\n\n // Ensure root div exists\n let modifiedHtml = html;\n if (!modifiedHtml.includes('id=\"root\"')) {\n modifiedHtml = modifiedHtml.replace(\"<body>\", '<body>\\n <div id=\"root\"></div>');\n }\n\n // Generate physical entry file\n const heliumDir = path.join(root, \"node_modules\", \".heliumts\");\n if (!fs.existsSync(heliumDir)) {\n fs.mkdirSync(heliumDir, { recursive: true });\n }\n const entryPath = path.join(heliumDir, \"entry.tsx\");\n fs.writeFileSync(entryPath, generateEntryModule());\n\n // Return with tags to inject the entry (runtime config is fetched by the client)\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: \"/node_modules/.heliumts/entry.tsx\",\n },\n injectTo: \"body\",\n },\n ];\n },\n },\n async config(config) {\n // Load environment variables before config is finalized\n const mode = config.mode || \"development\";\n const envVars = loadEnvFiles({ root, mode });\n\n // Create defines for client-side env variables\n const envDefines = createEnvDefines(envVars);\n\n // Load helium config to get client-side RPC transport settings\n const heliumConfig = await loadConfig(root);\n const rpcClientConfig = getRpcClientConfig(heliumConfig);\n\n // Provide default index.html if none exists\n return {\n appType: \"spa\",\n optimizeDeps: {\n include: [\"react-dom/client\"],\n // Exclude helium from pre-bundling since it's the framework itself\n // This ensures changes to helium are picked up immediately\n exclude: [\"heliumts\", \"heliumts/client\", \"heliumts/server\", \"heliumts/vite\"],\n },\n // SSR configuration to properly isolate server-only code\n ssr: {\n // Externalize Node.js built-in modules - these should never be bundled\n external: [\"util\", \"zlib\", \"http\", \"https\", \"http2\", \"fs\", \"path\", \"crypto\", \"stream\", \"os\", \"url\", \"net\", \"tls\", \"child_process\", \"worker_threads\"],\n // Don't externalize heliumts - let the plugin handle the client/server split\n noExternal: [\"heliumts\"],\n },\n // Ensure Node.js built-ins are not bundled for client\n build: {\n rollupOptions: {\n external: [\n // Node.js built-in modules should never be in client bundle\n /^node:/,\n \"util\",\n \"zlib\",\n \"http\",\n \"https\",\n \"http2\",\n \"fs\",\n \"path\",\n \"crypto\",\n \"stream\",\n \"os\",\n \"url\",\n \"net\",\n \"tls\",\n \"child_process\",\n \"worker_threads\",\n ],\n },\n },\n define: {\n ...envDefines,\n __HELIUM_RPC_TRANSPORT__: JSON.stringify(rpcClientConfig.transport),\n __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__: JSON.stringify(rpcClientConfig.autoHttpOnMobile),\n __HELIUM_RPC_TOKEN_VALIDITY_MS__: JSON.stringify(rpcClientConfig.tokenValidityMs),\n },\n };\n },\n resolveId(id, importer) {\n if (id === VIRTUAL_CLIENT_MODULE_ID) {\n if (isServerModule(importer, root, serverDir)) {\n return null;\n }\n return RESOLVED_VIRTUAL_CLIENT_MODULE_ID;\n }\n if (id === VIRTUAL_SERVER_MANIFEST_ID) {\n return RESOLVED_VIRTUAL_SERVER_MANIFEST_ID;\n }\n if (id === VIRTUAL_ENTRY_MODULE_ID) {\n // Add .tsx extension so Vite knows it contains JSX\n return RESOLVED_VIRTUAL_ENTRY_MODULE_ID + \".tsx\";\n }\n // Intercept heliumts/server imports from client code\n if (id === \"heliumts/server\") {\n // If imported from server code, let it resolve normally\n if (isServerModule(importer, root, serverDir)) {\n return null;\n }\n // For client code, redirect to virtual client module\n return RESOLVED_VIRTUAL_CLIENT_MODULE_ID;\n }\n return null;\n },\n load(id) {\n if (id === RESOLVED_VIRTUAL_CLIENT_MODULE_ID) {\n const { methods } = scanServerExports(root);\n return generateClientModule(methods);\n }\n if (id === RESOLVED_VIRTUAL_SERVER_MANIFEST_ID) {\n const { methods, httpHandlers, middleware, workers } = scanServerExports(root);\n return generateServerManifest(methods, httpHandlers, middleware, workers);\n }\n if (id === RESOLVED_VIRTUAL_ENTRY_MODULE_ID + \".tsx\") {\n return generateEntryModule();\n }\n },\n buildStart() {\n const { methods } = scanServerExports(root);\n const dts = generateTypeDefinitions(methods, root);\n const typesDir = path.join(root, \"src\", \"types\");\n const dtsPath = path.join(typesDir, \"heliumts-server.d.ts\");\n\n // Ensure src/types exists\n if (!fs.existsSync(typesDir)) {\n fs.mkdirSync(typesDir, { recursive: true });\n }\n\n // At build start we always allow writing the canonical set.\n // Only skip if content is identical to avoid needless TS invalidation.\n if (!fs.existsSync(dtsPath) || fs.readFileSync(dtsPath, \"utf-8\") !== dts) {\n fs.writeFileSync(dtsPath, dts);\n touchTsConfig(root);\n }\n\n // Check for route collisions in pages directory\n checkRouteCollisions(root);\n },\n configureServer(server) {\n // Add middleware to handle HTML fallback for nested routes\n // This ensures that routes like /docs/guides/auth properly serve index.html\n // so the client-side router can handle them\n server.middlewares.use((req, res, next) => {\n const url = req.url || \"\";\n const cleanUrl = url.split(\"?\")[0];\n\n // Skip if:\n // - Has file extension (asset request)\n // - Is an API/special endpoint\n // - Is a dev server endpoint\n if (\n path.extname(cleanUrl) !== \"\" ||\n cleanUrl.startsWith(\"/api\") ||\n cleanUrl.startsWith(\"/webhooks\") ||\n cleanUrl.startsWith(\"/auth\") ||\n cleanUrl.startsWith(\"/@\") ||\n cleanUrl.startsWith(\"/__helium__\")\n ) {\n return next();\n }\n\n // For all other routes (including nested paths like /docs/guides/auth),\n // rewrite to index.html so Vite serves it and the client-side router handles routing\n req.url = \"/index.html\";\n next();\n });\n\n /**\n * Write type definitions only if content has changed.\n * This prevents unnecessary TypeScript recompilation.\n *\n * When `allowFewer` is false (default) the file will NOT be\n * overwritten if the new content has fewer method declarations\n * than the existing file — this guards against writing a\n * degraded .d.ts while the user's file is only partially saved.\n */\n const writeTypesIfChanged = (dts: string, allowFewer = false): boolean => {\n const typesDir = path.join(root, \"src\", \"types\");\n const dtsPath = path.join(typesDir, \"heliumts-server.d.ts\");\n\n if (!fs.existsSync(typesDir)) {\n fs.mkdirSync(typesDir, { recursive: true });\n }\n\n // Check if file exists and content is the same\n if (fs.existsSync(dtsPath)) {\n const existing = fs.readFileSync(dtsPath, \"utf-8\");\n if (existing === dts) {\n return false; // No change needed\n }\n\n // Guard: don't overwrite with fewer methods unless explicitly allowed\n // (e.g. on unlink). This prevents losing types during partial saves.\n if (!allowFewer) {\n const countExports = (s: string) => (s.match(/export const \\w+:/g) || []).length;\n const existingCount = countExports(existing);\n const newCount = countExports(dts);\n if (newCount < existingCount) {\n log(\"info\", `Skipping type generation: found ${newCount} methods, existing has ${existingCount} (likely partial save)`);\n return false;\n }\n }\n }\n\n fs.writeFileSync(dtsPath, dts);\n\n // Touch tsconfig.json to force the TypeScript language server\n // to reload the project. Without this, TS may cache stale\n // module augmentations and autocomplete won't reflect the\n // new methods until a manual restart.\n touchTsConfig(root);\n\n return true; // File was written\n };\n\n const regenerateTypes = (allowFewer = false): boolean => {\n try {\n const { methods } = scanServerExports(root);\n const dts = generateTypeDefinitions(methods, root);\n return writeTypesIfChanged(dts, allowFewer);\n } catch (e) {\n log(\"error\", \"Failed to regenerate types\", e);\n return false;\n }\n };\n\n // Debounce timer for file changes\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n const DEBOUNCE_DELAY = 300; // ms — long enough for format-on-save to finish\n\n const handleServerFileChange = async (allowFewer = false) => {\n // Regenerate type definitions\n regenerateTypes(allowFewer);\n\n // Invalidate the virtual modules so they get regenerated\n const clientModule = server.environments.client?.moduleGraph.getModuleById(RESOLVED_VIRTUAL_CLIENT_MODULE_ID);\n const serverModule = server.environments.ssr?.moduleGraph.getModuleById(RESOLVED_VIRTUAL_SERVER_MANIFEST_ID);\n\n if (clientModule) {\n server.environments.client?.moduleGraph.invalidateModule(clientModule);\n }\n if (serverModule) {\n server.environments.ssr?.moduleGraph.invalidateModule(serverModule);\n }\n\n // Reload the server manifest and re-register methods\n try {\n // Clear config cache to ensure fresh config is loaded\n clearConfigCache();\n const config = await loadConfig(root);\n const mod = await server.ssrLoadModule(VIRTUAL_SERVER_MANIFEST_ID);\n const registerAll = mod.registerAll;\n const httpHandlers = mod.httpHandlers || [];\n const middlewareHandler = mod.middlewareHandler || null;\n const workers = mod.workers || [];\n\n // Update the dev server registry with new methods and HTTP handlers\n if (server.httpServer) {\n attachToDevServer(\n server.httpServer,\n (registry, httpRouter) => {\n registerAll(registry);\n httpRouter.registerRoutes(httpHandlers);\n if (middlewareHandler) {\n registry.setMiddleware(middlewareHandler);\n httpRouter.setMiddleware(middlewareHandler);\n }\n },\n config,\n workers\n );\n }\n } catch (e) {\n log(\"error\", \"Failed to reload Helium server manifest\", e);\n }\n\n // Trigger HMR for any client code that imports heliumts/server\n server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n };\n\n // Watch server directory for changes\n const serverPath = path.join(root, serverDir);\n server.watcher.add(serverPath);\n\n // Watch config files for changes\n const configFiles = [\"helium.config.ts\", \"helium.config.js\", \"helium.config.mjs\"];\n for (const configFile of configFiles) {\n const configPath = path.join(root, configFile);\n if (fs.existsSync(configPath)) {\n server.watcher.add(configPath);\n }\n }\n\n /**\n * Debounced handler for server file changes.\n * This prevents multiple rapid regenerations during file saves.\n * @param allowFewer - pass true when files are deleted, so the\n * method count is allowed to decrease.\n */\n let pendingAllowFewer = false;\n const debouncedHandleServerFileChange = (allowFewer = false) => {\n // If any event in the batch is an unlink, honour it\n if (allowFewer) {\n pendingAllowFewer = true;\n }\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n const shouldAllowFewer = pendingAllowFewer;\n pendingAllowFewer = false;\n handleServerFileChange(shouldAllowFewer);\n }, DEBOUNCE_DELAY);\n };\n\n server.watcher.on(\"change\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file changed, regenerate everything\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange();\n }\n\n // If config file changed, reload config and regenerate\n if (configFiles.some((cf) => normalized === cf)) {\n log(\"info\", `Config file changed: ${normalized}`);\n debouncedHandleServerFileChange();\n }\n });\n\n server.watcher.on(\"add\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file was added, regenerate everything\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange();\n }\n });\n\n server.watcher.on(\"unlink\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file was removed, regenerate (allow fewer methods)\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange(true);\n }\n });\n\n // We hook into the server start to attach our RPC server\n server.httpServer?.on(\"listening\", async () => {\n try {\n // Load config\n const config = await loadConfig(root);\n\n // Load the manifest using Vite's SSR loader\n // This allows us to load TS files directly and handle dependencies\n const mod = await server.ssrLoadModule(VIRTUAL_SERVER_MANIFEST_ID);\n const registerAll = mod.registerAll;\n const httpHandlers = mod.httpHandlers || [];\n const middlewareHandler = mod.middlewareHandler || null;\n const workers = mod.workers || [];\n\n if (server.httpServer) {\n attachToDevServer(\n server.httpServer,\n (registry, httpRouter) => {\n registerAll(registry);\n httpRouter.registerRoutes(httpHandlers);\n if (middlewareHandler) {\n registry.setMiddleware(middlewareHandler);\n httpRouter.setMiddleware(middlewareHandler);\n }\n },\n config,\n workers\n );\n }\n } catch (e) {\n log(\"error\", \"Failed to attach Helium RPC server\", e);\n }\n });\n },\n };\n}\n\n/**\n * Convert file path to POSIX format\n * @internal Exported for testing\n */\nexport function normalizeToPosix(filePath: string): string {\n return filePath.split(path.sep).join(\"/\");\n}\n\n/**\n * Check if an importer is a server module\n * @internal Exported for testing\n */\nexport function isServerModule(importer: string | undefined, root: string, serverDir: string): boolean {\n if (!importer || importer.startsWith(\"\\0\")) {\n return false;\n }\n\n const [importerPath] = importer.split(\"?\");\n if (!importerPath) {\n return false;\n }\n\n const relative = path.relative(root, importerPath);\n if (!relative || relative.startsWith(\"..\")) {\n return false;\n }\n\n const normalized = normalizeToPosix(relative);\n return normalized === serverDir || normalized.startsWith(`${serverDir}/`);\n}\n\n/**\n * Touch the project's tsconfig.json to force the TypeScript language server\n * to reload the project and pick up changed module augmentations.\n *\n * TS language server watches tsconfig.json for changes. When a `.d.ts` file\n * with `declare module` augmentations is regenerated, TS doesn't always\n * detect the new content — leading to stale autocomplete. By updating\n * tsconfig.json's mtime we trigger a full project reload.\n *\n * The file content is NOT modified; only the filesystem timestamp changes.\n *\n * @internal Exported for testing\n */\nexport function touchTsConfig(root: string): void {\n const tsconfigPath = path.join(root, \"tsconfig.json\");\n try {\n if (fs.existsSync(tsconfigPath)) {\n const now = new Date();\n fs.utimesSync(tsconfigPath, now, now);\n }\n } catch {\n // Non-critical: if we can't touch the file, TS may just need a manual reload\n }\n}\n"]}
1
+ {"version":3,"file":"heliumPlugin.js","sourceRoot":"","sources":["../../src/vite/heliumPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AAGxB,OAAO,EAAE,gBAAgB,EAAE,kB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AG,CAAC,CAAC;AAC9E,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACtC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;IACtD,IAAI,CAAC;QACD,IAAI,EAAE,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YAC9B,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,EAAE,CAAC,UAAU,CAAC,YAAY,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;QAC1C,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACL,6EAA6E;IACjF,CAAC;AACL,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport type { Plugin } from \"vite\";\n\nimport { clearConfigCache, getRpcClientConfig, loadConfig } from \"../server/config.js\";\nimport { attachToDevServer } from \"../server/devServer.js\";\nimport { createEnvDefines, injectEnvToProcess, loadEnvFiles } from \"../utils/envLoader.js\";\nimport { log } from \"../utils/logger.js\";\nimport {\n RESOLVED_VIRTUAL_CLIENT_MODULE_ID,\n RESOLVED_VIRTUAL_ENTRY_MODULE_ID,\n RESOLVED_VIRTUAL_SERVER_MANIFEST_ID,\n SERVER_DIR,\n VIRTUAL_CLIENT_MODULE_ID,\n VIRTUAL_ENTRY_MODULE_ID,\n VIRTUAL_SERVER_MANIFEST_ID,\n} from \"./paths.js\";\nimport { checkRouteCollisions, scanServerExports } from \"./scanner.js\";\nimport { generateClientModule, generateEntryModule, generateServerManifest, generateTypeDefinitions } from \"./virtualServerModule.js\";\n\nexport default function helium(): Plugin {\n let root = process.cwd();\n const serverDir = normalizeToPosix(SERVER_DIR);\n\n return {\n name: \"vite-plugin-helium\",\n enforce: \"pre\",\n configResolved(config) {\n root = config.root;\n\n // Load and inject environment variables\n const mode = config.mode || \"development\";\n const envVars = loadEnvFiles({ root, mode });\n injectEnvToProcess(envVars);\n },\n transformIndexHtml: {\n order: \"pre\",\n handler(html, _ctx) {\n // Check if HTML already has a script tag for entry\n if (html.includes(\"src/main.tsx\") || html.includes(\"src/main.ts\")) {\n return html; // User has their own entry, don't modify\n }\n\n // Ensure root div exists\n let modifiedHtml = html;\n if (!modifiedHtml.includes('id=\"root\"')) {\n modifiedHtml = modifiedHtml.replace(\"<body>\", '<body>\\n <div id=\"root\"></div>');\n }\n\n // Generate physical entry file\n const heliumDir = path.join(root, \"node_modules\", \".heliumts\");\n if (!fs.existsSync(heliumDir)) {\n fs.mkdirSync(heliumDir, { recursive: true });\n }\n const entryPath = path.join(heliumDir, \"entry.tsx\");\n fs.writeFileSync(entryPath, generateEntryModule());\n\n // Return with tags to inject the entry (runtime config is fetched by the client)\n return [\n {\n tag: \"script\",\n attrs: {\n type: \"module\",\n src: \"/node_modules/.heliumts/entry.tsx\",\n },\n injectTo: \"body\",\n },\n ];\n },\n },\n async config(config) {\n // Load environment variables before config is finalized\n const mode = config.mode || \"development\";\n const envVars = loadEnvFiles({ root, mode });\n\n // Create defines for client-side env variables\n const envDefines = createEnvDefines(envVars);\n\n // Load helium config to get client-side RPC transport settings\n const heliumConfig = await loadConfig(root);\n const rpcClientConfig = getRpcClientConfig(heliumConfig);\n\n // Provide default index.html if none exists\n return {\n appType: \"spa\",\n optimizeDeps: {\n include: [\"react-dom/client\"],\n // Exclude helium from pre-bundling since it's the framework itself\n // This ensures changes to helium are picked up immediately\n exclude: [\"heliumts\", \"heliumts/client\", \"heliumts/server\", \"heliumts/vite\"],\n },\n // SSR configuration to properly isolate server-only code\n ssr: {\n // Externalize Node.js built-in modules - these should never be bundled\n external: [\"util\", \"zlib\", \"http\", \"https\", \"http2\", \"fs\", \"path\", \"crypto\", \"stream\", \"os\", \"url\", \"net\", \"tls\", \"child_process\", \"worker_threads\"],\n // Don't externalize heliumts - let the plugin handle the client/server split\n noExternal: [\"heliumts\"],\n },\n // Ensure Node.js built-ins are not bundled for client\n build: {\n rollupOptions: {\n external: [\n // Node.js built-in modules should never be in client bundle\n /^node:/,\n \"util\",\n \"zlib\",\n \"http\",\n \"https\",\n \"http2\",\n \"fs\",\n \"path\",\n \"crypto\",\n \"stream\",\n \"os\",\n \"url\",\n \"net\",\n \"tls\",\n \"child_process\",\n \"worker_threads\",\n ],\n },\n },\n define: {\n ...envDefines,\n __HELIUM_DEV__: JSON.stringify(mode !== \"production\"),\n __HELIUM_RPC_TRANSPORT__: JSON.stringify(rpcClientConfig.transport),\n __HELIUM_RPC_AUTO_HTTP_ON_MOBILE__: JSON.stringify(rpcClientConfig.autoHttpOnMobile),\n __HELIUM_RPC_TOKEN_VALIDITY_MS__: JSON.stringify(rpcClientConfig.tokenValidityMs),\n },\n };\n },\n resolveId(id, importer) {\n if (id === VIRTUAL_CLIENT_MODULE_ID) {\n if (isServerModule(importer, root, serverDir)) {\n return null;\n }\n return RESOLVED_VIRTUAL_CLIENT_MODULE_ID;\n }\n if (id === VIRTUAL_SERVER_MANIFEST_ID) {\n return RESOLVED_VIRTUAL_SERVER_MANIFEST_ID;\n }\n if (id === VIRTUAL_ENTRY_MODULE_ID) {\n // Add .tsx extension so Vite knows it contains JSX\n return RESOLVED_VIRTUAL_ENTRY_MODULE_ID + \".tsx\";\n }\n // Intercept heliumts/server imports from client code\n if (id === \"heliumts/server\") {\n // If imported from server code, let it resolve normally\n if (isServerModule(importer, root, serverDir)) {\n return null;\n }\n // For client code, redirect to virtual client module\n return RESOLVED_VIRTUAL_CLIENT_MODULE_ID;\n }\n return null;\n },\n load(id) {\n if (id === RESOLVED_VIRTUAL_CLIENT_MODULE_ID) {\n const { methods } = scanServerExports(root);\n return generateClientModule(methods);\n }\n if (id === RESOLVED_VIRTUAL_SERVER_MANIFEST_ID) {\n const { methods, httpHandlers, middleware, workers } = scanServerExports(root);\n return generateServerManifest(methods, httpHandlers, middleware, workers);\n }\n if (id === RESOLVED_VIRTUAL_ENTRY_MODULE_ID + \".tsx\") {\n return generateEntryModule();\n }\n },\n buildStart() {\n const { methods } = scanServerExports(root);\n const dts = generateTypeDefinitions(methods, root);\n const typesDir = path.join(root, \"src\", \"types\");\n const dtsPath = path.join(typesDir, \"heliumts-server.d.ts\");\n\n // Ensure src/types exists\n if (!fs.existsSync(typesDir)) {\n fs.mkdirSync(typesDir, { recursive: true });\n }\n\n // At build start we always allow writing the canonical set.\n // Only skip if content is identical to avoid needless TS invalidation.\n if (!fs.existsSync(dtsPath) || fs.readFileSync(dtsPath, \"utf-8\") !== dts) {\n fs.writeFileSync(dtsPath, dts);\n touchTsConfig(root);\n }\n\n // Check for route collisions in pages directory\n checkRouteCollisions(root);\n },\n configureServer(server) {\n // Add middleware to handle HTML fallback for nested routes\n // This ensures that routes like /docs/guides/auth properly serve index.html\n // so the client-side router can handle them\n server.middlewares.use((req, res, next) => {\n const url = req.url || \"\";\n const cleanUrl = url.split(\"?\")[0];\n\n // Skip if:\n // - Has file extension (asset request)\n // - Is an API/special endpoint\n // - Is a dev server endpoint\n if (\n path.extname(cleanUrl) !== \"\" ||\n cleanUrl.startsWith(\"/api\") ||\n cleanUrl.startsWith(\"/webhooks\") ||\n cleanUrl.startsWith(\"/auth\") ||\n cleanUrl.startsWith(\"/@\") ||\n cleanUrl.startsWith(\"/__helium__\")\n ) {\n return next();\n }\n\n // For all other routes (including nested paths like /docs/guides/auth),\n // rewrite to index.html so Vite serves it and the client-side router handles routing\n req.url = \"/index.html\";\n next();\n });\n\n /**\n * Write type definitions only if content has changed.\n * This prevents unnecessary TypeScript recompilation.\n *\n * When `allowFewer` is false (default) the file will NOT be\n * overwritten if the new content has fewer method declarations\n * than the existing file — this guards against writing a\n * degraded .d.ts while the user's file is only partially saved.\n */\n const writeTypesIfChanged = (dts: string, allowFewer = false): boolean => {\n const typesDir = path.join(root, \"src\", \"types\");\n const dtsPath = path.join(typesDir, \"heliumts-server.d.ts\");\n\n if (!fs.existsSync(typesDir)) {\n fs.mkdirSync(typesDir, { recursive: true });\n }\n\n // Check if file exists and content is the same\n if (fs.existsSync(dtsPath)) {\n const existing = fs.readFileSync(dtsPath, \"utf-8\");\n if (existing === dts) {\n return false; // No change needed\n }\n\n // Guard: don't overwrite with fewer methods unless explicitly allowed\n // (e.g. on unlink). This prevents losing types during partial saves.\n if (!allowFewer) {\n const countExports = (s: string) => (s.match(/export const \\w+:/g) || []).length;\n const existingCount = countExports(existing);\n const newCount = countExports(dts);\n if (newCount < existingCount) {\n log(\"info\", `Skipping type generation: found ${newCount} methods, existing has ${existingCount} (likely partial save)`);\n return false;\n }\n }\n }\n\n fs.writeFileSync(dtsPath, dts);\n\n // Touch tsconfig.json to force the TypeScript language server\n // to reload the project. Without this, TS may cache stale\n // module augmentations and autocomplete won't reflect the\n // new methods until a manual restart.\n touchTsConfig(root);\n\n return true; // File was written\n };\n\n const regenerateTypes = (allowFewer = false): boolean => {\n try {\n const { methods } = scanServerExports(root);\n const dts = generateTypeDefinitions(methods, root);\n return writeTypesIfChanged(dts, allowFewer);\n } catch (e) {\n log(\"error\", \"Failed to regenerate types\", e);\n return false;\n }\n };\n\n // Debounce timer for file changes\n let debounceTimer: ReturnType<typeof setTimeout> | null = null;\n const DEBOUNCE_DELAY = 300; // ms — long enough for format-on-save to finish\n\n const handleServerFileChange = async (allowFewer = false) => {\n // Regenerate type definitions\n regenerateTypes(allowFewer);\n\n // Invalidate the virtual modules so they get regenerated\n const clientModule = server.environments.client?.moduleGraph.getModuleById(RESOLVED_VIRTUAL_CLIENT_MODULE_ID);\n const serverModule = server.environments.ssr?.moduleGraph.getModuleById(RESOLVED_VIRTUAL_SERVER_MANIFEST_ID);\n\n if (clientModule) {\n server.environments.client?.moduleGraph.invalidateModule(clientModule);\n }\n if (serverModule) {\n server.environments.ssr?.moduleGraph.invalidateModule(serverModule);\n }\n\n // Reload the server manifest and re-register methods\n try {\n // Clear config cache to ensure fresh config is loaded\n clearConfigCache();\n const config = await loadConfig(root);\n const mod = await server.ssrLoadModule(VIRTUAL_SERVER_MANIFEST_ID);\n const registerAll = mod.registerAll;\n const httpHandlers = mod.httpHandlers || [];\n const middlewareHandler = mod.middlewareHandler || null;\n const workers = mod.workers || [];\n\n // Update the dev server registry with new methods and HTTP handlers\n if (server.httpServer) {\n attachToDevServer(\n server.httpServer,\n (registry, httpRouter) => {\n registerAll(registry);\n httpRouter.registerRoutes(httpHandlers);\n if (middlewareHandler) {\n registry.setMiddleware(middlewareHandler);\n httpRouter.setMiddleware(middlewareHandler);\n }\n },\n config,\n workers\n );\n }\n } catch (e) {\n log(\"error\", \"Failed to reload Helium server manifest\", e);\n }\n\n // Trigger HMR for any client code that imports heliumts/server\n server.ws.send({\n type: \"full-reload\",\n path: \"*\",\n });\n };\n\n // Watch server directory for changes\n const serverPath = path.join(root, serverDir);\n server.watcher.add(serverPath);\n\n // Watch config files for changes\n const configFiles = [\"helium.config.ts\", \"helium.config.js\", \"helium.config.mjs\"];\n for (const configFile of configFiles) {\n const configPath = path.join(root, configFile);\n if (fs.existsSync(configPath)) {\n server.watcher.add(configPath);\n }\n }\n\n /**\n * Debounced handler for server file changes.\n * This prevents multiple rapid regenerations during file saves.\n * @param allowFewer - pass true when files are deleted, so the\n * method count is allowed to decrease.\n */\n let pendingAllowFewer = false;\n const debouncedHandleServerFileChange = (allowFewer = false) => {\n // If any event in the batch is an unlink, honour it\n if (allowFewer) {\n pendingAllowFewer = true;\n }\n if (debounceTimer) {\n clearTimeout(debounceTimer);\n }\n debounceTimer = setTimeout(() => {\n debounceTimer = null;\n const shouldAllowFewer = pendingAllowFewer;\n pendingAllowFewer = false;\n handleServerFileChange(shouldAllowFewer);\n }, DEBOUNCE_DELAY);\n };\n\n server.watcher.on(\"change\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file changed, regenerate everything\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange();\n }\n\n // If config file changed, reload config and regenerate\n if (configFiles.some((cf) => normalized === cf)) {\n log(\"info\", `Config file changed: ${normalized}`);\n debouncedHandleServerFileChange();\n }\n });\n\n server.watcher.on(\"add\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file was added, regenerate everything\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange();\n }\n });\n\n server.watcher.on(\"unlink\", (file) => {\n const relative = path.relative(root, file);\n const normalized = normalizeToPosix(relative);\n\n // If a server file was removed, regenerate (allow fewer methods)\n if (normalized.startsWith(`${serverDir}/`)) {\n debouncedHandleServerFileChange(true);\n }\n });\n\n // We hook into the server start to attach our RPC server\n server.httpServer?.on(\"listening\", async () => {\n try {\n // Load config\n const config = await loadConfig(root);\n\n // Load the manifest using Vite's SSR loader\n // This allows us to load TS files directly and handle dependencies\n const mod = await server.ssrLoadModule(VIRTUAL_SERVER_MANIFEST_ID);\n const registerAll = mod.registerAll;\n const httpHandlers = mod.httpHandlers || [];\n const middlewareHandler = mod.middlewareHandler || null;\n const workers = mod.workers || [];\n\n if (server.httpServer) {\n attachToDevServer(\n server.httpServer,\n (registry, httpRouter) => {\n registerAll(registry);\n httpRouter.registerRoutes(httpHandlers);\n if (middlewareHandler) {\n registry.setMiddleware(middlewareHandler);\n httpRouter.setMiddleware(middlewareHandler);\n }\n },\n config,\n workers\n );\n }\n } catch (e) {\n log(\"error\", \"Failed to attach Helium RPC server\", e);\n }\n });\n },\n };\n}\n\n/**\n * Convert file path to POSIX format\n * @internal Exported for testing\n */\nexport function normalizeToPosix(filePath: string): string {\n return filePath.split(path.sep).join(\"/\");\n}\n\n/**\n * Check if an importer is a server module\n * @internal Exported for testing\n */\nexport function isServerModule(importer: string | undefined, root: string, serverDir: string): boolean {\n if (!importer || importer.startsWith(\"\\0\")) {\n return false;\n }\n\n const [importerPath] = importer.split(\"?\");\n if (!importerPath) {\n return false;\n }\n\n const relative = path.relative(root, importerPath);\n if (!relative || relative.startsWith(\"..\")) {\n return false;\n }\n\n const normalized = normalizeToPosix(relative);\n return normalized === serverDir || normalized.startsWith(`${serverDir}/`);\n}\n\n/**\n * Touch the project's tsconfig.json to force the TypeScript language server\n * to reload the project and pick up changed module augmentations.\n *\n * TS language server watches tsconfig.json for changes. When a `.d.ts` file\n * with `declare module` augmentations is regenerated, TS doesn't always\n * detect the new content — leading to stale autocomplete. By updating\n * tsconfig.json's mtime we trigger a full project reload.\n *\n * The file content is NOT modified; only the filesystem timestamp changes.\n *\n * @internal Exported for testing\n */\nexport function touchTsConfig(root: string): void {\n const tsconfigPath = path.join(root, \"tsconfig.json\");\n try {\n if (fs.existsSync(tsconfigPath)) {\n const now = new Date();\n fs.utimesSync(tsconfigPath, now, now);\n }\n } catch {\n // Non-critical: if we can't touch the file, TS may just need a manual reload\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heliumts",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "A lightweight full-stack React framework with file-based routing, RPC, and SSG support",
5
5
  "keywords": [
6
6
  "react",
@@ -63,6 +63,7 @@
63
63
  "build": "tsc -p tsconfig.json",
64
64
  "prepare": "npm run build",
65
65
  "prepublishOnly": "npm run build",
66
+ "pentest": "node scripts/helium-pentest.mjs",
66
67
  "format": "prettier --write \"src/**/*.{ts,tsx,js}\"",
67
68
  "format:check": "prettier --check \"src/**/*.{ts,tsx,js}\"",
68
69
  "lint": "eslint --ext .ts,.tsx src",