@stratal/inertia 0.0.20 → 0.0.21

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.
@@ -1 +1 @@
1
- {"version":3,"file":"react.mjs","names":[],"sources":["../src/react/use-i18n.ts","../src/react/use-route.ts"],"sourcesContent":["/**\n * React hook for using Stratal's i18n translations on the frontend.\n *\n * Reads `locale` and `translations` from Inertia shared props (injected by\n * the `i18n` option on {@link InertiaModuleOptions}) and provides a type-safe\n * `t()` function powered by `@intlify/core-base`.\n *\n * @module\n */\n\nimport type { PageProps } from '@inertiajs/core'\nimport { usePage } from '@inertiajs/react'\nimport { compile, createCoreContext, registerMessageCompiler, translate } from '@intlify/core-base'\nimport { useMemo } from 'react'\nimport type { MessageKeys, MessageParams } from 'stratal/i18n'\n\n// Register JIT message compiler from the SAME @intlify/core-base instance that provides\n// createCoreContext/translate. Importing setupI18nCompiler from stratal/i18n/utils can\n// resolve a different @intlify/core-base copy (duplicate modules in node_modules),\n// causing the compiler registration to be invisible to this module's createCoreContext.\nregisterMessageCompiler(compile)\n\ninterface I18nPageProps extends PageProps {\n locale: string\n translations: Record<string, string>\n}\n\n/**\n * Hook that provides i18n translation capabilities in React components.\n *\n * Consumes `locale` and `translations` from Inertia shared props and returns\n * a `t()` function that translates message keys with optional interpolation.\n *\n * Requires the `i18n` option to be set on `InertiaModule.forRoot()` to inject\n * the shared props.\n *\n * @returns An object with:\n * - `t` — Translation function accepting a message key and optional params\n * - `locale` — The current locale string\n *\n * @example\n * ```tsx\n * import { useI18n } from '@stratal/inertia/react'\n *\n * export default function Header() {\n * const { t, locale } = useI18n()\n *\n * return (\n * <header>\n * <h1>{t('common.title')}</h1>\n * <p>{t('common.greeting', { name: 'World' })}</p>\n * <span>Locale: {locale}</span>\n * </header>\n * )\n * }\n * ```\n */\nexport function useI18n() {\n const { locale, translations } = usePage<I18nPageProps>().props\n\n const context = useMemo(\n () => createCoreContext({\n locale,\n messages: { [locale]: translations },\n missingWarn: !import.meta.env.PROD,\n fallbackWarn: !import.meta.env.PROD,\n }),\n [locale, translations],\n )\n\n const t = useMemo(\n () => (key: MessageKeys, params?: MessageParams): string => {\n const result = params !== undefined\n ? translate(context, key, params)\n : translate(context, key)\n return typeof result === 'string' ? result : key\n },\n [context],\n )\n\n return { t, locale }\n}\n","/**\n * React hook for Ziggy-like client-side URL generation.\n *\n * Reads serialized routes and the current request's matched-route snapshot\n * (injected by the `routes` option on {@link InertiaModuleOptions}) and\n * provides a type-safe `route()` function that mirrors the server-side\n * `buildRouteUrl()`, plus `current()` and `params` for current-route\n * introspection.\n *\n * @module\n */\n\nimport type { PageProps } from '@inertiajs/core'\nimport { usePage } from '@inertiajs/react'\nimport { useMemo } from 'react'\nimport type { CurrentRoute, RouteMatcher, RouteName, RouteParams, SerializedRoute, SerializedRoutes, TrailingSlashMode } from 'stratal/router'\n\ninterface RoutesPageProps extends PageProps {\n routes: SerializedRoutes\n trailingSlash?: TrailingSlashMode\n route: CurrentRoute\n}\n\n/**\n * Apply a trailing-slash mode to a URL or path.\n *\n * Pure reimplementation of `applyTrailingSlash()` from `stratal/router` —\n * mirrored here to keep the React bundle decoupled from server-only deps.\n *\n * - `'ignore'` — return as-is.\n * - `'always'` — append `/` unless path is root or last segment is file-like (`.json`, etc.).\n * - `'never'` — strip a single trailing `/` from the pathname (skip root).\n *\n * Preserves query string and hash. Handles relative paths and absolute URLs.\n */\nexport function applyTrailingSlash(url: string, mode: TrailingSlashMode): string {\n if (mode === 'ignore') return url\n\n const isAbsolute = /^https?:\\/\\//i.test(url)\n const parsed = isAbsolute ? new URL(url) : new URL(url, 'http://placeholder.local')\n const path = parsed.pathname\n if (path === '/') return url\n const hasTrailing = path.endsWith('/')\n\n if (mode === 'always' && !hasTrailing) {\n const lastSegment = path.slice(path.lastIndexOf('/') + 1)\n if (lastSegment.includes('.')) return url\n parsed.pathname = `${path}/`\n } else if (mode === 'never' && hasTrailing) {\n parsed.pathname = path.slice(0, -1)\n } else {\n return url\n }\n\n return isAbsolute\n ? parsed.toString()\n : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n/**\n * Encode a path-param value while preserving forward slashes so catch-all\n * params (`:slug{.+}`) round-trip cleanly. Mirrors the server-side\n * `encodePathParam()` in `stratal/router`.\n */\nfunction encodePathParam(value: string): string {\n return value.split('/').map(encodeURIComponent).join('/')\n}\n\n/**\n * Build a URL from a serialized route definition.\n *\n * Mirrors `buildRouteUrl()` from `stratal/router` (pure reimplementation to\n * avoid pulling server-side dependencies into the browser bundle).\n */\nfunction buildUrl(route: SerializedRoute, name: string, params?: Record<string, string>): string {\n const allParams = { ...params }\n const consumedKeys = new Set<string>()\n let url = route.path\n\n if (allParams.locale && route.localePaths?.length) {\n url = `/${allParams.locale}${url === '/' ? '' : url}`\n consumedKeys.add('locale')\n }\n\n for (const paramName of route.paramNames) {\n const value = allParams[paramName]\n if (value === undefined) {\n throw new Error(`Missing required parameter \"${paramName}\" for route \"${name}\" (path: ${route.path})`)\n }\n url = url.replace(\n new RegExp(`:${paramName}(\\\\{[^}]*\\\\})?`),\n encodePathParam(value),\n )\n consumedKeys.add(paramName)\n }\n\n let domain: string | undefined\n if (route.domain) {\n domain = route.domain\n for (const domainParam of route.domainParamNames) {\n const value = allParams[domainParam]\n if (value === undefined) {\n throw new Error(`Missing required parameter \"${domainParam}\" for route \"${name}\" (domain: ${route.domain})`)\n }\n domain = domain.replace(`{${domainParam}}`, encodeURIComponent(value))\n consumedKeys.add(domainParam)\n }\n }\n\n const queryEntries = Object.entries(allParams).filter(([key]) => !consumedKeys.has(key))\n if (queryEntries.length > 0) {\n const queryString = queryEntries\n .filter(([, v]) => Boolean(v))\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&')\n url = `${url}${queryString.length ? `?${queryString}` : ''}`\n }\n\n if (domain) {\n url = `https://${domain}${url}`\n }\n\n return url\n}\n\n/**\n * Filter a param bag down to the keys the target route actually declares —\n * so a `companyId` carried over from the current URL never leaks into the\n * query string of an unrelated route.\n */\nfunction filterCarryover(carryover: Record<string, string>, route: SerializedRoute): Record<string, string> {\n const allowed = new Set<string>([...route.paramNames, ...route.domainParamNames])\n if (route.localePaths?.length) allowed.add('locale')\n if (allowed.size === 0) return {}\n\n const filtered: Record<string, string> = {}\n for (const [key, value] of Object.entries(carryover)) {\n if (allowed.has(key)) filtered[key] = value\n }\n return filtered\n}\n\n/**\n * Pure URL resolver. Mirrors what {@link useRoute}'s `route()` does, but\n * without React — exposed for testing and for non-hook callers.\n *\n * Merges params in order (last wins): sticky `defaults`, current-route\n * carryover (filtered to the target's declared params), explicit params.\n */\nexport function resolveUrl<N extends RouteName>(\n name: N,\n explicitParams: RouteParams<N> | undefined,\n routes: SerializedRoutes,\n currentRoute: CurrentRoute,\n trailingSlash: TrailingSlashMode = 'ignore',\n): string {\n const target = routes[name]\n if (!target) {\n throw new Error(`Route \"${name}\" not found.`)\n }\n\n const merged = {\n ...currentRoute.defaults,\n ...filterCarryover(currentRoute.params, target),\n ...explicitParams,\n } as Record<string, string>\n\n return applyTrailingSlash(buildUrl(target, name, merged), trailingSlash)\n}\n\n/**\n * Pure overload signatures for {@link matchCurrent} / `useRoute().current()`.\n *\n * - No arg → matched route name (or `null`).\n * - With a name → `true`/`false`. Strict-typed: only real route names and\n * dotted wildcard prefixes (`'users.*'`) are accepted.\n */\nexport function matchCurrent(currentRoute: CurrentRoute): RouteName | null\nexport function matchCurrent(currentRoute: CurrentRoute, name: RouteMatcher): boolean\nexport function matchCurrent(currentRoute: CurrentRoute, name?: RouteMatcher): RouteName | null | boolean {\n if (name === undefined) return currentRoute.name\n if (currentRoute.name === null) return false\n if (typeof name === 'string' && name.endsWith('.*')) {\n const prefix = name.slice(0, -1)\n return currentRoute.name.startsWith(prefix)\n }\n return currentRoute.name === name\n}\n\n/**\n * Hook that provides Ziggy-like route URL generation in React components.\n *\n * Consumes `routes` and the current-request snapshot (`route`) from Inertia\n * shared props. Route names and params are strictly typed from\n * `StratalRouteMap` (generated by `quarry route:types`).\n *\n * Requires the `routes` option to be set on `InertiaModule.forRoot()`.\n *\n * Sticky params — anything in `defaults` (set server-side via `Uri.defaults()`)\n * and anything in the current route's extracted `params` (filtered to the\n * target route's declared params) — are merged into every `route()` call.\n * Explicit params always win.\n *\n * @returns\n * - `route(name, params?)` — URL builder\n * - `current()` / `current(name)` — matched route name (or wildcard match)\n * - `params` — extracted params for the current request URL\n *\n * @example\n * ```tsx\n * import { useRoute } from '@stratal/inertia/react'\n *\n * export default function UserProfile({ user }) {\n * const { route, current, currentRoute } = useRoute()\n *\n * return (\n * <nav>\n * <a href={route('users.index')}>All Users</a>\n * <a href={route('users.show', { id: user.id })}>{user.name}</a>\n * {current('users.*') && <span>On a users page</span>}\n * {currentRoute.name === 'users.show' && <span>#{currentRoute.params.id}</span>}\n * </nav>\n * )\n * }\n * ```\n */\nexport function useRoute() {\n const page = usePage<RoutesPageProps>()\n const { routes, trailingSlash = 'ignore', route: currentRoute } = page.props\n\n const route = useMemo(\n () => <N extends RouteName>(name: N, params?: RouteParams<N>): string =>\n resolveUrl(name, params, routes, currentRoute, trailingSlash),\n [routes, trailingSlash, currentRoute],\n )\n\n const current = useMemo(\n () => {\n function impl(): RouteName | null\n function impl(name: RouteMatcher): boolean\n function impl(name?: RouteMatcher): RouteName | null | boolean {\n return name === undefined ? matchCurrent(currentRoute) : matchCurrent(currentRoute, name)\n }\n return impl\n },\n [currentRoute],\n )\n\n return { route, current, currentRoute, params: currentRoute.params }\n}\n"],"mappings":";;;;AAoBA,wBAAwB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqChC,SAAgB,UAAU;CACxB,MAAM,EAAE,QAAQ,iBAAiB,SAAwB,CAAC;CAE1D,MAAM,UAAU,cACR,kBAAkB;EACtB;EACA,UAAU,GAAG,SAAS,cAAc;EACpC,aAAa,CAAC,OAAO,KAAK,IAAI;EAC9B,cAAc,CAAC,OAAO,KAAK,IAAI;EAChC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,UAAU,CAClD,KAAI,QAAQ,IAAI,IAAI,CAAE,UAAS,OAAO;AAExC,QAAO;;;;;;;;;AAUT,SAAgB,WACd,MACA,gBACA,QACA,cACA,gBAAmC,UAC3B;CACR,MAAM,SAAS,OAAO;AACtB,KAAI,CAAC,OACH,OAAM,IAAI,MAAM,UAAU,KAAK,cAAc;AAS/C,QAAO,mBAAmB,SAAS,QAAQ,MAAM;EAL/C,GAAG,aAAa;EAChB,GAAG,gBAAgB,aAAa,QAAQ,OAAO;EAC/C,GAAG;EAGkD,CAAC,EAAE,cAAc;;AAY1E,SAAgB,aAAa,cAA4B,MAAiD;AACxG,KAAI,SAAS,KAAA,EAAW,QAAO,aAAa;AAC5C,KAAI,aAAa,SAAS,KAAM,QAAO;AACvC,KAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,EAAE;EACnD,MAAM,SAAS,KAAK,MAAM,GAAG,GAAG;AAChC,SAAO,aAAa,KAAK,WAAW,OAAO;;AAE7C,QAAO,aAAa,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwC/B,SAAgB,WAAW;CAEzB,MAAM,EAAE,QAAQ,gBAAgB,UAAU,OAAO,iBADpC,SACyD,CAAC;AAoBvE,QAAO;EAAE,OAlBK,eACgB,MAAS,WACnC,WAAW,MAAM,QAAQ,QAAQ,cAAc,cAAc,EAC/D;GAAC;GAAQ;GAAe;GAAa,CAezB;EAAE,SAZA,cACR;GAGJ,SAAS,KAAK,MAAiD;AAC7D,WAAO,SAAS,KAAA,IAAY,aAAa,aAAa,GAAG,aAAa,cAAc,KAAK;;AAE3F,UAAO;KAET,CAAC,aAAa,CAGO;EAAE;EAAc,QAAQ,aAAa;EAAQ"}
1
+ {"version":3,"file":"react.mjs","names":[],"sources":["../src/react/use-i18n.ts","../src/react/use-route.ts"],"sourcesContent":["/**\n * React hook for using Stratal's i18n translations on the frontend.\n *\n * Reads `locale` and `translations` from Inertia shared props (injected by\n * the `i18n` option on {@link InertiaModuleOptions}) and provides a type-safe\n * `t()` function powered by `@intlify/core-base`.\n *\n * @module\n */\n\nimport type { PageProps } from '@inertiajs/core'\nimport { usePage } from '@inertiajs/react'\nimport { compile, createCoreContext, registerMessageCompiler, translate } from '@intlify/core-base'\nimport { useMemo } from 'react'\nimport type { MessageKeys, MessageParams } from 'stratal/i18n'\n\n// Register JIT message compiler from the SAME @intlify/core-base instance that provides\n// createCoreContext/translate. Importing setupI18nCompiler from stratal/i18n/utils can\n// resolve a different @intlify/core-base copy (duplicate modules in node_modules),\n// causing the compiler registration to be invisible to this module's createCoreContext.\nregisterMessageCompiler(compile)\n\ninterface I18nPageProps extends PageProps {\n locale: string\n translations: Record<string, string>\n}\n\n/**\n * Hook that provides i18n translation capabilities in React components.\n *\n * Consumes `locale` and `translations` from Inertia shared props and returns\n * a `t()` function that translates message keys with optional interpolation.\n *\n * Requires the `i18n` option to be set on `InertiaModule.forRoot()` to inject\n * the shared props.\n *\n * @returns An object with:\n * - `t` — Translation function accepting a message key and optional params\n * - `locale` — The current locale string\n *\n * @example\n * ```tsx\n * import { useI18n } from '@stratal/inertia/react'\n *\n * export default function Header() {\n * const { t, locale } = useI18n()\n *\n * return (\n * <header>\n * <h1>{t('common.title')}</h1>\n * <p>{t('common.greeting', { name: 'World' })}</p>\n * <span>Locale: {locale}</span>\n * </header>\n * )\n * }\n * ```\n */\nexport function useI18n() {\n const { locale, translations } = usePage<I18nPageProps>().props\n\n const context = useMemo(\n () => createCoreContext({\n locale,\n messages: { [locale]: translations },\n missingWarn: !import.meta.env.PROD,\n fallbackWarn: !import.meta.env.PROD,\n }),\n [locale, translations],\n )\n\n const t = useMemo(\n () => (key: MessageKeys, params?: MessageParams): string => {\n const result = params !== undefined\n ? translate(context, key, params)\n : translate(context, key)\n return typeof result === 'string' ? result : key\n },\n [context],\n )\n\n return { t, locale }\n}\n","/**\n * React hook for Ziggy-like client-side URL generation.\n *\n * Reads serialized routes and the current request's matched-route snapshot\n * (injected by the `routes` option on {@link InertiaModuleOptions}) and\n * provides a type-safe `route()` function that mirrors the server-side\n * `buildRouteUrl()`, plus `current()` and `params` for current-route\n * introspection.\n *\n * @module\n */\n\nimport type { PageProps } from '@inertiajs/core'\nimport { usePage } from '@inertiajs/react'\nimport { useMemo } from 'react'\nimport type { CurrentRoute, RouteMatcher, RouteName, RouteParams, SerializedRoute, SerializedRoutes, TrailingSlashMode } from 'stratal/router'\n\ninterface RoutesPageProps extends PageProps {\n routes: SerializedRoutes\n trailingSlash?: TrailingSlashMode\n route: CurrentRoute\n}\n\n/**\n * Apply a trailing-slash mode to a URL or path.\n *\n * Pure reimplementation of `applyTrailingSlash()` from `stratal/router` —\n * mirrored here to keep the React bundle decoupled from server-only deps.\n *\n * - `'ignore'` — return as-is.\n * - `'always'` — append `/` unless path is root or last segment is file-like (`.json`, etc.).\n * - `'never'` — strip a single trailing `/` from the pathname (skip root).\n *\n * Preserves query string and hash. Handles relative paths and absolute URLs.\n */\nexport function applyTrailingSlash(url: string, mode: TrailingSlashMode): string {\n if (mode === 'ignore') return url\n\n const isAbsolute = /^https?:\\/\\//i.test(url)\n const parsed = isAbsolute ? new URL(url) : new URL(url, 'http://placeholder.local')\n const path = parsed.pathname\n if (path === '/') return url\n const hasTrailing = path.endsWith('/')\n\n if (mode === 'always' && !hasTrailing) {\n const lastSegment = path.slice(path.lastIndexOf('/') + 1)\n if (lastSegment.includes('.')) return url\n parsed.pathname = `${path}/`\n } else if (mode === 'never' && hasTrailing) {\n parsed.pathname = path.slice(0, -1)\n } else {\n return url\n }\n\n return isAbsolute\n ? parsed.toString()\n : `${parsed.pathname}${parsed.search}${parsed.hash}`\n}\n\n/**\n * Encode a path-param value while preserving forward slashes so catch-all\n * params (`:slug{.+}`) round-trip cleanly. Mirrors the server-side\n * `encodePathParam()` in `stratal/router`.\n */\nfunction encodePathParam(value: string): string {\n return value.split('/').map(encodeURIComponent).join('/')\n}\n\n/**\n * Build a URL from a serialized route definition.\n *\n * Mirrors `buildRouteUrl()` from `stratal/router` (pure reimplementation to\n * avoid pulling server-side dependencies into the browser bundle).\n */\nfunction buildUrl(route: SerializedRoute, name: string, params?: Record<string, string>): string {\n const allParams = { ...params }\n const consumedKeys = new Set<string>()\n let url = route.path\n\n if (allParams.locale && route.localePaths?.length) {\n url = `/${allParams.locale}${url === '/' ? '' : url}`\n consumedKeys.add('locale')\n }\n\n for (const paramName of route.paramNames) {\n const value = allParams[paramName]\n if (value === undefined) {\n throw new Error(`Missing required parameter \"${paramName}\" for route \"${name}\" (path: ${route.path})`)\n }\n url = url.replace(\n new RegExp(`:${paramName}(\\\\{[^}]*\\\\})?`),\n encodePathParam(value),\n )\n consumedKeys.add(paramName)\n }\n\n let domain: string | undefined\n if (route.domain) {\n domain = route.domain\n for (const domainParam of route.domainParamNames) {\n const value = allParams[domainParam]\n if (value === undefined) {\n throw new Error(`Missing required parameter \"${domainParam}\" for route \"${name}\" (domain: ${route.domain})`)\n }\n domain = domain.replace(`{${domainParam}}`, encodeURIComponent(value))\n consumedKeys.add(domainParam)\n }\n }\n\n const queryEntries = Object.entries(allParams).filter(([key]) => !consumedKeys.has(key))\n if (queryEntries.length > 0) {\n const queryString = queryEntries\n .filter(([, v]) => Boolean(v))\n .map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)\n .join('&')\n url = `${url}${queryString.length ? `?${queryString}` : ''}`\n }\n\n if (domain) {\n url = `https://${domain}${url}`\n }\n\n return url\n}\n\n/**\n * Filter a param bag down to the keys the target route actually declares —\n * so a `companyId` carried over from the current URL never leaks into the\n * query string of an unrelated route.\n */\nfunction filterCarryover(carryover: Record<string, string>, route: SerializedRoute): Record<string, string> {\n const allowed = new Set<string>([...route.paramNames, ...route.domainParamNames])\n if (route.localePaths?.length) allowed.add('locale')\n if (allowed.size === 0) return {}\n\n const filtered: Record<string, string> = {}\n for (const [key, value] of Object.entries(carryover)) {\n if (allowed.has(key)) filtered[key] = value\n }\n return filtered\n}\n\n/**\n * Pure URL resolver. Mirrors what {@link useRoute}'s `route()` does, but\n * without React — exposed for testing and for non-hook callers.\n *\n * Merges params in order (last wins): sticky `defaults`, current-route\n * carryover (filtered to the target's declared params), explicit params.\n */\nexport function resolveUrl<N extends RouteName>(\n name: N,\n explicitParams: RouteParams<N> | undefined,\n routes: SerializedRoutes,\n currentRoute: CurrentRoute,\n trailingSlash: TrailingSlashMode = 'ignore',\n): string {\n const target = routes[name]\n if (!target) {\n throw new Error(`Route \"${name}\" not found.`)\n }\n\n const merged = {\n ...currentRoute.defaults,\n ...filterCarryover(currentRoute.params, target),\n ...explicitParams,\n } as Record<string, string>\n\n return applyTrailingSlash(buildUrl(target, name, merged), trailingSlash)\n}\n\n/**\n * Pure overload signatures for {@link matchCurrent} / `useRoute().current()`.\n *\n * - No arg → matched route name (or `null`).\n * - With a name → `true`/`false`. Strict-typed: only real route names and\n * dotted wildcard prefixes (`'users.*'`) are accepted.\n */\nexport function matchCurrent(currentRoute: CurrentRoute): RouteName | null\nexport function matchCurrent(currentRoute: CurrentRoute, name: RouteMatcher): boolean\nexport function matchCurrent(currentRoute: CurrentRoute, name?: RouteMatcher): RouteName | null | boolean {\n if (name === undefined) return currentRoute.name\n if (currentRoute.name === null) return false\n if (typeof name === 'string' && name.endsWith('.*')) {\n const prefix = name.slice(0, -1)\n return currentRoute.name.startsWith(prefix)\n }\n return currentRoute.name === name\n}\n\n/**\n * Hook that provides Ziggy-like route URL generation in React components.\n *\n * Consumes `routes` and the current-request snapshot (`route`) from Inertia\n * shared props. Route names and params are strictly typed from\n * `StratalRouteMap` (generated by `quarry route:types`).\n *\n * Requires the `routes` option to be set on `InertiaModule.forRoot()`.\n *\n * Sticky params — anything in `defaults` (set server-side via `Uri.defaults()`)\n * and anything in the current route's extracted `params` (filtered to the\n * target route's declared params) — are merged into every `route()` call.\n * Explicit params always win.\n *\n * @returns\n * - `route(name, params?)` — URL builder\n * - `current()` / `current(name)` — matched route name (or wildcard match)\n * - `params` — extracted params for the current request URL\n *\n * @example\n * ```tsx\n * import { useRoute } from '@stratal/inertia/react'\n *\n * export default function UserProfile({ user }) {\n * const { route, current, currentRoute } = useRoute()\n *\n * return (\n * <nav>\n * <a href={route('users.index')}>All Users</a>\n * <a href={route('users.show', { id: user.id })}>{user.name}</a>\n * {current('users.*') && <span>On a users page</span>}\n * {currentRoute.name === 'users.show' && <span>#{currentRoute.params.id}</span>}\n * </nav>\n * )\n * }\n * ```\n */\nexport function useRoute() {\n const page = usePage<RoutesPageProps>()\n const { routes, trailingSlash = 'ignore', route: currentRoute } = page.props\n\n const route = useMemo(\n () => <N extends RouteName>(name: N, params?: RouteParams<N>): string =>\n resolveUrl(name, params, routes, currentRoute, trailingSlash),\n [routes, trailingSlash, currentRoute],\n )\n\n const current = useMemo(\n () => {\n function impl(): RouteName | null\n function impl(name: RouteMatcher): boolean\n function impl(name?: RouteMatcher): RouteName | null | boolean {\n return name === undefined ? matchCurrent(currentRoute) : matchCurrent(currentRoute, name)\n }\n return impl\n },\n [currentRoute],\n )\n\n return { route, current, currentRoute, params: currentRoute.params }\n}\n"],"mappings":";;;;AAoBA,wBAAwB,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqChC,SAAgB,UAAU;CACxB,MAAM,EAAE,QAAQ,iBAAiB,SAAwB,CAAC;CAE1D,MAAM,UAAU,cACR,kBAAkB;EACtB;EACA,UAAU,GAAG,SAAS,cAAc;EACpC,aAAa,CAAC,OAAO,KAAK,IAAI;EAC9B,cAAc,CAAC,OAAO,KAAK,IAAI;EAChC,CAAC,EACF,CAAC,QAAQ,aAAa,CACvB;CAYD,OAAO;EAAE,GAVC,eACD,KAAkB,WAAmC;GAC1D,MAAM,SAAS,WAAW,KAAA,IACtB,UAAU,SAAS,KAAK,OAAO,GAC/B,UAAU,SAAS,IAAI;GAC3B,OAAO,OAAO,WAAW,WAAW,SAAS;KAE/C,CAAC,QAAQ,CAGD;EAAE;EAAQ;;;;;;;;;;;;;;;;AC7CtB,SAAgB,mBAAmB,KAA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,gBAAgB,aAAa,QAAQ,OAAO;EAC/C,GAAG;EAGkD,CAAC,EAAE,cAAc;;AAY1E,SAAgB,aAAa,cAA4B,MAAiD;CACxG,IAAI,SAAS,KAAA,GAAW,OAAO,aAAa;CAC5C,IAAI,aAAa,SAAS,MAAM,OAAO;CACvC,IAAI,OAAO,SAAS,YAAY,KAAK,SAAS,KAAK,EAAE;EACnD,MAAM,SAAS,KAAK,MAAM,GAAG,GAAG;EAChC,OAAO,aAAa,KAAK,WAAW,OAAO;;CAE7C,OAAO,aAAa,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwC/B,SAAgB,WAAW;CAEzB,MAAM,EAAE,QAAQ,gBAAgB,UAAU,OAAO,iBADpC,SACyD,CAAC;CAoBvE,OAAO;EAAE,OAlBK,eACgB,MAAS,WACnC,WAAW,MAAM,QAAQ,QAAQ,cAAc,cAAc,EAC/D;GAAC;GAAQ;GAAe;GAAa,CAezB;EAAE,SAZA,cACR;GAGJ,SAAS,KAAK,MAAiD;IAC7D,OAAO,SAAS,KAAA,IAAY,aAAa,aAAa,GAAG,aAAa,cAAc,KAAK;;GAE3F,OAAO;KAET,CAAC,aAAa,CAGO;EAAE;EAAc,QAAQ,aAAa;EAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"testing.mjs","names":[],"sources":["../src/augment/test-response.ts","../src/testing.ts"],"sourcesContent":["import type { Page } from '@inertiajs/core'\nimport { getValueAtPath, hasValueAtPath, TestResponse } from '@stratal/testing'\nimport { expect } from 'vitest'\n\ndeclare module '@stratal/testing' {\n interface TestResponse {\n /** Assert the response is an Inertia response. Optionally run a callback with the page object for custom assertions. */\n assertInertia(callback?: (page: Page) => void): Promise<this>\n /** Assert the Inertia page component matches the expected name. */\n assertInertiaComponent(component: string): Promise<this>\n /** Assert the Inertia page prop at the given dot-path equals the expected value. */\n assertInertiaProp(path: string, expected: unknown): Promise<this>\n /** Assert the Inertia page prop at the given dot-path exists. */\n assertInertiaPropExists(path: string): Promise<this>\n /** Assert the Inertia page prop at the given dot-path does not exist. */\n assertInertiaPropMissing(path: string): Promise<this>\n /** Assert the Inertia page URL matches the expected value. */\n assertInertiaUrl(url: string): Promise<this>\n /** Assert the Inertia page version matches the expected value. */\n assertInertiaVersion(version: string | null): Promise<this>\n /** Assert the Inertia page flash data contains the given key with the expected value. */\n assertInertiaFlash(key: string, value: unknown): Promise<this>\n /** Assert a prop is listed as deferred in the given group. */\n assertInertiaDeferredProp(prop: string, group: string): Promise<this>\n /** Assert a prop is listed as a merge prop. */\n assertInertiaMergeProp(prop: string): Promise<this>\n /** Assert a prop is listed as a shared prop. */\n assertInertiaSharedProp(prop: string): Promise<this>\n /** Assert the response is a successful precognition response (204 with precognition headers). */\n assertSuccessfulPrecognition(): this\n /** Assert the response is a precognition validation error (422 with precognition headers). Optionally assert specific errors. */\n assertPrecognitionValidationErrors(errors?: Record<string, string>): Promise<this>\n }\n}\n\nexport function augmentTestResponse(): void {\n TestResponse.macro('assertInertia', async function (this: TestResponse, callback?: (page: Page) => void) {\n this.assertHeader('x-inertia', 'true')\n this.assertOk()\n\n if (callback) {\n const page = await this.json<Page>()\n callback(page)\n }\n\n return this\n })\n\n TestResponse.macro('assertInertiaComponent', async function (this: TestResponse, component: string) {\n const page = await this.json<Page>()\n\n expect(\n page.component,\n `Expected Inertia component \"${component}\", got \"${page.component}\"`,\n ).toBe(component)\n\n return this\n })\n\n TestResponse.macro('assertInertiaProp', async function (this: TestResponse, path: string, expected: unknown) {\n const page = await this.json<Page>()\n const actual = getValueAtPath(page.props, path)\n\n expect(\n actual,\n `Expected Inertia prop \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`,\n ).toStrictEqual(expected)\n\n return this\n })\n\n TestResponse.macro('assertInertiaPropExists', async function (this: TestResponse, path: string) {\n const page = await this.json<Page>()\n const exists = hasValueAtPath(page.props, path)\n\n expect(\n exists,\n `Expected Inertia prop \"${path}\" to exist`,\n ).toBe(true)\n\n return this\n })\n\n TestResponse.macro('assertInertiaPropMissing', async function (this: TestResponse, path: string) {\n const page = await this.json<Page>()\n const exists = hasValueAtPath(page.props, path)\n\n expect(\n exists,\n `Expected Inertia prop \"${path}\" to not exist`,\n ).toBe(false)\n\n return this\n })\n\n TestResponse.macro('assertInertiaUrl', async function (this: TestResponse, url: string) {\n const page = await this.json<Page>()\n\n expect(\n page.url,\n `Expected Inertia URL \"${url}\", got \"${page.url}\"`,\n ).toBe(url)\n\n return this\n })\n\n TestResponse.macro('assertInertiaVersion', async function (this: TestResponse, version: string | null) {\n const page = await this.json<Page>()\n\n expect(\n page.version,\n `Expected Inertia version \"${version}\", got \"${page.version}\"`,\n ).toBe(version)\n\n return this\n })\n\n TestResponse.macro('assertInertiaFlash', async function (this: TestResponse, key: string, value: unknown) {\n const page = await this.json<Page>()\n const actual = page.flash?.[key]\n\n expect(\n actual,\n `Expected Inertia flash \"${key}\" to be ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n ).toStrictEqual(value)\n\n return this\n })\n\n TestResponse.macro('assertInertiaDeferredProp', async function (this: TestResponse, prop: string, group: string) {\n const page = await this.json<Page>()\n\n expect(\n page.deferredProps?.[group],\n `Expected Inertia deferred group \"${group}\" to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertInertiaMergeProp', async function (this: TestResponse, prop: string) {\n const page = await this.json<Page>()\n\n expect(\n page.mergeProps,\n `Expected Inertia mergeProps to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertInertiaSharedProp', async function (this: TestResponse, prop: string) {\n const page = await this.json<Page>()\n\n expect(\n page.sharedProps,\n `Expected Inertia sharedProps to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertSuccessfulPrecognition', function (this: TestResponse) {\n this.assertNoContent()\n this.assertHeader('Precognition', 'true')\n this.assertHeader('Precognition-Success', 'true')\n\n return this\n })\n\n TestResponse.macro('assertPrecognitionValidationErrors', async function (this: TestResponse, errors?: Record<string, string>) {\n this.assertUnprocessable()\n this.assertHeader('Precognition', 'true')\n\n if (errors) {\n const body = await this.json<{ errors: Record<string, string> }>()\n\n expect(\n body.errors,\n `Expected precognition errors to match ${JSON.stringify(errors)}, got ${JSON.stringify(body.errors)}`,\n ).toStrictEqual(errors)\n }\n\n return this\n })\n}\n","import { augmentTestResponse } from './augment/test-response'\n\n// Augmentation (side-effect import: augments TestResponse types)\nimport './augment/test-response'\n\n// Patch TestResponse.prototype with Inertia assertion methods\naugmentTestResponse()\n\n// Re-export useful types for test authors\nexport type { Page as InertiaPage } from '@inertiajs/core'\n"],"mappings":";;;AAmCA,SAAgB,sBAA4B;AAC1C,cAAa,MAAM,iBAAiB,eAAoC,UAAiC;AACvG,OAAK,aAAa,aAAa,OAAO;AACtC,OAAK,UAAU;AAEf,MAAI,SAEF,UAAS,MADU,KAAK,MAAY,CACtB;AAGhB,SAAO;GACP;AAEF,cAAa,MAAM,0BAA0B,eAAoC,WAAmB;EAClG,MAAM,OAAO,MAAM,KAAK,MAAY;AAEpC,SACE,KAAK,WACL,+BAA+B,UAAU,UAAU,KAAK,UAAU,GACnE,CAAC,KAAK,UAAU;AAEjB,SAAO;GACP;AAEF,cAAa,MAAM,qBAAqB,eAAoC,MAAc,UAAmB;EAE3G,MAAM,SAAS,gBAAe,MADX,KAAK,MAAY,EACD,OAAO,KAAK;AAE/C,SACE,QACA,0BAA0B,KAAK,UAAU,KAAK,UAAU,SAAS,CAAC,QAAQ,KAAK,UAAU,OAAO,GACjG,CAAC,cAAc,SAAS;AAEzB,SAAO;GACP;AAEF,cAAa,MAAM,2BAA2B,eAAoC,MAAc;AAI9F,SAFe,gBAAe,MADX,KAAK,MAAY,EACD,OAAO,KAGlC,EACN,0BAA0B,KAAK,YAChC,CAAC,KAAK,KAAK;AAEZ,SAAO;GACP;AAEF,cAAa,MAAM,4BAA4B,eAAoC,MAAc;AAI/F,SAFe,gBAAe,MADX,KAAK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AEjD,SAAO;GACP;AAEF,cAAa,MAAM,sCAAsC,eAAoC,QAAiC;AAC5H,OAAK,qBAAqB;AAC1B,OAAK,aAAa,gBAAgB,OAAO;AAEzC,MAAI,QAAQ;GACV,MAAM,OAAO,MAAM,KAAK,MAA0C;AAElE,UACE,KAAK,QACL,yCAAyC,KAAK,UAAU,OAAO,CAAC,QAAQ,KAAK,UAAU,KAAK,OAAO,GACpG,CAAC,cAAc,OAAO;;AAGzB,SAAO;GACP;;;;AClLJ,qBAAqB"}
1
+ {"version":3,"file":"testing.mjs","names":[],"sources":["../src/augment/test-response.ts","../src/testing.ts"],"sourcesContent":["import type { Page } from '@inertiajs/core'\nimport { getValueAtPath, hasValueAtPath, TestResponse } from '@stratal/testing'\nimport { expect } from 'vitest'\n\ndeclare module '@stratal/testing' {\n interface TestResponse {\n /** Assert the response is an Inertia response. Optionally run a callback with the page object for custom assertions. */\n assertInertia(callback?: (page: Page) => void): Promise<this>\n /** Assert the Inertia page component matches the expected name. */\n assertInertiaComponent(component: string): Promise<this>\n /** Assert the Inertia page prop at the given dot-path equals the expected value. */\n assertInertiaProp(path: string, expected: unknown): Promise<this>\n /** Assert the Inertia page prop at the given dot-path exists. */\n assertInertiaPropExists(path: string): Promise<this>\n /** Assert the Inertia page prop at the given dot-path does not exist. */\n assertInertiaPropMissing(path: string): Promise<this>\n /** Assert the Inertia page URL matches the expected value. */\n assertInertiaUrl(url: string): Promise<this>\n /** Assert the Inertia page version matches the expected value. */\n assertInertiaVersion(version: string | null): Promise<this>\n /** Assert the Inertia page flash data contains the given key with the expected value. */\n assertInertiaFlash(key: string, value: unknown): Promise<this>\n /** Assert a prop is listed as deferred in the given group. */\n assertInertiaDeferredProp(prop: string, group: string): Promise<this>\n /** Assert a prop is listed as a merge prop. */\n assertInertiaMergeProp(prop: string): Promise<this>\n /** Assert a prop is listed as a shared prop. */\n assertInertiaSharedProp(prop: string): Promise<this>\n /** Assert the response is a successful precognition response (204 with precognition headers). */\n assertSuccessfulPrecognition(): this\n /** Assert the response is a precognition validation error (422 with precognition headers). Optionally assert specific errors. */\n assertPrecognitionValidationErrors(errors?: Record<string, string>): Promise<this>\n }\n}\n\nexport function augmentTestResponse(): void {\n TestResponse.macro('assertInertia', async function (this: TestResponse, callback?: (page: Page) => void) {\n this.assertHeader('x-inertia', 'true')\n this.assertOk()\n\n if (callback) {\n const page = await this.json<Page>()\n callback(page)\n }\n\n return this\n })\n\n TestResponse.macro('assertInertiaComponent', async function (this: TestResponse, component: string) {\n const page = await this.json<Page>()\n\n expect(\n page.component,\n `Expected Inertia component \"${component}\", got \"${page.component}\"`,\n ).toBe(component)\n\n return this\n })\n\n TestResponse.macro('assertInertiaProp', async function (this: TestResponse, path: string, expected: unknown) {\n const page = await this.json<Page>()\n const actual = getValueAtPath(page.props, path)\n\n expect(\n actual,\n `Expected Inertia prop \"${path}\" to be ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`,\n ).toStrictEqual(expected)\n\n return this\n })\n\n TestResponse.macro('assertInertiaPropExists', async function (this: TestResponse, path: string) {\n const page = await this.json<Page>()\n const exists = hasValueAtPath(page.props, path)\n\n expect(\n exists,\n `Expected Inertia prop \"${path}\" to exist`,\n ).toBe(true)\n\n return this\n })\n\n TestResponse.macro('assertInertiaPropMissing', async function (this: TestResponse, path: string) {\n const page = await this.json<Page>()\n const exists = hasValueAtPath(page.props, path)\n\n expect(\n exists,\n `Expected Inertia prop \"${path}\" to not exist`,\n ).toBe(false)\n\n return this\n })\n\n TestResponse.macro('assertInertiaUrl', async function (this: TestResponse, url: string) {\n const page = await this.json<Page>()\n\n expect(\n page.url,\n `Expected Inertia URL \"${url}\", got \"${page.url}\"`,\n ).toBe(url)\n\n return this\n })\n\n TestResponse.macro('assertInertiaVersion', async function (this: TestResponse, version: string | null) {\n const page = await this.json<Page>()\n\n expect(\n page.version,\n `Expected Inertia version \"${version}\", got \"${page.version}\"`,\n ).toBe(version)\n\n return this\n })\n\n TestResponse.macro('assertInertiaFlash', async function (this: TestResponse, key: string, value: unknown) {\n const page = await this.json<Page>()\n const actual = page.flash?.[key]\n\n expect(\n actual,\n `Expected Inertia flash \"${key}\" to be ${JSON.stringify(value)}, got ${JSON.stringify(actual)}`,\n ).toStrictEqual(value)\n\n return this\n })\n\n TestResponse.macro('assertInertiaDeferredProp', async function (this: TestResponse, prop: string, group: string) {\n const page = await this.json<Page>()\n\n expect(\n page.deferredProps?.[group],\n `Expected Inertia deferred group \"${group}\" to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertInertiaMergeProp', async function (this: TestResponse, prop: string) {\n const page = await this.json<Page>()\n\n expect(\n page.mergeProps,\n `Expected Inertia mergeProps to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertInertiaSharedProp', async function (this: TestResponse, prop: string) {\n const page = await this.json<Page>()\n\n expect(\n page.sharedProps,\n `Expected Inertia sharedProps to contain \"${prop}\"`,\n ).toContain(prop)\n\n return this\n })\n\n TestResponse.macro('assertSuccessfulPrecognition', function (this: TestResponse) {\n this.assertNoContent()\n this.assertHeader('Precognition', 'true')\n this.assertHeader('Precognition-Success', 'true')\n\n return this\n })\n\n TestResponse.macro('assertPrecognitionValidationErrors', async function (this: TestResponse, errors?: Record<string, string>) {\n this.assertUnprocessable()\n this.assertHeader('Precognition', 'true')\n\n if (errors) {\n const body = await this.json<{ errors: Record<string, string> }>()\n\n expect(\n body.errors,\n `Expected precognition errors to match ${JSON.stringify(errors)}, got ${JSON.stringify(body.errors)}`,\n ).toStrictEqual(errors)\n }\n\n return this\n })\n}\n","import { augmentTestResponse } from './augment/test-response'\n\n// Augmentation (side-effect import: augments TestResponse types)\nimport './augment/test-response'\n\n// Patch TestResponse.prototype with Inertia assertion methods\naugmentTestResponse()\n\n// Re-export useful types for test authors\nexport type { Page as InertiaPage } from '@inertiajs/core'\n"],"mappings":";;;AAmCA,SAAgB,sBAA4B;CAC1C,aAAa,MAAM,iBAAiB,eAAoC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a,OAAgB;EAExG,MAAM,UAAS,MADI,KAAK,MAAY,EAChB,QAAQ;EAE5B,OACE,QACA,2BAA2B,IAAI,UAAU,KAAK,UAAU,MAAM,CAAC,QAAQ,KAAK,UAAU,OAAO,GAC9F,CAAC,cAAc,MAAM;EAEtB,OAAO;GACP;CAEF,aAAa,MAAM,6BAA6B,eAAoC,MAAc,OAAe;EAG/G,QACE,MAHiB,KAAK,MAAY,EAG7B,gBAAgB,QACrB,oCAAoC,MAAM,gBAAgB,KAAK,GAChE,CAAC,UAAU,KAAK;EAEjB,OAAO;GACP;CAEF,aAAa,MAAM,0BAA0B,eAAoC,MAAc;EAG7F,QACE,MAHiB,KAAK,MAAY,EAG7B,YACL,2CAA2C,KAAK,GACjD,CAAC,UAAU,KAAK;EAEjB,OAAO;GACP;CAEF,aAAa,MAAM,2BAA2B,eAAoC,MAAc;EAG9F,QACE,MAHiB,KAAK,MAAY,EAG7B,aACL,4CAA4C,KAAK,GAClD,CAAC,UAAU,KAAK;EAEjB,OAAO;GACP;CAEF,aAAa,MAAM,gCAAgC,WAA8B;EAC/E,KAAK,iBAAiB;EACtB,KAAK,aAAa,gBAAgB,OAAO;EACzC,KAAK,aAAa,wBAAwB,OAAO;EAEjD,OAAO;GACP;CAEF,aAAa,MAAM,sCAAsC,eAAoC,QAAiC;EAC5H,KAAK,qBAAqB;EAC1B,KAAK,aAAa,gBAAgB,OAAO;EAEzC,IAAI,QAAQ;GACV,MAAM,OAAO,MAAM,KAAK,MAA0C;GAElE,OACE,KAAK,QACL,yCAAyC,KAAK,UAAU,OAAO,CAAC,QAAQ,KAAK,UAAU,KAAK,OAAO,GACpG,CAAC,cAAc,OAAO;;EAGzB,OAAO;GACP;;;;AClLJ,qBAAqB"}
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  //#region src/generator/type-generator.ts
4
4
  async function loadTsMorph() {
@@ -221,7 +221,10 @@ function extractSharedDataType(project, SK, tsObj, moduleFilePath) {
221
221
  return null;
222
222
  }
223
223
  function componentNameToPropsTypeName(componentName, segmentCount = 2) {
224
- return componentName.split("/").slice(-segmentCount).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("") + "PageProps";
224
+ return componentName.split("/").slice(-segmentCount).map(toPascalCase).join("") + "PageProps";
225
+ }
226
+ function toPascalCase(segment) {
227
+ return segment.split(/[-_\s]+/).filter((part) => part.length > 0).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
225
228
  }
226
229
  function resolvePagePropsTypeNames(pages) {
227
230
  const result = /* @__PURE__ */ new Map();
@@ -348,8 +351,14 @@ function expandTypeToInline(type, tsObj, fallbackLocation, visiting = /* @__PURE
348
351
  }
349
352
  }
350
353
  function writeInertiaTypes(outputPath, content) {
354
+ if (existsSync(outputPath)) try {
355
+ if (readFileSync(outputPath, "utf-8") === content) return false;
356
+ } catch {}
351
357
  mkdirSync(dirname(outputPath), { recursive: true });
352
- writeFileSync(outputPath, content, "utf-8");
358
+ const tmpPath = `${outputPath}.tmp-${process.pid}-${Date.now()}`;
359
+ writeFileSync(tmpPath, content, "utf-8");
360
+ renameSync(tmpPath, outputPath);
361
+ return true;
353
362
  }
354
363
  function findAppModulePath(cwd) {
355
364
  return [join(cwd, "src", "app.module.ts"), join(cwd, "src", "app.module.tsx")].find(existsSync);
@@ -388,4 +397,4 @@ async function runTypeGeneration(cwd) {
388
397
  //#endregion
389
398
  export { runTypeGeneration as n, findPagesDir as t };
390
399
 
391
- //# sourceMappingURL=type-generator-C5JljyzK.mjs.map
400
+ //# sourceMappingURL=type-generator-o_PxETTs.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type-generator-o_PxETTs.mjs","names":[],"sources":["../src/generator/type-generator.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { dirname, join } from 'node:path'\n\nexport interface PageTypeInfo {\n componentName: string\n propsType: string\n}\n\nexport interface SharedDataTypeInfo {\n members: SharedDataMember[]\n}\n\nexport interface SharedDataMember {\n name: string\n type: string\n optional: boolean\n}\n\nexport interface FlashTypeInfo {\n members: { name: string; type: string }[]\n}\n\nasync function loadTsMorph() {\n return import('ts-morph')\n}\n\ntype TsMorphModule = Awaited<ReturnType<typeof loadTsMorph>>\ntype TsObj = TsMorphModule['ts']\ntype Project = InstanceType<TsMorphModule['Project']>\ntype SourceFile = InstanceType<TsMorphModule['Project']> extends { getSourceFiles(): (infer S)[] } ? S : never\ntype Node = ReturnType<SourceFile['getDescendants']>[number]\ntype Type = ReturnType<Node['getType']>\n\n// --- Shared ts-morph project creation ---\n\nasync function createProject(tsConfigPath?: string): Promise<{ project: Project; SyntaxKind: TsMorphModule['SyntaxKind']; ts: TsObj }> {\n const { Project, SyntaxKind, ts } = await loadTsMorph()\n\n const project = new Project({\n tsConfigFilePath: tsConfigPath,\n skipAddingFilesFromTsConfig: true,\n compilerOptions: tsConfigPath ? undefined : {\n jsx: ts.JsxEmit.ReactJSX,\n esModuleInterop: true,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n module: ts.ModuleKind.ESNext,\n target: ts.ScriptTarget.ESNext,\n },\n })\n\n return { project, SyntaxKind, ts }\n}\n\n// --- Controller ctx.inertia() extraction ---\n\nconst WRAPPER_TYPE_NAMES = [\n 'InertiaDeferredProp',\n 'InertiaMergeProp',\n 'InertiaOptionalProp',\n 'InertiaOnceProp',\n 'InertiaAlwaysProp',\n]\n\nexport function extractControllerPageTypes(\n project: Project,\n SK: TsMorphModule['SyntaxKind'],\n tsObj: TsObj,\n srcDir: string,\n pagesDir: string,\n): PageTypeInfo[] {\n project.addSourceFilesAtPaths(join(srcDir, '**/*.ts'))\n\n // Map from component name to all collected prop type strings (one per call site)\n const pages = new Map<string, string[]>()\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath()\n if (filePath.includes(pagesDir.replace(/\\\\/g, '/'))) continue\n // Skip test files\n if (filePath.includes('__tests__') || filePath.includes('.spec.') || filePath.includes('.test.')) continue\n\n const callExpressions = sourceFile.getDescendantsOfKind(SK.CallExpression)\n\n for (const call of callExpressions) {\n const expr = call.getExpression()\n if (!expr.isKind(SK.PropertyAccessExpression)) continue\n if (expr.getName() !== 'inertia') continue\n\n const args = call.getArguments()\n if (args.length === 0) continue\n\n // First arg must be a string literal (component name)\n const firstArg = args[0]\n if (!firstArg.isKind(SK.StringLiteral)) continue\n const componentName = firstArg.getLiteralValue()\n\n if (!pages.has(componentName)) {\n pages.set(componentName, [])\n }\n\n // Second arg is the props object\n if (args.length < 2) {\n pages.get(componentName)!.push('Record<string, never>')\n continue\n }\n\n const propsArg = args[1]\n const propsType = propsArg.getType()\n\n // Unwrap prop wrappers from each property\n if (propsType.isObject() && !propsType.isArray()) {\n const properties = propsType.getProperties()\n if (properties.length === 0) {\n pages.get(componentName)!.push('Record<string, never>')\n continue\n }\n\n const members = properties.map((prop) => {\n const decl = prop.getDeclarations()[0] ?? prop.getValueDeclaration()\n const location = decl ?? propsArg\n const isOptional = prop.isOptional()\n const propType = prop.getTypeAtLocation(location)\n const unwrapped = unwrapWrapperType(propType, tsObj, propsArg)\n return `${prop.getName()}${isOptional ? '?' : ''}: ${unwrapped}`\n })\n\n pages.get(componentName)!.push(`{ ${members.join('; ')} }`)\n } else {\n pages.get(componentName)!.push(typeToString(propsType, tsObj, propsArg))\n }\n }\n }\n\n return Array.from(pages.entries())\n .map(([componentName, typeVariants]) => {\n // Deduplicate identical variants then join with union\n const unique = [...new Set(typeVariants)]\n const propsType = unique.length === 1 ? unique[0] : unique.join(' | ')\n return { componentName, propsType }\n })\n .sort((a, b) => a.componentName.localeCompare(b.componentName))\n}\n\nfunction unwrapWrapperType(type: Type, tsObj: TsObj, fallbackLocation?: Node): string {\n if (type.isUnion()) {\n const unionTypes = type.getUnionTypes()\n const unwrapped = unionTypes\n .filter((t) => {\n const text = t.getText(undefined, tsObj.TypeFormatFlags.NoTruncation)\n return !WRAPPER_TYPE_NAMES.some((name) => text.includes(name))\n })\n .map((t) => typeToString(t, tsObj, fallbackLocation))\n\n if (unwrapped.length > 0) {\n return unwrapped.join(' | ')\n }\n }\n\n // Check if the type itself is a wrapper type — extract callback return type\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation)\n for (const wrapperName of WRAPPER_TYPE_NAMES) {\n if (text.includes(wrapperName)) {\n const callbackProp = type.getProperty('callback')\n if (callbackProp) {\n const decl = callbackProp.getDeclarations()[0] ?? callbackProp.getValueDeclaration()\n const location = decl ?? fallbackLocation\n if (!location) return 'unknown'\n const callbackType = callbackProp.getTypeAtLocation(location)\n const callSignatures = callbackType.getCallSignatures()\n if (callSignatures.length > 0) {\n return unwrapPromise(callSignatures[0].getReturnType(), tsObj, fallbackLocation)\n }\n }\n return 'unknown'\n }\n }\n\n return widenLiteralType(type, tsObj, fallbackLocation)\n}\n\nfunction unwrapPromise(type: Type, tsObj: TsObj, fallbackLocation?: Node): string {\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation)\n if (text.startsWith('Promise<')) {\n const typeArgs = type.getTypeArguments()\n if (typeArgs.length > 0) {\n return stripReadonly(typeArgs[0], tsObj, fallbackLocation)\n }\n }\n return stripReadonly(type, tsObj, fallbackLocation)\n}\n\nfunction stripReadonly(type: Type, tsObj: TsObj, fallbackLocation?: Node): string {\n if (type.isTuple()) {\n const elements = type.getTupleElements()\n const parts = elements.map((e) => typeToString(e, tsObj, fallbackLocation))\n return `[${parts.join(', ')}]`\n }\n\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation)\n if (text.startsWith('readonly ') && type.isArray()) {\n const elementType = type.getArrayElementType()\n if (elementType) {\n return `Array<${typeToString(elementType, tsObj, fallbackLocation)}>`\n }\n }\n\n return typeToString(type, tsObj, fallbackLocation)\n}\n\n// --- Extract this.inertia.share() call types ---\n\nexport function extractShareCallTypes(\n project: Project,\n SK: TsMorphModule['SyntaxKind'],\n tsObj: TsObj,\n srcDir: string,\n): Map<string, string> {\n const shareTypes = new Map<string, string>()\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath()\n if (!filePath.startsWith(srcDir.replace(/\\\\/g, '/'))) continue\n if (filePath.includes('__tests__') || filePath.includes('.spec.') || filePath.includes('.test.')) continue\n\n const callExpressions = sourceFile.getDescendantsOfKind(SK.CallExpression)\n\n for (const call of callExpressions) {\n const expr = call.getExpression()\n if (!expr.isKind(SK.PropertyAccessExpression)) continue\n if (expr.getName() !== 'share') continue\n\n // Check that the object is inertia-related (this.inertia.share, inertia.share)\n const objExpr = expr.getExpression()\n const objText = objExpr.getText()\n if (!objText.includes('inertia')) continue\n\n const args = call.getArguments()\n if (args.length < 2) continue\n\n const keyArg = args[0]\n if (!keyArg.isKind(SK.StringLiteral)) continue\n const key = keyArg.getLiteralValue()\n\n if (shareTypes.has(key)) continue\n\n const valueType = widenLiteralType(args[1].getType(), tsObj)\n shareTypes.set(key, valueType)\n }\n }\n\n return shareTypes\n}\n\n// --- Detect i18n config in InertiaModule.forRoot() ---\n\nexport function detectI18nConfig(\n project: Project,\n SK: TsMorphModule['SyntaxKind'],\n moduleFilePath: string,\n): boolean {\n const sourceFile = project.getSourceFile(moduleFilePath)\n if (!sourceFile) return false\n\n const callExpressions = sourceFile.getDescendantsOfKind(SK.CallExpression)\n\n for (const call of callExpressions) {\n const expr = call.getExpression()\n if (!expr.isKind(SK.PropertyAccessExpression)) continue\n\n const propName = expr.getName()\n if (propName !== 'forRoot' && propName !== 'forRootAsync') continue\n\n const objExpr = expr.getExpression()\n if (!objExpr.isKind(SK.Identifier) || objExpr.getText() !== 'InertiaModule') continue\n\n const args = call.getArguments()\n if (args.length === 0) continue\n\n const optionsArg = args[0]\n if (!optionsArg.isKind(SK.ObjectLiteralExpression)) continue\n\n return !!optionsArg.getProperty('i18n')\n }\n\n return false\n}\n\n// --- Extract ctx.flash() call types ---\n\nexport function extractFlashTypes(\n project: Project,\n SK: TsMorphModule['SyntaxKind'],\n tsObj: TsObj,\n srcDir: string,\n): FlashTypeInfo | null {\n const flashMembers = new Map<string, string>()\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath()\n if (!filePath.startsWith(srcDir.replace(/\\\\/g, '/'))) continue\n if (filePath.includes('__tests__') || filePath.includes('.spec.') || filePath.includes('.test.')) continue\n\n const callExpressions = sourceFile.getDescendantsOfKind(SK.CallExpression)\n\n for (const call of callExpressions) {\n const expr = call.getExpression()\n if (!expr.isKind(SK.PropertyAccessExpression)) continue\n if (expr.getName() !== 'flash') continue\n\n const args = call.getArguments()\n if (args.length < 2) continue\n\n const keyArg = args[0]\n if (!keyArg.isKind(SK.StringLiteral)) continue\n const key = keyArg.getLiteralValue()\n\n if (flashMembers.has(key)) continue\n\n const valueType = widenLiteralType(args[1].getType(), tsObj)\n flashMembers.set(key, valueType)\n }\n }\n\n if (flashMembers.size === 0) return null\n\n return {\n members: Array.from(flashMembers.entries()).map(([name, type]) => ({ name, type })),\n }\n}\n\n// --- Extract shared data from module config (existing, refactored) ---\n\nexport function extractSharedDataType(\n project: Project,\n SK: TsMorphModule['SyntaxKind'],\n tsObj: TsObj,\n moduleFilePath: string,\n): SharedDataTypeInfo | null {\n const sourceFile = project.getSourceFile(moduleFilePath)\n ?? project.addSourceFileAtPath(moduleFilePath)\n\n const callExpressions = sourceFile.getDescendantsOfKind(SK.CallExpression)\n\n for (const call of callExpressions) {\n const expr = call.getExpression()\n if (!expr.isKind(SK.PropertyAccessExpression)) continue\n\n const propName = expr.getName()\n if (propName !== 'forRoot' && propName !== 'forRootAsync') continue\n\n const objExpr = expr.getExpression()\n if (!objExpr.isKind(SK.Identifier) || objExpr.getText() !== 'InertiaModule') continue\n\n const args = call.getArguments()\n if (args.length === 0) continue\n\n const optionsArg = args[0]\n if (!optionsArg.isKind(SK.ObjectLiteralExpression)) continue\n\n const sharedDataProp = optionsArg.getProperty('sharedData')\n if (!sharedDataProp) continue\n\n if (!sharedDataProp.isKind(SK.PropertyAssignment)) continue\n\n const initializer = sharedDataProp.getInitializer()\n if (!initializer?.isKind(SK.ObjectLiteralExpression)) continue\n\n const members: SharedDataMember[] = []\n for (const prop of initializer.getProperties()) {\n if (!prop.isKind(SK.PropertyAssignment)) continue\n\n const name = prop.getName()\n const value = prop.getInitializer()\n if (!value) continue\n\n let valueType: string\n\n if (value.isKind(SK.ArrowFunction) || value.isKind(SK.FunctionExpression)) {\n const returnType = value.getReturnType()\n valueType = typeToString(returnType, tsObj)\n } else {\n valueType = typeToString(value.getType(), tsObj)\n }\n\n members.push({ name, type: valueType, optional: false })\n }\n\n if (members.length > 0) {\n return { members }\n }\n }\n\n return null\n}\n\n// --- Generate output ---\n\nexport interface GenerateTypesInput {\n pages: PageTypeInfo[]\n sharedData: SharedDataTypeInfo | null\n shareCallTypes: Map<string, string>\n hasI18n: boolean\n flashTypes: FlashTypeInfo | null\n}\n\nfunction componentNameToPropsTypeName(componentName: string, segmentCount = 2): string {\n const segments = componentName.split('/')\n const used = segments.slice(-segmentCount)\n return used.map(toPascalCase).join('') + 'PageProps'\n}\n\nfunction toPascalCase(segment: string): string {\n return segment\n .split(/[-_\\s]+/)\n .filter((part) => part.length > 0)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join('')\n}\n\nfunction resolvePagePropsTypeNames(pages: PageTypeInfo[]): Map<string, string> {\n const result = new Map<string, string>()\n\n // First pass: use last 2 segments\n const nameToComponents = new Map<string, string[]>()\n for (const page of pages) {\n const typeName = componentNameToPropsTypeName(page.componentName)\n const existing = nameToComponents.get(typeName) ?? []\n existing.push(page.componentName)\n nameToComponents.set(typeName, existing)\n }\n\n // Second pass: resolve collisions by using all segments\n for (const [typeName, components] of nameToComponents) {\n if (components.length === 1) {\n result.set(components[0], typeName)\n } else {\n for (const componentName of components) {\n const fullSegments = componentName.split('/').length\n result.set(componentName, componentNameToPropsTypeName(componentName, fullSegments))\n }\n }\n }\n\n return result\n}\n\nexport function generateInertiaTypes(input: GenerateTypesInput): string {\n const { pages, sharedData, shareCallTypes, hasI18n, flashTypes } = input\n\n // Compute type names with collision resolution\n const typeNames = resolvePagePropsTypeNames(pages)\n\n const lines: string[] = [\n '// Auto-generated by @stratal/inertia. Do not edit.',\n ]\n\n // Global page props types\n if (pages.length > 0) {\n lines.push('declare global {')\n for (const page of pages) {\n const typeName = typeNames.get(page.componentName)!\n lines.push(` type ${typeName} = ${page.propsType}`)\n }\n lines.push('}')\n lines.push('')\n }\n\n // InertiaPageRegistry augmentation referencing global types\n lines.push(\"declare module '@stratal/inertia' {\")\n lines.push(' interface InertiaPageRegistry {')\n for (const page of pages) {\n const typeName = typeNames.get(page.componentName)!\n lines.push(` '${page.componentName}': ${typeName}`)\n }\n lines.push(' }')\n lines.push('}')\n\n // Build InertiaConfig augmentation\n const configMembers: string[] = []\n\n // Flash data type\n if (flashTypes && flashTypes.members.length > 0) {\n const flashProps = flashTypes.members\n .map((m) => `${m.name}?: ${m.type}`)\n .join('; ')\n configMembers.push(` flashDataType: { ${flashProps} }`)\n }\n\n // Shared page props\n const sharedMembers: string[] = []\n\n // From module config (non-optional)\n if (sharedData) {\n for (const member of sharedData.members) {\n sharedMembers.push(` ${member.name}${member.optional ? '?' : ''}: ${member.type}`)\n }\n }\n\n // From i18n detection (non-optional)\n if (hasI18n) {\n sharedMembers.push(' locale: string')\n sharedMembers.push(' translations: Record<string, string>')\n }\n\n // From .share() calls (optional — per-request)\n for (const [key, type] of shareCallTypes) {\n // Skip if already declared by module config\n if (sharedData?.members.some((m) => m.name === key)) continue\n sharedMembers.push(` ${key}?: ${type}`)\n }\n\n if (sharedMembers.length > 0) {\n configMembers.push(` sharedPageProps: {\\n${sharedMembers.join('\\n')}\\n }`)\n }\n\n if (configMembers.length > 0) {\n lines.push('')\n lines.push(\"declare module '@inertiajs/core' {\")\n lines.push(' export interface InertiaConfig {')\n for (const member of configMembers) {\n lines.push(member)\n }\n lines.push(' }')\n lines.push('}')\n }\n\n lines.push('', 'export {}', '')\n\n return lines.join('\\n')\n}\n\n// --- Type string helpers ---\n\nfunction widenLiteralType(type: Type, tsObj: TsObj, fallbackLocation?: Node): string {\n if (type.isStringLiteral()) return 'string'\n if (type.isNumberLiteral()) return 'number'\n if (type.isBooleanLiteral()) return 'boolean'\n return typeToString(type, tsObj, fallbackLocation)\n}\n\nfunction typeToString(type: Type, tsObj: TsObj, fallbackLocation?: Node): string {\n // Always expand objects/unions/intersections so getText() can't leak inline\n // index signatures (e.g. StratalRouteMap params' `[key: string]: ...`).\n if (type.isObject() || type.isUnion() || type.isIntersection()) {\n return expandTypeToInline(type, tsObj, fallbackLocation)\n }\n\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation | tsObj.TypeFormatFlags.UseFullyQualifiedType)\n\n if (text.includes('import(')) {\n return expandTypeToInline(type, tsObj, fallbackLocation)\n }\n\n return text\n}\n\nfunction expandPropertyType(\n type: Type,\n tsObj: TsObj,\n fallbackLocation: Node | undefined,\n visiting: Set<Type>,\n isOptional: boolean,\n): string {\n // The `?` marker already implies `undefined`, so strip it from the union\n // to avoid `id?: undefined | string`.\n if (isOptional && type.isUnion()) {\n const parts = type.getUnionTypes().filter((t) => !t.isUndefined())\n if (parts.length === 0) return 'undefined'\n if (parts.length === 1) return expandTypeToInline(parts[0], tsObj, fallbackLocation, visiting)\n return parts.map((t) => expandTypeToInline(t, tsObj, fallbackLocation, visiting)).join(' | ')\n }\n return expandTypeToInline(type, tsObj, fallbackLocation, visiting)\n}\n\nfunction expandTypeToInline(\n type: Type,\n tsObj: TsObj,\n fallbackLocation?: Node,\n visiting = new Set<Type>(),\n): string {\n if (visiting.has(type)) return 'unknown'\n // `boolean` is internally `true | false` — short-circuit before the union branch.\n if (type.isBoolean()) return 'boolean'\n visiting.add(type)\n try {\n if (type.isObject() && !type.isArray() && !type.isReadonlyArray()) {\n // Named global types (Date, RegExp, Map, Set, ...) — emit text as-is.\n // Expanding them iterates every method and produces garbage like\n // `{ toString: ...; getTime: ...; }` for Date.\n const symbolName = type.getSymbol()?.getName()\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation | tsObj.TypeFormatFlags.UseFullyQualifiedType)\n if (\n symbolName\n && !symbolName.startsWith('__')\n && symbolName !== 'Object'\n && !text.includes('import(')\n ) {\n return text\n }\n\n const properties = type.getProperties()\n if (properties.length === 0) {\n const stringIndexType = type.getStringIndexType()\n if (stringIndexType) {\n return `Record<string, ${expandTypeToInline(stringIndexType, tsObj, fallbackLocation, visiting)}>`\n }\n // Use `{}` not `Record<string, never>` — `never` collapses intersections.\n return '{}'\n }\n\n const members = properties.map((prop) => {\n const decl = prop.getDeclarations()[0] ?? prop.getValueDeclaration()\n const location = decl ?? fallbackLocation\n const isOptional = prop.isOptional()\n if (!location) return `${prop.getName()}${isOptional ? '?' : ''}: unknown`\n const propType = prop.getTypeAtLocation(location)\n const propTypeStr = expandPropertyType(propType, tsObj, fallbackLocation, visiting, isOptional)\n return `${prop.getName()}${isOptional ? '?' : ''}: ${propTypeStr}`\n })\n\n return `{ ${members.join('; ')} }`\n }\n\n if (type.isArray() || type.isReadonlyArray()) {\n const elementType = type.getArrayElementType()\n if (elementType) {\n const inner = expandTypeToInline(elementType, tsObj, fallbackLocation, visiting)\n return type.isReadonlyArray() ? `ReadonlyArray<${inner}>` : `Array<${inner}>`\n }\n }\n\n if (type.isUnion()) {\n return type.getUnionTypes().map((t) => expandTypeToInline(t, tsObj, fallbackLocation, visiting)).join(' | ')\n }\n\n if (type.isIntersection()) {\n return type.getIntersectionTypes().map((t) => expandTypeToInline(t, tsObj, fallbackLocation, visiting)).join(' & ')\n }\n\n const text = type.getText(undefined, tsObj.TypeFormatFlags.NoTruncation)\n if (text.includes('import(')) {\n return 'unknown'\n }\n return text\n } finally {\n visiting.delete(type)\n }\n}\n\n// --- File path helpers ---\n\nexport function writeInertiaTypes(outputPath: string, content: string): boolean {\n if (existsSync(outputPath)) {\n try {\n if (readFileSync(outputPath, 'utf-8') === content) return false\n } catch {\n // fall through and write\n }\n }\n mkdirSync(dirname(outputPath), { recursive: true })\n const tmpPath = `${outputPath}.tmp-${process.pid}-${Date.now()}`\n writeFileSync(tmpPath, content, 'utf-8')\n renameSync(tmpPath, outputPath)\n return true\n}\n\nexport function findAppModulePath(cwd: string): string | undefined {\n const candidates = [\n join(cwd, 'src', 'app.module.ts'),\n join(cwd, 'src', 'app.module.tsx'),\n ]\n\n return candidates.find(existsSync)\n}\n\nexport function findPagesDir(cwd: string): string {\n return join(cwd, 'src', 'inertia', 'pages')\n}\n\nexport function findOutputPath(cwd: string): string {\n return join(cwd, 'src', 'inertia', 'inertia.d.ts')\n}\n\nexport function findTsConfigPath(cwd: string): string | undefined {\n const candidate = join(cwd, 'tsconfig.json')\n return existsSync(candidate) ? candidate : undefined\n}\n\n// --- Main pipeline ---\n\nexport async function runTypeGeneration(cwd: string): Promise<{ outputPath: string; pageCount: number }> {\n const pagesDir = findPagesDir(cwd)\n const srcDir = join(cwd, 'src')\n const outputPath = findOutputPath(cwd)\n const moduleFilePath = findAppModulePath(cwd)\n const tsConfigPath = findTsConfigPath(cwd)\n\n // Single shared project for all extractors\n const { project, SyntaxKind, ts } = await createProject(tsConfigPath)\n\n // 1. Controller ctx.inertia() calls — sole source of truth for InertiaPageRegistry\n const pages = extractControllerPageTypes(project, SyntaxKind, ts, srcDir, pagesDir)\n\n // 2. Module shared data config\n const sharedData = moduleFilePath\n ? extractSharedDataType(project, SyntaxKind, ts, moduleFilePath)\n : null\n\n // 3. i18n detection\n const hasI18n = moduleFilePath\n ? detectI18nConfig(project, SyntaxKind, moduleFilePath)\n : false\n\n // 4. Per-request .share() calls\n const shareCallTypes = extractShareCallTypes(project, SyntaxKind, ts, srcDir)\n\n // 5. Flash ctx.flash() calls\n const flashTypes = extractFlashTypes(project, SyntaxKind, ts, srcDir)\n\n // 6. Generate\n const content = generateInertiaTypes({\n pages,\n sharedData,\n shareCallTypes,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AGnF,MAAM,aAAa,iBACf,sBAAsB,SAAS,YAAY,IAAI,eAAe,GAC9D;CAGJ,MAAM,UAAU,iBACZ,iBAAiB,SAAS,YAAY,eAAe,GACrD;CAgBJ,kBAAkB,YAPF,qBAAqB;EACnC;EACA;EACA,gBATqB,sBAAsB,SAAS,YAAY,IAAI,OAStD;EACd;EACA,YARiB,kBAAkB,SAAS,YAAY,IAAI,OAQlD;EACX,CACoC,CAAC;CAEtC,OAAO;EAAE;EAAY,WAAW,MAAM;EAAQ"}
@@ -1 +1 @@
1
- {"version":3,"file":"vite.d.mts","names":[],"sources":["../src/vite/inertia-dev-css-plugin.ts","../src/vite/inertia-types-plugin.ts","../src/vite.ts"],"mappings":";;;UAMiB,oBAAA;EACf,OAAA;AAAA;AAAA,iBAqEc,oBAAA,CAAqB,OAAA,EAAS,oBAAA,GAAuB,MAAA;;;iBCrErD,mBAAA,CAAA,GAAuB,MAAA;;;UCDtB,2BAAA;;EAEf,OAAA;AAAA;AAAA,iBAGc,cAAA,CAAe,OAAA,GAAU,2BAAA,GAA8B,MAAA"}
1
+ {"version":3,"file":"vite.d.mts","names":[],"sources":["../src/vite/inertia-dev-css-plugin.ts","../src/vite/inertia-types-plugin.ts","../src/vite.ts"],"mappings":";;;UAMiB,oBAAA;EACf,OAAA;AAAA;AAAA,iBAqEc,oBAAA,CAAqB,OAAA,EAAS,oBAAA,GAAuB,MAAA;;;iBCpErD,mBAAA,CAAA,GAAuB,MAAA;;;UCFtB,2BAAA;;EAEf,OAAA;AAAA;AAAA,iBAGc,cAAA,CAAe,OAAA,GAAU,2BAAA,GAA8B,MAAA"}
package/dist/vite.mjs CHANGED
@@ -1,6 +1,8 @@
1
- import { n as runTypeGeneration, t as findPagesDir } from "./type-generator-C5JljyzK.mjs";
1
+ import { n as runTypeGeneration, t as findPagesDir } from "./type-generator-o_PxETTs.mjs";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { join, relative } from "node:path";
4
+ import { URL as URL$1 } from "node:url";
5
+ import { Worker } from "node:worker_threads";
4
6
  //#region src/vite/inertia-dev-css-plugin.ts
5
7
  const CSS_LANGS_RE = /\.(css|scss|sass|less|styl|stylus|pcss|postcss)(?:$|\?)/;
6
8
  const VIRTUAL_MODULE_ID = "virtual:inertia-ssr.css";
@@ -37,6 +39,25 @@ async function collectStyle(server, entries) {
37
39
  }
38
40
  function stratalInertiaDevCss(options) {
39
41
  let server;
42
+ let cachedCss = null;
43
+ let inflight = null;
44
+ let cacheEpoch = 0;
45
+ function invalidate() {
46
+ cachedCss = null;
47
+ cacheEpoch++;
48
+ }
49
+ async function getCss() {
50
+ if (cachedCss !== null) return cachedCss;
51
+ if (inflight) return inflight;
52
+ const epoch = cacheEpoch;
53
+ inflight = collectStyle(server, options.entries).then((css) => {
54
+ if (epoch === cacheEpoch) cachedCss = css;
55
+ return css;
56
+ }).finally(() => {
57
+ inflight = null;
58
+ });
59
+ return inflight;
60
+ }
40
61
  return {
41
62
  name: "stratal:inertia-dev-css",
42
63
  apply: "serve",
@@ -44,7 +65,10 @@ function stratalInertiaDevCss(options) {
44
65
  if (id === VIRTUAL_MODULE_ID) return RESOLVED_VIRTUAL_MODULE_ID;
45
66
  },
46
67
  async load(id) {
47
- if (id === RESOLVED_VIRTUAL_MODULE_ID) return await collectStyle(server, options.entries);
68
+ if (id === RESOLVED_VIRTUAL_MODULE_ID) return await getCss();
69
+ },
70
+ handleHotUpdate() {
71
+ invalidate();
48
72
  },
49
73
  configureServer(devServer) {
50
74
  server = devServer;
@@ -53,7 +77,7 @@ function stratalInertiaDevCss(options) {
53
77
  next();
54
78
  return;
55
79
  }
56
- collectStyle(server, options.entries).then((css) => {
80
+ getCss().then((css) => {
57
81
  res.setHeader("Content-Type", "text/css");
58
82
  res.setHeader("Cache-Control", "no-store");
59
83
  res.end(css);
@@ -66,18 +90,90 @@ function stratalInertiaDevCss(options) {
66
90
  };
67
91
  }
68
92
  //#endregion
93
+ //#region src/vite/type-gen-dispatcher.ts
94
+ const defaultSpawn = (cwd) => new Worker(new URL$1("./generator/type-generator.worker.mjs", import.meta.url), { workerData: { cwd } });
95
+ function createTypeGenDispatcher(options) {
96
+ const spawn = options.spawn ?? defaultSpawn;
97
+ const debounceMs = options.debounceMs ?? 250;
98
+ let pendingTimer = null;
99
+ let inflight = null;
100
+ let queued = false;
101
+ let disposed = false;
102
+ function fire() {
103
+ pendingTimer = null;
104
+ if (disposed) return;
105
+ if (inflight) {
106
+ queued = true;
107
+ return;
108
+ }
109
+ const worker = spawn(options.cwd);
110
+ inflight = worker;
111
+ const finish = () => {
112
+ if (inflight === worker) inflight = null;
113
+ if (disposed) return;
114
+ if (queued) {
115
+ queued = false;
116
+ fire();
117
+ }
118
+ };
119
+ worker.on("message", (msg) => {
120
+ options.onResult?.(msg);
121
+ });
122
+ worker.on("error", (err) => {
123
+ options.onError?.(err);
124
+ });
125
+ worker.on("exit", () => {
126
+ finish();
127
+ });
128
+ }
129
+ return {
130
+ schedule() {
131
+ if (disposed) return;
132
+ if (inflight) {
133
+ queued = true;
134
+ return;
135
+ }
136
+ if (pendingTimer) clearTimeout(pendingTimer);
137
+ pendingTimer = setTimeout(fire, debounceMs);
138
+ },
139
+ async dispose() {
140
+ disposed = true;
141
+ queued = false;
142
+ if (pendingTimer) {
143
+ clearTimeout(pendingTimer);
144
+ pendingTimer = null;
145
+ }
146
+ const worker = inflight;
147
+ inflight = null;
148
+ if (worker) try {
149
+ await worker.terminate();
150
+ } catch {}
151
+ }
152
+ };
153
+ }
154
+ //#endregion
69
155
  //#region src/vite/inertia-types-plugin.ts
70
156
  const INERTIA_CALL_PATTERN = /ctx\.inertia\(|\.share\(|ctx\.flash\(|ctx\.defer\(|ctx\.optional\(|ctx\.merge\(|ctx\.once\(|ctx\.always\(/;
71
157
  function stratalInertiaTypes() {
72
158
  let cwd;
73
159
  let pagesDir;
74
160
  let srcDir;
161
+ let dispatcher = null;
75
162
  return {
76
163
  name: "stratal:inertia-types",
77
164
  configResolved(config) {
78
165
  cwd = config.root;
79
166
  pagesDir = findPagesDir(cwd) + "/";
80
167
  srcDir = join(cwd, "src") + "/";
168
+ dispatcher = createTypeGenDispatcher({
169
+ cwd,
170
+ onError(err) {
171
+ console.warn("[stratal:inertia-types] Type generation worker errored:", err.message);
172
+ },
173
+ onResult(result) {
174
+ if (!result.ok && result.error) console.warn("[stratal:inertia-types] Type generation failed:", result.error);
175
+ }
176
+ });
81
177
  },
82
178
  async buildStart() {
83
179
  if (!existsSync(pagesDir)) return;
@@ -87,7 +183,8 @@ function stratalInertiaTypes() {
87
183
  console.warn("[stratal:inertia-types] Type generation failed during build:", error);
88
184
  }
89
185
  },
90
- async handleHotUpdate({ file }) {
186
+ handleHotUpdate({ file }) {
187
+ if (!dispatcher) return;
91
188
  if (!/\.(tsx|ts)$/.test(file)) return;
92
189
  if (!!relative(srcDir, file).startsWith("..")) return;
93
190
  if (!!relative(pagesDir, file).startsWith("..")) try {
@@ -96,10 +193,12 @@ function stratalInertiaTypes() {
96
193
  } catch {
97
194
  return;
98
195
  }
99
- try {
100
- await runTypeGeneration(cwd);
101
- } catch (error) {
102
- console.warn("[stratal:inertia-types] Type generation failed during HMR:", error);
196
+ dispatcher.schedule();
197
+ },
198
+ async closeBundle() {
199
+ if (dispatcher) {
200
+ await dispatcher.dispose();
201
+ dispatcher = null;
103
202
  }
104
203
  }
105
204
  };
@@ -118,6 +217,23 @@ function stratalInertia(options) {
118
217
  "@hono/zod-openapi",
119
218
  "@hono/swagger-ui"
120
219
  ];
220
+ const dedupe = [
221
+ "react",
222
+ "react-dom",
223
+ "react-is",
224
+ "scheduler",
225
+ "@inertiajs/core",
226
+ "@inertiajs/react"
227
+ ];
228
+ const noExternal = [
229
+ "react",
230
+ "react-dom",
231
+ "react-is",
232
+ "scheduler",
233
+ "use-sync-external-store",
234
+ "@inertiajs/core",
235
+ "@inertiajs/react"
236
+ ];
121
237
  const optimizeDepsInclude = [
122
238
  "buffer",
123
239
  "buffer/",
@@ -138,6 +254,14 @@ function stratalInertia(options) {
138
254
  exclude: [...existing, ...optimizeDepsExclude],
139
255
  include: [...existingInclude, ...optimizeDepsInclude]
140
256
  };
257
+ const existingDedupe = env.resolve?.dedupe ?? [];
258
+ const existingNoExternal = env.resolve?.noExternal;
259
+ const mergedNoExternal = [...Array.isArray(existingNoExternal) ? existingNoExternal : typeof existingNoExternal === "string" || existingNoExternal instanceof RegExp ? [existingNoExternal] : [], ...noExternal];
260
+ env.resolve = {
261
+ ...env.resolve,
262
+ dedupe: [...existingDedupe, ...dedupe],
263
+ noExternal: existingNoExternal === true ? true : mergedNoExternal
264
+ };
141
265
  const existingExternal = env.build?.rolldownOptions?.external ?? [];
142
266
  env.build = {
143
267
  ...env.build,
package/dist/vite.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"vite.mjs","names":[],"sources":["../src/vite/inertia-dev-css-plugin.ts","../src/vite/inertia-types-plugin.ts","../src/vite.ts"],"sourcesContent":["import type { ModuleNode, Plugin, ViteDevServer } from 'vite'\n\nconst CSS_LANGS_RE = /\\.(css|scss|sass|less|styl|stylus|pcss|postcss)(?:$|\\?)/\nconst VIRTUAL_MODULE_ID = 'virtual:inertia-ssr.css'\nconst RESOLVED_VIRTUAL_MODULE_ID = '\\0' + VIRTUAL_MODULE_ID\n\nexport interface InertiaDevCssOptions {\n entries: string[]\n}\n\nfunction collectStyleUrls(server: ViteDevServer, entries: string[]): string[] {\n const urls: string[] = []\n const visited = new Set<string>()\n\n function traverse(mod: ModuleNode) {\n if (visited.has(mod.url)) return\n visited.add(mod.url)\n\n if (CSS_LANGS_RE.test(mod.url)) {\n urls.push(mod.url)\n }\n\n for (const imported of mod.importedModules) {\n traverse(imported)\n }\n }\n\n for (const entry of entries) {\n const mod = server.moduleGraph.getModulesByFile(\n entry.startsWith('/') ? entry.slice(1) : entry,\n )\n\n if (mod) {\n for (const m of mod) {\n traverse(m)\n }\n }\n\n const urlMod = server.moduleGraph.urlToModuleMap.get(entry)\n if (urlMod) {\n traverse(urlMod)\n }\n }\n\n return urls\n}\n\nasync function collectStyle(server: ViteDevServer, entries: string[]): Promise<string> {\n for (const entry of entries) {\n try {\n await server.transformRequest(entry)\n }\n catch {\n //\n }\n }\n\n const urls = collectStyleUrls(server, entries)\n const styles: string[] = []\n\n for (const url of urls) {\n try {\n const separator = url.includes('?') ? '&' : '?'\n const result = await server.transformRequest(url + separator + 'direct')\n if (result?.code) {\n styles.push(result.code)\n }\n }\n catch {\n //\n }\n }\n\n return styles.join('\\n')\n}\n\nexport function stratalInertiaDevCss(options: InertiaDevCssOptions): Plugin {\n let server: ViteDevServer\n\n return {\n name: 'stratal:inertia-dev-css',\n apply: 'serve',\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n return await collectStyle(server, options.entries)\n }\n },\n\n configureServer(devServer) {\n server = devServer\n\n server.middlewares.use((req, res, next) => {\n const pathname = new URL(req.url ?? '', 'http://localhost').pathname\n if (pathname !== '/__inertia/ssr-css') { next(); return; }\n\n collectStyle(server, options.entries).then((css) => {\n res.setHeader('Content-Type', 'text/css')\n res.setHeader('Cache-Control', 'no-store')\n res.end(css)\n }).catch(() => {\n res.statusCode = 500\n res.end('')\n })\n })\n },\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport type { Plugin } from 'vite'\nimport { findPagesDir, runTypeGeneration } from '../generator/type-generator'\n\nconst INERTIA_CALL_PATTERN = /ctx\\.inertia\\(|\\.share\\(|ctx\\.flash\\(|ctx\\.defer\\(|ctx\\.optional\\(|ctx\\.merge\\(|ctx\\.once\\(|ctx\\.always\\(/\n\nexport function stratalInertiaTypes(): Plugin {\n let cwd: string\n let pagesDir: string\n let srcDir: string\n\n return {\n name: 'stratal:inertia-types',\n\n configResolved(config) {\n cwd = config.root\n pagesDir = findPagesDir(cwd) + '/'\n srcDir = join(cwd, 'src') + '/'\n },\n\n async buildStart() {\n if (!existsSync(pagesDir)) return\n try {\n await runTypeGeneration(cwd)\n } catch (error) {\n console.warn('[stratal:inertia-types] Type generation failed during build:', error)\n }\n },\n\n async handleHotUpdate({ file }) {\n if (!/\\.(tsx|ts)$/.test(file)) return\n\n const relToSrc = relative(srcDir, file)\n const isInSrc = !relToSrc.startsWith('..')\n\n if (!isInSrc) return\n\n // Page files always trigger regeneration\n const relToPages = relative(pagesDir, file)\n const isPageFile = !relToPages.startsWith('..')\n\n if (!isPageFile) {\n // For non-page files, only regenerate if they contain inertia-related calls\n try {\n const content = readFileSync(file, 'utf-8')\n if (!INERTIA_CALL_PATTERN.test(content)) return\n } catch {\n return\n }\n }\n\n try {\n await runTypeGeneration(cwd)\n } catch (error) {\n console.warn('[stratal:inertia-types] Type generation failed during HMR:', error)\n }\n },\n }\n}\n","import type { EnvironmentOptions, Plugin } from 'vite'\nimport { stratalInertiaDevCss } from './vite/inertia-dev-css-plugin'\nimport { stratalInertiaTypes } from './vite/inertia-types-plugin'\n\nexport { stratalInertiaDevCss, stratalInertiaTypes }\n\nexport interface StratalInertiaPluginOptions {\n /** Client entry path(s) for CSS collection (default: ['/src/inertia/app.tsx']) */\n entries?: string[]\n}\n\nexport function stratalInertia(options?: StratalInertiaPluginOptions): Plugin[] {\n const entries = options?.entries ?? ['/src/inertia/app.tsx']\n\n // Hono and stratal must NOT be pre-bundled by Vite's optimizeDeps. When they are,\n // a duplicate copy ends up in `.vite/deps_<env>/` while the worker bundle imports\n // another copy from node_modules — Response objects from one instance flow into\n // a Context class from the other, and Hono's `set res` setter crashes inside\n // `this.#res.headers.entries()` because the prototype chain doesn't match.\n const optimizeDepsExclude = [\n '@cloudflare/vite-plugin',\n 'wrangler',\n 'blake3-wasm',\n '@stratal/inertia',\n 'stratal',\n 'hono',\n '@hono/zod-openapi',\n '@hono/swagger-ui',\n ]\n const optimizeDepsInclude = ['buffer', 'buffer/', 'base64-js', 'ieee754']\n const devOnlyExternals = ['ts-morph']\n\n return [\n stratalInertiaDevCss({ entries }),\n stratalInertiaTypes(),\n {\n name: 'stratal:optimize-deps-fix',\n configEnvironment(_name: string, env: EnvironmentOptions) {\n const existing = env.optimizeDeps?.exclude ?? []\n const existingInclude = env.optimizeDeps?.include ?? []\n env.optimizeDeps = {\n ...env.optimizeDeps,\n exclude: [...existing, ...optimizeDepsExclude],\n include: [...existingInclude, ...optimizeDepsInclude],\n }\n\n const existingExternal = (env.build?.rolldownOptions?.external as string[]) ?? []\n env.build = {\n ...env.build,\n rolldownOptions: {\n ...env.build?.rolldownOptions,\n external: [...existingExternal, ...devOnlyExternals],\n },\n }\n },\n },\n ]\n}\n"],"mappings":";;;;AAEA,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B,OAAO;AAM1C,SAAS,iBAAiB,QAAuB,SAA6B;CAC5E,MAAM,OAAiB,EAAE;CACzB,MAAM,0BAAU,IAAI,KAAa;CAEjC,SAAS,SAAS,KAAiB;AACjC,MAAI,QAAQ,IAAI,IAAI,IAAI,CAAE;AAC1B,UAAQ,IAAI,IAAI,IAAI;AAEpB,MAAI,aAAa,KAAK,IAAI,IAAI,CAC5B,MAAK,KAAK,IAAI,IAAI;AAGpB,OAAK,MAAM,YAAY,IAAI,gBACzB,UAAS,SAAS;;AAItB,MAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,MAAM,OAAO,YAAY,iBAC7B,MAAM,WAAW,IAAI,GAAG,MAAM,MAAM,EAAE,GAAG,MAC1C;AAED,MAAI,IACF,MAAK,MAAM,KAAK,IACd,UAAS,EAAE;EAIf,MAAM,SAAS,OAAO,YAAY,eAAe,IAAI,MAAM;AAC3D,MAAI,OACF,UAAS,OAAO;;AAIpB,QAAO;;AAGT,eAAe,aAAa,QAAuB,SAAoC;AACrF,MAAK,MAAM,SAAS,QAClB,KAAI;AACF,QAAM,OAAO,iBAAiB,MAAM;SAEhC;CAKR,MAAM,OAAO,iBAAiB,QAAQ,Q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vite/inertia-types-plugin.ts","../src/vite.ts"],"sourcesContent":["import type { ModuleNode, Plugin, ViteDevServer } from 'vite'\n\nconst CSS_LANGS_RE = /\\.(css|scss|sass|less|styl|stylus|pcss|postcss)(?:$|\\?)/\nconst VIRTUAL_MODULE_ID = 'virtual:inertia-ssr.css'\nconst RESOLVED_VIRTUAL_MODULE_ID = '\\0' + VIRTUAL_MODULE_ID\n\nexport interface InertiaDevCssOptions {\n entries: string[]\n}\n\nfunction collectStyleUrls(server: ViteDevServer, entries: string[]): string[] {\n const urls: string[] = []\n const visited = new Set<string>()\n\n function traverse(mod: ModuleNode) {\n if (visited.has(mod.url)) return\n visited.add(mod.url)\n\n if (CSS_LANGS_RE.test(mod.url)) {\n urls.push(mod.url)\n }\n\n for (const imported of mod.importedModules) {\n traverse(imported)\n }\n }\n\n for (const entry of entries) {\n const mod = server.moduleGraph.getModulesByFile(\n entry.startsWith('/') ? entry.slice(1) : entry,\n )\n\n if (mod) {\n for (const m of mod) {\n traverse(m)\n }\n }\n\n const urlMod = server.moduleGraph.urlToModuleMap.get(entry)\n if (urlMod) {\n traverse(urlMod)\n }\n }\n\n return urls\n}\n\nasync function collectStyle(server: ViteDevServer, entries: string[]): Promise<string> {\n for (const entry of entries) {\n try {\n await server.transformRequest(entry)\n }\n catch {\n //\n }\n }\n\n const urls = collectStyleUrls(server, entries)\n const styles: string[] = []\n\n for (const url of urls) {\n try {\n const separator = url.includes('?') ? '&' : '?'\n const result = await server.transformRequest(url + separator + 'direct')\n if (result?.code) {\n styles.push(result.code)\n }\n }\n catch {\n //\n }\n }\n\n return styles.join('\\n')\n}\n\nexport function stratalInertiaDevCss(options: InertiaDevCssOptions): Plugin {\n let server: ViteDevServer\n let cachedCss: string | null = null\n let inflight: Promise<string> | null = null\n let cacheEpoch = 0\n\n function invalidate(): void {\n cachedCss = null\n cacheEpoch++\n }\n\n async function getCss(): Promise<string> {\n if (cachedCss !== null) return cachedCss\n if (inflight) return inflight\n const epoch = cacheEpoch\n inflight = collectStyle(server, options.entries)\n .then((css) => {\n // Drop stale result if invalidated mid-flight, so the next caller re-collects.\n if (epoch === cacheEpoch) cachedCss = css\n return css\n })\n .finally(() => {\n inflight = null\n })\n return inflight\n }\n\n return {\n name: 'stratal:inertia-dev-css',\n apply: 'serve',\n\n resolveId(id) {\n if (id === VIRTUAL_MODULE_ID) {\n return RESOLVED_VIRTUAL_MODULE_ID\n }\n },\n\n async load(id) {\n if (id === RESOLVED_VIRTUAL_MODULE_ID) {\n return await getCss()\n }\n },\n\n handleHotUpdate() {\n // JS/TS edits can add or remove CSS imports, which changes the SSR CSS graph\n // without the changed file itself matching CSS_LANGS_RE. Invalidate on every\n // HMR tick — collectStyle() is fast and dev-only.\n invalidate()\n },\n\n configureServer(devServer) {\n server = devServer\n\n server.middlewares.use((req, res, next) => {\n const pathname = new URL(req.url ?? '', 'http://localhost').pathname\n if (pathname !== '/__inertia/ssr-css') { next(); return; }\n\n getCss().then((css) => {\n res.setHeader('Content-Type', 'text/css')\n res.setHeader('Cache-Control', 'no-store')\n res.end(css)\n }).catch(() => {\n res.statusCode = 500\n res.end('')\n })\n })\n },\n }\n}\n","import { URL } from 'node:url'\nimport { Worker } from 'node:worker_threads'\n\nexport interface TypeGenWorkerResult {\n ok: boolean\n outputPath?: string\n pageCount?: number\n error?: string\n}\n\nexport interface TypeGenWorkerHandle {\n on(event: 'message', cb: (m: TypeGenWorkerResult) => void): this\n on(event: 'error', cb: (e: Error) => void): this\n on(event: 'exit', cb: (code: number) => void): this\n terminate(): Promise<number> | number\n}\n\nexport type TypeGenWorkerSpawner = (cwd: string) => TypeGenWorkerHandle\n\nexport interface TypeGenDispatcher {\n schedule(): void\n dispose(): Promise<void>\n}\n\nexport interface TypeGenDispatcherOptions {\n cwd: string\n spawn?: TypeGenWorkerSpawner\n debounceMs?: number\n onResult?: (result: TypeGenWorkerResult) => void\n onError?: (error: Error) => void\n}\n\nconst defaultSpawn: TypeGenWorkerSpawner = (cwd) =>\n new Worker(new URL('./generator/type-generator.worker.mjs', import.meta.url), {\n workerData: { cwd },\n })\n\nexport function createTypeGenDispatcher(options: TypeGenDispatcherOptions): TypeGenDispatcher {\n const spawn = options.spawn ?? defaultSpawn\n const debounceMs = options.debounceMs ?? 250\n\n let pendingTimer: ReturnType<typeof setTimeout> | null = null\n let inflight: TypeGenWorkerHandle | null = null\n let queued = false\n let disposed = false\n\n function fire() {\n pendingTimer = null\n if (disposed) return\n if (inflight) {\n queued = true\n return\n }\n\n const worker = spawn(options.cwd)\n inflight = worker\n\n const finish = () => {\n if (inflight === worker) inflight = null\n if (disposed) return\n if (queued) {\n queued = false\n fire()\n }\n }\n\n worker.on('message', (msg) => {\n // `exit` will follow; finish() runs there so terminate() has settled before the next spawn.\n options.onResult?.(msg)\n })\n\n worker.on('error', (err) => {\n options.onError?.(err)\n })\n\n worker.on('exit', () => {\n finish()\n })\n }\n\n return {\n schedule() {\n if (disposed) return\n if (inflight) {\n queued = true\n return\n }\n if (pendingTimer) clearTimeout(pendingTimer)\n pendingTimer = setTimeout(fire, debounceMs)\n },\n\n async dispose() {\n disposed = true\n queued = false\n if (pendingTimer) {\n clearTimeout(pendingTimer)\n pendingTimer = null\n }\n const worker = inflight\n inflight = null\n if (worker) {\n try {\n await worker.terminate()\n } catch {\n // ignore\n }\n }\n },\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join, relative } from 'node:path'\nimport type { Plugin } from 'vite'\nimport { findPagesDir, runTypeGeneration } from '../generator/type-generator'\nimport { createTypeGenDispatcher, type TypeGenDispatcher } from './type-gen-dispatcher'\n\nconst INERTIA_CALL_PATTERN = /ctx\\.inertia\\(|\\.share\\(|ctx\\.flash\\(|ctx\\.defer\\(|ctx\\.optional\\(|ctx\\.merge\\(|ctx\\.once\\(|ctx\\.always\\(/\n\nexport function stratalInertiaTypes(): Plugin {\n let cwd: string\n let pagesDir: string\n let srcDir: string\n let dispatcher: TypeGenDispatcher | null = null\n\n return {\n name: 'stratal:inertia-types',\n\n configResolved(config) {\n cwd = config.root\n pagesDir = findPagesDir(cwd) + '/'\n srcDir = join(cwd, 'src') + '/'\n dispatcher = createTypeGenDispatcher({\n cwd,\n onError(err) {\n console.warn('[stratal:inertia-types] Type generation worker errored:', err.message)\n },\n onResult(result) {\n if (!result.ok && result.error) {\n console.warn('[stratal:inertia-types] Type generation failed:', result.error)\n }\n },\n })\n },\n\n async buildStart() {\n if (!existsSync(pagesDir)) return\n try {\n await runTypeGeneration(cwd)\n } catch (error) {\n console.warn('[stratal:inertia-types] Type generation failed during build:', error)\n }\n },\n\n handleHotUpdate({ file }) {\n if (!dispatcher) return\n if (!/\\.(tsx|ts)$/.test(file)) return\n\n const relToSrc = relative(srcDir, file)\n const isInSrc = !relToSrc.startsWith('..')\n\n if (!isInSrc) return\n\n // Page files always trigger regeneration\n const relToPages = relative(pagesDir, file)\n const isPageFile = !relToPages.startsWith('..')\n\n if (!isPageFile) {\n // For non-page files, only regenerate if they contain inertia-related calls\n try {\n const content = readFileSync(file, 'utf-8')\n if (!INERTIA_CALL_PATTERN.test(content)) return\n } catch {\n return\n }\n }\n\n dispatcher.schedule()\n },\n\n async closeBundle() {\n if (dispatcher) {\n await dispatcher.dispose()\n dispatcher = null\n }\n },\n }\n}\n","import type { EnvironmentOptions, Plugin } from 'vite'\nimport { stratalInertiaDevCss } from './vite/inertia-dev-css-plugin'\nimport { stratalInertiaTypes } from './vite/inertia-types-plugin'\n\nexport { stratalInertiaDevCss, stratalInertiaTypes }\n\nexport interface StratalInertiaPluginOptions {\n /** Client entry path(s) for CSS collection (default: ['/src/inertia/app.tsx']) */\n entries?: string[]\n}\n\nexport function stratalInertia(options?: StratalInertiaPluginOptions): Plugin[] {\n const entries = options?.entries ?? ['/src/inertia/app.tsx']\n\n // Hono and stratal must NOT be pre-bundled by Vite's optimizeDeps. When they are,\n // a duplicate copy ends up in `.vite/deps_<env>/` while the worker bundle imports\n // another copy from node_modules — Response objects from one instance flow into\n // a Context class from the other, and Hono's `set res` setter crashes inside\n // `this.#res.headers.entries()` because the prototype chain doesn't match.\n //\n // React 19 ships its main entry as CJS and relies on the optimizer's CJS→ESM\n // conversion, so it cannot be excluded outright. To prevent the related\n // identity-mismatch bug (two `?v=<hash>` copies after the optimizer re-runs\n // when a new dep is auto-discovered), the React-ecosystem packages are listed\n // in `resolve.noExternal` so Vite treats them as part of the user module graph\n // and `resolve.dedupe` so all imports collapse to a single physical copy.\n const optimizeDepsExclude = [\n '@cloudflare/vite-plugin',\n 'wrangler',\n 'blake3-wasm',\n '@stratal/inertia',\n 'stratal',\n 'hono',\n '@hono/zod-openapi',\n '@hono/swagger-ui',\n ]\n const dedupe = [\n 'react',\n 'react-dom',\n 'react-is',\n 'scheduler',\n '@inertiajs/core',\n '@inertiajs/react',\n ]\n const noExternal = [\n 'react',\n 'react-dom',\n 'react-is',\n 'scheduler',\n 'use-sync-external-store',\n '@inertiajs/core',\n '@inertiajs/react',\n ]\n const optimizeDepsInclude = ['buffer', 'buffer/', 'base64-js', 'ieee754']\n const devOnlyExternals = ['ts-morph']\n\n return [\n stratalInertiaDevCss({ entries }),\n stratalInertiaTypes(),\n {\n name: 'stratal:optimize-deps-fix',\n configEnvironment(_name: string, env: EnvironmentOptions) {\n const existing = env.optimizeDeps?.exclude ?? []\n const existingInclude = env.optimizeDeps?.include ?? []\n env.optimizeDeps = {\n ...env.optimizeDeps,\n exclude: [...existing, ...optimizeDepsExclude],\n include: [...existingInclude, ...optimizeDepsInclude],\n }\n\n const existingDedupe = env.resolve?.dedupe ?? []\n const existingNoExternal = env.resolve?.noExternal\n const mergedNoExternal: (string | RegExp)[] = [\n ...(Array.isArray(existingNoExternal)\n ? existingNoExternal\n : typeof existingNoExternal === 'string' || existingNoExternal instanceof RegExp\n ? [existingNoExternal]\n : []),\n ...noExternal,\n ]\n env.resolve = {\n ...env.resolve,\n dedupe: [...existingDedupe, ...dedupe],\n noExternal: existingNoExternal === true ? true : mergedNoExternal,\n }\n\n const existingExternal = (env.build?.rolldownOptions?.external as string[]) ?? []\n env.build = {\n ...env.build,\n rolldownOptions: {\n ...env.build?.rolldownOptions,\n external: [...existingExternal, ...devOnlyExternals],\n },\n }\n },\n },\n ]\n}\n"],"mappings":";;;;;;AAEA,MAAM,eAAe;AACrB,MAAM,oBAAoB;AAC1B,MAAM,6BAA6B,OAAO;AAM1C,SAAS,iBAAiB,QAAuB,SAA6B;CAC5E,MAAM,OAAiB,EAAE;CACzB,MAAM,0BAAU,IAAI,KAAa;CAEjC,SAAS,SAAS,KAAiB;EACjC,IAAI,QAAQ,IAAI,IAAI,IAAI,EAAE;EAC1B,QAAQ,IAAI,IAAI,IAAI;EAEpB,IAAI,aAAa,KAAK,IAAI,IAAI,EAC5B,KAAK,KAAK,IAAI,IAAI;EAGpB,KAAK,MAAM,YAAY,IAAI,iBACzB,SAAS,SAAS;;CAItB,KAAK,MAAM,SAAS,SAAS;EAC3B,MAAM,MAAM,OAAO,YAAY,iBAC7B,MAAM,WAAW,IAAI,GAAG,MAAM,MAAM,EAAE,GAAG,MAC1C;EAED,IAAI,KACF,KAAK,MAAM,KAAK,KACd,SAAS,EAAE;EAIf,MAAM,SAAS,OAAO,YAAY,eAAe,IAAI,MAAM;EAC3D,IAAI,QACF,SAAS,OAAO;;CAIpB,OAAO;;AAGT,eAAe,aAAa,QAAuB,SAAoC;CACrF,KAAK,MAAM,SAAS,SAClB,IAAI;EACF,MAAM,OAAO,iBAAiB,MAAM;SAEhC;CAKR,MAAM,OAAO,iBAAiB,QAAQ,QAAQ;CAC9C,MAAM,SAAmB,EAAE;CAE3B,KAAK,MAAM,OAAO,MAChB,IAAI;EACF,MAAM,YAAY,IAAI,SAAS,IAAI,GAAG,MAAM;EAC5C,MAAM,SAAS,MAAM,OAAO,iBAAiB,MAAM,YAAY,SAAS;EACxE,IAAI,QAAQ,MACV,OAAO,KAAK,OAAO,KAAK;SAGtB;CAKR,OAAO,OAAO,KAAK,KAAK;;AAG1B,SAAgB,qBAAqB,SAAuC;CAC1E,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,mBAAmB,GACjC,qBACA,OAAO,uBAAuB,YAAY,8BAA8B,SACtE,CAAC,mBAAmB,GACpB,EAAE,EACR,GAAG,WACJ;IACD,IAAI,UAAU;KACZ,GAAG,IAAI;KACP,QAAQ,CAAC,GAAG,gBAAgB,GAAG,OAAO;KACtC,YAAY,uBAAuB,OAAO,OAAO;KAClD;IAED,MAAM,mBAAoB,IAAI,OAAO,iBAAiB,YAAyB,EAAE;IACjF,IAAI,QAAQ;KACV,GAAG,IAAI;KACP,iBAAiB;MACf,GAAG,IAAI,OAAO;MACd,UAAU,CAAC,GAAG,kBAAkB,GAAG,iBAAiB;MACrD;KACF;;GAEJ;EACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stratal/inertia",
3
- "version": "0.0.20",
3
+ "version": "0.0.21",
4
4
  "description": "Inertia.js v3 server adapter for Stratal framework — server-driven React SPAs",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -71,12 +71,12 @@
71
71
  "@inertiajs/react": ">=3",
72
72
  "@inertiajs/vite": ">=3",
73
73
  "@intlify/core-base": ">=11",
74
- "@stratal/testing": ">=0.0.20",
74
+ "@stratal/testing": ">=0.0.21",
75
75
  "hono": ">=4",
76
76
  "react": ">=19",
77
77
  "react-dom": ">=19",
78
78
  "reflect-metadata": ">=0.2",
79
- "stratal": ">=0.0.20",
79
+ "stratal": ">=0.0.21",
80
80
  "vite": ">=8",
81
81
  "vitest": ">=4"
82
82
  },
@@ -110,26 +110,26 @@
110
110
  }
111
111
  },
112
112
  "devDependencies": {
113
- "@cloudflare/vite-plugin": "^1.35.0",
114
- "@cloudflare/workers-types": "4.20260502.1",
115
- "@inertiajs/core": "^3.0.3",
116
- "@inertiajs/react": "^3.0.3",
117
- "@inertiajs/vite": "^3.0.3",
118
- "@intlify/core-base": "^11.4.0",
113
+ "@cloudflare/vite-plugin": "^1.36.3",
114
+ "@cloudflare/workers-types": "4.20260510.1",
115
+ "@inertiajs/core": "^3.1.1",
116
+ "@inertiajs/react": "^3.1.1",
117
+ "@inertiajs/vite": "^3.1.1",
118
+ "@intlify/core-base": "^11.4.2",
119
119
  "@stratal/testing": "workspace:*",
120
- "@types/node": "^25.6.0",
120
+ "@types/node": "^25.6.2",
121
121
  "@types/react": "^19.2.14",
122
122
  "@types/react-dom": "^19.2.3",
123
123
  "@vitest/runner": "~4.1.5",
124
124
  "@vitest/snapshot": "~4.1.5",
125
- "hono": "^4.12.16",
126
- "react": "^19.2.5",
127
- "react-dom": "^19.2.5",
125
+ "hono": "^4.12.18",
126
+ "react": "^19.2.6",
127
+ "react-dom": "^19.2.6",
128
128
  "reflect-metadata": "^0.2.2",
129
129
  "stratal": "workspace:*",
130
- "tsdown": "^0.21.10",
130
+ "tsdown": "^0.22.0",
131
131
  "typescript": "^6.0.3",
132
- "vite": "^8.0.10",
132
+ "vite": "^8.0.11",
133
133
  "vitest": "~4.1.5"
134
134
  }
135
135
  }