@useavalon/avalon 0.3.2-canary.11 → 0.3.2-canary.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mod.d.ts CHANGED
@@ -22,7 +22,7 @@ export type { HydrationDirectiveDefinition, HydrationDirectiveFn, } from "./src/
22
22
  export { getDirective, getRegisteredDirectives, isCustomDirective, registerHydrationDirective, unregisterHydrationDirective, } from "./src/islands/hydration-directives.ts";
23
23
  export type { PreloadIntegrationsOptions } from "./src/islands/integration-loader.ts";
24
24
  export { DEFAULT_PRELOAD_FRAMEWORKS, detectAndLoadIntegration, detectFrameworksFromPageContent, loadIntegration, preloadIntegrations, } from "./src/islands/integration-loader.ts";
25
- export { default as Island, type IslandProps, renderIsland } from "./src/islands/island.tsx";
25
+ export { default as Island, type IslandProps, renderIsland, withListKey, } from "./src/islands/island.tsx";
26
26
  export type { CacheConfig as IslandCacheConfig, CacheStats as IslandCacheStats, } from "./src/islands/render-cache.ts";
27
27
  export { clearCache, clearIslandCache, configureCache, getCacheConfig, getCacheStats, invalidateCacheForFile, invalidateCacheForPath, logCacheStats, } from "./src/islands/render-cache.ts";
28
28
  export type { Framework, RenderParams, SvelteSSRCSSEntry } from "./src/islands/types.ts";
package/dist/mod.js CHANGED
@@ -1 +1 @@
1
- export{ACTION_ERROR_STATUS,ActionError,createActionClient,defineAction,isAction,isActionError}from"./src/actions/define.js";export{findActionsEntryInfo,generateActionTypes,getActionsWatchDir}from"./src/build/actions-types-generator.js";export{generateIslandManifest,getIslandBundlePath,loadIslandManifest}from"./src/build/island-manifest.js";export{generateIslandTypes,watchAndGenerateTypes}from"./src/build/island-types-generator.js";export{mdxIslandTransform}from"./src/build/mdx-island-transform.js";export{pageIslandTransform}from"./src/build/page-island-transform.js";export{registry as integrationRegistry}from"./src/core/integrations/registry.js";export{registerBuiltinDirectives}from"./src/islands/builtin-directives.js";export{analyzeComponentFile,renderComponentSSROnly}from"./src/islands/component-analysis.js";export{addSvelteSSRCSS,clearSvelteComponentCSS,generateComponentScopeId,getSvelteComponentCSS,getSvelteSSRCSS,getSvelteSSRCSSForHead,getSvelteSSRCSSStats}from"./src/islands/css-utils.js";export{createIslandRegistry,createIslandResolver,createIslandValidator,createIslandWatcher,DEFAULT_DISCOVERY_CONFIG,discoverAllIslands,discoverIslandDirectories,discoverIslandsInDirectory,formatCircularDependency,formatValidationError,formatValidationResult,formatValidationWarning,getDefaultIslandsPath,getQualifiedIslandName,hasDefaultIslandsDirectory,ISLAND_FILE_EXTENSIONS,IslandRegistry,IslandResolver,IslandValidator,IslandWatcher,isIslandsDirectory,isSupportedIslandExtension,parseQualifiedIslandName,validateAllIslands}from"./src/islands/discovery/index.js";export{detectFramework,detectFrameworkFromSrc,resolveIslandPath}from"./src/islands/framework-detection.js";export{getDirective,getRegisteredDirectives,isCustomDirective,registerHydrationDirective,unregisterHydrationDirective}from"./src/islands/hydration-directives.js";export{DEFAULT_PRELOAD_FRAMEWORKS,detectAndLoadIntegration,detectFrameworksFromPageContent,loadIntegration,preloadIntegrations}from"./src/islands/integration-loader.js";export{default as Island,renderIsland}from"./src/islands/island.js";export{clearCache,clearIslandCache,configureCache,getCacheConfig,getCacheStats,invalidateCacheForFile,invalidateCacheForPath,logCacheStats}from"./src/islands/render-cache.js";export{renderToHtml}from"./src/render/ssr.js";export{createNitroCoordinationPlugin,createNitroIntegration,createVirtualModulesPlugin,getAvalonConfig,getViteDevServer,isDevelopmentMode,RESOLVED_VIRTUAL_IDS,VIRTUAL_MODULE_IDS}from"./src/vite-plugin/nitro-integration.js";export{avalon,getLayoutsDir,getNitroConfig,getPagesDir,getResolvedConfig,isNitroEnabled}from"./src/vite-plugin/plugin.js";export async function build(e){throw Error("avalon build() is not available in the published package. Use `vite build` or the Avalon CLI instead.")}export{IslandErrorBoundary,withIslandErrorBoundary}from"./src/components/IslandErrorBoundary.js";export{LayoutErrorBoundary}from"./src/components/LayoutErrorBoundary.js";export*from"./src/layout-system.js";export{clearDiscoveryCache,clearMiddlewareCache,discoverScopedMiddleware,executeScopedMiddleware,getContextValue,getMatchingMiddleware,getMiddlewareCacheSize,hasContextValue,invalidateMiddleware,setContextValue}from"./src/middleware/index.js";export{usePersistentState}from"./src/persistence/use-persistent-state.js";export{CRON_ALIASES,CronConfigSchema,CronJobSchema,CronScheduleSchema,isValidCronExpression}from"./src/schemas/cron.js";
1
+ export{ACTION_ERROR_STATUS,ActionError,createActionClient,defineAction,isAction,isActionError}from"./src/actions/define.js";export{findActionsEntryInfo,generateActionTypes,getActionsWatchDir}from"./src/build/actions-types-generator.js";export{generateIslandManifest,getIslandBundlePath,loadIslandManifest}from"./src/build/island-manifest.js";export{generateIslandTypes,watchAndGenerateTypes}from"./src/build/island-types-generator.js";export{mdxIslandTransform}from"./src/build/mdx-island-transform.js";export{pageIslandTransform}from"./src/build/page-island-transform.js";export{registry as integrationRegistry}from"./src/core/integrations/registry.js";export{registerBuiltinDirectives}from"./src/islands/builtin-directives.js";export{analyzeComponentFile,renderComponentSSROnly}from"./src/islands/component-analysis.js";export{addSvelteSSRCSS,clearSvelteComponentCSS,generateComponentScopeId,getSvelteComponentCSS,getSvelteSSRCSS,getSvelteSSRCSSForHead,getSvelteSSRCSSStats}from"./src/islands/css-utils.js";export{createIslandRegistry,createIslandResolver,createIslandValidator,createIslandWatcher,DEFAULT_DISCOVERY_CONFIG,discoverAllIslands,discoverIslandDirectories,discoverIslandsInDirectory,formatCircularDependency,formatValidationError,formatValidationResult,formatValidationWarning,getDefaultIslandsPath,getQualifiedIslandName,hasDefaultIslandsDirectory,ISLAND_FILE_EXTENSIONS,IslandRegistry,IslandResolver,IslandValidator,IslandWatcher,isIslandsDirectory,isSupportedIslandExtension,parseQualifiedIslandName,validateAllIslands}from"./src/islands/discovery/index.js";export{detectFramework,detectFrameworkFromSrc,resolveIslandPath}from"./src/islands/framework-detection.js";export{getDirective,getRegisteredDirectives,isCustomDirective,registerHydrationDirective,unregisterHydrationDirective}from"./src/islands/hydration-directives.js";export{DEFAULT_PRELOAD_FRAMEWORKS,detectAndLoadIntegration,detectFrameworksFromPageContent,loadIntegration,preloadIntegrations}from"./src/islands/integration-loader.js";export{default as Island,renderIsland,withListKey}from"./src/islands/island.js";export{clearCache,clearIslandCache,configureCache,getCacheConfig,getCacheStats,invalidateCacheForFile,invalidateCacheForPath,logCacheStats}from"./src/islands/render-cache.js";export{renderToHtml}from"./src/render/ssr.js";export{createNitroCoordinationPlugin,createNitroIntegration,createVirtualModulesPlugin,getAvalonConfig,getViteDevServer,isDevelopmentMode,RESOLVED_VIRTUAL_IDS,VIRTUAL_MODULE_IDS}from"./src/vite-plugin/nitro-integration.js";export{avalon,getLayoutsDir,getNitroConfig,getPagesDir,getResolvedConfig,isNitroEnabled}from"./src/vite-plugin/plugin.js";export async function build(e){throw Error("avalon build() is not available in the published package. Use `vite build` or the Avalon CLI instead.")}export{IslandErrorBoundary,withIslandErrorBoundary}from"./src/components/IslandErrorBoundary.js";export{LayoutErrorBoundary}from"./src/components/LayoutErrorBoundary.js";export*from"./src/layout-system.js";export{clearDiscoveryCache,clearMiddlewareCache,discoverScopedMiddleware,executeScopedMiddleware,getContextValue,getMatchingMiddleware,getMiddlewareCacheSize,hasContextValue,invalidateMiddleware,setContextValue}from"./src/middleware/index.js";export{usePersistentState}from"./src/persistence/use-persistent-state.js";export{CRON_ALIASES,CronConfigSchema,CronJobSchema,CronScheduleSchema,isValidCronExpression}from"./src/schemas/cron.js";
@@ -1,2 +1,2 @@
1
1
  import{parseSync as e,visitorKeys as t}from"oxc-parser";const n=new Set([`FunctionDeclaration`,`FunctionExpression`,`ArrowFunctionExpression`]);function r(e){return!!e&&typeof e==`object`&&typeof e.type==`string`}function i(e){let t=e;for(;t.type===`ParenthesizedExpression`&&r(t.expression);)t=t.expression;return t}function*a(e){let n=t[e.type];if(n)for(let t of n){let n=e[t];if(Array.isArray(n))for(let e of n)r(e)&&(yield e);else r(n)&&(yield n)}}function*o(e){let t=[];function*n(e){yield{node:e,ancestors:t},t.push(e);for(let t of a(e))yield*n(t);t.pop()}yield*n(e)}function s(t,n){let r=e(n.endsWith(`.jsx`)?`page.jsx`:`page.tsx`,t.replace(/\bawait\b/g,`void `),{lang:n.endsWith(`.jsx`)?`jsx`:`tsx`,range:!0});if(r.errors.length>0){let e=r.errors[0];throw Error(`[avalon] failed to parse ${n} after island transform: ${e.message}`)}return r.program}function c(e,t){return e.type===`UnaryExpression`&&e.operator===`void`&&t.startsWith(`await`,e.start)}function l(e,t){let n=1;for(let r=0;r<t&&r<e.length;r++)e[r]===`
2
- `&&n++;return n}function u(e){return r(e)&&e.type===`Identifier`&&typeof e.name==`string`?e.name:null}function d(e,t){return u(e.id)||(t?.type===`VariableDeclarator`?u(t.id):t?.type===`AssignmentExpression`?u(t.left):null)}function f(e){for(let t=e.length-1;t>=0;t--)if(n.has(e[t].type))return{fn:e[t],parent:t>0?e[t-1]:null};return null}function p(e){return e?e.type===`MethodDefinition`||e.type===`Property`&&e.method===!0:!1}function m(e){let t=new Set;for(let{node:n}of o(e)){if(n.type!==`ExportDefaultDeclaration`||!r(n.declaration))continue;let e=n.declaration,i=u(e)??u(e.id);i&&t.add(i)}return t}function h(e,t,n,r){let i=l(n,r);throw Error(`[avalon] island at ${t}:${i} sits inside a ${e} that cannot be marked async. Move it into the page default export, a nested function, or a .map() callback.`)}function g(e,t,r){let i=new Set,a=new Map,s=new Map;for(let{node:l,ancestors:u}of o(e)){if(n.has(l.type)&&a.set(l,u.at(-1)??null),c(l,r)){let e=f(u);if(!e)continue;p(e.parent)&&h(`method`,t,r,l.start),e.fn.generator===!0&&h(`generator`,t,r,l.start),i.add(e.fn)}if(l.type===`JSXElement`){let e=_(l);if(!e)continue;let t=s.get(e)??[];t.push({ancestors:u.slice()}),s.set(e,t)}}let l=m(e),u=!0;for(;u;){u=!1;for(let e of i){let n=d(e,a.get(e)??null);if(!(!n||!/^[A-Z]/.test(n)||l.has(n)))for(let e of s.get(n)??[]){let n=f(e.ancestors);n&&!i.has(n.fn)&&(p(n.parent)&&h(`method`,t,r,n.fn.start),i.add(n.fn),u=!0)}}}return i}function _(e){if(!r(e.openingElement))return null;let t=e.openingElement.name;return r(t)&&t.type===`JSXIdentifier`&&typeof t.name==`string`?t.name:null}function v(e){let t=[];for(let n of e)n.async!==!0&&t.push({start:n.start,end:n.start,text:`async `});return t}function y(e){if(!r(e.callee))return null;let t=i(e.callee),n=t.type===`ChainExpression`&&r(t.expression)?t.expression:t;return n.type===`MemberExpression`?n:null}function b(e){let t=y(e);return!t||t.computed===!0||!r(t.property)?null:u(t.property)}function x(e){if(e.type!==`CallExpression`)return!1;let t=i(r(e.callee)?e.callee:e);return t.type!==`MemberExpression`||t.computed===!0?!1:u(t.object)===`Promise`&&u(t.property)===`all`}function S(e){if(e.optional===!0)return!0;if(!r(e.callee))return!1;let t=i(e.callee);return t.type===`ChainExpression`?!0:t.type===`MemberExpression`&&t.optional===!0}function C(e){let t=Array.isArray(e.arguments)?e.arguments:[];return t[0]&&r(t[0])?i(t[0]):null}function w(e,t,n){if(!e)return!1;if(t.has(e))return!0;let r=u(e);return!!(r&&n.has(r))}const T=new Set([`map`,`flatMap`]),E=new Set([`forEach`,`filter`,`reduce`,`reduceRight`,`some`,`every`,`find`,`findIndex`,`findLast`,`findLastIndex`]);function D(e,t,n,r,i){for(let{node:a}of o(e)){if(a.type!==`CallExpression`)continue;let e=b(a);!e||!E.has(e)||w(C(a),t,n)&&h(`${e}() callback`,r,i,a.start)}}function O(e,t,n,r,i){let a=!0;for(;a;){a=!1;for(let{node:s,ancestors:c}of o(e)){if(s.type!==`CallExpression`)continue;let e=b(s);if(!e||!T.has(e)||!w(C(s),t,n))continue;let o=c.at(-1)??null;if(o&&x(o))continue;let l=f(c);l&&(p(l.parent)&&h(`method`,r,i,s.start),l.fn.generator===!0&&h(`generator`,r,i,s.start),!t.has(l.fn)&&(t.add(l.fn),a=!0))}}}function k(e,t){let n=A(t,e),i=[];for(let{node:a,ancestors:s}of o(e)){if(a.type!==`CallExpression`)continue;let e=b(a);if(!e||!T.has(e)||!w(C(a),t,n))continue;let o=s.at(-1)??null;if(o&&x(o))continue;let c=S(a);if(e===`flatMap`){let e=y(a),t=e&&r(e.property)?e.property:null;i.push({start:a.start,end:a.start,text:`(await Promise.all(`}),t&&i.push({start:t.start,end:t.end,text:`map`}),i.push({start:a.end,end:a.end,text:c?` ?? [])).flat()`:`)).flat()`});continue}i.push({start:a.start,end:a.start,text:`await Promise.all(`}),i.push({start:a.end,end:a.end,text:c?` ?? [])`:`)`})}return i}function A(e,t){let n=m(t),r=new Set;for(let{node:i,ancestors:a}of o(t)){if(!e.has(i))continue;let t=d(i,a.at(-1)??null);t&&/^[A-Z]/.test(t)&&!n.has(t)&&r.add(t)}return r}function j(e,t){if(e.type===`JSXSpreadAttribute`&&r(e.argument))return`...${t.slice(e.argument.start,e.argument.end)}`;if(e.type!==`JSXAttribute`||!r(e.name))return null;let n=typeof e.name.name==`string`?e.name.name:null;if(!n||n===`key`)return null;if(!r(e.value))return`${n}: true`;if(e.value.type===`JSXExpressionContainer`&&r(e.value.expression)){let r=e.value.expression;return`${n}: ${t.slice(r.start,r.end)}`}return`${n}: ${t.slice(e.value.start,e.value.end)}`}function M(e,t,n){let i=r(e.openingElement)?e.openingElement:null,a=[],o=i&&Array.isArray(i.attributes)?i.attributes:[];for(let e of o){if(!r(e))continue;let t=j(e,n);t&&a.push(t)}if(i?.selfClosing!==!0&&r(e.closingElement)){let t=n.slice(i?i.end:e.start,e.closingElement.start);t.trim()&&a.push(`children: (${t})`)}return`await ${t}(${a.length>0?`{ ${a.join(`, `)} }`:`{}`})`}function N(e,t,n){let r=A(t,e);if(r.size===0)return[];let i=[];for(let{node:t,ancestors:a}of o(e)){if(t.type!==`JSXElement`)continue;let e=_(t);if(!e||!r.has(e))continue;let o=a.at(-1),s=o?.type===`JSXElement`||o?.type===`JSXFragment`,c=M(t,e,n);i.push({start:t.start,end:t.end,text:s?`{${c}}`:c})}return i}function P(e,t){let n=[...t].sort((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}export function ensureAwaitContextsAsync(e,t){let n=s(e,t),r=g(n,t,e),i=A(r,n);return O(n,r,i,t,e),D(n,r,i,t,e),P(e,[...v(r),...k(n,r),...N(n,r,e)])}
2
+ `&&n++;return n}function u(e){return r(e)&&e.type===`Identifier`&&typeof e.name==`string`?e.name:null}function d(e,t){return u(e.id)||(t?.type===`VariableDeclarator`?u(t.id):t?.type===`AssignmentExpression`?u(t.left):null)}function f(e){for(let t=e.length-1;t>=0;t--)if(n.has(e[t].type))return{fn:e[t],parent:t>0?e[t-1]:null};return null}function p(e){return e?e.type===`MethodDefinition`||e.type===`Property`&&e.method===!0:!1}function m(e){let t=new Set;for(let{node:n}of o(e)){if(n.type!==`ExportDefaultDeclaration`||!r(n.declaration))continue;let e=n.declaration,i=u(e)??u(e.id);i&&t.add(i)}return t}function h(e,t,n,r){let i=l(n,r);throw Error(`[avalon] island at ${t}:${i} sits inside a ${e} that cannot be marked async. Move it into the page default export, a nested function, or a .map() callback.`)}function g(e,t,n,r){p(e.parent)&&h(`method`,t,n,r),e.fn.generator===!0&&h(`generator`,t,n,r)}function _(e,t,n){let r=new Set;for(let{node:i,ancestors:a}of o(e))if(c(i,n)){let e=f(a);if(!e)continue;g(e,t,n,i.start),r.add(e.fn)}return r}function v(e){let t=new Map;for(let{node:n,ancestors:r}of o(e)){if(n.type!==`JSXElement`)continue;let e=C(n);if(!e)continue;let i=t.get(e)??[];i.push({ancestors:r.slice()}),t.set(e,i)}return t}function y(e){let t=new Map;for(let{node:r,ancestors:i}of o(e))n.has(r.type)&&t.set(r,i.at(-1)??null);return t}function b(e,t,n){let r=d(e,t);return!r||!/^[A-Z]/.test(r)||n.has(r)?null:r}function x(e,t,n,r){let i=f(e);return!i||t.has(i.fn)?!1:(g(i,n,r,i.fn.start),t.add(i.fn),!0)}function S(e,t,n,r){let i=y(e),a=v(e),o=m(e),s=!0;for(;s;){s=!1;for(let e of t){let c=b(e,i.get(e)??null,o);if(c)for(let e of a.get(c)??[])x(e.ancestors,t,n,r)&&(s=!0)}}}function C(e){if(!r(e.openingElement))return null;let t=e.openingElement.name;return r(t)&&t.type===`JSXIdentifier`&&typeof t.name==`string`?t.name:null}function w(e){let t=[];for(let n of e)n.async!==!0&&t.push({start:n.start,end:n.start,text:`async `});return t}function T(e){if(!r(e.callee))return null;let t=i(e.callee),n=t.type===`ChainExpression`&&r(t.expression)?t.expression:t;return n.type===`MemberExpression`?n:null}function E(e){let t=T(e);return!t||t.computed===!0||!r(t.property)?null:u(t.property)}function D(e){if(e.type!==`CallExpression`)return!1;let t=i(r(e.callee)?e.callee:e);return t.type!==`MemberExpression`||t.computed===!0?!1:u(t.object)===`Promise`&&u(t.property)===`all`}function O(e){if(e.optional===!0)return!0;if(!r(e.callee))return!1;let t=i(e.callee);return t.type===`ChainExpression`?!0:t.type===`MemberExpression`&&t.optional===!0}function k(e){let t=Array.isArray(e.arguments)?e.arguments:[];return t[0]&&r(t[0])?i(t[0]):null}function A(e,t,n){if(!e)return!1;if(t.has(e))return!0;let r=u(e);return!!(r&&n.has(r))}const j=new Set([`map`,`flatMap`]),M=new Set([`forEach`,`filter`,`reduce`,`reduceRight`,`some`,`every`,`find`,`findIndex`,`findLast`,`findLastIndex`]);function N(e,t,n,r,i){for(let{node:a}of o(e)){if(a.type!==`CallExpression`)continue;let e=E(a);!e||!M.has(e)||A(k(a),t,n)&&h(`${e}() callback`,r,i,a.start)}}function P(e,t,n,r){if(e.type!==`CallExpression`)return null;let i=E(e);if(!i||!j.has(i)||!A(k(e),n,r))return null;let a=t.at(-1)??null;return a&&D(a)?null:e}function F(e,t,n,r,i){let a=!0;for(;a;){a=!1;for(let{node:s,ancestors:c}of o(e)){if(!P(s,c,t,n))continue;let e=f(c);e&&(g(e,r,i,s.start),!t.has(e.fn)&&(t.add(e.fn),a=!0))}}}function I(e,t){let n=T(e),i=n&&r(n.property)?n.property:null;return[{start:e.start,end:e.start,text:`(await Promise.all(`},...i?[{start:i.start,end:i.end,text:`map`}]:[],{start:e.end,end:e.end,text:t?` ?? [])).flat()`:`)).flat()`}]}function L(e){let t=O(e);return E(e)===`flatMap`?I(e,t):[{start:e.start,end:e.start,text:`await Promise.all(`},{start:e.end,end:e.end,text:t?` ?? [])`:`)`}]}function R(e,t){let n=z(t,e),r=[];for(let{node:i,ancestors:a}of o(e))P(i,a,t,n)&&r.push(...L(i));return r}function z(e,t){let n=m(t),r=new Set;for(let{node:i,ancestors:a}of o(t)){if(!e.has(i))continue;let t=d(i,a.at(-1)??null);t&&/^[A-Z]/.test(t)&&!n.has(t)&&r.add(t)}return r}function B(e,t){if(e.type===`JSXSpreadAttribute`&&r(e.argument))return`...${t.slice(e.argument.start,e.argument.end)}`;if(e.type!==`JSXAttribute`||!r(e.name))return null;let n=typeof e.name.name==`string`?e.name.name:null;if(!n||n===`key`)return null;if(!r(e.value))return`${n}: true`;if(e.value.type===`JSXExpressionContainer`&&r(e.value.expression)){let r=e.value.expression;return`${n}: ${t.slice(r.start,r.end)}`}return`${n}: ${t.slice(e.value.start,e.value.end)}`}function V(e,t){if(e.type!==`JSXAttribute`||!r(e.name)||(typeof e.name.name==`string`?e.name.name:null)!==`key`||!r(e.value))return null;if(e.value.type===`JSXExpressionContainer`&&r(e.value.expression)){let n=e.value.expression;return t.slice(n.start,n.end)}return t.slice(e.value.start,e.value.end)}function H(e,t){let n=[],i=null,a=e&&Array.isArray(e.attributes)?e.attributes:[];for(let e of a){if(!r(e))continue;let a=V(e,t);if(a!=null){i=a;continue}let o=B(e,t);o&&n.push(o)}return{props:n,keyExpr:i}}function U(e,t,n){let i=r(e.openingElement)?e.openingElement:null,{props:a,keyExpr:o}=H(i,n);if(i?.selfClosing!==!0&&r(e.closingElement)){let t=n.slice(i?i.end:e.start,e.closingElement.start);t.trim()&&a.push(`children: (${t})`)}let s=`await ${t}(${a.length>0?`{ ${a.join(`, `)} }`:`{}`})`;return o==null?s:`__pageKeyed(${o}, ${s})`}function W(e,t,n){let r=z(t,e);if(r.size===0)return[];let i=[];for(let{node:t,ancestors:a}of o(e)){if(t.type!==`JSXElement`)continue;let e=C(t);if(!e||!r.has(e))continue;let o=a.at(-1),s=o?.type===`JSXElement`||o?.type===`JSXFragment`,c=U(t,e,n);i.push({start:t.start,end:t.end,text:s?`{${c}}`:c})}return i}function G(e,t){let n=[...t].sort((e,t)=>t.start-e.start||t.end-e.end),r=e;for(let e of n)r=r.slice(0,e.start)+e.text+r.slice(e.end);return r}export function ensureAwaitContextsAsync(e,t){let n=s(e,t),r=_(n,t,e),i=z(r,n),a=0;for(;r.size!==a;)a=r.size,i=z(r,n),F(n,r,i,t,e),S(n,r,t,e);return N(n,r,i,t,e),G(e,[...w(r),...R(n,r),...W(n,r,e)])}
@@ -1,2 +1,2 @@
1
- import{dirname as e}from"node:path";import{addToManifest as t,generateComponentId as n}from"../server-islands/manifest.js";import{ensureAwaitContextsAsync as r}from"./page-island-await.js";function i(e){let t=[],n=/^[ \t]*import\s+([A-Z]\w*)\s+from\s+(['"][^'"]+['"])/gm,r=null;for(r=n.exec(e);r!==null;r=n.exec(e))t.push({localName:r[1],importPath:r[2].slice(1,-1),fullMatch:r[0].trimStart()});return t}const a=[{prefix:`@shared/`,map:e=>`/app/shared/${e}`},{prefix:`@modules/`,map:e=>`/app/modules/${e}`},{prefix:`@/`,map:e=>`/app/${e}`},{prefix:`$components/`,map:e=>`/src/components/${e}`},{prefix:`$islands/`,map:e=>`/src/islands/${e}`},{prefix:`~/`,map:e=>`/src/${e}`}];function o(e){return e.startsWith(`/`)?e:`/${e}`}function s(e,t){for(let{find:n,replacement:r}of t){let t=o(r);if(typeof n==`string`){if(e===n||e.startsWith(`${n}/`))return`${t}${e.slice(n.length)}`}else if(n.test(e))return e.replace(n,t)}return null}function c(e){for(let{prefix:t,map:n}of a)if(e.startsWith(t))return n(e.slice(t.length));return null}function l(t,n){if(!t.startsWith(`.`))return null;let r=n.replaceAll(`\\`,`/`),i=r.indexOf(`/app/`);if(i===-1&&(i=r.indexOf(`/src/`)),i===-1)return null;let a=e(r.slice(i)).split(`/`);for(let e of t.split(`/`))e===`..`?a.pop():e!==`.`&&a.push(e);return a.join(`/`)}function u(e,t,n=[]){return e.startsWith(`/`)?e:s(e,n)??c(e)??l(e,t)??`/src/${e.split(`/`).pop()}`}function d(e){if(e.endsWith(`.vue`))return`vue`;if(e.endsWith(`.svelte`))return`svelte`;if(e.includes(`.solid.`))return`solid`;if(e.includes(`.lit.`))return`lit`;if(e.includes(`.qwik.`))return`qwik`;if(e.includes(`.react.`))return`react`;if(e.endsWith(`.tsx`)||e.endsWith(`.jsx`))return`preact`}function f(e,t,n){let r=e.replaceAll(`\\`,`/`),i=t.replace(/^\//,``);if(r.includes(`/${i}/`)&&/\.(tsx|jsx)$/.test(r))return!0;if(n){let e=n.dir.replace(/^\//,``);if(RegExp(`/${e}/[^/]+/${n.pagesDirName}/`).test(r)&&/\.(tsx|jsx)$/.test(r))return!0}return!1}function p(e,t,n){let r=e.replaceAll(`\\`,`/`),i=t.replace(/^\//,``);if(r.includes(`/${i}/`)&&/\.(tsx|jsx)$/.test(r))return!0;if(n){let e=n.dir.replace(/^\//,``);if(RegExp(`/${e}/[^/]+/${n.layoutsDirName}/`).test(r)&&/\.(tsx|jsx)$/.test(r))return!0}return!1}const m=new Set([`qwik`]);function h(e){let t=d(e);return t!==void 0&&m.has(t)}const g=String.raw`[\s][^>]*island[\s]*[={]`,_=String.raw`[\s][^>]*server[\s]*[={]`,v=String.raw`[\s/>]`;function y(e,t){return t.some(t=>RegExp(`<${t}${g}`).test(e))}function b(e,t){return t.some(t=>RegExp(`<${t}${_}`).test(e))}function x(e,t){return t.some(t=>h(t.importPath)?RegExp(`<${t.localName}${v}`).test(e):!1)}function S(e,r,i,a=[]){let o=new Map;for(let s of r){let r=u(s.importPath,i,a),c=d(r),l=RegExp(`<${s.localName}${g}`),f=RegExp(`<${s.localName}${_}`),p=l.test(e),h=f.test(e);if(p||h){o.set(s.localName,{srcPath:r,framework:c,importPath:s.importPath,autoIsland:!1,hasServerProp:h}),h&&t(n(r),r);continue}c&&m.has(c)&&RegExp(`<${s.localName}${v}`).test(e)&&o.set(s.localName,{srcPath:r,framework:c,importPath:s.importPath,autoIsland:!0,hasServerProp:!1})}return o}function C(e,t){for(;t<e.length&&/\s/.test(e[t]);)t++;return t}function w(e,t){let n=e[t];for(t++;t<e.length&&e[t]!==n;)e[t]===`\\`&&t++,t++;return t<e.length?t+1:t}function T(e,t){for(t++;t<e.length&&e[t]!=="`";){if(e[t]===`\\`){t+=2;continue}if(e[t]===`$`&&e[t+1]===`{`){t=E(t+1,e);continue}t++}return t<e.length?t+1:t}function E(e,t){let n=e+1,r=1;for(;n<t.length&&r>0;){let e=t[n];e===`{`?(r++,n++):e===`}`?(r--,r>0&&n++):e===`'`||e===`"`||e==="`"?n=w(t,n):n++}return n<t.length?n+1:n}function D(e,t){let n=t+1,r=E(t,e);return{value:e.slice(n,r-1),endIdx:r}}function O(e,t){let n=e[t],r=t+1;for(;r<e.length&&e[r]!==n;)e[r]===`\\`&&r++,r++;return{value:`"${e.slice(t+1,r)}"`,endIdx:r+1}}function k(e,t){let n=t,r=t;for(;r<e.length&&/[a-zA-Z0-9_$]/.test(e[r]);)r++;let i=e.slice(n,r);if(!i)return null;if(r=C(e,r),e[r]!==`=`)return{name:i,value:null,endIdx:r};if(r=C(e,r+1),e[r]===`{`){let t=D(e,r);return{name:i,value:t.value,endIdx:t.endIdx}}if(e[r]===`"`||e[r]===`'`){let t=O(e,r);return{name:i,value:t.value,endIdx:t.endIdx}}return null}function A(e,t,n){if(e[t]===`/`&&e[t+1]===`>`)return{endIdx:t+2,selfClosing:!0};if(e[t]===`>`){let r=`</${n}>`,i=e.indexOf(r,t+1);return i===-1?null:{endIdx:i+r.length,selfClosing:!1}}return null}function j(e,t,n){let r=C(e,t+1+n.length),i=null,a=null,o=[];for(;r<e.length;){r=C(e,r);let t=A(e,r,n);if(t)return{endIdx:t.endIdx,islandProp:i,serverProp:a,otherProps:o};let s=k(e,r);if(!s)return null;if(r=s.endIdx,s.name===`island`)i=s.value??`{}`;else if(s.name===`server`)a=s.value??`{}`;else{let e=s.value===null?`${s.name}: true`:`${s.name}: ${s.value}`;o.push(e)}}return null}function M(e,t,n,r,i){let a=n?`, framework: "${n}"`:``,o=e.otherProps.length>0?`, props: { ${e.otherProps.join(`, `)} }`:``,s=`, component: ${i}`;if(r)return`await __pageRenderIsland({ src: "`+t+`"`+a+s+o+`, ssr: true, ssrOnly: true })`;if(e.serverProp){let n=`, server: (${e.serverProp})`,r=e.islandProp?`, island: (${e.islandProp})`:``;return`await __pageRenderIsland({ src: "`+t+`"`+a+s+n+r+o+` })`}let c=e.islandProp??``;return`await __pageRenderIsland({ src: "`+t+`"`+a+s+`, ...(`+c+`)`+o+`, ssr: (`+c+`).ssr !== undefined ? (`+c+`).ssr : true })`}function N(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return!1;let r=e[n];return r===`>`?e[n-1]!==`=`:r===`}`}function P(e,t){let n=e.slice(t,t+2);if(e[t]==="`")return T(e,t);if(e[t]===`{`&&n===`{/`&&e[t+2]===`*`)return F(e,t);if(n===`//`){let n=e.indexOf(`
2
- `,t);return n===-1?e.length:n+1}if(n===`/*`){let n=e.indexOf(`*/`,t+2);return n===-1?e.length:n+2}return-1}function F(e,t){let n=e.indexOf(`*/`,t+3);if(n===-1)return-1;let r=n+2;for(;r<e.length&&/\s/.test(e[r]);)r++;return r<e.length&&e[r]===`}`?r+1:-1}function I(e,t,n){if(!e.startsWith(n,t))return!1;let r=t+n.length;return r>=e.length||!/[a-zA-Z0-9_$]/.test(e[r])}function L(e,t,n,r,i){let a=`<${t}`,o=``,s=0;for(;s<e.length;){let c=P(e,s);if(c!==-1){o+=e.slice(s,c),s=c;continue}let{text:l,next:u}=R(e,s,{tag:a,componentName:t,srcPath:n,framework:r,autoIsland:i});o+=l,s=u}return o}function R(e,t,n){if(!I(e,t,n.tag))return{text:e[t],next:t+1};let r=j(e,t,n.componentName);if(!r||!r.islandProp&&!r.serverProp&&!n.autoIsland){let n=r?r.endIdx:t+1;return{text:e.slice(t,n),next:n}}let i=M(r,n.srcPath,n.framework,n.autoIsland&&!r.islandProp,n.componentName);return{text:N(e,t)?`{${i}}`:i,next:r.endIdx}}function z(e){if(/\bexport\s+default\s+function\b(?!\s*\*)/.test(e))return e.replace(/\bexport\s+default\s+function\b(?!\s*\*)/,`export default async function`);let t=/\bexport\s+default\s+(\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/;if(t.test(e))return e.replace(t,`export default async $1 =>`);let n=/\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/.exec(e);if(n){let t=n[1].replaceAll(`$`,String.raw`\$&`),r=new RegExp(String.raw`(^|[^.\w])function\s+${t}\s*\(`,`m`),i=new RegExp(String.raw`\basync\s+function\s+${t}\b`);if(r.test(e)&&!i.test(e))return e.replace(r,e=>e.replace(`function`,`async function`));let a=new RegExp(String.raw`(\b(?:const|let|var)\s+${t}\s*=\s*)(?!async\b)(\([^)]*\)\s*=>|function\b|[A-Za-z_$][\w$]*\s*=>)`);if(a.test(e))return e.replace(a,`$1async $2`)}return e}export function pageIslandTransform(e={}){let{pagesDir:t=`src/pages`,layoutsDir:n=`src/layouts`,modules:a=null}=e,o=[];return{name:`avalon:page-island-transform`,enforce:`pre`,configResolved(e){o=e.resolve?.alias??[]},transform(e,s){let c=p(s,n,a);if(!f(s,t,a)&&!c)return null;let l=i(e);if(l.length===0)return null;let u=l.map(e=>e.localName);if(!y(e,u)&&!b(e,u)&&!x(e,l))return null;let d=S(e,l,s,o);if(d.size===0)return null;let m=`import { renderIsland as __pageRenderIsland } from '@useavalon/avalon';\n${e}`;for(let[e,t]of d)m=L(m,e,t.srcPath,t.framework,t.autoIsland);return m.includes(`__pageRenderIsland(`)&&(m=z(m),m=r(m,s)),{code:m,map:null}}}}
1
+ import{dirname as e}from"node:path";import{addToManifest as t,generateComponentId as n}from"../server-islands/manifest.js";import{ensureAwaitContextsAsync as r}from"./page-island-await.js";function i(e){let t=[],n=/^[ \t]*import\s+([A-Z]\w*)\s+from\s+(['"][^'"]+['"])/gm,r=null;for(r=n.exec(e);r!==null;r=n.exec(e))t.push({localName:r[1],importPath:r[2].slice(1,-1),fullMatch:r[0].trimStart()});return t}const a=[{prefix:`@shared/`,map:e=>`/app/shared/${e}`},{prefix:`@modules/`,map:e=>`/app/modules/${e}`},{prefix:`@/`,map:e=>`/app/${e}`},{prefix:`$components/`,map:e=>`/src/components/${e}`},{prefix:`$islands/`,map:e=>`/src/islands/${e}`},{prefix:`~/`,map:e=>`/src/${e}`}];function o(e){return e.startsWith(`/`)?e:`/${e}`}function s(e,t){for(let{find:n,replacement:r}of t){let t=o(r);if(typeof n==`string`){if(e===n||e.startsWith(`${n}/`))return`${t}${e.slice(n.length)}`}else if(n.test(e))return e.replace(n,t)}return null}function c(e){for(let{prefix:t,map:n}of a)if(e.startsWith(t))return n(e.slice(t.length));return null}function l(t,n){if(!t.startsWith(`.`))return null;let r=n.replaceAll(`\\`,`/`),i=r.indexOf(`/app/`);if(i===-1&&(i=r.indexOf(`/src/`)),i===-1)return null;let a=e(r.slice(i)).split(`/`);for(let e of t.split(`/`))e===`..`?a.pop():e!==`.`&&a.push(e);return a.join(`/`)}function u(e,t,n=[]){return e.startsWith(`/`)?e:s(e,n)??c(e)??l(e,t)??`/src/${e.split(`/`).pop()}`}function d(e){if(e.endsWith(`.vue`))return`vue`;if(e.endsWith(`.svelte`))return`svelte`;if(e.includes(`.solid.`))return`solid`;if(e.includes(`.lit.`))return`lit`;if(e.includes(`.qwik.`))return`qwik`;if(e.includes(`.react.`))return`react`;if(e.endsWith(`.tsx`)||e.endsWith(`.jsx`))return`preact`}function f(e,t,n){let r=e.replaceAll(`\\`,`/`),i=t.replace(/^\//,``);if(r.includes(`/${i}/`)&&/\.(tsx|jsx)$/.test(r))return!0;if(n){let e=n.dir.replace(/^\//,``);if(RegExp(`/${e}/[^/]+/${n.pagesDirName}/`).test(r)&&/\.(tsx|jsx)$/.test(r))return!0}return!1}function p(e,t,n){let r=e.replaceAll(`\\`,`/`),i=t.replace(/^\//,``);if(r.includes(`/${i}/`)&&/\.(tsx|jsx)$/.test(r))return!0;if(n){let e=n.dir.replace(/^\//,``);if(RegExp(`/${e}/[^/]+/${n.layoutsDirName}/`).test(r)&&/\.(tsx|jsx)$/.test(r))return!0}return!1}const m=new Set([`qwik`]);function h(e){let t=d(e);return t!==void 0&&m.has(t)}const g=String.raw`[\s][^>]*island[\s]*[={]`,_=String.raw`[\s][^>]*server[\s]*[={]`,v=String.raw`[\s/>]`;function y(e,t){return t.some(t=>RegExp(`<${t}${g}`).test(e))}function b(e,t){return t.some(t=>RegExp(`<${t}${_}`).test(e))}function x(e,t){return t.some(t=>h(t.importPath)?RegExp(`<${t.localName}${v}`).test(e):!1)}function S(e,r,i,a=[]){let o=new Map;for(let s of r){let r=u(s.importPath,i,a),c=d(r),l=RegExp(`<${s.localName}${g}`),f=RegExp(`<${s.localName}${_}`),p=l.test(e),h=f.test(e);if(p||h){o.set(s.localName,{srcPath:r,framework:c,importPath:s.importPath,autoIsland:!1,hasServerProp:h}),h&&t(n(r),r);continue}c&&m.has(c)&&RegExp(`<${s.localName}${v}`).test(e)&&o.set(s.localName,{srcPath:r,framework:c,importPath:s.importPath,autoIsland:!0,hasServerProp:!1})}return o}function C(e,t){for(;t<e.length&&/\s/.test(e[t]);)t++;return t}function w(e,t){let n=e[t];for(t++;t<e.length&&e[t]!==n;)e[t]===`\\`&&t++,t++;return t<e.length?t+1:t}function T(e,t){for(t++;t<e.length&&e[t]!=="`";){if(e[t]===`\\`){t+=2;continue}if(e[t]===`$`&&e[t+1]===`{`){t=E(t+1,e);continue}t++}return t<e.length?t+1:t}function E(e,t){let n=e+1,r=1;for(;n<t.length&&r>0;){let e=t[n];e===`{`?(r++,n++):e===`}`?(r--,r>0&&n++):e===`'`||e===`"`||e==="`"?n=w(t,n):n++}return n<t.length?n+1:n}function D(e,t){let n=t+1,r=E(t,e);return{value:e.slice(n,r-1),endIdx:r}}function O(e,t){let n=e[t],r=t+1;for(;r<e.length&&e[r]!==n;)e[r]===`\\`&&r++,r++;return{value:`"${e.slice(t+1,r)}"`,endIdx:r+1}}function k(e,t){let n=t,r=t;for(;r<e.length&&/[a-zA-Z0-9_$]/.test(e[r]);)r++;let i=e.slice(n,r);if(!i)return null;if(r=C(e,r),e[r]!==`=`)return{name:i,value:null,endIdx:r};if(r=C(e,r+1),e[r]===`{`){let t=D(e,r);return{name:i,value:t.value,endIdx:t.endIdx}}if(e[r]===`"`||e[r]===`'`){let t=O(e,r);return{name:i,value:t.value,endIdx:t.endIdx}}return null}function A(e,t,n){if(e[t]===`/`&&e[t+1]===`>`)return{endIdx:t+2,selfClosing:!0};if(e[t]===`>`){let r=`</${n}>`,i=e.indexOf(r,t+1);return i===-1?null:{endIdx:i+r.length,selfClosing:!1}}return null}function j(e,t,n){let r=C(e,t+1+n.length),i=null,a=null,o=null,s=[];for(;r<e.length;){r=C(e,r);let t=A(e,r,n);if(t)return{endIdx:t.endIdx,islandProp:i,serverProp:a,keyProp:o,otherProps:s};let c=k(e,r);if(!c)return null;if(r=c.endIdx,c.name===`island`)i=c.value??`{}`;else if(c.name===`server`)a=c.value??`{}`;else if(c.name===`key`)o=c.value;else{let e=c.value===null?`${c.name}: true`:`${c.name}: ${c.value}`;s.push(e)}}return null}function M(e,t,n,r,i){let a=n?`, framework: "${n}"`:``,o=e.otherProps.length>0?`, props: { ${e.otherProps.join(`, `)} }`:``,s=e.keyProp==null?``:`, key: (${e.keyProp})`,c=`, component: ${i}`;if(r)return`await __pageRenderIsland({ src: "`+t+`"`+a+c+o+s+`, ssr: true, ssrOnly: true })`;if(e.serverProp){let n=`, server: (${e.serverProp})`,r=e.islandProp?`, island: (${e.islandProp})`:``;return`await __pageRenderIsland({ src: "`+t+`"`+a+c+n+r+o+s+` })`}let l=e.islandProp??``;return`await __pageRenderIsland({ src: "`+t+`"`+a+c+`, ...(`+l+`)`+o+`, ssr: (`+l+`).ssr !== undefined ? (`+l+`).ssr : true`+s+` })`}function N(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return!1;let r=e[n];return r===`>`?e[n-1]!==`=`:r===`}`}function P(e,t){let n=e.slice(t,t+2);if(e[t]==="`")return T(e,t);if(e[t]===`{`&&n===`{/`&&e[t+2]===`*`)return F(e,t);if(n===`//`){let n=e.indexOf(`
2
+ `,t);return n===-1?e.length:n+1}if(n===`/*`){let n=e.indexOf(`*/`,t+2);return n===-1?e.length:n+2}return-1}function F(e,t){let n=e.indexOf(`*/`,t+3);if(n===-1)return-1;let r=n+2;for(;r<e.length&&/\s/.test(e[r]);)r++;return r<e.length&&e[r]===`}`?r+1:-1}function I(e,t,n){if(!e.startsWith(n,t))return!1;let r=t+n.length;return r>=e.length||!/[a-zA-Z0-9_$]/.test(e[r])}function L(e,t,n,r,i){let a=`<${t}`,o=``,s=0;for(;s<e.length;){let c=P(e,s);if(c!==-1){o+=e.slice(s,c),s=c;continue}let{text:l,next:u}=R(e,s,{tag:a,componentName:t,srcPath:n,framework:r,autoIsland:i});o+=l,s=u}return o}function R(e,t,n){if(!I(e,t,n.tag))return{text:e[t],next:t+1};let r=j(e,t,n.componentName);if(!r||!r.islandProp&&!r.serverProp&&!n.autoIsland){let n=r?r.endIdx:t+1;return{text:e.slice(t,n),next:n}}let i=M(r,n.srcPath,n.framework,n.autoIsland&&!r.islandProp,n.componentName);return{text:N(e,t)?`{${i}}`:i,next:r.endIdx}}function z(e){if(/\bexport\s+default\s+function\b(?!\s*\*)/.test(e))return e.replace(/\bexport\s+default\s+function\b(?!\s*\*)/,`export default async function`);let t=/\bexport\s+default\s+(\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>/;if(t.test(e))return e.replace(t,`export default async $1 =>`);let n=/\bexport\s+default\s+([A-Za-z_$][\w$]*)\s*;/.exec(e);if(n){let t=n[1].replaceAll(`$`,String.raw`\$&`),r=new RegExp(String.raw`(^|[^.\w])function\s+${t}\s*\(`,`m`),i=new RegExp(String.raw`\basync\s+function\s+${t}\b`);if(r.test(e)&&!i.test(e))return e.replace(r,e=>e.replace(`function`,`async function`));let a=new RegExp(String.raw`(\b(?:const|let|var)\s+${t}\s*=\s*)(?!async\b)(\([^)]*\)\s*=>|function\b|[A-Za-z_$][\w$]*\s*=>)`);if(a.test(e))return e.replace(a,`$1async $2`)}return e}export function pageIslandTransform(e={}){let{pagesDir:t=`src/pages`,layoutsDir:n=`src/layouts`,modules:a=null}=e,o=[];return{name:`avalon:page-island-transform`,enforce:`pre`,configResolved(e){o=e.resolve?.alias??[]},transform(e,s){let c=p(s,n,a);if(!f(s,t,a)&&!c)return null;let l=i(e);if(l.length===0)return null;let u=l.map(e=>e.localName);if(!y(e,u)&&!b(e,u)&&!x(e,l))return null;let d=S(e,l,s,o);if(d.size===0)return null;let m=`import { renderIsland as __pageRenderIsland } from '@useavalon/avalon';\n${e}`;for(let[e,t]of d)m=L(m,e,t.srcPath,t.framework,t.autoIsland);return m.includes(`__pageRenderIsland(`)&&(m=z(m),m=r(m,s)),m.includes(`__pageKeyed(`)&&(m=m.replace(`import { renderIsland as __pageRenderIsland } from '@useavalon/avalon';`,`import { renderIsland as __pageRenderIsland, withListKey as __pageKeyed } from '@useavalon/avalon';`)),{code:m,map:null}}}}
@@ -1 +1 @@
1
- export function normalizeCssHref(e){let t=(e.split(`?`)[0]?.split(`#`)[0]??e).replaceAll(`\\`,`/`);return t.startsWith(`/`)?t:`/${t}`}function t(e){return e.dataset.avalonCss}export function applyDevCssHot(n,i,a){let o=normalizeCssHref(i);for(let e of n.querySelectorAll(`link[data-avalon-css]`))t(e)===o&&(e.href=`${o}?direct&v=${Date.now()}`);a&&applyCssText(n,i,a)}export function applyCssText(n,r,i){if(!i||i.includes(`__vite__updateStyle`)||i.includes(`import.meta.hot`))return;let a=normalizeCssHref(r),o;for(let e of n.querySelectorAll(`style[data-avalon-css]`))if(t(e)===a){o=e;break}o||(o=n.createElement(`style`),o.dataset.avalonCss=a,n.head.appendChild(o)),o.textContent=i}
1
+ export function normalizeCssHref(e){let t=(e.split(`?`)[0]?.split(`#`)[0]??e).replaceAll(`\\`,`/`);return t.startsWith(`/`)?t:`/${t}`}function t(e){return e.dataset.avalonCss}function n(e,n){for(let r of e.querySelectorAll(`style[data-avalon-css]`))if(t(r)===n)return r}export function applyDevCssHot(n,r,a){let o=normalizeCssHref(r);for(let e of n.querySelectorAll(`link[data-avalon-css]`))t(e)===o&&(e.href=`${o}?direct&v=${Date.now()}`);a&&applyCssText(n,r,a)}export function applyCssText(t,r,i){if(!i||i.includes(`__vite__updateStyle`)||i.includes(`import.meta.hot`))return;let a=normalizeCssHref(r),o=n(t,a);o||(o=t.createElement(`style`),o.dataset.avalonCss=a,t.head.appendChild(o)),o.textContent=i}
@@ -1 +1 @@
1
- import{AdapterRegistry as e}from"./framework-adapter.js";export class HMRCoordinator{registry=new e;stateSnapshots=new Map;updateQueue=new Set;isProcessing=!1;initialize(){import.meta.hot&&(import.meta.hot.accept(),import.meta.hot.on(`vite:beforeUpdate`,e=>this.handleUpdate(e)),import.meta.hot.on(`vite:beforeFullReload`,()=>{this.handleBeforeFullReload()}),import.meta.hot.on(`vite:error`,e=>{console.error(`[HMR] error:`,e),this.handleError(e)}),document.addEventListener(`hmr-update-required`,e=>{let{src:t,reason:n}=e.detail;n===`css-module-update`&&(this.updateQueue.add(this.normalizePath(t)),this.isProcessing||this.processUpdateQueue().catch(e=>{console.error(`[HMR] Failed to process CSS module update:`,e)}))}))}registerAdapter(e,t){this.registry.register(e,t)}getRegistry(){return this.registry}async handleUpdate(e){if(e.type!==`update`||!e.updates)return;let t=[];for(let n of e.updates)n.type===`js-update`&&t.push(n);this.queueJSUpdates(t),!this.isProcessing&&this.updateQueue.size>0&&await this.processUpdateQueue()}queueJSUpdates(e){for(let t of e){let e=this.normalizePath(t.path||t.acceptedPath);this.isIslandModule(e)&&this.updateQueue.add(e)}}async processUpdateQueue(){if(this.updateQueue.size!==0){this.isProcessing=!0;try{let e=Array.from(this.updateQueue);this.updateQueue.clear();for(let t of e){let e=this.findAffectedIslands(t);for(let t of e)try{await this.updateIsland(t)}catch(e){console.error(`[HMR] Failed to update island:`,e)}}}finally{this.isProcessing=!1}}}findAffectedIslands(e){let t=[],n=this.normalizePath(e),r=document.querySelectorAll(`[data-src]`);for(let e of r){let r=e.dataset.src;if(!r)continue;let i=this.normalizePath(r);(i===n||i.endsWith(n)||n.endsWith(i)||i.split(`/`).pop()===n.split(`/`).pop())&&t.push(e)}return t}async updateIsland(e){let t=e.dataset.framework,n=e.dataset.src,r=e.dataset.props;if(!t||!n){console.warn(`[HMR] Island missing framework or src attribute`,e);return}let i=this.registry.get(t.toLowerCase());if(!i){console.warn(`[HMR] No adapter registered for framework: ${t}`);return}try{let a=r?JSON.parse(r):{},o=i.preserveState(e);o&&this.stateSnapshots.set(this.getIslandId(e),o),delete e.dataset.hydrated,delete e.dataset.hydrationStatus,e.querySelector(`.hydration-error-indicator, .hmr-error-indicator`)?.remove();let s=Date.now(),c=await import(n.includes(`?`)?`${n}&t=${s}`:`${n}?t=${s}`),l=this.resolveComponent(c,n);await i.update(e,l,a),o&&(i.restoreState(e,o),this.stateSnapshots.delete(this.getIslandId(e))),e.dataset.hydrated=`true`,e.dispatchEvent(new CustomEvent(`hmr-update`,{detail:{framework:t,src:n,timestamp:Date.now(),success:!0},bubbles:!0}))}catch(r){throw console.error(`[HMR] Failed to update ${t} island ${n}:`,r),i.handleError(e,r),e.dispatchEvent(new CustomEvent(`hmr-error`,{detail:{framework:t,src:n,error:r.message,timestamp:Date.now()},bubbles:!0})),r}}resolveComponent(e,t){if(e.default)return e.default;for(let t of Object.keys(e)){if(t===`default`)continue;let n=e[t];if(typeof n==`function`&&n.prototype)return n}throw Error(`Component ${t} has no default export`)}handleBeforeFullReload(){let e=document.querySelectorAll(`[data-hydrated="true"]`),t={};for(let n of e){let e=n.dataset.framework,r=n.dataset.src;if(!e||!r)continue;let i=this.registry.get(e.toLowerCase());if(!i)continue;let a=i.preserveState(n);a&&(t[r]=a)}try{sessionStorage.setItem(`__avalon_hmr_states__`,JSON.stringify(t))}catch(e){console.warn(`[HMR] Failed to save states:`,e)}}handleError(e){let t=Error(e.err.message);t.stack=e.err.stack,console.error(`[HMR] Error:`,t),globalThis.window!==void 0&&import(`./hmr-error-overlay.js`).then(({showHMRErrorOverlay:n})=>{n({framework:`unknown`,src:`unknown`,error:t,filePath:e.err.id||e.err.loc?.file||`unknown`,line:e.err.loc?.line,column:e.err.loc?.column})}).catch(()=>{console.error(`[HMR] Failed to show error overlay`)})}normalizePath(e){let t=e.replaceAll(`\\`,`/`);t.startsWith(`/`)&&(t=t.slice(1));let n=t.indexOf(`?`);n!==-1&&(t=t.slice(0,n));let r=t.indexOf(`#`);return r!==-1&&(t=t.slice(0,r)),t.startsWith(`src/`)&&(t=t.slice(4)),t}isIslandModule(e){return e.includes(`/islands/`)||e.includes(`\\islands\\`)}getIslandId(e){let t=e.dataset.src??``;return`${e.dataset.framework??``}:${t}:${Array.from(document.querySelectorAll(`[data-src="${t}"]`)).indexOf(e)}`}}let n=null;export function getHMRCoordinator(){return n??=new HMRCoordinator,n}export function initializeHMR(){import.meta.hot&&getHMRCoordinator().initialize()}
1
+ import{AdapterRegistry as e}from"./framework-adapter.js";export class HMRCoordinator{registry=new e;stateSnapshots=new Map;updateQueue=new Set;isProcessing=!1;initialize(){import.meta.hot&&(import.meta.hot.accept(),import.meta.hot.on(`vite:beforeUpdate`,e=>this.handleUpdate(e)),import.meta.hot.on(`vite:beforeFullReload`,()=>{this.handleBeforeFullReload()}),import.meta.hot.on(`vite:error`,e=>{console.error(`[HMR] error:`,e),this.handleError(e)}),document.addEventListener(`hmr-update-required`,e=>{let{src:t,reason:n}=e.detail;n===`css-module-update`&&(this.updateQueue.add(this.normalizePath(t)),this.isProcessing||this.processUpdateQueue().catch(e=>{console.error(`[HMR] Failed to process CSS module update:`,e)}))}))}registerAdapter(e,t){this.registry.register(e,t)}getRegistry(){return this.registry}async handleUpdate(e){if(e.type!==`update`||!e.updates)return;let t=[];for(let n of e.updates)n.type===`js-update`&&t.push(n);this.queueJSUpdates(t),!this.isProcessing&&this.updateQueue.size>0&&await this.processUpdateQueue()}queueJSUpdates(e){for(let t of e){let e=this.normalizePath(t.path??t.acceptedPath);this.isIslandModule(e)&&this.updateQueue.add(e)}}async processUpdateQueue(){if(this.updateQueue.size!==0){this.isProcessing=!0;try{let e=Array.from(this.updateQueue);this.updateQueue.clear();for(let t of e){let e=this.findAffectedIslands(t);for(let t of e)try{await this.updateIsland(t)}catch(e){console.error(`[HMR] Failed to update island:`,e)}}}finally{this.isProcessing=!1}}}findAffectedIslands(e){let t=[],n=this.normalizePath(e),r=document.querySelectorAll(`[data-src]`);for(let e of r){let r=e.dataset.src;if(!r)continue;let i=this.normalizePath(r);(i===n||i.endsWith(n)||n.endsWith(i)||i.split(`/`).pop()===n.split(`/`).pop())&&t.push(e)}return t}async updateIsland(e){let t=e.dataset.framework,n=e.dataset.src,r=e.dataset.props;if(!t||!n){console.warn(`[HMR] Island missing framework or src attribute`,e);return}let i=this.registry.get(t.toLowerCase());if(!i){console.warn(`[HMR] No adapter registered for framework: ${t}`);return}try{let a=r?JSON.parse(r):{},o=i.preserveState(e);o&&this.stateSnapshots.set(this.getIslandId(e),o),delete e.dataset.hydrated,delete e.dataset.hydrationStatus,e.querySelector(`.hydration-error-indicator, .hmr-error-indicator`)?.remove();let s=Date.now(),c=await import(n.includes(`?`)?`${n}&t=${s}`:`${n}?t=${s}`),l=this.resolveComponent(c,n);await i.update(e,l,a),o&&(i.restoreState(e,o),this.stateSnapshots.delete(this.getIslandId(e))),e.dataset.hydrated=`true`,e.dispatchEvent(new CustomEvent(`hmr-update`,{detail:{framework:t,src:n,timestamp:Date.now(),success:!0},bubbles:!0}))}catch(r){throw console.error(`[HMR] Failed to update ${t} island ${n}:`,r),i.handleError(e,r),e.dispatchEvent(new CustomEvent(`hmr-error`,{detail:{framework:t,src:n,error:r.message,timestamp:Date.now()},bubbles:!0})),r}}resolveComponent(e,t){if(e.default)return e.default;for(let t of Object.keys(e)){if(t===`default`)continue;let n=e[t];if(typeof n==`function`&&n.prototype)return n}throw Error(`Component ${t} has no default export`)}handleBeforeFullReload(){let e=document.querySelectorAll(`[data-hydrated="true"]`),t={};for(let n of e){let e=n.dataset.framework,r=n.dataset.src;if(!e||!r)continue;let i=this.registry.get(e.toLowerCase());if(!i)continue;let a=i.preserveState(n);a&&(t[r]=a)}try{sessionStorage.setItem(`__avalon_hmr_states__`,JSON.stringify(t))}catch(e){console.warn(`[HMR] Failed to save states:`,e)}}handleError(e){let t=Error(e.err.message);t.stack=e.err.stack,console.error(`[HMR] Error:`,t),globalThis.window!==void 0&&import(`./hmr-error-overlay.js`).then(({showHMRErrorOverlay:n})=>{n({framework:`unknown`,src:`unknown`,error:t,filePath:e.err.id??e.err.loc?.file??`unknown`,line:e.err.loc?.line,column:e.err.loc?.column})}).catch(()=>{console.error(`[HMR] Failed to show error overlay`)})}normalizePath(e){let t=e.replaceAll(`\\`,`/`);t.startsWith(`/`)&&(t=t.slice(1));let n=t.indexOf(`?`);n!==-1&&(t=t.slice(0,n));let r=t.indexOf(`#`);return r!==-1&&(t=t.slice(0,r)),t.startsWith(`src/`)&&(t=t.slice(4)),t}isIslandModule(e){return e.includes(`/islands/`)||e.includes(`\\islands\\`)}getIslandId(e){let t=e.dataset.src??``,n=e.dataset.framework??``,r=0;for(let n of document.querySelectorAll(`[data-src]`)){if(n===e)break;n.dataset.src===t&&(r+=1)}return`${n}:${t}:${r}`}}let n=null;export function getHMRCoordinator(){return n??=new HMRCoordinator,n}export function initializeHMR(){import.meta.hot&&getHMRCoordinator().initialize()}
@@ -42,7 +42,14 @@ export interface IslandProps {
42
42
  server?: ServerIslandProp;
43
43
  /** Island directive for combined server + client islands */
44
44
  island?: IslandDirective;
45
+ /** React/Preact list key — set on the host VNode, never serialized into props */
46
+ key?: string | number;
45
47
  }
48
+ /**
49
+ * Attach a list key to a VNode returned from a rewritten helper call.
50
+ * Pages import this as `__pageKeyed` from the island transform.
51
+ */
52
+ export declare function withListKey(key: unknown, vnode: JSX.Element): JSX.Element;
46
53
  /**
47
54
  * Universal Island component – renders `<avalon-island>` custom elements for better DOM structure.
48
55
  *
@@ -66,4 +73,4 @@ export default function Island({ src, condition, conditionArg, props, children,
66
73
  * Error isolation: If SSR fails, returns an error placeholder instead of throwing,
67
74
  * allowing the page to continue rendering other islands.
68
75
  */
69
- export declare function renderIsland({ src, condition, conditionArg, props, children, ssr, framework, ssrOnly, renderOptions, component: preloadedComponent, server, island, }: IslandProps): Promise<JSX.Element>;
76
+ export declare function renderIsland({ src, condition, conditionArg, props, children, ssr, framework, ssrOnly, renderOptions, component: preloadedComponent, server, island, key, }: IslandProps): Promise<JSX.Element>;
@@ -1 +1 @@
1
- import{getIslandBundlePath as e}from"../build/island-manifest.js";import{shellH as t,shellFragment as n}from"../render/shell-engine.js";import{addToManifest as r,generateComponentId as i}from"../server-islands/manifest.js";import{renderServerIsland as a}from"../server-islands/renderer.js";import{devError as o,devLog as s,devWarn as c,isDev as l,logRenderTiming as u}from"../utils/dev-logger.js";import{analyzeComponentFile as d,renderComponentSSROnly as f}from"./component-analysis.js";import{detectFramework as p}from"./framework-detection.js";import{isCustomDirective as m,serializeDirectiveScript as h}from"./hydration-directives.js";import{detectFrameworkFromPath as g,loadIntegration as _}from"./integration-loader.js";import{addModulepreload as v}from"./modulepreload-collector.js";import{generatePerIslandScript as y}from"./per-island-script.js";import{addUniversalCSS as b}from"./universal-css-collector.js";import{addUniversalHead as x}from"./universal-head-collector.js";function S(e){return`island-${e.replaceAll(/[^a-zA-Z0-9]/g,`-`)}`}function C(){return globalThis.__avalonHydrationMode===void 0?globalThis.__viteDevServer?!1:typeof __AVALON_PER_ISLAND__<`u`?__AVALON_PER_ISLAND__:!l():globalThis.__avalonHydrationMode===`per-island`}function w(r,i){if(!C()||i.shouldSkipHydration)return r;let a=e(i.src);i.condition===`on:client`&&v(a);let o=m(i.condition),s=o?h(i.condition):void 0,c=y({islandId:i.islandId,componentSrc:a,framework:i.framework,condition:i.condition,conditionArg:i.conditionArg,propsJson:JSON.stringify(i.props),isCustomDirective:o,directiveScript:s??void 0});return t(n(),null,r,t(`div`,{dangerouslySetInnerHTML:{__html:c},"data-island-script":``}))}function T(e){let t={};e.renderId&&(t[`data-solid-render-id`]=e.renderId);let n=e.metadata;return n?.tagName&&(t[`data-tag-name`]=n.tagName),t}function E(t,n,r,i,a){let o={"data-condition":n,"data-src":e(t),"data-props":JSON.stringify(r),"data-render-strategy":`hydrate`,...T(i)};if(m(n)){o[`data-custom-directive`]=n;let e=h(n);e&&(o[`data-directive-script`]=e)}return a&&(o[`data-condition-arg`]=a),o}function D(e){return e.startsWith(`<script`)?`script`:e.startsWith(`<style`)?`style`:e.startsWith(`<meta`)?`meta`:e.startsWith(`<link`)?`link`:e.includes(`window._$HY`)||e.includes(`_$HY=`)?`script`:`other`}function O(e){let t=e.match(/<style[^>]*>([\s\S]*?)<\/style>/i);return t?t[1].trim():null}function k(e,t,n,r){if(e.css&&b(e.css,t,n,e.scopeId),e.head){let i=e.head.trim(),a=D(i);if(a===`style`){let a=O(i);a&&(s(`${r} Extracting CSS from head <style> tag`),b(a,t,n,e.scopeId));return}x(e.head,t,n,a)}}function A(e){let{islandId:n,detectedFramework:r,shouldSkipHydration:i,src:a,condition:o,conditionArg:c,props:l,hydrationData:u,children:d}=e,f={id:n,"data-framework":r},p=i?{"data-render-strategy":`ssr-only`}:E(a,o,l,u,c);r===`lit`&&s(`🔍 [Island Component] ${a} - Lit hydration data:`,{hydrationDataKeys:Object.keys(u),metadata:u.metadata});let m={...f,...p},h;return h=typeof d==`string`?t(`avalon-island`,{...m,dangerouslySetInnerHTML:{__html:d}}):t(`avalon-island`,m,d),w(h,{islandId:n,src:a,condition:o,conditionArg:c,props:l,framework:r,shouldSkipHydration:i})}function j(n){let{islandId:r,detectedFramework:i,shouldSkipHydration:a,src:o,condition:s,props:c,hydrationData:l,conditionArg:u}=n;if(a)return t(`avalon-island`,{id:r,"data-render-strategy":`ssr-only`,"data-framework":i});let d={id:r,"data-condition":s,"data-src":e(o),"data-props":JSON.stringify(c),"data-render-strategy":`hydrate`,"data-framework":i,...T(l)};if(m(s)){d[`data-custom-directive`]=s;let e=h(s);e&&(d[`data-directive-script`]=e)}return u&&(d[`data-condition-arg`]=u),w(t(`avalon-island`,d),{islandId:r,src:o,condition:s,conditionArg:u,props:c,framework:i,shouldSkipHydration:a})}export default function M({src:e,condition:t=`on:client`,conditionArg:n,props:r={},children:i,ssr:a=t!==`on:client`,framework:o,ssrOnly:l=!1,renderOptions:u={},hydrationData:d={}}){let f=S(e),p=l||!!u.forceSSROnly,m=o||g(e),h=i!=null&&i!==``;return s(`🔍 [Island Component] ${e}`,{ssr:a,ssrOnly:l,hasChildren:h,framework:o,condition:t}),a&&h?A({islandId:f,detectedFramework:m,shouldSkipHydration:p,src:e,condition:t,conditionArg:n,props:r,hydrationData:d,children:i}):(a&&!h&&p&&c(`${e}: SSR-only component has no rendered content. This may indicate a rendering error.`),j({islandId:f,detectedFramework:m,shouldSkipHydration:p,src:e,condition:t,props:r,hydrationData:d,conditionArg:n}))}function N(n,r){let i=r instanceof Error?r.message:String(r);return o(`🚨 Island SSR failed for ${n}:`,r),r instanceof Error&&r.stack&&o(`Stack trace:`,r.stack),t(`avalon-island`,{id:S(n),"data-src":e(n),"data-ssr-error":i,"data-render-strategy":`client-only`})}async function P({src:e,condition:t,conditionArg:n,props:r,children:i,ssr:a,framework:s,ssrOnly:c,renderOptions:u,component:d}){let f=`🏝️ [${e}]`;if(!a||i)return M({src:e,condition:t,conditionArg:n,props:r,children:i,ssr:a,framework:s,ssrOnly:c,renderOptions:u});let p;try{p=await _(s)}catch(i){return o(`${f} Failed to load ${s} integration:`,i),M({src:e,condition:t,conditionArg:n,props:r,ssr:!1,framework:s,ssrOnly:c,renderOptions:u})}try{let i=await p.render({component:d??null,props:r,src:e,condition:t,ssrOnly:c,viteServer:globalThis.__viteDevServer,isDev:l()});return k(i,e,s,f),M({src:e,condition:t,conditionArg:n,props:r,children:i.html,ssr:!0,framework:s,ssrOnly:c,renderOptions:u,hydrationData:c?void 0:i.hydrationData})}catch(i){return o(`${f} Fast path SSR failed:`,i),M({src:e,condition:t,conditionArg:n,props:r,ssr:!1,framework:s,ssrOnly:c,renderOptions:u})}}async function F(e,t,n,r){if(t||n.detectScripts===!1)return t;try{let t=await d(e,n);if(t.decision.warnings?.length)for(let e of t.decision.warnings)c(`${r} Analysis warning: ${e}`);return!t.decision.shouldHydrate}catch(e){return c(`${r} Component analysis failed:`,e),t}}async function I(e){return e.endsWith(`.vue`)?`vue`:e.endsWith(`.svelte`)?`svelte`:e.endsWith(`.tsx`)||e.endsWith(`.jsx`)||e.endsWith(`.ts`)||e.endsWith(`.js`)?p(e):`unknown`}async function L(e,t,n,r,i,a,o){let s=await I(e),c=s,u=await(await R(s,a)).render({component:o??null,props:n,src:e,condition:t,ssrOnly:r,viteServer:globalThis.__viteDevServer,isDev:l()});return k(u,e,s,a),M({src:e,condition:t,props:n,children:u.html,ssr:!0,framework:c,ssrOnly:r,renderOptions:i,hydrationData:r?void 0:u.hydrationData})}async function R(e,t){try{s(`${t} Loading integration for framework: ${e}`);let n=await _(e);return s(`${t} ✅ Integration loaded successfully`),n}catch(n){throw o(`${t} Failed to load ${e} integration:`,n),Error(`Failed to load integration for framework '${e}'. Make sure @useavalon/${e} is installed.\nInstall it with: deno add @useavalon/${e}`,{cause:n})}}export async function renderIsland({src:o,condition:s=`on:client`,conditionArg:c,props:d={},children:f,ssr:p=s!==`on:client`,framework:m,ssrOnly:h=!1,renderOptions:_={},component:v,server:y,island:b}){let x=l()?performance.now():0,S=`🏝️ [${o}]`;try{if(y){let s=i(o);r(s,o);let c=m||g(o),l=a(s,d,y,b,b?e(o):void 0,o,c);return t(n(),null,t(`div`,{dangerouslySetInnerHTML:{__html:l},"data-server-island-wrapper":``}))}return h&&!p&&(p=!0),m?await P({src:o,condition:s,conditionArg:c,props:d,children:f,ssr:p,framework:m,ssrOnly:h,renderOptions:_,component:v}):await z({src:o,condition:s,conditionArg:c,props:d,children:f,ssr:p,ssrOnly:h,renderOptions:_,logPrefix:S,component:v})}catch(e){return N(o,e)}finally{l()&&u(o,performance.now()-x)}}async function z(e){let{src:t,condition:n,conditionArg:r,props:i,children:a,ssr:c,ssrOnly:l,renderOptions:u,logPrefix:d,component:f}=e;if(s(`🔍 [renderIsland] ${t} - Starting render (slow path)`,{ssr:c,ssrOnly:l,hasChildren:!!a,condition:n}),await F(t,l,u,d))return B(t,n,i,a,c,u,d);if(!c||a)return M({src:t,condition:n,conditionArg:r,props:i,children:a,ssr:c,renderOptions:u});try{return await L(t,n,i,l,u,d,f)}catch(e){let a=await I(t);return o(`${d} Framework rendering failed:`,e),M({src:t,condition:n,conditionArg:r,props:i,ssr:!1,framework:a,renderOptions:u})}}function B(e,t,n,r,i,a,s){return i&&!r?f({src:e,condition:t,props:n,renderOptions:a}).catch(r=>(o(`${s} SSR failed for SSR-only component:`,r),M({src:e,condition:t,props:n,ssr:!1,ssrOnly:!0,renderOptions:a}))):M({src:e,condition:t,props:n,children:r,ssr:i,ssrOnly:!0,renderOptions:a})}
1
+ import{getIslandBundlePath as e}from"../build/island-manifest.js";import{shellH as t,shellFragment as n}from"../render/shell-engine.js";import{addToManifest as r,generateComponentId as i}from"../server-islands/manifest.js";import{renderServerIsland as a}from"../server-islands/renderer.js";import{devError as o,devLog as s,devWarn as c,isDev as l,logRenderTiming as u}from"../utils/dev-logger.js";import{analyzeComponentFile as d,renderComponentSSROnly as f}from"./component-analysis.js";import{detectFramework as p}from"./framework-detection.js";import{isCustomDirective as m,serializeDirectiveScript as h}from"./hydration-directives.js";import{detectFrameworkFromPath as g,loadIntegration as _}from"./integration-loader.js";import{addModulepreload as v}from"./modulepreload-collector.js";import{generatePerIslandScript as y}from"./per-island-script.js";import{addUniversalCSS as b}from"./universal-css-collector.js";import{addUniversalHead as x}from"./universal-head-collector.js";function S(e,r){return r==null?e:t(n(),{key:r},e)}export function withListKey(e,t){return S(t,e)}function w(e){return`island-${e.replaceAll(/[^a-zA-Z0-9]/g,`-`)}`}function T(){return globalThis.__avalonHydrationMode===void 0?globalThis.__viteDevServer?!1:typeof __AVALON_PER_ISLAND__<`u`?__AVALON_PER_ISLAND__:!l():globalThis.__avalonHydrationMode===`per-island`}function E(r,i){if(!T()||i.shouldSkipHydration)return r;let a=e(i.src);i.condition===`on:client`&&v(a);let o=m(i.condition),s=o?h(i.condition):void 0,c=y({islandId:i.islandId,componentSrc:a,framework:i.framework,condition:i.condition,conditionArg:i.conditionArg,propsJson:JSON.stringify(i.props),isCustomDirective:o,directiveScript:s??void 0});return t(n(),null,r,t(`div`,{dangerouslySetInnerHTML:{__html:c},"data-island-script":``}))}function D(e){let t={};e.renderId&&(t[`data-solid-render-id`]=e.renderId);let n=e.metadata;return n?.tagName&&(t[`data-tag-name`]=n.tagName),t}function O(t,n,r,i,a){let o={"data-condition":n,"data-src":e(t),"data-props":JSON.stringify(r),"data-render-strategy":`hydrate`,...D(i)};if(m(n)){o[`data-custom-directive`]=n;let e=h(n);e&&(o[`data-directive-script`]=e)}return a&&(o[`data-condition-arg`]=a),o}function k(e){return e.startsWith(`<script`)?`script`:e.startsWith(`<style`)?`style`:e.startsWith(`<meta`)?`meta`:e.startsWith(`<link`)?`link`:e.includes(`window._$HY`)||e.includes(`_$HY=`)?`script`:`other`}function A(e){let t=e.match(/<style[^>]*>([\s\S]*?)<\/style>/i);return t?t[1].trim():null}function j(e,t,n,r){if(e.css&&b(e.css,t,n,e.scopeId),e.head){let i=e.head.trim(),a=k(i);if(a===`style`){let a=A(i);a&&(s(`${r} Extracting CSS from head <style> tag`),b(a,t,n,e.scopeId));return}x(e.head,t,n,a)}}function M(e){let{islandId:n,detectedFramework:r,shouldSkipHydration:i,src:a,condition:o,conditionArg:c,props:l,hydrationData:u,children:d}=e,f={id:n,"data-framework":r},p=i?{"data-render-strategy":`ssr-only`}:O(a,o,l,u,c);r===`lit`&&s(`🔍 [Island Component] ${a} - Lit hydration data:`,{hydrationDataKeys:Object.keys(u),metadata:u.metadata});let m={...f,...p},h;return h=typeof d==`string`?t(`avalon-island`,{...m,dangerouslySetInnerHTML:{__html:d}}):t(`avalon-island`,m,d),E(h,{islandId:n,src:a,condition:o,conditionArg:c,props:l,framework:r,shouldSkipHydration:i})}function N(n){let{islandId:r,detectedFramework:i,shouldSkipHydration:a,src:o,condition:s,props:c,hydrationData:l,conditionArg:u}=n;if(a)return t(`avalon-island`,{id:r,"data-render-strategy":`ssr-only`,"data-framework":i});let d={id:r,"data-condition":s,"data-src":e(o),"data-props":JSON.stringify(c),"data-render-strategy":`hydrate`,"data-framework":i,...D(l)};if(m(s)){d[`data-custom-directive`]=s;let e=h(s);e&&(d[`data-directive-script`]=e)}return u&&(d[`data-condition-arg`]=u),E(t(`avalon-island`,d),{islandId:r,src:o,condition:s,conditionArg:u,props:c,framework:i,shouldSkipHydration:a})}export default function P({src:e,condition:t=`on:client`,conditionArg:n,props:r={},children:i,ssr:a=t!==`on:client`,framework:o,ssrOnly:l=!1,renderOptions:u={},hydrationData:d={}}){let f=w(e),p=l||!!u.forceSSROnly,m=o||g(e),h=i!=null&&i!==``;return s(`🔍 [Island Component] ${e}`,{ssr:a,ssrOnly:l,hasChildren:h,framework:o,condition:t}),a&&h?M({islandId:f,detectedFramework:m,shouldSkipHydration:p,src:e,condition:t,conditionArg:n,props:r,hydrationData:d,children:i}):(a&&!h&&p&&c(`${e}: SSR-only component has no rendered content. This may indicate a rendering error.`),N({islandId:f,detectedFramework:m,shouldSkipHydration:p,src:e,condition:t,props:r,hydrationData:d,conditionArg:n}))}function F(n,r){let i=r instanceof Error?r.message:String(r);return o(`🚨 Island SSR failed for ${n}:`,r),r instanceof Error&&r.stack&&o(`Stack trace:`,r.stack),t(`avalon-island`,{id:w(n),"data-src":e(n),"data-ssr-error":i,"data-render-strategy":`client-only`})}async function I({src:e,condition:t,conditionArg:n,props:r,children:i,ssr:a,framework:s,ssrOnly:c,renderOptions:u,component:d}){let f=`🏝️ [${e}]`;if(!a||i)return P({src:e,condition:t,conditionArg:n,props:r,children:i,ssr:a,framework:s,ssrOnly:c,renderOptions:u});let p;try{p=await _(s)}catch(i){return o(`${f} Failed to load ${s} integration:`,i),P({src:e,condition:t,conditionArg:n,props:r,ssr:!1,framework:s,ssrOnly:c,renderOptions:u})}try{let i=await p.render({component:d??null,props:r,src:e,condition:t,ssrOnly:c,viteServer:globalThis.__viteDevServer,isDev:l()});return j(i,e,s,f),P({src:e,condition:t,conditionArg:n,props:r,children:i.html,ssr:!0,framework:s,ssrOnly:c,renderOptions:u,hydrationData:c?void 0:i.hydrationData})}catch(i){return o(`${f} Fast path SSR failed:`,i),P({src:e,condition:t,conditionArg:n,props:r,ssr:!1,framework:s,ssrOnly:c,renderOptions:u})}}async function L(e,t,n,r){if(t||n.detectScripts===!1)return t;try{let t=await d(e,n);if(t.decision.warnings?.length)for(let e of t.decision.warnings)c(`${r} Analysis warning: ${e}`);return!t.decision.shouldHydrate}catch(e){return c(`${r} Component analysis failed:`,e),t}}async function R(e){return e.endsWith(`.vue`)?`vue`:e.endsWith(`.svelte`)?`svelte`:e.endsWith(`.tsx`)||e.endsWith(`.jsx`)||e.endsWith(`.ts`)||e.endsWith(`.js`)?p(e):`unknown`}async function z(e,t,n,r,i,a,o){let s=await R(e),c=s,u=await(await B(s,a)).render({component:o??null,props:n,src:e,condition:t,ssrOnly:r,viteServer:globalThis.__viteDevServer,isDev:l()});return j(u,e,s,a),P({src:e,condition:t,props:n,children:u.html,ssr:!0,framework:c,ssrOnly:r,renderOptions:i,hydrationData:r?void 0:u.hydrationData})}async function B(e,t){try{s(`${t} Loading integration for framework: ${e}`);let n=await _(e);return s(`${t} ✅ Integration loaded successfully`),n}catch(n){throw o(`${t} Failed to load ${e} integration:`,n),Error(`Failed to load integration for framework '${e}'. Make sure @useavalon/${e} is installed.\nInstall it with: deno add @useavalon/${e}`,{cause:n})}}export async function renderIsland({src:o,condition:s=`on:client`,conditionArg:c,props:d={},children:f,ssr:p=s!==`on:client`,framework:m,ssrOnly:h=!1,renderOptions:_={},component:v,server:y,island:b,key:x}){let C=l()?performance.now():0,w=`🏝️ [${o}]`;try{if(y){let s=i(o);r(s,o);let c=m||g(o),l=a(s,d,y,b,b?e(o):void 0,o,c);return S(t(n(),null,t(`div`,{dangerouslySetInnerHTML:{__html:l},"data-server-island-wrapper":``})),x)}return h&&!p&&(p=!0),S(m?await I({src:o,condition:s,conditionArg:c,props:d,children:f,ssr:p,framework:m,ssrOnly:h,renderOptions:_,component:v}):await V({src:o,condition:s,conditionArg:c,props:d,children:f,ssr:p,ssrOnly:h,renderOptions:_,logPrefix:w,component:v}),x)}catch(e){return S(F(o,e),x)}finally{l()&&u(o,performance.now()-C)}}async function V(e){let{src:t,condition:n,conditionArg:r,props:i,children:a,ssr:c,ssrOnly:l,renderOptions:u,logPrefix:d,component:f}=e;if(s(`🔍 [renderIsland] ${t} - Starting render (slow path)`,{ssr:c,ssrOnly:l,hasChildren:!!a,condition:n}),await L(t,l,u,d))return H(t,n,i,a,c,u,d);if(!c||a)return P({src:t,condition:n,conditionArg:r,props:i,children:a,ssr:c,renderOptions:u});try{return await z(t,n,i,l,u,d,f)}catch(e){let a=await R(t);return o(`${d} Framework rendering failed:`,e),P({src:t,condition:n,conditionArg:r,props:i,ssr:!1,framework:a,renderOptions:u})}}function H(e,t,n,r,i,a,s){return i&&!r?f({src:e,condition:t,props:n,renderOptions:a}).catch(r=>(o(`${s} SSR failed for SSR-only component:`,r),P({src:e,condition:t,props:n,ssr:!1,ssrOnly:!0,renderOptions:a}))):P({src:e,condition:t,props:n,children:r,ssr:i,ssrOnly:!0,renderOptions:a})}
@@ -31,6 +31,8 @@ export interface IslandProps {
31
31
  renderOptions?: AnalyzerOptions;
32
32
  /** Server island configuration — defers rendering to a server endpoint after page load */
33
33
  server?: ServerIslandProp;
34
+ /** React/Preact list key — set on the host VNode, never serialized into props */
35
+ key?: string | number;
34
36
  }
35
37
  /**
36
38
  * Parameters for framework-specific render functions
@@ -1,2 +1,2 @@
1
- import{relative as e}from"node:path";import{readDirectCss as t}from"../render/collect-css.js";const n=/\.(css|scss|sass|less|styl|stylus)$/;export function isCssHotFile(e){return n.test(e.split(`?`)[0]??e)}export function fileToDevHref(t,n){let r=e(t,n).replaceAll(`\\`,`/`);return r.startsWith(`/`)?r:`/${r}`}export function isBrowserFullReloadPayload(e){return!e||typeof e!=`object`?!1:e.type===`full-reload`}function o(e){let t=e.path;return typeof t==`string`?t:``}function s(e){let t=e.triggeredBy;return typeof t==`string`?t:``}export function isCssCorrelatedReload(e){if(!e||typeof e!=`object`)return!1;let t=s(e);if(t)return isCssHotFile(t);let n=o(e);return!n||n===`*`?!0:isCssHotFile(n)}export function shouldDropCssFullReload(e,t){return e&&isBrowserFullReloadPayload(t)&&isCssCorrelatedReload(t)}export function scheduleCssPush(e,t,n,r){if(t.has(e)){n.add(e);return}t.add(e),r(e).finally(()=>{t.delete(e),n.has(e)&&(n.delete(e),scheduleCssPush(e,t,n,r))})}export function generateDevCssHmrModule(){return[`if (import.meta.hot) {`,` import.meta.hot.on('avalon:css', function (data) {`,` if (!data || typeof data.href !== 'string') return;`,` var href = data.href.split('?')[0];`,` var id = href.charAt(0) === '/' ? href : '/' + href;`,` var css = typeof data.css === 'string' ? data.css : '';`,` var links = document.querySelectorAll('link[data-avalon-css]');`,` for (var i = 0; i < links.length; i++) {`,` if (links[i].getAttribute('data-avalon-css') === id) {`,` links[i].href = id + '?direct&v=' + Date.now();`,` }`,` }`,` if (!css || css.indexOf('__vite__updateStyle') !== -1 || css.indexOf('import.meta.hot') !== -1) return;`,` var style;`,` var nodes = document.querySelectorAll('style[data-avalon-css]');`,` for (var j = 0; j < nodes.length; j++) {`,` if (nodes[j].getAttribute('data-avalon-css') === id) { style = nodes[j]; break; }`,` }`,` if (!style) {`,` style = document.createElement('style');`,` style.setAttribute('type', 'text/css');`,` style.setAttribute('data-avalon-css', id);`,` document.head.appendChild(style);`,` }`,` style.textContent = css;`,` });`,`}`,``].join(`
1
+ import{relative as e}from"node:path";import{readDirectCss as t}from"../render/collect-css.js";const n=/\.(css|scss|sass|less|styl|stylus)$/;export function isCssHotFile(e){return n.test(e.split(`?`)[0]??e)}export function fileToDevHref(t,n){let r=e(t,n).replaceAll(`\\`,`/`);return r.startsWith(`/`)?r:`/${r}`}export function isBrowserFullReloadPayload(e){return!e||typeof e!=`object`?!1:e.type===`full-reload`}function o(e){let t=e.path;return typeof t==`string`?t:``}function s(e){let t=e.triggeredBy;return typeof t==`string`?t:``}export function isCssCorrelatedReload(e){if(!e||typeof e!=`object`)return!1;let t=s(e);if(t)return isCssHotFile(t);let n=o(e);return!n||n===`*`?!0:isCssHotFile(n)}export function shouldDropCssFullReload(e,t){return e&&isBrowserFullReloadPayload(t)&&isCssCorrelatedReload(t)}export function scheduleCssPush(e,t,n,r){if(t.has(e)){n.add(e);return}t.add(e),r(e).finally(()=>{t.delete(e),n.has(e)&&(n.delete(e),scheduleCssPush(e,t,n,r))})}export function generateDevCssHmrModule(){return[`if (import.meta.hot) {`,` import.meta.hot.on('avalon:css', function (data) {`,` if (!data || typeof data.href !== 'string') return;`,` var href = data.href.split('?')[0];`,` var id = href.charAt(0) === '/' ? href : '/' + href;`,` var css = typeof data.css === 'string' ? data.css : '';`,` var links = document.querySelectorAll('link[data-avalon-css]');`,` for (var i = 0; i < links.length; i++) {`,` if (links[i].dataset.avalonCss === id) {`,` links[i].href = id + '?direct&v=' + Date.now();`,` }`,` }`,` if (!css || css.indexOf('__vite__updateStyle') !== -1 || css.indexOf('import.meta.hot') !== -1) return;`,` var style;`,` var nodes = document.querySelectorAll('style[data-avalon-css]');`,` for (var j = 0; j < nodes.length; j++) {`,` if (nodes[j].dataset.avalonCss === id) { style = nodes[j]; break; }`,` }`,` if (!style) {`,` style = document.createElement('style');`,` style.setAttribute('type', 'text/css');`,` style.dataset.avalonCss = id;`,` document.head.appendChild(style);`,` }`,` style.textContent = css;`,` });`,`}`,``].join(`
2
2
  `)}export function createDevCssHmrPlugin(){let e=!1,t,n=new Set,i=new Set,a=()=>{e=!0,t!==void 0&&clearTimeout(t),t=setTimeout(()=>{e=!1,t=void 0},250)};return{name:`avalon:dev-css-hmr`,apply:`serve`,enforce:`pre`,applyToEnvironment:()=>!0,configureServer(t){return()=>{let n=t.ws.send.bind(t.ws);t.ws.send=((...t)=>{if(!shouldDropCssFullReload(e,t[0]))return n(...t)})}},hotUpdate({file:e,server:t}){if(isCssHotFile(e))return a(),scheduleCssPush(e,n,i,e=>d(t,e)),[]}}}function c(e,t,n){let r=new Set(e.getModulesByFile?.(t)??[]);for(let t of n){let n=e.getModuleById?.(t);n&&r.add(n);let i=e.urlToModuleMap?.get(t);i&&r.add(i)}return r}function l(e,t){let n=e._pendingRequests;if(n)for(let e of t)n.delete(e)}export function invalidateCssFile(e,t){let n=e.config?.root?fileToDevHref(e.config.root,t):``,r=n?[n,`${n}?direct`]:[];for(let n of Object.values(e.environments??{})){let e=n.moduleGraph;for(let n of c(e,t,r))e.invalidateModule(n);l(n,r)}}export function cssHotPayload(e,t){return{type:`custom`,event:`avalon:css`,data:{href:e,css:t}}}function u(e,t,n){let r=cssHotPayload(t,n),i=new Set,a=e=>{!e||i.has(e)||(i.add(e),e.send(r))};a(e.ws),a(e.environments?.client?.hot)}async function d(e,n){invalidateCssFile(e,n);let r=fileToDevHref(e.config.root,n),a=await t(e,r);u(e,r,a),e.config.logger.info(`css hmr ${r} (${a.length}b)`,{timestamp:!0})}
@@ -7,25 +7,25 @@ import{existsSync as e,readdirSync as t,readFileSync as n,rmSync as r}from"node:
7
7
  import{hydrateServerIsland}from"/@fs${N(`src/client/server-island-hydrate.ts`)}";
8
8
  hydrateServerIsland(${JSON.stringify(a)},${JSON.stringify(o)},${s},${JSON.stringify(c)},${JSON.stringify(l)});
9
9
  <\/script>`}function N(t){let n=s(o(a(import.meta.url).resolve(`@useavalon/avalon`)),t);if(t.endsWith(`.ts`)&&!e(n)){let t=n.replace(/\.ts$/,`.js`);if(e(t))return t}return n}function pe(t,n){let r=s(o(a(s(process.cwd(),`package.json`)).resolve(`@useavalon/${t}`)),n);if(n.endsWith(`.ts`)&&!e(r)){let t=r.replace(/\.ts$/,`.js`);if(e(t))return t}return r}export const VIRTUAL_MODULE_IDS={PAGE_ROUTES:`virtual:avalon/page-routes`,PAGE_LOADER:`virtual:avalon/page-loader`,ISLAND_MANIFEST:`virtual:avalon/island-manifest`,RUNTIME_CONFIG:`virtual:avalon/runtime-config`,CONFIG:`virtual:avalon/config`,LAYOUTS:`virtual:avalon/layouts`,ASSETS:`virtual:avalon/assets`,RENDERER:`virtual:avalon/renderer`,CLIENT_ENTRY:`virtual:avalon/client-entry`,DEV_CSS_HMR:`virtual:avalon/dev-css-hmr`,INTEGRATION_LOADER:`virtual:avalon/integration-loader`,ACTIONS:`virtual:avalon/actions`};export const RESOLVED_VIRTUAL_IDS={PAGE_ROUTES:`\0${VIRTUAL_MODULE_IDS.PAGE_ROUTES}`,PAGE_LOADER:`\0${VIRTUAL_MODULE_IDS.PAGE_LOADER}`,ISLAND_MANIFEST:`\0${VIRTUAL_MODULE_IDS.ISLAND_MANIFEST}`,RUNTIME_CONFIG:`\0${VIRTUAL_MODULE_IDS.RUNTIME_CONFIG}`,CONFIG:`\0${VIRTUAL_MODULE_IDS.CONFIG}`,LAYOUTS:`\0${VIRTUAL_MODULE_IDS.LAYOUTS}`,ASSETS:`\0${VIRTUAL_MODULE_IDS.ASSETS}`,RENDERER:`\0${VIRTUAL_MODULE_IDS.RENDERER}`,CLIENT_ENTRY:`\0${VIRTUAL_MODULE_IDS.CLIENT_ENTRY}`,DEV_CSS_HMR:`\0${VIRTUAL_MODULE_IDS.DEV_CSS_HMR}`,INTEGRATION_LOADER:`\0${VIRTUAL_MODULE_IDS.INTEGRATION_LOADER}`,ACTIONS:`\0${VIRTUAL_MODULE_IDS.ACTIONS}`};function me(e){return e===`react`?[]:[/^react/,/^react-dom/]}function he(e){return e===`react`?[`import { createElement as h } from 'react';`,`import { renderToString as preactRenderToString } from 'react-dom/server';`]:[`import { h } from 'preact';`,`import preactRenderToString from 'preact-render-to-string';`]}function ge(e){return e===`react`?[`import { setShellRenderToString, setShellElementFactory } from '@useavalon/avalon/render/shell-engine';`,`import { renderToString as __reactRenderToString } from 'react-dom/server';`,`import { createElement as __reactCreateElement, Fragment as __reactFragment } from 'react';`,`setShellRenderToString((vnode) => __reactRenderToString(vnode));`,`setShellElementFactory(__reactCreateElement, __reactFragment);`]:[]}function _e(e){return e===`react`?`@useavalon/react/client`:`@useavalon/preact/client`}function ve(e){let t=N(`src/core/integrations/registry.ts`),n=[`solid`,`vue`,`svelte`,`lit`].filter(t=>e.includes(t));return`${[`import { registry } from "${t}";`,...n.map(e=>`import { ${e}Integration } from "@useavalon/${e}";`),...n.map(e=>`if (${e}Integration) registry.register(${e}Integration);`)].join(`
10
- `)}\n`}function ye(e,t,n,r,i,a){let o={preset:e.preset,serverDir:t.serverDir??e.serverDir??`./server`,routeRules:e.routeRules,runtimeConfig:e.runtimeConfig,compatibilityDate:e.compatibilityDate,scanDirs:[`.`],noExternals:[`estree-walker`,/^@useavalon\//,/^estree-util/,/^preact/,...me(r.core),/^vue/,/^@vue\//],handlers:[{route:`/_server-islands/**`,handler:i},{route:`/_actions/**`,handler:a}],virtual:{"virtual:server-island-manifest":()=>re(n),"virtual:avalon-actions-manifest":()=>le(n),"virtual:server-island-key":()=>{let e=process.env.AVALON_KEY??``;return`export const serverIslandKey = ${JSON.stringify(e)};\n`},"virtual:server-island-integrations":()=>ve(r.integrations)},traceDeps:[...new Set([`undici`,...e.traceDeps??[]])]};return be(o,e,t),o}function be(e,t,n){n.renderer===!1?e.renderer=!1:t.renderer&&(e.renderer=t.renderer),t.publicRuntimeConfig&&(e.publicRuntimeConfig=t.publicRuntimeConfig),t.publicAssets&&(e.publicAssets=t.publicAssets),t.compressPublicAssets&&(e.compressPublicAssets=t.compressPublicAssets),t.serverEntry&&(e.serverEntry=t.serverEntry);let r=process.argv.includes(`build`)||process.env.NODE_ENV===`production`;t.experimentalTasks&&r&&(e.experimental={...e.experimental,tasks:!0},t.tasks&&Object.keys(t.tasks).length>0&&(e.tasks=t.tasks),t.scheduledTasks&&Object.keys(t.scheduledTasks).length>0&&(e.scheduledTasks=t.scheduledTasks)),t.prerender&&(e.prerender={routes:[],crawlLinks:!1})}export function createNitroIntegration(e,t={}){let n=v(t,e),r=c(ye(n,t,process.cwd(),e,N(`src/server-islands/route.ts`),N(`src/actions/route.ts`))),i=createNitroCoordinationPlugin({avalonConfig:e,nitroConfig:t,verbose:e.verbose}),a=createVirtualModulesPlugin({avalonConfig:e,nitroConfig:t,verbose:e.verbose}),o=b(e,t),s=y(e,{verbose:e.verbose,generatePreloadHints:!0}),l=S(x(t.preset??`node_server`,e.isDev)),u=d(t.cron,e.verbose);return{nitroOptions:n,plugins:[ee(),...Array.isArray(r)?r:[r],i,a,o,s,l,u]}}export function createNitroCoordinationPlugin(e){let{avalonConfig:t,verbose:n}=e;return{name:`avalon:nitro-coordination`,enforce:`pre`,config(e,{command:t}){if(t===`serve`)return{server:{watch:{ignored:[`**/.output/**`,`**/dist/**`,`**/.netlify/**`,`**/.vercel/**`,`**/.cloudflare/**`,`**/.wrangler/**`,`**/.firebase/**`,`**/.amplify-hosting/**`]},fs:{deny:[`.output`,`dist`,`.netlify`,`.vercel`,`.cloudflare`,`.wrangler`,`.firebase`,`.amplify-hosting`]}}}},configResolved(e){globalThis.__avalonHydrationMode=e.command===`serve`?`entry-client`:`per-island`;try{u(e.root||process.cwd())}catch{}},configureServer(e){globalThis.__viteDevServer=e;let i=e.config.root||process.cwd(),a=e=>{if(e.includes(`/actions/`))try{u(i)}catch{}};e.watcher.on(`add`,a),e.watcher.on(`unlink`,a);let o=e.config.root||process.cwd(),c=e.config.build?.outDir?s(o,e.config.build.outDir):s(o,`dist`);try{r(c,{recursive:!0,force:!0})}catch{}try{r(s(o,`.output`),{recursive:!0,force:!0})}catch{}let d=!1,f=new Promise(t=>{let n=()=>{(e.environments?.nitro)?.devServer?.entry||d?(d=!0,t()):setTimeout(n,50)};setTimeout(n,100),setTimeout(()=>{d=!0,t()},15e3)});e.middlewares.use(async(e,t,n)=>{if(d)return n();let r=e.url||`/`;if(r.startsWith(`/@`)||r.startsWith(`/__`)||/\/[^/]+\.[a-z0-9]+(\?|$)/i.test(r))return n();await f,n()});let p=null;async function m(){return p||=await g({baseDir:`${e.config.root||process.cwd()}/src`,devMode:!1}),p}function h(){p=null}Te(e,t,n,h),m().catch(e=>{console.warn(`[middleware] Failed to discover middleware:`,e)});let _=e.environments?.ssr,v=!!_&&l(_);v&&Ce(e,t.integrations,n).catch(e=>{console.error(`[prewarm] Core modules pre-warm failed:`,e)}),e.middlewares.use(async(n,r,i)=>{let a=n.url||`/`;if(!a.startsWith(`/_server-islands/`)||!v)return i();try{let{decrypt:i}=await e.ssrLoadModule(N(`src/server-islands/encryption.ts`)),{h:o,renderToString:s}=await H(e,t.core),c=new URL(a,`http://${n.headers.host||`localhost`}`).searchParams.get(`p`)||``;if(!c&&n.method===`POST`&&(c=await k(n,`Timed out reading server island request body`)),!c){r.statusCode=400,r.setHeader(`Content-Type`,`text/plain`),r.end(`Missing encrypted props`);return}let l=de(c,i);if(!l.ok){r.statusCode=400,r.setHeader(`Content-Type`,`text/plain`),r.end(`Bad Request: decryption failed`);return}let{props:u,srcPath:d,islandMeta:f}=l;if(!d){r.statusCode=404,r.setHeader(`Content-Type`,`text/plain`),r.end(`Component not found (no __src in payload)`);return}let p=(await e.ssrLoadModule(d)).default;if(typeof p!=`function`){r.statusCode=500,r.setHeader(`Content-Type`,`text/plain`),r.end(`Module "${d}" does not export a default component function`);return}let m=s(o(p,u));f&&(m+=fe(a,f,d,u)),r.statusCode=200,r.setHeader(`Content-Type`,`text/html`),r.setHeader(`Cache-Control`,`private, no-store`),r.end(m)}catch(e){console.error(`[server-islands] Dev handler error:`,e),r.statusCode=500,r.setHeader(`Content-Type`,`text/plain`),r.end(`Server island render failed: ${e instanceof Error?e.message:String(e)}`)}}),e.middlewares.use(async(t,n,r)=>{let i=t.url||`/`;if(!i.startsWith(`/_actions/`)||!v)return r();try{let r=M(e.config.root||process.cwd()),[a,o,s]=await Promise.all([e.ssrLoadModule(N(`src/actions/endpoint.ts`)),e.ssrLoadModule(N(`src/actions/registry.ts`)),r?e.ssrLoadModule(r):Promise.resolve({server:{}})]),c=o.flattenActions(s.server),l=a.defineActionHandler({registry:c,isDev:!0}),u=new URL(i,`http://${t.headers.host||`localhost`}`),d=(t.method||`GET`).toUpperCase(),f;d===`POST`&&(f=await k(t,`Timed out reading action request body`));let p=await l({url:u,web:{request:new Request(u,{method:d,headers:t.headers,body:f})},context:{}});n.statusCode=p.status,p.headers.forEach((e,t)=>{n.setHeader(t,e)}),n.end(await p.text())}catch(e){console.error(`[actions] Dev handler error:`,e),n.statusCode=500,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({error:{code:`INTERNAL_SERVER_ERROR`,message:e instanceof Error?e.message:String(e)}}))}}),e.middlewares.use(async(r,i,a)=>{if(!v)return a();let o=r.url||`/`;if(o.endsWith(`.html`)&&(o=o.slice(0,-5)||`/`),o===`/index`&&(o=`/`),o.startsWith(`/@`)||o.startsWith(`/__`)||o.startsWith(`/node_modules/`)||o.startsWith(`/src/client/`)||o.startsWith(`/packages/`)||o.includes(`.`)&&!o.endsWith(`/`)||o.startsWith(`/api/`))return a();try{if(await xe(e,o,r,i,m,n)||await Ue(e,o,t,i))return;let a=await We(e,o,t);if(a){i.statusCode=200,i.setHeader(`Content-Type`,`text/html`),i.end(a);return}await Se(e,o,i,t)}catch(e){console.error(`[SSR Error]`,e),i.statusCode=500,i.setHeader(`Content-Type`,`text/html`),i.end(T(e))}})},buildStart(){}}}async function xe(e,t,n,r,i,a){let o=performance.now(),s=await i();if(s.length===0)return!1;let c={};for(let[e,t]of Object.entries(n.headers))typeof t==`string`?c[e]=t:Array.isArray(t)&&(c[e]=t.join(`, `));let l=`http://${n.headers.host||`localhost`}${t}`,u=await _({url:l,method:n.method||`GET`,path:t,node:{req:n,res:r},req:new Request(l,{method:n.method||`GET`,headers:c}),context:{}},s,{devMode:!1}),d=performance.now()-o;return d>100&&console.warn(`⚠️ Slow middleware: ${d.toFixed(0)}ms for ${t}`),u?(r.statusCode=u.status,u.headers.forEach((e,t)=>{r.setHeader(t,e)}),r.end(await u.text()),!0):!1}async function Se(e,t,n,r){try{let{discoverErrorPages:i,getErrorPageModule:a,generateDefaultErrorPage:o}=await import(`../nitro/error-handler.js`),s=a(404,await i({isDev:r.isDev,pagesDir:r.pagesDir,loadPageModule:async t=>await e.ssrLoadModule(t)}));if(s?.default&&typeof s.default==`function`){let{renderToHtml:e}=await import(`../render/ssr.js`),r=s.default,i=await e({component:()=>r({statusCode:404,message:`Page not found: ${t}`,url:t})},{});n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(i);return}let c=o(404,`Page not found: ${t}`,r.isDev);n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(c)}catch{n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(E(t))}}async function Ce(e,t,n){let r=performance.now(),i=[{path:N(`src/render/ssr.ts`),assignTo:`ssr`},{path:N(`src/core/layout/enhanced-layout-resolver.ts`),assignTo:`layout`},{path:N(`src/middleware/index.ts`),assignTo:null},...t.map(e=>({path:pe(e,`server/renderer.ts`),assignTo:null}))],a=(await Promise.allSettled(i.map(async({path:t,assignTo:n})=>{let r=await e.ssrLoadModule(t);n===`ssr`&&(B=r),n===`layout`&&(V=r)}))).filter(e=>e.status===`fulfilled`).length,o=performance.now()-r;n&&a>0&&console.log(`🔥 SSR ready in ${o.toFixed(0)}ms (${a}/${i.length} core modules)`)}export function createVirtualModulesPlugin(e){let{avalonConfig:t,nitroConfig:n,verbose:r}=e,i=null;return{name:`avalon:nitro-virtual-modules`,enforce:`pre`,resolveId(e){return e===VIRTUAL_MODULE_IDS.PAGE_ROUTES?RESOLVED_VIRTUAL_IDS.PAGE_ROUTES:e===VIRTUAL_MODULE_IDS.PAGE_LOADER?RESOLVED_VIRTUAL_IDS.PAGE_LOADER:e===VIRTUAL_MODULE_IDS.ISLAND_MANIFEST?RESOLVED_VIRTUAL_IDS.ISLAND_MANIFEST:e===VIRTUAL_MODULE_IDS.RUNTIME_CONFIG?RESOLVED_VIRTUAL_IDS.RUNTIME_CONFIG:e===VIRTUAL_MODULE_IDS.CONFIG?RESOLVED_VIRTUAL_IDS.CONFIG:e===VIRTUAL_MODULE_IDS.LAYOUTS?RESOLVED_VIRTUAL_IDS.LAYOUTS:e===VIRTUAL_MODULE_IDS.ASSETS?RESOLVED_VIRTUAL_IDS.ASSETS:e===VIRTUAL_MODULE_IDS.RENDERER?RESOLVED_VIRTUAL_IDS.RENDERER:e===VIRTUAL_MODULE_IDS.CLIENT_ENTRY?RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY:e===VIRTUAL_MODULE_IDS.DEV_CSS_HMR?RESOLVED_VIRTUAL_IDS.DEV_CSS_HMR:e===VIRTUAL_MODULE_IDS.INTEGRATION_LOADER?RESOLVED_VIRTUAL_IDS.INTEGRATION_LOADER:e===VIRTUAL_MODULE_IDS.ACTIONS?RESOLVED_VIRTUAL_IDS.ACTIONS:null},async load(e){return e===RESOLVED_VIRTUAL_IDS.PAGE_ROUTES?await Ee(t,r):e===RESOLVED_VIRTUAL_IDS.PAGE_LOADER?await De(t,r):e===RESOLVED_VIRTUAL_IDS.ISLAND_MANIFEST?Oe():e===RESOLVED_VIRTUAL_IDS.RUNTIME_CONFIG?ke(t,n):e===RESOLVED_VIRTUAL_IDS.CONFIG?generateConfigModule(t,n):e===RESOLVED_VIRTUAL_IDS.LAYOUTS?(i||=await Ae(t,n),i):e===RESOLVED_VIRTUAL_IDS.ASSETS?je(n):e===RESOLVED_VIRTUAL_IDS.RENDERER?Me(t):e===RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY?await Fe(t,n):e===RESOLVED_VIRTUAL_IDS.DEV_CSS_HMR?te():e===RESOLVED_VIRTUAL_IDS.INTEGRATION_LOADER?generateIntegrationLoaderModule(t):e===RESOLVED_VIRTUAL_IDS.ACTIONS?ue():null},handleHotUpdate({file:e,server:t}){let{isPage:n,isComponent:r,isLayout:a,isCss:o}=R(e);o&&(i=null),n&&(F(t,RESOLVED_VIRTUAL_IDS.PAGE_ROUTES),F(t,RESOLVED_VIRTUAL_IDS.PAGE_LOADER),I(t)),(n||r||a)&&(i=null,F(t,RESOLVED_VIRTUAL_IDS.LAYOUTS),a&&P(t,RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY),setTimeout(()=>{t.ws.send({type:`full-reload`,path:`*`})},500)),we(e)&&P(t,RESOLVED_VIRTUAL_IDS.CONFIG)}}}function P(e,t){let n=e.moduleGraph.getModuleById(t);n&&e.moduleGraph.invalidateModule(n)}function F(e,t){P(e,t);let n=e.environments;if(n)for(let e of Object.values(n)){let n=e.moduleGraph;if(n)try{let e=n.getModuleById(t);e&&n.invalidateModule(e)}catch{}}}async function I(e){let t=e.environments?.nitro;if(t)try{t.devServer?.sendMessage?.({type:`full-reload`}),await t.devServer?.reloadRoutes?.()}catch{}}function L(e){F(e,RESOLVED_VIRTUAL_IDS.PAGE_ROUTES),F(e,RESOLVED_VIRTUAL_IDS.PAGE_LOADER),I(e),setTimeout(()=>{e.ws.send({type:`full-reload`,path:`*`})},500)}function R(e){let t=e.endsWith(`.css`);return{isPage:e.includes(`/pages/`)&&!t,isComponent:e.includes(`/components/`)&&/\.[tj]sx?$/.test(e),isLayout:(e.includes(`/layouts/`)||e.includes(`_layout`))&&/\.[tj]sx?$/.test(e),isCss:t}}function we(e){return e.includes(`vite.config`)||e.includes(`avalon.config`)||e.includes(`nitro.config`)}function Te(e,t,n,r){e.watcher.on(`change`,e=>{e.includes(`_middleware`)&&(h(),r?.()),(e.includes(`/render/`)||e.includes(`/layout/`)||e.includes(`/islands/`))&&(B=null,V=null),(e.includes(`/layouts/`)||e.includes(`_layout`))&&globalThis.__avalonLayoutResolver?.clearCache?.()}),e.watcher.on(`add`,t=>{t.includes(`_middleware`)&&(h(),r?.()),isPageFile(t)&&L(e)}),e.watcher.on(`unlink`,t=>{t.includes(`_middleware`)&&(h(),r?.()),isPageFile(t)&&L(e)})}export function isPageFile(e){return R(e).isPage}async function Ee(e,t){try{let{getAllPageDirs:t}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:n}=await import(`../nitro/route-discovery.js`),r=await n(await t(e.pagesDir,e.modules,process.cwd()),{developmentMode:e.isDev});return`export const pageRoutes = ${JSON.stringify(r,null,2)};\nexport default pageRoutes;\n`}catch{return`export const pageRoutes = [];
10
+ `)}\n`}function ye(e,t,n,r,i,a){let o={preset:e.preset,serverDir:t.serverDir??e.serverDir??`./server`,routeRules:e.routeRules,runtimeConfig:e.runtimeConfig,compatibilityDate:e.compatibilityDate,scanDirs:[`.`],noExternals:[`estree-walker`,/^@useavalon\//,/^estree-util/,/^preact/,...me(r.core),/^vue/,/^@vue\//],handlers:[{route:`/_server-islands/**`,handler:i},{route:`/_actions/**`,handler:a}],virtual:{"virtual:server-island-manifest":()=>re(n),"virtual:avalon-actions-manifest":()=>le(n),"virtual:server-island-key":()=>{let e=process.env.AVALON_KEY??``;return`export const serverIslandKey = ${JSON.stringify(e)};\n`},"virtual:server-island-integrations":()=>ve(r.integrations)},traceDeps:[...new Set([`undici`,...e.traceDeps??[]])]};return Ce(o,e,t),o}function be(e,t,n){if(n.renderer===!1){e.renderer=!1;return}t.renderer&&(e.renderer=t.renderer)}function xe(){return process.argv.includes(`build`)||process.env.NODE_ENV===`production`}function Se(e,t){t.experimentalTasks&&xe()&&(e.experimental={...e.experimental,tasks:!0},t.tasks&&Object.keys(t.tasks).length>0&&(e.tasks=t.tasks),t.scheduledTasks&&Object.keys(t.scheduledTasks).length>0&&(e.scheduledTasks=t.scheduledTasks))}function Ce(e,t,n){be(e,t,n),t.publicRuntimeConfig&&(e.publicRuntimeConfig=t.publicRuntimeConfig),t.publicAssets&&(e.publicAssets=t.publicAssets),t.compressPublicAssets&&(e.compressPublicAssets=t.compressPublicAssets),t.serverEntry&&(e.serverEntry=t.serverEntry),Se(e,t),t.prerender&&(e.prerender={routes:[],crawlLinks:!1})}export function createNitroIntegration(e,t={}){let n=v(t,e),r=c(ye(n,t,process.cwd(),e,N(`src/server-islands/route.ts`),N(`src/actions/route.ts`))),i=createNitroCoordinationPlugin({avalonConfig:e,nitroConfig:t,verbose:e.verbose}),a=createVirtualModulesPlugin({avalonConfig:e,nitroConfig:t,verbose:e.verbose}),o=b(e,t),s=y(e,{verbose:e.verbose,generatePreloadHints:!0}),l=S(x(t.preset??`node_server`,e.isDev)),u=d(t.cron,e.verbose);return{nitroOptions:n,plugins:[ee(),...Array.isArray(r)?r:[r],i,a,o,s,l,u]}}export function createNitroCoordinationPlugin(e){let{avalonConfig:t,verbose:n}=e;return{name:`avalon:nitro-coordination`,enforce:`pre`,config(e,{command:t}){if(t===`serve`)return{server:{watch:{ignored:[`**/.output/**`,`**/dist/**`,`**/.netlify/**`,`**/.vercel/**`,`**/.cloudflare/**`,`**/.wrangler/**`,`**/.firebase/**`,`**/.amplify-hosting/**`]},fs:{deny:[`.output`,`dist`,`.netlify`,`.vercel`,`.cloudflare`,`.wrangler`,`.firebase`,`.amplify-hosting`]}}}},configResolved(e){globalThis.__avalonHydrationMode=e.command===`serve`?`entry-client`:`per-island`;try{u(e.root||process.cwd())}catch{}},configureServer(e){globalThis.__viteDevServer=e;let i=e.config.root||process.cwd(),a=e=>{if(e.includes(`/actions/`))try{u(i)}catch{}};e.watcher.on(`add`,a),e.watcher.on(`unlink`,a);let o=e.config.root||process.cwd(),c=e.config.build?.outDir?s(o,e.config.build.outDir):s(o,`dist`);try{r(c,{recursive:!0,force:!0})}catch{}try{r(s(o,`.output`),{recursive:!0,force:!0})}catch{}let d=!1,f=new Promise(t=>{let n=()=>{(e.environments?.nitro)?.devServer?.entry||d?(d=!0,t()):setTimeout(n,50)};setTimeout(n,100),setTimeout(()=>{d=!0,t()},15e3)});e.middlewares.use(async(e,t,n)=>{if(d)return n();let r=e.url||`/`;if(r.startsWith(`/@`)||r.startsWith(`/__`)||/\/[^/]+\.[a-z0-9]+(\?|$)/i.test(r))return n();await f,n()});let p=null;async function m(){return p||=await g({baseDir:`${e.config.root||process.cwd()}/src`,devMode:!1}),p}function h(){p=null}Oe(e,t,n,h),m().catch(e=>{console.warn(`[middleware] Failed to discover middleware:`,e)});let _=e.environments?.ssr,v=!!_&&l(_);v&&Ee(e,t.integrations,n).catch(e=>{console.error(`[prewarm] Core modules pre-warm failed:`,e)}),e.middlewares.use(async(n,r,i)=>{let a=n.url||`/`;if(!a.startsWith(`/_server-islands/`)||!v)return i();try{let{decrypt:i}=await e.ssrLoadModule(N(`src/server-islands/encryption.ts`)),{h:o,renderToString:s}=await H(e,t.core),c=new URL(a,`http://${n.headers.host||`localhost`}`).searchParams.get(`p`)||``;if(!c&&n.method===`POST`&&(c=await k(n,`Timed out reading server island request body`)),!c){r.statusCode=400,r.setHeader(`Content-Type`,`text/plain`),r.end(`Missing encrypted props`);return}let l=de(c,i);if(!l.ok){r.statusCode=400,r.setHeader(`Content-Type`,`text/plain`),r.end(`Bad Request: decryption failed`);return}let{props:u,srcPath:d,islandMeta:f}=l;if(!d){r.statusCode=404,r.setHeader(`Content-Type`,`text/plain`),r.end(`Component not found (no __src in payload)`);return}let p=(await e.ssrLoadModule(d)).default;if(typeof p!=`function`){r.statusCode=500,r.setHeader(`Content-Type`,`text/plain`),r.end(`Module "${d}" does not export a default component function`);return}let m=s(o(p,u));f&&(m+=fe(a,f,d,u)),r.statusCode=200,r.setHeader(`Content-Type`,`text/html`),r.setHeader(`Cache-Control`,`private, no-store`),r.end(m)}catch(e){console.error(`[server-islands] Dev handler error:`,e),r.statusCode=500,r.setHeader(`Content-Type`,`text/plain`),r.end(`Server island render failed: ${e instanceof Error?e.message:String(e)}`)}}),e.middlewares.use(async(t,n,r)=>{let i=t.url||`/`;if(!i.startsWith(`/_actions/`)||!v)return r();try{let r=M(e.config.root||process.cwd()),[a,o,s]=await Promise.all([e.ssrLoadModule(N(`src/actions/endpoint.ts`)),e.ssrLoadModule(N(`src/actions/registry.ts`)),r?e.ssrLoadModule(r):Promise.resolve({server:{}})]),c=o.flattenActions(s.server),l=a.defineActionHandler({registry:c,isDev:!0}),u=new URL(i,`http://${t.headers.host||`localhost`}`),d=(t.method||`GET`).toUpperCase(),f;d===`POST`&&(f=await k(t,`Timed out reading action request body`));let p=await l({url:u,web:{request:new Request(u,{method:d,headers:t.headers,body:f})},context:{}});n.statusCode=p.status,p.headers.forEach((e,t)=>{n.setHeader(t,e)}),n.end(await p.text())}catch(e){console.error(`[actions] Dev handler error:`,e),n.statusCode=500,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({error:{code:`INTERNAL_SERVER_ERROR`,message:e instanceof Error?e.message:String(e)}}))}}),e.middlewares.use(async(r,i,a)=>{if(!v)return a();let o=r.url||`/`;if(o.endsWith(`.html`)&&(o=o.slice(0,-5)||`/`),o===`/index`&&(o=`/`),o.startsWith(`/@`)||o.startsWith(`/__`)||o.startsWith(`/node_modules/`)||o.startsWith(`/src/client/`)||o.startsWith(`/packages/`)||o.includes(`.`)&&!o.endsWith(`/`)||o.startsWith(`/api/`))return a();try{if(await we(e,o,r,i,m,n)||await Ke(e,o,t,i))return;let a=await qe(e,o,t);if(a){i.statusCode=200,i.setHeader(`Content-Type`,`text/html`),i.end(a);return}await Te(e,o,i,t)}catch(e){console.error(`[SSR Error]`,e),i.statusCode=500,i.setHeader(`Content-Type`,`text/html`),i.end(T(e))}})},buildStart(){}}}async function we(e,t,n,r,i,a){let o=performance.now(),s=await i();if(s.length===0)return!1;let c={};for(let[e,t]of Object.entries(n.headers))typeof t==`string`?c[e]=t:Array.isArray(t)&&(c[e]=t.join(`, `));let l=`http://${n.headers.host||`localhost`}${t}`,u=await _({url:l,method:n.method||`GET`,path:t,node:{req:n,res:r},req:new Request(l,{method:n.method||`GET`,headers:c}),context:{}},s,{devMode:!1}),d=performance.now()-o;return d>100&&console.warn(`⚠️ Slow middleware: ${d.toFixed(0)}ms for ${t}`),u?(r.statusCode=u.status,u.headers.forEach((e,t)=>{r.setHeader(t,e)}),r.end(await u.text()),!0):!1}async function Te(e,t,n,r){try{let{discoverErrorPages:i,getErrorPageModule:a,generateDefaultErrorPage:o}=await import(`../nitro/error-handler.js`),s=a(404,await i({isDev:r.isDev,pagesDir:r.pagesDir,loadPageModule:async t=>await e.ssrLoadModule(t)}));if(s?.default&&typeof s.default==`function`){let{renderToHtml:e}=await import(`../render/ssr.js`),r=s.default,i=await e({component:()=>r({statusCode:404,message:`Page not found: ${t}`,url:t})},{});n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(i);return}let c=o(404,`Page not found: ${t}`,r.isDev);n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(c)}catch{n.statusCode=404,n.setHeader(`Content-Type`,`text/html`),n.end(E(t))}}async function Ee(e,t,n){let r=performance.now(),i=[{path:N(`src/render/ssr.ts`),assignTo:`ssr`},{path:N(`src/core/layout/enhanced-layout-resolver.ts`),assignTo:`layout`},{path:N(`src/middleware/index.ts`),assignTo:null},...t.map(e=>({path:pe(e,`server/renderer.ts`),assignTo:null}))],a=(await Promise.allSettled(i.map(async({path:t,assignTo:n})=>{let r=await e.ssrLoadModule(t);n===`ssr`&&(B=r),n===`layout`&&(V=r)}))).filter(e=>e.status===`fulfilled`).length,o=performance.now()-r;n&&a>0&&console.log(`🔥 SSR ready in ${o.toFixed(0)}ms (${a}/${i.length} core modules)`)}export function createVirtualModulesPlugin(e){let{avalonConfig:t,nitroConfig:n,verbose:r}=e,i=null;return{name:`avalon:nitro-virtual-modules`,enforce:`pre`,resolveId(e){return e===VIRTUAL_MODULE_IDS.PAGE_ROUTES?RESOLVED_VIRTUAL_IDS.PAGE_ROUTES:e===VIRTUAL_MODULE_IDS.PAGE_LOADER?RESOLVED_VIRTUAL_IDS.PAGE_LOADER:e===VIRTUAL_MODULE_IDS.ISLAND_MANIFEST?RESOLVED_VIRTUAL_IDS.ISLAND_MANIFEST:e===VIRTUAL_MODULE_IDS.RUNTIME_CONFIG?RESOLVED_VIRTUAL_IDS.RUNTIME_CONFIG:e===VIRTUAL_MODULE_IDS.CONFIG?RESOLVED_VIRTUAL_IDS.CONFIG:e===VIRTUAL_MODULE_IDS.LAYOUTS?RESOLVED_VIRTUAL_IDS.LAYOUTS:e===VIRTUAL_MODULE_IDS.ASSETS?RESOLVED_VIRTUAL_IDS.ASSETS:e===VIRTUAL_MODULE_IDS.RENDERER?RESOLVED_VIRTUAL_IDS.RENDERER:e===VIRTUAL_MODULE_IDS.CLIENT_ENTRY?RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY:e===VIRTUAL_MODULE_IDS.DEV_CSS_HMR?RESOLVED_VIRTUAL_IDS.DEV_CSS_HMR:e===VIRTUAL_MODULE_IDS.INTEGRATION_LOADER?RESOLVED_VIRTUAL_IDS.INTEGRATION_LOADER:e===VIRTUAL_MODULE_IDS.ACTIONS?RESOLVED_VIRTUAL_IDS.ACTIONS:null},async load(e){return e===RESOLVED_VIRTUAL_IDS.PAGE_ROUTES?await ke(t,r):e===RESOLVED_VIRTUAL_IDS.PAGE_LOADER?await Ae(t,r):e===RESOLVED_VIRTUAL_IDS.ISLAND_MANIFEST?je():e===RESOLVED_VIRTUAL_IDS.RUNTIME_CONFIG?Me(t,n):e===RESOLVED_VIRTUAL_IDS.CONFIG?generateConfigModule(t,n):e===RESOLVED_VIRTUAL_IDS.LAYOUTS?(i||=await Ne(t,n),i):e===RESOLVED_VIRTUAL_IDS.ASSETS?Pe(n):e===RESOLVED_VIRTUAL_IDS.RENDERER?Fe(t):e===RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY?await Re(t,n):e===RESOLVED_VIRTUAL_IDS.DEV_CSS_HMR?te():e===RESOLVED_VIRTUAL_IDS.INTEGRATION_LOADER?generateIntegrationLoaderModule(t):e===RESOLVED_VIRTUAL_IDS.ACTIONS?ue():null},handleHotUpdate({file:e,server:t}){let{isPage:n,isComponent:r,isLayout:a,isCss:o}=R(e);o&&(i=null),n&&(F(t,RESOLVED_VIRTUAL_IDS.PAGE_ROUTES),F(t,RESOLVED_VIRTUAL_IDS.PAGE_LOADER),I(t)),(n||r||a)&&(i=null,F(t,RESOLVED_VIRTUAL_IDS.LAYOUTS),a&&P(t,RESOLVED_VIRTUAL_IDS.CLIENT_ENTRY),setTimeout(()=>{t.ws.send({type:`full-reload`,path:`*`})},500)),De(e)&&P(t,RESOLVED_VIRTUAL_IDS.CONFIG)}}}function P(e,t){let n=e.moduleGraph.getModuleById(t);n&&e.moduleGraph.invalidateModule(n)}function F(e,t){P(e,t);let n=e.environments;if(n)for(let e of Object.values(n)){let n=e.moduleGraph;if(n)try{let e=n.getModuleById(t);e&&n.invalidateModule(e)}catch{}}}async function I(e){let t=e.environments?.nitro;if(t)try{t.devServer?.sendMessage?.({type:`full-reload`}),await t.devServer?.reloadRoutes?.()}catch{}}function L(e){F(e,RESOLVED_VIRTUAL_IDS.PAGE_ROUTES),F(e,RESOLVED_VIRTUAL_IDS.PAGE_LOADER),I(e),setTimeout(()=>{e.ws.send({type:`full-reload`,path:`*`})},500)}function R(e){let t=e.endsWith(`.css`);return{isPage:e.includes(`/pages/`)&&!t,isComponent:e.includes(`/components/`)&&/\.[tj]sx?$/.test(e),isLayout:(e.includes(`/layouts/`)||e.includes(`_layout`))&&/\.[tj]sx?$/.test(e),isCss:t}}function De(e){return e.includes(`vite.config`)||e.includes(`avalon.config`)||e.includes(`nitro.config`)}function Oe(e,t,n,r){e.watcher.on(`change`,e=>{e.includes(`_middleware`)&&(h(),r?.()),(e.includes(`/render/`)||e.includes(`/layout/`)||e.includes(`/islands/`))&&(B=null,V=null),(e.includes(`/layouts/`)||e.includes(`_layout`))&&globalThis.__avalonLayoutResolver?.clearCache?.()}),e.watcher.on(`add`,t=>{t.includes(`_middleware`)&&(h(),r?.()),isPageFile(t)&&L(e)}),e.watcher.on(`unlink`,t=>{t.includes(`_middleware`)&&(h(),r?.()),isPageFile(t)&&L(e)})}export function isPageFile(e){return R(e).isPage}async function ke(e,t){try{let{getAllPageDirs:t}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:n}=await import(`../nitro/route-discovery.js`),r=await n(await t(e.pagesDir,e.modules,process.cwd()),{developmentMode:e.isDev});return`export const pageRoutes = ${JSON.stringify(r,null,2)};\nexport default pageRoutes;\n`}catch{return`export const pageRoutes = [];
11
11
  export default pageRoutes;
12
- `}}async function De(e,t){try{let{getAllPageDirs:t}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:n}=await import(`../nitro/route-discovery.js`),{relative:r}=await import(`node:path`),i=process.cwd(),a=await n(await t(e.pagesDir,e.modules,i),{developmentMode:e.isDev}),o=[],s=[];for(let e=0;e<a.length;e++){let t=a[e],n=`page_${e}`,c=r(i,t.filePath).replaceAll(`\\`,`/`),l=c.startsWith(`/`)?c:`/${c}`;o.push(`import * as ${n} from '${l}';`),s.push(` { pattern: ${JSON.stringify(t.pattern)}, params: ${JSON.stringify(t.params)}, module: ${n} }`)}return[...o,``,`const routes = [`,s.join(`,
12
+ `}}async function Ae(e,t){try{let{getAllPageDirs:t}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:n}=await import(`../nitro/route-discovery.js`),{relative:r}=await import(`node:path`),i=process.cwd(),a=await n(await t(e.pagesDir,e.modules,i),{developmentMode:e.isDev}),o=[],s=[];for(let e=0;e<a.length;e++){let t=a[e],n=`page_${e}`,c=r(i,t.filePath).replaceAll(`\\`,`/`),l=c.startsWith(`/`)?c:`/${c}`;o.push(`import * as ${n} from '${l}';`),s.push(` { pattern: ${JSON.stringify(t.pattern)}, params: ${JSON.stringify(t.params)}, module: ${n} }`)}return[...o,``,`const routes = [`,s.join(`,
13
13
  `),`];`,``,`/**`,` * Match a pathname against discovered routes and return the page module.`,` * Uses the same pattern matching as Avalon's route discovery.`,` */`,`/**`,` * Match a pathname against discovered routes, returning the matched`,` * page module AND the extracted dynamic route params (e.g. { id: "123" }).`,` */`,`export function loadPage(pathname) {`,` const cleanPath = pathname.split('?')[0];`,` for (const route of routes) {`,` const m = matchRoute(cleanPath, route.pattern);`,` if (m.matched) return { module: route.module, params: m.params };`,` }`,` return null;`,`}`,``,`/**`,` * Match one pattern and capture dynamic segments:`,` * /users/:id vs /users/123 -> { id: "123" }`,` * /blog/** vs /blog/a/b -> { slug: "a/b" }`,` */`,`function matchRoute(pathname, pattern) {`,String.raw` const normPath = pathname === '/' ? '/' : pathname.replace(/\/$/, '');`,String.raw` const normPattern = pattern === '/' ? '/' : pattern.replace(/\/$/, '');`,` if (normPath === normPattern) return { matched: true, params: {} };`,` const patternParts = normPattern.split('/');`,` const pathParts = normPath.split('/');`,` const params = {};`,` for (let i = 0; i < patternParts.length; i++) {`,` const seg = patternParts[i];`,` if (seg === '**') {`,` params.slug = pathParts.slice(i).join('/');`,` return { matched: true, params };`,` }`,` if (i >= pathParts.length) return { matched: false, params: {} };`,` if (seg.startsWith(':')) params[seg.slice(1)] = pathParts[i];`,` else if (seg !== pathParts[i]) return { matched: false, params: {} };`,` }`,` if (pathParts.length > patternParts.length) return { matched: false, params: {} };`,` return { matched: true, params };`,`}`,``,`export default { loadPage, routes };`,``].join(`
14
14
  `)}catch(e){return console.error(`[page-loader] Failed to generate page loader:`,e),`export function loadPage() { return null; }
15
15
  export default { loadPage, routes: [] };
16
- `}}function Oe(){return`export const islandManifest = { islands: {}, clientEntry: "", css: [] };
16
+ `}}function je(){return`export const islandManifest = { islands: {}, clientEntry: "", css: [] };
17
17
  export default islandManifest;
18
- `}function ke(e,t){let n={avalon:{streaming:t.streaming??!0,pagesDir:e.pagesDir,layoutsDir:e.layoutsDir,isDev:e.isDev},...t.runtimeConfig};return`export const runtimeConfig = ${JSON.stringify(n,null,2)};\nexport function useRuntimeConfig() { return runtimeConfig; }\nexport default runtimeConfig;\n`}export function generateConfigModule(e,t){let n=globalThis.__avalonConfig?.isDev??e.isDev,r={streaming:t.streaming??!0,pagesDir:e.pagesDir,layoutsDir:e.layoutsDir,isDev:n,...t.runtimeConfig};return`globalThis.__avalonHydrationMode = "${n?`entry-client`:`per-island`}";\nconst config = ${JSON.stringify(r,null,2)};\nexport function useAvalonConfig() { return config; }\nexport default config;\n`}async function Ae(e,t){let{getAllLayoutDirs:n}=await import(`./module-discovery.js`),{relative:r,resolve:i}=await import(`node:path`),{stat:a,readFile:o}=await import(`node:fs/promises`),c=process.cwd(),l=await n(e.layoutsDir,e.modules,c),u=[],d=0,f=i(c,e.layoutsDir);for(let{dir:t,prefix:n}of l){let i=s(t,`_layout.tsx`);try{if(!(await a(i)).isFile())continue}catch{continue}let o=r(c,i).replaceAll(`\\`,`/`),l=o.startsWith(`/`)?o:`/${o}`,p=t.startsWith(f),m=p&&!e.modules?`RootLayout`:`Layout_${d}`;u.push({prefix:n,importPath:l,varName:m,isShared:p,filePath:i}),d++}let p=u.filter(e=>e.isShared),m=u.filter(e=>!e.isShared),h=new Map;for(let e of m)try{let t=(await o(e.filePath,`utf8`)).match(/layoutConfig\s*=\s*{[\s\S]*?skipLayouts\s*:\s*\[([^\]]*)\]/)?.[1]??``,n=/['"`]_layout['"`]/.test(t);h.set(e.importPath,n)}catch{h.set(e.importPath,!1)}let g=u.map(e=>`import ${e.varName} from '${e.importPath}';`),_=m.toSorted((e,t)=>t.prefix.length-e.prefix.length).map(e=>{let t=e.prefix===`/`,n=h.get(e.importPath)??!1,r=t||n;return` { prefix: ${JSON.stringify(e.prefix)}, Layout: ${e.varName}, skipRoot: ${r} }`}),v=p.length>0?p[0].varName:`null`,y=`{"routes":[],"fallbackHrefs":[],"globalHrefs":[]}`;if(e.isDev){let{getAllPageDirs:n}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:r}=await import(`../nitro/route-discovery.js`),i=await r(await n(e.pagesDir,e.modules,c),{developmentMode:e.isDev}),a=O({cwd:c,globalCSS:t.globalCSS??[],routes:i.map(e=>({pattern:e.pattern,filePath:e.filePath})),layouts:u.map(e=>({prefix:e.prefix,filePath:e.filePath,isRoot:e.isShared,skipRoot:h.get(e.importPath)??!1}))});y=JSON.stringify(a)}return[`// Auto-generated by Avalon — do not edit`,...he(e.core),`import { getUniversalCSSForHead } from '@useavalon/avalon/islands/universal-css-collector';`,`import { getUniversalHeadForInjection, injectSolidHydrationScriptIfNeeded } from '@useavalon/avalon/islands/universal-head-collector';`,`import { appendDevCssLinks, layoutPrefixMatches, selectDevCssHrefs } from '@useavalon/avalon/render/dev-css-select';`,...g,``,`const RootLayoutComponent = ${v};`,`const _cssTable = ${y};`,``,`const moduleLayouts = [`,_.join(`,
18
+ `}function Me(e,t){let n={avalon:{streaming:t.streaming??!0,pagesDir:e.pagesDir,layoutsDir:e.layoutsDir,isDev:e.isDev},...t.runtimeConfig};return`export const runtimeConfig = ${JSON.stringify(n,null,2)};\nexport function useRuntimeConfig() { return runtimeConfig; }\nexport default runtimeConfig;\n`}export function generateConfigModule(e,t){let n=globalThis.__avalonConfig?.isDev??e.isDev,r={streaming:t.streaming??!0,pagesDir:e.pagesDir,layoutsDir:e.layoutsDir,isDev:n,...t.runtimeConfig};return`globalThis.__avalonHydrationMode = "${n?`entry-client`:`per-island`}";\nconst config = ${JSON.stringify(r,null,2)};\nexport function useAvalonConfig() { return config; }\nexport default config;\n`}async function Ne(e,t){let{getAllLayoutDirs:n}=await import(`./module-discovery.js`),{relative:r,resolve:i}=await import(`node:path`),{stat:a,readFile:o}=await import(`node:fs/promises`),c=process.cwd(),l=await n(e.layoutsDir,e.modules,c),u=[],d=0,f=i(c,e.layoutsDir);for(let{dir:t,prefix:n}of l){let i=s(t,`_layout.tsx`);try{if(!(await a(i)).isFile())continue}catch{continue}let o=r(c,i).replaceAll(`\\`,`/`),l=o.startsWith(`/`)?o:`/${o}`,p=t.startsWith(f),m=p&&!e.modules?`RootLayout`:`Layout_${d}`;u.push({prefix:n,importPath:l,varName:m,isShared:p,filePath:i}),d++}let p=u.filter(e=>e.isShared),m=u.filter(e=>!e.isShared),h=new Map;for(let e of m)try{let t=(await o(e.filePath,`utf8`)).match(/layoutConfig\s*=\s*{[\s\S]*?skipLayouts\s*:\s*\[([^\]]*)\]/)?.[1]??``,n=/['"`]_layout['"`]/.test(t);h.set(e.importPath,n)}catch{h.set(e.importPath,!1)}let g=u.map(e=>`import ${e.varName} from '${e.importPath}';`),_=m.toSorted((e,t)=>t.prefix.length-e.prefix.length).map(e=>{let t=e.prefix===`/`,n=h.get(e.importPath)??!1,r=t||n;return` { prefix: ${JSON.stringify(e.prefix)}, Layout: ${e.varName}, skipRoot: ${r} }`}),v=p.length>0?p[0].varName:`null`,y=`{"routes":[],"fallbackHrefs":[],"globalHrefs":[]}`;if(e.isDev){let{getAllPageDirs:n}=await import(`./module-discovery.js`),{discoverPageRoutesFromMultipleDirs:r}=await import(`../nitro/route-discovery.js`),i=await r(await n(e.pagesDir,e.modules,c),{developmentMode:e.isDev}),a=O({cwd:c,globalCSS:t.globalCSS??[],routes:i.map(e=>({pattern:e.pattern,filePath:e.filePath})),layouts:u.map(e=>({prefix:e.prefix,filePath:e.filePath,isRoot:e.isShared,skipRoot:h.get(e.importPath)??!1}))});y=JSON.stringify(a)}return[`// Auto-generated by Avalon — do not edit`,...he(e.core),`import { getUniversalCSSForHead } from '@useavalon/avalon/islands/universal-css-collector';`,`import { getUniversalHeadForInjection, injectSolidHydrationScriptIfNeeded } from '@useavalon/avalon/islands/universal-head-collector';`,`import { appendDevCssLinks, layoutPrefixMatches, selectDevCssHrefs } from '@useavalon/avalon/render/dev-css-select';`,...g,``,`const RootLayoutComponent = ${v};`,`const _cssTable = ${y};`,``,`const moduleLayouts = [`,_.join(`,
19
19
  `),`];`,``,`function getLayoutsForPath(pathname) {`,` return moduleLayouts.find((entry) => layoutPrefixMatches(pathname, entry.prefix)) ?? null;`,`}`,``,`function injectUniversalAssets(html, pathname, skipLayouts) {`,` if (process.env.NODE_ENV !== 'production') {`,` var hrefs = selectDevCssHrefs(_cssTable, pathname, skipLayouts);`,` html = appendDevCssLinks(html, hrefs);`,` }`,` const universalCSS = getUniversalCSSForHead(true);`,` if (universalCSS && html.includes('</head>')) {`,String.raw` html = html.replace('</head>', universalCSS + '\n</head>');`,` }`,` const universalHead = getUniversalHeadForInjection(true);`,` if (universalHead && html.includes('</head>')) {`,String.raw` html = html.replace('</head>', universalHead + '\n</head>');`,` }`,` html = injectSolidHydrationScriptIfNeeded(html);`,` return html;`,`}`,``,`export async function wrapWithLayouts(pageHtml, pageModule, context, injectAssets) {`,` const pathname = context.url.pathname;`,` const frontmatter = {`,` ...(pageModule.frontmatter || {}),`,` ...(pageModule.metadata || {}),`,` currentPath: pathname,`,` };`,` const pageLayoutConfig = pageModule.layoutConfig;`,` const skipAll = pageLayoutConfig?.skipLayouts?.includes('_layout');`,``,` const layoutEntry = getLayoutsForPath(pathname);`,` const routeInfo = { path: pathname, params: context.params, query: context.url.searchParams };`,` let html;`,``,` if (!layoutEntry || skipAll) {`,` if (RootLayoutComponent && !skipAll) {`,` const rootProps = {`,` children: h('avalon-page', { id: 'app', dangerouslySetInnerHTML: { __html: pageHtml } }),`,` frontmatter,`,` data: {},`,` route: routeInfo,`,` };`,` const rootResult = RootLayoutComponent(rootProps);`,` const resolvedRoot = rootResult instanceof Promise ? await rootResult : rootResult;`,String.raw` html = '<!DOCTYPE html>\n' + preactRenderToString(resolvedRoot);`,` } else {`,` // skipAll is true — page provides its own HTML shell or needs a minimal one`,` if (pageHtml.trimStart().startsWith('<html')) {`,String.raw` html = '<!DOCTYPE html>\n' + pageHtml;`,` } else {`,` const title = String(frontmatter.title || 'Avalon');`,` html = [`,` '<!DOCTYPE html>',`,` '<html lang="en">',`,` '<head>',`,` '<meta charset="utf-8">',`,` '<meta name="viewport" content="width=device-width, initial-scale=1">',`,` '<title>' + title + '</title>',`,` '</head>',`,` '<body>',`,` '<div id="app">' + pageHtml + '</div>',`,` '</body>',`,` '</html>',`,String.raw` ].join('\n');`,` }`,` }`,` } else {`,` const layoutProps = {`,` children: h('avalon-page', { dangerouslySetInnerHTML: { __html: pageHtml } }),`,` frontmatter,`,` data: {},`,` route: routeInfo,`,` };`,` const layoutResult = layoutEntry.Layout(layoutProps);`,` const resolvedLayout = layoutResult instanceof Promise ? await layoutResult : layoutResult;`,` let wrappedHtml = preactRenderToString(resolvedLayout);`,``,` // If the layout provides its own HTML shell (starts with <html),`,` // skip root wrapping regardless of skipRoot flag — the layout IS the document.`,` const layoutProvidesShell = wrappedHtml.trimStart().startsWith('<html');`,``,` if (!layoutProvidesShell && !layoutEntry.skipRoot && RootLayoutComponent) {`,` const rootProps = {`,` children: h('avalon-page', { dangerouslySetInnerHTML: { __html: wrappedHtml } }),`,` frontmatter,`,` data: {},`,` route: routeInfo,`,` };`,` const rootResult = RootLayoutComponent(rootProps);`,` const resolvedRoot = rootResult instanceof Promise ? await rootResult : rootResult;`,` wrappedHtml = preactRenderToString(resolvedRoot);`,` }`,``,String.raw` html = '<!DOCTYPE html>\n' + wrappedHtml;`,` }`,``,` if (injectAssets) {`,` html = injectAssets(html);`,` }`,` return injectUniversalAssets(html, pathname, skipAll);`,`}`,``,`export default { wrapWithLayouts };`,``].join(`
20
- `)}function je(e){let t=e.clientEntry??`app/entry-client`;return[`// Auto-generated by Avalon — do not edit`,`// @ts-ignore — virtual import resolved by Nitro's Vite assets plugin at build time`,`import clientAssets from '${t.startsWith(`/`)?t:`/${t}`}?assets=client';`,``,`function buildAssetTags() {`,` const cssLinks = (clientAssets?.css ?? [])`,` .filter(attr => {`,` const href = attr.href || '';`,` // The SSR build produces ssr-index-*.css containing all global, reset,`,` // token, and layout CSS module styles. The client build may also emit`,` // entry-client-*.css (a subset) and index-*.css. To avoid duplicates,`,` // prefer ssr-index when it exists; otherwise fall back to the others.`,` var hasSsrIndex = (clientAssets?.css ?? []).some(function(a) { return (a.href || '').includes('ssr-index'); });`,` if (hasSsrIndex) return href.includes('ssr-index');`,` if (href.includes('entry-client') && href.endsWith('.css')) return true;`,String.raw` if (/\/index-[^/]+\.css$/.test(href)) return true;`,` return false;`,` })`,` .map(attr => '<link rel="stylesheet" href="' + attr.href + '">')`,String.raw` .join('\n');`,` const jsPreloads = (clientAssets?.js ?? [])`,` .map(attr => '<link rel="modulepreload" href="' + attr.href + '">')`,String.raw` .join('\n');`,` const entryScript = clientAssets?.entry`,` ? '<script type="module" src="' + clientAssets.entry + '"><\/script>'`,` : '';`,` return { cssLinks, jsPreloads, entryScript };`,`}`,``,`export function injectAssets(html) {`,` const { cssLinks, jsPreloads, entryScript } = buildAssetTags();`,` if (html.includes('</head>')) {`,String.raw` html = html.replace('</head>', cssLinks + '\n' + jsPreloads + '\n</head>');`,` }`,` if (html.includes('</body>')) {`,String.raw` html = html.replace('</body>', entryScript + '\n</body>');`,` }`,` return html;`,`}`,``,`export { clientAssets };`,`export default { injectAssets, clientAssets };`,``].join(`
21
- `)}function Me(e){let t=Array.isArray(e.integrations)?e.integrations:[],n=[],r=[];for(let e of t){let t=`${e}Integration`;n.push(`import { ${t} } from '@useavalon/${e}';`),r.push(`registry.register(${t});`)}let i=ge(e.core);return[`// Auto-generated by Avalon — do not edit`,`import { createNitroRenderer } from '@useavalon/avalon/nitro/renderer';`,`import { registerBuiltinDirectives } from '@useavalon/avalon';`,`import { registry } from '@useavalon/avalon/islands/integration-registry';`,`import avalonConfig from 'virtual:avalon/config';`,`import { loadPage } from 'virtual:avalon/page-loader';`,`import { wrapWithLayouts } from 'virtual:avalon/layouts';`,`import { injectAssets } from 'virtual:avalon/assets';`,...n,``,...i,``,`// Pre-register framework integrations for SSR`,...r,``,`// Register built-in custom hydration directives (on:delay, on:scroll, etc.)`,`registerBuiltinDirectives();`,``,`// Set hydration mode flag — intentionally duplicated from virtual:avalon/config`,`// for module-load-order resilience (config import may be tree-shaken or deferred).`,`globalThis.__avalonHydrationMode = avalonConfig.isDev ? "entry-client" : "per-island";`,``,`export default createNitroRenderer({`,` avalonConfig,`,` isDev: avalonConfig.isDev,`,` resolvePageRoute: async (pathname) => {`,` const match = loadPage(pathname);`,` if (!match || !('default' in match.module)) return null;`,` return { filePath: '[virtual:' + pathname + ']', pattern: pathname, params: match.params };`,` },`,` loadPageModule: async (filePath) => {`,String.raw` const m = filePath.match(/^\[virtual:(.+)\]$/);`,` const pathname = m ? m[1] : filePath;`,` const match = loadPage(pathname);`,` if (match) return match.module;`,` return { default: () => null, metadata: { title: 'Avalon' } };`,` },`,` wrapWithLayouts: (pageHtml, pageModule, context) =>`,` wrapWithLayouts(pageHtml, pageModule, context, injectAssets),`,`});`,``].join(`
22
- `)}async function Ne(e,t){let{readdir:n}=await import(`node:fs/promises`),{relative:r,join:i}=await import(`node:path`),a=[];for(let{dir:o}of e){let e;try{e=await n(o,{withFileTypes:!0})}catch{continue}for(let n of e){if(!n.isFile()||!n.name.endsWith(`.css`))continue;let e=r(t,i(o,n.name)).replaceAll(`\\`,`/`);a.push(e.startsWith(`/`)?e:`/${e}`)}}return a}function Pe(e){if(e.length===0)return[];let t=[`// Layout CSS (auto-discovered)`],n=0;for(let r of e)r.includes(`.module.`)?(t.push(`import _lcss${n} from '${r}';`),n++):t.push(`import '${r}';`);return t}async function Fe(e,t){let{getAllLayoutDirs:n}=await import(`./module-discovery.js`),r=process.cwd(),i=await Ne(await n(e.layoutsDir,e.modules,r),r),a=globalThis.__avalonConfig?.isDev??e.isDev,o=a?`@useavalon/avalon/client/main`:`@useavalon/avalon/client/main-slim`,s=[`// Auto-generated by Avalon — do not edit`,`// Island hydration runtime`];(globalThis.__avalonHydrationMode??`entry-client`)===`entry-client`?s.push(`import '${o}';`):s.push(`// Per-island hydration mode — no shared runtime needed`),a&&s.push(`import '${VIRTUAL_MODULE_IDS.DEV_CSS_HMR}';`),s.push(``);let c=t.globalCSS??[];for(let e of c){let t=e.startsWith(`/`)?e:`/${e}`;s.push(`// Global CSS`,`import '${t}';`)}return c.length>0&&s.push(``),s.push(...Pe(i),``),s.join(`
23
- `)}function Ie(){return[`// --- Inlined Solid adapter (production) ---`,`// Eliminates a separate chunk + network request for the Solid client adapter.`,`// Only imports hydrate/createComponent — no render() fallback (saves ~1-2 KiB).`,`function _ensureHydrationContext() {`,` if (!globalThis._$HY) {`,` globalThis._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };`,` }`,`}`,``,`async function _solidHydrate(container, Component, props) {`,` if (!container) throw new Error("Container element is required for hydration");`,` if (!Component || typeof Component !== "function") {`,` throw new Error("Invalid Solid component: expected function, got " + typeof Component);`,` }`,` var el = container;`,` var renderId = el.dataset.solidRenderId || el.dataset.renderId;`,` var { hydrate: solidHydrate, createComponent } = await import("solid-js/web");`,` _ensureHydrationContext();`,` solidHydrate(function() { return createComponent(Component, props || {}); }, el, { renderId: renderId || "" });`,`}`,``,`var _solidModule = { hydrate: _solidHydrate };`,``]}function Le(e,t,n){let r=[];for(let i of e){let e=t[i];e&&(i===`solid`&&!n?r.push(` case "solid":`,` return _solidModule;`):i===`react`?r.push(` case "react":`):r.push(` case "${i}":`,` return import("${e}");`))}return e.includes(`react`)&&!e.includes(`preact`)&&r.push(` return import("${t.react}");`),r}function Re(e,t){let n=[];for(let r of e){let e=t[r];e&&n.push(` case "${r}":`,` return import("${e}").then(m => m.${r}Adapter);`)}return n}export function generateIntegrationLoaderModule(e){let t=(e.integrations??[]).map(e=>typeof e==`string`?e:e.name),n={preact:`@useavalon/preact/client`,react:_e(e.core),vue:`@useavalon/vue/client`,svelte:`@useavalon/svelte/client`,solid:`@useavalon/solid/client`,lit:`@useavalon/lit/client`,qwik:`@useavalon/qwik/client`},r={preact:`@useavalon/preact/client/hmr`,react:`@useavalon/react/client/hmr`,vue:`@useavalon/vue/client/hmr`,svelte:`@useavalon/svelte/client/hmr`,solid:`@useavalon/solid/client/hmr`,lit:`@useavalon/lit/client/hmr`,qwik:`@useavalon/qwik/client/hmr`},i=t.includes(`lit`),a=t.includes(`solid`),o=(globalThis.__avalonConfig?.isDev??e.isDev)===!0,s=[`// Auto-generated by Avalon — only includes configured integrations`,``];return a&&!o&&s.push(...Ie()),s.push(`// --- loadIntegrationModule ---`,`export async function loadIntegrationModule(framework) {`,` switch (framework) {`,...Le(t,n,o),` default:`," throw new Error(`Unknown or unconfigured framework: ${framework}`);",` }`,`}`,``,`// --- Lit hydration pre-load (only if Lit is configured) ---`),i?s.push(`export async function preLitHydration() {`,` await import("@useavalon/lit/client");`,`}`):s.push(`export async function preLitHydration() {}`),s.push(``,`// --- HMR adapter loader ---`,`export async function loadHMRAdapter(framework) {`,` switch (framework) {`,...Re(t,r),` default: return null;`,` }`,`}`),s.join(`
24
- `)}export function getViteDevServer(){return globalThis.__viteDevServer}export function getAvalonConfig(){return globalThis.__avalonConfig}export function isDevelopmentMode(){return globalThis.__avalonConfig?.isDev??!0}const z=`<!--AVALON_STREAM_BOUNDARY-->`;let B=null,V=null;async function H(e,t){if(t===`react`){let e=await import(`react`),t=await import(`react-dom/server`),n=e.default??e,r=t.default??t;return{h:e.createElement??n.createElement,renderToString:t.renderToString??r.renderToString}}let n=await e.ssrLoadModule(`preact`),r=await e.ssrLoadModule(`preact-render-to-string`);return{h:n.h,renderToString:r.render??r.default}}function U(e){return e.split(`/`).pop()?.replace(/\.[^.]+$/,``)||``}async function W(e,t,n){let r=[];for(let n of t){let t=await e.ssrLoadModule(n);r.push({file:n,module:t})}for(let r of t){let t=await C(e,r);n.push(...t)}return r}async function G(e,t,n,r){let i=[],a=[];for(let o of e){let e=o.module.default;if(!(!e||typeof e!=`function`))try{let s=e({...t,children:n(`div`,null,`test`)}),c=r(s instanceof Promise?await s:s);c.trim().startsWith(`<html`)||c.includes(`<!DOCTYPE`)?i.push(o):a.push(o)}catch{a.push(o)}}return{shellLayouts:i,wrapperLayouts:a}}async function ze(e,t,n,r){try{let i=e({...t,children:n(`div`,{dangerouslySetInnerHTML:{__html:z}})});return r(i instanceof Promise?await i:i)}catch{return null}}function Be(e,t){let n=e;if(t.length>0){let e=`<style data-avalon-ssr-css>${t.join(`
25
- `)}</style>`;n.includes(`</head>`)?n=n.replace(`</head>`,`${e}\n</head>`):n+=e}n.trim().toLowerCase().startsWith(`<!doctype`)||(n=`<!DOCTYPE html>\n${n}`);let r=f(!0);r&&n.includes(`</head>`)&&(n=n.replace(`</head>`,`${r}\n</head>`));let i=p(!0);return i&&n.includes(`</head>`)&&(n=n.replace(`</head>`,`${i}\n</head>`)),m(n)}async function K(e,t,n){try{let n=typeof e==`function`?e():e;return t(n instanceof Promise?await n:n)}catch(e){return console.error(`${n} Error rendering page component:`,e),`<div>Error rendering page</div>`}}async function q(e,t,n,r,i,a){let o=e;for(let{module:e}of t){let t=e.default;if(!(!t||typeof t!=`function`))try{let e=t({...n,children:r(`div`,{dangerouslySetInnerHTML:{__html:o}})});o=i(e instanceof Promise?await e:e)}catch(e){console.error(`${a} Error rendering wrapper layout:`,e)}}return o}async function Ve(e,t,n,r,i){if(t.length===0)return e;let{module:a}=t.at(-1),o=a.default;if(!o||typeof o!=`function`)return e;try{let t=o({...n,children:r(`div`,{dangerouslySetInnerHTML:{__html:e}})});return i(t instanceof Promise?await t:t)}catch(t){return console.error(`[SSR] Error rendering shell layout:`,t),e}}function He(e){if(e.includes(`/src/client/main.js`)||e.includes(`/@vite/client`))return e;let t=e.lastIndexOf(`</body>`);return t===-1?e:e.slice(0,t)+`
20
+ `)}function Pe(e){let t=e.clientEntry??`app/entry-client`;return[`// Auto-generated by Avalon — do not edit`,`// @ts-ignore — virtual import resolved by Nitro's Vite assets plugin at build time`,`import clientAssets from '${t.startsWith(`/`)?t:`/${t}`}?assets=client';`,``,`function buildAssetTags() {`,` const cssLinks = (clientAssets?.css ?? [])`,` .filter(attr => {`,` const href = attr.href || '';`,` // The SSR build produces ssr-index-*.css containing all global, reset,`,` // token, and layout CSS module styles. The client build may also emit`,` // entry-client-*.css (a subset) and index-*.css. To avoid duplicates,`,` // prefer ssr-index when it exists; otherwise fall back to the others.`,` var hasSsrIndex = (clientAssets?.css ?? []).some(function(a) { return (a.href || '').includes('ssr-index'); });`,` if (hasSsrIndex) return href.includes('ssr-index');`,` if (href.includes('entry-client') && href.endsWith('.css')) return true;`,String.raw` if (/\/index-[^/]+\.css$/.test(href)) return true;`,` return false;`,` })`,` .map(attr => '<link rel="stylesheet" href="' + attr.href + '">')`,String.raw` .join('\n');`,` const jsPreloads = (clientAssets?.js ?? [])`,` .map(attr => '<link rel="modulepreload" href="' + attr.href + '">')`,String.raw` .join('\n');`,` const entryScript = clientAssets?.entry`,` ? '<script type="module" src="' + clientAssets.entry + '"><\/script>'`,` : '';`,` return { cssLinks, jsPreloads, entryScript };`,`}`,``,`export function injectAssets(html) {`,` const { cssLinks, jsPreloads, entryScript } = buildAssetTags();`,` if (html.includes('</head>')) {`,String.raw` html = html.replace('</head>', cssLinks + '\n' + jsPreloads + '\n</head>');`,` }`,` if (html.includes('</body>')) {`,String.raw` html = html.replace('</body>', entryScript + '\n</body>');`,` }`,` return html;`,`}`,``,`export { clientAssets };`,`export default { injectAssets, clientAssets };`,``].join(`
21
+ `)}function Fe(e){let t=Array.isArray(e.integrations)?e.integrations:[],n=[],r=[];for(let e of t){let t=`${e}Integration`;n.push(`import { ${t} } from '@useavalon/${e}';`),r.push(`registry.register(${t});`)}let i=ge(e.core);return[`// Auto-generated by Avalon — do not edit`,`import { createNitroRenderer } from '@useavalon/avalon/nitro/renderer';`,`import { registerBuiltinDirectives } from '@useavalon/avalon';`,`import { registry } from '@useavalon/avalon/islands/integration-registry';`,`import avalonConfig from 'virtual:avalon/config';`,`import { loadPage } from 'virtual:avalon/page-loader';`,`import { wrapWithLayouts } from 'virtual:avalon/layouts';`,`import { injectAssets } from 'virtual:avalon/assets';`,...n,``,...i,``,`// Pre-register framework integrations for SSR`,...r,``,`// Register built-in custom hydration directives (on:delay, on:scroll, etc.)`,`registerBuiltinDirectives();`,``,`// Set hydration mode flag — intentionally duplicated from virtual:avalon/config`,`// for module-load-order resilience (config import may be tree-shaken or deferred).`,`globalThis.__avalonHydrationMode = avalonConfig.isDev ? "entry-client" : "per-island";`,``,`export default createNitroRenderer({`,` avalonConfig,`,` isDev: avalonConfig.isDev,`,` resolvePageRoute: async (pathname) => {`,` const match = loadPage(pathname);`,` if (!match || !('default' in match.module)) return null;`,` return { filePath: '[virtual:' + pathname + ']', pattern: pathname, params: match.params };`,` },`,` loadPageModule: async (filePath) => {`,String.raw` const m = filePath.match(/^\[virtual:(.+)\]$/);`,` const pathname = m ? m[1] : filePath;`,` const match = loadPage(pathname);`,` if (match) return match.module;`,` return { default: () => null, metadata: { title: 'Avalon' } };`,` },`,` wrapWithLayouts: (pageHtml, pageModule, context) =>`,` wrapWithLayouts(pageHtml, pageModule, context, injectAssets),`,`});`,``].join(`
22
+ `)}async function Ie(e,t){let{readdir:n}=await import(`node:fs/promises`),{relative:r,join:i}=await import(`node:path`),a=[];for(let{dir:o}of e){let e;try{e=await n(o,{withFileTypes:!0})}catch{continue}for(let n of e){if(!n.isFile()||!n.name.endsWith(`.css`))continue;let e=r(t,i(o,n.name)).replaceAll(`\\`,`/`);a.push(e.startsWith(`/`)?e:`/${e}`)}}return a}function Le(e){if(e.length===0)return[];let t=[`// Layout CSS (auto-discovered)`],n=0;for(let r of e)r.includes(`.module.`)?(t.push(`import _lcss${n} from '${r}';`),n++):t.push(`import '${r}';`);return t}async function Re(e,t){let{getAllLayoutDirs:n}=await import(`./module-discovery.js`),r=process.cwd(),i=await Ie(await n(e.layoutsDir,e.modules,r),r),a=globalThis.__avalonConfig?.isDev??e.isDev,o=a?`@useavalon/avalon/client/main`:`@useavalon/avalon/client/main-slim`,s=[`// Auto-generated by Avalon — do not edit`,`// Island hydration runtime`];(globalThis.__avalonHydrationMode??`entry-client`)===`entry-client`?s.push(`import '${o}';`):s.push(`// Per-island hydration mode — no shared runtime needed`),a&&s.push(`import '${VIRTUAL_MODULE_IDS.DEV_CSS_HMR}';`),s.push(``);let c=t.globalCSS??[];for(let e of c){let t=e.startsWith(`/`)?e:`/${e}`;s.push(`// Global CSS`,`import '${t}';`)}return c.length>0&&s.push(``),s.push(...Le(i),``),s.join(`
23
+ `)}function ze(){return[`// --- Inlined Solid adapter (production) ---`,`// Eliminates a separate chunk + network request for the Solid client adapter.`,`// Only imports hydrate/createComponent — no render() fallback (saves ~1-2 KiB).`,`function _ensureHydrationContext() {`,` if (!globalThis._$HY) {`,` globalThis._$HY = { events: [], completed: new WeakSet(), r: {}, fe() {} };`,` }`,`}`,``,`async function _solidHydrate(container, Component, props) {`,` if (!container) throw new Error("Container element is required for hydration");`,` if (!Component || typeof Component !== "function") {`,` throw new Error("Invalid Solid component: expected function, got " + typeof Component);`,` }`,` var el = container;`,` var renderId = el.dataset.solidRenderId || el.dataset.renderId;`,` var { hydrate: solidHydrate, createComponent } = await import("solid-js/web");`,` _ensureHydrationContext();`,` solidHydrate(function() { return createComponent(Component, props || {}); }, el, { renderId: renderId || "" });`,`}`,``,`var _solidModule = { hydrate: _solidHydrate };`,``]}function Be(e,t,n){let r=[];for(let i of e){let e=t[i];e&&(i===`solid`&&!n?r.push(` case "solid":`,` return _solidModule;`):i===`react`?r.push(` case "react":`):r.push(` case "${i}":`,` return import("${e}");`))}return e.includes(`react`)&&!e.includes(`preact`)&&r.push(` return import("${t.react}");`),r}function Ve(e,t){let n=[];for(let r of e){let e=t[r];e&&n.push(` case "${r}":`,` return import("${e}").then(m => m.${r}Adapter);`)}return n}export function generateIntegrationLoaderModule(e){let t=(e.integrations??[]).map(e=>typeof e==`string`?e:e.name),n={preact:`@useavalon/preact/client`,react:_e(e.core),vue:`@useavalon/vue/client`,svelte:`@useavalon/svelte/client`,solid:`@useavalon/solid/client`,lit:`@useavalon/lit/client`,qwik:`@useavalon/qwik/client`},r={preact:`@useavalon/preact/client/hmr`,react:`@useavalon/react/client/hmr`,vue:`@useavalon/vue/client/hmr`,svelte:`@useavalon/svelte/client/hmr`,solid:`@useavalon/solid/client/hmr`,lit:`@useavalon/lit/client/hmr`,qwik:`@useavalon/qwik/client/hmr`},i=t.includes(`lit`),a=t.includes(`solid`),o=(globalThis.__avalonConfig?.isDev??e.isDev)===!0,s=[`// Auto-generated by Avalon — only includes configured integrations`,``];return a&&!o&&s.push(...ze()),s.push(`// --- loadIntegrationModule ---`,`export async function loadIntegrationModule(framework) {`,` switch (framework) {`,...Be(t,n,o),` default:`," throw new Error(`Unknown or unconfigured framework: ${framework}`);",` }`,`}`,``,`// --- Lit hydration pre-load (only if Lit is configured) ---`),i?s.push(`export async function preLitHydration() {`,` await import("@useavalon/lit/client");`,`}`):s.push(`export async function preLitHydration() {}`),s.push(``,`// --- HMR adapter loader ---`,`export async function loadHMRAdapter(framework) {`,` switch (framework) {`,...Ve(t,r),` default: return null;`,` }`,`}`),s.join(`
24
+ `)}export function getViteDevServer(){return globalThis.__viteDevServer}export function getAvalonConfig(){return globalThis.__avalonConfig}export function isDevelopmentMode(){return globalThis.__avalonConfig?.isDev??!0}const z=`<!--AVALON_STREAM_BOUNDARY-->`;let B=null,V=null;async function H(e,t){if(t===`react`){let e=await import(`react`),t=await import(`react-dom/server`),n=e.default??e,r=t.default??t;return{h:e.createElement??n.createElement,renderToString:t.renderToString??r.renderToString}}let n=await e.ssrLoadModule(`preact`),r=await e.ssrLoadModule(`preact-render-to-string`);return{h:n.h,renderToString:r.render??r.default}}function U(e){return e.split(`/`).pop()?.replace(/\.[^.]+$/,``)||``}async function W(e,t,n){let r=[];for(let n of t){let t=await e.ssrLoadModule(n);r.push({file:n,module:t})}for(let r of t){let t=await C(e,r);n.push(...t)}return r}async function G(e,t,n,r){let i=[],a=[];for(let o of e){let e=o.module.default;if(!(!e||typeof e!=`function`))try{let s=e({...t,children:n(`div`,null,`test`)}),c=r(s instanceof Promise?await s:s);c.trim().startsWith(`<html`)||c.includes(`<!DOCTYPE`)?i.push(o):a.push(o)}catch{a.push(o)}}return{shellLayouts:i,wrapperLayouts:a}}async function He(e,t,n,r){try{let i=e({...t,children:n(`div`,{dangerouslySetInnerHTML:{__html:z}})});return r(i instanceof Promise?await i:i)}catch{return null}}function Ue(e,t){let n=e;if(t.length>0){let e=`<style data-avalon-ssr-css>${t.join(`
25
+ `)}</style>`;n.includes(`</head>`)?n=n.replace(`</head>`,`${e}\n</head>`):n+=e}n.trim().toLowerCase().startsWith(`<!doctype`)||(n=`<!DOCTYPE html>\n${n}`);let r=f(!0);r&&n.includes(`</head>`)&&(n=n.replace(`</head>`,`${r}\n</head>`));let i=p(!0);return i&&n.includes(`</head>`)&&(n=n.replace(`</head>`,`${i}\n</head>`)),m(n)}async function K(e,t,n){try{let n=typeof e==`function`?e():e;return t(n instanceof Promise?await n:n)}catch(e){return console.error(`${n} Error rendering page component:`,e),`<div>Error rendering page</div>`}}async function q(e,t,n,r,i,a){let o=e;for(let{module:e}of t){let t=e.default;if(!(!t||typeof t!=`function`))try{let e=t({...n,children:r(`div`,{dangerouslySetInnerHTML:{__html:o}})});o=i(e instanceof Promise?await e:e)}catch(e){console.error(`${a} Error rendering wrapper layout:`,e)}}return o}async function We(e,t,n,r,i){if(t.length===0)return e;let{module:a}=t.at(-1),o=a.default;if(!o||typeof o!=`function`)return e;try{let t=o({...n,children:r(`div`,{dangerouslySetInnerHTML:{__html:e}})});return i(t instanceof Promise?await t:t)}catch(t){return console.error(`[SSR] Error rendering shell layout:`,t),e}}function Ge(e){if(e.includes(`/src/client/main.js`)||e.includes(`/@vite/client`))return e;let t=e.lastIndexOf(`</body>`);return t===-1?e:e.slice(0,t)+`
26
26
  <script type="module" src="/@vite/client"><\/script>
27
27
  <script type="module" src="/src/client/main.js"><\/script>
28
- `+e.slice(t)}async function Ue(e,t,n,r){if(!n.modules)return!1;let i=t.split(`?`)[0],a=await Q(i,n,e);if(!a)return!1;try{let t=await e.ssrLoadModule(a),o=t.default;if(!o)return!1;let s=t.layoutConfig,c=await C(e,a),l=await W(e,await Y(i,e),c);if(l.length===0)return!1;let{h:u,renderToString:d}=await H(e,n.core),f=s?.skipLayouts||[],p=l.filter(({file:e})=>!f.includes(U(e))),m=t.frontmatter,h=t.metadata,g={children:null,frontmatter:{...m,...h,currentPath:i},params:{},url:i},{shellLayouts:_,wrapperLayouts:v}=await G(p,g,u,d);if(_.length===0)return!1;let{module:y}=_.at(-1),b=y.default;if(!b||typeof b!=`function`)return!1;let x=await ze(b,g,u,d);if(x===null)return!1;let S=x.indexOf(z);if(S===-1)return!1;let w=x.slice(0,S),T=x.slice(S+29),E=Be(w,c);r.statusCode=200,r.setHeader(`Content-Type`,`text/html; charset=utf-8`),r.setHeader(`Transfer-Encoding`,`chunked`),r.setHeader(`X-Avalon-Streaming`,`1`),r.flushHeaders(),r.write(E);let D=await K(o,d,`[SSR Streaming]`);if(D.trim().startsWith(`<!DOCTYPE html>`)||D.trim().startsWith(`<html`))return r.end(D),!0;let O=He(await q(D,v,g,u,d,`[SSR Streaming]`)+T);return r.end(O),!0}catch(e){return r.headersSent?(r.end(`<div>Streaming SSR error: ${e.message}</div></body></html>`),!0):!1}}async function We(e,t,n){let r=t.split(`?`)[0],i=await Q(r,n,e);if(!i)return null;try{let t=await e.ssrLoadModule(i),a=t.default;if(!a)return console.warn(`[SSR] Page ${i} has no default export`),null;let o=await C(e,i),s=await W(e,await Y(r,e),o),c;return c=n.modules&&s.length>0?await Ge(a,t,s,r,n,e):await Ze(a,t,r,n,e),o.length>0&&(c=w(c,o)),c}catch(e){throw console.error(`[SSR] Error rendering ${i}:`,e),e}}async function Ge(e,t,n,r,i,a){let{h:o,renderToString:s}=await H(a,i.core),c=t.layoutConfig?.skipLayouts||[],l=n.filter(({file:e})=>!c.includes(U(e))),u=await K(e,s,`[SSR]`);if(u.trim().startsWith(`<!DOCTYPE html>`)||u.trim().startsWith(`<html`))return J(u);let d=t.frontmatter,f=t.metadata,p={children:null,frontmatter:{...d,...f,currentPath:r},params:{},url:r},{shellLayouts:m,wrapperLayouts:h}=await G(l,p,o,s),g=await Ve(await q(u,h,p,o,s,`[SSR]`),m,p,o,s);if(g.trim().startsWith(`<!DOCTYPE html>`)||g.trim().startsWith(`<html`))return J(g);let _=t.metadata||{},v=_.title||`Avalon App`,y=_.description||``;return`<!DOCTYPE html>
28
+ `+e.slice(t)}async function Ke(e,t,n,r){if(!n.modules)return!1;let i=t.split(`?`)[0],a=await Q(i,n,e);if(!a)return!1;try{let t=await e.ssrLoadModule(a),o=t.default;if(!o)return!1;let s=t.layoutConfig,c=await C(e,a),l=await W(e,await Y(i,e),c);if(l.length===0)return!1;let{h:u,renderToString:d}=await H(e,n.core),f=s?.skipLayouts||[],p=l.filter(({file:e})=>!f.includes(U(e))),m=t.frontmatter,h=t.metadata,g={children:null,frontmatter:{...m,...h,currentPath:i},params:{},url:i},{shellLayouts:_,wrapperLayouts:v}=await G(p,g,u,d);if(_.length===0)return!1;let{module:y}=_.at(-1),b=y.default;if(!b||typeof b!=`function`)return!1;let x=await He(b,g,u,d);if(x===null)return!1;let S=x.indexOf(z);if(S===-1)return!1;let w=x.slice(0,S),T=x.slice(S+29),E=Ue(w,c);r.statusCode=200,r.setHeader(`Content-Type`,`text/html; charset=utf-8`),r.setHeader(`Transfer-Encoding`,`chunked`),r.setHeader(`X-Avalon-Streaming`,`1`),r.flushHeaders(),r.write(E);let D=await K(o,d,`[SSR Streaming]`);if(D.trim().startsWith(`<!DOCTYPE html>`)||D.trim().startsWith(`<html`))return r.end(D),!0;let O=Ge(await q(D,v,g,u,d,`[SSR Streaming]`)+T);return r.end(O),!0}catch(e){return r.headersSent?(r.end(`<div>Streaming SSR error: ${e.message}</div></body></html>`),!0):!1}}async function qe(e,t,n){let r=t.split(`?`)[0],i=await Q(r,n,e);if(!i)return null;try{let t=await e.ssrLoadModule(i),a=t.default;if(!a)return console.warn(`[SSR] Page ${i} has no default export`),null;let o=await C(e,i),s=await W(e,await Y(r,e),o),c;return c=n.modules&&s.length>0?await Je(a,t,s,r,n,e):await et(a,t,r,n,e),o.length>0&&(c=w(c,o)),c}catch(e){throw console.error(`[SSR] Error rendering ${i}:`,e),e}}async function Je(e,t,n,r,i,a){let{h:o,renderToString:s}=await H(a,i.core),c=t.layoutConfig?.skipLayouts||[],l=n.filter(({file:e})=>!c.includes(U(e))),u=await K(e,s,`[SSR]`);if(u.trim().startsWith(`<!DOCTYPE html>`)||u.trim().startsWith(`<html`))return J(u);let d=t.frontmatter,f=t.metadata,p={children:null,frontmatter:{...d,...f,currentPath:r},params:{},url:r},{shellLayouts:m,wrapperLayouts:h}=await G(l,p,o,s),g=await We(await q(u,h,p,o,s,`[SSR]`),m,p,o,s);if(g.trim().startsWith(`<!DOCTYPE html>`)||g.trim().startsWith(`<html`))return J(g);let _=t.metadata||{},v=_.title||`Avalon App`,y=_.description||``;return`<!DOCTYPE html>
29
29
  <html lang="en">
30
30
  <head>
31
31
  <meta charset="utf-8">
@@ -43,7 +43,7 @@ export default islandManifest;
43
43
  <script type="module" src="/src/client/main.js"><\/script>`:t.slice(0,r)+`
44
44
  <script type="module" src="/@vite/client"><\/script>
45
45
  <script type="module" src="/src/client/main.js"><\/script>
46
- `+t.slice(r)}async function Y(e,t){let n=t.config.root||process.cwd(),r=globalThis.__avalonConfig,a=`_layout.tsx`,o=[],s=e.split(`/`).filter(Boolean),c=[``];for(let e=0;e<s.length;e++)c.push(`/${s.slice(0,e+1).join(`/`)}`);async function l(e){try{if((await i(e)).isFile()){let t=e.slice(n.length);o.includes(t)||o.push(t)}}catch{}}if(r?.layoutsDir&&await l(`${`${n}/${r.layoutsDir}`}/${a}`),r?.modules){let e=`${n}/${r.modules.dir}`,t=r.modules.layoutsDirName,i=s[0]||``,o=[`home`,`root`,`main`,`index`];if(!i||o.includes(i.toLowerCase()))for(let n of o)await l(`${e}/${n}/${t}/${a}`);else await l(`${e}/${i}/${t}/${a}`)}let u=`${n}/src/layouts`;for(let e of c)await l(e===``?`${u}/${a}`:`${u}${e}/${a}`);return o}async function X(e,t){try{if((await i(`${e}/${t}`)).isFile())return`/${t}`}catch{}return null}async function Z(e,t,n){for(let r of n){let n=await X(e,`${t}${r}`);if(n)return n}if(!t.endsWith(`/index`))for(let r of n){let n=await X(e,`${t}/index${r}`);if(n)return n}return null}function Ke(e,t,n){let r=t.split(`/`).filter(Boolean),i=r[0]||``,a=[`home`,`root`,`main`,`index`],o,s;if(!i||a.includes(i.toLowerCase()))o=`home`,s=n;else{o=i;let e=r.slice(1);s=e.length>0?`/${e.join(`/`)}`:`/index`}return`${e.dir}/${o}/${e.pagesDirName}${s}`}async function Q(e,t,n){let r=e;r.endsWith(`/`)&&r!==`/`&&(r=r.slice(0,-1)),r===`/`&&(r=`/index`);let i=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mdx`,`.md`],a=n.config.root||process.cwd();if(t.modules){let n=await Z(a,Ke(t.modules,e,r),i);if(n)return n}return Z(a,`${t.pagesDir}${r}`,i)}function qe(e,t,n){if(globalThis.__avalonLayoutResolver)return;let r=e.EnhancedLayoutResolver,i=t.layoutsDir||`src/layouts`;globalThis.__avalonLayoutResolver=new r({baseDirectory:`${n}/${i}`,filePattern:`_layout.tsx`,excludeDirectories:[`node_modules`,`.git`,`dist`,`build`],enableWatching:!0,developmentMode:!1,enableCaching:!0,cacheTTL:60*1e3,maxCacheSize:100,enableStreaming:!0,enableErrorBoundaries:!0,enableMetrics:!1,enableDebugInfo:!1,modulesDir:t.modules?`${n}/${t.modules.dir}`:void 0,modulesLayoutsDirName:t.modules?.layoutsDirName})}async function Je(e,t,n,r){try{let{renderToString:r}=await H(t,n.core);return typeof e==`function`?r(e()):``}catch{return`<p>Loading page: ${$(r)}</p>`}}async function Ye(e,t,n,r,i,a,o){if(!e.renderToHtmlWithLayouts||!t.EnhancedLayoutResolver||!t.EnhancedLayoutResolverUtils)return null;try{qe(t,r,i.config.root||process.cwd());let s=`http://localhost${a}`,c={params:{},query:{},url:s,request:{method:`GET`,url:s,headers:new Headers}};return await e.renderToHtmlWithLayouts(n,globalThis.__avalonLayoutResolver,c,a,{title:o.title||`Avalon App`},void 0,{suppressWarnings:!0})}catch{return null}}async function Xe(e,t,n,r,i,a){try{B||=await i.ssrLoadModule(N(`src/render/ssr.ts`));let o=B;V||=await i.ssrLoadModule(N(`src/core/layout/enhanced-layout-resolver.ts`));let s=V,c={component:()=>typeof e==`function`?e():e,options:{title:a.title||`Avalon App`},frontmatter:t.frontmatter},l=await Ye(o,s,c,r,i,n,a);if(l!==null)return l;if(o.renderToHtml)return await o.renderToHtml(c,{title:a.title||`Avalon App`},void 0,{suppressWarnings:!0})}catch{}return null}async function Ze(e,t,n,r,i){let a=t.metadata||{},o=await Xe(e,t,n,r,i,a);if(o!==null)return o;let s=a.title||`Avalon App`,c=a.description||``,l=await Je(e,i,r,n);return`<!DOCTYPE html>
46
+ `+t.slice(r)}async function Y(e,t){let n=t.config.root||process.cwd(),r=globalThis.__avalonConfig,a=`_layout.tsx`,o=[],s=e.split(`/`).filter(Boolean),c=[``];for(let e=0;e<s.length;e++)c.push(`/${s.slice(0,e+1).join(`/`)}`);async function l(e){try{if((await i(e)).isFile()){let t=e.slice(n.length);o.includes(t)||o.push(t)}}catch{}}if(r?.layoutsDir&&await l(`${`${n}/${r.layoutsDir}`}/${a}`),r?.modules){let e=`${n}/${r.modules.dir}`,t=r.modules.layoutsDirName,i=s[0]||``,o=[`home`,`root`,`main`,`index`];if(!i||o.includes(i.toLowerCase()))for(let n of o)await l(`${e}/${n}/${t}/${a}`);else await l(`${e}/${i}/${t}/${a}`)}let u=`${n}/src/layouts`;for(let e of c)await l(e===``?`${u}/${a}`:`${u}${e}/${a}`);return o}async function X(e,t){try{if((await i(`${e}/${t}`)).isFile())return`/${t}`}catch{}return null}async function Z(e,t,n){for(let r of n){let n=await X(e,`${t}${r}`);if(n)return n}if(!t.endsWith(`/index`))for(let r of n){let n=await X(e,`${t}/index${r}`);if(n)return n}return null}function Ye(e,t,n){let r=t.split(`/`).filter(Boolean),i=r[0]||``,a=[`home`,`root`,`main`,`index`],o,s;if(!i||a.includes(i.toLowerCase()))o=`home`,s=n;else{o=i;let e=r.slice(1);s=e.length>0?`/${e.join(`/`)}`:`/index`}return`${e.dir}/${o}/${e.pagesDirName}${s}`}async function Q(e,t,n){let r=e;r.endsWith(`/`)&&r!==`/`&&(r=r.slice(0,-1)),r===`/`&&(r=`/index`);let i=[`.tsx`,`.ts`,`.jsx`,`.js`,`.mdx`,`.md`],a=n.config.root||process.cwd();if(t.modules){let n=await Z(a,Ye(t.modules,e,r),i);if(n)return n}return Z(a,`${t.pagesDir}${r}`,i)}function Xe(e,t,n){if(globalThis.__avalonLayoutResolver)return;let r=e.EnhancedLayoutResolver,i=t.layoutsDir||`src/layouts`;globalThis.__avalonLayoutResolver=new r({baseDirectory:`${n}/${i}`,filePattern:`_layout.tsx`,excludeDirectories:[`node_modules`,`.git`,`dist`,`build`],enableWatching:!0,developmentMode:!1,enableCaching:!0,cacheTTL:60*1e3,maxCacheSize:100,enableStreaming:!0,enableErrorBoundaries:!0,enableMetrics:!1,enableDebugInfo:!1,modulesDir:t.modules?`${n}/${t.modules.dir}`:void 0,modulesLayoutsDirName:t.modules?.layoutsDirName})}async function Ze(e,t,n,r){try{let{renderToString:r}=await H(t,n.core);return typeof e==`function`?r(e()):``}catch{return`<p>Loading page: ${$(r)}</p>`}}async function Qe(e,t,n,r,i,a,o){if(!e.renderToHtmlWithLayouts||!t.EnhancedLayoutResolver||!t.EnhancedLayoutResolverUtils)return null;try{Xe(t,r,i.config.root||process.cwd());let s=`http://localhost${a}`,c={params:{},query:{},url:s,request:{method:`GET`,url:s,headers:new Headers}};return await e.renderToHtmlWithLayouts(n,globalThis.__avalonLayoutResolver,c,a,{title:o.title||`Avalon App`},void 0,{suppressWarnings:!0})}catch{return null}}async function $e(e,t,n,r,i,a){try{B||=await i.ssrLoadModule(N(`src/render/ssr.ts`));let o=B;V||=await i.ssrLoadModule(N(`src/core/layout/enhanced-layout-resolver.ts`));let s=V,c={component:()=>typeof e==`function`?e():e,options:{title:a.title||`Avalon App`},frontmatter:t.frontmatter},l=await Qe(o,s,c,r,i,n,a);if(l!==null)return l;if(o.renderToHtml)return await o.renderToHtml(c,{title:a.title||`Avalon App`},void 0,{suppressWarnings:!0})}catch{}return null}async function et(e,t,n,r,i){let a=t.metadata||{},o=await $e(e,t,n,r,i,a);if(o!==null)return o;let s=a.title||`Avalon App`,c=a.description||``,l=await Ze(e,i,r,n);return`<!DOCTYPE html>
47
47
  <html lang="en">
48
48
  <head>
49
49
  <meta charset="utf-8">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useavalon/avalon",
3
- "version": "0.3.2-canary.11",
3
+ "version": "0.3.2-canary.13",
4
4
  "description": "Multi-framework islands architecture for the modern web",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -164,7 +164,7 @@
164
164
  },
165
165
  "dependencies": {
166
166
  "@mdx-js/rollup": "^3.0.0",
167
- "@useavalon/core": "^0.3.2-canary.11",
167
+ "@useavalon/core": "^0.3.2-canary.13",
168
168
  "h3": "^2.0.1-rc.16",
169
169
  "marked": "^17.0.4",
170
170
  "oxc-parser": "^0.120.0",