From b050ae28604ce6165216f6e9ec2cb3fa6b089100 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 9 Feb 2026 13:25:48 -0600 Subject: [PATCH 01/12] refactor: replace hardcoded Integration enum with auto-discovery registry Introduce a registry pattern that auto-discovers integrations from src/integrations/*/index.ts at startup, eliminating the need to edit shared files (constants.ts, config.ts, run-with-core.ts) when adding new SDK integrations. This enables parallel agent-team development for the multi-SDK expansion. Key changes: - Add src/lib/registry.ts with IntegrationRegistry (auto-discovery via fs.readdirSync + dynamic import) - Add src/lib/language-detection.ts for multi-language project detection - Migrate 5 existing JS integrations to src/integrations/{name}/ - Replace Integration enum with string type alias - Expand Bash tool permissions for Python, Ruby, PHP, Go, .NET, Elixir, and Kotlin package managers - Add language, stability, and priority fields to FrameworkConfig --- src/bin.ts | 1 - src/integrations/nextjs/index.ts | 106 ++++++++ src/integrations/nextjs/utils.ts | 66 +++++ src/integrations/react-router/index.ts | 113 ++++++++ src/integrations/react-router/utils.ts | 173 ++++++++++++ src/integrations/react/index.ts | 59 +++++ src/integrations/tanstack-start/index.ts | 61 +++++ src/integrations/vanilla-js/index.ts | 59 +++++ src/lib/agent-interface.ts | 45 +++- src/lib/config.ts | 110 ++------ src/lib/constants.ts | 54 ++-- src/lib/framework-config.ts | 22 +- src/lib/installer-core.events.spec.ts | 4 +- src/lib/installer-core.spec.ts | 3 +- src/lib/language-detection.ts | 125 +++++++++ src/lib/registry.ts | 153 +++++++++++ src/lib/run-with-core.ts | 109 ++++++-- src/nextjs/nextjs-installer-agent.ts | 113 +------- src/nextjs/utils.ts | 75 +----- .../react-router-installer-agent.ts | 126 +-------- src/react-router/utils.ts | 247 +----------------- src/react/react-installer-agent.ts | 61 +---- .../tanstack-start-installer-agent.ts | 66 +---- src/vanilla-js/vanilla-js-installer-agent.ts | 64 +---- 24 files changed, 1149 insertions(+), 866 deletions(-) create mode 100644 src/integrations/nextjs/index.ts create mode 100644 src/integrations/nextjs/utils.ts create mode 100644 src/integrations/react-router/index.ts create mode 100644 src/integrations/react-router/utils.ts create mode 100644 src/integrations/react/index.ts create mode 100644 src/integrations/tanstack-start/index.ts create mode 100644 src/integrations/vanilla-js/index.ts create mode 100644 src/lib/language-detection.ts create mode 100644 src/lib/registry.ts diff --git a/src/bin.ts b/src/bin.ts index 4d9f3ef..ce5fa01 100644 --- a/src/bin.ts +++ b/src/bin.ts @@ -124,7 +124,6 @@ const installerOptions = { }, integration: { describe: 'Integration to set up', - choices: ['nextjs', 'react', 'tanstack-start', 'react-router', 'vanilla-js'] as const, type: 'string' as const, }, 'force-install': { diff --git a/src/integrations/nextjs/index.ts b/src/integrations/nextjs/index.ts new file mode 100644 index 0000000..6e1bcdc --- /dev/null +++ b/src/integrations/nextjs/index.ts @@ -0,0 +1,106 @@ +/* Next.js integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { getPackageVersion } from '../../utils/package-json.js'; +import { getPackageDotJson } from '../../utils/clack-utils.js'; +import clack from '../../utils/clack.js'; +import chalk from 'chalk'; +import * as semver from 'semver'; +import { getNextJsRouter, getNextJsVersionBucket, getNextJsRouterName, NextJsRouter } from './utils.js'; + +const MINIMUM_NEXTJS_VERSION = '15.3.0'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Next.js', + integration: 'nextjs', + docsUrl: 'https://workos.com/docs/user-management/authkit/nextjs', + unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/nextjs', + skillName: 'workos-authkit-nextjs', + language: 'javascript', + stability: 'stable', + priority: 100, + gatherContext: async (options: InstallerOptions) => { + const router = await getNextJsRouter(options); + return { router }; + }, + }, + + detection: { + packageName: 'next', + packageDisplayName: 'Next.js', + getVersion: (packageJson: any) => getPackageVersion('next', packageJson), + getVersionBucket: getNextJsVersionBucket, + }, + + environment: { + uploadToHosting: true, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: (context: any) => { + const router = context.router as NextJsRouter; + return { + router: router === NextJsRouter.APP_ROUTER ? 'app' : 'pages', + }; + }, + }, + + prompts: { + getAdditionalContextLines: (context: any) => { + const router = context.router as NextJsRouter; + const routerType = router === NextJsRouter.APP_ROUTER ? 'app' : 'pages'; + return [`Router: ${routerType}`]; + }, + }, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: (context: any) => { + const router = context.router as NextJsRouter; + const routerName = getNextJsRouterName(router); + return [ + `Analyzed your Next.js project structure (${routerName})`, + `Created and configured WorkOS AuthKit`, + `Integrated authentication into your application`, + ]; + }, + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + // Check Next.js version - agent wizard requires >= 15.3.0 + const packageJson = await getPackageDotJson(options); + const nextVersion = getPackageVersion('next', packageJson); + + if (nextVersion) { + const coercedVersion = semver.coerce(nextVersion); + if (coercedVersion && semver.lt(coercedVersion, MINIMUM_NEXTJS_VERSION)) { + const docsUrl = config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl; + + clack.log.warn( + `Sorry: the installer can't help you with Next.js ${nextVersion}. Upgrade to Next.js ${MINIMUM_NEXTJS_VERSION} or later, or check out the manual setup guide.`, + ); + clack.log.info(`Setup Next.js manually: ${chalk.cyan(docsUrl)}`); + clack.outro('WorkOS AuthKit installer will see you next time!'); + return ''; + } + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/nextjs/utils.ts b/src/integrations/nextjs/utils.ts new file mode 100644 index 0000000..e627faa --- /dev/null +++ b/src/integrations/nextjs/utils.ts @@ -0,0 +1,66 @@ +import fg from 'fast-glob'; +import { abortIfCancelled } from '../../utils/clack-utils.js'; +import clack from '../../utils/clack.js'; +import { getVersionBucket } from '../../utils/semver.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { IGNORE_PATTERNS } from '../../lib/constants.js'; + +export function getNextJsVersionBucket(version: string | undefined): string { + return getVersionBucket(version, 11); +} + +export enum NextJsRouter { + APP_ROUTER = 'app-router', + PAGES_ROUTER = 'pages-router', +} + +export async function getNextJsRouter({ installDir }: Pick): Promise { + const pagesMatches = await fg('**/pages/_app.@(ts|tsx|js|jsx)', { + dot: true, + cwd: installDir, + ignore: IGNORE_PATTERNS, + }); + + const hasPagesDir = pagesMatches.length > 0; + + const appMatches = await fg('**/app/**/layout.@(ts|tsx|js|jsx)', { + dot: true, + cwd: installDir, + ignore: IGNORE_PATTERNS, + }); + + const hasAppDir = appMatches.length > 0; + + if (hasPagesDir && !hasAppDir) { + clack.log.info(`Detected ${getNextJsRouterName(NextJsRouter.PAGES_ROUTER)} 📃`); + return NextJsRouter.PAGES_ROUTER; + } + + if (hasAppDir && !hasPagesDir) { + clack.log.info(`Detected ${getNextJsRouterName(NextJsRouter.APP_ROUTER)} 📱`); + return NextJsRouter.APP_ROUTER; + } + + const result: NextJsRouter = await abortIfCancelled( + clack.select({ + message: 'What router are you using?', + options: [ + { + label: getNextJsRouterName(NextJsRouter.APP_ROUTER), + value: NextJsRouter.APP_ROUTER, + }, + { + label: getNextJsRouterName(NextJsRouter.PAGES_ROUTER), + value: NextJsRouter.PAGES_ROUTER, + }, + ], + }), + 'nextjs', + ); + + return result; +} + +export const getNextJsRouterName = (router: NextJsRouter) => { + return router === NextJsRouter.APP_ROUTER ? 'app router' : 'pages router'; +}; diff --git a/src/integrations/react-router/index.ts b/src/integrations/react-router/index.ts new file mode 100644 index 0000000..6423e3a --- /dev/null +++ b/src/integrations/react-router/index.ts @@ -0,0 +1,113 @@ +/* React Router integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { getPackageVersion } from '../../utils/package-json.js'; +import { getPackageDotJson } from '../../utils/clack-utils.js'; +import clack from '../../utils/clack.js'; +import chalk from 'chalk'; +import * as semver from 'semver'; +import { getReactRouterMode, getReactRouterModeName, getReactRouterVersionBucket, ReactRouterMode } from './utils.js'; + +const MINIMUM_REACT_ROUTER_VERSION = '6.0.0'; + +export const config: FrameworkConfig = { + metadata: { + name: 'React Router', + integration: 'react-router', + docsUrl: 'https://workos.com/docs/user-management/authkit/react-router', + unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/react-router', + skillName: 'workos-authkit-react-router', + language: 'javascript', + stability: 'stable', + priority: 80, + gatherContext: async (options: InstallerOptions) => { + const routerMode = await getReactRouterMode(options); + return { routerMode }; + }, + }, + + detection: { + packageName: 'react-router', + packageDisplayName: 'React Router', + getVersion: (packageJson: any) => getPackageVersion('react-router', packageJson), + getVersionBucket: getReactRouterVersionBucket, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: (context: any) => { + const routerMode = context.routerMode as ReactRouterMode; + return { routerMode: routerMode || 'unknown' }; + }, + }, + + prompts: { + getAdditionalContextLines: (context: any) => { + const routerMode = context.routerMode as ReactRouterMode; + const modeName = routerMode ? getReactRouterModeName(routerMode) : 'unknown'; + + const frameworkIdMap: Record = { + [ReactRouterMode.V6]: 'react-react-router-6', + [ReactRouterMode.V7_FRAMEWORK]: 'react-react-router-7-framework', + [ReactRouterMode.V7_DATA]: 'react-react-router-7-data', + [ReactRouterMode.V7_DECLARATIVE]: 'react-react-router-7-declarative', + }; + + const frameworkId = routerMode ? frameworkIdMap[routerMode] : ReactRouterMode.V7_FRAMEWORK; + + return [`Router mode: ${modeName}`, `Framework docs ID: ${frameworkId}`]; + }, + }, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: (context: any) => { + const routerMode = context.routerMode as ReactRouterMode; + const modeName = routerMode ? getReactRouterModeName(routerMode) : 'React Router'; + return [ + `Analyzed your React Router project structure (${modeName})`, + `Created and configured WorkOS AuthKit`, + `Integrated authentication into your application`, + ]; + }, + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const packageJson = await getPackageDotJson(options); + const reactRouterVersion = getPackageVersion('react-router', packageJson); + + if (reactRouterVersion) { + const coercedVersion = semver.coerce(reactRouterVersion); + if (coercedVersion && semver.lt(coercedVersion, MINIMUM_REACT_ROUTER_VERSION)) { + const docsUrl = config.metadata.unsupportedVersionDocsUrl ?? config.metadata.docsUrl; + + clack.log.warn( + `Sorry: the installer can't help you with React Router ${reactRouterVersion}. Upgrade to React Router ${MINIMUM_REACT_ROUTER_VERSION} or later, or check out the manual setup guide.`, + ); + clack.log.info(`Setup React Router manually: ${chalk.cyan(docsUrl)}`); + clack.outro('WorkOS AuthKit installer will see you next time!'); + return ''; + } + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/react-router/utils.ts b/src/integrations/react-router/utils.ts new file mode 100644 index 0000000..3680097 --- /dev/null +++ b/src/integrations/react-router/utils.ts @@ -0,0 +1,173 @@ +import { major } from 'semver'; +import fg from 'fast-glob'; +import { abortIfCancelled, getPackageDotJson } from '../../utils/clack-utils.js'; +import clack from '../../utils/clack.js'; +import { getVersionBucket } from '../../utils/semver.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { IGNORE_PATTERNS } from '../../lib/constants.js'; +import { getPackageVersion } from '../../utils/package-json.js'; +import chalk from 'chalk'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import * as semver from 'semver'; + +export enum ReactRouterMode { + V6 = 'v6', + V7_FRAMEWORK = 'v7-framework', + V7_DATA = 'v7-data', + V7_DECLARATIVE = 'v7-declarative', +} + +export function getReactRouterVersionBucket(version: string | undefined): string { + return getVersionBucket(version, 6); +} + +async function hasReactRouterConfig({ installDir }: Pick): Promise { + const configMatches = await fg('**/react-router.config.@(ts|js|tsx|jsx)', { + dot: true, + cwd: installDir, + ignore: IGNORE_PATTERNS, + }); + return configMatches.length > 0; +} + +async function hasCreateBrowserRouter({ installDir }: Pick): Promise { + const sourceFiles = await fg('**/*.@(ts|tsx|js|jsx)', { + dot: true, + cwd: installDir, + ignore: IGNORE_PATTERNS, + }); + + for (const file of sourceFiles) { + try { + const filePath = path.join(installDir, file); + const content = fs.readFileSync(filePath, 'utf-8'); + if (content.includes('createBrowserRouter')) { + return true; + } + } catch { + continue; + } + } + return false; +} + +async function hasDeclarativeRouter({ installDir }: Pick): Promise { + const sourceFiles = await fg('**/*.@(ts|tsx|js|jsx)', { + dot: true, + cwd: installDir, + ignore: IGNORE_PATTERNS, + }); + + for (const file of sourceFiles) { + try { + const filePath = path.join(installDir, file); + const content = fs.readFileSync(filePath, 'utf-8'); + if ( + content.includes(' { + const { installDir } = options; + + const packageJson = await getPackageDotJson(options); + const reactRouterVersion = + getPackageVersion('react-router-dom', packageJson) || getPackageVersion('react-router', packageJson); + + if (!reactRouterVersion) { + clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); + const result: ReactRouterMode = await abortIfCancelled( + clack.select({ + message: 'What React Router version and mode are you using?', + options: [ + { label: 'React Router v6', value: ReactRouterMode.V6 }, + { label: 'React Router v7 - Framework mode', value: ReactRouterMode.V7_FRAMEWORK }, + { label: 'React Router v7 - Data mode', value: ReactRouterMode.V7_DATA }, + { label: 'React Router v7 - Declarative mode', value: ReactRouterMode.V7_DECLARATIVE }, + ], + }), + 'react-router', + ); + return result; + } + + const coercedVersion = semver.coerce(reactRouterVersion); + const majorVersion = coercedVersion ? major(coercedVersion) : null; + + if (majorVersion === 6) { + clack.log.info('Detected React Router v6'); + return ReactRouterMode.V6; + } + + if (majorVersion === 7) { + const hasConfig = await hasReactRouterConfig({ installDir }); + if (hasConfig) { + clack.log.info('Detected React Router v7 - Framework mode'); + return ReactRouterMode.V7_FRAMEWORK; + } + + const hasDataMode = await hasCreateBrowserRouter({ installDir }); + if (hasDataMode) { + clack.log.info('Detected React Router v7 - Data mode'); + return ReactRouterMode.V7_DATA; + } + + const hasDeclarative = await hasDeclarativeRouter({ installDir }); + if (hasDeclarative) { + clack.log.info('Detected React Router v7 - Declarative mode'); + return ReactRouterMode.V7_DECLARATIVE; + } + + clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); + const result: ReactRouterMode = await abortIfCancelled( + clack.select({ + message: 'What React Router v7 mode are you using?', + options: [ + { label: 'Framework mode', value: ReactRouterMode.V7_FRAMEWORK }, + { label: 'Data mode', value: ReactRouterMode.V7_DATA }, + { label: 'Declarative mode', value: ReactRouterMode.V7_DECLARATIVE }, + ], + }), + 'react-router', + ); + return result; + } + + clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); + const result: ReactRouterMode = await abortIfCancelled( + clack.select({ + message: 'What React Router version and mode are you using?', + options: [ + { label: 'React Router v6', value: ReactRouterMode.V6 }, + { label: 'React Router v7 - Framework mode', value: ReactRouterMode.V7_FRAMEWORK }, + { label: 'React Router v7 - Data mode', value: ReactRouterMode.V7_DATA }, + { label: 'React Router v7 - Declarative mode', value: ReactRouterMode.V7_DECLARATIVE }, + ], + }), + 'react-router', + ); + return result; +} + +export function getReactRouterModeName(mode: ReactRouterMode): string { + switch (mode) { + case ReactRouterMode.V6: + return 'v6'; + case ReactRouterMode.V7_FRAMEWORK: + return 'v7 Framework mode'; + case ReactRouterMode.V7_DATA: + return 'v7 Data mode'; + case ReactRouterMode.V7_DECLARATIVE: + return 'v7 Declarative mode'; + } +} diff --git a/src/integrations/react/index.ts b/src/integrations/react/index.ts new file mode 100644 index 0000000..4cbebe2 --- /dev/null +++ b/src/integrations/react/index.ts @@ -0,0 +1,59 @@ +/* React SPA integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'React (SPA)', + integration: 'react', + docsUrl: 'https://workos.com/docs/user-management/authkit/react', + unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/react', + skillName: 'workos-authkit-react', + language: 'javascript', + stability: 'stable', + priority: 70, + }, + + detection: { + packageName: 'react', + packageDisplayName: 'React', + getVersion: (packageJson: any) => packageJson.dependencies?.react || packageJson.devDependencies?.react, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: false, + getEnvVars: (_apiKey: string, clientId: string) => ({ + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your React project structure', + 'Created and configured WorkOS AuthKit', + 'Integrated authentication into your application', + ], + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/tanstack-start/index.ts b/src/integrations/tanstack-start/index.ts new file mode 100644 index 0000000..046c0ff --- /dev/null +++ b/src/integrations/tanstack-start/index.ts @@ -0,0 +1,61 @@ +/* TanStack Start integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { getPackageVersion } from '../../utils/package-json.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'TanStack Start', + integration: 'tanstack-start', + docsUrl: 'https://workos.com/docs/user-management/authkit/tanstack-start', + unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/tanstack-start', + skillName: 'workos-authkit-tanstack-start', + language: 'javascript', + stability: 'stable', + priority: 90, + }, + + detection: { + packageName: '@tanstack/react-start', + packageDisplayName: 'TanStack Start', + getVersion: (packageJson: any) => getPackageVersion('@tanstack/react-start', packageJson), + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your TanStack Start project structure', + 'Created and configured WorkOS AuthKit', + 'Integrated authentication into your application', + ], + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/vanilla-js/index.ts b/src/integrations/vanilla-js/index.ts new file mode 100644 index 0000000..71b8b0c --- /dev/null +++ b/src/integrations/vanilla-js/index.ts @@ -0,0 +1,59 @@ +/* Vanilla JavaScript integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Vanilla JavaScript', + integration: 'vanilla-js', + docsUrl: 'https://workos.com/docs/user-management/authkit/javascript', + unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/javascript', + skillName: 'workos-authkit-vanilla-js', + language: 'javascript', + stability: 'stable', + priority: 10, // Lowest — fallback for any JS project + }, + + detection: { + packageName: 'workos', + packageDisplayName: 'Vanilla JavaScript', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: false, + getEnvVars: (_apiKey: string, clientId: string) => ({ + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Created WorkOS AuthKit integration', + 'Added authentication to your JavaScript application', + 'Set up login/logout functionality', + ], + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/lib/agent-interface.ts b/src/lib/agent-interface.ts index f7e7e10..54713d1 100644 --- a/src/lib/agent-interface.ts +++ b/src/lib/agent-interface.ts @@ -85,8 +85,26 @@ type AgentRunConfig = { /** * Package managers that can be used to run commands. + * Includes JS and non-JS ecosystem package managers for multi-SDK support. */ -const PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun', 'npx']; +const PACKAGE_MANAGERS = [ + // JavaScript + 'npm', 'pnpm', 'yarn', 'bun', 'npx', 'pnpx', 'bunx', + // Python + 'pip', 'pip3', 'poetry', 'uv', 'pipx', 'python', 'python3', + // Ruby + 'gem', 'bundle', 'bundler', 'ruby', + // PHP + 'composer', 'php', + // Go + 'go', + // .NET + 'dotnet', 'nuget', + // Elixir + 'mix', 'hex', 'elixir', + // Kotlin/Java + 'gradle', 'gradlew', './gradlew', 'mvn', +]; /** * Safe scripts/commands that can be run with any package manager. @@ -109,6 +127,31 @@ const SAFE_SCRIPTS = [ // Linting/formatting script names (actual tools are in LINTING_TOOLS) 'lint', 'format', + // Common cross-language commands + 'check', + 'test', + 'run', + 'serve', + 'dev', + 'start', + 'compile', + 'vet', + // Python-specific + 'manage.py', + 'pytest', + // Ruby-specific + 'rspec', + 'rake', + 'routes', + // PHP-specific + 'artisan', + 'phpunit', + // Elixir-specific + 'deps.get', + 'credo', + 'dialyzer', + // .NET-specific + 'restore', ]; /** diff --git a/src/lib/config.ts b/src/lib/config.ts index 08f7ab9..d013e95 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -1,9 +1,23 @@ +/** + * Integration detection configuration. + * + * This module previously held hardcoded INTEGRATION_CONFIG and INTEGRATION_ORDER. + * These are now provided by the auto-discovery registry (src/lib/registry.ts). + * + * This file is kept for backwards compatibility — functions that previously + * used INTEGRATION_CONFIG now delegate to the registry. + */ + import { getPackageDotJson } from '../utils/clack-utils.js'; import { hasPackageInstalled } from '../utils/package-json.js'; import type { InstallerOptions } from '../utils/types.js'; -import { Integration } from './constants.js'; +import type { Integration } from './constants.js'; -type IntegrationConfig = { +/** + * @deprecated Use registry.detectionOrder() + config.detection.detect() instead. + * This type is kept for any code that still references it. + */ +export type IntegrationConfig = { name: string; filterPatterns: string[]; ignorePatterns: string[]; @@ -15,98 +29,30 @@ type IntegrationConfig = { defaultChanges: string; }; -export const INTEGRATION_CONFIG = { - [Integration.nextjs]: { +/** + * Legacy detection configs for existing JS integrations. + * Used by clack-utils.ts for abort/cancel messages. + * New integrations do NOT need to be added here. + */ +export const INTEGRATION_CONFIG: Record = { + nextjs: { name: 'Next.js', - filterPatterns: ['**/*.{tsx,ts,jsx,js,mjs,cjs}'], - ignorePatterns: ['node_modules', 'dist', 'build', 'public', 'static', 'next-env.d.*'], - detect: async (options) => { - const packageJson = await getPackageDotJson(options); - return hasPackageInstalled('next', packageJson); - }, - generateFilesRules: '', - filterFilesRules: '', docsUrl: 'https://workos.com/docs/user-management/authkit/nextjs', - defaultChanges: - '• Installed @workos/authkit-nextjs package\n• Initialized WorkOS AuthKit with your credentials\n• Created authentication routes and callbacks\n• Added login/logout UI components', - nextSteps: - '• Customize the auth UI to match your app design\n• Add protected routes using withAuth() middleware\n• Access user session with getUser() in your components', }, - [Integration.react]: { + react: { name: 'React (SPA)', - filterPatterns: ['**/*.{tsx,ts,jsx,js}'], - ignorePatterns: ['node_modules', 'dist', 'build', 'public', 'static', 'assets'], - detect: async (options) => { - const packageJson = await getPackageDotJson(options); - // Detect React without routing frameworks - const hasReact = hasPackageInstalled('react', packageJson); - const hasNext = hasPackageInstalled('next', packageJson); - const hasReactRouter = hasPackageInstalled('react-router', packageJson); - const hasTanstack = hasPackageInstalled('@tanstack/react-start', packageJson); - return hasReact && !hasNext && !hasReactRouter && !hasTanstack; - }, - generateFilesRules: '', - filterFilesRules: '', docsUrl: 'https://workos.com/docs/user-management/authkit/react', - defaultChanges: - '• Installed @workos/authkit-react package\n• Added AuthKitProvider to wrap your app\n• Created login and callback components', - nextSteps: - '• Use useAuth() hook to access auth state in components\n• Add protected routes with conditional rendering\n• Customize auth UI to match your design', }, - [Integration.tanstackStart]: { + 'tanstack-start': { name: 'TanStack Start', - filterPatterns: ['**/*.{tsx,ts,jsx,js}'], - ignorePatterns: ['node_modules', 'dist', 'build', '.vinxi', '.output'], - detect: async (options) => { - const packageJson = await getPackageDotJson(options); - return hasPackageInstalled('@tanstack/react-start', packageJson); - }, - generateFilesRules: '', - filterFilesRules: '', docsUrl: 'https://workos.com/docs/user-management/authkit/tanstack-start', - defaultChanges: - '• Installed WorkOS AuthKit SDK package\n• Added AuthKit middleware and routes\n• Created authentication components', - nextSteps: - '• Use useAuth() hook to access auth state\n• Add protected routes with authentication checks\n• Customize auth UI to match your app', }, - [Integration.reactRouter]: { + 'react-router': { name: 'React Router', - filterPatterns: ['**/*.{tsx,ts,jsx,js}'], - ignorePatterns: ['node_modules', 'dist', 'build', 'public', 'static', 'assets'], - detect: async (options) => { - const packageJson = await getPackageDotJson(options); - return hasPackageInstalled('react-router', packageJson); - }, - generateFilesRules: '', - filterFilesRules: '', docsUrl: 'https://workos.com/docs/user-management/authkit/react-router', - defaultChanges: - '• Installed @workos/authkit-react-router package\n• Added AuthKitProvider with React Router integration\n• Created auth routes and loaders', - nextSteps: - '• Use useAuth() hook in your components\n• Add protected routes with loader functions\n• Customize auth flow to match your needs', }, - [Integration.vanillaJs]: { + 'vanilla-js': { name: 'Vanilla JavaScript', - filterPatterns: ['**/*.{html,js,ts}'], - ignorePatterns: ['node_modules', 'dist', 'build'], - detect: async (options) => { - // Fallback: if no framework detected, assume vanilla JS - return true; - }, - generateFilesRules: '', - filterFilesRules: '', docsUrl: 'https://workos.com/docs/user-management/authkit/javascript', - defaultChanges: - '• Installed @workos/authkit-js package (or added CDN script)\n• Created auth initialization and callback handling\n• Added login button and auth state display', - nextSteps: - '• Integrate auth state into your existing UI\n• Add logout functionality where needed\n• Protect pages that require authentication', }, -} as const satisfies Record; - -export const INTEGRATION_ORDER = [ - Integration.nextjs, - Integration.tanstackStart, - Integration.reactRouter, - Integration.react, - Integration.vanillaJs, // fallback -] as const; +}; diff --git a/src/lib/constants.ts b/src/lib/constants.ts index e083a15..cc05e97 100644 --- a/src/lib/constants.ts +++ b/src/lib/constants.ts @@ -1,41 +1,23 @@ import { getConfig } from './settings.js'; -export enum Integration { - nextjs = 'nextjs', - react = 'react', - tanstackStart = 'tanstack-start', - reactRouter = 'react-router', - vanillaJs = 'vanilla-js', -} - -export function getIntegrationDescription(type: string): string { - switch (type) { - case Integration.nextjs: - return 'Next.js'; - case Integration.react: - return 'React (SPA)'; - case Integration.tanstackStart: - return 'TanStack Start'; - case Integration.reactRouter: - return 'React Router'; - case Integration.vanillaJs: - return 'Vanilla JavaScript'; - default: - throw new Error(`Unknown integration ${type}`); - } -} - -type IntegrationChoice = { - name: string; - value: string; -}; +/** + * Integration identifier type. + * No longer an enum — each integration self-registers via the auto-discovery registry. + * The string value matches the integration directory name (e.g., 'nextjs', 'react-router'). + */ +export type Integration = string; -export function getIntegrationChoices(): IntegrationChoice[] { - return Object.keys(Integration).map((type: string) => ({ - name: getIntegrationDescription(type), - value: type, - })); -} +/** + * Well-known integration names for backwards compatibility. + * New integrations do NOT need to be added here — they're auto-discovered. + */ +export const KNOWN_INTEGRATIONS = { + nextjs: 'nextjs', + react: 'react', + tanstackStart: 'tanstack-start', + reactRouter: 'react-router', + vanillaJs: 'vanilla-js', +} as const; export interface Args { debug: boolean; @@ -57,7 +39,7 @@ export const OAUTH_PORT = settings.legacy.oauthPort; /** * Common glob patterns to ignore when searching for files. - * Used by both Next.js and React Router integrations. + * Used by multiple integrations. */ export const IGNORE_PATTERNS: string[] = [ '**/node_modules/**', diff --git a/src/lib/framework-config.ts b/src/lib/framework-config.ts index 26f7815..bdb33fb 100644 --- a/src/lib/framework-config.ts +++ b/src/lib/framework-config.ts @@ -1,5 +1,5 @@ -import type { Integration } from './constants.js'; import type { InstallerOptions } from '../utils/types.js'; +import type { Language } from './language-detection.js'; /** * Configuration interface for framework-specific agent integrations. @@ -21,8 +21,8 @@ export interface FrameworkMetadata { /** Display name (e.g., "Next.js", "React") */ name: string; - /** Integration type from constants */ - integration: Integration; + /** Integration identifier (e.g., 'nextjs', 'python'). String, not enum — auto-discovered from registry. */ + integration: string; /** URL to framework-specific WorkOS AuthKit docs */ docsUrl: string; @@ -43,9 +43,23 @@ export interface FrameworkMetadata { /** * Name of the framework-specific skill for agent integration. * Skills are located in .claude/skills/{skillName}/SKILL.md - * Will be populated per-framework in Phase 3. */ skillName?: string; + + /** Language ecosystem this integration belongs to */ + language: Language; + + /** Stability tier: 'stable' for tested integrations, 'experimental' for new ones */ + stability: 'stable' | 'experimental'; + + /** Detection priority — higher numbers are checked first */ + priority: number; + + /** Default package manager command (e.g., 'pip', 'gem', 'go'). Optional for JS integrations. */ + packageManager?: string; + + /** Primary manifest file (e.g., 'pyproject.toml', 'Gemfile'). Optional for JS integrations. */ + manifestFile?: string; } /** diff --git a/src/lib/installer-core.events.spec.ts b/src/lib/installer-core.events.spec.ts index 0941166..27b7da7 100644 --- a/src/lib/installer-core.events.spec.ts +++ b/src/lib/installer-core.events.spec.ts @@ -27,7 +27,7 @@ import { installerMachine } from './installer-core.js'; import { createEventCapture, compareEventSequences, filterDeterministicEvents } from './installer-core.test-utils.js'; import type { InstallerOptions } from '../utils/types.js'; import type { DetectionOutput, GitCheckOutput, AgentOutput, InstallerMachineContext } from './installer-core.types.js'; -import { Integration } from './constants.js'; + /** * Creates mock actor implementations for testing. @@ -39,7 +39,7 @@ function createMockActors() { return { checkAuthentication: fromPromise(async () => true), detectIntegration: fromPromise(async () => ({ - integration: Integration.nextjs, + integration: 'nextjs', })), checkGitStatus: fromPromise(async () => ({ isClean: true, diff --git a/src/lib/installer-core.spec.ts b/src/lib/installer-core.spec.ts index 6a402c5..90dfe97 100644 --- a/src/lib/installer-core.spec.ts +++ b/src/lib/installer-core.spec.ts @@ -2,7 +2,6 @@ import { describe, it, expect } from 'vitest'; import { createActor, fromPromise } from 'xstate'; import { installerMachine } from './installer-core.js'; import { createInstallerEventEmitter } from './events.js'; -import { Integration } from './constants.js'; import type { InstallerOptions } from '../utils/types.js'; import type { DetectionOutput, @@ -16,7 +15,7 @@ import type { const baseMockActors = { checkAuthentication: fromPromise(async () => true), detectIntegration: fromPromise(async () => ({ - integration: Integration.nextjs, + integration: 'nextjs', })), checkGitStatus: fromPromise(async () => ({ isClean: true, diff --git a/src/lib/language-detection.ts b/src/lib/language-detection.ts new file mode 100644 index 0000000..96c6da8 --- /dev/null +++ b/src/lib/language-detection.ts @@ -0,0 +1,125 @@ +import { existsSync, readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; + +/** + * Supported programming languages for framework detection. + */ +export type Language = 'javascript' | 'python' | 'ruby' | 'php' | 'go' | 'kotlin' | 'dotnet' | 'elixir'; + +export interface LanguageSignal { + language: Language; + confidence: number; // 0-1 + manifestFile: string; +} + +export interface LanguageDetectionResult { + primary: Language; + signals: LanguageSignal[]; + ambiguous: boolean; +} + +function fileExists(cwd: string, filename: string): { found: boolean; manifestFile: string } { + const fullPath = join(cwd, filename); + return { found: existsSync(fullPath), manifestFile: filename }; +} + +function globExists(cwd: string, pattern: string): { found: boolean; manifestFile: string } { + // Simple glob for *.ext patterns in the root directory + const ext = pattern.replace('*', ''); + try { + const files = readdirSync(cwd); + const match = files.find((f) => f.endsWith(ext)); + return { found: !!match, manifestFile: match || pattern }; + } catch { + return { found: false, manifestFile: pattern }; + } +} + +function detectPython(cwd: string): { found: boolean; manifestFile: string } { + for (const file of ['pyproject.toml', 'requirements.txt', 'setup.py', 'Pipfile']) { + if (existsSync(join(cwd, file))) { + return { found: true, manifestFile: file }; + } + } + return { found: false, manifestFile: 'pyproject.toml' }; +} + +function detectKotlin(cwd: string): { found: boolean; manifestFile: string } { + const ktsPath = join(cwd, 'build.gradle.kts'); + if (existsSync(ktsPath)) { + try { + const content = readFileSync(ktsPath, 'utf-8'); + if (/org\.jetbrains\.kotlin/.test(content) || /kotlin\(/.test(content)) { + return { found: true, manifestFile: 'build.gradle.kts' }; + } + } catch { + // Can't read file + } + } + + // Also check build.gradle (Groovy DSL) + const gradlePath = join(cwd, 'build.gradle'); + if (existsSync(gradlePath)) { + try { + const content = readFileSync(gradlePath, 'utf-8'); + if (/kotlin/.test(content)) { + return { found: true, manifestFile: 'build.gradle' }; + } + } catch { + // Can't read file + } + } + + return { found: false, manifestFile: 'build.gradle.kts' }; +} + +/** + * Language detectors ordered by specificity. + * More specific languages are checked first. + * JavaScript is last because many non-JS projects also have package.json. + */ +const LANGUAGE_DETECTORS: Array<{ + language: Language; + detect: (cwd: string) => { found: boolean; manifestFile: string }; +}> = [ + { language: 'elixir', detect: (cwd) => fileExists(cwd, 'mix.exs') }, + { language: 'go', detect: (cwd) => fileExists(cwd, 'go.mod') }, + { language: 'dotnet', detect: (cwd) => globExists(cwd, '*.csproj') }, + { language: 'kotlin', detect: detectKotlin }, + { language: 'ruby', detect: (cwd) => fileExists(cwd, 'Gemfile') }, + { language: 'php', detect: (cwd) => fileExists(cwd, 'composer.json') }, + { language: 'python', detect: detectPython }, + { language: 'javascript', detect: (cwd) => fileExists(cwd, 'package.json') }, +]; + +/** + * Detect the primary programming language of a project. + * Runs all detectors and returns the highest-priority match. + * Sets `ambiguous: true` if multiple non-JS languages are detected. + */ +export function detectLanguage(cwd: string): LanguageDetectionResult | undefined { + const signals: LanguageSignal[] = []; + + for (const detector of LANGUAGE_DETECTORS) { + const result = detector.detect(cwd); + if (result.found) { + signals.push({ + language: detector.language, + confidence: 1.0, + manifestFile: result.manifestFile, + }); + } + } + + if (signals.length === 0) { + return undefined; + } + + const primary = signals[0].language; + + // Ambiguous if multiple non-JS languages detected + const nonJsSignals = signals.filter((s) => s.language !== 'javascript'); + const ambiguous = nonJsSignals.length > 1; + + return { primary, signals, ambiguous }; +} diff --git a/src/lib/registry.ts b/src/lib/registry.ts new file mode 100644 index 0000000..4bc2d79 --- /dev/null +++ b/src/lib/registry.ts @@ -0,0 +1,153 @@ +import { readdirSync, existsSync } from 'node:fs'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import type { FrameworkConfig } from './framework-config.js'; +import type { Language } from './language-detection.js'; +import type { InstallerOptions } from '../utils/types.js'; + +/** + * Standard exports from an integration module. + * Each `src/integrations/{name}/index.ts` must export these. + */ +export interface IntegrationModule { + config: FrameworkConfig; + run: (options: InstallerOptions) => Promise; +} + +/** + * Registry that provides lookup, detection, and enumeration of integrations. + */ +export interface IntegrationRegistry { + /** All registered integrations */ + all(): FrameworkConfig[]; + + /** Get config by integration name */ + get(name: string): IntegrationModule | undefined; + + /** Get integrations for a specific language, ordered by priority */ + forLanguage(language: Language): FrameworkConfig[]; + + /** Get integration names for CLI choices */ + choices(): Array<{ name: string; value: string }>; + + /** Detection order: all integrations sorted by priority (higher = checked first) */ + detectionOrder(): FrameworkConfig[]; +} + +/** + * Build the integration registry by discovering all integration modules. + * Scans `src/integrations/` (or `dist/integrations/` at runtime) for directories + * with an index.js/index.ts file and dynamically imports them. + */ +export async function buildRegistry(): Promise { + const modules = new Map(); + + // Resolve the integrations directory relative to this file + // In dev: src/lib/registry.ts -> src/integrations/ + // In dist: dist/lib/registry.js -> dist/integrations/ + const __filename = fileURLToPath(import.meta.url); + const __dirname = dirname(__filename); + const integrationsDir = join(__dirname, '..', 'integrations'); + + if (!existsSync(integrationsDir)) { + throw new Error( + `No integrations directory found at ${integrationsDir}. Is the build corrupt?`, + ); + } + + const entries = readdirSync(integrationsDir, { withFileTypes: true }); + const dirs = entries.filter((e) => e.isDirectory()).map((e) => e.name); + + if (dirs.length === 0) { + throw new Error( + 'No integrations found. Is the build corrupt?', + ); + } + + for (const dir of dirs) { + // Skip directories starting with _ (convention for internal files like _manifest.ts) + if (dir.startsWith('_')) continue; + + const indexPath = join(integrationsDir, dir, 'index.js'); + const indexTsPath = join(integrationsDir, dir, 'index.ts'); + + if (!existsSync(indexPath) && !existsSync(indexTsPath)) { + // Skip directories without an index file (not an integration) + continue; + } + + try { + const mod = (await import(join(integrationsDir, dir, 'index.js'))) as IntegrationModule; + + if (!mod.config || !mod.run) { + console.warn(`Integration ${dir} missing 'config' or 'run' export, skipping`); + continue; + } + + const name = mod.config.metadata.integration; + + if (modules.has(name)) { + throw new Error( + `Duplicate integration name: '${name}' (found in both existing and '${dir}/')`, + ); + } + + modules.set(name, mod); + } catch (err) { + if (err instanceof Error && err.message.startsWith('Duplicate integration name')) { + throw err; // Re-throw duplicate name errors + } + console.warn(`Failed to load integration from ${dir}/: ${err}`); + } + } + + // Build sorted config array (by priority, descending) + const sortedConfigs = Array.from(modules.values()) + .map((m) => m.config) + .sort((a, b) => b.metadata.priority - a.metadata.priority); + + return { + all() { + return sortedConfigs; + }, + + get(name: string) { + return modules.get(name); + }, + + forLanguage(language: Language) { + return sortedConfigs.filter((c) => c.metadata.language === language); + }, + + choices() { + return sortedConfigs.map((c) => ({ + name: c.metadata.name, + value: c.metadata.integration, + })); + }, + + detectionOrder() { + return sortedConfigs; + }, + }; +} + +// Singleton cache +let _registry: IntegrationRegistry | null = null; + +/** + * Get the integration registry (builds once, caches thereafter). + */ +export async function getRegistry(): Promise { + if (!_registry) { + _registry = await buildRegistry(); + } + return _registry; +} + +/** + * Reset the registry cache. Used in tests. + */ +export function resetRegistry(): void { + _registry = null; +} diff --git a/src/lib/run-with-core.ts b/src/lib/run-with-core.ts index 89350a8..286050f 100644 --- a/src/lib/run-with-core.ts +++ b/src/lib/run-with-core.ts @@ -15,7 +15,7 @@ import type { AgentOutput, BranchCheckOutput, } from './installer-core.types.js'; -import { Integration } from './constants.js'; +import type { Integration } from './constants.js'; import { parseEnvFile } from '../utils/env-parser.js'; import { enableDebugLogs, initLogFile, logInfo, logError } from '../utils/debug.js'; @@ -46,31 +46,18 @@ import { generateCommitMessage as generateCommitMessageAi, generatePrDescription as generatePrDescriptionAi, } from './ai-content.js'; -import { INTEGRATION_CONFIG, INTEGRATION_ORDER } from './config.js'; import { autoConfigureWorkOSEnvironment } from './workos-management.js'; import { detectPort, getCallbackPath } from './port-detection.js'; import { writeEnvLocal } from './env-writer.js'; -import { runNextjsInstallerAgent } from '../nextjs/nextjs-installer-agent.js'; -import { runReactInstallerAgent } from '../react/react-installer-agent.js'; -import { runReactRouterInstallerAgent } from '../react-router/react-router-installer-agent.js'; -import { runTanstackStartInstallerAgent } from '../tanstack-start/tanstack-start-installer-agent.js'; -import { runVanillaJsInstallerAgent } from '../vanilla-js/vanilla-js-installer-agent.js'; +import { getRegistry } from './registry.js'; async function runIntegrationInstallerFn(integration: Integration, options: InstallerOptions): Promise { - switch (integration) { - case Integration.nextjs: - return runNextjsInstallerAgent(options); - case Integration.react: - return runReactInstallerAgent(options); - case Integration.reactRouter: - return runReactRouterInstallerAgent(options); - case Integration.tanstackStart: - return runTanstackStartInstallerAgent(options); - case Integration.vanillaJs: - return runVanillaJsInstallerAgent(options); - default: - throw new Error(`Unknown integration: ${integration}`); + const registry = await getRegistry(); + const mod = registry.get(integration); + if (!mod) { + throw new Error(`Unknown integration: ${integration}`); } + return mod.run(options); } function readExistingCredentials(installDir: string): { apiKey?: string; clientId?: string } { @@ -92,19 +79,85 @@ function readExistingCredentials(installDir: string): { apiKey?: string; clientI } async function detectIntegrationFn(options: Pick): Promise { - const integrationConfigs = Object.entries(INTEGRATION_CONFIG).sort( - ([a], [b]) => INTEGRATION_ORDER.indexOf(a as Integration) - INTEGRATION_ORDER.indexOf(b as Integration), - ); + const registry = await getRegistry(); + const configs = registry.detectionOrder(); - for (const [integration, config] of integrationConfigs) { - const detected = await config.detect(options); + for (const config of configs) { + // Use the detect function from INTEGRATION_CONFIG in config.ts for JS integrations, + // or fall back to checking if the framework package is installed + const detected = await detectSingleIntegration(config.metadata.integration, options); if (detected) { - return integration as Integration; + return config.metadata.integration; } } return undefined; } +/** + * Detect if a single integration matches the project. + * Uses package.json detection for JS integrations, manifest files for others. + */ +async function detectSingleIntegration( + integration: string, + options: Pick, +): Promise { + const { getPackageDotJson } = await import('../utils/clack-utils.js'); + const { hasPackageInstalled } = await import('../utils/package-json.js'); + const { existsSync } = await import('node:fs'); + const { join } = await import('node:path'); + + const registry = await getRegistry(); + const mod = registry.get(integration); + if (!mod) return false; + + const config = mod.config; + + // For JS integrations, check package.json + if (config.metadata.language === 'javascript') { + const packageJson = await getPackageDotJson(options); + + switch (integration) { + case 'nextjs': + return hasPackageInstalled('next', packageJson); + case 'tanstack-start': + return hasPackageInstalled('@tanstack/react-start', packageJson); + case 'react-router': + return hasPackageInstalled('react-router', packageJson); + case 'react': { + const hasReact = hasPackageInstalled('react', packageJson); + const hasNext = hasPackageInstalled('next', packageJson); + const hasReactRouter = hasPackageInstalled('react-router', packageJson); + const hasTanstack = hasPackageInstalled('@tanstack/react-start', packageJson); + const hasSvelteKit = hasPackageInstalled('@sveltejs/kit', packageJson); + return hasReact && !hasNext && !hasReactRouter && !hasTanstack && !hasSvelteKit; + } + case 'sveltekit': + return hasPackageInstalled('@sveltejs/kit', packageJson); + case 'node': { + const hasExpress = hasPackageInstalled('express', packageJson); + const hasFrontend = + hasPackageInstalled('next', packageJson) || + hasPackageInstalled('@sveltejs/kit', packageJson) || + hasPackageInstalled('react', packageJson) || + hasPackageInstalled('@tanstack/react-start', packageJson); + return hasExpress && !hasFrontend; + } + case 'vanilla-js': + return true; // Fallback + default: + // Unknown JS integration — try package name detection + return hasPackageInstalled(config.detection.packageName, packageJson); + } + } + + // For non-JS integrations, check manifest files + if (config.metadata.manifestFile) { + return existsSync(join(options.installDir, config.metadata.manifestFile)); + } + + return false; +} + export async function runWithCore(options: InstallerOptions): Promise { // Initialize debug/logging early so we capture all failures initLogFile(); @@ -188,7 +241,7 @@ export async function runWithCore(options: InstallerOptions): Promise { const callbackPath = getCallbackPath(integration); const redirectUri = installerOptions.redirectUri || `http://localhost:${port}${callbackPath}`; - const requiresApiKey = [Integration.nextjs, Integration.tanstackStart, Integration.reactRouter].includes( + const requiresApiKey = ['nextjs', 'tanstack-start', 'react-router'].includes( integration, ); if (credentials.apiKey && requiresApiKey) { @@ -199,7 +252,7 @@ export async function runWithCore(options: InstallerOptions): Promise { } const redirectUriKey = - integration === Integration.nextjs ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI'; + integration === 'nextjs' ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI'; writeEnvLocal(installerOptions.installDir, { ...(credentials.apiKey ? { WORKOS_API_KEY: credentials.apiKey } : {}), diff --git a/src/nextjs/nextjs-installer-agent.ts b/src/nextjs/nextjs-installer-agent.ts index 0313374..5cc561c 100644 --- a/src/nextjs/nextjs-installer-agent.ts +++ b/src/nextjs/nextjs-installer-agent.ts @@ -1,112 +1,5 @@ -/* Simplified Next.js wizard using Claude Agent SDK with WorkOS MCP */ -import type { InstallerOptions } from '../utils/types.js'; -import { enableDebugLogs } from '../utils/debug.js'; -import { runAgentInstaller } from '../lib/agent-runner.js'; -import { Integration } from '../lib/constants.js'; -import { getPackageVersion } from '../utils/package-json.js'; -import { getPackageDotJson } from '../utils/clack-utils.js'; -import clack from '../utils/clack.js'; -import chalk from 'chalk'; -import * as semver from 'semver'; -import { getNextJsRouter, getNextJsVersionBucket, getNextJsRouterName, NextJsRouter } from './utils.js'; - /** - * Next.js framework configuration for the universal agent runner. + * @deprecated Import from 'src/integrations/nextjs/index.js' instead. + * This file is kept for backwards compatibility. */ -const MINIMUM_NEXTJS_VERSION = '15.3.0'; - -const NEXTJS_AGENT_CONFIG = { - metadata: { - name: 'Next.js', - integration: Integration.nextjs, - docsUrl: 'https://workos.com/docs/user-management/authkit/nextjs', - unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/nextjs', - skillName: 'workos-authkit-nextjs', - gatherContext: async (options: InstallerOptions) => { - const router = await getNextJsRouter(options); - return { router }; - }, - }, - - detection: { - packageName: 'next', - packageDisplayName: 'Next.js', - getVersion: (packageJson: any) => getPackageVersion('next', packageJson), - getVersionBucket: getNextJsVersionBucket, - }, - - environment: { - uploadToHosting: true, - requiresApiKey: true, // Server-side framework - getEnvVars: (apiKey: string, clientId: string) => ({ - WORKOS_API_KEY: apiKey, - WORKOS_CLIENT_ID: clientId, - }), - }, - - analytics: { - getTags: (context: any) => { - const router = context.router as NextJsRouter; - return { - router: router === NextJsRouter.APP_ROUTER ? 'app' : 'pages', - }; - }, - }, - - prompts: { - getAdditionalContextLines: (context: any) => { - const router = context.router as NextJsRouter; - const routerType = router === NextJsRouter.APP_ROUTER ? 'app' : 'pages'; - return [`Router: ${routerType}`]; - }, - }, - - ui: { - successMessage: 'WorkOS AuthKit integration complete', - getOutroChanges: (context: any) => { - const router = context.router as NextJsRouter; - const routerName = getNextJsRouterName(router); - return [ - `Analyzed your Next.js project structure (${routerName})`, - `Created and configured WorkOS AuthKit`, - `Integrated authentication into your application`, - ]; - }, - getOutroNextSteps: () => { - return [ - 'Start your development server to test authentication', - 'Visit the WorkOS Dashboard to manage users and settings', - ]; - }, - }, -}; - -/** - * Next.js wizard powered by the universal agent runner. - * @returns Summary of what was done, or empty string if version check fails - */ -export async function runNextjsInstallerAgent(options: InstallerOptions): Promise { - if (options.debug) { - enableDebugLogs(); - } - - // Check Next.js version - agent wizard requires >= 15.3.0 - const packageJson = await getPackageDotJson(options); - const nextVersion = getPackageVersion('next', packageJson); - - if (nextVersion) { - const coercedVersion = semver.coerce(nextVersion); - if (coercedVersion && semver.lt(coercedVersion, MINIMUM_NEXTJS_VERSION)) { - const docsUrl = NEXTJS_AGENT_CONFIG.metadata.unsupportedVersionDocsUrl ?? NEXTJS_AGENT_CONFIG.metadata.docsUrl; - - clack.log.warn( - `Sorry: the installer can't help you with Next.js ${nextVersion}. Upgrade to Next.js ${MINIMUM_NEXTJS_VERSION} or later, or check out the manual setup guide.`, - ); - clack.log.info(`Setup Next.js manually: ${chalk.cyan(docsUrl)}`); - clack.outro('WorkOS AuthKit installer will see you next time!'); - return ''; - } - } - - return runAgentInstaller(NEXTJS_AGENT_CONFIG, options); -} +export { run as runNextjsInstallerAgent, config as NEXTJS_AGENT_CONFIG } from '../integrations/nextjs/index.js'; diff --git a/src/nextjs/utils.ts b/src/nextjs/utils.ts index d84d730..c68ecb2 100644 --- a/src/nextjs/utils.ts +++ b/src/nextjs/utils.ts @@ -1,66 +1,9 @@ -import fg from 'fast-glob'; -import { abortIfCancelled } from '../utils/clack-utils.js'; -import clack from '../utils/clack.js'; -import { getVersionBucket } from '../utils/semver.js'; -import type { InstallerOptions } from '../utils/types.js'; -import { IGNORE_PATTERNS, Integration } from '../lib/constants.js'; - -export function getNextJsVersionBucket(version: string | undefined): string { - return getVersionBucket(version, 11); -} - -export enum NextJsRouter { - APP_ROUTER = 'app-router', - PAGES_ROUTER = 'pages-router', -} - -export async function getNextJsRouter({ installDir }: Pick): Promise { - const pagesMatches = await fg('**/pages/_app.@(ts|tsx|js|jsx)', { - dot: true, - cwd: installDir, - ignore: IGNORE_PATTERNS, - }); - - const hasPagesDir = pagesMatches.length > 0; - - const appMatches = await fg('**/app/**/layout.@(ts|tsx|js|jsx)', { - dot: true, - cwd: installDir, - ignore: IGNORE_PATTERNS, - }); - - const hasAppDir = appMatches.length > 0; - - if (hasPagesDir && !hasAppDir) { - clack.log.info(`Detected ${getNextJsRouterName(NextJsRouter.PAGES_ROUTER)} 📃`); - return NextJsRouter.PAGES_ROUTER; - } - - if (hasAppDir && !hasPagesDir) { - clack.log.info(`Detected ${getNextJsRouterName(NextJsRouter.APP_ROUTER)} 📱`); - return NextJsRouter.APP_ROUTER; - } - - const result: NextJsRouter = await abortIfCancelled( - clack.select({ - message: 'What router are you using?', - options: [ - { - label: getNextJsRouterName(NextJsRouter.APP_ROUTER), - value: NextJsRouter.APP_ROUTER, - }, - { - label: getNextJsRouterName(NextJsRouter.PAGES_ROUTER), - value: NextJsRouter.PAGES_ROUTER, - }, - ], - }), - Integration.nextjs, - ); - - return result; -} - -export const getNextJsRouterName = (router: NextJsRouter) => { - return router === NextJsRouter.APP_ROUTER ? 'app router' : 'pages router'; -}; +/** + * @deprecated Import from 'src/integrations/nextjs/utils.js' instead. + */ +export { + getNextJsVersionBucket, + NextJsRouter, + getNextJsRouter, + getNextJsRouterName, +} from '../integrations/nextjs/utils.js'; diff --git a/src/react-router/react-router-installer-agent.ts b/src/react-router/react-router-installer-agent.ts index 29d0b9c..c507b6b 100644 --- a/src/react-router/react-router-installer-agent.ts +++ b/src/react-router/react-router-installer-agent.ts @@ -1,123 +1,7 @@ -/* React Router wizard using Claude Agent SDK with WorkOS MCP */ -import type { InstallerOptions } from '../utils/types.js'; -import type { FrameworkConfig } from '../lib/framework-config.js'; -import { enableDebugLogs } from '../utils/debug.js'; -import { runAgentInstaller } from '../lib/agent-runner.js'; -import { Integration } from '../lib/constants.js'; -import { getPackageVersion } from '../utils/package-json.js'; -import { getPackageDotJson } from '../utils/clack-utils.js'; -import clack from '../utils/clack.js'; -import chalk from 'chalk'; -import * as semver from 'semver'; -import { getReactRouterMode, getReactRouterModeName, getReactRouterVersionBucket, ReactRouterMode } from './utils.js'; - /** - * React Router framework configuration for the universal agent runner. + * @deprecated Import from 'src/integrations/react-router/index.js' instead. */ -const MINIMUM_REACT_ROUTER_VERSION = '6.0.0'; - -const REACT_ROUTER_AGENT_CONFIG: FrameworkConfig = { - metadata: { - name: 'React Router', - integration: Integration.reactRouter, - docsUrl: 'https://workos.com/docs/user-management/authkit/react-router', - unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/react-router', - skillName: 'workos-authkit-react-router', - gatherContext: async (options: InstallerOptions) => { - const routerMode = await getReactRouterMode(options); - return { routerMode }; - }, - }, - - detection: { - packageName: 'react-router', - packageDisplayName: 'React Router', - getVersion: (packageJson: any) => getPackageVersion('react-router', packageJson), - getVersionBucket: getReactRouterVersionBucket, - }, - - environment: { - uploadToHosting: false, - requiresApiKey: true, // Can do SSR - getEnvVars: (apiKey: string, clientId: string) => ({ - WORKOS_API_KEY: apiKey, - WORKOS_CLIENT_ID: clientId, - }), - }, - - analytics: { - getTags: (context: any) => { - const routerMode = context.routerMode as ReactRouterMode; - return { - routerMode: routerMode || 'unknown', - }; - }, - }, - - prompts: { - getAdditionalContextLines: (context: any) => { - const routerMode = context.routerMode as ReactRouterMode; - const modeName = routerMode ? getReactRouterModeName(routerMode) : 'unknown'; - - // Map router mode to framework ID for MCP docs resource - const frameworkIdMap: Record = { - [ReactRouterMode.V6]: 'react-react-router-6', - [ReactRouterMode.V7_FRAMEWORK]: 'react-react-router-7-framework', - [ReactRouterMode.V7_DATA]: 'react-react-router-7-data', - [ReactRouterMode.V7_DECLARATIVE]: 'react-react-router-7-declarative', - }; - - const frameworkId = routerMode ? frameworkIdMap[routerMode] : ReactRouterMode.V7_FRAMEWORK; - - return [`Router mode: ${modeName}`, `Framework docs ID: ${frameworkId}`]; - }, - }, - - ui: { - successMessage: 'WorkOS AuthKit integration complete', - getOutroChanges: (context: any) => { - const routerMode = context.routerMode as ReactRouterMode; - const modeName = routerMode ? getReactRouterModeName(routerMode) : 'React Router'; - return [ - `Analyzed your React Router project structure (${modeName})`, - `Created and configured WorkOS AuthKit`, - `Integrated authentication into your application`, - ]; - }, - getOutroNextSteps: () => [ - 'Start your development server to test authentication', - 'Visit the WorkOS Dashboard to manage users and settings', - ], - }, -}; - -/** - * React Router wizard powered by the universal agent runner. - * @returns Summary of what was done, or empty string if version check fails - */ -export async function runReactRouterInstallerAgent(options: InstallerOptions): Promise { - if (options.debug) { - enableDebugLogs(); - } - - // Check React Router version - agent wizard requires >= 6.0.0 - const packageJson = await getPackageDotJson(options); - const reactRouterVersion = getPackageVersion('react-router', packageJson); - - if (reactRouterVersion) { - const coercedVersion = semver.coerce(reactRouterVersion); - if (coercedVersion && semver.lt(coercedVersion, MINIMUM_REACT_ROUTER_VERSION)) { - const docsUrl = - REACT_ROUTER_AGENT_CONFIG.metadata.unsupportedVersionDocsUrl ?? REACT_ROUTER_AGENT_CONFIG.metadata.docsUrl; - - clack.log.warn( - `Sorry: the installer can't help you with React Router ${reactRouterVersion}. Upgrade to React Router ${MINIMUM_REACT_ROUTER_VERSION} or later, or check out the manual setup guide.`, - ); - clack.log.info(`Setup React Router manually: ${chalk.cyan(docsUrl)}`); - clack.outro('WorkOS AuthKit installer will see you next time!'); - return ''; - } - } - - return runAgentInstaller(REACT_ROUTER_AGENT_CONFIG, options); -} +export { + run as runReactRouterInstallerAgent, + config as REACT_ROUTER_AGENT_CONFIG, +} from '../integrations/react-router/index.js'; diff --git a/src/react-router/utils.ts b/src/react-router/utils.ts index 7847fdc..b93ae18 100644 --- a/src/react-router/utils.ts +++ b/src/react-router/utils.ts @@ -1,242 +1,9 @@ -import { major } from 'semver'; -import fg from 'fast-glob'; -import { abortIfCancelled, getPackageDotJson } from '../utils/clack-utils.js'; -import clack from '../utils/clack.js'; -import { getVersionBucket } from '../utils/semver.js'; -import type { InstallerOptions } from '../utils/types.js'; -import { IGNORE_PATTERNS, Integration } from '../lib/constants.js'; -import { getPackageVersion } from '../utils/package-json.js'; -import chalk from 'chalk'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import * as semver from 'semver'; - -export enum ReactRouterMode { - V6 = 'v6', // React Router v6 - V7_FRAMEWORK = 'v7-framework', // React Router v7 with react-router.config.ts - V7_DATA = 'v7-data', // React Router v7 with createBrowserRouter - V7_DECLARATIVE = 'v7-declarative', // React Router v7 with BrowserRouter -} - /** - * Get React Router version bucket for analytics + * @deprecated Import from 'src/integrations/react-router/utils.js' instead. */ -export function getReactRouterVersionBucket(version: string | undefined): string { - return getVersionBucket(version, 6); -} - -/** - * Check if react-router.config.ts exists (indicates framework mode - React Router v7) - */ -async function hasReactRouterConfig({ installDir }: Pick): Promise { - const configMatches = await fg('**/react-router.config.@(ts|js|tsx|jsx)', { - dot: true, - cwd: installDir, - ignore: IGNORE_PATTERNS, - }); - - return configMatches.length > 0; -} - -/** - * Search for createBrowserRouter usage in source files - */ -async function hasCreateBrowserRouter({ installDir }: Pick): Promise { - const sourceFiles = await fg('**/*.@(ts|tsx|js|jsx)', { - dot: true, - cwd: installDir, - ignore: IGNORE_PATTERNS, - }); - - for (const file of sourceFiles) { - try { - const filePath = path.join(installDir, file); - const content = fs.readFileSync(filePath, 'utf-8'); - - // Check for createBrowserRouter import or usage - if (content.includes('createBrowserRouter')) { - return true; - } - } catch { - // Skip files that can't be read - continue; - } - } - - return false; -} - -/** - * Search for declarative BrowserRouter usage - */ -async function hasDeclarativeRouter({ installDir }: Pick): Promise { - const sourceFiles = await fg('**/*.@(ts|tsx|js|jsx)', { - dot: true, - cwd: installDir, - ignore: IGNORE_PATTERNS, - }); - - for (const file of sourceFiles) { - try { - const filePath = path.join(installDir, file); - const content = fs.readFileSync(filePath, 'utf-8'); - - // Check for BrowserRouter usage (JSX or import) - if ( - content.includes(' { - const { installDir } = options; - - // First, get the React Router version - const packageJson = await getPackageDotJson(options); - const reactRouterVersion = - getPackageVersion('react-router-dom', packageJson) || getPackageVersion('react-router', packageJson); - - if (!reactRouterVersion) { - // If we can't detect version, ask the user - clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); - const result: ReactRouterMode = await abortIfCancelled( - clack.select({ - message: 'What React Router version and mode are you using?', - options: [ - { - label: 'React Router v6', - value: ReactRouterMode.V6, - }, - { - label: 'React Router v7 - Framework mode', - value: ReactRouterMode.V7_FRAMEWORK, - }, - { - label: 'React Router v7 - Data mode', - value: ReactRouterMode.V7_DATA, - }, - { - label: 'React Router v7 - Declarative mode', - value: ReactRouterMode.V7_DECLARATIVE, - }, - ], - }), - Integration.reactRouter, - ); - return result; - } - - const coercedVersion = semver.coerce(reactRouterVersion); - const majorVersion = coercedVersion ? major(coercedVersion) : null; - - // If v6, return V6 - if (majorVersion === 6) { - clack.log.info('Detected React Router v6'); - return ReactRouterMode.V6; - } - - // If v7, detect the mode - if (majorVersion === 7) { - // First check for framework mode (react-router.config.ts) - const hasConfig = await hasReactRouterConfig({ installDir }); - if (hasConfig) { - clack.log.info('Detected React Router v7 - Framework mode'); - return ReactRouterMode.V7_FRAMEWORK; - } - - // Check for data mode (createBrowserRouter) - const hasDataMode = await hasCreateBrowserRouter({ installDir }); - if (hasDataMode) { - clack.log.info('Detected React Router v7 - Data mode'); - return ReactRouterMode.V7_DATA; - } - - // Check for declarative mode (BrowserRouter) - const hasDeclarative = await hasDeclarativeRouter({ installDir }); - if (hasDeclarative) { - clack.log.info('Detected React Router v7 - Declarative mode'); - return ReactRouterMode.V7_DECLARATIVE; - } - - // If v7 but can't detect mode, ask the user - clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); - const result: ReactRouterMode = await abortIfCancelled( - clack.select({ - message: 'What React Router v7 mode are you using?', - options: [ - { - label: 'Framework mode', - value: ReactRouterMode.V7_FRAMEWORK, - }, - { - label: 'Data mode', - value: ReactRouterMode.V7_DATA, - }, - { - label: 'Declarative mode', - value: ReactRouterMode.V7_DECLARATIVE, - }, - ], - }), - Integration.reactRouter, - ); - return result; - } - - // If version is not 6 or 7, default to asking - clack.log.info(`Learn more about React Router modes: ${chalk.cyan('https://reactrouter.com/start/modes')}`); - const result: ReactRouterMode = await abortIfCancelled( - clack.select({ - message: 'What React Router version and mode are you using?', - options: [ - { - label: 'React Router v6', - value: ReactRouterMode.V6, - }, - { - label: 'React Router v7 - Framework mode', - value: ReactRouterMode.V7_FRAMEWORK, - }, - { - label: 'React Router v7 - Data mode', - value: ReactRouterMode.V7_DATA, - }, - { - label: 'React Router v7 - Declarative mode', - value: ReactRouterMode.V7_DECLARATIVE, - }, - ], - }), - Integration.reactRouter, - ); - return result; -} - -/** - * Get human-readable name for React Router mode - */ -export function getReactRouterModeName(mode: ReactRouterMode): string { - switch (mode) { - case ReactRouterMode.V6: - return 'v6'; - case ReactRouterMode.V7_FRAMEWORK: - return 'v7 Framework mode'; - case ReactRouterMode.V7_DATA: - return 'v7 Data mode'; - case ReactRouterMode.V7_DECLARATIVE: - return 'v7 Declarative mode'; - } -} +export { + ReactRouterMode, + getReactRouterVersionBucket, + getReactRouterMode, + getReactRouterModeName, +} from '../integrations/react-router/utils.js'; diff --git a/src/react/react-installer-agent.ts b/src/react/react-installer-agent.ts index 5086282..5299f29 100644 --- a/src/react/react-installer-agent.ts +++ b/src/react/react-installer-agent.ts @@ -1,57 +1,4 @@ -/* React SPA wizard using Claude Agent SDK */ -import type { InstallerOptions } from '../utils/types.js'; -import type { FrameworkConfig } from '../lib/framework-config.js'; -import { enableDebugLogs } from '../utils/debug.js'; -import { runAgentInstaller } from '../lib/agent-runner.js'; -import { Integration } from '../lib/constants.js'; - -const REACT_AGENT_CONFIG: FrameworkConfig = { - metadata: { - name: 'React', - integration: Integration.react, - docsUrl: 'https://workos.com/docs/user-management/authkit/react', - unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/react', - skillName: 'workos-authkit-react', - }, - - detection: { - packageName: 'react', - packageDisplayName: 'React', - getVersion: (packageJson: any) => packageJson.dependencies?.react || packageJson.devDependencies?.react, - }, - - environment: { - uploadToHosting: false, - requiresApiKey: false, // Client-only SPA - getEnvVars: (_apiKey: string, clientId: string) => ({ - WORKOS_CLIENT_ID: clientId, // Only client ID needed - }), - }, - - analytics: { - getTags: () => ({}), - }, - - prompts: {}, - - ui: { - successMessage: 'WorkOS AuthKit integration complete', - getOutroChanges: () => [ - 'Analyzed your React project structure', - 'Created and configured WorkOS AuthKit', - 'Integrated authentication into your application', - ], - getOutroNextSteps: () => [ - 'Start your development server to test authentication', - 'Visit the WorkOS Dashboard to manage users and settings', - ], - }, -}; - -export async function runReactInstallerAgent(options: InstallerOptions): Promise { - if (options.debug) { - enableDebugLogs(); - } - - return runAgentInstaller(REACT_AGENT_CONFIG, options); -} +/** + * @deprecated Import from 'src/integrations/react/index.js' instead. + */ +export { run as runReactInstallerAgent, config as REACT_AGENT_CONFIG } from '../integrations/react/index.js'; diff --git a/src/tanstack-start/tanstack-start-installer-agent.ts b/src/tanstack-start/tanstack-start-installer-agent.ts index db2e95e..9785db6 100644 --- a/src/tanstack-start/tanstack-start-installer-agent.ts +++ b/src/tanstack-start/tanstack-start-installer-agent.ts @@ -1,59 +1,7 @@ -/* TanStack Start wizard using Claude Agent SDK */ -import type { InstallerOptions } from '../utils/types.js'; -import type { FrameworkConfig } from '../lib/framework-config.js'; -import { enableDebugLogs } from '../utils/debug.js'; -import { runAgentInstaller } from '../lib/agent-runner.js'; -import { Integration } from '../lib/constants.js'; -import { getPackageVersion } from '../utils/package-json.js'; - -const TANSTACK_START_AGENT_CONFIG: FrameworkConfig = { - metadata: { - name: 'TanStack Start', - integration: Integration.tanstackStart, - docsUrl: 'https://workos.com/docs/user-management/authkit/tanstack-start', - unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/tanstack-start', - skillName: 'workos-authkit-tanstack-start', - }, - - detection: { - packageName: '@tanstack/react-start', - packageDisplayName: 'TanStack Start', - getVersion: (packageJson: any) => getPackageVersion('@tanstack/react-start', packageJson), - }, - - environment: { - uploadToHosting: false, - requiresApiKey: true, // Server-side framework - getEnvVars: (apiKey: string, clientId: string) => ({ - WORKOS_API_KEY: apiKey, - WORKOS_CLIENT_ID: clientId, - }), - }, - - analytics: { - getTags: () => ({}), - }, - - prompts: {}, - - ui: { - successMessage: 'WorkOS AuthKit integration complete', - getOutroChanges: () => [ - 'Analyzed your TanStack Start project structure', - 'Created and configured WorkOS AuthKit', - 'Integrated authentication into your application', - ], - getOutroNextSteps: () => [ - 'Start your development server to test authentication', - 'Visit the WorkOS Dashboard to manage users and settings', - ], - }, -}; - -export async function runTanstackStartInstallerAgent(options: InstallerOptions): Promise { - if (options.debug) { - enableDebugLogs(); - } - - return runAgentInstaller(TANSTACK_START_AGENT_CONFIG, options); -} +/** + * @deprecated Import from 'src/integrations/tanstack-start/index.js' instead. + */ +export { + run as runTanstackStartInstallerAgent, + config as TANSTACK_START_AGENT_CONFIG, +} from '../integrations/tanstack-start/index.js'; diff --git a/src/vanilla-js/vanilla-js-installer-agent.ts b/src/vanilla-js/vanilla-js-installer-agent.ts index e300edd..457dce1 100644 --- a/src/vanilla-js/vanilla-js-installer-agent.ts +++ b/src/vanilla-js/vanilla-js-installer-agent.ts @@ -1,57 +1,7 @@ -/* Vanilla JS wizard using Claude Agent SDK */ -import type { InstallerOptions } from '../utils/types.js'; -import type { FrameworkConfig } from '../lib/framework-config.js'; -import { enableDebugLogs } from '../utils/debug.js'; -import { runAgentInstaller } from '../lib/agent-runner.js'; -import { Integration } from '../lib/constants.js'; - -const VANILLA_JS_AGENT_CONFIG: FrameworkConfig = { - metadata: { - name: 'Vanilla JavaScript', - integration: Integration.vanillaJs, - docsUrl: 'https://workos.com/docs/user-management/authkit/javascript', - unsupportedVersionDocsUrl: 'https://workos.com/docs/user-management/authkit/javascript', - skillName: 'workos-authkit-vanilla-js', - }, - - detection: { - packageName: 'workos', - packageDisplayName: 'Vanilla JavaScript', - getVersion: () => undefined, - }, - - environment: { - uploadToHosting: false, - requiresApiKey: false, // Client-only - getEnvVars: (apiKey: string, clientId: string) => ({ - WORKOS_CLIENT_ID: clientId, // Only client ID needed - }), - }, - - analytics: { - getTags: () => ({}), - }, - - prompts: {}, - - ui: { - successMessage: 'WorkOS AuthKit integration complete', - getOutroChanges: () => [ - 'Created WorkOS AuthKit integration', - 'Added authentication to your JavaScript application', - 'Set up login/logout functionality', - ], - getOutroNextSteps: () => [ - 'Start your development server to test authentication', - 'Visit the WorkOS Dashboard to manage users and settings', - ], - }, -}; - -export async function runVanillaJsInstallerAgent(options: InstallerOptions): Promise { - if (options.debug) { - enableDebugLogs(); - } - - return runAgentInstaller(VANILLA_JS_AGENT_CONFIG, options); -} +/** + * @deprecated Import from 'src/integrations/vanilla-js/index.js' instead. + */ +export { + run as runVanillaJsInstallerAgent, + config as VANILLA_JS_AGENT_CONFIG, +} from '../integrations/vanilla-js/index.js'; From e8957813b5a798b6a36f3ac24b5d25b7d46cf17a Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 9 Feb 2026 14:00:46 -0600 Subject: [PATCH 02/12] feat: add 10 new SDK integrations via agent team Add support for SvelteKit, Node.js/Express, Python/Django, Ruby/Rails, Go/Gin, PHP, PHP/Laravel, Kotlin/Spring Boot, .NET/ASP.NET Core, and Elixir/Phoenix. Each integration includes a FrameworkConfig + skill file and was implemented in parallel by an agent team with zero merge conflicts. Non-JS integrations use a custom run() that bypasses the JS-centric runAgentInstaller and calls initializeAgent/runAgent directly. Also fixes port-detection crash for unknown integrations by adding optional chaining with sensible defaults. --- skills/workos-authkit-sveltekit/SKILL.md | 160 ++++++++++++ skills/workos-dotnet/SKILL.md | 154 ++++++++++++ skills/workos-elixir/SKILL.md | 166 +++++++++++++ skills/workos-go/SKILL.md | 183 ++++++++++++++ skills/workos-kotlin/SKILL.md | 157 ++++++++++++ skills/workos-node/SKILL.md | 301 +++++++++++++++++++++++ skills/workos-php-laravel/SKILL.md | 147 +++++++++++ skills/workos-php/SKILL.md | 127 ++++++++++ skills/workos-python/SKILL.md | 220 +++++++++++++++++ skills/workos-ruby/SKILL.md | 255 +++++++++++++++++++ src/integrations/dotnet/index.ts | 200 +++++++++++++++ src/integrations/elixir/index.ts | 183 ++++++++++++++ src/integrations/go/index.ts | 263 ++++++++++++++++++++ src/integrations/kotlin/index.ts | 63 +++++ src/integrations/node/index.ts | 62 +++++ src/integrations/php-laravel/index.ts | 61 +++++ src/integrations/php/index.ts | 61 +++++ src/integrations/python/index.ts | 292 ++++++++++++++++++++++ src/integrations/ruby/index.ts | 172 +++++++++++++ src/integrations/sveltekit/index.ts | 60 +++++ src/lib/port-detection.ts | 7 +- 21 files changed, 3292 insertions(+), 2 deletions(-) create mode 100644 skills/workos-authkit-sveltekit/SKILL.md create mode 100644 skills/workos-dotnet/SKILL.md create mode 100644 skills/workos-elixir/SKILL.md create mode 100644 skills/workos-go/SKILL.md create mode 100644 skills/workos-kotlin/SKILL.md create mode 100644 skills/workos-node/SKILL.md create mode 100644 skills/workos-php-laravel/SKILL.md create mode 100644 skills/workos-php/SKILL.md create mode 100644 skills/workos-python/SKILL.md create mode 100644 skills/workos-ruby/SKILL.md create mode 100644 src/integrations/dotnet/index.ts create mode 100644 src/integrations/elixir/index.ts create mode 100644 src/integrations/go/index.ts create mode 100644 src/integrations/kotlin/index.ts create mode 100644 src/integrations/node/index.ts create mode 100644 src/integrations/php-laravel/index.ts create mode 100644 src/integrations/php/index.ts create mode 100644 src/integrations/python/index.ts create mode 100644 src/integrations/ruby/index.ts create mode 100644 src/integrations/sveltekit/index.ts diff --git a/skills/workos-authkit-sveltekit/SKILL.md b/skills/workos-authkit-sveltekit/SKILL.md new file mode 100644 index 0000000..59f4731 --- /dev/null +++ b/skills/workos-authkit-sveltekit/SKILL.md @@ -0,0 +1,160 @@ +--- +name: workos-authkit-sveltekit +description: Integrate WorkOS AuthKit with SvelteKit. Server-side authentication with hooks and file-based routing. +--- + +# WorkOS AuthKit for SvelteKit + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://github.com/workos/authkit-sveltekit/blob/main/README.md` + +The README is the source of truth. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `svelte.config.js` (or `svelte.config.ts`) exists +- Confirm `package.json` contains `@sveltejs/kit` dependency +- Confirm `src/routes/` directory exists + +### Environment Variables + +Check `.env` or `.env.local` for: + +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` +- `WORKOS_REDIRECT_URI` - valid callback URL +- `WORKOS_COOKIE_PASSWORD` - 32+ characters + +SvelteKit uses `$env/static/private` and `$env/dynamic/private` natively. The agent should write env vars to `.env` (SvelteKit's default) or `.env.local`. + +## Step 3: Install SDK + +Detect package manager, install SDK package from README. + +``` +pnpm-lock.yaml? → pnpm add @workos-inc/authkit-sveltekit +yarn.lock? → yarn add @workos-inc/authkit-sveltekit +bun.lockb? → bun add @workos-inc/authkit-sveltekit +else → npm install @workos-inc/authkit-sveltekit +``` + +**Verify:** SDK package exists in node_modules before continuing. + +## Step 4: Configure Server Hooks + +SvelteKit uses `src/hooks.server.ts` for server-side middleware. This is where the AuthKit handler is registered. + +Create or update `src/hooks.server.ts` with the authkit handle function from the README. + +### Existing Hooks (IMPORTANT) + +If `src/hooks.server.ts` already exists with custom logic, use SvelteKit's `sequence()` helper to compose hooks: + +```typescript +import { sequence } from '@sveltejs/kit/hooks'; +import { authkitHandle } from '@workos-inc/authkit-sveltekit'; // Check README for exact export + +export const handle = sequence(authkitHandle, yourExistingHandle); +``` + +Check README for the exact export name and usage pattern. + +## Step 5: Create Callback Route + +Parse `WORKOS_REDIRECT_URI` to determine route path: + +``` +URI path --> Route location +/callback --> src/routes/callback/+server.ts +/auth/callback --> src/routes/auth/callback/+server.ts +``` + +Use the SDK's callback handler from the README. Do not write custom OAuth logic. + +**Critical:** SvelteKit uses `+server.ts` for API routes, not `+page.server.ts`. + +## Step 6: Layout Setup + +Update `src/routes/+layout.server.ts` to load the auth session and pass it to all pages. + +Check README for the exact pattern — typically a `load` function that returns the user session from locals. + +```typescript +// src/routes/+layout.server.ts +import type { LayoutServerLoad } from './$types'; + +export const load: LayoutServerLoad = async (event) => { + // Check README for exact API — session is typically on event.locals + return { + user: event.locals.user, // or similar from README + }; +}; +``` + +## Step 7: UI Integration + +Add auth UI to `src/routes/+page.svelte` using the session data from the layout. + +- Show user info when authenticated +- Show sign-in link/button when not authenticated +- Add sign-out functionality + +Check README for sign-in URL generation and sign-out patterns. + +## Verification Checklist (ALL MUST PASS) + +Run these commands to confirm integration. **Do not mark complete until all pass:** + +```bash +# 1. Check hooks.server.ts exists and has authkit +grep -i "workos\|authkit" src/hooks.server.ts || echo "FAIL: authkit missing from hooks.server.ts" + +# 2. Check callback route exists +find src/routes -name "+server.ts" -path "*/callback/*" + +# 3. Check layout loads auth session +grep -i "user\|auth\|session" src/routes/+layout.server.ts || echo "FAIL: auth session missing from layout" + +# 4. Build succeeds +pnpm build || npm run build +``` + +## Error Recovery + +### "Cannot find module '@workos-inc/authkit-sveltekit'" + +- Check: SDK installed before writing imports +- Check: SDK package directory exists in node_modules +- Re-run install if missing + +### hooks.server.ts not taking effect + +- Check: File is at `src/hooks.server.ts`, not `src/hooks.ts` or elsewhere +- Check: Named export is `handle` (SvelteKit requirement) +- Check: If using `sequence()`, all handles are properly composed + +### Callback route not found (404) + +- Check: File uses `+server.ts` (not `+page.server.ts`) +- Check: Route path matches `WORKOS_REDIRECT_URI` path exactly +- Check: Exports `GET` handler (SvelteKit convention) + +### "locals" type errors + +- Check: App.Locals interface is augmented in `src/app.d.ts` +- Check README for TypeScript setup instructions + +### Cookie password error + +- Verify `WORKOS_COOKIE_PASSWORD` is 32+ characters +- Generate new: `openssl rand -base64 32` + +### Auth state not available in pages + +- Check: `+layout.server.ts` load function returns user data +- Check: Pages access data via `export let data` (Svelte 4) or `$page.data` (Svelte 5) diff --git a/skills/workos-dotnet/SKILL.md b/skills/workos-dotnet/SKILL.md new file mode 100644 index 0000000..1f744f2 --- /dev/null +++ b/skills/workos-dotnet/SKILL.md @@ -0,0 +1,154 @@ +--- +name: workos-dotnet +description: Integrate WorkOS AuthKit with .NET (ASP.NET Core). Backend authentication with DI registration, auth endpoints, and appsettings configuration. +--- + +# WorkOS AuthKit for .NET (ASP.NET Core) + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://raw.githubusercontent.com/workos/workos-dotnet/main/README.md` + +The README is the source of truth for SDK API usage. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm a `*.csproj` file exists in the project root +- Detect project style: + - **Minimal API** (modern): `Program.cs` with `WebApplication.CreateBuilder()` — .NET 6+ + - **Startup pattern** (older): `Startup.cs` with `ConfigureServices()` / `Configure()` — .NET 5 and earlier + +This detection determines WHERE to register WorkOS services and middleware. + +### Environment Variables + +Check `appsettings.Development.json` for: +- `WORKOS_API_KEY` — starts with `sk_` +- `WORKOS_CLIENT_ID` — starts with `client_` + +## Step 3: Install SDK + +```bash +dotnet add package WorkOS.net +``` + +**Verify:** Check the `*.csproj` file contains a `", + "ClientId": "", + "RedirectUri": "http://localhost:5000/auth/callback" + } +} +``` + +Use the actual credential values provided in the environment context. + +**Important:** Do NOT put secrets in `appsettings.json` (committed to git). Use `appsettings.Development.json` (gitignored) or `dotnet user-secrets`. + +## Step 7: Verification + +Run these checks — **do not mark complete until all pass:** + +```bash +# 1. Check WorkOS.net is in csproj +grep -i "WorkOS" *.csproj + +# 2. Check auth endpoints exist +grep -r "auth/login\|auth/callback\|auth/logout" *.cs + +# 3. Build succeeds +dotnet build +``` + +**If build fails:** Read the error output carefully. Common issues: +- Missing `using` statements for WorkOS namespaces +- Incorrect DI registration order +- Missing session/cookie middleware registration + +## Error Recovery + +### "dotnet: command not found" +- .NET SDK is not installed. Inform the user to install from https://dotnet.microsoft.com/download + +### NuGet restore failures +- Check internet connectivity +- Try `dotnet restore` explicitly before `dotnet build` + +### "No project file found" +- Ensure you're in the correct directory with a `*.csproj` file + +### Build errors after integration +- Check that all `using` statements are correct +- Verify DI registration order (services before middleware) +- Ensure `app.UseSession()` is called before mapping auth endpoints diff --git a/skills/workos-elixir/SKILL.md b/skills/workos-elixir/SKILL.md new file mode 100644 index 0000000..ddcf092 --- /dev/null +++ b/skills/workos-elixir/SKILL.md @@ -0,0 +1,166 @@ +--- +name: workos-elixir +description: Integrate WorkOS AuthKit with Elixir/Phoenix applications. Server-side authentication with Phoenix controllers and routes. +--- + +# WorkOS AuthKit for Elixir (Phoenix) + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://raw.githubusercontent.com/workos/workos-elixir/main/README.md` + +The README is the source of truth for SDK API usage. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `mix.exs` exists +- Read `mix.exs` to extract the app name (look for `app: :my_app` in `project/0`) +- Confirm `lib/{app}_web/router.ex` exists (Phoenix project marker) +- Confirm `config/runtime.exs` exists + +### Determine App Name + +The app name from `mix.exs` determines all file paths. For example, if `app: :my_app`: +- Web module: `lib/my_app_web/` +- Router: `lib/my_app_web/router.ex` +- Controllers: `lib/my_app_web/controllers/` + +### Environment Variables + +Check `.env.local` for: +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` + +## Step 3: Install SDK + +Add the `workos` package to `mix.exs` dependencies: + +```elixir +defp deps do + [ + # ... existing deps + {:workos, "~> 1.0"} + ] +end +``` + +Then run: + +```bash +mix deps.get +``` + +**Verify:** Check that `mix deps.get` completed successfully (exit code 0). + +## Step 4: Configure WorkOS + +Add WorkOS configuration to `config/runtime.exs`: + +```elixir +config :workos, + api_key: System.get_env("WORKOS_API_KEY"), + client_id: System.get_env("WORKOS_CLIENT_ID") +``` + +This ensures credentials are loaded from environment variables at runtime, not compiled into the release. + +## Step 5: Create Auth Controller + +Create `lib/{app}_web/controllers/auth_controller.ex`: + +```elixir +defmodule {AppName}Web.AuthController do + use {AppName}Web, :controller + + def sign_in(conn, _params) do + client_id = Application.get_env(:workos, :client_id) + redirect_uri = "http://localhost:4000/auth/callback" + + authorization_url = WorkOS.UserManagement.get_authorization_url(%{ + provider: "authkit", + client_id: client_id, + redirect_uri: redirect_uri + }) + + case authorization_url do + {:ok, url} -> redirect(conn, external: url) + {:error, reason} -> conn |> put_status(500) |> text("Auth error: #{inspect(reason)}") + end + end + + def callback(conn, %{"code" => code}) do + client_id = Application.get_env(:workos, :client_id) + + case WorkOS.UserManagement.authenticate_with_code(%{ + code: code, + client_id: client_id + }) do + {:ok, auth_response} -> + conn + |> put_session(:user, auth_response.user) + |> redirect(to: "/") + + {:error, reason} -> + conn |> put_status(401) |> text("Authentication failed: #{inspect(reason)}") + end + end + + def sign_out(conn, _params) do + conn + |> clear_session() + |> redirect(to: "/") + end +end +``` + +**IMPORTANT:** Adapt the module name and API calls based on the README. The WorkOS Elixir SDK API may differ from the pseudocode above. Always follow the README for exact function names, parameter shapes, and return types. + +## Step 6: Add Routes + +Add auth routes to `lib/{app}_web/router.ex`. Add these routes inside or outside the existing pipeline scope as appropriate: + +```elixir +scope "/auth", {AppName}Web do + pipe_through :browser + + get "/sign-in", AuthController, :sign_in + get "/callback", AuthController, :callback + post "/sign-out", AuthController, :sign_out +end +``` + +## Step 7: Verification + +Run the following to confirm the integration compiles: + +```bash +mix compile +``` + +**If compilation fails:** +1. Read the error message carefully +2. Check that the WorkOS SDK module names match what's in the README +3. Verify the app name is consistent across all files +4. Fix the issue and re-run `mix compile` + +## Error Recovery + +### "could not compile dependency :workos" +- Check Elixir version compatibility (1.15+ recommended) +- Try `mix deps.clean workos && mix deps.get` + +### "module WorkOS.UserManagement is not available" +- The SDK API may use different module paths — re-read the README +- Check if the SDK uses `WorkOS.SSO` or another module instead + +### "undefined function" in controller +- Verify `use {AppName}Web, :controller` is correct +- Check that the SDK functions match the README exactly + +### Route conflicts +- Check existing routes in router.ex for `/auth` prefix conflicts +- Adjust the scope path if needed (e.g., `/workos-auth`) diff --git a/skills/workos-go/SKILL.md b/skills/workos-go/SKILL.md new file mode 100644 index 0000000..5e23c5d --- /dev/null +++ b/skills/workos-go/SKILL.md @@ -0,0 +1,183 @@ +--- +name: workos-go +description: Integrate WorkOS AuthKit with Go applications. Supports Gin and stdlib net/http. +--- + +# WorkOS AuthKit for Go + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://github.com/workos/workos-go/blob/main/README.md` + +The README is the source of truth for SDK API usage. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `go.mod` exists in the project root +- Confirm Go module is initialized (module path declared in `go.mod`) + +### Environment Variables + +Check `.env` for: + +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` +- `WORKOS_REDIRECT_URI` - valid callback URL (e.g., `http://localhost:8080/auth/callback`) + +### Framework Detection + +Read `go.mod` to detect web framework: + +``` +go.mod contains github.com/gin-gonic/gin? + | + +-- Yes --> Use Gin router patterns + | + +-- No --> Use stdlib net/http patterns +``` + +## Step 3: Install SDK + +Run: + +```bash +go get github.com/workos/workos-go/v4 +``` + +**Verify:** Check that `go.mod` now contains `github.com/workos/workos-go/v4`. Both `go.mod` and `go.sum` will be modified — this is expected. + +## Step 4: Configure Authentication + +### 4a: Create Auth Handler File + +Create an auth handler file. Respect existing project structure: +- If `internal/` directory exists, create `internal/auth/handlers.go` +- If `handlers/` directory exists, create `handlers/auth.go` +- Otherwise, create `auth/handlers.go` + +The file must: +- Declare a package matching the directory name +- Import `github.com/workos/workos-go/v4` packages as needed +- Read env vars with `os.Getenv("WORKOS_API_KEY")`, `os.Getenv("WORKOS_CLIENT_ID")`, `os.Getenv("WORKOS_REDIRECT_URI")` + +### 4b: Implement Handlers + +Implement these three handlers following the redirect-based auth flow from the README: + +**Login handler** (`/auth/login`): +- Get the authorization URL from WorkOS +- Redirect the user to the AuthKit sign-in page + +**Callback handler** (`/auth/callback`): +- Extract the `code` query parameter from the redirect +- Exchange the authorization code for a user profile using the WorkOS SDK +- Store user info in session (or return as JSON for API-first apps) +- Redirect to homepage or return user data + +**Logout handler** (`/auth/logout`): +- Clear session data +- Redirect to homepage + +**CRITICAL:** Use idiomatic Go error handling throughout: + +```go +result, err := someFunction() +if err != nil { + http.Error(w, "Error message", http.StatusInternalServerError) + return +} +``` + +### 4c: Wire Handlers into Router + +#### If using Gin: + +```go +r := gin.Default() +r.GET("/auth/login", handleLogin) +r.GET("/auth/callback", handleCallback) +r.GET("/auth/logout", handleLogout) +``` + +#### If using stdlib net/http: + +```go +http.HandleFunc("/auth/login", handleLogin) +http.HandleFunc("/auth/callback", handleCallback) +http.HandleFunc("/auth/logout", handleLogout) +``` + +Wire these routes into the existing router setup in `main.go` or wherever routes are defined. Do NOT replace existing routes — add alongside them. + +### 4d: Initialize WorkOS Client + +In the appropriate init location (package-level `init()` or `main()`), initialize the WorkOS client: + +```go +import "github.com/workos/workos-go/v4/pkg/usermanagement" + +func init() { + usermanagement.SetAPIKey(os.Getenv("WORKOS_API_KEY")) +} +``` + +Follow the README for the exact initialization pattern — it may differ from above. + +## Step 5: Environment Setup + +The `.env` file should already contain the required variables (written by the installer). Verify it contains: + +``` +WORKOS_API_KEY=sk_... +WORKOS_CLIENT_ID=client_... +WORKOS_REDIRECT_URI=http://localhost:8080/auth/callback +``` + +**Note for production:** Go does not have a built-in .env convention. In production, set real OS environment variables. The `.env` file is for development only. If using a `.env` loader like `github.com/joho/godotenv`, the agent may install it and add `godotenv.Load()` to `main()`. + +## Step 6: Verification + +Run these commands. **Do not mark complete until all pass:** + +```bash +# 1. Go module is tidy +go mod tidy + +# 2. Build succeeds +go build ./... + +# 3. Vet passes (catches common mistakes) +go vet ./... +``` + +If build fails: +- Check import paths match the SDK version in `go.mod` +- Ensure all new files have correct package declarations +- Run `go mod tidy` to resolve dependency issues + +## Error Recovery + +### "cannot find module providing package github.com/workos/workos-go/v4/..." + +- Run `go mod tidy` to sync dependencies +- Check that `go get` completed successfully +- Verify the import path matches exactly (v4 suffix required) + +### "undefined: usermanagement.SetAPIKey" or similar + +- SDK API may have changed — refer to the fetched README +- Check the correct subpackage import path + +### Build fails with type errors + +- Ensure handler function signatures match the framework (Gin uses `*gin.Context`, stdlib uses `http.ResponseWriter, *http.Request`) +- Check that error return values are handled + +### "package X is not in std" + +- Run `go mod tidy` after adding new imports +- Ensure `go get` was run before writing import statements diff --git a/skills/workos-kotlin/SKILL.md b/skills/workos-kotlin/SKILL.md new file mode 100644 index 0000000..a65a2bc --- /dev/null +++ b/skills/workos-kotlin/SKILL.md @@ -0,0 +1,157 @@ +--- +name: workos-kotlin +description: Integrate WorkOS AuthKit with Kotlin/Spring Boot. Backend authentication with Gradle. +--- + +# WorkOS AuthKit for Kotlin (Spring Boot) + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://raw.githubusercontent.com/workos/workos-kotlin/main/README.md` + +The README is the source of truth. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `build.gradle.kts` exists (Kotlin DSL) or `build.gradle` (Groovy DSL) +- Confirm Spring Boot plugin is present (`org.springframework.boot`) +- Detect Gradle wrapper: check if `./gradlew` exists + +### Gradle Wrapper + +```bash +# If gradlew exists, ensure it's executable +if [ -f ./gradlew ]; then chmod +x ./gradlew; fi +``` + +Use `./gradlew` if wrapper exists, otherwise fall back to `gradle`. + +### Environment Variables + +Check `application.properties` or `application.yml` for: + +- `workos.api-key` or `WORKOS_API_KEY` +- `workos.client-id` or `WORKOS_CLIENT_ID` + +## Step 3: Install SDK + +Add the WorkOS Kotlin SDK dependency to `build.gradle.kts`: + +```kotlin +dependencies { + implementation("com.workos:workos-kotlin:{version}") + // ... existing dependencies +} +``` + +Check the README for the latest version number. + +**Verify:** Run `./gradlew dependencies` or `gradle dependencies` to confirm the dependency resolves. + +## Step 4: Configure Authentication + +### 4a: Application Properties + +Add WorkOS configuration to `src/main/resources/application.properties`: + +```properties +workos.api-key=${WORKOS_API_KEY} +workos.client-id=${WORKOS_CLIENT_ID} +workos.redirect-uri=http://localhost:8080/auth/callback +``` + +Or if the project uses `application.yml`, add the equivalent YAML. + +### 4b: Create WorkOS Configuration Bean + +Create a configuration class that initializes the WorkOS client: + +```kotlin +@Configuration +class WorkOSConfig { + @Value("\${workos.api-key}") + lateinit var apiKey: String + + @Bean + fun workos(): WorkOS = WorkOS(apiKey) +} +``` + +Adapt based on the SDK README — the exact client initialization may vary. + +### 4c: Create Auth Controller + +Create a Spring `@RestController` with these endpoints: + +1. **GET /auth/login** — Redirect user to WorkOS AuthKit hosted login + - Use `workos.sso.getAuthorizationUrl()` or equivalent from README + - Include `clientId`, `redirectUri`, and `provider: "authkit"` parameters + +2. **GET /auth/callback** — Exchange authorization code for user profile + - Extract `code` query parameter + - Call `workos.sso.getProfileAndToken(code)` or equivalent + - Store user session (use Spring's `HttpSession`) + - Redirect to home page + +3. **GET /auth/logout** — Clear session and redirect + - Invalidate `HttpSession` + - Redirect to home page or WorkOS logout URL + +**Follow the README for exact API method names and parameters.** + +## Step 5: Session Management + +Use Spring's built-in `HttpSession` for session management: + +- Store user profile in session after callback +- Check session in protected routes +- Clear session on logout + +If Spring Security is already configured, integrate with the existing security filter chain rather than replacing it. + +## Step 6: Verification + +Run the build to verify everything compiles: + +```bash +./gradlew build +``` + +**If build fails:** +- Check dependency resolution: `./gradlew dependencies | grep workos` +- Check for missing imports in the auth controller +- Verify application.properties syntax +- Gradle builds can be slow (30-60s) — be patient + +### Checklist + +- [ ] WorkOS SDK dependency in build.gradle.kts +- [ ] Application properties configured +- [ ] Auth controller with login, callback, logout endpoints +- [ ] Build succeeds (`./gradlew build`) + +## Error Recovery + +### Dependency resolution failure + +- Check Maven Central is accessible +- Verify the artifact coordinates match README exactly +- Ensure `mavenCentral()` is in the `repositories` block of build.gradle.kts + +### "Could not resolve com.workos:workos-kotlin" + +- The package may use a different group ID — check README +- Ensure repositories block includes `mavenCentral()` + +### Build fails with missing Spring Boot annotations + +- Verify `org.springframework.boot` plugin is applied +- Check Spring Boot starter dependencies are present + +### Gradle wrapper permission denied + +- Run `chmod +x ./gradlew` before building diff --git a/skills/workos-node/SKILL.md b/skills/workos-node/SKILL.md new file mode 100644 index 0000000..a81a320 --- /dev/null +++ b/skills/workos-node/SKILL.md @@ -0,0 +1,301 @@ +--- +name: workos-node +description: Integrate WorkOS AuthKit with Node.js/Express backend applications. Server-side authentication with redirect-based OAuth flow. Use when project has express in package.json without a frontend framework. +--- + +# WorkOS AuthKit for Node.js (Express) + +## Decision Tree + +``` +1. Fetch README (BLOCKING) + ├── Extract package name from install command + └── README is source of truth for ALL code patterns + +2. Detect project structure + ├── TypeScript? (tsconfig.json present) + │ ├── Yes → use .ts files, verify with tsc --noEmit + │ └── No → use .js files, verify with node --check + ├── Entry point location + │ ├── src/index.ts or src/app.ts (modern TS setup) + │ ├── app.js or server.js (classic CJS) + │ └── index.js (minimal) + └── ESM or CJS? + ├── "type": "module" in package.json → ESM (import/export) + └── else → CJS (require/module.exports) + +3. Follow README install/setup exactly + └── Do not invent commands or patterns +``` + +## Fetch SDK Documentation (BLOCKING) + +**STOP - Do not proceed until complete.** + +WebFetch: `https://raw.githubusercontent.com/workos/workos-node/main/README.md` + +From README, extract: + +1. Package name (expected: `@workos-inc/node`) +2. Install command +3. Client initialization pattern +4. API usage for User Management / AuthKit + +**README overrides this skill if conflict.** + +## Pre-Flight Checklist + +- [ ] README fetched and package name extracted +- [ ] `package.json` exists with `express` dependency +- [ ] Identify entry point file (src/index.ts, src/app.ts, app.js, server.js, index.js) +- [ ] Detect TypeScript (tsconfig.json exists) +- [ ] Detect module system ("type": "module" → ESM, else CJS) +- [ ] Detect package manager (pnpm-lock.yaml → yarn.lock → bun.lockb → npm) +- [ ] Environment variables set or .env file prepared + +## Environment Variables + +| Variable | Format | Required | +| ------------------------ | ------------ | -------- | +| `WORKOS_API_KEY` | `sk_...` | Yes | +| `WORKOS_CLIENT_ID` | `client_...` | Yes | +| `WORKOS_REDIRECT_URI` | Full URL | Yes | +| `WORKOS_COOKIE_PASSWORD` | 32+ chars | Yes | + +Default redirect URI: `http://localhost:3000/auth/callback` + +Generate cookie password if missing: `openssl rand -base64 32` + +## Step 1: Install SDK + +Detect package manager, then install: + +``` +pnpm-lock.yaml → pnpm add @workos-inc/node +yarn.lock → yarn add @workos-inc/node +bun.lockb → bun add @workos-inc/node +else → npm install @workos-inc/node +``` + +### Verification + +- [ ] `@workos-inc/node` in package.json dependencies +- [ ] No install errors in output + +## Step 2: Initialize WorkOS Client + +Create or update a WorkOS client module. Adapt to the project's module system: + +**ESM / TypeScript:** + +```typescript +import { WorkOS } from '@workos-inc/node'; + +const workos = new WorkOS(process.env.WORKOS_API_KEY); +const clientId = process.env.WORKOS_CLIENT_ID; +``` + +**CJS:** + +```javascript +const { WorkOS } = require('@workos-inc/node'); + +const workos = new WorkOS(process.env.WORKOS_API_KEY); +const clientId = process.env.WORKOS_CLIENT_ID; +``` + +Place this where the Express app is initialized, or in a shared module that routes can import. + +## Step 3: Create /auth/login Route + +Redirects the user to WorkOS AuthKit for sign-in: + +```typescript +app.get('/auth/login', (req, res) => { + const authorizationUrl = workos.userManagement.getAuthorizationUrl({ + provider: 'authkit', + redirectUri: process.env.WORKOS_REDIRECT_URI, + clientId, + }); + + res.redirect(authorizationUrl); +}); +``` + +## Step 4: Create /auth/callback Route + +Exchanges the authorization code for a user object: + +```typescript +app.get('/auth/callback', async (req, res) => { + const code = req.query.code as string; + + try { + const { user, accessToken, refreshToken } = await workos.userManagement.authenticateWithCode({ + code, + clientId, + }); + + // Store user in session + req.session.user = user; + req.session.accessToken = accessToken; + req.session.refreshToken = refreshToken; + + res.redirect('/'); + } catch (error) { + res.redirect('/auth/login'); + } +}); +``` + +**Key points:** + +- Use `authenticateWithCode` — do not write custom OAuth logic +- Route path MUST match `WORKOS_REDIRECT_URI` +- Store tokens in session for subsequent requests + +## Step 5: Create /auth/logout Route + +```typescript +app.get('/auth/logout', (req, res) => { + req.session.destroy(() => { + res.redirect('/'); + }); +}); +``` + +## Step 6: Configure Session Management + +If `express-session` is not already installed, install it: + +``` +pnpm add express-session +# TypeScript projects also need: +pnpm add -D @types/express-session +``` + +Add session middleware **before** auth routes: + +```typescript +import session from 'express-session'; + +app.use(session({ + secret: process.env.WORKOS_COOKIE_PASSWORD, + resave: false, + saveUninitialized: false, + cookie: { secure: process.env.NODE_ENV === 'production', httpOnly: true }, +})); +``` + +### Verification + +- [ ] `express-session` in package.json dependencies +- [ ] Session middleware registered before routes +- [ ] Secret uses WORKOS_COOKIE_PASSWORD env var + +## Step 7: Add Auth Middleware for Protected Routes (Optional) + +```typescript +function requireAuth(req, res, next) { + if (!req.session.user) { + return res.redirect('/auth/login'); + } + next(); +} + +// Usage: +app.get('/dashboard', requireAuth, (req, res) => { + res.json({ user: req.session.user }); +}); +``` + +## Step 8: Write .env File + +Create `.env` if it doesn't exist. Do NOT overwrite existing values: + +``` +WORKOS_API_KEY=sk_test_... +WORKOS_CLIENT_ID=client_... +WORKOS_REDIRECT_URI=http://localhost:3000/auth/callback +WORKOS_COOKIE_PASSWORD= +``` + +Ensure `.env` is in `.gitignore`. + +## Step 9: Verify Build + +**TypeScript projects:** + +```bash +npx tsc --noEmit +``` + +**JavaScript projects:** + +```bash +node --check +``` + +### Final Verification Checklist + +- [ ] SDK package installed (`@workos-inc/node` in node_modules) +- [ ] WorkOS client initialized with API key +- [ ] `/auth/login` route redirects to AuthKit +- [ ] `/auth/callback` route exchanges code for user +- [ ] `/auth/logout` route destroys session +- [ ] Session middleware configured before auth routes +- [ ] `.env` file has all required variables +- [ ] Build/syntax check passes with exit code 0 + +## Error Recovery + +### Module not found: @workos-inc/node + +**Cause:** SDK not installed or wrong package name +**Fix:** Re-run install command for detected package manager +**Verify:** `ls node_modules/@workos-inc/node` + +### Session not persisting across requests + +**Cause:** express-session middleware not configured or registered after routes +**Fix:** Ensure `app.use(session(...))` appears BEFORE route definitions +**Verify:** Check middleware order in entry point file + +### Callback returns 404 + +**Cause:** Route path doesn't match WORKOS_REDIRECT_URI +**Fix:** Compare route path string to WORKOS_REDIRECT_URI env var — must match exactly +**Verify:** `grep -r "auth/callback" src/ app.js server.js index.js 2>/dev/null` + +### authenticateWithCode fails + +**Cause:** Invalid or expired code, or wrong clientId +**Fix:** Verify WORKOS_CLIENT_ID matches dashboard, ensure redirect URI matches exactly +**Verify:** Check WorkOS dashboard logs for error details + +### Cookie password error + +**Cause:** WORKOS_COOKIE_PASSWORD not set or < 32 chars +**Fix:** `openssl rand -base64 32`, update .env +**Verify:** `echo $WORKOS_COOKIE_PASSWORD | wc -c` (should be 33+) + +### TypeScript compilation errors + +**Cause:** Missing type definitions or import issues +**Fix:** Install `@types/express-session`, verify tsconfig includes source files +**Verify:** `npx tsc --noEmit` exits with code 0 + +### ESM/CJS mismatch + +**Cause:** Using `import` in CJS project or `require` in ESM project +**Fix:** Check `"type"` field in package.json — `"module"` means ESM, absent means CJS +**Verify:** Match import style to module system + +## Critical Rules + +1. **Install SDK before writing imports** — never create import statements for uninstalled packages +2. **Use SDK functions** — never construct OAuth URLs manually +3. **Follow README patterns** — SDK APIs change between versions +4. **Match module system** — detect ESM vs CJS before writing any code +5. **Session before routes** — express-session middleware must be registered before auth routes +6. **Production note** — mention that in-memory sessions should be replaced with Redis/DB for production diff --git a/skills/workos-php-laravel/SKILL.md b/skills/workos-php-laravel/SKILL.md new file mode 100644 index 0000000..7b96954 --- /dev/null +++ b/skills/workos-php-laravel/SKILL.md @@ -0,0 +1,147 @@ +--- +name: workos-php-laravel +description: Integrate WorkOS AuthKit with Laravel applications. Uses the dedicated workos-php-laravel SDK with service provider, middleware, and config publishing. +--- + +# WorkOS AuthKit for Laravel + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://github.com/workos/workos-php-laravel/blob/main/README.md` + +The README is the source of truth. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `artisan` file exists at project root +- Confirm `composer.json` contains `laravel/framework` dependency +- Confirm `app/` and `routes/` directories exist + +### Environment Variables + +Check `.env` for: + +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` +- `WORKOS_REDIRECT_URI` - valid callback URL (e.g., `http://localhost:8000/auth/callback`) + +If `.env` exists but is missing these variables, append them. If `.env` doesn't exist, copy `.env.example` and add them. + +## Step 3: Install SDK + +```bash +composer require workos/workos-php-laravel +``` + +**Verify:** Check `composer.json` contains `workos/workos-php-laravel` in require section before continuing. + +## Step 4: Publish Configuration + +```bash +php artisan vendor:publish --provider="WorkOS\Laravel\WorkOSServiceProvider" +``` + +This creates `config/workos.php`. Verify the file exists after publishing. + +If the artisan command fails, check README for the correct provider class name — it may differ. + +## Step 5: Configure Environment + +Ensure `.env` contains: + +``` +WORKOS_API_KEY=sk_... +WORKOS_CLIENT_ID=client_... +WORKOS_REDIRECT_URI=http://localhost:8000/auth/callback +``` + +Also ensure `config/workos.php` reads these env vars correctly. Check README for exact config structure. + +## Step 6: Create Auth Controller + +Create `app/Http/Controllers/AuthController.php` with methods for: + +- `login()` — Redirect to WorkOS AuthKit authorization URL +- `callback()` — Handle OAuth callback, exchange code for user profile +- `logout()` — Clear session and redirect + +Use SDK methods from README. Do NOT construct OAuth URLs manually. + +## Step 7: Add Routes + +Add to `routes/web.php`: + +```php +use App\Http\Controllers\AuthController; + +Route::get('/login', [AuthController::class, 'login'])->name('login'); +Route::get('/auth/callback', [AuthController::class, 'callback']); +Route::get('/logout', [AuthController::class, 'logout'])->name('logout'); +``` + +Ensure the callback route path matches `WORKOS_REDIRECT_URI`. + +## Step 8: Add Middleware (if applicable) + +Check README for any authentication middleware the SDK provides. If available: + +1. Register middleware in `app/Http/Kernel.php` or `bootstrap/app.php` (Laravel 11+) +2. Apply to routes that require authentication + +For Laravel 11+, middleware is registered in `bootstrap/app.php` instead of `Kernel.php`. + +## Step 9: Add UI Integration + +Update the home page or dashboard view to show: + +- Sign in link when user is not authenticated +- User info and sign out link when authenticated + +Use Blade directives or SDK helpers from README. + +## Verification Checklist (ALL MUST PASS) + +```bash +# 1. Config file exists +ls config/workos.php + +# 2. Controller exists +ls app/Http/Controllers/AuthController.php + +# 3. Routes registered +php artisan route:list | grep -E "login|callback|logout" + +# 4. SDK installed +composer show workos/workos-php-laravel + +# 5. Lint check +php -l app/Http/Controllers/AuthController.php +``` + +## Error Recovery + +### "Class WorkOS\Laravel\WorkOSServiceProvider not found" + +- Verify `composer require` completed successfully +- Run `composer dump-autoload` +- Check `vendor/workos/` directory exists + +### "Route not defined" + +- Verify routes are in `routes/web.php` +- Run `php artisan route:clear && php artisan route:cache` + +### Config not loading + +- Verify `config/workos.php` exists +- Run `php artisan config:clear` +- Check `.env` variables match config keys + +### Middleware issues (Laravel 11+) + +- Laravel 11 removed `Kernel.php` — register middleware in `bootstrap/app.php` +- Check README for Laravel version-specific instructions diff --git a/skills/workos-php/SKILL.md b/skills/workos-php/SKILL.md new file mode 100644 index 0000000..7839ac2 --- /dev/null +++ b/skills/workos-php/SKILL.md @@ -0,0 +1,127 @@ +--- +name: workos-php +description: Integrate WorkOS AuthKit with generic PHP applications. Uses the workos-php SDK directly with standalone auth endpoint files. +--- + +# WorkOS AuthKit for PHP + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://github.com/workos/workos-php/blob/main/README.md` + +The README is the source of truth. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `composer.json` exists at project root +- If `composer.json` doesn't exist, create a minimal one with `composer init --no-interaction` + +### Environment Variables + +Check for `.env` file with: + +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` +- `WORKOS_REDIRECT_URI` - valid callback URL (e.g., `http://localhost:8000/callback.php`) + +If `.env` doesn't exist, create it with the required variables. + +## Step 3: Install SDK + +```bash +composer require workos/workos-php +``` + +**Verify:** Check `composer.json` contains `workos/workos-php` in require section. + +Also install a dotenv library if not present: + +```bash +composer require vlucas/phpdotenv +``` + +## Step 4: Create Bootstrap File + +Create a bootstrap or config file (e.g., `config.php` or `bootstrap.php`) that: + +1. Requires Composer autoloader: `require_once __DIR__ . '/vendor/autoload.php';` +2. Loads `.env` using phpdotenv +3. Initializes the WorkOS SDK client with API key + +Use SDK initialization from README. Do NOT hardcode credentials. + +## Step 5: Create Auth Endpoint Files + +### `login.php` + +- Initialize WorkOS client (include bootstrap) +- Generate authorization URL using SDK +- Redirect user to WorkOS AuthKit + +### `callback.php` + +- Initialize WorkOS client (include bootstrap) +- Exchange authorization code from `$_GET['code']` for user profile using SDK +- Start session, store user data +- Redirect to home/dashboard + +### `logout.php` + +- Destroy session +- Redirect to home page + +Use SDK methods from README for all WorkOS API calls. Do NOT construct OAuth URLs manually. + +## Step 6: Create Home Page + +Create or update `index.php` to show: + +- Sign in link (`login.php`) when no session +- User info and sign out link (`logout.php`) when session exists + +## Verification Checklist (ALL MUST PASS) + +```bash +# 1. SDK installed +composer show workos/workos-php + +# 2. Auth files exist +ls login.php callback.php logout.php + +# 3. No syntax errors +php -l login.php +php -l callback.php +php -l logout.php +php -l index.php + +# 4. Autoloader exists +ls vendor/autoload.php +``` + +## Error Recovery + +### "Class WorkOS\WorkOS not found" + +- Verify `composer require` completed successfully +- Check `vendor/autoload.php` is required in bootstrap +- Run `composer dump-autoload` + +### Session issues + +- Ensure `session_start()` is called before any session access +- Check PHP session configuration (`session.save_path`) + +### Redirect URI mismatch + +- Compare callback file path to `WORKOS_REDIRECT_URI` in `.env` +- URLs must match exactly (including trailing slash) + +### Environment variables not loading + +- Verify `.env` file exists in project root +- Verify phpdotenv is installed and loaded in bootstrap +- Check file permissions on `.env` diff --git a/skills/workos-python/SKILL.md b/skills/workos-python/SKILL.md new file mode 100644 index 0000000..590c294 --- /dev/null +++ b/skills/workos-python/SKILL.md @@ -0,0 +1,220 @@ +--- +name: workos-python +description: Integrate WorkOS AuthKit with Python/Django. Server-side authentication with Django views and URL routing. +--- + +# WorkOS AuthKit for Python (Django) + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP. Do not proceed until complete.** + +WebFetch: `https://raw.githubusercontent.com/workos/workos-python/main/README.md` + +The README is the source of truth for SDK API usage. If this skill conflicts with README, follow README. + +## Step 2: Pre-Flight Validation + +### Project Structure + +- Confirm `manage.py` exists (Django project root) +- Identify the Django settings module: look for `settings.py` or a `settings/` directory with `base.py` +- Identify the root `urls.py` (project-level URL configuration) +- If settings are split (`settings/base.py`, `settings/dev.py`, etc.), modify `base.py` + +### Environment Variables + +Check `.env` for: + +- `WORKOS_API_KEY` - starts with `sk_` +- `WORKOS_CLIENT_ID` - starts with `client_` + +Python/Django does NOT use `WORKOS_COOKIE_PASSWORD` or `WORKOS_REDIRECT_URI` as env vars. The redirect URI is passed directly in code. + +### Package Manager Detection + +``` +uv.lock exists? → uv add +pyproject.toml has [tool.poetry]? → poetry add +Pipfile exists? → pipenv install +requirements.txt exists? → pip install (+ append to requirements.txt) +else → pip install +``` + +## Step 3: Install SDK + +Install using the detected package manager: + +```bash +# uv +uv add workos python-dotenv + +# poetry +poetry add workos python-dotenv + +# pipenv +pipenv install workos python-dotenv + +# pip +pip install workos python-dotenv +``` + +If using `requirements.txt`, also append `workos` and `python-dotenv` to it (if not already listed). + +**Verify installation:** + +```bash +python -c "import workos; print('workos OK')" +python -c "import dotenv; print('dotenv OK')" +``` + +## Step 4: Configure Django Settings + +Edit the project's `settings.py` (or `settings/base.py` if split): + +1. Add imports at the top of the file (after existing imports): + +```python +import os +from dotenv import load_dotenv + +load_dotenv() +``` + +2. Add WorkOS configuration (at the bottom of settings, before any local settings import): + +```python +# WorkOS AuthKit Configuration +WORKOS_API_KEY = os.environ.get('WORKOS_API_KEY', '') +WORKOS_CLIENT_ID = os.environ.get('WORKOS_CLIENT_ID', '') +``` + +3. Ensure session support is configured: + - `'django.contrib.sessions'` must be in `INSTALLED_APPS` + - `'django.contrib.sessions.middleware.SessionMiddleware'` must be in `MIDDLEWARE` + - These are included by default in Django projects — verify they haven't been removed + +**Do NOT remove or reorder existing settings.** Only add new entries. + +## Step 5: Create Auth Views + +Create an auth views file. Prefer adding to an existing app's `views.py`, or create a new `auth_views.py` in the main project directory. + +Follow the exact patterns from the WorkOS Python SDK README for: + +### Login View +- Import and initialize the WorkOS client +- Call the SDK's method to generate an authorization URL +- Pass `redirect_uri` pointing to your callback view (e.g., `http://localhost:8000/auth/callback`) +- Pass `client_id` from settings +- Redirect the user to the returned authorization URL + +### Callback View +- Receive the `code` query parameter from the request +- Use the SDK to exchange the code for a user profile +- Store the user information in `request.session` +- Redirect to the home page + +### Logout View +- Clear the Django session with `request.session.flush()` +- Redirect to the home page + +**CRITICAL:** Use the SDK methods from the README. Do NOT manually construct OAuth URLs. + +## Step 6: Configure URL Routing + +Add URL patterns to the project's `urls.py`: + +```python +from django.urls import path +from . import auth_views # adjust import path as needed + +urlpatterns = [ + # ... existing patterns ... + path('auth/login/', auth_views.login_view, name='workos_login'), + path('auth/callback/', auth_views.callback_view, name='workos_callback'), + path('auth/logout/', auth_views.logout_view, name='workos_logout'), +] +``` + +Adjust the import path based on where you placed the auth views in Step 5. + +## Step 7: UI Integration + +Update the home page template (or create `templates/home.html`) to show authentication state: + +```html +{% if request.session.user %} +

Welcome, {{ request.session.user.email }}!

+ Log out +{% else %} + Log in +{% endif %} +``` + +If no home view exists, create a simple one that renders this template. + +Ensure `TEMPLATES` in settings has `APP_DIRS: True` or the template directory is configured. + +## Step 8: Verification Checklist (ALL MUST PASS) + +Run these commands to confirm integration. **Do not mark complete until all pass:** + +```bash +# 1. WorkOS SDK is importable +python -c "import workos; print('OK')" + +# 2. python-dotenv is importable +python -c "import dotenv; print('OK')" + +# 3. .env has credentials +python -c " +from dotenv import load_dotenv; import os; load_dotenv() +assert os.environ.get('WORKOS_API_KEY','').startswith('sk_'), 'WORKOS_API_KEY missing or invalid' +assert os.environ.get('WORKOS_CLIENT_ID','').startswith('client_'), 'WORKOS_CLIENT_ID missing or invalid' +print('Credentials OK') +" + +# 4. Django check passes +python manage.py check +``` + +## Error Recovery + +### "ModuleNotFoundError: No module named 'workos'" + +- Verify the install command completed successfully +- If using a virtual environment, ensure it's activated +- Re-run the install command + +### "ModuleNotFoundError: No module named 'dotenv'" + +- Install: use detected package manager to install `python-dotenv` +- Import as `from dotenv import load_dotenv` (NOT `import dotenv`) + +### Django check fails + +- Run `python manage.py check` to see specific errors +- Common: missing migrations (`python manage.py migrate`), invalid URL patterns, missing template directories + +### Callback returns error + +- Verify redirect URI in code matches `http://localhost:8000/auth/callback/` +- Verify `WORKOS_CLIENT_ID` and `WORKOS_API_KEY` are set in `.env` +- Check the authorization code is being exchanged correctly per SDK README + +### Session not persisting + +- Ensure `django.contrib.sessions` is in `INSTALLED_APPS` +- Ensure `SessionMiddleware` is in `MIDDLEWARE` +- Run `python manage.py migrate` if sessions table is missing + +### "CSRF verification failed" + +- Auth views that receive external redirects (callback) should be decorated with `@csrf_exempt` +- Or use `GET` method for callback (WorkOS redirects via GET) + +### Virtual environment issues + +- Check for `.venv/`, `venv/`, or poetry/pipenv managed environments +- If no venv detected, install globally but warn the user diff --git a/skills/workos-ruby/SKILL.md b/skills/workos-ruby/SKILL.md new file mode 100644 index 0000000..636dfe8 --- /dev/null +++ b/skills/workos-ruby/SKILL.md @@ -0,0 +1,255 @@ +--- +name: workos-ruby +description: Integrate WorkOS AuthKit with Ruby on Rails. Server-side auth with controllers and routes. Use when Gemfile exists with rails gem or config/routes.rb exists. +--- + +# WorkOS AuthKit for Ruby on Rails + +## Step 1: Fetch SDK Documentation (BLOCKING) + +**STOP — Do not proceed until this fetch is complete.** + +``` +WebFetch: https://raw.githubusercontent.com/workos/workos-ruby/main/README.md +``` + +The README is the **source of truth** for gem installation, API usage, and code patterns. +If this skill conflicts with the README, **follow the README**. + +## Step 2: Pre-Flight Validation + +### Confirm Rails Project Structure + +```bash +ls config/routes.rb app/controllers/application_controller.rb Gemfile +``` + +All three must exist. If not, abort — this is not a Rails project. + +### Check Rails Version + +```bash +grep "gem ['\"]rails['\"]" Gemfile +``` + +Note the version constraint for compatibility awareness. + +### Check Existing Auth + +```bash +grep -r "workos\|devise\|omniauth" Gemfile app/controllers/ config/initializers/ 2>/dev/null || true +``` + +If WorkOS is already configured, note what exists and adapt rather than duplicate. + +## Step 3: Install WorkOS Gem + +Install the gem using Bundler: + +```bash +bundle add workos +``` + +### Verify Installation + +```bash +bundle show workos +``` + +Must output a path. If it fails, check `Gemfile` for the entry and run `bundle install`. + +## Step 4: Install dotenv-rails (if needed) + +Check if dotenv-rails is already in the Gemfile: + +```bash +grep "dotenv" Gemfile +``` + +If NOT present, install it for `.env` support: + +```bash +bundle add dotenv-rails --group development,test +``` + +## Step 5: Create WorkOS Initializer + +Create `config/initializers/workos.rb`: + +```ruby +# config/initializers/workos.rb +WorkOS.configure do |config| + config.api_key = ENV.fetch("WORKOS_API_KEY") + config.client_id = ENV.fetch("WORKOS_CLIENT_ID") +end +``` + +### Verify + +```bash +cat config/initializers/workos.rb +``` + +## Step 6: Create Environment File + +Create or update `.env` in the project root: + +``` +WORKOS_API_KEY=your_api_key_here +WORKOS_CLIENT_ID=your_client_id_here +WORKOS_REDIRECT_URI=http://localhost:3000/auth/callback +``` + +**Important**: If `.env` already exists, append only missing variables — do not overwrite existing values. + +If the environment variables were already provided (check if they have real values, not placeholder text), use those values. + +### Verify + +```bash +grep WORKOS .env +``` + +## Step 7: Create Auth Controller + +Create `app/controllers/auth_controller.rb` following the patterns from the README: + +```ruby +# app/controllers/auth_controller.rb +class AuthController < ApplicationController + def login + authorization_url = WorkOS::UserManagement.get_authorization_url( + redirect_uri: ENV.fetch("WORKOS_REDIRECT_URI"), + provider: "authkit" + ) + redirect_to authorization_url, allow_other_host: true + end + + def callback + code = params[:code] + + auth_response = WorkOS::UserManagement.authenticate_with_code( + code: code, + ip_address: request.remote_ip, + user_agent: request.user_agent + ) + + session[:user] = auth_response.user.to_json + redirect_to root_path + end + + def logout + session.delete(:user) + redirect_to root_path + end +end +``` + +**IMPORTANT**: Cross-check the controller code with the README. The README is the source of truth for: +- Method names (`get_authorization_url`, `authenticate_with_code`) +- Parameter names and structure +- Response object shape + +If the README shows different method signatures, **use the README version**. + +### Verify + +```bash +cat app/controllers/auth_controller.rb +``` + +## Step 8: Add Routes + +Add authentication routes to `config/routes.rb`. Insert these inside the existing `Rails.application.routes.draw` block: + +```ruby +get "/auth/login", to: "auth#login" +get "/auth/callback", to: "auth#callback" +get "/auth/logout", to: "auth#logout" +``` + +**Do not replace** the existing routes file. Insert the new routes alongside existing ones. + +### Verify + +```bash +grep -A 5 "auth" config/routes.rb +``` + +## Step 9: Add Current User Helper (Optional but Recommended) + +If the project has `app/controllers/application_controller.rb`, add a helper method: + +```ruby +# Add to ApplicationController +class ApplicationController < ActionController::Base + helper_method :current_user + + private + + def current_user + return nil unless session[:user] + @current_user ||= JSON.parse(session[:user]) + end +end +``` + +**Only add the `current_user` method and `helper_method` declaration** — do not overwrite the entire file. Merge into the existing class. + +## Step 10: Final Verification + +### Check Routes Compile + +```bash +bundle exec rails routes | grep auth +``` + +Expected output should show three routes: `/auth/login`, `/auth/callback`, `/auth/logout`. + +### Check All Files Exist + +```bash +ls config/initializers/workos.rb app/controllers/auth_controller.rb .env +``` + +### Check Gemfile Has WorkOS + +```bash +grep workos Gemfile +``` + +## Error Recovery + +### "uninitialized constant WorkOS" + +**Cause**: Gem not loaded or initializer not created. +**Fix**: +1. Verify `bundle show workos` succeeds +2. Verify `config/initializers/workos.rb` exists and requires nothing extra (Rails auto-loads gems) +3. Run `bundle install` if gem is in Gemfile but not installed + +### "Missing API key" or "WORKOS_API_KEY" + +**Cause**: Environment variable not set or dotenv not loading. +**Fix**: +1. Verify `.env` file exists with `WORKOS_API_KEY` +2. Verify `dotenv-rails` gem is in Gemfile +3. For production, set env vars through your hosting provider instead of `.env` + +### "NoMethodError" on WorkOS methods + +**Cause**: SDK API may have changed — method names differ from what's in this skill. +**Fix**: Re-read the README (Step 1). Use the exact method names shown there. + +### "RoutingError" for /auth/* paths + +**Cause**: Routes not added or misspelled. +**Fix**: +1. Run `bundle exec rails routes | grep auth` +2. Verify routes are inside `Rails.application.routes.draw` block +3. Verify controller file is named `auth_controller.rb` (not `authentication_controller.rb`) + +### Callback returns error from WorkOS + +**Cause**: Redirect URI mismatch between WorkOS Dashboard and `.env`. +**Fix**: Ensure `WORKOS_REDIRECT_URI` in `.env` exactly matches the redirect URI configured in the WorkOS Dashboard. diff --git a/src/integrations/dotnet/index.ts b/src/integrations/dotnet/index.ts new file mode 100644 index 0000000..76b87ab --- /dev/null +++ b/src/integrations/dotnet/index.ts @@ -0,0 +1,200 @@ +/* .NET (ASP.NET Core) integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { SPINNER_MESSAGE } from '../../lib/framework-config.js'; +import { getOrAskForWorkOSCredentials } from '../../utils/clack-utils.js'; +import { analytics } from '../../utils/analytics.js'; +import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js'; +import { initializeAgent, runAgent } from '../../lib/agent-interface.js'; +import { autoConfigureWorkOSEnvironment } from '../../lib/workos-management.js'; +import { validateInstallation } from '../../lib/validation/index.js'; + +export const config: FrameworkConfig = { + metadata: { + name: '.NET (ASP.NET Core)', + integration: 'dotnet', + docsUrl: 'https://github.com/workos/workos-dotnet', + skillName: 'workos-dotnet', + language: 'dotnet', + stability: 'experimental', + priority: 35, + packageManager: 'dotnet', + manifestFile: '*.csproj', + }, + + detection: { + // Detection handled by language-detection.ts globExists('*.csproj'). + // These fields satisfy the FrameworkDetection interface but aren't used for non-JS SDKs. + packageName: 'WorkOS.net', + packageDisplayName: '.NET (ASP.NET Core)', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your ASP.NET Core project structure', + 'Installed WorkOS.net NuGet package', + 'Created authentication endpoints (login, callback, logout)', + 'Configured WorkOS in appsettings', + ], + getOutroNextSteps: () => [ + 'Run `dotnet run` to start your development server', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +/** + * Custom run function for .NET — bypasses runAgentInstaller's JS-centric assumptions + * (no package.json, no .env.local, no TypeScript detection, no JS port detection). + */ +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + options.emitter?.emit('status', { + message: `Setting up WorkOS AuthKit for ${config.metadata.name}`, + }); + + analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, { + action: 'started agent integration', + integration: config.metadata.integration, + }); + + const { apiKey, clientId } = await getOrAskForWorkOSCredentials(options, config.environment.requiresApiKey); + + // Auto-configure WorkOS environment (redirect URI, CORS, homepage) + const callerHandledConfig = Boolean(options.apiKey || options.clientId); + if (!callerHandledConfig && apiKey) { + const port = 5000; // ASP.NET Core default HTTP port + await autoConfigureWorkOSEnvironment(apiKey, config.metadata.integration, port, { + homepageUrl: options.homepageUrl, + redirectUri: options.redirectUri, + }); + } + + // Build prompt — credentials are passed via prompt context since .NET doesn't use .env.local + const skillName = config.metadata.skillName!; + const redirectUri = options.redirectUri || 'http://localhost:5000/auth/callback'; + + const prompt = `You are integrating WorkOS AuthKit into this ASP.NET Core application. + +## Project Context + +- Framework: ASP.NET Core +- Language: C# +- Package manager: dotnet (NuGet) + +## Environment + +The following WorkOS credentials should be configured in appsettings.Development.json: +- WORKOS_API_KEY: ${apiKey || '(not provided)'} +- WORKOS_CLIENT_ID: ${clientId} +- WORKOS_REDIRECT_URI: ${redirectUri} + +## Your Task + +Use the \`${skillName}\` skill to integrate WorkOS AuthKit into this application. + +The skill contains step-by-step instructions including: +1. Fetching the SDK documentation +2. Installing the WorkOS.net NuGet package +3. Configuring DI registration +4. Creating authentication endpoints +5. Setting up appsettings configuration + +Report your progress using [STATUS] prefixes. + +Begin by invoking the ${skillName} skill.`; + + const agent = await initializeAgent( + { + workingDirectory: options.installDir, + workOSApiKey: apiKey, + workOSApiHost: 'https://api.workos.com', + }, + options, + ); + + const agentResult = await runAgent( + agent, + prompt, + options, + { + spinnerMessage: SPINNER_MESSAGE, + successMessage: config.ui.successMessage, + errorMessage: 'Integration failed', + }, + options.emitter, + ); + + if (agentResult.error) { + await analytics.shutdown('error'); + const message = agentResult.errorMessage || agentResult.error; + throw new Error(`Agent SDK error: ${message}`); + } + + // Post-installation validation + if (!options.noValidate) { + options.emitter?.emit('validation:start', { framework: config.metadata.integration }); + + const validationResult = await validateInstallation(config.metadata.integration, options.installDir, { + runBuild: true, + }); + + if (validationResult.issues.length > 0) { + options.emitter?.emit('validation:issues', { issues: validationResult.issues }); + } + + options.emitter?.emit('validation:complete', { + passed: validationResult.passed, + issueCount: validationResult.issues.length, + durationMs: validationResult.durationMs, + }); + } + + const envVars = config.environment.getEnvVars(apiKey, clientId); + + const changes = [ + ...config.ui.getOutroChanges({}), + Object.keys(envVars).length > 0 ? 'Configured WorkOS credentials in appsettings' : '', + ].filter(Boolean); + + const nextSteps = config.ui.getOutroNextSteps({}); + + const lines: string[] = [ + 'Successfully installed WorkOS AuthKit!', + '', + 'What the agent did:', + ...changes.map((c) => `• ${c}`), + '', + 'Next steps:', + ...nextSteps.map((s) => `• ${s}`), + '', + `Learn more: ${config.metadata.docsUrl}`, + '', + 'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.', + ]; + + await analytics.shutdown('success'); + + return lines.join('\n'); +} diff --git a/src/integrations/elixir/index.ts b/src/integrations/elixir/index.ts new file mode 100644 index 0000000..ea55f34 --- /dev/null +++ b/src/integrations/elixir/index.ts @@ -0,0 +1,183 @@ +/* Elixir/Phoenix integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { SPINNER_MESSAGE } from '../../lib/framework-config.js'; +import { analytics } from '../../utils/analytics.js'; +import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js'; +import { getOrAskForWorkOSCredentials } from '../../utils/clack-utils.js'; +import { initializeAgent, runAgent } from '../../lib/agent-interface.js'; +import { writeEnvLocal } from '../../lib/env-writer.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Elixir (Phoenix)', + integration: 'elixir', + docsUrl: 'https://github.com/workos/workos-elixir', + skillName: 'workos-elixir', + language: 'elixir', + stability: 'experimental', + priority: 30, + packageManager: 'mix', + manifestFile: 'mix.exs', + }, + + detection: { + // Required by FrameworkDetection interface — stubs for non-JS integration. + // Actual detection uses language-detection.ts (mix.exs) + registry manifestFile check. + packageName: 'workos', + packageDisplayName: 'WorkOS Elixir', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Phoenix project structure', + 'Installed workos Hex package', + 'Configured WorkOS in config/runtime.exs', + 'Created auth controller and routes', + ], + getOutroNextSteps: () => [ + 'Run `mix phx.server` to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +/** + * Custom run function for Elixir — bypasses runAgentInstaller() which assumes + * package.json exists. Directly calls initializeAgent/runAgent instead. + */ +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + options.emitter?.emit('status', { + message: `Setting up WorkOS AuthKit for ${config.metadata.name}`, + }); + + analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, { + action: 'started agent integration', + integration: config.metadata.integration, + }); + + // Get WorkOS credentials + const { apiKey, clientId } = await getOrAskForWorkOSCredentials(options, config.environment.requiresApiKey); + + // Write env vars to .env.local for the agent to reference + const callerHandledConfig = Boolean(options.apiKey || options.clientId); + if (!callerHandledConfig) { + const port = 4000; // Phoenix default + const callbackPath = '/auth/callback'; + const redirectUri = options.redirectUri || `http://localhost:${port}${callbackPath}`; + + writeEnvLocal(options.installDir, { + ...(apiKey ? { WORKOS_API_KEY: apiKey } : {}), + WORKOS_CLIENT_ID: clientId, + WORKOS_REDIRECT_URI: redirectUri, + }); + } + + // Build Elixir-specific prompt + const integrationPrompt = buildElixirPrompt(); + + // Initialize and run agent + const agent = await initializeAgent( + { + workingDirectory: options.installDir, + workOSApiKey: apiKey, + workOSApiHost: 'https://api.workos.com', + }, + options, + ); + + const agentResult = await runAgent( + agent, + integrationPrompt, + options, + { + spinnerMessage: SPINNER_MESSAGE, + successMessage: config.ui.successMessage, + errorMessage: 'Integration failed', + }, + options.emitter, + ); + + if (agentResult.error) { + await analytics.shutdown('error'); + const message = agentResult.errorMessage || agentResult.error; + throw new Error(`Agent SDK error: ${message}`); + } + + // Build summary + const changes = config.ui.getOutroChanges({}); + const nextSteps = config.ui.getOutroNextSteps({}); + + const lines: string[] = [ + 'Successfully installed WorkOS AuthKit!', + '', + 'What the agent did:', + ...changes.map((c) => `• ${c}`), + '', + 'Next steps:', + ...nextSteps.map((s) => `• ${s}`), + '', + `Learn more: ${config.metadata.docsUrl}`, + '', + 'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.', + ]; + + await analytics.shutdown('success'); + return lines.join('\n'); +} + +function buildElixirPrompt(): string { + return `You are integrating WorkOS AuthKit into this Elixir/Phoenix application. + +## Project Context + +- Framework: Phoenix (Elixir) +- Package manager: mix (Hex) + +## Environment + +The following environment variables have been configured in .env.local: +- WORKOS_API_KEY +- WORKOS_CLIENT_ID +- WORKOS_REDIRECT_URI + +Note: For Elixir/Phoenix, these should be read via System.get_env() in config/runtime.exs rather than from .env.local directly. + +## Your Task + +Use the \`workos-elixir\` skill to integrate WorkOS AuthKit into this application. + +The skill contains step-by-step instructions including: +1. Fetching the SDK documentation +2. Validating the Phoenix project structure +3. Installing the workos Hex package +4. Configuring WorkOS in runtime.exs +5. Creating auth controller and routes +6. Verification with mix compile + +Report your progress using [STATUS] prefixes. + +Begin by invoking the workos-elixir skill.`; +} diff --git a/src/integrations/go/index.ts b/src/integrations/go/index.ts new file mode 100644 index 0000000..bf2e6fe --- /dev/null +++ b/src/integrations/go/index.ts @@ -0,0 +1,263 @@ +/* Go integration — auto-discovered by registry */ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import { SPINNER_MESSAGE } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { analytics } from '../../utils/analytics.js'; +import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js'; +import { initializeAgent, runAgent } from '../../lib/agent-interface.js'; +import { getOrAskForWorkOSCredentials } from '../../utils/clack-utils.js'; +import { autoConfigureWorkOSEnvironment } from '../../lib/workos-management.js'; +import { validateInstallation } from '../../lib/validation/index.js'; +import { parseEnvFile } from '../../utils/env-parser.js'; + +/** Default port for Go HTTP servers */ +const GO_DEFAULT_PORT = 8080; +const GO_CALLBACK_PATH = '/auth/callback'; + +/** + * Detect whether go.mod includes the Gin web framework. + */ +function detectGoFramework(installDir: string): 'gin' | 'stdlib' { + try { + const goMod = readFileSync(join(installDir, 'go.mod'), 'utf-8'); + return goMod.includes('github.com/gin-gonic/gin') ? 'gin' : 'stdlib'; + } catch { + return 'stdlib'; + } +} + +/** + * Write environment variables to .env (Go convention, not .env.local). + * Merges with existing .env if present. + */ +function writeGoEnv(installDir: string, envVars: Record): void { + const envPath = join(installDir, '.env'); + let existing: Record = {}; + + if (existsSync(envPath)) { + existing = parseEnvFile(readFileSync(envPath, 'utf-8')); + } + + const merged = { ...existing, ...envVars }; + const content = Object.entries(merged) + .map(([key, value]) => `${key}=${value}`) + .join('\n'); + + writeFileSync(envPath, content + '\n'); +} + +export const config: FrameworkConfig = { + metadata: { + name: 'Go', + integration: 'go', + docsUrl: 'https://workos.com/docs/authkit/vanilla/go', + skillName: 'workos-go', + language: 'go', + stability: 'experimental', + priority: 50, + packageManager: 'go', + manifestFile: 'go.mod', + gatherContext: async (options) => { + return { framework: detectGoFramework(options.installDir) }; + }, + }, + + detection: { + packageName: 'github.com/workos/workos-go/v4', + packageDisplayName: 'Go', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: (context: any) => (context?.framework ? { 'go-framework': context.framework } : {}), + }, + + prompts: { + getAdditionalContextLines: (context: any) => [ + ...(context?.framework ? [`Go web framework: ${context.framework}`] : []), + ], + }, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Go project structure', + 'Installed workos-go SDK', + 'Created authentication handlers', + 'Configured environment variables', + ], + getOutroNextSteps: () => [ + 'Run `go run .` to start your server', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +/** + * Run the Go integration. + * + * Custom flow that bypasses runAgentInstaller because the universal runner + * assumes package.json exists (getPackageDotJson aborts without it) and + * port-detection/env-writer are JS-specific. + */ +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + options.emitter?.emit('status', { + message: `Setting up WorkOS AuthKit for ${config.metadata.name}`, + }); + + analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, { + action: 'started agent integration', + integration: config.metadata.integration, + }); + + // Get WorkOS credentials + const { apiKey, clientId } = await getOrAskForWorkOSCredentials(options, config.environment.requiresApiKey); + + // Auto-configure WorkOS environment (redirect URI, CORS) + const callerHandledConfig = Boolean(options.apiKey || options.clientId); + if (!callerHandledConfig && apiKey) { + const redirectUri = options.redirectUri || `http://localhost:${GO_DEFAULT_PORT}${GO_CALLBACK_PATH}`; + await autoConfigureWorkOSEnvironment(apiKey, config.metadata.integration, GO_DEFAULT_PORT, { + homepageUrl: options.homepageUrl, + redirectUri, + }); + } + + // Gather Go-specific context + const frameworkContext = config.metadata.gatherContext ? await config.metadata.gatherContext(options) : {}; + + // Write .env (not .env.local — Go convention) + if (!callerHandledConfig) { + const redirectUri = options.redirectUri || `http://localhost:${GO_DEFAULT_PORT}${GO_CALLBACK_PATH}`; + writeGoEnv(options.installDir, { + ...(apiKey ? { WORKOS_API_KEY: apiKey } : {}), + WORKOS_CLIENT_ID: clientId, + WORKOS_REDIRECT_URI: redirectUri, + }); + } + + // Set analytics tags + const contextTags = config.analytics.getTags(frameworkContext); + Object.entries(contextTags).forEach(([key, value]) => { + analytics.setTag(key, value); + }); + + // Build prompt + const additionalLines = config.prompts.getAdditionalContextLines + ? config.prompts.getAdditionalContextLines(frameworkContext) + : []; + const additionalContext = + additionalLines.length > 0 ? '\n' + additionalLines.map((line) => `- ${line}`).join('\n') : ''; + + const skillName = config.metadata.skillName!; + const integrationPrompt = `You are integrating WorkOS AuthKit into this ${config.metadata.name} application. + +## Project Context + +- Language: Go +- Framework: ${frameworkContext.framework === 'gin' ? 'Gin' : 'stdlib net/http'}${additionalContext} + +## Environment + +The following environment variables have been configured in .env: +- WORKOS_API_KEY +- WORKOS_CLIENT_ID +- WORKOS_REDIRECT_URI + +## Your Task + +Use the \`${skillName}\` skill to integrate WorkOS AuthKit into this application. + +The skill contains step-by-step instructions including: +1. Fetching the SDK documentation +2. Installing the SDK +3. Detecting Gin vs stdlib +4. Creating authentication handlers +5. Wiring handlers into the router +6. Verification with go build and go vet + +Report your progress using [STATUS] prefixes. + +Begin by invoking the ${skillName} skill.`; + + // Initialize and run agent + const agent = await initializeAgent( + { + workingDirectory: options.installDir, + workOSApiKey: apiKey, + workOSApiHost: 'https://api.workos.com', + }, + options, + ); + + const agentResult = await runAgent( + agent, + integrationPrompt, + options, + { + spinnerMessage: SPINNER_MESSAGE, + successMessage: config.ui.successMessage, + errorMessage: 'Integration failed', + }, + options.emitter, + ); + + if (agentResult.error) { + await analytics.shutdown('error'); + const message = agentResult.errorMessage || agentResult.error; + throw new Error(`Agent SDK error: ${message}`); + } + + // Post-installation validation (gracefully skips — no rules file for Go) + if (!options.noValidate) { + options.emitter?.emit('validation:start', { framework: config.metadata.integration }); + + const validationResult = await validateInstallation(config.metadata.integration, options.installDir, { + runBuild: true, + }); + + if (validationResult.issues.length > 0) { + options.emitter?.emit('validation:issues', { issues: validationResult.issues }); + } + + options.emitter?.emit('validation:complete', { + passed: validationResult.passed, + issueCount: validationResult.issues.length, + durationMs: validationResult.durationMs, + }); + } + + // Build summary + const changes = config.ui.getOutroChanges(frameworkContext).filter(Boolean); + const nextSteps = config.ui.getOutroNextSteps(frameworkContext).filter(Boolean); + + const lines: string[] = [ + 'Successfully installed WorkOS AuthKit!', + '', + ...(changes.length > 0 ? ['What the agent did:', ...changes.map((c) => `• ${c}`), ''] : []), + ...(nextSteps.length > 0 ? ['Next steps:', ...nextSteps.map((s) => `• ${s}`), ''] : []), + `Learn more: ${config.metadata.docsUrl}`, + '', + 'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.', + ]; + + await analytics.shutdown('success'); + + return lines.join('\n'); +} diff --git a/src/integrations/kotlin/index.ts b/src/integrations/kotlin/index.ts new file mode 100644 index 0000000..102077e --- /dev/null +++ b/src/integrations/kotlin/index.ts @@ -0,0 +1,63 @@ +/* Kotlin (Spring Boot) integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Kotlin (Spring Boot)', + integration: 'kotlin', + docsUrl: 'https://github.com/workos/workos-kotlin', + skillName: 'workos-kotlin', + language: 'kotlin', + stability: 'experimental', + priority: 40, + packageManager: 'gradle', + manifestFile: 'build.gradle.kts', + }, + + detection: { + packageName: 'com.workos:workos-kotlin', + packageDisplayName: 'Kotlin (Spring Boot)', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Kotlin/Spring Boot project structure', + 'Added WorkOS Kotlin SDK dependency to build.gradle.kts', + 'Created authentication controller with login, callback, and logout endpoints', + 'Configured application.properties with WorkOS credentials', + ], + getOutroNextSteps: () => [ + 'Run ./gradlew bootRun to start your application', + 'Visit http://localhost:8080/auth/login to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/node/index.ts b/src/integrations/node/index.ts new file mode 100644 index 0000000..7745ae0 --- /dev/null +++ b/src/integrations/node/index.ts @@ -0,0 +1,62 @@ +/* Node.js (Express) integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { getPackageVersion } from '../../utils/package-json.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Node.js (Express)', + integration: 'node', + docsUrl: 'https://workos.com/docs/authkit/vanilla/nodejs', + skillName: 'workos-node', + language: 'javascript', + stability: 'experimental', + priority: 70, + }, + + detection: { + packageName: 'express', + packageDisplayName: 'Express', + getVersion: (packageJson: any) => getPackageVersion('express', packageJson), + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Express project structure', + 'Installed and configured @workos-inc/node SDK', + 'Created authentication routes (/auth/login, /auth/callback, /auth/logout)', + 'Configured session management', + ], + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + 'For production, replace in-memory sessions with Redis or a database store', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/php-laravel/index.ts b/src/integrations/php-laravel/index.ts new file mode 100644 index 0000000..3001fcd --- /dev/null +++ b/src/integrations/php-laravel/index.ts @@ -0,0 +1,61 @@ +/* PHP Laravel integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'PHP (Laravel)', + integration: 'php-laravel', + docsUrl: 'https://github.com/workos/workos-php-laravel', + skillName: 'workos-php-laravel', + language: 'php', + stability: 'experimental', + priority: 45, + packageManager: 'composer', + manifestFile: 'composer.json', + }, + + detection: { + packageName: 'laravel/framework', + packageDisplayName: 'Laravel', + getVersion: (packageJson: any) => packageJson?.require?.['laravel/framework'], + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Laravel project structure', + 'Installed and configured WorkOS AuthKit Laravel SDK', + 'Created authentication controller and routes', + ], + getOutroNextSteps: () => [ + 'Run `php artisan serve` to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/php/index.ts b/src/integrations/php/index.ts new file mode 100644 index 0000000..608e6f3 --- /dev/null +++ b/src/integrations/php/index.ts @@ -0,0 +1,61 @@ +/* Generic PHP integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'PHP', + integration: 'php', + docsUrl: 'https://github.com/workos/workos-php', + skillName: 'workos-php', + language: 'php', + stability: 'experimental', + priority: 44, + packageManager: 'composer', + manifestFile: 'composer.json', + }, + + detection: { + packageName: 'php', + packageDisplayName: 'PHP', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your PHP project structure', + 'Installed and configured WorkOS PHP SDK', + 'Created authentication endpoint files', + ], + getOutroNextSteps: () => [ + 'Start your PHP development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/integrations/python/index.ts b/src/integrations/python/index.ts new file mode 100644 index 0000000..5bfe090 --- /dev/null +++ b/src/integrations/python/index.ts @@ -0,0 +1,292 @@ +/* Python/Django integration — auto-discovered by registry */ +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { analytics } from '../../utils/analytics.js'; +import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js'; +import { parseEnvFile } from '../../utils/env-parser.js'; + +/** + * Detect which Python package manager the project uses. + */ +function detectPythonPackageManager(installDir: string): { name: string; installCmd: string } { + if (existsSync(join(installDir, 'uv.lock'))) { + return { name: 'uv', installCmd: 'uv add' }; + } + + if (existsSync(join(installDir, 'pyproject.toml'))) { + try { + const content = readFileSync(join(installDir, 'pyproject.toml'), 'utf-8'); + if (content.includes('[tool.poetry]')) { + return { name: 'poetry', installCmd: 'poetry add' }; + } + } catch { + /* ignore */ + } + } + + if (existsSync(join(installDir, 'Pipfile'))) { + return { name: 'pipenv', installCmd: 'pipenv install' }; + } + + return { name: 'pip', installCmd: 'pip install' }; +} + +/** + * Detect if this is a Django project. + */ +function isDjangoProject(installDir: string): boolean { + if (existsSync(join(installDir, 'manage.py'))) return true; + + const pyprojectPath = join(installDir, 'pyproject.toml'); + if (existsSync(pyprojectPath)) { + try { + const content = readFileSync(pyprojectPath, 'utf-8'); + if (/django/i.test(content)) return true; + } catch { + /* ignore */ + } + } + + const reqPath = join(installDir, 'requirements.txt'); + if (existsSync(reqPath)) { + try { + const content = readFileSync(reqPath, 'utf-8'); + if (/^django/im.test(content)) return true; + } catch { + /* ignore */ + } + } + + return false; +} + +/** + * Write .env file for Python projects (not .env.local). + * Merges with existing .env. No cookie password generation. + */ +function writeEnvFile(installDir: string, envVars: Record): void { + const envPath = join(installDir, '.env'); + + let existingEnv: Record = {}; + if (existsSync(envPath)) { + try { + existingEnv = parseEnvFile(readFileSync(envPath, 'utf-8')); + } catch { + /* ignore */ + } + } + + const merged = { ...existingEnv, ...envVars }; + const content = Object.entries(merged) + .map(([key, value]) => `${key}=${value}`) + .join('\n'); + + writeFileSync(envPath, content + '\n'); +} + +export const config: FrameworkConfig = { + metadata: { + name: 'Python (Django)', + integration: 'python', + docsUrl: 'https://workos.com/docs/user-management/authkit/vanilla/python', + skillName: 'workos-python', + language: 'python', + stability: 'experimental', + priority: 60, + packageManager: 'pip', + manifestFile: 'pyproject.toml', + gatherContext: async (options: InstallerOptions) => { + const pkgMgr = detectPythonPackageManager(options.installDir); + return { + packageManager: pkgMgr.name, + installCommand: pkgMgr.installCmd, + isDjango: isDjangoProject(options.installDir), + }; + }, + }, + + detection: { + // Dummy values for FrameworkDetection interface compat — Python doesn't use package.json + packageName: 'workos', + packageDisplayName: 'Python (Django)', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: (context: any) => ({ + 'python-package-manager': context?.packageManager || 'unknown', + 'python-is-django': String(context?.isDjango ?? false), + }), + }, + + prompts: { + getAdditionalContextLines: (context: any) => { + const lines: string[] = []; + if (context?.packageManager) lines.push(`Package manager: ${context.packageManager}`); + if (context?.installCommand) lines.push(`Install command: ${context.installCommand}`); + if (context?.isDjango) lines.push('Framework: Django'); + return lines; + }, + }, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Python/Django project structure', + 'Installed WorkOS Python SDK', + 'Created authentication views (login, callback, logout)', + 'Configured URL routing and environment variables', + ], + getOutroNextSteps: () => [ + 'Run `python manage.py runserver` to test authentication', + 'Visit http://localhost:8000/auth/login to test the login flow', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +/** + * Build the agent prompt for Python/Django integration. + */ +function buildPythonPrompt( + frameworkContext: Record, +): string { + const contextLines = ['- Framework: Python (Django)']; + if (frameworkContext.packageManager) contextLines.push(`- Package manager: ${frameworkContext.packageManager}`); + if (frameworkContext.installCommand) contextLines.push(`- Install command: ${frameworkContext.installCommand}`); + + const skillName = config.metadata.skillName!; + + return `You are integrating WorkOS AuthKit into this Python/Django application. + +## Project Context + +${contextLines.join('\n')} + +## Environment + +The following environment variables have been configured in .env: +- WORKOS_API_KEY +- WORKOS_CLIENT_ID + +## Your Task + +Use the \`${skillName}\` skill to integrate WorkOS AuthKit into this application. + +The skill contains step-by-step instructions including: +1. Fetching the SDK documentation +2. Installing the SDK and python-dotenv +3. Configuring Django settings +4. Creating authentication views +5. Setting up URL routing +6. Adding authentication UI + +Report your progress using [STATUS] prefixes. + +Begin by invoking the ${skillName} skill.`; +} + +/** + * Custom run function that bypasses runAgentInstaller. + * Calls initializeAgent + runAgent directly, handling Python-specific + * env writing and prompt building. + */ +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + options.emitter?.emit('status', { + message: 'Setting up WorkOS AuthKit for Python (Django)', + }); + + const apiKey = options.apiKey || ''; + const clientId = options.clientId || ''; + + // Gather Python-specific context + const frameworkContext = config.metadata.gatherContext + ? await config.metadata.gatherContext(options) + : {}; + + analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, { + action: 'started agent integration', + integration: 'python', + }); + + // Set analytics tags + const contextTags = config.analytics.getTags(frameworkContext); + for (const [key, value] of Object.entries(contextTags)) { + analytics.setTag(key, value); + } + + // Write .env (not .env.local) with WorkOS credentials + writeEnvFile(options.installDir, { + ...(apiKey ? { WORKOS_API_KEY: apiKey } : {}), + WORKOS_CLIENT_ID: clientId, + }); + + // Build Python-specific prompt + const prompt = buildPythonPrompt(frameworkContext); + + // Initialize and run agent directly (bypass runAgentInstaller) + const { initializeAgent, runAgent } = await import('../../lib/agent-interface.js'); + + const agentConfig = await initializeAgent( + { + workingDirectory: options.installDir, + workOSApiKey: apiKey, + workOSApiHost: 'https://api.workos.com', + }, + options, + ); + + const result = await runAgent( + agentConfig, + prompt, + options, + { + spinnerMessage: 'Setting up WorkOS AuthKit for Python/Django...', + successMessage: config.ui.successMessage, + errorMessage: 'Python integration failed', + }, + options.emitter, + ); + + if (result.error) { + await analytics.shutdown('error'); + throw new Error(`Agent error: ${result.errorMessage || result.error}`); + } + + // Build completion summary + const changes = config.ui.getOutroChanges({}); + const nextSteps = config.ui.getOutroNextSteps({}); + + const lines: string[] = [ + 'Successfully installed WorkOS AuthKit!', + '', + 'What the agent did:', + ...changes.map((c) => `• ${c}`), + '', + 'Next steps:', + ...nextSteps.map((s) => `• ${s}`), + '', + `Learn more: ${config.metadata.docsUrl}`, + '', + 'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.', + ]; + + await analytics.shutdown('success'); + return lines.join('\n'); +} diff --git a/src/integrations/ruby/index.ts b/src/integrations/ruby/index.ts new file mode 100644 index 0000000..bbd4c70 --- /dev/null +++ b/src/integrations/ruby/index.ts @@ -0,0 +1,172 @@ +/* Ruby/Rails integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { SPINNER_MESSAGE } from '../../lib/framework-config.js'; +import { analytics } from '../../utils/analytics.js'; +import { INSTALLER_INTERACTION_EVENT_NAME } from '../../lib/constants.js'; +import { initializeAgent, runAgent } from '../../lib/agent-interface.js'; +import { getOrAskForWorkOSCredentials } from '../../utils/clack-utils.js'; +import { autoConfigureWorkOSEnvironment } from '../../lib/workos-management.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'Ruby (Rails)', + integration: 'ruby', + docsUrl: 'https://workos.com/docs/authkit/vanilla/ruby', + skillName: 'workos-ruby', + language: 'ruby', + stability: 'experimental', + priority: 55, + packageManager: 'bundle', + manifestFile: 'Gemfile', + }, + + detection: { + packageName: 'rails', + packageDisplayName: 'Rails', + getVersion: () => undefined, + }, + + environment: { + uploadToHosting: false, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your Rails project structure', + 'Installed and configured the WorkOS Ruby SDK', + 'Created authentication controller with login, callback, and logout', + 'Added authentication routes to config/routes.rb', + ], + getOutroNextSteps: () => [ + 'Start your Rails server with `rails server` to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +/** + * Custom run function for Ruby/Rails — bypasses runAgentInstaller + * since that assumes a JS project (package.json, node_modules, .env.local). + */ +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + options.emitter?.emit('status', { + message: `Setting up WorkOS AuthKit for ${config.metadata.name}`, + }); + + analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, { + action: 'started agent integration', + integration: config.metadata.integration, + }); + + // Get WorkOS credentials + const { apiKey, clientId } = await getOrAskForWorkOSCredentials(options, config.environment.requiresApiKey); + + // Auto-configure WorkOS environment (redirect URI, CORS, homepage) if not already done + const callerHandledConfig = Boolean(options.apiKey || options.clientId); + if (!callerHandledConfig && apiKey) { + const port = 3000; // Rails default + await autoConfigureWorkOSEnvironment(apiKey, config.metadata.integration, port, { + homepageUrl: options.homepageUrl, + redirectUri: options.redirectUri, + }); + } + + // Build prompt for the agent + const redirectUri = options.redirectUri || 'http://localhost:3000/auth/callback'; + const prompt = `You are integrating WorkOS AuthKit into this Ruby on Rails application. + +## Project Context + +- Framework: Ruby (Rails) +- Language: Ruby + +## Environment + +The following environment variables should be configured in a .env file: +- WORKOS_API_KEY=${apiKey ? '(provided)' : '(not set)'} +- WORKOS_CLIENT_ID=${clientId || '(not set)'} +- WORKOS_REDIRECT_URI=${redirectUri} + +## Your Task + +Use the \`workos-ruby\` skill to integrate WorkOS AuthKit into this application. + +The skill contains step-by-step instructions including: +1. Fetching the SDK documentation +2. Installing the WorkOS Ruby gem +3. Creating the WorkOS initializer +4. Creating the AuthController with login, callback, and logout +5. Adding authentication routes + +Report your progress using [STATUS] prefixes. + +Begin by invoking the workos-ruby skill.`; + + // Initialize and run agent + const agent = await initializeAgent( + { + workingDirectory: options.installDir, + workOSApiKey: apiKey, + workOSApiHost: 'https://api.workos.com', + }, + options, + ); + + const agentResult = await runAgent( + agent, + prompt, + options, + { + spinnerMessage: SPINNER_MESSAGE, + successMessage: config.ui.successMessage, + errorMessage: 'Integration failed', + }, + options.emitter, + ); + + if (agentResult.error) { + await analytics.shutdown('error'); + const message = agentResult.errorMessage || agentResult.error; + throw new Error(`Agent SDK error: ${message}`); + } + + // Build completion summary + const changes = config.ui.getOutroChanges({}); + const nextSteps = config.ui.getOutroNextSteps({}); + + const lines: string[] = [ + 'Successfully installed WorkOS AuthKit!', + '', + 'What the agent did:', + ...changes.map((c) => `• ${c}`), + '', + 'Next steps:', + ...nextSteps.map((s) => `• ${s}`), + '', + `Learn more: ${config.metadata.docsUrl}`, + '', + 'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.', + ]; + + await analytics.shutdown('success'); + + return lines.join('\n'); +} diff --git a/src/integrations/sveltekit/index.ts b/src/integrations/sveltekit/index.ts new file mode 100644 index 0000000..f61862f --- /dev/null +++ b/src/integrations/sveltekit/index.ts @@ -0,0 +1,60 @@ +/* SvelteKit integration — auto-discovered by registry */ +import type { FrameworkConfig } from '../../lib/framework-config.js'; +import type { InstallerOptions } from '../../utils/types.js'; +import { enableDebugLogs } from '../../utils/debug.js'; +import { getPackageVersion } from '../../utils/package-json.js'; + +export const config: FrameworkConfig = { + metadata: { + name: 'SvelteKit', + integration: 'sveltekit', + docsUrl: 'https://github.com/workos/authkit-sveltekit', + skillName: 'workos-authkit-sveltekit', + language: 'javascript', + stability: 'experimental', + priority: 85, + }, + + detection: { + packageName: '@sveltejs/kit', + packageDisplayName: 'SvelteKit', + getVersion: (packageJson: any) => getPackageVersion('@sveltejs/kit', packageJson), + }, + + environment: { + uploadToHosting: true, + requiresApiKey: true, + getEnvVars: (apiKey: string, clientId: string) => ({ + WORKOS_API_KEY: apiKey, + WORKOS_CLIENT_ID: clientId, + }), + }, + + analytics: { + getTags: () => ({}), + }, + + prompts: {}, + + ui: { + successMessage: 'WorkOS AuthKit integration complete', + getOutroChanges: () => [ + 'Analyzed your SvelteKit project structure', + 'Created and configured WorkOS AuthKit', + 'Integrated authentication into your application', + ], + getOutroNextSteps: () => [ + 'Start your development server to test authentication', + 'Visit the WorkOS Dashboard to manage users and settings', + ], + }, +}; + +export async function run(options: InstallerOptions): Promise { + if (options.debug) { + enableDebugLogs(); + } + + const { runAgentInstaller } = await import('../../lib/agent-runner.js'); + return runAgentInstaller(config, options); +} diff --git a/src/lib/port-detection.ts b/src/lib/port-detection.ts index eb94c7b..f8f6477 100644 --- a/src/lib/port-detection.ts +++ b/src/lib/port-detection.ts @@ -13,14 +13,17 @@ const INTEGRATION_TO_SETTINGS_KEY: Record = { 'vanilla-js': 'vanillaJs', }; +const DEFAULT_PORT = 3000; +const DEFAULT_CALLBACK_PATH = '/auth/callback'; + function getDefaultPort(integration: Integration): number { const settingsKey = INTEGRATION_TO_SETTINGS_KEY[integration]; - return settings.frameworks[settingsKey].port; + return settings.frameworks[settingsKey]?.port ?? DEFAULT_PORT; } export function getCallbackPath(integration: Integration): string { const settingsKey = INTEGRATION_TO_SETTINGS_KEY[integration]; - return settings.frameworks[settingsKey].callbackPath; + return settings.frameworks[settingsKey]?.callbackPath ?? DEFAULT_CALLBACK_PATH; } /** From ce4d0d5cef04b57c96dcec89712421b896681f72 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 9 Feb 2026 15:07:25 -0600 Subject: [PATCH 03/12] feat: extend eval system for 10 new SDK integrations Add graders, scenarios, and infrastructure for SvelteKit, Node.js, Python, Ruby, Go, PHP, PHP-Laravel, Kotlin, .NET, and Elixir evals. - Language-aware fixture manager (pip, bundle, go mod, composer, mix, dotnet restore, gradle) - Generic checkCommand() in BuildGrader for non-JS validation - Agent executor uses string-keyed skill names, writes .env for non-JS frameworks - 10 new grader files with framework-specific checks - 34 total scenarios (24 existing + 10 new) --- tests/evals/agent-executor.ts | 71 +++++++++++++++------ tests/evals/cli.ts | 7 +- tests/evals/fixture-manager.ts | 78 ++++++++++++++++++++--- tests/evals/graders/build-grader.ts | 21 ++++++ tests/evals/graders/dotnet.grader.ts | 55 ++++++++++++++++ tests/evals/graders/elixir.grader.ts | 51 +++++++++++++++ tests/evals/graders/go.grader.ts | 47 ++++++++++++++ tests/evals/graders/kotlin.grader.ts | 41 ++++++++++++ tests/evals/graders/node.grader.ts | 51 +++++++++++++++ tests/evals/graders/php-laravel.grader.ts | 55 ++++++++++++++++ tests/evals/graders/php.grader.ts | 45 +++++++++++++ tests/evals/graders/python.grader.ts | 55 ++++++++++++++++ tests/evals/graders/ruby.grader.ts | 51 +++++++++++++++ tests/evals/graders/sveltekit.grader.ts | 59 +++++++++++++++++ tests/evals/quality-key-files.ts | 28 ++++++++ tests/evals/runner.ts | 23 +++++++ tests/evals/versioning.spec.ts | 6 +- tests/evals/versioning.ts | 22 +++++-- 18 files changed, 730 insertions(+), 36 deletions(-) create mode 100644 tests/evals/graders/dotnet.grader.ts create mode 100644 tests/evals/graders/elixir.grader.ts create mode 100644 tests/evals/graders/go.grader.ts create mode 100644 tests/evals/graders/kotlin.grader.ts create mode 100644 tests/evals/graders/node.grader.ts create mode 100644 tests/evals/graders/php-laravel.grader.ts create mode 100644 tests/evals/graders/php.grader.ts create mode 100644 tests/evals/graders/python.grader.ts create mode 100644 tests/evals/graders/ruby.grader.ts create mode 100644 tests/evals/graders/sveltekit.grader.ts diff --git a/tests/evals/agent-executor.ts b/tests/evals/agent-executor.ts index ad072b6..3c4b0cd 100644 --- a/tests/evals/agent-executor.ts +++ b/tests/evals/agent-executor.ts @@ -1,8 +1,10 @@ import path from 'node:path'; +import { writeFileSync, existsSync, readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { Integration } from '../../src/lib/constants.js'; import { loadCredentials } from './env-loader.js'; import { writeEnvLocal } from '../../src/lib/env-writer.js'; +import { parseEnvFile } from '../../src/utils/env-parser.js'; import { getConfig } from '../../src/lib/settings.js'; import { LatencyTracker } from './latency-tracker.js'; import type { ToolCall, LatencyMetrics } from './types.js'; @@ -21,14 +23,45 @@ export interface AgentExecutorOptions { } // Skill name mapping for each framework -const SKILL_NAMES: Record = { - [Integration.nextjs]: 'workos-authkit-nextjs', - [Integration.react]: 'workos-authkit-react', - [Integration.reactRouter]: 'workos-authkit-react-router', - [Integration.tanstackStart]: 'workos-authkit-tanstack-start', - [Integration.vanillaJs]: 'workos-authkit-vanilla-js', +const SKILL_NAMES: Record = { + nextjs: 'workos-authkit-nextjs', + react: 'workos-authkit-react', + 'react-router': 'workos-authkit-react-router', + 'tanstack-start': 'workos-authkit-tanstack-start', + 'vanilla-js': 'workos-authkit-vanilla-js', + // New SDKs + sveltekit: 'workos-authkit-sveltekit', + node: 'workos-node', + python: 'workos-python', + ruby: 'workos-ruby', + go: 'workos-go', + php: 'workos-php', + 'php-laravel': 'workos-php-laravel', + kotlin: 'workos-kotlin', + dotnet: 'workos-dotnet', + elixir: 'workos-elixir', }; +/** Frameworks that use package.json / .env.local */ +const JS_FRAMEWORKS = ['nextjs', 'react', 'react-router', 'tanstack-start', 'vanilla-js', 'sveltekit', 'node']; + +/** + * Write a .env file (for non-JS frameworks). + * Merges with existing .env if present. + */ +function writeEnvFile(workDir: string, envVars: Record): void { + const envPath = join(workDir, '.env'); + let existing: Record = {}; + if (existsSync(envPath)) { + existing = parseEnvFile(readFileSync(envPath, 'utf-8')); + } + const merged = { ...existing, ...envVars }; + const content = Object.entries(merged) + .map(([key, value]) => `${key}=${value}`) + .join('\n'); + writeFileSync(envPath, content + '\n'); +} + export class AgentExecutor { private options: AgentExecutorOptions; private credentials: ReturnType; @@ -57,11 +90,17 @@ export class AgentExecutor { // Start latency tracking this.latencyTracker.start(); - // Write .env.local with credentials (agent configures redirect URI per framework) - writeEnvLocal(this.workDir, { + // Write credentials to appropriate env file based on framework + const envVars = { WORKOS_API_KEY: this.credentials.workosApiKey, WORKOS_CLIENT_ID: this.credentials.workosClientId, - }); + }; + + if (JS_FRAMEWORKS.includes(this.framework)) { + writeEnvLocal(this.workDir, envVars); + } else { + writeEnvFile(this.workDir, envVars); + } // Build prompt const skillName = SKILL_NAMES[integration]; @@ -191,14 +230,8 @@ Begin by invoking the ${skillName} skill.`; } } - private getIntegration(): Integration { - const map: Record = { - nextjs: Integration.nextjs, - react: Integration.react, - 'react-router': Integration.reactRouter, - 'tanstack-start': Integration.tanstackStart, - 'vanilla-js': Integration.vanillaJs, - }; - return map[this.framework]; + private getIntegration(): string { + // Integration is now a string type — framework name IS the integration name + return this.framework; } } diff --git a/tests/evals/cli.ts b/tests/evals/cli.ts index bfda37d..b2a0aaf 100644 --- a/tests/evals/cli.ts +++ b/tests/evals/cli.ts @@ -20,7 +20,12 @@ export interface CliOptions { pruneKeep?: number; } -const FRAMEWORKS = ['nextjs', 'react', 'react-router', 'tanstack-start', 'vanilla-js']; +const FRAMEWORKS = [ + 'nextjs', 'react', 'react-router', 'tanstack-start', 'vanilla-js', + // New SDKs + 'sveltekit', 'node', 'python', 'ruby', 'go', + 'php', 'php-laravel', 'kotlin', 'dotnet', 'elixir', +]; const STATES = [ 'example', 'example-auth0', diff --git a/tests/evals/fixture-manager.ts b/tests/evals/fixture-manager.ts index eae3fdc..5de9961 100644 --- a/tests/evals/fixture-manager.ts +++ b/tests/evals/fixture-manager.ts @@ -1,4 +1,5 @@ import { cp, rm, mkdtemp } from 'node:fs/promises'; +import { existsSync, readdirSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { execFileNoThrow } from '../../src/utils/exec-file.js'; @@ -29,15 +30,9 @@ export class FixtureManager { await cp(fixtureSource, this.tempDir, { recursive: true }); - // Install dependencies using safe exec + // Install dependencies — detect language and use appropriate package manager console.log(' Installing dependencies...'); - const result = await execFileNoThrow('pnpm', ['install'], { - cwd: this.tempDir, - }); - - if (result.status !== 0) { - throw new Error(`pnpm install failed: ${result.stderr}`); - } + await this.installDependencies(this.tempDir); // Initialize git repo for diff capture (quality grading) await execFileNoThrow('git', ['init'], { cwd: this.tempDir }); @@ -57,4 +52,71 @@ export class FixtureManager { getTempDir(): string | null { return this.tempDir; } + + /** + * Detect project language and install dependencies using the appropriate package manager. + */ + private async installDependencies(workDir: string): Promise { + // JS projects + if (existsSync(join(workDir, 'package.json'))) { + const result = await execFileNoThrow('pnpm', ['install'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`pnpm install failed: ${result.stderr}`); + return; + } + + // Python + if (existsSync(join(workDir, 'requirements.txt'))) { + const result = await execFileNoThrow('pip', ['install', '-r', 'requirements.txt'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`pip install failed: ${result.stderr}`); + return; + } + if (existsSync(join(workDir, 'pyproject.toml'))) { + const result = await execFileNoThrow('pip', ['install', '-e', '.'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`pip install failed: ${result.stderr}`); + return; + } + + // Ruby + if (existsSync(join(workDir, 'Gemfile'))) { + const result = await execFileNoThrow('bundle', ['install'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`bundle install failed: ${result.stderr}`); + return; + } + + // Go + if (existsSync(join(workDir, 'go.mod'))) { + const result = await execFileNoThrow('go', ['mod', 'download'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`go mod download failed: ${result.stderr}`); + return; + } + + // PHP + if (existsSync(join(workDir, 'composer.json'))) { + const result = await execFileNoThrow('composer', ['install', '--no-interaction'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`composer install failed: ${result.stderr}`); + return; + } + + // Elixir + if (existsSync(join(workDir, 'mix.exs'))) { + const result = await execFileNoThrow('mix', ['deps.get'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`mix deps.get failed: ${result.stderr}`); + return; + } + + // .NET + const csprojFiles = readdirSync(workDir).filter((f) => f.endsWith('.csproj')); + if (csprojFiles.length > 0) { + const result = await execFileNoThrow('dotnet', ['restore'], { cwd: workDir }); + if (result.status !== 0) throw new Error(`dotnet restore failed: ${result.stderr}`); + return; + } + + // Kotlin/Gradle — deps resolved at build time, skip + if (existsSync(join(workDir, 'build.gradle.kts')) || existsSync(join(workDir, 'build.gradle'))) { + return; + } + + console.warn(' No recognized dependency manifest found, skipping install'); + } } diff --git a/tests/evals/graders/build-grader.ts b/tests/evals/graders/build-grader.ts index 9834ac1..eb5b205 100644 --- a/tests/evals/graders/build-grader.ts +++ b/tests/evals/graders/build-grader.ts @@ -24,6 +24,27 @@ export class BuildGrader { }; } + /** + * Run an arbitrary command as a grading check. + * Used for non-JS build/validation commands (e.g., go build, python -m py_compile, ruby -c). + */ + async checkCommand(cmd: string, args: string[], name: string, timeout = 120000): Promise { + const result = await execFileNoThrow(cmd, args, { + cwd: this.workDir, + timeout, + }); + + if (result.status === 0) { + return { name, passed: true }; + } + + return { + name, + passed: false, + message: `${cmd} ${args.join(' ')} failed: ${result.stderr.slice(0, 500)}`, + }; + } + async checkTypecheck(): Promise { const result = await execFileNoThrow('pnpm', ['tsc', '--noEmit'], { cwd: this.workDir, diff --git a/tests/evals/graders/dotnet.grader.ts b/tests/evals/graders/dotnet.grader.ts new file mode 100644 index 0000000..c149048 --- /dev/null +++ b/tests/evals/graders/dotnet.grader.ts @@ -0,0 +1,55 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * .NET Grader + * + * SDK: WorkOS (NuGet) + * + * Key patterns: + * - WorkOS in *.csproj + * - Program.cs contains auth routes + * - dotnet build passes + */ +export class DotnetGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check WorkOS in *.csproj + checks.push( + await this.fileGrader.checkFileWithPattern( + '**/*.csproj', + ['WorkOS'], + 'WorkOS package reference in .csproj', + ), + ); + + // Check Program.cs contains auth routes + checks.push( + await this.fileGrader.checkFileWithPattern( + '**/Program.cs', + [/auth|authorization|callback/i], + 'Program.cs contains auth routes', + ), + ); + + // Check dotnet build passes + checks.push( + await this.buildGrader.checkCommand('dotnet', ['build'], 'dotnet build'), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/elixir.grader.ts b/tests/evals/graders/elixir.grader.ts new file mode 100644 index 0000000..695a6dc --- /dev/null +++ b/tests/evals/graders/elixir.grader.ts @@ -0,0 +1,51 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Elixir Grader + * + * SDK: workos (Hex) + * + * Key patterns: + * - workos in mix.exs + * - Auth controller exists + * - mix compile passes + */ +export class ElixirGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in mix.exs + checks.push( + ...(await this.fileGrader.checkFileContains('mix.exs', ['workos'])), + ); + + // Check auth controller exists + checks.push( + await this.fileGrader.checkFileWithPattern( + 'lib/**/*controller*.ex', + [/auth|authorization|callback/i], + 'Auth controller exists', + ), + ); + + // Check mix compile passes + checks.push( + await this.buildGrader.checkCommand('mix', ['compile'], 'mix compile'), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/go.grader.ts b/tests/evals/graders/go.grader.ts new file mode 100644 index 0000000..83d0ff8 --- /dev/null +++ b/tests/evals/graders/go.grader.ts @@ -0,0 +1,47 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Go Grader + * + * SDK: workos (Go module) + * + * Key patterns: + * - workos in go.mod + * - go build ./... passes + * - go vet ./... passes + */ +export class GoGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in go.mod + checks.push( + ...(await this.fileGrader.checkFileContains('go.mod', ['workos'])), + ); + + // Check go build ./... passes + checks.push( + await this.buildGrader.checkCommand('go', ['build', './...'], 'go build ./...'), + ); + + // Check go vet ./... passes + checks.push( + await this.buildGrader.checkCommand('go', ['vet', './...'], 'go vet ./...'), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/kotlin.grader.ts b/tests/evals/graders/kotlin.grader.ts new file mode 100644 index 0000000..628f9a4 --- /dev/null +++ b/tests/evals/graders/kotlin.grader.ts @@ -0,0 +1,41 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Kotlin Grader + * + * SDK: workos (Gradle) + * + * Key patterns: + * - workos in build.gradle.kts + * - ./gradlew build passes (180s timeout for JVM cold start) + */ +export class KotlinGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in build.gradle.kts + checks.push( + ...(await this.fileGrader.checkFileContains('build.gradle.kts', ['workos'])), + ); + + // Check ./gradlew build passes (180s timeout for JVM cold start) + checks.push( + await this.buildGrader.checkCommand('./gradlew', ['build'], './gradlew build', 180000), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/node.grader.ts b/tests/evals/graders/node.grader.ts new file mode 100644 index 0000000..d5f44ca --- /dev/null +++ b/tests/evals/graders/node.grader.ts @@ -0,0 +1,51 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Node.js Grader + * + * SDK: @workos-inc/node + * + * Key patterns: + * - @workos-inc/node in package.json + * - server.js contains getAuthorizationUrl, authenticateWithCode, loadSealedSession + * - node --check server.js passes syntax validation + */ +export class NodeGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check @workos-inc/node in package.json + checks.push( + ...(await this.fileGrader.checkFileContains('package.json', ['@workos-inc/node'])), + ); + + // Check server.js contains required auth functions + checks.push( + ...(await this.fileGrader.checkFileContains('server.js', [ + 'getAuthorizationUrl', + 'authenticateWithCode', + 'loadSealedSession', + ])), + ); + + // Check node --check server.js passes + checks.push( + await this.buildGrader.checkCommand('node', ['--check', 'server.js'], 'node --check server.js'), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/php-laravel.grader.ts b/tests/evals/graders/php-laravel.grader.ts new file mode 100644 index 0000000..7bd70fc --- /dev/null +++ b/tests/evals/graders/php-laravel.grader.ts @@ -0,0 +1,55 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * PHP Laravel Grader + * + * SDK: workos (Composer, Laravel integration) + * + * Key patterns: + * - workos in composer.json + * - Auth controller exists + * - Routes contain auth paths + */ +export class PhpLaravelGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in composer.json + checks.push( + ...(await this.fileGrader.checkFileContains('composer.json', ['workos'])), + ); + + // Check auth controller exists + checks.push( + await this.fileGrader.checkFileWithPattern( + 'app/Http/Controllers/**/*.php', + ['workos'], + 'Auth controller exists with WorkOS integration', + ), + ); + + // Check routes contain auth paths + checks.push( + await this.fileGrader.checkFileWithPattern( + 'routes/**/*.php', + [/auth|login|callback/], + 'Routes contain auth paths', + ), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/php.grader.ts b/tests/evals/graders/php.grader.ts new file mode 100644 index 0000000..45cc6b8 --- /dev/null +++ b/tests/evals/graders/php.grader.ts @@ -0,0 +1,45 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * PHP Grader + * + * SDK: workos (Composer) + * + * Key patterns: + * - workos in composer.json + * - Auth endpoint files exist + */ +export class PhpGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in composer.json + checks.push( + ...(await this.fileGrader.checkFileContains('composer.json', ['workos'])), + ); + + // Check auth endpoint files exist + checks.push( + await this.fileGrader.checkFileWithPattern( + '**/*.php', + ['workos'], + 'Auth endpoint files contain WorkOS integration', + ), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/python.grader.ts b/tests/evals/graders/python.grader.ts new file mode 100644 index 0000000..e80ce62 --- /dev/null +++ b/tests/evals/graders/python.grader.ts @@ -0,0 +1,55 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Python Grader + * + * SDK: workos (PyPI) + * + * Key patterns: + * - workos in requirements.txt + * - server.py contains get_authorization_url, authenticate_with_code, load_sealed_session + * - python -m py_compile server.py passes syntax validation + */ +export class PythonGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in requirements.txt + checks.push( + ...(await this.fileGrader.checkFileContains('requirements.txt', ['workos'])), + ); + + // Check server.py contains required auth functions + checks.push( + ...(await this.fileGrader.checkFileContains('server.py', [ + 'get_authorization_url', + 'authenticate_with_code', + 'load_sealed_session', + ])), + ); + + // Check python -m py_compile server.py passes + checks.push( + await this.buildGrader.checkCommand( + 'python', + ['-m', 'py_compile', 'server.py'], + 'python -m py_compile server.py', + ), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/ruby.grader.ts b/tests/evals/graders/ruby.grader.ts new file mode 100644 index 0000000..1551eef --- /dev/null +++ b/tests/evals/graders/ruby.grader.ts @@ -0,0 +1,51 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * Ruby Grader + * + * SDK: workos (RubyGems) + * + * Key patterns: + * - workos in Gemfile + * - server.rb contains authorization_url, authenticate_with_code, load_sealed_session + * - ruby -c server.rb passes syntax validation + */ +export class RubyGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check workos in Gemfile + checks.push( + ...(await this.fileGrader.checkFileContains('Gemfile', ['workos'])), + ); + + // Check server.rb contains required auth functions + checks.push( + ...(await this.fileGrader.checkFileContains('server.rb', [ + 'authorization_url', + 'authenticate_with_code', + 'load_sealed_session', + ])), + ); + + // Check ruby -c server.rb passes syntax check + checks.push( + await this.buildGrader.checkCommand('ruby', ['-c', 'server.rb'], 'ruby -c server.rb'), + ); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/graders/sveltekit.grader.ts b/tests/evals/graders/sveltekit.grader.ts new file mode 100644 index 0000000..6fbe084 --- /dev/null +++ b/tests/evals/graders/sveltekit.grader.ts @@ -0,0 +1,59 @@ +import { FileGrader } from './file-grader.js'; +import { BuildGrader } from './build-grader.js'; +import type { Grader, GradeResult, GradeCheck } from '../types.js'; + +/** + * SvelteKit Grader + * + * SDK: @workos-inc/authkit-sveltekit + * + * Key patterns: + * - @workos-inc/authkit-sveltekit in package.json + * - hooks.server.ts exists for server-side auth hooks + * - Callback route exists for OAuth redirect + * - pnpm build passes + */ +export class SvelteKitGrader implements Grader { + private fileGrader: FileGrader; + private buildGrader: BuildGrader; + + constructor(workDir: string) { + this.fileGrader = new FileGrader(workDir); + this.buildGrader = new BuildGrader(workDir); + } + + async grade(): Promise { + const checks: GradeCheck[] = []; + + // Check @workos-inc/authkit-sveltekit in package.json + checks.push( + ...(await this.fileGrader.checkFileContains('package.json', ['@workos-inc/authkit-sveltekit'])), + ); + + // Check hooks.server.ts exists + checks.push( + await this.fileGrader.checkFileWithPattern( + 'src/hooks.server.ts', + ['@workos-inc/authkit-sveltekit'], + 'hooks.server.ts exists with AuthKit integration', + ), + ); + + // Check callback route exists + checks.push( + await this.fileGrader.checkFileWithPattern( + 'src/routes/**/+server.ts', + ['@workos-inc/authkit-sveltekit'], + 'Callback route exists', + ), + ); + + // Check build succeeds + checks.push(await this.buildGrader.checkBuild()); + + return { + passed: checks.every((c) => c.passed), + checks, + }; + } +} diff --git a/tests/evals/quality-key-files.ts b/tests/evals/quality-key-files.ts index 3bb8b0f..0ef3299 100644 --- a/tests/evals/quality-key-files.ts +++ b/tests/evals/quality-key-files.ts @@ -64,4 +64,32 @@ export const QUALITY_KEY_FILES: Record = { // HTML entry 'index.html', ], + + // New SDKs + sveltekit: [ + 'src/hooks.server.ts', + 'src/routes/callback/+server.ts', + 'src/routes/+layout.server.ts', + 'src/routes/+page.svelte', + ], + node: ['server.js', 'server.ts', 'src/index.ts', 'index.html'], + python: ['server.py', 'app.py', 'index.html'], + ruby: ['server.rb', 'app.rb', 'index.html'], + go: ['main.go', 'handlers/**/*.go', 'auth/**/*.go'], + php: ['public/index.php', 'login.php', 'callback.php'], + 'php-laravel': [ + 'app/Http/Controllers/*Auth*.php', + 'routes/web.php', + 'config/workos.php', + ], + kotlin: [ + 'src/main/kotlin/**/*Controller*.kt', + 'src/main/resources/application.properties', + ], + dotnet: ['Program.cs', '*.csproj'], + elixir: [ + 'lib/*_web/controllers/*auth*.ex', + 'lib/*_web/router.ex', + 'config/runtime.exs', + ], }; diff --git a/tests/evals/runner.ts b/tests/evals/runner.ts index f81f6d3..ff06374 100644 --- a/tests/evals/runner.ts +++ b/tests/evals/runner.ts @@ -3,6 +3,17 @@ import { ReactGrader } from './graders/react.grader.js'; import { ReactRouterGrader } from './graders/react-router.grader.js'; import { TanstackGrader } from './graders/tanstack.grader.js'; import { VanillaGrader } from './graders/vanilla.grader.js'; +// New SDK graders +import { SvelteKitGrader } from './graders/sveltekit.grader.js'; +import { NodeGrader } from './graders/node.grader.js'; +import { PythonGrader } from './graders/python.grader.js'; +import { RubyGrader } from './graders/ruby.grader.js'; +import { GoGrader } from './graders/go.grader.js'; +import { PhpGrader } from './graders/php.grader.js'; +import { PhpLaravelGrader } from './graders/php-laravel.grader.js'; +import { KotlinGrader } from './graders/kotlin.grader.js'; +import { DotnetGrader } from './graders/dotnet.grader.js'; +import { ElixirGrader } from './graders/elixir.grader.js'; import { saveResults } from './history.js'; import { ParallelRunner } from './parallel-runner.js'; import { renderDashboard } from './dashboard/index.js'; @@ -53,6 +64,18 @@ const SCENARIOS: Scenario[] = [ { framework: 'vanilla-js', state: 'example-auth0', grader: VanillaGrader }, { framework: 'vanilla-js', state: 'partial-install', grader: VanillaGrader }, { framework: 'vanilla-js', state: 'conflicting-auth', grader: VanillaGrader }, + + // New SDKs (1 state each — happy path) + { framework: 'sveltekit', state: 'example', grader: SvelteKitGrader }, + { framework: 'node', state: 'example', grader: NodeGrader }, + { framework: 'python', state: 'example', grader: PythonGrader }, + { framework: 'ruby', state: 'example', grader: RubyGrader }, + { framework: 'go', state: 'example', grader: GoGrader }, + { framework: 'php', state: 'example', grader: PhpGrader }, + { framework: 'php-laravel', state: 'example', grader: PhpLaravelGrader }, + { framework: 'kotlin', state: 'example', grader: KotlinGrader }, + { framework: 'dotnet', state: 'example', grader: DotnetGrader }, + { framework: 'elixir', state: 'example', grader: ElixirGrader }, ]; export interface ExtendedEvalOptions extends EvalOptions { diff --git a/tests/evals/versioning.spec.ts b/tests/evals/versioning.spec.ts index 615f50d..d30a71d 100644 --- a/tests/evals/versioning.spec.ts +++ b/tests/evals/versioning.spec.ts @@ -91,9 +91,9 @@ describe('versioning', () => { const metadata = await captureVersionMetadata(); - // Should have called git hash-object for each framework - expect(execFileNoThrow).toHaveBeenCalledTimes(5); - expect(Object.keys(metadata.skillVersions)).toHaveLength(5); + // Should have called git hash-object for each framework (15 total: 5 original + 10 new) + expect(execFileNoThrow).toHaveBeenCalledTimes(15); + expect(Object.keys(metadata.skillVersions)).toHaveLength(15); }); it('handles mixed success/failure gracefully', async () => { diff --git a/tests/evals/versioning.ts b/tests/evals/versioning.ts index 6418a4f..1f3c16a 100644 --- a/tests/evals/versioning.ts +++ b/tests/evals/versioning.ts @@ -8,11 +8,23 @@ import { join } from 'node:path'; * Used to compute git hashes for version tracking. */ const SKILL_FILES: Record = { - nextjs: 'src/nextjs/nextjs-installer-agent.ts', - react: 'src/react/react-installer-agent.ts', - 'react-router': 'src/react-router/react-router-installer-agent.ts', - 'tanstack-start': 'src/tanstack-start/tanstack-start-installer-agent.ts', - 'vanilla-js': 'src/vanilla-js/vanilla-js-installer-agent.ts', + // Existing JS SDKs (updated paths from Phase 1 migration) + nextjs: 'src/integrations/nextjs/index.ts', + react: 'src/integrations/react/index.ts', + 'react-router': 'src/integrations/react-router/index.ts', + 'tanstack-start': 'src/integrations/tanstack-start/index.ts', + 'vanilla-js': 'src/integrations/vanilla-js/index.ts', + // New SDKs + sveltekit: 'src/integrations/sveltekit/index.ts', + node: 'src/integrations/node/index.ts', + python: 'src/integrations/python/index.ts', + ruby: 'src/integrations/ruby/index.ts', + go: 'src/integrations/go/index.ts', + php: 'src/integrations/php/index.ts', + 'php-laravel': 'src/integrations/php-laravel/index.ts', + kotlin: 'src/integrations/kotlin/index.ts', + dotnet: 'src/integrations/dotnet/index.ts', + elixir: 'src/integrations/elixir/index.ts', }; export interface VersionMetadata { From 42202f97418ec4725ecc27f3b0afac5ae6b11b84 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 9 Feb 2026 15:17:26 -0600 Subject: [PATCH 04/12] feat: add eval fixtures for 10 new SDK integrations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Minimal project scaffolds matching WorkOS AuthKit quickstart patterns: - SvelteKit (svelte.config.js, app.html, routes) - Node.js/Express (server.js, CJS matching quickstart) - Python/Flask (server.py, requirements.txt) - Ruby/Sinatra (server.rb, Gemfile) - Go/Gin (main.go, go.mod) - PHP (composer.json, public/index.php) - PHP-Laravel (artisan, routes/web.php, Blade template) - Kotlin/Spring Boot (build.gradle.kts, Application.kt) - .NET/ASP.NET Core (Example.csproj, Program.cs) - Elixir/Phoenix (mix.exs, router.ex, controller) Each fixture is the "before" state — a working app before WorkOS is added. The eval system runs the installer agent against these and grades the result. --- tests/fixtures/dotnet/example/Example.csproj | 5 + tests/fixtures/dotnet/example/Program.cs | 7 + .../fixtures/dotnet/example/appsettings.json | 7 + tests/fixtures/dotnet/example/index.html | 9 + .../fixtures/elixir/example/config/config.exs | 6 + .../elixir/example/lib/example/application.ex | 12 + .../controllers/page_controller.ex | 17 + .../example/lib/example_web/endpoint.ex | 5 + .../elixir/example/lib/example_web/router.ex | 13 + tests/fixtures/elixir/example/mix.exs | 28 + tests/fixtures/go/example/go.mod | 5 + tests/fixtures/go/example/index.html | 9 + tests/fixtures/go/example/main.go | 17 + .../fixtures/kotlin/example/build.gradle.kts | 22 + .../kotlin/example/settings.gradle.kts | 1 + .../main/kotlin/com/example/Application.kt | 11 + .../src/main/resources/application.properties | 1 + tests/fixtures/node/example/index.html | 9 + tests/fixtures/node/example/package.json | 12 + tests/fixtures/node/example/server.js | 12 + tests/fixtures/php-laravel/example/artisan | 10 + .../php-laravel/example/bootstrap/app.php | 4 + .../php-laravel/example/composer.json | 12 + .../example/resources/views/welcome.blade.php | 9 + .../php-laravel/example/routes/web.php | 7 + tests/fixtures/php/example/composer.json | 11 + tests/fixtures/php/example/public/index.php | 9 + tests/fixtures/python/example/index.html | 9 + .../fixtures/python/example/requirements.txt | 2 + tests/fixtures/python/example/server.py | 12 + tests/fixtures/ruby/example/Gemfile | 4 + tests/fixtures/ruby/example/index.html | 9 + tests/fixtures/ruby/example/server.rb | 7 + .../example/.svelte-kit/ambient.d.ts | 277 ++ .../generated/client-optimized/app.js | 29 + .../generated/client-optimized/matchers.js | 1 + .../generated/client-optimized/nodes/0.js | 1 + .../generated/client-optimized/nodes/1.js | 1 + .../generated/client-optimized/nodes/2.js | 1 + .../.svelte-kit/generated/client/app.js | 29 + .../.svelte-kit/generated/client/matchers.js | 1 + .../.svelte-kit/generated/client/nodes/0.js | 1 + .../.svelte-kit/generated/client/nodes/1.js | 1 + .../.svelte-kit/generated/client/nodes/2.js | 1 + .../example/.svelte-kit/generated/root.js | 3 + .../example/.svelte-kit/generated/root.svelte | 68 + .../.svelte-kit/generated/server/internal.js | 53 + .../example/.svelte-kit/non-ambient.d.ts | 41 + .../output/client/.vite/manifest.json | 109 + .../_app/immutable/assets/2.Cwfcd7nv.css | 1 + .../client/_app/immutable/chunks/BShzwfeu.js | 1 + .../client/_app/immutable/chunks/B_PiQ68N.js | 1 + .../client/_app/immutable/chunks/C8WMVNin.js | 1 + .../client/_app/immutable/chunks/CE0Ev3WY.js | 1 + .../client/_app/immutable/chunks/Csl9sg0z.js | 1 + .../client/_app/immutable/chunks/jjmyhcpZ.js | 2 + .../_app/immutable/entry/app.CpUzidFU.js | 2 + .../_app/immutable/entry/start.T22yjXU7.js | 1 + .../client/_app/immutable/nodes/0.Cc7SJR4r.js | 1 + .../client/_app/immutable/nodes/1.DcKD0893.js | 1 + .../client/_app/immutable/nodes/2.BFij7fXI.js | 1 + .../output/client/_app/version.json | 1 + .../output/server/.vite/manifest.json | 119 + .../_app/immutable/assets/_page.Cwfcd7nv.css | 1 + .../output/server/chunks/context.js | 109 + .../output/server/chunks/environment.js | 36 + .../output/server/chunks/equality.js | 14 + .../output/server/chunks/exports.js | 231 + .../.svelte-kit/output/server/chunks/index.js | 1297 ++++++ .../output/server/chunks/internal.js | 2712 +++++++++++ .../output/server/chunks/shared.js | 1188 +++++ .../.svelte-kit/output/server/chunks/utils.js | 43 + .../output/server/chunks/utils2.js | 98 + .../server/entries/fallbacks/error.svelte.js | 54 + .../server/entries/pages/_layout.svelte.js | 9 + .../server/entries/pages/_page.svelte.js | 6 + .../.svelte-kit/output/server/index.js | 3982 +++++++++++++++++ .../.svelte-kit/output/server/internal.js | 13 + .../output/server/manifest-full.js | 39 + .../.svelte-kit/output/server/manifest.js | 39 + .../.svelte-kit/output/server/nodes/0.js | 8 + .../.svelte-kit/output/server/nodes/1.js | 8 + .../.svelte-kit/output/server/nodes/2.js | 8 + .../.svelte-kit/output/server/remote-entry.js | 555 +++ .../example/.svelte-kit/tsconfig.json | 46 + .../.svelte-kit/types/route_meta_data.json | 3 + .../.svelte-kit/types/src/routes/$types.d.ts | 24 + tests/fixtures/sveltekit/example/package.json | 21 + tests/fixtures/sveltekit/example/src/app.html | 11 + .../example/src/routes/+layout.svelte | 5 + .../sveltekit/example/src/routes/+page.svelte | 36 + .../sveltekit/example/svelte.config.js | 10 + .../fixtures/sveltekit/example/tsconfig.json | 14 + .../fixtures/sveltekit/example/vite.config.ts | 6 + 94 files changed, 11690 insertions(+) create mode 100644 tests/fixtures/dotnet/example/Example.csproj create mode 100644 tests/fixtures/dotnet/example/Program.cs create mode 100644 tests/fixtures/dotnet/example/appsettings.json create mode 100644 tests/fixtures/dotnet/example/index.html create mode 100644 tests/fixtures/elixir/example/config/config.exs create mode 100644 tests/fixtures/elixir/example/lib/example/application.ex create mode 100644 tests/fixtures/elixir/example/lib/example_web/controllers/page_controller.ex create mode 100644 tests/fixtures/elixir/example/lib/example_web/endpoint.ex create mode 100644 tests/fixtures/elixir/example/lib/example_web/router.ex create mode 100644 tests/fixtures/elixir/example/mix.exs create mode 100644 tests/fixtures/go/example/go.mod create mode 100644 tests/fixtures/go/example/index.html create mode 100644 tests/fixtures/go/example/main.go create mode 100644 tests/fixtures/kotlin/example/build.gradle.kts create mode 100644 tests/fixtures/kotlin/example/settings.gradle.kts create mode 100644 tests/fixtures/kotlin/example/src/main/kotlin/com/example/Application.kt create mode 100644 tests/fixtures/kotlin/example/src/main/resources/application.properties create mode 100644 tests/fixtures/node/example/index.html create mode 100644 tests/fixtures/node/example/package.json create mode 100644 tests/fixtures/node/example/server.js create mode 100644 tests/fixtures/php-laravel/example/artisan create mode 100644 tests/fixtures/php-laravel/example/bootstrap/app.php create mode 100644 tests/fixtures/php-laravel/example/composer.json create mode 100644 tests/fixtures/php-laravel/example/resources/views/welcome.blade.php create mode 100644 tests/fixtures/php-laravel/example/routes/web.php create mode 100644 tests/fixtures/php/example/composer.json create mode 100644 tests/fixtures/php/example/public/index.php create mode 100644 tests/fixtures/python/example/index.html create mode 100644 tests/fixtures/python/example/requirements.txt create mode 100644 tests/fixtures/python/example/server.py create mode 100644 tests/fixtures/ruby/example/Gemfile create mode 100644 tests/fixtures/ruby/example/index.html create mode 100644 tests/fixtures/ruby/example/server.rb create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/C8WMVNin.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/internal.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/manifest-full.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/manifest.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/0.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/1.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/2.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/remote-entry.js create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/tsconfig.json create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/types/route_meta_data.json create mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/types/src/routes/$types.d.ts create mode 100644 tests/fixtures/sveltekit/example/package.json create mode 100644 tests/fixtures/sveltekit/example/src/app.html create mode 100644 tests/fixtures/sveltekit/example/src/routes/+layout.svelte create mode 100644 tests/fixtures/sveltekit/example/src/routes/+page.svelte create mode 100644 tests/fixtures/sveltekit/example/svelte.config.js create mode 100644 tests/fixtures/sveltekit/example/tsconfig.json create mode 100644 tests/fixtures/sveltekit/example/vite.config.ts diff --git a/tests/fixtures/dotnet/example/Example.csproj b/tests/fixtures/dotnet/example/Example.csproj new file mode 100644 index 0000000..f577589 --- /dev/null +++ b/tests/fixtures/dotnet/example/Example.csproj @@ -0,0 +1,5 @@ + + + net8.0 + + diff --git a/tests/fixtures/dotnet/example/Program.cs b/tests/fixtures/dotnet/example/Program.cs new file mode 100644 index 0000000..e01f740 --- /dev/null +++ b/tests/fixtures/dotnet/example/Program.cs @@ -0,0 +1,7 @@ +var builder = WebApplication.CreateBuilder(args); +var app = builder.Build(); + +app.MapGet("/", () => Results.Content( + System.IO.File.ReadAllText("index.html"), "text/html")); + +app.Run("http://localhost:3000"); diff --git a/tests/fixtures/dotnet/example/appsettings.json b/tests/fixtures/dotnet/example/appsettings.json new file mode 100644 index 0000000..960be50 --- /dev/null +++ b/tests/fixtures/dotnet/example/appsettings.json @@ -0,0 +1,7 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information" + } + } +} diff --git a/tests/fixtures/dotnet/example/index.html b/tests/fixtures/dotnet/example/index.html new file mode 100644 index 0000000..5c06a10 --- /dev/null +++ b/tests/fixtures/dotnet/example/index.html @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/elixir/example/config/config.exs b/tests/fixtures/elixir/example/config/config.exs new file mode 100644 index 0000000..c033afb --- /dev/null +++ b/tests/fixtures/elixir/example/config/config.exs @@ -0,0 +1,6 @@ +import Config + +config :example, ExampleWeb.Endpoint, + url: [host: "localhost"], + http: [port: 3000], + secret_key_base: "placeholder_secret_key_base_for_fixture" diff --git a/tests/fixtures/elixir/example/lib/example/application.ex b/tests/fixtures/elixir/example/lib/example/application.ex new file mode 100644 index 0000000..8a25635 --- /dev/null +++ b/tests/fixtures/elixir/example/lib/example/application.ex @@ -0,0 +1,12 @@ +defmodule Example.Application do + use Application + + def start(_type, _args) do + children = [ + ExampleWeb.Endpoint + ] + + opts = [strategy: :one_for_one, name: Example.Supervisor] + Supervisor.start_link(children, opts) + end +end diff --git a/tests/fixtures/elixir/example/lib/example_web/controllers/page_controller.ex b/tests/fixtures/elixir/example/lib/example_web/controllers/page_controller.ex new file mode 100644 index 0000000..48ea80a --- /dev/null +++ b/tests/fixtures/elixir/example/lib/example_web/controllers/page_controller.ex @@ -0,0 +1,17 @@ +defmodule ExampleWeb.PageController do + use Phoenix.Controller, formats: [:html] + + def index(conn, _params) do + html(conn, """ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + + """) + end +end diff --git a/tests/fixtures/elixir/example/lib/example_web/endpoint.ex b/tests/fixtures/elixir/example/lib/example_web/endpoint.ex new file mode 100644 index 0000000..eccfdeb --- /dev/null +++ b/tests/fixtures/elixir/example/lib/example_web/endpoint.ex @@ -0,0 +1,5 @@ +defmodule ExampleWeb.Endpoint do + use Phoenix.Endpoint, otp_app: :example + + plug ExampleWeb.Router +end diff --git a/tests/fixtures/elixir/example/lib/example_web/router.ex b/tests/fixtures/elixir/example/lib/example_web/router.ex new file mode 100644 index 0000000..ded6964 --- /dev/null +++ b/tests/fixtures/elixir/example/lib/example_web/router.ex @@ -0,0 +1,13 @@ +defmodule ExampleWeb.Router do + use Phoenix.Router + + pipeline :browser do + plug :accepts, ["html"] + end + + scope "/", ExampleWeb do + pipe_through :browser + + get "/", PageController, :index + end +end diff --git a/tests/fixtures/elixir/example/mix.exs b/tests/fixtures/elixir/example/mix.exs new file mode 100644 index 0000000..f514bba --- /dev/null +++ b/tests/fixtures/elixir/example/mix.exs @@ -0,0 +1,28 @@ +defmodule Example.MixProject do + use Mix.Project + + def project do + [ + app: :example, + version: "0.1.0", + elixir: "~> 1.15", + start_permanent: Mix.env() == :prod, + deps: deps() + ] + end + + def application do + [ + mod: {Example.Application, []}, + extra_applications: [:logger] + ] + end + + defp deps do + [ + {:phoenix, "~> 1.7"}, + {:phoenix_html, "~> 4.0"}, + {:plug_cowboy, "~> 2.7"} + ] + end +end diff --git a/tests/fixtures/go/example/go.mod b/tests/fixtures/go/example/go.mod new file mode 100644 index 0000000..58a360f --- /dev/null +++ b/tests/fixtures/go/example/go.mod @@ -0,0 +1,5 @@ +module example.com/authkit-example + +go 1.21 + +require github.com/gin-gonic/gin v1.9.1 diff --git a/tests/fixtures/go/example/index.html b/tests/fixtures/go/example/index.html new file mode 100644 index 0000000..5c06a10 --- /dev/null +++ b/tests/fixtures/go/example/index.html @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/go/example/main.go b/tests/fixtures/go/example/main.go new file mode 100644 index 0000000..ce831b1 --- /dev/null +++ b/tests/fixtures/go/example/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +func main() { + r := gin.Default() + + r.GET("/", func(c *gin.Context) { + c.File("./index.html") + }) + + r.Run(":3000") +} diff --git a/tests/fixtures/kotlin/example/build.gradle.kts b/tests/fixtures/kotlin/example/build.gradle.kts new file mode 100644 index 0000000..8a2bc6c --- /dev/null +++ b/tests/fixtures/kotlin/example/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + id("org.springframework.boot") version "3.2.0" + id("io.spring.dependency-management") version "1.1.4" + kotlin("jvm") version "1.9.21" + kotlin("plugin.spring") version "1.9.21" +} + +group = "com.example" +version = "0.0.1" + +java { + sourceCompatibility = JavaVersion.VERSION_17 +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.jetbrains.kotlin:kotlin-reflect") +} diff --git a/tests/fixtures/kotlin/example/settings.gradle.kts b/tests/fixtures/kotlin/example/settings.gradle.kts new file mode 100644 index 0000000..749a944 --- /dev/null +++ b/tests/fixtures/kotlin/example/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "authkit-example" diff --git a/tests/fixtures/kotlin/example/src/main/kotlin/com/example/Application.kt b/tests/fixtures/kotlin/example/src/main/kotlin/com/example/Application.kt new file mode 100644 index 0000000..2b564e8 --- /dev/null +++ b/tests/fixtures/kotlin/example/src/main/kotlin/com/example/Application.kt @@ -0,0 +1,11 @@ +package com.example + +import org.springframework.boot.autoconfigure.SpringBootApplication +import org.springframework.boot.runApplication + +@SpringBootApplication +class Application + +fun main(args: Array) { + runApplication(*args) +} diff --git a/tests/fixtures/kotlin/example/src/main/resources/application.properties b/tests/fixtures/kotlin/example/src/main/resources/application.properties new file mode 100644 index 0000000..b0f2669 --- /dev/null +++ b/tests/fixtures/kotlin/example/src/main/resources/application.properties @@ -0,0 +1 @@ +server.port=3000 diff --git a/tests/fixtures/node/example/index.html b/tests/fixtures/node/example/index.html new file mode 100644 index 0000000..5c06a10 --- /dev/null +++ b/tests/fixtures/node/example/index.html @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/node/example/package.json b/tests/fixtures/node/example/package.json new file mode 100644 index 0000000..7c012b8 --- /dev/null +++ b/tests/fixtures/node/example/package.json @@ -0,0 +1,12 @@ +{ + "name": "node-express-fixture", + "private": true, + "version": "0.0.0", + "scripts": { + "start": "node server.js" + }, + "dependencies": { + "express": "^4.21.0", + "dotenv": "^16.4.0" + } +} diff --git a/tests/fixtures/node/example/server.js b/tests/fixtures/node/example/server.js new file mode 100644 index 0000000..0adc397 --- /dev/null +++ b/tests/fixtures/node/example/server.js @@ -0,0 +1,12 @@ +const path = require('path'); +const express = require('express'); + +const app = express(); + +app.get('/', (req, res) => { + res.sendFile(path.join(__dirname, 'index.html')); +}); + +app.listen(3000, () => { + console.log('Server running on http://localhost:3000'); +}); diff --git a/tests/fixtures/php-laravel/example/artisan b/tests/fixtures/php-laravel/example/artisan new file mode 100644 index 0000000..4504e57 --- /dev/null +++ b/tests/fixtures/php-laravel/example/artisan @@ -0,0 +1,10 @@ +#!/usr/bin/env php +make(Illuminate\Contracts\Console\Kernel::class); +$status = $kernel->handle( + $input = new Symfony\Component\Console\Input\ArgvInput, + new Symfony\Component\Console\Output\ConsoleOutput +); +exit($status); diff --git a/tests/fixtures/php-laravel/example/bootstrap/app.php b/tests/fixtures/php-laravel/example/bootstrap/app.php new file mode 100644 index 0000000..2ae1cd0 --- /dev/null +++ b/tests/fixtures/php-laravel/example/bootstrap/app.php @@ -0,0 +1,4 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/php-laravel/example/routes/web.php b/tests/fixtures/php-laravel/example/routes/web.php new file mode 100644 index 0000000..86a06c5 --- /dev/null +++ b/tests/fixtures/php-laravel/example/routes/web.php @@ -0,0 +1,7 @@ +=8.1" + }, + "autoload": { + "psr-4": { + "App\\": "src/" + } + } +} diff --git a/tests/fixtures/php/example/public/index.php b/tests/fixtures/php/example/public/index.php new file mode 100644 index 0000000..6b3c262 --- /dev/null +++ b/tests/fixtures/php/example/public/index.php @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/python/example/index.html b/tests/fixtures/python/example/index.html new file mode 100644 index 0000000..5c06a10 --- /dev/null +++ b/tests/fixtures/python/example/index.html @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/python/example/requirements.txt b/tests/fixtures/python/example/requirements.txt new file mode 100644 index 0000000..f34604e --- /dev/null +++ b/tests/fixtures/python/example/requirements.txt @@ -0,0 +1,2 @@ +flask +python-dotenv diff --git a/tests/fixtures/python/example/server.py b/tests/fixtures/python/example/server.py new file mode 100644 index 0000000..038e9cb --- /dev/null +++ b/tests/fixtures/python/example/server.py @@ -0,0 +1,12 @@ +from flask import Flask, send_file + +app = Flask(__name__) + + +@app.route("/") +def index(): + return send_file("index.html") + + +if __name__ == "__main__": + app.run(debug=True, port=3000) diff --git a/tests/fixtures/ruby/example/Gemfile b/tests/fixtures/ruby/example/Gemfile new file mode 100644 index 0000000..185d241 --- /dev/null +++ b/tests/fixtures/ruby/example/Gemfile @@ -0,0 +1,4 @@ +source "https://rubygems.org" + +gem "sinatra" +gem "dotenv" diff --git a/tests/fixtures/ruby/example/index.html b/tests/fixtures/ruby/example/index.html new file mode 100644 index 0000000..5c06a10 --- /dev/null +++ b/tests/fixtures/ruby/example/index.html @@ -0,0 +1,9 @@ + + + AuthKit example + +

AuthKit example

+

Sign in

+

Sign out

+ + diff --git a/tests/fixtures/ruby/example/server.rb b/tests/fixtures/ruby/example/server.rb new file mode 100644 index 0000000..45056bf --- /dev/null +++ b/tests/fixtures/ruby/example/server.rb @@ -0,0 +1,7 @@ +require "sinatra" + +set :port, 3000 + +get "/" do + send_file "index.html" +end diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts b/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts new file mode 100644 index 0000000..4320be1 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts @@ -0,0 +1,277 @@ + +// this file is generated — do not edit it + + +/// + +/** + * Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured). + * + * _Unlike_ [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. + * + * ```ts + * import { API_KEY } from '$env/static/private'; + * ``` + * + * Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: + * + * ``` + * MY_FEATURE_FLAG="" + * ``` + * + * You can override `.env` values from the command line like so: + * + * ```sh + * MY_FEATURE_FLAG="enabled" npm run dev + * ``` + */ +declare module '$env/static/private' { + export const MANPATH: string; + export const GHOSTTY_RESOURCES_DIR: string; + export const LESS_TERMCAP_mb: string; + export const NIX_PROFILES: string; + export const NoDefaultCurrentDirectoryInExePath: string; + export const TERM_PROGRAM: string; + export const CLAUDE_CODE_ENTRYPOINT: string; + export const FNM_LOGLEVEL: string; + export const LESS_TERMCAP_md: string; + export const LESS_TERMCAP_me: string; + export const PYENV_ROOT: string; + export const SHELL: string; + export const TERM: string; + export const FNM_NODE_DIST_MIRROR: string; + export const HOMEBREW_REPOSITORY: string; + export const LESS_TERMCAP_mh: string; + export const RIPGREP_CONFIG_PATH: string; + export const TMPDIR: string; + export const TERM_PROGRAM_VERSION: string; + export const ZDOTDIR: string; + export const LESS_TERMCAP_ue: string; + export const PNPM_HOME: string; + export const ZSH: string; + export const FNM_COREPACK_ENABLED: string; + export const GIT_EDITOR: string; + export const USER: string; + export const LESS_TERMCAP_mr: string; + export const COMMAND_MODE: string; + export const OPENAI_API_KEY: string; + export const MANROFFOPT: string; + export const RPROMPT: string; + export const CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: string; + export const SSH_AUTH_SOCK: string; + export const CALENDLY_API_KEY: string; + export const CODE_DIR: string; + export const __CF_USER_TEXT_ENCODING: string; + export const FZF_DEFAULT_OPTS: string; + export const DOTFILES: string; + export const TMUX: string; + export const npm_config_verify_deps_before_run: string; + export const CACHEDIR: string; + export const FNM_VERSION_FILE_STRATEGY: string; + export const LESS_TERMCAP_us: string; + export const FNM_ARCH: string; + export const GOOGLE_API_KEY: string; + export const PATH: string; + export const GHOSTTY_SHELL_FEATURES: string; + export const LaunchInstanceID: string; + export const ZPLUGDIR: string; + export const __CFBundleIdentifier: string; + export const npm_command: string; + export const CONTEXT7_API_KEY: string; + export const PWD: string; + export const EDITOR: string; + export const PERPLEXITY_API_KEY: string; + export const OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: string; + export const LANG: string; + export const NODE_PATH: string; + export const KEYTIMEOUT: string; + export const VIM_TMP: string; + export const FNM_MULTISHELL_PATH: string; + export const TMUX_PANE: string; + export const XPC_FLAGS: string; + export const NIX_SSL_CERT_FILE: string; + export const ANTHROPIC_API_KEY: string; + export const RBENV_SHELL: string; + export const pnpm_config_verify_deps_before_run: string; + export const XPC_SERVICE_NAME: string; + export const HOME: string; + export const PYENV_SHELL: string; + export const SHLVL: string; + export const TERMINFO: string; + export const XDG_CONFIG_HOME: string; + export const CLAUDE_CODE_TASK_LIST_ID: string; + export const HOMEBREW_PREFIX: string; + export const FNM_DIR: string; + export const PROMPT: string; + export const LOGNAME: string; + export const PNPM_PACKAGE_NAME: string; + export const FZF_CTRL_T_COMMAND: string; + export const LESS_TERMCAP_so: string; + export const XDG_DATA_DIRS: string; + export const FZF_DEFAULT_COMMAND: string; + export const GHOSTTY_BIN_DIR: string; + export const COREPACK_ENABLE_AUTO_PIN: string; + export const npm_config_user_agent: string; + export const FNM_RESOLVE_ENGINES: string; + export const HOMEBREW_CELLAR: string; + export const INFOPATH: string; + export const REPORTTIME: string; + export const GITHUB_PERSONAL_ACCESS_TOKEN: string; + export const OSLogRateLimit: string; + export const GROK_API_KEY: string; + export const NIA_API_KEY: string; + export const SECURITYSESSIONID: string; + export const CLAUDECODE: string; + export const NODE_EXTRA_CA_CERTS: string; + export const COLORTERM: string; + export const LESS_TERMCAP_se: string; + export const NODE_ENV: string; +} + +/** + * Similar to [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + * + * Values are replaced statically at build time. + * + * ```ts + * import { PUBLIC_BASE_URL } from '$env/static/public'; + * ``` + */ +declare module '$env/static/public' { + +} + +/** + * This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured). + * + * This module cannot be imported into client-side code. + * + * ```ts + * import { env } from '$env/dynamic/private'; + * console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); + * ``` + * + * > [!NOTE] In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. + */ +declare module '$env/dynamic/private' { + export const env: { + MANPATH: string; + GHOSTTY_RESOURCES_DIR: string; + LESS_TERMCAP_mb: string; + NIX_PROFILES: string; + NoDefaultCurrentDirectoryInExePath: string; + TERM_PROGRAM: string; + CLAUDE_CODE_ENTRYPOINT: string; + FNM_LOGLEVEL: string; + LESS_TERMCAP_md: string; + LESS_TERMCAP_me: string; + PYENV_ROOT: string; + SHELL: string; + TERM: string; + FNM_NODE_DIST_MIRROR: string; + HOMEBREW_REPOSITORY: string; + LESS_TERMCAP_mh: string; + RIPGREP_CONFIG_PATH: string; + TMPDIR: string; + TERM_PROGRAM_VERSION: string; + ZDOTDIR: string; + LESS_TERMCAP_ue: string; + PNPM_HOME: string; + ZSH: string; + FNM_COREPACK_ENABLED: string; + GIT_EDITOR: string; + USER: string; + LESS_TERMCAP_mr: string; + COMMAND_MODE: string; + OPENAI_API_KEY: string; + MANROFFOPT: string; + RPROMPT: string; + CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: string; + SSH_AUTH_SOCK: string; + CALENDLY_API_KEY: string; + CODE_DIR: string; + __CF_USER_TEXT_ENCODING: string; + FZF_DEFAULT_OPTS: string; + DOTFILES: string; + TMUX: string; + npm_config_verify_deps_before_run: string; + CACHEDIR: string; + FNM_VERSION_FILE_STRATEGY: string; + LESS_TERMCAP_us: string; + FNM_ARCH: string; + GOOGLE_API_KEY: string; + PATH: string; + GHOSTTY_SHELL_FEATURES: string; + LaunchInstanceID: string; + ZPLUGDIR: string; + __CFBundleIdentifier: string; + npm_command: string; + CONTEXT7_API_KEY: string; + PWD: string; + EDITOR: string; + PERPLEXITY_API_KEY: string; + OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: string; + LANG: string; + NODE_PATH: string; + KEYTIMEOUT: string; + VIM_TMP: string; + FNM_MULTISHELL_PATH: string; + TMUX_PANE: string; + XPC_FLAGS: string; + NIX_SSL_CERT_FILE: string; + ANTHROPIC_API_KEY: string; + RBENV_SHELL: string; + pnpm_config_verify_deps_before_run: string; + XPC_SERVICE_NAME: string; + HOME: string; + PYENV_SHELL: string; + SHLVL: string; + TERMINFO: string; + XDG_CONFIG_HOME: string; + CLAUDE_CODE_TASK_LIST_ID: string; + HOMEBREW_PREFIX: string; + FNM_DIR: string; + PROMPT: string; + LOGNAME: string; + PNPM_PACKAGE_NAME: string; + FZF_CTRL_T_COMMAND: string; + LESS_TERMCAP_so: string; + XDG_DATA_DIRS: string; + FZF_DEFAULT_COMMAND: string; + GHOSTTY_BIN_DIR: string; + COREPACK_ENABLE_AUTO_PIN: string; + npm_config_user_agent: string; + FNM_RESOLVE_ENGINES: string; + HOMEBREW_CELLAR: string; + INFOPATH: string; + REPORTTIME: string; + GITHUB_PERSONAL_ACCESS_TOKEN: string; + OSLogRateLimit: string; + GROK_API_KEY: string; + NIA_API_KEY: string; + SECURITYSESSIONID: string; + CLAUDECODE: string; + NODE_EXTRA_CA_CERTS: string; + COLORTERM: string; + LESS_TERMCAP_se: string; + NODE_ENV: string; + [key: `PUBLIC_${string}`]: undefined; + [key: `${string}`]: string | undefined; + } +} + +/** + * Similar to [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. + * + * Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. + * + * ```ts + * import { env } from '$env/dynamic/public'; + * console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); + * ``` + */ +declare module '$env/dynamic/public' { + export const env: { + [key: `PUBLIC_${string}`]: string | undefined; + } +} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js new file mode 100644 index 0000000..c3c7b78 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js @@ -0,0 +1,29 @@ +export { matchers } from './matchers.js'; + +export const nodes = [ + () => import('./nodes/0'), + () => import('./nodes/1'), + () => import('./nodes/2') +]; + +export const server_loads = []; + +export const dictionary = { + "/": [2] + }; + +export const hooks = { + handleError: (({ error }) => { console.error(error) }), + + reroute: (() => {}), + transport: {} +}; + +export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode])); +export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode])); + +export const hash = false; + +export const decode = (type, value) => decoders[type](value); + +export { default as root } from '../root.js'; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js new file mode 100644 index 0000000..f6bd30a --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js @@ -0,0 +1 @@ +export const matchers = {}; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js new file mode 100644 index 0000000..fed1375 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js @@ -0,0 +1 @@ +export { default as component } from "../../../../src/routes/+layout.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js new file mode 100644 index 0000000..4f4b013 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js @@ -0,0 +1 @@ +export { default as component } from "../../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js new file mode 100644 index 0000000..1cb4f85 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js @@ -0,0 +1 @@ +export { default as component } from "../../../../src/routes/+page.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js new file mode 100644 index 0000000..c3c7b78 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js @@ -0,0 +1,29 @@ +export { matchers } from './matchers.js'; + +export const nodes = [ + () => import('./nodes/0'), + () => import('./nodes/1'), + () => import('./nodes/2') +]; + +export const server_loads = []; + +export const dictionary = { + "/": [2] + }; + +export const hooks = { + handleError: (({ error }) => { console.error(error) }), + + reroute: (() => {}), + transport: {} +}; + +export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode])); +export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode])); + +export const hash = false; + +export const decode = (type, value) => decoders[type](value); + +export { default as root } from '../root.js'; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js new file mode 100644 index 0000000..f6bd30a --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js @@ -0,0 +1 @@ +export const matchers = {}; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js new file mode 100644 index 0000000..fed1375 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js @@ -0,0 +1 @@ +export { default as component } from "../../../../src/routes/+layout.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js new file mode 100644 index 0000000..4f4b013 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js @@ -0,0 +1 @@ +export { default as component } from "../../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js new file mode 100644 index 0000000..1cb4f85 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js @@ -0,0 +1 @@ +export { default as component } from "../../../../src/routes/+page.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js new file mode 100644 index 0000000..4d1e892 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js @@ -0,0 +1,3 @@ +import { asClassComponent } from 'svelte/legacy'; +import Root from './root.svelte'; +export default asClassComponent(Root); \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte new file mode 100644 index 0000000..0795183 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte @@ -0,0 +1,68 @@ + + + + +{#if constructors[1]} + {@const Pyramid_0 = constructors[0]} + + + + + + +{:else} + {@const Pyramid_0 = constructors[0]} + + + +{/if} + +{#if mounted} +
+ {#if navigated} + {title} + {/if} +
+{/if} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js new file mode 100644 index 0000000..009267f --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js @@ -0,0 +1,53 @@ + +import root from '../root.js'; +import { set_building, set_prerendering } from '__sveltekit/environment'; +import { set_assets } from '$app/paths/internal/server'; +import { set_manifest, set_read_implementation } from '__sveltekit/server'; +import { set_private_env, set_public_env } from '../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/shared-server.js'; + +export const options = { + app_template_contains_nonce: false, + async: false, + csp: {"mode":"auto","directives":{"upgrade-insecure-requests":false,"block-all-mixed-content":false},"reportOnly":{"upgrade-insecure-requests":false,"block-all-mixed-content":false}}, + csrf_check_origin: true, + csrf_trusted_origins: [], + embedded: false, + env_public_prefix: 'PUBLIC_', + env_private_prefix: '', + hash_routing: false, + hooks: null, // added lazily, via `get_hooks` + preload_strategy: "modulepreload", + root, + service_worker: false, + service_worker_options: undefined, + templates: { + app: ({ head, body, assets, nonce, env }) => "\n\n\t\n\t\t\n\t\t\n\t\t" + head + "\n\t\n\t\n\t\t
" + body + "
\n\t\n\n", + error: ({ status, message }) => "\n\n\t\n\t\t\n\t\t" + message + "\n\n\t\t\n\t\n\t\n\t\t
\n\t\t\t" + status + "\n\t\t\t
\n\t\t\t\t

" + message + "

\n\t\t\t
\n\t\t
\n\t\n\n" + }, + version_hash: "zurjbz" +}; + +export async function get_hooks() { + let handle; + let handleFetch; + let handleError; + let handleValidationError; + let init; + + + let reroute; + let transport; + + + return { + handle, + handleFetch, + handleError, + handleValidationError, + init, + reroute, + transport + }; +} + +export { set_assets, set_building, set_manifest, set_prerendering, set_private_env, set_public_env, set_read_implementation }; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts b/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts new file mode 100644 index 0000000..f2cfe55 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts @@ -0,0 +1,41 @@ + +// this file is generated — do not edit it + + +declare module "svelte/elements" { + export interface HTMLAttributes { + 'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-preload-code'?: + | true + | '' + | 'eager' + | 'viewport' + | 'hover' + | 'tap' + | 'off' + | undefined + | null; + 'data-sveltekit-preload-data'?: true | '' | 'hover' | 'tap' | 'off' | undefined | null; + 'data-sveltekit-reload'?: true | '' | 'off' | undefined | null; + 'data-sveltekit-replacestate'?: true | '' | 'off' | undefined | null; + } +} + +export {}; + + +declare module "$app/types" { + export interface AppTypes { + RouteId(): "/"; + RouteParams(): { + + }; + LayoutParams(): { + "/": Record + }; + Pathname(): "/"; + ResolvedPathname(): `${"" | `/${string}`}${ReturnType}`; + Asset(): string & {}; + } +} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json new file mode 100644 index 0000000..f6bef3e --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json @@ -0,0 +1,109 @@ +{ + ".svelte-kit/generated/client-optimized/app.js": { + "file": "_app/immutable/entry/app.CpUzidFU.js", + "name": "entry/app", + "src": ".svelte-kit/generated/client-optimized/app.js", + "isEntry": true, + "imports": [ + "_B_PiQ68N.js", + "_jjmyhcpZ.js", + "_C8WMVNin.js", + "_CE0Ev3WY.js" + ], + "dynamicImports": [ + ".svelte-kit/generated/client-optimized/nodes/0.js", + ".svelte-kit/generated/client-optimized/nodes/1.js", + ".svelte-kit/generated/client-optimized/nodes/2.js" + ] + }, + ".svelte-kit/generated/client-optimized/nodes/0.js": { + "file": "_app/immutable/nodes/0.Cc7SJR4r.js", + "name": "nodes/0", + "src": ".svelte-kit/generated/client-optimized/nodes/0.js", + "isEntry": true, + "isDynamicEntry": true, + "imports": [ + "_C8WMVNin.js", + "_Csl9sg0z.js", + "_B_PiQ68N.js" + ] + }, + ".svelte-kit/generated/client-optimized/nodes/1.js": { + "file": "_app/immutable/nodes/1.DcKD0893.js", + "name": "nodes/1", + "src": ".svelte-kit/generated/client-optimized/nodes/1.js", + "isEntry": true, + "isDynamicEntry": true, + "imports": [ + "_C8WMVNin.js", + "_Csl9sg0z.js", + "_B_PiQ68N.js", + "_jjmyhcpZ.js", + "_BShzwfeu.js" + ] + }, + ".svelte-kit/generated/client-optimized/nodes/2.js": { + "file": "_app/immutable/nodes/2.BFij7fXI.js", + "name": "nodes/2", + "src": ".svelte-kit/generated/client-optimized/nodes/2.js", + "isEntry": true, + "isDynamicEntry": true, + "imports": [ + "_C8WMVNin.js", + "_Csl9sg0z.js" + ], + "css": [ + "_app/immutable/assets/2.Cwfcd7nv.css" + ] + }, + "_BShzwfeu.js": { + "file": "_app/immutable/chunks/BShzwfeu.js", + "name": "entry", + "imports": [ + "_B_PiQ68N.js", + "_CE0Ev3WY.js" + ] + }, + "_B_PiQ68N.js": { + "file": "_app/immutable/chunks/B_PiQ68N.js", + "name": "runtime" + }, + "_C8WMVNin.js": { + "file": "_app/immutable/chunks/C8WMVNin.js", + "name": "disclose-version", + "imports": [ + "_B_PiQ68N.js" + ] + }, + "_CE0Ev3WY.js": { + "file": "_app/immutable/chunks/CE0Ev3WY.js", + "name": "index-client", + "imports": [ + "_B_PiQ68N.js" + ] + }, + "_Csl9sg0z.js": { + "file": "_app/immutable/chunks/Csl9sg0z.js", + "name": "legacy", + "imports": [ + "_B_PiQ68N.js" + ] + }, + "_jjmyhcpZ.js": { + "file": "_app/immutable/chunks/jjmyhcpZ.js", + "name": "render", + "imports": [ + "_B_PiQ68N.js", + "_C8WMVNin.js" + ] + }, + "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/client/entry.js": { + "file": "_app/immutable/entry/start.T22yjXU7.js", + "name": "entry/start", + "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/client/entry.js", + "isEntry": true, + "imports": [ + "_BShzwfeu.js" + ] + } +} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css new file mode 100644 index 0000000..bd4f0b4 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css @@ -0,0 +1 @@ +main.svelte-1uha8ag{padding:2rem;font-family:system-ui,-apple-system,sans-serif}h1.svelte-1uha8ag{color:#333}nav.svelte-1uha8ag{margin-top:2rem}a.svelte-1uha8ag{color:#06c;text-decoration:none}a.svelte-1uha8ag:hover{text-decoration:underline} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js new file mode 100644 index 0000000..1bbc389 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js @@ -0,0 +1 @@ +var Qt=t=>{throw TypeError(t)};var Pe=(t,e,n)=>e.has(t)||Qt("Cannot "+n);var w=(t,e,n)=>(Pe(t,e,"read from private field"),n?n.call(t):e.get(t)),U=(t,e,n)=>e.has(t)?Qt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);import{aJ as Lt,aK as $e,aH as T,i as I,av as O,aG as pt,aL as Ce}from"./B_PiQ68N.js";import{o as Zt}from"./CE0Ev3WY.js";const B=[];function Nt(t,e=Lt){let n=null;const r=new Set;function a(i){if($e(t,i)&&(t=i,n)){const c=!B.length;for(const l of r)l[1](),B.push(l,t);if(c){for(let l=0;l{r.delete(l),r.size===0&&n&&(n(),n=null)}}return{set:a,update:s,subscribe:o}}class zt{constructor(e,n){this.status=e,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${e}`}}toString(){return JSON.stringify(this.body)}}class qt{constructor(e,n){this.status=e,this.location=n}}class Dt extends Error{constructor(e,n,r){super(r),this.status=e,this.text=n}}new URL("sveltekit-internal://");function je(t,e){return t==="/"||e==="ignore"?t:e==="never"?t.endsWith("/")?t.slice(0,-1):t:e==="always"&&!t.endsWith("/")?t+"/":t}function Ne(t){return t.split("%25").map(decodeURI).join("%25")}function ze(t){for(const e in t)t[e]=decodeURIComponent(t[e]);return t}function At({href:t}){return t.split("#")[0]}function qe(...t){let e=5381;for(const n of t)if(typeof n=="string"){let r=n.length;for(;r;)e=e*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)e=e*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(e>>>0).toString(36)}new TextEncoder;new TextDecoder;function De(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r((t instanceof Request?t.method:(e==null?void 0:e.method)||"GET")!=="GET"&&Y.delete(Vt(t)),Ve(t,e));const Y=new Map;function Ke(t,e){const n=Vt(t,e),r=document.querySelector(n);if(r!=null&&r.textContent){r.remove();let{body:a,...s}=JSON.parse(r.textContent);const o=r.getAttribute("data-ttl");return o&&Y.set(n,{body:a,init:s,ttl:1e3*Number(o)}),r.getAttribute("data-b64")!==null&&(a=De(a)),Promise.resolve(new Response(a,s))}return window.fetch(t,e)}function Be(t,e,n){if(Y.size>0){const r=Vt(t,n),a=Y.get(r);if(a){if(performance.now(){const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return e.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const s=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(s)return e.push({name:s[1],matcher:s[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const o=r.split(/\[(.+?)\](?!\])/);return"/"+o.map((c,l)=>{if(l%2){if(c.startsWith("x+"))return Ut(String.fromCharCode(parseInt(c.slice(2),16)));if(c.startsWith("u+"))return Ut(String.fromCharCode(...c.slice(2).split("-").map(_=>parseInt(_,16))));const d=Ge.exec(c),[,u,y,f,h]=d;return e.push({name:f,matcher:h,optional:!!u,rest:!!y,chained:y?l===1&&o[0]==="":!1}),y?"([^]*?)":u?"([^/]*)?":"([^/]+?)"}return Ut(c)}).join("")}).join("")}/?$`),params:e}}function Fe(t){return t!==""&&!/^\([^)]+\)$/.test(t)}function We(t){return t.slice(1).split("/").filter(Fe)}function Ye(t,e,n){const r={},a=t.slice(1),s=a.filter(i=>i!==void 0);let o=0;for(let i=0;id).join("/"),o=0),l===void 0)if(c.rest)l="";else continue;if(!c.matcher||n[c.matcher](l)){r[c.name]=l;const d=e[i+1],u=a[i+1];d&&!d.rest&&d.optional&&u&&c.chained&&(o=0),!d&&!u&&Object.keys(r).length===s.length&&(o=0);continue}if(c.optional&&c.chained){o++;continue}return}if(!o)return r}function Ut(t){return t.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function He({nodes:t,server_loads:e,dictionary:n,matchers:r}){const a=new Set(e);return Object.entries(n).map(([i,[c,l,d]])=>{const{pattern:u,params:y}=Me(i),f={id:i,exec:h=>{const _=u.exec(h);if(_)return Ye(_,y,r)},errors:[1,...d||[]].map(h=>t[h]),layouts:[0,...l||[]].map(o),leaf:s(c)};return f.errors.length=f.layouts.length=Math.max(f.errors.length,f.layouts.length),f});function s(i){const c=i<0;return c&&(i=~i),[c,t[i]]}function o(i){return i===void 0?i:[a.has(i),t[i]]}}function de(t,e=JSON.parse){try{return e(sessionStorage[t])}catch{}}function te(t,e,n=JSON.stringify){const r=n(e);try{sessionStorage[t]=r}catch{}}var ie;const A=((ie=globalThis.__sveltekit_zurjbz)==null?void 0:ie.base)??"";var ce;const Je=((ce=globalThis.__sveltekit_zurjbz)==null?void 0:ce.assets)??A??"",Xe="1770671592599",he="sveltekit:snapshot",pe="sveltekit:scroll",ge="sveltekit:states",Qe="sveltekit:pageurl",M="sveltekit:history",J="sveltekit:navigation",z={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Kt=location.origin;function me(t){if(t instanceof URL)return t;let e=document.baseURI;if(!e){const n=document.getElementsByTagName("base");e=n.length?n[0].href:document.URL}return new URL(t,e)}function St(){return{x:pageXOffset,y:pageYOffset}}function G(t,e){return t.getAttribute(`data-sveltekit-${e}`)}const ee={...z,"":z.hover};function _e(t){let e=t.assignedSlot??t.parentNode;return(e==null?void 0:e.nodeType)===11&&(e=e.host),e}function we(t,e){for(;t&&t!==e;){if(t.nodeName.toUpperCase()==="A"&&t.hasAttribute("href"))return t;t=_e(t)}}function Ot(t,e,n){let r;try{if(r=new URL(t instanceof SVGAElement?t.href.baseVal:t.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const i=location.hash.split("#")[1]||"/";r.hash=`#${i}${r.hash}`}}catch{}const a=t instanceof SVGAElement?t.target.baseVal:t.target,s=!r||!!a||Et(r,e,n)||(t.getAttribute("rel")||"").split(/\s+/).includes("external"),o=(r==null?void 0:r.origin)===Kt&&t.hasAttribute("download");return{url:r,external:s,target:a,download:o}}function gt(t){let e=null,n=null,r=null,a=null,s=null,o=null,i=t;for(;i&&i!==document.documentElement;)r===null&&(r=G(i,"preload-code")),a===null&&(a=G(i,"preload-data")),e===null&&(e=G(i,"keepfocus")),n===null&&(n=G(i,"noscroll")),s===null&&(s=G(i,"reload")),o===null&&(o=G(i,"replacestate")),i=_e(i);function c(l){switch(l){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:ee[r??"off"],preload_data:ee[a??"off"],keepfocus:c(e),noscroll:c(n),reload:c(s),replace_state:c(o)}}function ne(t){const e=Nt(t);let n=!0;function r(){n=!0,e.update(o=>o)}function a(o){n=!1,e.set(o)}function s(o){let i;return e.subscribe(c=>{(i===void 0||n&&c!==i)&&o(i=c)})}return{notify:r,set:a,subscribe:s}}const ve={v:()=>{}};function Ze(){const{set:t,subscribe:e}=Nt(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Je}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const o=(await a.json()).version!==Xe;return o&&(t(!0),ve.v(),clearTimeout(n)),o}catch{return!1}}return{subscribe:e,check:r}}function Et(t,e,n){return t.origin!==Kt||!t.pathname.startsWith(e)?!0:n?t.pathname!==location.pathname:!1}function Un(t){}const ye=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...ye];const tn=new Set([...ye]);[...tn];function en(t){return t.filter(e=>e!=null)}function Bt(t){return t instanceof zt||t instanceof Dt?t.status:500}function nn(t){return t instanceof Dt?t.text:"Internal Error"}let R,X,Tt;const an=Zt.toString().includes("$$")||/function \w+\(\) \{\}/.test(Zt.toString());var nt,at,rt,ot,st,it,ct,lt,le,ft,fe,ut,ue;an?(R={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL("https://example.com")},X={current:null},Tt={current:!1}):(R=new(le=class{constructor(){U(this,nt,T({}));U(this,at,T(null));U(this,rt,T(null));U(this,ot,T({}));U(this,st,T({id:null}));U(this,it,T({}));U(this,ct,T(-1));U(this,lt,T(new URL("https://example.com")))}get data(){return I(w(this,nt))}set data(e){O(w(this,nt),e)}get form(){return I(w(this,at))}set form(e){O(w(this,at),e)}get error(){return I(w(this,rt))}set error(e){O(w(this,rt),e)}get params(){return I(w(this,ot))}set params(e){O(w(this,ot),e)}get route(){return I(w(this,st))}set route(e){O(w(this,st),e)}get state(){return I(w(this,it))}set state(e){O(w(this,it),e)}get status(){return I(w(this,ct))}set status(e){O(w(this,ct),e)}get url(){return I(w(this,lt))}set url(e){O(w(this,lt),e)}},nt=new WeakMap,at=new WeakMap,rt=new WeakMap,ot=new WeakMap,st=new WeakMap,it=new WeakMap,ct=new WeakMap,lt=new WeakMap,le),X=new(fe=class{constructor(){U(this,ft,T(null))}get current(){return I(w(this,ft))}set current(e){O(w(this,ft),e)}},ft=new WeakMap,fe),Tt=new(ue=class{constructor(){U(this,ut,T(!1))}get current(){return I(w(this,ut))}set current(e){O(w(this,ut),e)}},ut=new WeakMap,ue),ve.v=()=>Tt.current=!0);function rn(t){Object.assign(R,t)}const on=new Set(["icon","shortcut icon","apple-touch-icon"]),D=de(pe)??{},Q=de(he)??{},N={url:ne({}),page:ne({}),navigating:Nt(null),updated:Ze()};function Gt(t){D[t]=St()}function sn(t,e){let n=t+1;for(;D[n];)delete D[n],n+=1;for(n=e+1;Q[n];)delete Q[n],n+=1}function Z(t,e=!1){return e?location.replace(t.href):location.href=t.href,new Promise(()=>{})}async function be(){if("serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistration(A||"/");t&&await t.update()}}function ae(){}let Mt,Pt,mt,$,$t,b;const _t=[],wt=[];let v=null;function Ct(){var t;(t=v==null?void 0:v.fork)==null||t.then(e=>e==null?void 0:e.discard()),v=null}const ht=new Map,ke=new Set,cn=new Set,H=new Set;let m={branch:[],error:null,url:null},Se=!1,vt=!1,re=!0,tt=!1,W=!1,Ee=!1,Ft=!1,Re,S,L,q;const yt=new Set,oe=new Map;async function Pn(t,e,n){var s,o,i,c,l;(s=globalThis.__sveltekit_zurjbz)!=null&&s.data&&globalThis.__sveltekit_zurjbz.data,document.URL!==location.href&&(location.href=location.href),b=t,await((i=(o=t.hooks).init)==null?void 0:i.call(o)),Mt=He(t),$=document.documentElement,$t=e,Pt=t.nodes[0],mt=t.nodes[1],Pt(),mt(),S=(c=history.state)==null?void 0:c[M],L=(l=history.state)==null?void 0:l[J],S||(S=L=Date.now(),history.replaceState({...history.state,[M]:S,[J]:L},""));const r=D[S];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await kn($t,n)):(await F({type:"enter",url:me(b.hash?Rn(new URL(location.href)):location.href),replace_state:!0}),a()),bn()}function ln(){_t.length=0,Ft=!1}function xe(t){wt.some(e=>e==null?void 0:e.snapshot)&&(Q[t]=wt.map(e=>{var n;return(n=e==null?void 0:e.snapshot)==null?void 0:n.capture()}))}function Le(t){var e;(e=Q[t])==null||e.forEach((n,r)=>{var a,s;(s=(a=wt[r])==null?void 0:a.snapshot)==null||s.restore(n)})}function se(){Gt(S),te(pe,D),xe(L),te(he,Q)}async function fn(t,e,n,r){let a;e.invalidateAll&&Ct(),await F({type:"goto",url:me(t),keepfocus:e.keepFocus,noscroll:e.noScroll,replace_state:e.replaceState,state:e.state,redirect_count:n,nav_token:r,accept:()=>{e.invalidateAll&&(Ft=!0,a=[...oe.keys()]),e.invalidate&&e.invalidate.forEach(yn)}}),e.invalidateAll&&pt().then(pt).then(()=>{oe.forEach(({resource:s},o)=>{var i;a!=null&&a.includes(o)&&((i=s.refresh)==null||i.call(s))})})}async function un(t){if(t.id!==(v==null?void 0:v.id)){Ct();const e={};yt.add(e),v={id:t.id,token:e,promise:Ue({...t,preload:e}).then(n=>(yt.delete(e),n.type==="loaded"&&n.state.error&&Ct(),n)),fork:null}}return v.promise}async function It(t){var n;const e=(n=await Rt(t,!1))==null?void 0:n.route;e&&await Promise.all([...e.layouts,e.leaf].map(r=>r==null?void 0:r[1]()))}async function Ae(t,e,n){var a;m=t.state;const r=document.querySelector("style[data-sveltekit]");if(r&&r.remove(),Object.assign(R,t.props.page),Re=new b.root({target:e,props:{...t.props,stores:N,components:wt},hydrate:n,sync:!1}),await Promise.resolve(),Le(L),n){const s={from:null,to:{params:m.params,route:{id:((a=m.route)==null?void 0:a.id)??null},url:new URL(location.href)},willUnload:!1,type:"enter",complete:Promise.resolve()};H.forEach(o=>o(s))}vt=!0}function bt({url:t,params:e,branch:n,status:r,error:a,route:s,form:o}){let i="never";if(A&&(t.pathname===A||t.pathname===A+"/"))i="always";else for(const f of n)(f==null?void 0:f.slash)!==void 0&&(i=f.slash);t.pathname=je(t.pathname,i),t.search=t.search;const c={type:"loaded",state:{url:t,params:e,branch:n,error:a,route:s},props:{constructors:en(n).map(f=>f.node.component),page:Xt(R)}};o!==void 0&&(c.props.form=o);let l={},d=!R,u=0;for(let f=0;fi(new URL(o))))return!0;return!1}function Yt(t,e){return(t==null?void 0:t.type)==="data"?t:(t==null?void 0:t.type)==="skip"?e??null:null}function pn(t,e){if(!t)return new Set(e.searchParams.keys());const n=new Set([...t.searchParams.keys(),...e.searchParams.keys()]);for(const r of n){const a=t.searchParams.getAll(r),s=e.searchParams.getAll(r);a.every(o=>s.includes(o))&&s.every(o=>a.includes(o))&&n.delete(r)}return n}function gn({error:t,url:e,route:n,params:r}){return{type:"loaded",state:{error:t,url:e,route:n,params:r,branch:[]},props:{page:Xt(R),constructors:[]}}}async function Ue({id:t,invalidating:e,url:n,params:r,route:a,preload:s}){if((v==null?void 0:v.id)===t)return yt.delete(v.token),v.promise;const{errors:o,layouts:i,leaf:c}=a,l=[...i,c];o.forEach(g=>g==null?void 0:g().catch(()=>{})),l.forEach(g=>g==null?void 0:g[1]().catch(()=>{}));const d=m.url?t!==kt(m.url):!1,u=m.route?a.id!==m.route.id:!1,y=pn(m.url,n);let f=!1;const h=l.map(async(g,p)=>{var C;if(!g)return;const k=m.branch[p];return g[1]===(k==null?void 0:k.loader)&&!hn(f,u,d,y,(C=k.universal)==null?void 0:C.uses,r)?k:(f=!0,Wt({loader:g[1],url:n,params:r,route:a,parent:async()=>{var dt;const P={};for(let V=0;V{});const _=[];for(let g=0;gPromise.resolve({}),server_data_node:Yt(s)}),i={node:await mt(),loader:mt,universal:null,server:null,data:null};return bt({url:n,params:a,branch:[o,i],status:t,error:e,route:null})}catch(o){if(o instanceof qt)return fn(new URL(o.location,location.href),{},0);throw o}}async function _n(t){const e=t.href;if(ht.has(e))return ht.get(e);let n;try{const r=(async()=>{let a=await b.hooks.reroute({url:new URL(t),fetch:async(s,o)=>dn(s,o,t).promise})??t;if(typeof a=="string"){const s=new URL(t);b.hash?s.hash=a:s.pathname=a,a=s}return a})();ht.set(e,r),n=await r}catch{ht.delete(e);return}return n}async function Rt(t,e){if(t&&!Et(t,A,b.hash)){const n=await _n(t);if(!n)return;const r=wn(n);for(const a of Mt){const s=a.exec(r);if(s)return{id:kt(t),invalidating:e,route:a,params:ze(s),url:t}}}}function wn(t){return Ne(b.hash?t.hash.replace(/^#/,"").replace(/[?#].+/,""):t.pathname.slice(A.length))||"/"}function kt(t){return(b.hash?t.hash.replace(/^#/,""):t.pathname)+t.search}function Te({url:t,type:e,intent:n,delta:r,event:a}){let s=!1;const o=Jt(m,n,t,e);r!==void 0&&(o.navigation.delta=r),a!==void 0&&(o.navigation.event=a);const i={...o.navigation,cancel:()=>{s=!0,o.reject(new Error("navigation cancelled"))}};return tt||ke.forEach(c=>c(i)),s?null:o}async function F({type:t,url:e,popped:n,keepfocus:r,noscroll:a,replace_state:s,state:o={},redirect_count:i=0,nav_token:c={},accept:l=ae,block:d=ae,event:u}){var V;const y=q;q=c;const f=await Rt(e,!1),h=t==="enter"?Jt(m,f,e,t):Te({url:e,type:t,delta:n==null?void 0:n.delta,intent:f,event:u});if(!h){d(),q===c&&(q=y);return}const _=S,g=L;l(),tt=!0,vt&&h.navigation.type!=="enter"&&N.navigating.set(X.current=h.navigation);let p=f&&await Ue(f);if(!p){if(Et(e,A,b.hash))return await Z(e,s);p=await Ie(e,{id:null},await et(new Dt(404,"Not Found",`Not found: ${e.pathname}`),{url:e,params:{},route:{id:null}}),404,s)}if(e=(f==null?void 0:f.url)||e,q!==c)return h.reject(new Error("navigation aborted")),!1;if(p.type==="redirect"){if(i<20){await F({type:t,url:new URL(p.location,e),popped:n,keepfocus:r,noscroll:a,replace_state:s,state:o,redirect_count:i+1,nav_token:c}),h.fulfil(void 0);return}p=await Ht({status:500,error:await et(new Error("Redirect loop"),{url:e,params:{},route:{id:null}}),url:e,route:{id:null}})}else p.props.page.status>=400&&await N.updated.check()&&(await be(),await Z(e,s));if(ln(),Gt(_),xe(g),p.props.page.url.pathname!==e.pathname&&(e.pathname=p.props.page.url.pathname),o=n?n.state:o,!n){const E=s?0:1,K={[M]:S+=E,[J]:L+=E,[ge]:o};(s?history.replaceState:history.pushState).call(history,K,"",e),s||sn(S,L)}const k=f&&(v==null?void 0:v.id)===f.id?v.fork:null;v=null,p.props.page.state=o;let x;if(vt){const E=(await Promise.all(Array.from(cn,j=>j(h.navigation)))).filter(j=>typeof j=="function");if(E.length>0){let j=function(){E.forEach(xt=>{H.delete(xt)})};E.push(j),E.forEach(xt=>{H.add(xt)})}m=p.state,p.props.page&&(p.props.page.url=e);const K=k&&await k;K?x=K.commit():(Re.$set(p.props),rn(p.props.page),x=(V=Ce)==null?void 0:V()),Ee=!0}else await Ae(p,$t,!1);const{activeElement:C}=document;await x,await pt(),await pt();let P=n?n.scroll:a?St():null;if(re){const E=e.hash&&document.getElementById(Oe(e));if(P)scrollTo(P.x,P.y);else if(E){E.scrollIntoView();const{top:K,left:j}=E.getBoundingClientRect();P={x:pageXOffset+j,y:pageYOffset+K}}else scrollTo(0,0)}const dt=document.activeElement!==C&&document.activeElement!==document.body;!r&&!dt&&En(e,P),re=!0,p.props.page&&Object.assign(R,p.props.page),tt=!1,t==="popstate"&&Le(L),h.fulfil(void 0),H.forEach(E=>E(h.navigation)),N.navigating.set(X.current=null)}async function Ie(t,e,n,r,a){return t.origin===Kt&&t.pathname===location.pathname&&!Se?await Ht({status:r,error:n,url:t,route:e}):await Z(t,a)}function vn(){let t,e={element:void 0,href:void 0},n;$.addEventListener("mousemove",i=>{const c=i.target;clearTimeout(t),t=setTimeout(()=>{s(c,z.hover)},20)});function r(i){i.defaultPrevented||s(i.composedPath()[0],z.tap)}$.addEventListener("mousedown",r),$.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(i=>{for(const c of i)c.isIntersecting&&(It(new URL(c.target.href)),a.unobserve(c.target))},{threshold:0});async function s(i,c){const l=we(i,$),d=l===e.element&&(l==null?void 0:l.href)===e.href&&c>=n;if(!l||d)return;const{url:u,external:y,download:f}=Ot(l,A,b.hash);if(y||f)return;const h=gt(l),_=u&&kt(m.url)===kt(u);if(!(h.reload||_))if(c<=h.preload_data){e={element:l,href:l.href},n=z.tap;const g=await Rt(u,!1);if(!g)return;un(g)}else c<=h.preload_code&&(e={element:l,href:l.href},n=c,It(u))}function o(){a.disconnect();for(const i of $.querySelectorAll("a")){const{url:c,external:l,download:d}=Ot(i,A,b.hash);if(l||d)continue;const u=gt(i);u.reload||(u.preload_code===z.viewport&&a.observe(i),u.preload_code===z.eager&&It(c))}}H.add(o),o()}function et(t,e){if(t instanceof zt)return t.body;const n=Bt(t),r=nn(t);return b.hooks.handleError({error:t,event:e,status:n,message:r})??{message:r}}function yn(t){if(typeof t=="function")_t.push(t);else{const{href:e}=new URL(t,location.href);_t.push(n=>n.href===e)}}function bn(){var e;history.scrollRestoration="manual",addEventListener("beforeunload",n=>{let r=!1;if(se(),!tt){const a=Jt(m,void 0,null,"leave"),s={...a.navigation,cancel:()=>{r=!0,a.reject(new Error("navigation cancelled"))}};ke.forEach(o=>o(s))}r?(n.preventDefault(),n.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&se()}),(e=navigator.connection)!=null&&e.saveData||vn(),$.addEventListener("click",async n=>{if(n.button||n.which!==1||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.defaultPrevented)return;const r=we(n.composedPath()[0],$);if(!r)return;const{url:a,external:s,target:o,download:i}=Ot(r,A,b.hash);if(!a)return;if(o==="_parent"||o==="_top"){if(window.parent!==window)return}else if(o&&o!=="_self")return;const c=gt(r);if(!(r instanceof SVGAElement)&&a.protocol!==location.protocol&&!(a.protocol==="https:"||a.protocol==="http:")||i)return;const[d,u]=(b.hash?a.hash.replace(/^#/,""):a.href).split("#"),y=d===At(location);if(s||c.reload&&(!y||!u)){Te({url:a,type:"link",event:n})?tt=!0:n.preventDefault();return}if(u!==void 0&&y){const[,f]=m.url.href.split("#");if(f===u){if(n.preventDefault(),u===""||u==="top"&&r.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=r.ownerDocument.getElementById(decodeURIComponent(u));h&&(h.scrollIntoView(),h.focus())}return}if(W=!0,Gt(S),t(a),!c.replace_state)return;W=!1}n.preventDefault(),await new Promise(f=>{requestAnimationFrame(()=>{setTimeout(f,0)}),setTimeout(f,100)}),await F({type:"link",url:a,keepfocus:c.keepfocus,noscroll:c.noscroll,replace_state:c.replace_state??a.href===location.href,event:n})}),$.addEventListener("submit",n=>{if(n.defaultPrevented)return;const r=HTMLFormElement.prototype.cloneNode.call(n.target),a=n.submitter;if(((a==null?void 0:a.formTarget)||r.target)==="_blank"||((a==null?void 0:a.formMethod)||r.method)!=="get")return;const i=new URL((a==null?void 0:a.hasAttribute("formaction"))&&(a==null?void 0:a.formAction)||r.action);if(Et(i,A,!1))return;const c=n.target,l=gt(c);if(l.reload)return;n.preventDefault(),n.stopPropagation();const d=new FormData(c,a);i.search=new URLSearchParams(d).toString(),F({type:"form",url:i,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??i.href===location.href,event:n})}),addEventListener("popstate",async n=>{var r;if(!jt){if((r=n.state)!=null&&r[M]){const a=n.state[M];if(q={},a===S)return;const s=D[a],o=n.state[ge]??{},i=new URL(n.state[Qe]??location.href),c=n.state[J],l=m.url?At(location)===At(m.url):!1;if(c===L&&(Ee||l)){o!==R.state&&(R.state=o),t(i),D[S]=St(),s&&scrollTo(s.x,s.y),S=a;return}const u=a-S;await F({type:"popstate",url:i,popped:{state:o,scroll:s,delta:u},accept:()=>{S=a,L=c},block:()=>{history.go(-u)},nav_token:q,event:n})}else if(!W){const a=new URL(location.href);t(a),b.hash&&location.reload()}}}),addEventListener("hashchange",()=>{W&&(W=!1,history.replaceState({...history.state,[M]:++S,[J]:L},"",location.href))});for(const n of document.querySelectorAll("link"))on.has(n.rel)&&(n.href=n.href);addEventListener("pageshow",n=>{n.persisted&&N.navigating.set(X.current=null)});function t(n){m.url=R.url=n,N.page.set(Xt(R)),N.page.notify()}}async function kn(t,{status:e=200,error:n,node_ids:r,params:a,route:s,server_route:o,data:i,form:c}){Se=!0;const l=new URL(location.href);let d;({params:a={},route:s={id:null}}=await Rt(l,!1)||{}),d=Mt.find(({id:f})=>f===s.id);let u,y=!0;try{const f=r.map(async(_,g)=>{const p=i[g];return p!=null&&p.uses&&(p.uses=Sn(p.uses)),Wt({loader:b.nodes[_],url:l,params:a,route:s,parent:async()=>{const k={};for(let x=0;x{const i=history.state;jt=!0,location.replace(`#${r}`),b.hash&&location.replace(t.hash),history.replaceState(i,"",t.hash),scrollTo(s,o),jt=!1})}else{const s=document.body,o=s.getAttribute("tabindex");s.tabIndex=-1,s.focus({preventScroll:!0,focusVisible:!1}),o!==null?s.setAttribute("tabindex",o):s.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const s=[];for(let o=0;o{if(a.rangeCount===s.length){for(let o=0;o{a=d,s=u});return o.catch(()=>{}),{navigation:{from:{params:t.params,route:{id:((c=t.route)==null?void 0:c.id)??null},url:t.url},to:n&&{params:(e==null?void 0:e.params)??null,route:{id:((l=e==null?void 0:e.route)==null?void 0:l.id)??null},url:n},willUnload:!e,type:r,complete:o},fulfil:a,reject:s}}function Xt(t){return{data:t.data,error:t.error,form:t.form,params:t.params,route:t.route,state:t.state,status:t.status,url:t.url}}function Rn(t){const e=new URL(t);return e.hash=decodeURIComponent(t.hash),e}function Oe(t){let e;if(b.hash){const[,,n]=t.hash.split("#",3);e=n??""}else e=t.hash.slice(1);return decodeURIComponent(e)}export{Pn as a,Un as l,R as p,N as s}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js new file mode 100644 index 0000000..7a7a219 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js @@ -0,0 +1 @@ +var lt=Object.defineProperty;var pn=e=>{throw TypeError(e)};var at=(e,n,t)=>n in e?lt(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var Q=(e,n,t)=>at(e,typeof n!="symbol"?n+"":n,t),Ke=(e,n,t)=>n.has(e)||pn("Cannot "+t);var d=(e,n,t)=>(Ke(e,n,"read from private field"),t?t.call(e):n.get(e)),F=(e,n,t)=>n.has(e)?pn("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),K=(e,n,t,r)=>(Ke(e,n,"write to private field"),r?r.call(e,t):n.set(e,t),t),ce=(e,n,t)=>(Ke(e,n,"access private method"),t);var ut=Array.isArray,ot=Array.prototype.indexOf,we=Array.prototype.includes,Zt=Array.from,Jt=Object.defineProperty,be=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyDescriptors,_t=Object.prototype,vt=Array.prototype,bn=Object.getPrototypeOf,hn=Object.isExtensible;const Wt=()=>{};function Xt(e){return e()}function dt(e){for(var n=0;n{e=r,n=s});return{promise:t,resolve:e,reject:n}}const A=2,Me=4,Oe=8,Rn=1<<24,G=16,U=32,oe=64,Sn=128,N=512,E=1024,x=2048,q=4096,L=8192,$=16384,rn=32768,je=65536,wn=1<<17,xn=1<<18,De=1<<19,kn=1<<20,ie=32768,$e=1<<21,sn=1<<22,Z=1<<23,Ae=Symbol("$state"),Qt=Symbol("legacy props"),_e=new class extends Error{constructor(){super(...arguments);Q(this,"name","StaleReactionError");Q(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Ve=3,On=8;function pt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function ht(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function wt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function yt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function gt(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function nr(){throw new Error("https://svelte.dev/e/hydration_failed")}function tr(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function mt(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function Et(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Tt(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function rr(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const sr=1,fr=2,ir=4,lr=8,ar=16,ur=1,or=2,bt="[",At="[!",Rt="]",fn={},T=Symbol();function ln(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function cr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let le=!1;function _r(e){le=e}let m;function ye(e){if(e===null)throw ln(),fn;return m=e}function vr(){return ye(X(m))}function dr(e){if(le){if(X(m)!==null)throw ln(),fn;m=e}}function pr(e=1){if(le){for(var n=e,t=m;n--;)t=X(t);m=t}}function hr(e=!0){for(var n=0,t=m;;){if(t.nodeType===On){var r=t.data;if(r===Rt){if(n===0)return t;n-=1}else(r===bt||r===At)&&(n+=1)}var s=X(t);e&&t.remove(),t=s}}function wr(e){if(!e||e.nodeType!==On)throw ln(),fn;return e.data}function Dn(e){return e===this.v}function St(e,n){return e!=e?n==n:e!==n||e!==null&&typeof e=="object"||typeof e=="function"}function Pn(e){return!St(e,this.v)}let Be=!1;function yr(){Be=!0}let S=null;function Le(e){S=e}function gr(e,n=!1,t){S={p:S,i:!1,c:null,e:null,s:e,x:null,l:Be&&!n?{s:null,u:null,$:[]}:null}}function mr(e){var n=S,t=n.e;if(t!==null){n.e=null;for(var r of t)$n(r)}return n.i=!0,S=n.p,{}}function Pe(){return!Be||S!==null&&S.l===null}let ne=[];function Nn(){var e=ne;ne=[],dt(e)}function yn(e){if(ne.length===0&&!Re){var n=ne;queueMicrotask(()=>{n===ne&&Nn()})}ne.push(e)}function xt(){for(;ne.length>0;)Nn()}function kt(e){var n=w;if(n===null)return v.f|=Z,e;if(n.f&rn)qe(e,n);else{if(!(n.f&Sn))throw e;n.b.error(e)}}function qe(e,n){for(;n!==null;){if(n.f&Sn)try{n.b.error(e);return}catch(t){e=t}n=n.parent}throw e}const Ot=-7169;function y(e,n){e.f=e.f&Ot|n}function an(e){e.f&N||e.deps===null?y(e,E):y(e,q)}function In(e){if(e!==null)for(const n of e)!(n.f&A)||!(n.f&ie)||(n.f^=ie,In(n.deps))}function Dt(e,n,t){e.f&x?n.add(e):e.f&q&&t.add(e),In(e.deps),y(e,E)}const Fe=new Set;let p=null,b=null,k=[],He=null,Ze=!1,Re=!1;var ve,de,re,pe,xe,ke,se,B,he,Y,Je,We,Fn;const vn=class vn{constructor(){F(this,Y);Q(this,"committed",!1);Q(this,"current",new Map);Q(this,"previous",new Map);F(this,ve,new Set);F(this,de,new Set);F(this,re,0);F(this,pe,0);F(this,xe,null);F(this,ke,new Set);F(this,se,new Set);F(this,B,new Map);Q(this,"is_fork",!1);F(this,he,!1)}is_deferred(){return this.is_fork||d(this,pe)>0}skip_effect(n){d(this,B).has(n)||d(this,B).set(n,{d:[],m:[]})}unskip_effect(n){var t=d(this,B).get(n);if(t){d(this,B).delete(n);for(var r of t.d)y(r,x),H(r);for(r of t.m)y(r,q),H(r)}}process(n){var s;k=[],this.apply();var t=[],r=[];for(const f of n)ce(this,Y,Je).call(this,f,t,r);if(this.is_deferred()){ce(this,Y,We).call(this,r),ce(this,Y,We).call(this,t);for(const[f,i]of d(this,B))Ln(f,i)}else{for(const f of d(this,ve))f();d(this,ve).clear(),d(this,re)===0&&ce(this,Y,Fn).call(this),p=null,gn(r),gn(t),(s=d(this,xe))==null||s.resolve()}b=null}capture(n,t){t!==T&&!this.previous.has(n)&&this.previous.set(n,t),n.f&Z||(this.current.set(n,n.v),b==null||b.set(n,n.v))}activate(){p=this,this.apply()}deactivate(){p===this&&(p=null,b=null)}flush(){if(this.activate(),k.length>0){if(Cn(),p!==null&&p!==this)return}else d(this,re)===0&&this.process([]);this.deactivate()}discard(){for(const n of d(this,de))n(this);d(this,de).clear()}increment(n){K(this,re,d(this,re)+1),n&&K(this,pe,d(this,pe)+1)}decrement(n){K(this,re,d(this,re)-1),n&&K(this,pe,d(this,pe)-1),!d(this,he)&&(K(this,he,!0),yn(()=>{K(this,he,!1),this.is_deferred()?k.length>0&&this.flush():this.revive()}))}revive(){for(const n of d(this,ke))d(this,se).delete(n),y(n,x),H(n);for(const n of d(this,se))y(n,q),H(n);this.flush()}oncommit(n){d(this,ve).add(n)}ondiscard(n){d(this,de).add(n)}settled(){return(d(this,xe)??K(this,xe,An())).promise}static ensure(){if(p===null){const n=p=new vn;Fe.add(p),Re||yn(()=>{p===n&&n.flush()})}return p}apply(){}};ve=new WeakMap,de=new WeakMap,re=new WeakMap,pe=new WeakMap,xe=new WeakMap,ke=new WeakMap,se=new WeakMap,B=new WeakMap,he=new WeakMap,Y=new WeakSet,Je=function(n,t,r){n.f^=E;for(var s=n.first,f=null;s!==null;){var i=s.f,u=(i&(U|oe))!==0,l=u&&(i&E)!==0,a=l||(i&L)!==0||d(this,B).has(s);if(!a&&s.fn!==null){u?s.f^=E:f!==null&&i&(Me|Oe|Rn)?f.b.defer_effect(s):i&Me?t.push(s):Ne(s)&&(i&G&&d(this,se).add(s),Se(s));var o=s.first;if(o!==null){s=o;continue}}var _=s.parent;for(s=s.next;s===null&&_!==null;)_===f&&(f=null),s=_.next,_=_.parent}},We=function(n){for(var t=0;t1){this.previous.clear();var n=b,t=!0;for(const f of Fe){if(f===this){t=!1;continue}const i=[];for(const[l,a]of this.current){if(f.current.has(l))if(t&&a!==f.current.get(l))f.current.set(l,a);else continue;i.push(l)}if(i.length===0)continue;const u=[...f.current.keys()].filter(l=>!this.current.has(l));if(u.length>0){var r=k;k=[];const l=new Set,a=new Map;for(const o of i)Mn(o,u,l,a);if(k.length>0){p=f,f.apply();for(const o of k)ce(s=f,Y,Je).call(s,o,[],[]);f.deactivate()}k=r}}p=null,b=n}this.committed=!0,Fe.delete(this)};let ge=vn;function Pt(e){var n=Re;Re=!0;try{for(var t;;){if(xt(),k.length===0&&(p==null||p.flush(),k.length===0))return He=null,t;Cn()}}finally{Re=n}}function Cn(){Ze=!0;var e=null;try{for(var n=0;k.length>0;){var t=ge.ensure();if(n++>1e3){var r,s;Nt()}t.process(k),J.clear()}}finally{k=[],Ze=!1,He=null}}function Nt(){try{gt()}catch(e){qe(e,He)}}let C=null;function gn(e){var n=e.length;if(n!==0){for(var t=0;t0)){J.clear();for(const s of C){if(s.f&($|L))continue;const f=[s];let i=s.parent;for(;i!==null;)C.has(i)&&(C.delete(i),f.push(i)),i=i.parent;for(let u=f.length-1;u>=0;u--){const l=f[u];l.f&($|L)||Se(l)}}C.clear()}}C=null}}function Mn(e,n,t,r){if(!t.has(e)&&(t.add(e),e.reactions!==null))for(const s of e.reactions){const f=s.f;f&A?Mn(s,n,t,r):f&(sn|G)&&!(f&x)&&jn(s,n,r)&&(y(s,x),H(s))}}function jn(e,n,t){const r=t.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(we.call(n,s))return!0;if(s.f&A&&jn(s,n,t))return t.set(s,!0),!0}return t.set(e,!1),!1}function H(e){for(var n=He=e;n.parent!==null;){n=n.parent;var t=n.f;if(Ze&&n===w&&t&G&&!(t&xn))return;if(t&(oe|U)){if(!(t&E))return;n.f^=E}}k.push(n)}function Ln(e,n){if(!(e.f&U&&e.f&E)){e.f&x?n.d.push(e):e.f&q&&n.m.push(e),y(e,E);for(var t=e.first;t!==null;)Ln(t,n),t=t.next}}function It(e,n,t,r){const s=Pe()?un:Mt;var f=e.filter(c=>!c.settled);if(t.length===0&&f.length===0){r(n.map(s));return}var i=p,u=w,l=Ft(),a=f.length===1?f[0].promise:f.length>1?Promise.all(f.map(c=>c.promise)):null;function o(c){l();try{r(c)}catch(g){u.f&$||qe(g,u)}i==null||i.deactivate(),Xe()}if(t.length===0){a.then(()=>o(n.map(s)));return}function _(){l(),Promise.all(t.map(c=>Ct(c))).then(c=>o([...n.map(s),...c])).catch(c=>qe(c,u))}a?a.then(_):_()}function Ft(){var e=w,n=v,t=S,r=p;return function(f=!0){me(e),W(n),Le(t),f&&(r==null||r.activate())}}function Xe(){me(null),W(null),Le(null)}function un(e){var n=A|x,t=v!==null&&v.f&A?v:null;return w!==null&&(w.f|=De),{ctx:S,deps:null,effects:null,equals:Dn,f:n,fn:e,reactions:null,rv:0,v:T,wv:0,parent:t??w,ac:null}}function Ct(e,n,t){let r=w;r===null&&pt();var s=r.b,f=void 0,i=cn(T),u=!v,l=new Map;return Vt(()=>{var g;var a=An();f=a.promise;try{Promise.resolve(e()).then(a.resolve,a.reject).then(()=>{o===p&&o.committed&&o.deactivate(),Xe()})}catch(h){a.reject(h),Xe()}var o=p;if(u){var _=s.is_rendered();s.update_pending_count(1),o.increment(_),(g=l.get(o))==null||g.reject(_e),l.delete(o),l.set(o,a)}const c=(h,j=void 0)=>{if(o.activate(),j)j!==_e&&(i.f|=Z,en(i,j));else{i.f&Z&&(i.f^=Z),en(i,h);for(const[R,Ie]of l){if(l.delete(R),R===o)break;Ie.reject(_e)}}u&&(s.update_pending_count(-1),o.decrement(_))};a.promise.then(c,h=>c(null,h||"unknown"))}),Ut(()=>{for(const a of l.values())a.reject(_e)}),new Promise(a=>{function o(_){function c(){_===f?a(i):o(f)}_.then(c,c)}o(f)})}function Er(e){const n=un(e);return et(n),n}function Mt(e){const n=un(e);return n.equals=Pn,n}function qn(e){var n=e.effects;if(n!==null){e.effects=null;for(var t=0;t0&&!Un&&Lt()}return n}function Lt(){Un=!1;for(const e of Qe)e.f&E&&y(e,q),Ne(e)&&Se(e);Qe.clear()}function ze(e){ee(e,e.v+1)}function Vn(e,n){var t=e.reactions;if(t!==null)for(var r=Pe(),s=t.length,f=0;f{if(fe===f)return u();var l=v,a=fe;W(null),Tn(f);var o=u();return W(l),Tn(a),o};return r&&t.set("length",z(e.length)),new Proxy(e,{defineProperty(u,l,a){(!("value"in a)||a.configurable===!1||a.enumerable===!1||a.writable===!1)&&mt();var o=t.get(l);return o===void 0?o=i(()=>{var _=z(a.value);return t.set(l,_),_}):ee(o,a.value,!0),!0},deleteProperty(u,l){var a=t.get(l);if(a===void 0){if(l in u){const o=i(()=>z(T));t.set(l,o),ze(s)}}else ee(a,T),ze(s);return!0},get(u,l,a){var g;if(l===Ae)return e;var o=t.get(l),_=l in u;if(o===void 0&&(!_||(g=be(u,l))!=null&&g.writable)&&(o=i(()=>{var h=Ee(_?u[l]:T),j=z(h);return j}),t.set(l,o)),o!==void 0){var c=Te(o);return c===T?void 0:c}return Reflect.get(u,l,a)},getOwnPropertyDescriptor(u,l){var a=Reflect.getOwnPropertyDescriptor(u,l);if(a&&"value"in a){var o=t.get(l);o&&(a.value=Te(o))}else if(a===void 0){var _=t.get(l),c=_==null?void 0:_.v;if(_!==void 0&&c!==T)return{enumerable:!0,configurable:!0,value:c,writable:!0}}return a},has(u,l){var c;if(l===Ae)return!0;var a=t.get(l),o=a!==void 0&&a.v!==T||Reflect.has(u,l);if(a!==void 0||w!==null&&(!o||(c=be(u,l))!=null&&c.writable)){a===void 0&&(a=i(()=>{var g=o?Ee(u[l]):T,h=z(g);return h}),t.set(l,a));var _=Te(a);if(_===T)return!1}return o},set(u,l,a,o){var dn;var _=t.get(l),c=l in u;if(r&&l==="length")for(var g=a;g<_.v;g+=1){var h=t.get(g+"");h!==void 0?ee(h,T):g in u&&(h=i(()=>z(T)),t.set(g+"",h))}if(_===void 0)(!c||(dn=be(u,l))!=null&&dn.writable)&&(_=i(()=>z(void 0)),ee(_,Ee(a)),t.set(l,_));else{c=_.v!==T;var j=i(()=>Ee(a));ee(_,j)}var R=Reflect.getOwnPropertyDescriptor(u,l);if(R!=null&&R.set&&R.set.call(o,a),!c){if(r&&typeof l=="string"){var Ie=t.get("length"),Ge=Number(l);Number.isInteger(Ge)&&Ge>=Ie.v&&ee(Ie,Ge+1)}ze(s)}return!0},ownKeys(u){Te(s);var l=Reflect.ownKeys(u).filter(_=>{var c=t.get(_);return c===void 0||c.v!==T});for(var[a,o]of t)o.v!==T&&!(a in u)&&l.push(a);return l},setPrototypeOf(){Et()}})}var mn,qt,Bn,Hn;function br(){if(mn===void 0){mn=window,qt=/Firefox/.test(navigator.userAgent);var e=Element.prototype,n=Node.prototype,t=Text.prototype;Bn=be(n,"firstChild").get,Hn=be(n,"nextSibling").get,hn(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),hn(t)&&(t.__t=void 0)}}function Ye(e=""){return document.createTextNode(e)}function nn(e){return Bn.call(e)}function X(e){return Hn.call(e)}function Ar(e,n){if(!le)return nn(e);var t=nn(m);if(t===null)t=m.appendChild(Ye());else if(n&&t.nodeType!==Ve){var r=Ye();return t==null||t.before(r),ye(r),r}return n&&_n(t),ye(t),t}function Rr(e,n=!1){if(!le){var t=nn(e);return t instanceof Comment&&t.data===""?X(t):t}if(n){if((m==null?void 0:m.nodeType)!==Ve){var r=Ye();return m==null||m.before(r),ye(r),r}_n(m)}return m}function Sr(e,n=1,t=!1){let r=le?m:e;for(var s;n--;)s=r,r=X(r);if(!le)return r;if(t){if((r==null?void 0:r.nodeType)!==Ve){var f=Ye();return r===null?s==null||s.after(f):r.before(f),ye(f),f}_n(r)}return ye(r),r}function xr(e){e.textContent=""}function kr(){return!1}function _n(e){if(e.nodeValue.length<65536)return;let n=e.nextSibling;for(;n!==null&&n.nodeType===Ve;)n.remove(),e.nodeValue+=n.nodeValue,n=e.nextSibling}function Gn(e){var n=v,t=w;W(null),me(null);try{return e()}finally{W(n),me(t)}}function Kn(e){w===null&&(v===null&&yt(),wt()),ue&&ht()}function Yt(e,n){var t=n.last;t===null?n.last=n.first=e:(t.next=e,e.prev=t,n.last=e)}function V(e,n,t){var r=w;r!==null&&r.f&L&&(e|=L);var s={ctx:S,deps:null,nodes:null,f:e|x|N,first:null,fn:n,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};if(t)try{Se(s),s.f|=rn}catch(u){throw ae(s),u}else n!==null&&H(s);var f=s;if(t&&f.deps===null&&f.teardown===null&&f.nodes===null&&f.first===f.last&&!(f.f&De)&&(f=f.first,e&G&&e&je&&f!==null&&(f.f|=je)),f!==null&&(f.parent=r,r!==null&&Yt(f,r),v!==null&&v.f&A&&!(e&oe))){var i=v;(i.effects??(i.effects=[])).push(f)}return s}function zn(){return v!==null&&!M}function Ut(e){const n=V(Oe,null,!1);return y(n,E),n.teardown=e,n}function Or(e){Kn();var n=w.f,t=!v&&(n&U)!==0&&(n&rn)===0;if(t){var r=S;(r.e??(r.e=[])).push(e)}else return $n(e)}function $n(e){return V(Me|kn,e,!1)}function Dr(e){return Kn(),V(Oe|kn,e,!0)}function Pr(e){ge.ensure();const n=V(oe|De,e,!0);return(t={})=>new Promise(r=>{t.outro?Gt(n,()=>{ae(n),r(void 0)}):(ae(n),r(void 0))})}function Nr(e){return V(Me,e,!1)}function Vt(e){return V(sn|De,e,!0)}function Ir(e,n=0){return V(Oe|n,e,!0)}function Fr(e,n=[],t=[],r=[]){It(r,n,t,s=>{V(Oe,()=>e(...s.map(Te)),!0)})}function Cr(e,n=0){var t=V(G|n,e,!0);return t}function Mr(e){return V(U|De,e,!0)}function Zn(e){var n=e.teardown;if(n!==null){const t=ue,r=v;En(!0),W(null);try{n.call(null)}finally{En(t),W(r)}}}function Jn(e,n=!1){var t=e.first;for(e.first=e.last=null;t!==null;){const s=t.ac;s!==null&&Gn(()=>{s.abort(_e)});var r=t.next;t.f&oe?t.parent=null:ae(t,n),t=r}}function Bt(e){for(var n=e.first;n!==null;){var t=n.next;n.f&U||ae(n),n=t}}function ae(e,n=!0){var t=!1;(n||e.f&xn)&&e.nodes!==null&&e.nodes.end!==null&&(Ht(e.nodes.start,e.nodes.end),t=!0),Jn(e,n&&!t),Ue(e,0),y(e,$);var r=e.nodes&&e.nodes.t;if(r!==null)for(const f of r)f.stop();Zn(e);var s=e.parent;s!==null&&s.first!==null&&Wn(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=null}function Ht(e,n){for(;e!==null;){var t=e===n?null:X(e);e.remove(),e=t}}function Wn(e){var n=e.parent,t=e.prev,r=e.next;t!==null&&(t.next=r),r!==null&&(r.prev=t),n!==null&&(n.first===e&&(n.first=r),n.last===e&&(n.last=t))}function Gt(e,n,t=!0){var r=[];Xn(e,r,!0);var s=()=>{t&&ae(e),n&&n()},f=r.length;if(f>0){var i=()=>--f||s();for(var u of r)u.out(i)}else s()}function Xn(e,n,t){if(!(e.f&L)){e.f^=L;var r=e.nodes&&e.nodes.t;if(r!==null)for(const u of r)(u.is_global||t)&&n.push(u);for(var s=e.first;s!==null;){var f=s.next,i=(s.f&je)!==0||(s.f&U)!==0&&(e.f&G)!==0;Xn(s,n,i?t:!1),s=f}}}function jr(e){Qn(e,!0)}function Qn(e,n){if(e.f&L){e.f^=L,e.f&E||(y(e,x),H(e));for(var t=e.first;t!==null;){var r=t.next,s=(t.f&je)!==0||(t.f&U)!==0;Qn(t,s?n:!1),t=r}var f=e.nodes&&e.nodes.t;if(f!==null)for(const i of f)(i.is_global||n)&&i.in()}}function Lr(e,n){if(e.nodes)for(var t=e.nodes.start,r=e.nodes.end;t!==null;){var s=t===r?null:X(t);n.append(t),t=s}}let Ce=!1,ue=!1;function En(e){ue=e}let v=null,M=!1;function W(e){v=e}let w=null;function me(e){w=e}let I=null;function et(e){v!==null&&(I===null?I=[e]:I.push(e))}let O=null,D=0,P=null;function Kt(e){P=e}let nt=1,te=0,fe=te;function Tn(e){fe=e}function tt(){return++nt}function Ne(e){var n=e.f;if(n&x)return!0;if(n&A&&(e.f&=~ie),n&q){for(var t=e.deps,r=t.length,s=0;se.wv)return!0}n&N&&b===null&&y(e,E)}return!1}function rt(e,n,t=!0){var r=e.reactions;if(r!==null&&!(I!==null&&we.call(I,e)))for(var s=0;s{e.ac.abort(_e)}),e.ac=null);try{e.f|=$e;var o=e.fn,_=o(),c=e.deps,g=p==null?void 0:p.is_fork;if(O!==null){var h;if(g||Ue(e,D),c!==null&&D>0)for(c.length=D+O.length,h=0;h",""),n.content}function t(r,n){var e=l;e.nodes===null&&(e.nodes={start:r,end:n,a:null,t:null})}function M(r,n){var e=(n&p)!==0,_=(n&T)!==0,a,m=!r.startsWith("");return()=>{if(d)return t(o,null),o;a===void 0&&(a=w(m?r:""+r),e||(a=f(a)));var s=_||E?document.importNode(a,!0):a.cloneNode(!0);if(e){var c=f(s),v=s.lastChild;t(c,v)}else t(s,s);return s}}function F(r=""){if(!d){var n=i(r+"");return t(n,n),n}var e=o;return e.nodeType!==x?(e.before(e=i()),y(e)):N(e),t(e,e),e}function L(){if(d)return t(o,null),o;var r=document.createDocumentFragment(),n=document.createComment(""),e=i();return r.append(n,e),t(n,e),r}function O(r,n){if(d){var e=l;(!(e.f&h)||e.nodes.end===null)&&(e.nodes.end=o),g();return}r!==null&&r.before(n)}const A="5";var u;typeof window<"u"&&((u=window.__svelte??(window.__svelte={})).v??(u.v=new Set)).add(A);export{O as a,t as b,L as c,M as f,F as t}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js new file mode 100644 index 0000000..e23b8da --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js @@ -0,0 +1 @@ +import{u as o,c as t,l as c,b as u}from"./B_PiQ68N.js";function l(n){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function r(n){t===null&&l(),c&&t.l!==null?a(t).m.push(n):o(()=>{const e=u(n);if(typeof e=="function")return e})}function a(n){var e=n.l;return e.u??(e.u={a:[],b:[],m:[]})}export{r as o}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js new file mode 100644 index 0000000..fa3c840 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js @@ -0,0 +1 @@ +import{e}from"./B_PiQ68N.js";e(); diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js new file mode 100644 index 0000000..a071743 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js @@ -0,0 +1,2 @@ +var De=Object.defineProperty;var ue=s=>{throw TypeError(s)};var ke=(s,e,i)=>e in s?De(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i;var Z=(s,e,i)=>ke(s,typeof e!="symbol"?e+"":e,i),ee=(s,e,i)=>e.has(s)||ue("Cannot "+i);var t=(s,e,i)=>(ee(s,e,"read from private field"),i?i.call(s):e.get(s)),h=(s,e,i)=>e.has(s)?ue("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,i),n=(s,e,i,a)=>(ee(s,e,"write to private field"),a?a.call(s,i):e.set(s,i),i),c=(s,e,i)=>(ee(s,e,"access private method"),i);import{D as Ae,i as me,F as Oe,G as be,b as Fe,H as _e,I as j,z as A,h as O,v as H,J as Ye,K as k,L as te,M as se,q as Ee,N as Ie,O as G,P as J,Q as de,R as Me,S as Te,c as we,U as Be,V as ce,W as Ce,X as pe,Y as Le,Z as Pe,_ as ie,B as K,$ as Ve,a0 as He,a1 as ge,a2 as qe,a3 as xe,a as We,a4 as oe,a5 as $e,a6 as je,a7 as Ue,a8 as ze,a9 as Ge,aa as re,w as Je,ab as Ke,ac as Qe,ad as ne,ae as W,af as Xe,ag as Ze,ah as et,ai as tt,p as st,aj as it,ak as rt,m as nt}from"./B_PiQ68N.js";import{b as at}from"./C8WMVNin.js";function ht(s){let e=0,i=be(0),a;return()=>{Ae()&&(me(i),Oe(()=>(e===0&&(a=Fe(()=>s(()=>_e(i)))),e+=1,()=>{j(()=>{e-=1,e===0&&(a==null||a(),a=void 0,_e(i))})})))}}var ft=je|Ue|ze;function ot(s,e,i){new lt(s,e,i)}var p,q,y,F,m,v,d,b,w,N,Y,R,C,I,L,P,S,Q,f,Re,Se,ae,U,z,he;class lt{constructor(e,i,a){h(this,f);Z(this,"parent");Z(this,"is_pending",!1);h(this,p);h(this,q,O?A:null);h(this,y);h(this,F);h(this,m);h(this,v,null);h(this,d,null);h(this,b,null);h(this,w,null);h(this,N,null);h(this,Y,0);h(this,R,0);h(this,C,!1);h(this,I,!1);h(this,L,new Set);h(this,P,new Set);h(this,S,null);h(this,Q,ht(()=>(n(this,S,be(t(this,Y))),()=>{n(this,S,null)})));n(this,p,e),n(this,y,i),n(this,F,a),this.parent=H.b,this.is_pending=!!t(this,y).pending,n(this,m,Ye(()=>{if(H.b=this,O){const r=t(this,q);We(),r.nodeType===oe&&r.data===$e?c(this,f,Se).call(this):(c(this,f,Re).call(this),t(this,R)===0&&(this.is_pending=!1))}else{var l=c(this,f,ae).call(this);try{n(this,v,k(()=>a(l)))}catch(r){this.error(r)}t(this,R)>0?c(this,f,z).call(this):this.is_pending=!1}return()=>{var r;(r=t(this,N))==null||r.remove()}},ft)),O&&n(this,p,A)}defer_effect(e){Ie(e,t(this,L),t(this,P))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!t(this,y).pending}update_pending_count(e){c(this,f,he).call(this,e),n(this,Y,t(this,Y)+e),!(!t(this,S)||t(this,C))&&(n(this,C,!0),j(()=>{n(this,C,!1),t(this,S)&&Pe(t(this,S),t(this,Y))}))}get_effect_pending(){return t(this,Q).call(this),me(t(this,S))}error(e){var i=t(this,y).onerror;let a=t(this,y).failed;if(t(this,I)||!i&&!a)throw e;t(this,v)&&(ie(t(this,v)),n(this,v,null)),t(this,d)&&(ie(t(this,d)),n(this,d,null)),t(this,b)&&(ie(t(this,b)),n(this,b,null)),O&&(K(t(this,q)),Ve(),K(He()));var l=!1,r=!1;const _=()=>{if(l){xe();return}l=!0,r&&qe(),te.ensure(),n(this,Y,0),t(this,b)!==null&&se(t(this,b),()=>{n(this,b,null)}),this.is_pending=this.has_pending_snippet(),n(this,v,c(this,f,U).call(this,()=>(n(this,I,!1),k(()=>t(this,F).call(this,t(this,p)))))),t(this,R)>0?c(this,f,z).call(this):this.is_pending=!1};j(()=>{try{r=!0,i==null||i(e,_),r=!1}catch(g){ge(g,t(this,m)&&t(this,m).parent)}a&&n(this,b,c(this,f,U).call(this,()=>{te.ensure(),n(this,I,!0);try{return k(()=>{a(t(this,p),()=>e,()=>_)})}catch(g){return ge(g,t(this,m).parent),null}finally{n(this,I,!1)}}))})}}p=new WeakMap,q=new WeakMap,y=new WeakMap,F=new WeakMap,m=new WeakMap,v=new WeakMap,d=new WeakMap,b=new WeakMap,w=new WeakMap,N=new WeakMap,Y=new WeakMap,R=new WeakMap,C=new WeakMap,I=new WeakMap,L=new WeakMap,P=new WeakMap,S=new WeakMap,Q=new WeakMap,f=new WeakSet,Re=function(){try{n(this,v,k(()=>t(this,F).call(this,t(this,p))))}catch(e){this.error(e)}},Se=function(){const e=t(this,y).pending;e&&(n(this,d,k(()=>e(t(this,p)))),j(()=>{var i=c(this,f,ae).call(this);n(this,v,c(this,f,U).call(this,()=>(te.ensure(),k(()=>t(this,F).call(this,i))))),t(this,R)>0?c(this,f,z).call(this):(se(t(this,d),()=>{n(this,d,null)}),this.is_pending=!1)}))},ae=function(){var e=t(this,p);return this.is_pending&&(n(this,N,Ee()),t(this,p).before(t(this,N)),e=t(this,N)),e},U=function(e){var i=H,a=Te,l=we;G(t(this,m)),J(t(this,m)),de(t(this,m).ctx);try{return e()}catch(r){return Me(r),null}finally{G(i),J(a),de(l)}},z=function(){const e=t(this,y).pending;t(this,v)!==null&&(n(this,w,document.createDocumentFragment()),t(this,w).append(t(this,N)),Be(t(this,v),t(this,w))),t(this,d)===null&&n(this,d,k(()=>e(t(this,p))))},he=function(e){var i;if(!this.has_pending_snippet()){this.parent&&c(i=this.parent,f,he).call(i,e);return}if(n(this,R,t(this,R)+e),t(this,R)===0){this.is_pending=!1;for(const a of t(this,L))ce(a,Ce),pe(a);for(const a of t(this,P))ce(a,Le),pe(a);t(this,L).clear(),t(this,P).clear(),t(this,d)&&se(t(this,d),()=>{n(this,d,null)}),t(this,w)&&(t(this,p).before(t(this,w)),n(this,w,null))}};const ut=["touchstart","touchmove"];function _t(s){return ut.includes(s)}const dt=new Set,ve=new Set;let ye=null;function $(s){var le;var e=this,i=e.ownerDocument,a=s.type,l=((le=s.composedPath)==null?void 0:le.call(s))||[],r=l[0]||s.target;ye=s;var _=0,g=ye===s&&s.__root;if(g){var D=l.indexOf(g);if(D!==-1&&(e===document||e===window)){s.__root=e;return}var M=l.indexOf(e);if(M===-1)return;D<=M&&(_=D)}if(r=l[_]||s.target,r!==e){Ge(s,"currentTarget",{configurable:!0,get(){return r||i}});var X=Te,E=H;J(null),G(null);try{for(var o,u=[];r!==null;){var T=r.assignedSlot||r.parentNode||r.host||null;try{var V=r["__"+a];V!=null&&(!r.disabled||s.target===r)&&V.call(r,s)}catch(x){o?u.push(x):o=x}if(s.cancelBubble||T===e||T===null)break;r=T}if(o){for(let x of u)queueMicrotask(()=>{throw x});throw o}}finally{s.__root=e,delete s.currentTarget,J(X),G(E)}}}function yt(s,e){var i=e==null?"":typeof e=="object"?e+"":e;i!==(s.__t??(s.__t=s.nodeValue))&&(s.__t=i,s.nodeValue=i+"")}function ct(s,e){return Ne(s,e)}function mt(s,e){re(),e.intro=e.intro??!1;const i=e.target,a=O,l=A;try{for(var r=Je(i);r&&(r.nodeType!==oe||r.data!==Ke);)r=Qe(r);if(!r)throw ne;W(!0),K(r);const _=Ne(s,{...e,anchor:r});return W(!1),_}catch(_){if(_ instanceof Error&&_.message.split(` +`).some(g=>g.startsWith("https://svelte.dev/e/")))throw _;return _!==ne&&console.warn("Failed to hydrate: ",_),e.recover===!1&&Xe(),re(),Ze(i),W(!1),ct(s,e)}finally{W(a),K(l)}}const B=new Map;function Ne(s,{target:e,anchor:i,props:a={},events:l,context:r,intro:_=!0}){re();var g=new Set,D=E=>{for(var o=0;o{var E=i??e.appendChild(Ee());return ot(E,{pending:()=>{}},o=>{st({});var u=we;if(r&&(u.c=r),l&&(a.$$events=l),O&&at(o,null),M=s(o,a)||{},O&&(H.nodes.end=A,A===null||A.nodeType!==oe||A.data!==it))throw rt(),ne;nt()}),()=>{var T;for(var o of g){e.removeEventListener(o,$);var u=B.get(o);--u===0?(document.removeEventListener(o,$),B.delete(o)):B.set(o,u)}ve.delete(D),E!==i&&((T=E.parentNode)==null||T.removeChild(E))}});return fe.set(M,X),M}let fe=new WeakMap;function bt(s,e){const i=fe.get(s);return i?(fe.delete(s),i(e)):Promise.resolve()}export{mt as h,ct as m,yt as s,bt as u}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js new file mode 100644 index 0000000..d58ecbd --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.Cc7SJR4r.js","../chunks/C8WMVNin.js","../chunks/B_PiQ68N.js","../chunks/Csl9sg0z.js","../nodes/1.DcKD0893.js","../chunks/jjmyhcpZ.js","../chunks/BShzwfeu.js","../chunks/CE0Ev3WY.js","../nodes/2.BFij7fXI.js","../assets/2.Cwfcd7nv.css"])))=>i.map(i=>d[i]); +var ye=Object.defineProperty;var X=t=>{throw TypeError(t)};var Ee=(t,e,r)=>e in t?ye(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var $=(t,e,r)=>Ee(t,typeof e!="symbol"?e+"":e,r),ee=(t,e,r)=>e.has(t)||X("Cannot "+r);var n=(t,e,r)=>(ee(t,e,"read from private field"),r?r.call(t):e.get(t)),w=(t,e,r)=>e.has(t)?X("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),M=(t,e,r,i)=>(ee(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r);import{al as te,am as Pe,_ as z,M as Se,q as re,K as se,h as U,z as Re,U as we,an as Ae,a as ce,J as oe,a6 as fe,ao as Oe,a5 as ke,a0 as Ie,B as Te,ae,ap as xe,F as Le,b as ue,I as De,aq as le,ar as Be,as as Ce,at as je,i as E,au as Me,av as D,aw as qe,v as Fe,ax as Ue,ay as Ne,l as Ye,az as ze,aA as Ve,k as pe,aB as Ge,aC as He,aD as de,aE as Je,a9 as Ke,aF as We,p as Ze,d as Qe,u as Xe,aG as $e,f as q,s as et,m as tt,aH as V,n as rt,o as st,t as at,aI as p}from"../chunks/B_PiQ68N.js";import{h as nt,m as it,u as ct,s as ot}from"../chunks/jjmyhcpZ.js";import{a as x,f as he,c as G,t as ft}from"../chunks/C8WMVNin.js";import{o as ut}from"../chunks/CE0Ev3WY.js";var S,A,b,T,B,C,N;class _e{constructor(e,r=!0){$(this,"anchor");w(this,S,new Map);w(this,A,new Map);w(this,b,new Map);w(this,T,new Set);w(this,B,!0);w(this,C,()=>{var e=te;if(n(this,S).has(e)){var r=n(this,S).get(e),i=n(this,A).get(r);if(i)Pe(i),n(this,T).delete(r);else{var c=n(this,b).get(r);c&&(n(this,A).set(r,c.effect),n(this,b).delete(r),c.fragment.lastChild.remove(),this.anchor.before(c.fragment),i=c.effect)}for(const[o,a]of n(this,S)){if(n(this,S).delete(o),o===e)break;const s=n(this,b).get(a);s&&(z(s.effect),n(this,b).delete(a))}for(const[o,a]of n(this,A)){if(o===r||n(this,T).has(o))continue;const s=()=>{if(Array.from(n(this,S).values()).includes(o)){var l=document.createDocumentFragment();we(a,l),l.append(re()),n(this,b).set(o,{effect:a,fragment:l})}else z(a);n(this,T).delete(o),n(this,A).delete(o)};n(this,B)||!i?(n(this,T).add(o),Se(a,s,!1)):s()}}});w(this,N,e=>{n(this,S).delete(e);const r=Array.from(n(this,S).values());for(const[i,c]of n(this,b))r.includes(i)||(z(c.effect),n(this,b).delete(i))});this.anchor=e,M(this,B,r)}ensure(e,r){var i=te,c=Ae();if(r&&!n(this,A).has(e)&&!n(this,b).has(e))if(c){var o=document.createDocumentFragment(),a=re();o.append(a),n(this,b).set(e,{effect:se(()=>r(a)),fragment:o})}else n(this,A).set(e,se(()=>r(this.anchor)));if(n(this,S).set(i,e),c){for(const[s,f]of n(this,A))s===e?i.unskip_effect(f):i.skip_effect(f);for(const[s,f]of n(this,b))s===e?i.unskip_effect(f.effect):i.skip_effect(f.effect);i.oncommit(n(this,C)),i.ondiscard(n(this,N))}else U&&(this.anchor=Re),n(this,C).call(this)}}S=new WeakMap,A=new WeakMap,b=new WeakMap,T=new WeakMap,B=new WeakMap,C=new WeakMap,N=new WeakMap;function H(t,e,r=!1){U&&ce();var i=new _e(t),c=r?fe:0;function o(a,s){if(U){const l=Oe(t)===ke;if(a===l){var f=Ie();Te(f),i.anchor=f,ae(!1),i.ensure(a,s),ae(!0);return}}i.ensure(a,s)}oe(()=>{var a=!1;e((s,f=!0)=>{a=!0,o(f,s)}),a||o(!1,null)},c)}function J(t,e,r){U&&ce();var i=new _e(t);oe(()=>{var c=e()??null;i.ensure(c,c&&(o=>r(o,c)))},fe)}function ne(t,e){return t===e||(t==null?void 0:t[le])===e}function K(t={},e,r,i){return xe(()=>{var c,o;return Le(()=>{c=o,o=[],ue(()=>{t!==r(...o)&&(e(t,...o),c&&ne(r(...c),t)&&e(null,...c))})}),()=>{De(()=>{o&&ne(r(...o),t)&&e(null,...o)})}}),t}let F=!1;function lt(t){var e=F;try{return F=!1,[t(),F]}finally{F=e}}function W(t,e,r,i){var R;var c=!Ye||(r&ze)!==0,o=(r&Ne)!==0,a=(r&He)!==0,s=i,f=!0,l=()=>(f&&(f=!1,s=a?ue(i):i),s),_;if(o){var L=le in t||de in t;_=((R=Be(t,e))==null?void 0:R.set)??(L&&e in t?u=>t[e]=u:void 0)}var k,m=!1;o?[k,m]=lt(()=>t[e]):k=t[e],k===void 0&&i!==void 0&&(k=l(),_&&(c&&Ce(),_(k)));var v;if(c?v=()=>{var u=t[e];return u===void 0?l():(f=!0,u)}:v=()=>{var u=t[e];return u!==void 0&&(s=void 0),u===void 0?s:u},c&&!(r&je))return v;if(_){var d=t.$$legacy;return function(u,h){return arguments.length>0?((!c||!h||d||m)&&_(h?v():u),u):v()}}var P=!1,g=(r&Ve?pe:Ge)(()=>(P=!1,v()));o&&E(g);var I=Fe;return function(u,h){if(arguments.length>0){const Y=h?E(g):c&&o?Me(u):u;return D(g,Y),P=!0,s!==void 0&&(s=Y),u}return qe&&P||I.f&Ue?g.v:E(g)}}function dt(t){return class extends ht{constructor(e){super({component:t,...e})}}}var O,y;class ht{constructor(e){w(this,O);w(this,y);var o;var r=new Map,i=(a,s)=>{var f=We(s,!1,!1);return r.set(a,f),f};const c=new Proxy({...e.props||{},$$events:{}},{get(a,s){return E(r.get(s)??i(s,Reflect.get(a,s)))},has(a,s){return s===de?!0:(E(r.get(s)??i(s,Reflect.get(a,s))),Reflect.has(a,s))},set(a,s,f){return D(r.get(s)??i(s,f),f),Reflect.set(a,s,f)}});M(this,y,(e.hydrate?nt:it)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover})),(!((o=e==null?void 0:e.props)!=null&&o.$$host)||e.sync===!1)&&Je(),M(this,O,c.$$events);for(const a of Object.keys(n(this,y)))a==="$set"||a==="$destroy"||a==="$on"||Ke(this,a,{get(){return n(this,y)[a]},set(s){n(this,y)[a]=s},enumerable:!0});n(this,y).$set=a=>{Object.assign(c,a)},n(this,y).$destroy=()=>{ct(n(this,y))}}$set(e){n(this,y).$set(e)}$on(e,r){n(this,O)[e]=n(this,O)[e]||[];const i=(...c)=>r.call(this,...c);return n(this,O)[e].push(i),()=>{n(this,O)[e]=n(this,O)[e].filter(c=>c!==i)}}$destroy(){n(this,y).$destroy()}}O=new WeakMap,y=new WeakMap;const _t="modulepreload",vt=function(t,e){return new URL(t,e).href},ie={},Z=function(e,r,i){let c=Promise.resolve();if(r&&r.length>0){const a=document.getElementsByTagName("link"),s=document.querySelector("meta[property=csp-nonce]"),f=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));c=Promise.allSettled(r.map(l=>{if(l=vt(l,i),l in ie)return;ie[l]=!0;const _=l.endsWith(".css"),L=_?'[rel="stylesheet"]':"";if(!!i)for(let v=a.length-1;v>=0;v--){const d=a[v];if(d.href===l&&(!_||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${L}`))return;const m=document.createElement("link");if(m.rel=_?"stylesheet":_t,_||(m.as="script"),m.crossOrigin="",m.href=l,f&&m.setAttribute("nonce",f),document.head.appendChild(m),_)return new Promise((v,d)=>{m.addEventListener("load",v),m.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return c.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},At={};var mt=he('
'),gt=he(" ",1);function bt(t,e){Ze(e,!0);let r=W(e,"components",23,()=>[]),i=W(e,"data_0",3,null),c=W(e,"data_1",3,null);Qe(()=>e.stores.page.set(e.page)),Xe(()=>{e.stores,e.page,e.constructors,r(),e.form,i(),c(),e.stores.page.notify()});let o=V(!1),a=V(!1),s=V(null);ut(()=>{const d=e.stores.page.subscribe(()=>{E(o)&&(D(a,!0),$e().then(()=>{D(s,document.title||"untitled page",!0)}))});return D(o,!0),d});const f=p(()=>e.constructors[1]);var l=gt(),_=q(l);{var L=d=>{const P=p(()=>e.constructors[0]);var g=G(),I=q(g);J(I,()=>E(P),(R,u)=>{K(u(R,{get data(){return i()},get form(){return e.form},get params(){return e.page.params},children:(h,Y)=>{var Q=G(),me=q(Q);J(me,()=>E(f),(ge,be)=>{K(be(ge,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),j=>r()[1]=j,()=>{var j;return(j=r())==null?void 0:j[1]})}),x(h,Q)},$$slots:{default:!0}}),h=>r()[0]=h,()=>{var h;return(h=r())==null?void 0:h[0]})}),x(d,g)},k=d=>{const P=p(()=>e.constructors[0]);var g=G(),I=q(g);J(I,()=>E(P),(R,u)=>{K(u(R,{get data(){return i()},get form(){return e.form},get params(){return e.page.params}}),h=>r()[0]=h,()=>{var h;return(h=r())==null?void 0:h[0]})}),x(d,g)};H(_,d=>{e.constructors[1]?d(L):d(k,!1)})}var m=et(_,2);{var v=d=>{var P=mt(),g=rt(P);{var I=R=>{var u=ft();at(()=>ot(u,E(s))),x(R,u)};H(g,R=>{E(a)&&R(I)})}st(P),x(d,P)};H(m,d=>{E(o)&&d(v)})}x(t,l),tt()}const Ot=dt(bt),kt=[()=>Z(()=>import("../nodes/0.Cc7SJR4r.js"),__vite__mapDeps([0,1,2,3]),import.meta.url),()=>Z(()=>import("../nodes/1.DcKD0893.js"),__vite__mapDeps([4,1,2,3,5,6,7]),import.meta.url),()=>Z(()=>import("../nodes/2.BFij7fXI.js"),__vite__mapDeps([8,1,2,3,9]),import.meta.url)],It=[],Tt={"/":[2]},ve={handleError:({error:t})=>{console.error(t)},reroute:()=>{},transport:{}},yt=Object.fromEntries(Object.entries(ve.transport).map(([t,e])=>[t,e.decode])),xt=Object.fromEntries(Object.entries(ve.transport).map(([t,e])=>[t,e.encode])),Lt=!1,Dt=(t,e)=>yt[t](e);export{Dt as decode,yt as decoders,Tt as dictionary,xt as encoders,Lt as hash,ve as hooks,At as matchers,kt as nodes,Ot as root,It as server_loads}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js new file mode 100644 index 0000000..0d629ba --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js @@ -0,0 +1 @@ +import{l as o,a as r}from"../chunks/BShzwfeu.js";export{o as load_css,r as start}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js new file mode 100644 index 0000000..5725fba --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js @@ -0,0 +1 @@ +import{c as o,a as s}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";import{h as l,a as d,f as m}from"../chunks/B_PiQ68N.js";function c(f,a,t,e,u){var i;l&&d();var n=(i=a.$$slots)==null?void 0:i[t],r=!1;n===!0&&(n=a.children,r=!0),n===void 0||n(f,r?()=>e:e)}function v(f,a){var t=o(),e=m(t);c(e,a,"default",{}),s(f,t)}export{v as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js new file mode 100644 index 0000000..116149e --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js @@ -0,0 +1 @@ +import{a as b,f as k}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";import{c as x,d as $,u as i,b as y,r as l,g as j,i as v,j as E,k as q,p as w,f as z,t as A,m as B,n as u,o as m,s as C}from"../chunks/B_PiQ68N.js";import{s as g}from"../chunks/jjmyhcpZ.js";import{s as D,p as _}from"../chunks/BShzwfeu.js";function F(a=!1){const e=x,t=e.l.u;if(!t)return;let r=()=>E(e.s);if(a){let o=0,s={};const p=q(()=>{let n=!1;const c=e.s;for(const f in c)c[f]!==s[f]&&(s[f]=c[f],n=!0);return n&&o++,o});r=()=>v(p)}t.b.length&&$(()=>{d(e,r),l(t.b)}),i(()=>{const o=y(()=>t.m.map(j));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{d(e,r),l(t.a)})}function d(a,e){if(a.l.s)for(const t of a.l.s)v(t);e()}const G={get error(){return _.error},get status(){return _.status}};D.updated.check;const h=G;var H=k("

",1);function N(a,e){w(e,!1),F();var t=H(),r=z(t),o=u(r,!0);m(r);var s=C(r,2),p=u(s,!0);m(s),A(()=>{var n;g(o,h.status),g(p,(n=h.error)==null?void 0:n.message)}),b(a,t),B()}export{N as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js new file mode 100644 index 0000000..58828a4 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js @@ -0,0 +1 @@ +import{a as s,f as t}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";var i=t('

Welcome to SvelteKit

This is a minimal SvelteKit application.

');function n(a){var e=i();s(a,e)}export{n as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json new file mode 100644 index 0000000..88188f8 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json @@ -0,0 +1 @@ +{"version":"1770671592599"} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json new file mode 100644 index 0000000..ea6666b --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json @@ -0,0 +1,119 @@ +{ + ".svelte-kit/generated/server/internal.js": { + "file": "internal.js", + "name": "internal", + "src": ".svelte-kit/generated/server/internal.js", + "isEntry": true, + "imports": [ + "_internal.js", + "_environment.js" + ] + }, + "_context.js": { + "file": "chunks/context.js", + "name": "context" + }, + "_environment.js": { + "file": "chunks/environment.js", + "name": "environment" + }, + "_equality.js": { + "file": "chunks/equality.js", + "name": "equality" + }, + "_exports.js": { + "file": "chunks/exports.js", + "name": "exports", + "imports": [ + "_context.js", + "_equality.js" + ] + }, + "_index.js": { + "file": "chunks/index.js", + "name": "index", + "imports": [ + "_context.js", + "_utils2.js" + ] + }, + "_internal.js": { + "file": "chunks/internal.js", + "name": "internal", + "imports": [ + "_index.js", + "_environment.js", + "_context.js", + "_equality.js" + ] + }, + "_shared.js": { + "file": "chunks/shared.js", + "name": "shared", + "imports": [ + "_utils.js", + "_utils2.js" + ] + }, + "_utils.js": { + "file": "chunks/utils.js", + "name": "utils" + }, + "_utils2.js": { + "file": "chunks/utils2.js", + "name": "utils" + }, + "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/app/server/remote/index.js": { + "file": "remote-entry.js", + "name": "remote-entry", + "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/app/server/remote/index.js", + "isEntry": true, + "imports": [ + "_shared.js", + "_environment.js" + ] + }, + "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte": { + "file": "entries/fallbacks/error.svelte.js", + "name": "entries/fallbacks/error.svelte", + "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte", + "isEntry": true, + "imports": [ + "_context.js", + "_exports.js", + "_utils.js" + ] + }, + "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/server/index.js": { + "file": "index.js", + "name": "index", + "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/server/index.js", + "isEntry": true, + "imports": [ + "_environment.js", + "_shared.js", + "_index.js", + "_exports.js", + "_utils.js", + "_internal.js" + ] + }, + "src/routes/+layout.svelte": { + "file": "entries/pages/_layout.svelte.js", + "name": "entries/pages/_layout.svelte", + "src": "src/routes/+layout.svelte", + "isEntry": true, + "imports": [ + "_index.js" + ] + }, + "src/routes/+page.svelte": { + "file": "entries/pages/_page.svelte.js", + "name": "entries/pages/_page.svelte", + "src": "src/routes/+page.svelte", + "isEntry": true, + "css": [ + "_app/immutable/assets/_page.Cwfcd7nv.css" + ] + } +} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css new file mode 100644 index 0000000..bd4f0b4 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css @@ -0,0 +1 @@ +main.svelte-1uha8ag{padding:2rem;font-family:system-ui,-apple-system,sans-serif}h1.svelte-1uha8ag{color:#333}nav.svelte-1uha8ag{margin-top:2rem}a.svelte-1uha8ag{color:#06c;text-decoration:none}a.svelte-1uha8ag:hover{text-decoration:underline} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js new file mode 100644 index 0000000..989c4e5 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js @@ -0,0 +1,109 @@ +var is_array = Array.isArray; +var index_of = Array.prototype.indexOf; +var includes = Array.prototype.includes; +var array_from = Array.from; +var define_property = Object.defineProperty; +var get_descriptor = Object.getOwnPropertyDescriptor; +var object_prototype = Object.prototype; +var array_prototype = Array.prototype; +var get_prototype_of = Object.getPrototypeOf; +var is_extensible = Object.isExtensible; +const noop = () => { +}; +function run_all(arr) { + for (var i = 0; i < arr.length; i++) { + arr[i](); + } +} +function deferred() { + var resolve; + var reject; + var promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +} +function lifecycle_outside_component(name) { + { + throw new Error(`https://svelte.dev/e/lifecycle_outside_component`); + } +} +const ATTR_REGEX = /[&"<]/g; +const CONTENT_REGEX = /[&<]/g; +function escape_html(value, is_attr) { + const str = String(value ?? ""); + const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; + pattern.lastIndex = 0; + let escaped = ""; + let last = 0; + while (pattern.test(str)) { + const i = pattern.lastIndex - 1; + const ch = str[i]; + escaped += str.substring(last, i) + (ch === "&" ? "&" : ch === '"' ? """ : "<"); + last = i + 1; + } + return escaped + str.substring(last); +} +var ssr_context = null; +function set_ssr_context(v) { + ssr_context = v; +} +function getContext(key) { + const context_map = get_or_init_context_map(); + const result = ( + /** @type {T} */ + context_map.get(key) + ); + return result; +} +function setContext(key, context) { + get_or_init_context_map().set(key, context); + return context; +} +function get_or_init_context_map(name) { + if (ssr_context === null) { + lifecycle_outside_component(); + } + return ssr_context.c ??= new Map(get_parent_context(ssr_context) || void 0); +} +function push(fn) { + ssr_context = { p: ssr_context, c: null, r: null }; +} +function pop() { + ssr_context = /** @type {SSRContext} */ + ssr_context.p; +} +function get_parent_context(ssr_context2) { + let parent = ssr_context2.p; + while (parent !== null) { + const context_map = parent.c; + if (context_map !== null) { + return context_map; + } + parent = parent.p; + } + return null; +} +export { + array_prototype as a, + get_prototype_of as b, + is_array as c, + deferred as d, + is_extensible as e, + index_of as f, + get_descriptor as g, + define_property as h, + includes as i, + array_from as j, + escape_html as k, + set_ssr_context as l, + ssr_context as m, + noop as n, + object_prototype as o, + push as p, + pop as q, + run_all as r, + setContext as s, + getContext as t +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js new file mode 100644 index 0000000..421fed0 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js @@ -0,0 +1,36 @@ +const BROWSER = false; +let base = ""; +let assets = base; +const app_dir = "_app"; +const relative = true; +const initial = { base, assets }; +function override(paths) { + base = paths.base; + assets = paths.assets; +} +function reset() { + base = initial.base; + assets = initial.assets; +} +function set_assets(path) { + assets = initial.assets = path; +} +let prerendering = false; +function set_building() { +} +function set_prerendering() { + prerendering = true; +} +export { + BROWSER as B, + assets as a, + base as b, + app_dir as c, + reset as d, + set_building as e, + set_prerendering as f, + override as o, + prerendering as p, + relative as r, + set_assets as s +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js new file mode 100644 index 0000000..3c6fc90 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js @@ -0,0 +1,14 @@ +function equals(value) { + return value === this.v; +} +function safe_not_equal(a, b) { + return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function"; +} +function safe_equals(value) { + return !safe_not_equal(value, this.v); +} +export { + safe_not_equal as a, + equals as e, + safe_equals as s +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js new file mode 100644 index 0000000..6f03fa9 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js @@ -0,0 +1,231 @@ +import { n as noop } from "./context.js"; +import { a as safe_not_equal } from "./equality.js"; +const SCHEME = /^[a-z][a-z\d+\-.]+:/i; +const internal = new URL("sveltekit-internal://"); +function resolve(base, path) { + if (path[0] === "/" && path[1] === "/") return path; + let url = new URL(base, internal); + url = new URL(path, url); + return url.protocol === internal.protocol ? url.pathname + url.search + url.hash : url.href; +} +function normalize_path(path, trailing_slash) { + if (path === "/" || trailing_slash === "ignore") return path; + if (trailing_slash === "never") { + return path.endsWith("/") ? path.slice(0, -1) : path; + } else if (trailing_slash === "always" && !path.endsWith("/")) { + return path + "/"; + } + return path; +} +function decode_pathname(pathname) { + return pathname.split("%25").map(decodeURI).join("%25"); +} +function decode_params(params) { + for (const key in params) { + params[key] = decodeURIComponent(params[key]); + } + return params; +} +function make_trackable(url, callback, search_params_callback, allow_hash = false) { + const tracked = new URL(url); + Object.defineProperty(tracked, "searchParams", { + value: new Proxy(tracked.searchParams, { + get(obj, key) { + if (key === "get" || key === "getAll" || key === "has") { + return (param, ...rest) => { + search_params_callback(param); + return obj[key](param, ...rest); + }; + } + callback(); + const value = Reflect.get(obj, key); + return typeof value === "function" ? value.bind(obj) : value; + } + }), + enumerable: true, + configurable: true + }); + const tracked_url_properties = ["href", "pathname", "search", "toString", "toJSON"]; + if (allow_hash) tracked_url_properties.push("hash"); + for (const property of tracked_url_properties) { + Object.defineProperty(tracked, property, { + get() { + callback(); + return url[property]; + }, + enumerable: true, + configurable: true + }); + } + { + tracked[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { + return inspect(url, opts); + }; + tracked.searchParams[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { + return inspect(url.searchParams, opts); + }; + } + if (!allow_hash) { + disable_hash(tracked); + } + return tracked; +} +function disable_hash(url) { + allow_nodejs_console_log(url); + Object.defineProperty(url, "hash", { + get() { + throw new Error( + "Cannot access event.url.hash. Consider using `page.url.hash` inside a component instead" + ); + } + }); +} +function disable_search(url) { + allow_nodejs_console_log(url); + for (const property of ["search", "searchParams"]) { + Object.defineProperty(url, property, { + get() { + throw new Error(`Cannot access url.${property} on a page with prerendering enabled`); + } + }); + } +} +function allow_nodejs_console_log(url) { + { + url[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { + return inspect(new URL(url), opts); + }; + } +} +const subscriber_queue = []; +function readable(value, start) { + return { + subscribe: writable(value, start).subscribe + }; +} +function writable(value, start = noop) { + let stop = null; + const subscribers = /* @__PURE__ */ new Set(); + function set(new_value) { + if (safe_not_equal(value, new_value)) { + value = new_value; + if (stop) { + const run_queue = !subscriber_queue.length; + for (const subscriber of subscribers) { + subscriber[1](); + subscriber_queue.push(subscriber, value); + } + if (run_queue) { + for (let i = 0; i < subscriber_queue.length; i += 2) { + subscriber_queue[i][0](subscriber_queue[i + 1]); + } + subscriber_queue.length = 0; + } + } + } + } + function update(fn) { + set(fn( + /** @type {T} */ + value + )); + } + function subscribe(run, invalidate = noop) { + const subscriber = [run, invalidate]; + subscribers.add(subscriber); + if (subscribers.size === 1) { + stop = start(set, update) || noop; + } + run( + /** @type {T} */ + value + ); + return () => { + subscribers.delete(subscriber); + if (subscribers.size === 0 && stop) { + stop(); + stop = null; + } + }; + } + return { set, update, subscribe }; +} +function validator(expected) { + function validate(module, file) { + if (!module) return; + for (const key in module) { + if (key[0] === "_" || expected.has(key)) continue; + const values = [...expected.values()]; + const hint = hint_for_supported_files(key, file?.slice(file.lastIndexOf("."))) ?? `valid exports are ${values.join(", ")}, or anything with a '_' prefix`; + throw new Error(`Invalid export '${key}'${file ? ` in ${file}` : ""} (${hint})`); + } + } + return validate; +} +function hint_for_supported_files(key, ext = ".js") { + const supported_files = []; + if (valid_layout_exports.has(key)) { + supported_files.push(`+layout${ext}`); + } + if (valid_page_exports.has(key)) { + supported_files.push(`+page${ext}`); + } + if (valid_layout_server_exports.has(key)) { + supported_files.push(`+layout.server${ext}`); + } + if (valid_page_server_exports.has(key)) { + supported_files.push(`+page.server${ext}`); + } + if (valid_server_exports.has(key)) { + supported_files.push(`+server${ext}`); + } + if (supported_files.length > 0) { + return `'${key}' is a valid export in ${supported_files.slice(0, -1).join(", ")}${supported_files.length > 1 ? " or " : ""}${supported_files.at(-1)}`; + } +} +const valid_layout_exports = /* @__PURE__ */ new Set([ + "load", + "prerender", + "csr", + "ssr", + "trailingSlash", + "config" +]); +const valid_page_exports = /* @__PURE__ */ new Set([...valid_layout_exports, "entries"]); +const valid_layout_server_exports = /* @__PURE__ */ new Set([...valid_layout_exports]); +const valid_page_server_exports = /* @__PURE__ */ new Set([...valid_layout_server_exports, "actions", "entries"]); +const valid_server_exports = /* @__PURE__ */ new Set([ + "GET", + "POST", + "PATCH", + "PUT", + "DELETE", + "OPTIONS", + "HEAD", + "fallback", + "prerender", + "trailingSlash", + "config", + "entries" +]); +const validate_layout_exports = validator(valid_layout_exports); +const validate_page_exports = validator(valid_page_exports); +const validate_layout_server_exports = validator(valid_layout_server_exports); +const validate_page_server_exports = validator(valid_page_server_exports); +const validate_server_exports = validator(valid_server_exports); +export { + SCHEME as S, + decode_params as a, + validate_layout_exports as b, + validate_page_server_exports as c, + disable_search as d, + validate_page_exports as e, + resolve as f, + decode_pathname as g, + validate_server_exports as h, + make_trackable as m, + normalize_path as n, + readable as r, + validate_layout_server_exports as v, + writable as w +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js new file mode 100644 index 0000000..7da5071 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js @@ -0,0 +1,1297 @@ +import { k as escape_html, n as noop, l as set_ssr_context, m as ssr_context, p as push, q as pop } from "./context.js"; +import { i as is_primitive, g as get_type, D as DevalueError, a as is_plain_object, e as enumerable_symbols, s as stringify_key, b as stringify_string, c as escaped } from "./utils2.js"; +const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$"; +const unsafe_chars = /[<\b\f\n\r\t\0\u2028\u2029]/g; +const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/; +function uneval(value, replacer) { + const counts = /* @__PURE__ */ new Map(); + const keys = []; + const custom = /* @__PURE__ */ new Map(); + function walk(thing) { + if (!is_primitive(thing)) { + if (counts.has(thing)) { + counts.set(thing, counts.get(thing) + 1); + return; + } + counts.set(thing, 1); + if (replacer) { + const str2 = replacer(thing, (value2) => uneval(value2, replacer)); + if (typeof str2 === "string") { + custom.set(thing, str2); + return; + } + } + if (typeof thing === "function") { + throw new DevalueError(`Cannot stringify a function`, keys, thing, value); + } + const type = get_type(thing); + switch (type) { + case "Number": + case "BigInt": + case "String": + case "Boolean": + case "Date": + case "RegExp": + case "URL": + case "URLSearchParams": + return; + case "Array": + thing.forEach((value2, i) => { + keys.push(`[${i}]`); + walk(value2); + keys.pop(); + }); + break; + case "Set": + Array.from(thing).forEach(walk); + break; + case "Map": + for (const [key, value2] of thing) { + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ); + walk(value2); + keys.pop(); + } + break; + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "BigInt64Array": + case "BigUint64Array": + walk(thing.buffer); + return; + case "ArrayBuffer": + return; + case "Temporal.Duration": + case "Temporal.Instant": + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.PlainMonthDay": + case "Temporal.PlainYearMonth": + case "Temporal.ZonedDateTime": + return; + default: + if (!is_plain_object(thing)) { + throw new DevalueError( + `Cannot stringify arbitrary non-POJOs`, + keys, + thing, + value + ); + } + if (enumerable_symbols(thing).length > 0) { + throw new DevalueError( + `Cannot stringify POJOs with symbolic keys`, + keys, + thing, + value + ); + } + for (const key in thing) { + keys.push(stringify_key(key)); + walk(thing[key]); + keys.pop(); + } + } + } + } + walk(value); + const names = /* @__PURE__ */ new Map(); + Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => { + names.set(entry[0], get_name(i)); + }); + function stringify(thing) { + if (names.has(thing)) { + return names.get(thing); + } + if (is_primitive(thing)) { + return stringify_primitive(thing); + } + if (custom.has(thing)) { + return custom.get(thing); + } + const type = get_type(thing); + switch (type) { + case "Number": + case "String": + case "Boolean": + return `Object(${stringify(thing.valueOf())})`; + case "RegExp": + return `new RegExp(${stringify_string(thing.source)}, "${thing.flags}")`; + case "Date": + return `new Date(${thing.getTime()})`; + case "URL": + return `new URL(${stringify_string(thing.toString())})`; + case "URLSearchParams": + return `new URLSearchParams(${stringify_string(thing.toString())})`; + case "Array": + const members = ( + /** @type {any[]} */ + thing.map( + (v, i) => i in thing ? stringify(v) : "" + ) + ); + const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ","; + return `[${members.join(",")}${tail}]`; + case "Set": + case "Map": + return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`; + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "BigInt64Array": + case "BigUint64Array": { + let str2 = `new ${type}`; + if (counts.get(thing.buffer) === 1) { + const array = new thing.constructor(thing.buffer); + str2 += `([${array}])`; + } else { + str2 += `([${stringify(thing.buffer)}])`; + } + const a = thing.byteOffset; + const b = a + thing.byteLength; + if (a > 0 || b !== thing.buffer.byteLength) { + const m = +/(\d+)/.exec(type)[1] / 8; + str2 += `.subarray(${a / m},${b / m})`; + } + return str2; + } + case "ArrayBuffer": { + const ui8 = new Uint8Array(thing); + return `new Uint8Array([${ui8.toString()}]).buffer`; + } + case "Temporal.Duration": + case "Temporal.Instant": + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.PlainMonthDay": + case "Temporal.PlainYearMonth": + case "Temporal.ZonedDateTime": + return `${type}.from(${stringify_string(thing.toString())})`; + default: + const keys2 = Object.keys(thing); + const obj = keys2.map((key) => `${safe_key(key)}:${stringify(thing[key])}`).join(","); + const proto = Object.getPrototypeOf(thing); + if (proto === null) { + return keys2.length > 0 ? `{${obj},__proto__:null}` : `{__proto__:null}`; + } + return `{${obj}}`; + } + } + const str = stringify(value); + if (names.size) { + const params = []; + const statements = []; + const values = []; + names.forEach((name, thing) => { + params.push(name); + if (custom.has(thing)) { + values.push( + /** @type {string} */ + custom.get(thing) + ); + return; + } + if (is_primitive(thing)) { + values.push(stringify_primitive(thing)); + return; + } + const type = get_type(thing); + switch (type) { + case "Number": + case "String": + case "Boolean": + values.push(`Object(${stringify(thing.valueOf())})`); + break; + case "RegExp": + values.push(thing.toString()); + break; + case "Date": + values.push(`new Date(${thing.getTime()})`); + break; + case "Array": + values.push(`Array(${thing.length})`); + thing.forEach((v, i) => { + statements.push(`${name}[${i}]=${stringify(v)}`); + }); + break; + case "Set": + values.push(`new Set`); + statements.push( + `${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}` + ); + break; + case "Map": + values.push(`new Map`); + statements.push( + `${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}` + ); + break; + case "ArrayBuffer": + values.push( + `new Uint8Array([${new Uint8Array(thing).join(",")}]).buffer` + ); + break; + default: + values.push( + Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}" + ); + Object.keys(thing).forEach((key) => { + statements.push( + `${name}${safe_prop(key)}=${stringify(thing[key])}` + ); + }); + } + }); + statements.push(`return ${str}`); + return `(function(${params.join(",")}){${statements.join( + ";" + )}}(${values.join(",")}))`; + } else { + return str; + } +} +function get_name(num) { + let name = ""; + do { + name = chars[num % chars.length] + name; + num = ~~(num / chars.length) - 1; + } while (num >= 0); + return reserved.test(name) ? `${name}0` : name; +} +function escape_unsafe_char(c) { + return escaped[c] || c; +} +function escape_unsafe_chars(str) { + return str.replace(unsafe_chars, escape_unsafe_char); +} +function safe_key(key) { + return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escape_unsafe_chars(JSON.stringify(key)); +} +function safe_prop(key) { + return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escape_unsafe_chars(JSON.stringify(key))}]`; +} +function stringify_primitive(thing) { + if (typeof thing === "string") return stringify_string(thing); + if (thing === void 0) return "void 0"; + if (thing === 0 && 1 / thing < 0) return "-0"; + const str = String(thing); + if (typeof thing === "number") return str.replace(/^(-)?0\./, "$1."); + if (typeof thing === "bigint") return thing + "n"; + return str; +} +const DERIVED = 1 << 1; +const EFFECT = 1 << 2; +const RENDER_EFFECT = 1 << 3; +const MANAGED_EFFECT = 1 << 24; +const BLOCK_EFFECT = 1 << 4; +const BRANCH_EFFECT = 1 << 5; +const ROOT_EFFECT = 1 << 6; +const BOUNDARY_EFFECT = 1 << 7; +const CONNECTED = 1 << 9; +const CLEAN = 1 << 10; +const DIRTY = 1 << 11; +const MAYBE_DIRTY = 1 << 12; +const INERT = 1 << 13; +const DESTROYED = 1 << 14; +const EFFECT_RAN = 1 << 15; +const EFFECT_TRANSPARENT = 1 << 16; +const EAGER_EFFECT = 1 << 17; +const HEAD_EFFECT = 1 << 18; +const EFFECT_PRESERVED = 1 << 19; +const USER_EFFECT = 1 << 20; +const WAS_MARKED = 1 << 15; +const REACTION_IS_UPDATING = 1 << 21; +const ASYNC = 1 << 22; +const ERROR_VALUE = 1 << 23; +const STATE_SYMBOL = Symbol("$state"); +const LEGACY_PROPS = Symbol("legacy props"); +const STALE_REACTION = new class StaleReactionError extends Error { + name = "StaleReactionError"; + message = "The reaction that called `getAbortSignal()` was re-run or destroyed"; +}(); +const COMMENT_NODE = 8; +const HYDRATION_START = "["; +const HYDRATION_START_ELSE = "[!"; +const HYDRATION_END = "]"; +const HYDRATION_ERROR = {}; +const ELEMENT_IS_NAMESPACED = 1; +const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; +const ELEMENT_IS_INPUT = 1 << 2; +const UNINITIALIZED = Symbol(); +const DOM_BOOLEAN_ATTRIBUTES = [ + "allowfullscreen", + "async", + "autofocus", + "autoplay", + "checked", + "controls", + "default", + "disabled", + "formnovalidate", + "indeterminate", + "inert", + "ismap", + "loop", + "multiple", + "muted", + "nomodule", + "novalidate", + "open", + "playsinline", + "readonly", + "required", + "reversed", + "seamless", + "selected", + "webkitdirectory", + "defer", + "disablepictureinpicture", + "disableremoteplayback" +]; +function is_boolean_attribute(name) { + return DOM_BOOLEAN_ATTRIBUTES.includes(name); +} +const PASSIVE_EVENTS = ["touchstart", "touchmove"]; +function is_passive_event(name) { + return PASSIVE_EVENTS.includes(name); +} +function r(e) { + var t, f, n = ""; + if ("string" == typeof e || "number" == typeof e) n += e; + else if ("object" == typeof e) if (Array.isArray(e)) { + var o = e.length; + for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f); + } else for (f in e) e[f] && (n && (n += " "), n += f); + return n; +} +function clsx$1() { + for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t); + return n; +} +const replacements = { + translate: /* @__PURE__ */ new Map([ + [true, "yes"], + [false, "no"] + ]) +}; +function attr(name, value, is_boolean = false) { + if (name === "hidden" && value !== "until-found") { + is_boolean = true; + } + if (value == null || !value && is_boolean) return ""; + const normalized = name in replacements && replacements[name].get(value) || value; + const assignment = is_boolean ? "" : `="${escape_html(normalized, true)}"`; + return ` ${name}${assignment}`; +} +function clsx(value) { + if (typeof value === "object") { + return clsx$1(value); + } else { + return value ?? ""; + } +} +const whitespace = [..." \n\r\f \v\uFEFF"]; +function to_class(value, hash, directives) { + var classname = value == null ? "" : "" + value; + if (hash) { + classname = classname ? classname + " " + hash : hash; + } + if (directives) { + for (var key in directives) { + if (directives[key]) { + classname = classname ? classname + " " + key : key; + } else if (classname.length) { + var len = key.length; + var a = 0; + while ((a = classname.indexOf(key, a)) >= 0) { + var b = a + len; + if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) { + classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1); + } else { + a = b; + } + } + } + } + } + return classname === "" ? null : classname; +} +function append_styles(styles, important = false) { + var separator = important ? " !important;" : ";"; + var css = ""; + for (var key in styles) { + var value = styles[key]; + if (value != null && value !== "") { + css += " " + key + ": " + value + separator; + } + } + return css; +} +function to_css_name(name) { + if (name[0] !== "-" || name[1] !== "-") { + return name.toLowerCase(); + } + return name; +} +function to_style(value, styles) { + if (styles) { + var new_style = ""; + var normal_styles; + var important_styles; + if (Array.isArray(styles)) { + normal_styles = styles[0]; + important_styles = styles[1]; + } else { + normal_styles = styles; + } + if (value) { + value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim(); + var in_str = false; + var in_apo = 0; + var in_comment = false; + var reserved_names = []; + if (normal_styles) { + reserved_names.push(...Object.keys(normal_styles).map(to_css_name)); + } + if (important_styles) { + reserved_names.push(...Object.keys(important_styles).map(to_css_name)); + } + var start_index = 0; + var name_index = -1; + const len = value.length; + for (var i = 0; i < len; i++) { + var c = value[i]; + if (in_comment) { + if (c === "/" && value[i - 1] === "*") { + in_comment = false; + } + } else if (in_str) { + if (in_str === c) { + in_str = false; + } + } else if (c === "/" && value[i + 1] === "*") { + in_comment = true; + } else if (c === '"' || c === "'") { + in_str = c; + } else if (c === "(") { + in_apo++; + } else if (c === ")") { + in_apo--; + } + if (!in_comment && in_str === false && in_apo === 0) { + if (c === ":" && name_index === -1) { + name_index = i; + } else if (c === ";" || i === len - 1) { + if (name_index !== -1) { + var name = to_css_name(value.substring(start_index, name_index).trim()); + if (!reserved_names.includes(name)) { + if (c !== ";") { + i++; + } + var property = value.substring(start_index, i).trim(); + new_style += " " + property + ";"; + } + } + start_index = i + 1; + name_index = -1; + } + } + } + } + if (normal_styles) { + new_style += append_styles(normal_styles); + } + if (important_styles) { + new_style += append_styles(important_styles, true); + } + new_style = new_style.trim(); + return new_style === "" ? null : new_style; + } + return value == null ? null : String(value); +} +const BLOCK_OPEN = ``; +const BLOCK_CLOSE = ``; +let controller = null; +function abort() { + controller?.abort(STALE_REACTION); + controller = null; +} +function await_invalid() { + const error = new Error(`await_invalid +Encountered asynchronous work while rendering synchronously. +https://svelte.dev/e/await_invalid`); + error.name = "Svelte error"; + throw error; +} +function invalid_csp() { + const error = new Error(`invalid_csp +\`csp.nonce\` was set while \`csp.hash\` was \`true\`. These options cannot be used simultaneously. +https://svelte.dev/e/invalid_csp`); + error.name = "Svelte error"; + throw error; +} +function server_context_required() { + const error = new Error(`server_context_required +Could not resolve \`render\` context. +https://svelte.dev/e/server_context_required`); + error.name = "Svelte error"; + throw error; +} +function unresolved_hydratable(key, stack) { + { + console.warn(`https://svelte.dev/e/unresolved_hydratable`); + } +} +function get_render_context() { + const store = als?.getStore(); + { + server_context_required(); + } + return store; +} +let als = null; +let text_encoder; +let crypto; +async function sha256(data) { + text_encoder ??= new TextEncoder(); + crypto ??= globalThis.crypto?.subtle?.digest ? globalThis.crypto : ( + // @ts-ignore - we don't install node types in the prod build + // don't use 'node:crypto' because static analysers will think we rely on node when we don't + (await import( + /* @vite-ignore */ + "node:crypto" + )).webcrypto + ); + const hash_buffer = await crypto.subtle.digest("SHA-256", text_encoder.encode(data)); + return base64_encode(hash_buffer); +} +function base64_encode(bytes) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(bytes).toString("base64"); + } + let binary = ""; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +class Renderer { + /** + * The contents of the renderer. + * @type {RendererItem[]} + */ + #out = []; + /** + * Any `onDestroy` callbacks registered during execution of this renderer. + * @type {(() => void)[] | undefined} + */ + #on_destroy = void 0; + /** + * Whether this renderer is a component body. + * @type {boolean} + */ + #is_component_body = false; + /** + * The type of string content that this renderer is accumulating. + * @type {RendererType} + */ + type; + /** @type {Renderer | undefined} */ + #parent; + /** + * Asynchronous work associated with this renderer + * @type {Promise | undefined} + */ + promise = void 0; + /** + * State which is associated with the content tree as a whole. + * It will be re-exposed, uncopied, on all children. + * @type {SSRState} + * @readonly + */ + global; + /** + * State that is local to the branch it is declared in. + * It will be shallow-copied to all children. + * + * @type {{ select_value: string | undefined }} + */ + local; + /** + * @param {SSRState} global + * @param {Renderer | undefined} [parent] + */ + constructor(global, parent) { + this.#parent = parent; + this.global = global; + this.local = parent ? { ...parent.local } : { select_value: void 0 }; + this.type = parent ? parent.type : "body"; + } + /** + * @param {(renderer: Renderer) => void} fn + */ + head(fn) { + const head = new Renderer(this.global, this); + head.type = "head"; + this.#out.push(head); + head.child(fn); + } + /** + * @param {Array>} blockers + * @param {(renderer: Renderer) => void} fn + */ + async_block(blockers, fn) { + this.#out.push(BLOCK_OPEN); + this.async(blockers, fn); + this.#out.push(BLOCK_CLOSE); + } + /** + * @param {Array>} blockers + * @param {(renderer: Renderer) => void} fn + */ + async(blockers, fn) { + let callback = fn; + if (blockers.length > 0) { + const context = ssr_context; + callback = (renderer) => { + return Promise.all(blockers).then(() => { + const previous_context = ssr_context; + try { + set_ssr_context(context); + return fn(renderer); + } finally { + set_ssr_context(previous_context); + } + }); + }; + } + this.child(callback); + } + /** + * @param {Array<() => void>} thunks + */ + run(thunks) { + const context = ssr_context; + let promise = Promise.resolve(thunks[0]()); + const promises = [promise]; + for (const fn of thunks.slice(1)) { + promise = promise.then(() => { + const previous_context = ssr_context; + set_ssr_context(context); + try { + return fn(); + } finally { + set_ssr_context(previous_context); + } + }); + promises.push(promise); + } + promise.catch(noop); + this.promise = promise; + return promises; + } + /** + * @param {(renderer: Renderer) => MaybePromise} fn + */ + child_block(fn) { + this.#out.push(BLOCK_OPEN); + this.child(fn); + this.#out.push(BLOCK_CLOSE); + } + /** + * Create a child renderer. The child renderer inherits the state from the parent, + * but has its own content. + * @param {(renderer: Renderer) => MaybePromise} fn + */ + child(fn) { + const child = new Renderer(this.global, this); + this.#out.push(child); + const parent = ssr_context; + set_ssr_context({ + ...ssr_context, + p: parent, + c: null, + r: child + }); + const result = fn(child); + set_ssr_context(parent); + if (result instanceof Promise) { + if (child.global.mode === "sync") { + await_invalid(); + } + result.catch(() => { + }); + child.promise = result; + } + return child; + } + /** + * Create a component renderer. The component renderer inherits the state from the parent, + * but has its own content. It is treated as an ordering boundary for ondestroy callbacks. + * @param {(renderer: Renderer) => MaybePromise} fn + * @param {Function} [component_fn] + * @returns {void} + */ + component(fn, component_fn) { + push(); + const child = this.child(fn); + child.#is_component_body = true; + pop(); + } + /** + * @param {Record} attrs + * @param {(renderer: Renderer) => void} fn + * @param {string | undefined} [css_hash] + * @param {Record | undefined} [classes] + * @param {Record | undefined} [styles] + * @param {number | undefined} [flags] + * @param {boolean | undefined} [is_rich] + * @returns {void} + */ + select(attrs, fn, css_hash, classes, styles, flags, is_rich) { + const { value, ...select_attrs } = attrs; + this.push(``); + this.child((renderer) => { + renderer.local.select_value = value; + fn(renderer); + }); + this.push(`${is_rich ? "" : ""}`); + } + /** + * @param {Record} attrs + * @param {string | number | boolean | ((renderer: Renderer) => void)} body + * @param {string | undefined} [css_hash] + * @param {Record | undefined} [classes] + * @param {Record | undefined} [styles] + * @param {number | undefined} [flags] + * @param {boolean | undefined} [is_rich] + */ + option(attrs, body, css_hash, classes, styles, flags, is_rich) { + this.#out.push(` { + if ("value" in attrs) { + value = attrs.value; + } + if (value === this.local.select_value) { + renderer.#out.push(" selected"); + } + renderer.#out.push(`>${body2}${is_rich ? "" : ""}`); + if (head) { + renderer.head((child) => child.push(head)); + } + }; + if (typeof body === "function") { + this.child((renderer) => { + const r2 = new Renderer(this.global, this); + body(r2); + if (this.global.mode === "async") { + return r2.#collect_content_async().then((content) => { + close(renderer, content.body.replaceAll("", ""), content); + }); + } else { + const content = r2.#collect_content(); + close(renderer, content.body.replaceAll("", ""), content); + } + }); + } else { + close(this, body, { body }); + } + } + /** + * @param {(renderer: Renderer) => void} fn + */ + title(fn) { + const path = this.get_path(); + const close = (head) => { + this.global.set_title(head, path); + }; + this.child((renderer) => { + const r2 = new Renderer(renderer.global, renderer); + fn(r2); + if (renderer.global.mode === "async") { + return r2.#collect_content_async().then((content) => { + close(content.head); + }); + } else { + const content = r2.#collect_content(); + close(content.head); + } + }); + } + /** + * @param {string | (() => Promise)} content + */ + push(content) { + if (typeof content === "function") { + this.child(async (renderer) => renderer.push(await content())); + } else { + this.#out.push(content); + } + } + /** + * @param {() => void} fn + */ + on_destroy(fn) { + (this.#on_destroy ??= []).push(fn); + } + /** + * @returns {number[]} + */ + get_path() { + return this.#parent ? [...this.#parent.get_path(), this.#parent.#out.indexOf(this)] : []; + } + /** + * @deprecated this is needed for legacy component bindings + */ + copy() { + const copy = new Renderer(this.global, this.#parent); + copy.#out = this.#out.map((item) => item instanceof Renderer ? item.copy() : item); + copy.promise = this.promise; + return copy; + } + /** + * @param {Renderer} other + * @deprecated this is needed for legacy component bindings + */ + subsume(other) { + if (this.global.mode !== other.global.mode) { + throw new Error( + "invariant: A renderer cannot switch modes. If you're seeing this, there's a compiler bug. File an issue!" + ); + } + this.local = other.local; + this.#out = other.#out.map((item) => { + if (item instanceof Renderer) { + item.subsume(item); + } + return item; + }); + this.promise = other.promise; + this.type = other.type; + } + get length() { + return this.#out.length; + } + /** + * Only available on the server and when compiling with the `server` option. + * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. + * @template {Record} Props + * @param {Component} component + * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} [options] + * @returns {RenderOutput} + */ + static render(component, options = {}) { + let sync; + const result = ( + /** @type {RenderOutput} */ + {} + ); + Object.defineProperties(result, { + html: { + get: () => { + return (sync ??= Renderer.#render(component, options)).body; + } + }, + head: { + get: () => { + return (sync ??= Renderer.#render(component, options)).head; + } + }, + body: { + get: () => { + return (sync ??= Renderer.#render(component, options)).body; + } + }, + hashes: { + value: { + script: "" + } + }, + then: { + value: ( + /** + * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. + * + * @template TResult1 + * @template [TResult2=never] + * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled + * @param { (reason: unknown) => TResult2 } onrejected + */ + (onfulfilled, onrejected) => { + { + const result2 = sync ??= Renderer.#render(component, options); + const user_result = onfulfilled({ + head: result2.head, + body: result2.body, + html: result2.body, + hashes: { script: [] } + }); + return Promise.resolve(user_result); + } + } + ) + } + }); + return result; + } + /** + * Collect all of the `onDestroy` callbacks registered during rendering. In an async context, this is only safe to call + * after awaiting `collect_async`. + * + * Child renderers are "porous" and don't affect execution order, but component body renderers + * create ordering boundaries. Within a renderer, callbacks run in order until hitting a component boundary. + * @returns {Iterable<() => void>} + */ + *#collect_on_destroy() { + for (const component of this.#traverse_components()) { + yield* component.#collect_ondestroy(); + } + } + /** + * Performs a depth-first search of renderers, yielding the deepest components first, then additional components as we backtrack up the tree. + * @returns {Iterable} + */ + *#traverse_components() { + for (const child of this.#out) { + if (typeof child !== "string") { + yield* child.#traverse_components(); + } + } + if (this.#is_component_body) { + yield this; + } + } + /** + * @returns {Iterable<() => void>} + */ + *#collect_ondestroy() { + if (this.#on_destroy) { + for (const fn of this.#on_destroy) { + yield fn; + } + } + for (const child of this.#out) { + if (child instanceof Renderer && !child.#is_component_body) { + yield* child.#collect_ondestroy(); + } + } + } + /** + * Render a component. Throws if any of the children are performing asynchronous work. + * + * @template {Record} Props + * @param {Component} component + * @param {{ props?: Omit; context?: Map; idPrefix?: string }} options + * @returns {AccumulatedContent} + */ + static #render(component, options) { + var previous_context = ssr_context; + try { + const renderer = Renderer.#open_render("sync", component, options); + const content = renderer.#collect_content(); + return Renderer.#close_render(content, renderer); + } finally { + abort(); + set_ssr_context(previous_context); + } + } + /** + * Render a component. + * + * @template {Record} Props + * @param {Component} component + * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} options + * @returns {Promise} + */ + static async #render_async(component, options) { + const previous_context = ssr_context; + try { + const renderer = Renderer.#open_render("async", component, options); + const content = await renderer.#collect_content_async(); + const hydratables = await renderer.#collect_hydratables(); + if (hydratables !== null) { + content.head = hydratables + content.head; + } + return Renderer.#close_render(content, renderer); + } finally { + set_ssr_context(previous_context); + abort(); + } + } + /** + * Collect all of the code from the `out` array and return it as a string, or a promise resolving to a string. + * @param {AccumulatedContent} content + * @returns {AccumulatedContent} + */ + #collect_content(content = { head: "", body: "" }) { + for (const item of this.#out) { + if (typeof item === "string") { + content[this.type] += item; + } else if (item instanceof Renderer) { + item.#collect_content(content); + } + } + return content; + } + /** + * Collect all of the code from the `out` array and return it as a string. + * @param {AccumulatedContent} content + * @returns {Promise} + */ + async #collect_content_async(content = { head: "", body: "" }) { + await this.promise; + for (const item of this.#out) { + if (typeof item === "string") { + content[this.type] += item; + } else if (item instanceof Renderer) { + await item.#collect_content_async(content); + } + } + return content; + } + async #collect_hydratables() { + const ctx = get_render_context().hydratable; + for (const [_, key] of ctx.unresolved_promises) { + unresolved_hydratable(key, ctx.lookup.get(key)?.stack ?? ""); + } + for (const comparison of ctx.comparisons) { + await comparison; + } + return await this.#hydratable_block(ctx); + } + /** + * @template {Record} Props + * @param {'sync' | 'async'} mode + * @param {import('svelte').Component} component + * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} options + * @returns {Renderer} + */ + static #open_render(mode, component, options) { + const renderer = new Renderer( + new SSRState(mode, options.idPrefix ? options.idPrefix + "-" : "", options.csp) + ); + renderer.push(BLOCK_OPEN); + push(); + if (options.context) ssr_context.c = options.context; + ssr_context.r = renderer; + component(renderer, options.props ?? {}); + pop(); + renderer.push(BLOCK_CLOSE); + return renderer; + } + /** + * @param {AccumulatedContent} content + * @param {Renderer} renderer + * @returns {AccumulatedContent & { hashes: { script: Sha256Source[] } }} + */ + static #close_render(content, renderer) { + for (const cleanup of renderer.#collect_on_destroy()) { + cleanup(); + } + let head = content.head + renderer.global.get_title(); + let body = content.body; + for (const { hash, code } of renderer.global.css) { + head += ``; + } + return { + head, + body, + hashes: { + script: renderer.global.csp.script_hashes + } + }; + } + /** + * @param {HydratableContext} ctx + */ + async #hydratable_block(ctx) { + if (ctx.lookup.size === 0) { + return null; + } + let entries = []; + let has_promises = false; + for (const [k, v] of ctx.lookup) { + if (v.promises) { + has_promises = true; + for (const p of v.promises) await p; + } + entries.push(`[${uneval(k)},${v.serialized}]`); + } + let prelude = `const h = (window.__svelte ??= {}).h ??= new Map();`; + if (has_promises) { + prelude = `const r = (v) => Promise.resolve(v); + ${prelude}`; + } + const body = ` + { + ${prelude} + + for (const [k, v] of [ + ${entries.join(",\n ")} + ]) { + h.set(k, v); + } + } + `; + let csp_attr = ""; + if (this.global.csp.nonce) { + csp_attr = ` nonce="${this.global.csp.nonce}"`; + } else if (this.global.csp.hash) { + const hash = await sha256(body); + this.global.csp.script_hashes.push(`sha256-${hash}`); + } + return ` + ${body}<\/script>`; + } +} +class SSRState { + /** @readonly @type {Csp & { script_hashes: Sha256Source[] }} */ + csp; + /** @readonly @type {'sync' | 'async'} */ + mode; + /** @readonly @type {() => string} */ + uid; + /** @readonly @type {Set<{ hash: string; code: string }>} */ + css = /* @__PURE__ */ new Set(); + /** @type {{ path: number[], value: string }} */ + #title = { path: [], value: "" }; + /** + * @param {'sync' | 'async'} mode + * @param {string} id_prefix + * @param {Csp} csp + */ + constructor(mode, id_prefix = "", csp = { hash: false }) { + this.mode = mode; + this.csp = { ...csp, script_hashes: [] }; + let uid = 1; + this.uid = () => `${id_prefix}s${uid++}`; + } + get_title() { + return this.#title.value; + } + /** + * Performs a depth-first (lexicographic) comparison using the path. Rejects sets + * from earlier than or equal to the current value. + * @param {string} value + * @param {number[]} path + */ + set_title(value, path) { + const current = this.#title.path; + let i = 0; + let l = Math.min(path.length, current.length); + while (i < l && path[i] === current[i]) i += 1; + if (path[i] === void 0) return; + if (current[i] === void 0 || path[i] > current[i]) { + this.#title.path = path; + this.#title.value = value; + } + } +} +const INVALID_ATTR_NAME_CHAR_REGEX = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u; +function render(component, options = {}) { + if (options.csp?.hash && options.csp.nonce) { + invalid_csp(); + } + return Renderer.render( + /** @type {Component} */ + component, + options + ); +} +function attributes(attrs, css_hash, classes, styles, flags = 0) { + if (styles) { + attrs.style = to_style(attrs.style, styles); + } + if (attrs.class) { + attrs.class = clsx(attrs.class); + } + if (css_hash || classes) { + attrs.class = to_class(attrs.class, css_hash, classes); + } + let attr_str = ""; + let name; + const is_html = (flags & ELEMENT_IS_NAMESPACED) === 0; + const lowercase = (flags & ELEMENT_PRESERVE_ATTRIBUTE_CASE) === 0; + const is_input = (flags & ELEMENT_IS_INPUT) !== 0; + for (name in attrs) { + if (typeof attrs[name] === "function") continue; + if (name[0] === "$" && name[1] === "$") continue; + if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue; + var value = attrs[name]; + if (lowercase) { + name = name.toLowerCase(); + } + if (is_input) { + if (name === "defaultvalue" || name === "defaultchecked") { + name = name === "defaultvalue" ? "value" : "checked"; + if (attrs[name]) continue; + } + } + attr_str += attr(name, value, is_html && is_boolean_attribute(name)); + } + return attr_str; +} +function slot(renderer, $$props, name, slot_props, fallback_fn) { + var slot_fn = $$props.$$slots?.[name]; + if (slot_fn === true) { + slot_fn = $$props["children"]; + } + if (slot_fn !== void 0) { + slot_fn(renderer, slot_props); + } +} +export { + ASYNC as A, + BOUNDARY_EFFECT as B, + COMMENT_NODE as C, + DIRTY as D, + ERROR_VALUE as E, + HYDRATION_ERROR as H, + INERT as I, + LEGACY_PROPS as L, + MAYBE_DIRTY as M, + ROOT_EFFECT as R, + STATE_SYMBOL as S, + UNINITIALIZED as U, + WAS_MARKED as W, + HYDRATION_END as a, + HYDRATION_START as b, + HYDRATION_START_ELSE as c, + EFFECT_RAN as d, + CONNECTED as e, + CLEAN as f, + DERIVED as g, + EFFECT as h, + BLOCK_EFFECT as i, + BRANCH_EFFECT as j, + RENDER_EFFECT as k, + MANAGED_EFFECT as l, + HEAD_EFFECT as m, + DESTROYED as n, + EFFECT_TRANSPARENT as o, + EFFECT_PRESERVED as p, + EAGER_EFFECT as q, + STALE_REACTION as r, + USER_EFFECT as s, + REACTION_IS_UPDATING as t, + uneval as u, + is_passive_event as v, + render as w, + slot as x +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js new file mode 100644 index 0000000..160cf7c --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js @@ -0,0 +1,2712 @@ +import { H as HYDRATION_ERROR, C as COMMENT_NODE, a as HYDRATION_END, b as HYDRATION_START, c as HYDRATION_START_ELSE, B as BOUNDARY_EFFECT, E as ERROR_VALUE, d as EFFECT_RAN, e as CONNECTED, f as CLEAN, M as MAYBE_DIRTY, D as DIRTY, g as DERIVED, W as WAS_MARKED, I as INERT, h as EFFECT, i as BLOCK_EFFECT, U as UNINITIALIZED, j as BRANCH_EFFECT, R as ROOT_EFFECT, k as RENDER_EFFECT, l as MANAGED_EFFECT, m as HEAD_EFFECT, n as DESTROYED, A as ASYNC, o as EFFECT_TRANSPARENT, p as EFFECT_PRESERVED, q as EAGER_EFFECT, S as STATE_SYMBOL, r as STALE_REACTION, s as USER_EFFECT, t as REACTION_IS_UPDATING, v as is_passive_event, L as LEGACY_PROPS, w as render } from "./index.js"; +import { B as BROWSER } from "./environment.js"; +import { r as run_all, d as deferred, i as includes, o as object_prototype, a as array_prototype, g as get_descriptor, b as get_prototype_of, c as is_array, e as is_extensible, f as index_of, h as define_property, j as array_from, s as setContext } from "./context.js"; +import { s as safe_equals, e as equals } from "./equality.js"; +let public_env = {}; +function set_private_env(environment) { +} +function set_public_env(environment) { + public_env = environment; +} +function effect_update_depth_exceeded() { + { + throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); + } +} +function hydration_failed() { + { + throw new Error(`https://svelte.dev/e/hydration_failed`); + } +} +function state_descriptors_fixed() { + { + throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); + } +} +function state_prototype_fixed() { + { + throw new Error(`https://svelte.dev/e/state_prototype_fixed`); + } +} +function state_unsafe_mutation() { + { + throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); + } +} +function svelte_boundary_reset_onerror() { + { + throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`); + } +} +function hydration_mismatch(location) { + { + console.warn(`https://svelte.dev/e/hydration_mismatch`); + } +} +function svelte_boundary_reset_noop() { + { + console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`); + } +} +let hydrating = false; +function set_hydrating(value) { + hydrating = value; +} +let hydrate_node; +function set_hydrate_node(node) { + if (node === null) { + hydration_mismatch(); + throw HYDRATION_ERROR; + } + return hydrate_node = node; +} +function hydrate_next() { + return set_hydrate_node(/* @__PURE__ */ get_next_sibling(hydrate_node)); +} +function next(count = 1) { + if (hydrating) { + var i = count; + var node = hydrate_node; + while (i--) { + node = /** @type {TemplateNode} */ + /* @__PURE__ */ get_next_sibling(node); + } + hydrate_node = node; + } +} +function skip_nodes(remove = true) { + var depth = 0; + var node = hydrate_node; + while (true) { + if (node.nodeType === COMMENT_NODE) { + var data = ( + /** @type {Comment} */ + node.data + ); + if (data === HYDRATION_END) { + if (depth === 0) return node; + depth -= 1; + } else if (data === HYDRATION_START || data === HYDRATION_START_ELSE) { + depth += 1; + } + } + var next2 = ( + /** @type {TemplateNode} */ + /* @__PURE__ */ get_next_sibling(node) + ); + if (remove) node.remove(); + node = next2; + } +} +let tracing_mode_flag = false; +let component_context = null; +function set_component_context(context) { + component_context = context; +} +function push(props, runes = false, fn) { + component_context = { + p: component_context, + i: false, + c: null, + e: null, + s: props, + x: null, + l: null + }; +} +function pop(component) { + var context = ( + /** @type {ComponentContext} */ + component_context + ); + var effects = context.e; + if (effects !== null) { + context.e = null; + for (var fn of effects) { + create_user_effect(fn); + } + } + context.i = true; + component_context = context.p; + return ( + /** @type {T} */ + {} + ); +} +function is_runes() { + return true; +} +let micro_tasks = []; +function run_micro_tasks() { + var tasks = micro_tasks; + micro_tasks = []; + run_all(tasks); +} +function queue_micro_task(fn) { + if (micro_tasks.length === 0 && !is_flushing_sync) { + var tasks = micro_tasks; + queueMicrotask(() => { + if (tasks === micro_tasks) run_micro_tasks(); + }); + } + micro_tasks.push(fn); +} +function flush_tasks() { + while (micro_tasks.length > 0) { + run_micro_tasks(); + } +} +function handle_error(error) { + var effect = active_effect; + if (effect === null) { + active_reaction.f |= ERROR_VALUE; + return error; + } + if ((effect.f & EFFECT_RAN) === 0) { + if ((effect.f & BOUNDARY_EFFECT) === 0) { + throw error; + } + effect.b.error(error); + } else { + invoke_error_boundary(error, effect); + } +} +function invoke_error_boundary(error, effect) { + while (effect !== null) { + if ((effect.f & BOUNDARY_EFFECT) !== 0) { + try { + effect.b.error(error); + return; + } catch (e) { + error = e; + } + } + effect = effect.parent; + } + throw error; +} +const STATUS_MASK = -7169; +function set_signal_status(signal, status) { + signal.f = signal.f & STATUS_MASK | status; +} +function update_derived_status(derived) { + if ((derived.f & CONNECTED) !== 0 || derived.deps === null) { + set_signal_status(derived, CLEAN); + } else { + set_signal_status(derived, MAYBE_DIRTY); + } +} +function clear_marked(deps) { + if (deps === null) return; + for (const dep of deps) { + if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) { + continue; + } + dep.f ^= WAS_MARKED; + clear_marked( + /** @type {Derived} */ + dep.deps + ); + } +} +function defer_effect(effect, dirty_effects, maybe_dirty_effects) { + if ((effect.f & DIRTY) !== 0) { + dirty_effects.add(effect); + } else if ((effect.f & MAYBE_DIRTY) !== 0) { + maybe_dirty_effects.add(effect); + } + clear_marked(effect.deps); + set_signal_status(effect, CLEAN); +} +const batches = /* @__PURE__ */ new Set(); +let current_batch = null; +let batch_values = null; +let queued_root_effects = []; +let last_scheduled_effect = null; +let is_flushing = false; +let is_flushing_sync = false; +class Batch { + committed = false; + /** + * The current values of any sources that are updated in this batch + * They keys of this map are identical to `this.#previous` + * @type {Map} + */ + current = /* @__PURE__ */ new Map(); + /** + * The values of any sources that are updated in this batch _before_ those updates took place. + * They keys of this map are identical to `this.#current` + * @type {Map} + */ + previous = /* @__PURE__ */ new Map(); + /** + * When the batch is committed (and the DOM is updated), we need to remove old branches + * and append new ones by calling the functions added inside (if/each/key/etc) blocks + * @type {Set<() => void>} + */ + #commit_callbacks = /* @__PURE__ */ new Set(); + /** + * If a fork is discarded, we need to destroy any effects that are no longer needed + * @type {Set<(batch: Batch) => void>} + */ + #discard_callbacks = /* @__PURE__ */ new Set(); + /** + * The number of async effects that are currently in flight + */ + #pending = 0; + /** + * The number of async effects that are currently in flight, _not_ inside a pending boundary + */ + #blocking_pending = 0; + /** + * A deferred that resolves when the batch is committed, used with `settled()` + * TODO replace with Promise.withResolvers once supported widely enough + * @type {{ promise: Promise, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null} + */ + #deferred = null; + /** + * Deferred effects (which run after async work has completed) that are DIRTY + * @type {Set} + */ + #dirty_effects = /* @__PURE__ */ new Set(); + /** + * Deferred effects that are MAYBE_DIRTY + * @type {Set} + */ + #maybe_dirty_effects = /* @__PURE__ */ new Set(); + /** + * A map of branches that still exist, but will be destroyed when this batch + * is committed — we skip over these during `process`. + * The value contains child effects that were dirty/maybe_dirty before being reset, + * so they can be rescheduled if the branch survives. + * @type {Map} + */ + #skipped_branches = /* @__PURE__ */ new Map(); + is_fork = false; + #decrement_queued = false; + is_deferred() { + return this.is_fork || this.#blocking_pending > 0; + } + /** + * Add an effect to the #skipped_branches map and reset its children + * @param {Effect} effect + */ + skip_effect(effect) { + if (!this.#skipped_branches.has(effect)) { + this.#skipped_branches.set(effect, { d: [], m: [] }); + } + } + /** + * Remove an effect from the #skipped_branches map and reschedule + * any tracked dirty/maybe_dirty child effects + * @param {Effect} effect + */ + unskip_effect(effect) { + var tracked = this.#skipped_branches.get(effect); + if (tracked) { + this.#skipped_branches.delete(effect); + for (var e of tracked.d) { + set_signal_status(e, DIRTY); + schedule_effect(e); + } + for (e of tracked.m) { + set_signal_status(e, MAYBE_DIRTY); + schedule_effect(e); + } + } + } + /** + * + * @param {Effect[]} root_effects + */ + process(root_effects) { + queued_root_effects = []; + this.apply(); + var effects = []; + var render_effects = []; + for (const root2 of root_effects) { + this.#traverse_effect_tree(root2, effects, render_effects); + } + if (this.is_deferred()) { + this.#defer_effects(render_effects); + this.#defer_effects(effects); + for (const [e, t] of this.#skipped_branches) { + reset_branch(e, t); + } + } else { + for (const fn of this.#commit_callbacks) fn(); + this.#commit_callbacks.clear(); + if (this.#pending === 0) { + this.#commit(); + } + current_batch = null; + flush_queued_effects(render_effects); + flush_queued_effects(effects); + this.#deferred?.resolve(); + } + batch_values = null; + } + /** + * Traverse the effect tree, executing effects or stashing + * them for later execution as appropriate + * @param {Effect} root + * @param {Effect[]} effects + * @param {Effect[]} render_effects + */ + #traverse_effect_tree(root2, effects, render_effects) { + root2.f ^= CLEAN; + var effect = root2.first; + var pending_boundary = null; + while (effect !== null) { + var flags2 = effect.f; + var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0; + var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0; + var skip = is_skippable_branch || (flags2 & INERT) !== 0 || this.#skipped_branches.has(effect); + if (!skip && effect.fn !== null) { + if (is_branch) { + effect.f ^= CLEAN; + } else if (pending_boundary !== null && (flags2 & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0) { + pending_boundary.b.defer_effect(effect); + } else if ((flags2 & EFFECT) !== 0) { + effects.push(effect); + } else if (is_dirty(effect)) { + if ((flags2 & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect); + update_effect(effect); + } + var child = effect.first; + if (child !== null) { + effect = child; + continue; + } + } + var parent = effect.parent; + effect = effect.next; + while (effect === null && parent !== null) { + if (parent === pending_boundary) { + pending_boundary = null; + } + effect = parent.next; + parent = parent.parent; + } + } + } + /** + * @param {Effect[]} effects + */ + #defer_effects(effects) { + for (var i = 0; i < effects.length; i += 1) { + defer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects); + } + } + /** + * Associate a change to a given source with the current + * batch, noting its previous and current values + * @param {Source} source + * @param {any} value + */ + capture(source2, value) { + if (value !== UNINITIALIZED && !this.previous.has(source2)) { + this.previous.set(source2, value); + } + if ((source2.f & ERROR_VALUE) === 0) { + this.current.set(source2, source2.v); + batch_values?.set(source2, source2.v); + } + } + activate() { + current_batch = this; + this.apply(); + } + deactivate() { + if (current_batch !== this) return; + current_batch = null; + batch_values = null; + } + flush() { + this.activate(); + if (queued_root_effects.length > 0) { + flush_effects(); + if (current_batch !== null && current_batch !== this) { + return; + } + } else if (this.#pending === 0) { + this.process([]); + } + this.deactivate(); + } + discard() { + for (const fn of this.#discard_callbacks) fn(this); + this.#discard_callbacks.clear(); + } + #commit() { + if (batches.size > 1) { + this.previous.clear(); + var previous_batch_values = batch_values; + var is_earlier = true; + for (const batch of batches) { + if (batch === this) { + is_earlier = false; + continue; + } + const sources = []; + for (const [source2, value] of this.current) { + if (batch.current.has(source2)) { + if (is_earlier && value !== batch.current.get(source2)) { + batch.current.set(source2, value); + } else { + continue; + } + } + sources.push(source2); + } + if (sources.length === 0) { + continue; + } + const others = [...batch.current.keys()].filter((s) => !this.current.has(s)); + if (others.length > 0) { + var prev_queued_root_effects = queued_root_effects; + queued_root_effects = []; + const marked = /* @__PURE__ */ new Set(); + const checked = /* @__PURE__ */ new Map(); + for (const source2 of sources) { + mark_effects(source2, others, marked, checked); + } + if (queued_root_effects.length > 0) { + current_batch = batch; + batch.apply(); + for (const root2 of queued_root_effects) { + batch.#traverse_effect_tree(root2, [], []); + } + batch.deactivate(); + } + queued_root_effects = prev_queued_root_effects; + } + } + current_batch = null; + batch_values = previous_batch_values; + } + this.committed = true; + batches.delete(this); + } + /** + * + * @param {boolean} blocking + */ + increment(blocking) { + this.#pending += 1; + if (blocking) this.#blocking_pending += 1; + } + /** + * + * @param {boolean} blocking + */ + decrement(blocking) { + this.#pending -= 1; + if (blocking) this.#blocking_pending -= 1; + if (this.#decrement_queued) return; + this.#decrement_queued = true; + queue_micro_task(() => { + this.#decrement_queued = false; + if (!this.is_deferred()) { + this.revive(); + } else if (queued_root_effects.length > 0) { + this.flush(); + } + }); + } + revive() { + for (const e of this.#dirty_effects) { + this.#maybe_dirty_effects.delete(e); + set_signal_status(e, DIRTY); + schedule_effect(e); + } + for (const e of this.#maybe_dirty_effects) { + set_signal_status(e, MAYBE_DIRTY); + schedule_effect(e); + } + this.flush(); + } + /** @param {() => void} fn */ + oncommit(fn) { + this.#commit_callbacks.add(fn); + } + /** @param {(batch: Batch) => void} fn */ + ondiscard(fn) { + this.#discard_callbacks.add(fn); + } + settled() { + return (this.#deferred ??= deferred()).promise; + } + static ensure() { + if (current_batch === null) { + const batch = current_batch = new Batch(); + batches.add(current_batch); + if (!is_flushing_sync) { + queue_micro_task(() => { + if (current_batch !== batch) { + return; + } + batch.flush(); + }); + } + } + return current_batch; + } + apply() { + return; + } +} +function flushSync(fn) { + var was_flushing_sync = is_flushing_sync; + is_flushing_sync = true; + try { + var result; + if (fn) ; + while (true) { + flush_tasks(); + if (queued_root_effects.length === 0) { + current_batch?.flush(); + if (queued_root_effects.length === 0) { + last_scheduled_effect = null; + return ( + /** @type {T} */ + result + ); + } + } + flush_effects(); + } + } finally { + is_flushing_sync = was_flushing_sync; + } +} +function flush_effects() { + is_flushing = true; + var source_stacks = null; + try { + var flush_count = 0; + while (queued_root_effects.length > 0) { + var batch = Batch.ensure(); + if (flush_count++ > 1e3) { + var updates, entry; + if (BROWSER) ; + infinite_loop_guard(); + } + batch.process(queued_root_effects); + old_values.clear(); + if (BROWSER) ; + } + } finally { + queued_root_effects = []; + is_flushing = false; + last_scheduled_effect = null; + } +} +function infinite_loop_guard() { + try { + effect_update_depth_exceeded(); + } catch (error) { + invoke_error_boundary(error, last_scheduled_effect); + } +} +let eager_block_effects = null; +function flush_queued_effects(effects) { + var length = effects.length; + if (length === 0) return; + var i = 0; + while (i < length) { + var effect = effects[i++]; + if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) { + eager_block_effects = /* @__PURE__ */ new Set(); + update_effect(effect); + if (effect.deps === null && effect.first === null && effect.nodes === null) { + if (effect.teardown === null && effect.ac === null) { + unlink_effect(effect); + } else { + effect.fn = null; + } + } + if (eager_block_effects?.size > 0) { + old_values.clear(); + for (const e of eager_block_effects) { + if ((e.f & (DESTROYED | INERT)) !== 0) continue; + const ordered_effects = [e]; + let ancestor = e.parent; + while (ancestor !== null) { + if (eager_block_effects.has(ancestor)) { + eager_block_effects.delete(ancestor); + ordered_effects.push(ancestor); + } + ancestor = ancestor.parent; + } + for (let j = ordered_effects.length - 1; j >= 0; j--) { + const e2 = ordered_effects[j]; + if ((e2.f & (DESTROYED | INERT)) !== 0) continue; + update_effect(e2); + } + } + eager_block_effects.clear(); + } + } + } + eager_block_effects = null; +} +function mark_effects(value, sources, marked, checked) { + if (marked.has(value)) return; + marked.add(value); + if (value.reactions !== null) { + for (const reaction of value.reactions) { + const flags2 = reaction.f; + if ((flags2 & DERIVED) !== 0) { + mark_effects( + /** @type {Derived} */ + reaction, + sources, + marked, + checked + ); + } else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && depends_on(reaction, sources, checked)) { + set_signal_status(reaction, DIRTY); + schedule_effect( + /** @type {Effect} */ + reaction + ); + } + } + } +} +function depends_on(reaction, sources, checked) { + const depends = checked.get(reaction); + if (depends !== void 0) return depends; + if (reaction.deps !== null) { + for (const dep of reaction.deps) { + if (includes.call(sources, dep)) { + return true; + } + if ((dep.f & DERIVED) !== 0 && depends_on( + /** @type {Derived} */ + dep, + sources, + checked + )) { + checked.set( + /** @type {Derived} */ + dep, + true + ); + return true; + } + } + } + checked.set(reaction, false); + return false; +} +function schedule_effect(signal) { + var effect = last_scheduled_effect = signal; + while (effect.parent !== null) { + effect = effect.parent; + var flags2 = effect.f; + if (is_flushing && effect === active_effect && (flags2 & BLOCK_EFFECT) !== 0 && (flags2 & HEAD_EFFECT) === 0) { + return; + } + if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { + if ((flags2 & CLEAN) === 0) return; + effect.f ^= CLEAN; + } + } + queued_root_effects.push(effect); +} +function reset_branch(effect, tracked) { + if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) { + return; + } + if ((effect.f & DIRTY) !== 0) { + tracked.d.push(effect); + } else if ((effect.f & MAYBE_DIRTY) !== 0) { + tracked.m.push(effect); + } + set_signal_status(effect, CLEAN); + var e = effect.first; + while (e !== null) { + reset_branch(e, tracked); + e = e.next; + } +} +function createSubscriber(start) { + let subscribers = 0; + let version = source(0); + let stop; + return () => { + if (effect_tracking()) { + get(version); + render_effect(() => { + if (subscribers === 0) { + stop = untrack(() => start(() => increment(version))); + } + subscribers += 1; + return () => { + queue_micro_task(() => { + subscribers -= 1; + if (subscribers === 0) { + stop?.(); + stop = void 0; + increment(version); + } + }); + }; + }); + } + }; +} +var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED | BOUNDARY_EFFECT; +function boundary(node, props, children) { + new Boundary(node, props, children); +} +class Boundary { + /** @type {Boundary | null} */ + parent; + is_pending = false; + /** @type {TemplateNode} */ + #anchor; + /** @type {TemplateNode | null} */ + #hydrate_open = hydrating ? hydrate_node : null; + /** @type {BoundaryProps} */ + #props; + /** @type {((anchor: Node) => void)} */ + #children; + /** @type {Effect} */ + #effect; + /** @type {Effect | null} */ + #main_effect = null; + /** @type {Effect | null} */ + #pending_effect = null; + /** @type {Effect | null} */ + #failed_effect = null; + /** @type {DocumentFragment | null} */ + #offscreen_fragment = null; + /** @type {TemplateNode | null} */ + #pending_anchor = null; + #local_pending_count = 0; + #pending_count = 0; + #pending_count_update_queued = false; + #is_creating_fallback = false; + /** @type {Set} */ + #dirty_effects = /* @__PURE__ */ new Set(); + /** @type {Set} */ + #maybe_dirty_effects = /* @__PURE__ */ new Set(); + /** + * A source containing the number of pending async deriveds/expressions. + * Only created if `$effect.pending()` is used inside the boundary, + * otherwise updating the source results in needless `Batch.ensure()` + * calls followed by no-op flushes + * @type {Source | null} + */ + #effect_pending = null; + #effect_pending_subscriber = createSubscriber(() => { + this.#effect_pending = source(this.#local_pending_count); + return () => { + this.#effect_pending = null; + }; + }); + /** + * @param {TemplateNode} node + * @param {BoundaryProps} props + * @param {((anchor: Node) => void)} children + */ + constructor(node, props, children) { + this.#anchor = node; + this.#props = props; + this.#children = children; + this.parent = /** @type {Effect} */ + active_effect.b; + this.is_pending = !!this.#props.pending; + this.#effect = block(() => { + active_effect.b = this; + if (hydrating) { + const comment = this.#hydrate_open; + hydrate_next(); + const server_rendered_pending = ( + /** @type {Comment} */ + comment.nodeType === COMMENT_NODE && /** @type {Comment} */ + comment.data === HYDRATION_START_ELSE + ); + if (server_rendered_pending) { + this.#hydrate_pending_content(); + } else { + this.#hydrate_resolved_content(); + if (this.#pending_count === 0) { + this.is_pending = false; + } + } + } else { + var anchor = this.#get_anchor(); + try { + this.#main_effect = branch(() => children(anchor)); + } catch (error) { + this.error(error); + } + if (this.#pending_count > 0) { + this.#show_pending_snippet(); + } else { + this.is_pending = false; + } + } + return () => { + this.#pending_anchor?.remove(); + }; + }, flags); + if (hydrating) { + this.#anchor = hydrate_node; + } + } + #hydrate_resolved_content() { + try { + this.#main_effect = branch(() => this.#children(this.#anchor)); + } catch (error) { + this.error(error); + } + } + #hydrate_pending_content() { + const pending = this.#props.pending; + if (!pending) return; + this.#pending_effect = branch(() => pending(this.#anchor)); + queue_micro_task(() => { + var anchor = this.#get_anchor(); + this.#main_effect = this.#run(() => { + Batch.ensure(); + return branch(() => this.#children(anchor)); + }); + if (this.#pending_count > 0) { + this.#show_pending_snippet(); + } else { + pause_effect( + /** @type {Effect} */ + this.#pending_effect, + () => { + this.#pending_effect = null; + } + ); + this.is_pending = false; + } + }); + } + #get_anchor() { + var anchor = this.#anchor; + if (this.is_pending) { + this.#pending_anchor = create_text(); + this.#anchor.before(this.#pending_anchor); + anchor = this.#pending_anchor; + } + return anchor; + } + /** + * Defer an effect inside a pending boundary until the boundary resolves + * @param {Effect} effect + */ + defer_effect(effect) { + defer_effect(effect, this.#dirty_effects, this.#maybe_dirty_effects); + } + /** + * Returns `false` if the effect exists inside a boundary whose pending snippet is shown + * @returns {boolean} + */ + is_rendered() { + return !this.is_pending && (!this.parent || this.parent.is_rendered()); + } + has_pending_snippet() { + return !!this.#props.pending; + } + /** + * @param {() => Effect | null} fn + */ + #run(fn) { + var previous_effect = active_effect; + var previous_reaction = active_reaction; + var previous_ctx = component_context; + set_active_effect(this.#effect); + set_active_reaction(this.#effect); + set_component_context(this.#effect.ctx); + try { + return fn(); + } catch (e) { + handle_error(e); + return null; + } finally { + set_active_effect(previous_effect); + set_active_reaction(previous_reaction); + set_component_context(previous_ctx); + } + } + #show_pending_snippet() { + const pending = ( + /** @type {(anchor: Node) => void} */ + this.#props.pending + ); + if (this.#main_effect !== null) { + this.#offscreen_fragment = document.createDocumentFragment(); + this.#offscreen_fragment.append( + /** @type {TemplateNode} */ + this.#pending_anchor + ); + move_effect(this.#main_effect, this.#offscreen_fragment); + } + if (this.#pending_effect === null) { + this.#pending_effect = branch(() => pending(this.#anchor)); + } + } + /** + * Updates the pending count associated with the currently visible pending snippet, + * if any, such that we can replace the snippet with content once work is done + * @param {1 | -1} d + */ + #update_pending_count(d) { + if (!this.has_pending_snippet()) { + if (this.parent) { + this.parent.#update_pending_count(d); + } + return; + } + this.#pending_count += d; + if (this.#pending_count === 0) { + this.is_pending = false; + for (const e of this.#dirty_effects) { + set_signal_status(e, DIRTY); + schedule_effect(e); + } + for (const e of this.#maybe_dirty_effects) { + set_signal_status(e, MAYBE_DIRTY); + schedule_effect(e); + } + this.#dirty_effects.clear(); + this.#maybe_dirty_effects.clear(); + if (this.#pending_effect) { + pause_effect(this.#pending_effect, () => { + this.#pending_effect = null; + }); + } + if (this.#offscreen_fragment) { + this.#anchor.before(this.#offscreen_fragment); + this.#offscreen_fragment = null; + } + } + } + /** + * Update the source that powers `$effect.pending()` inside this boundary, + * and controls when the current `pending` snippet (if any) is removed. + * Do not call from inside the class + * @param {1 | -1} d + */ + update_pending_count(d) { + this.#update_pending_count(d); + this.#local_pending_count += d; + if (!this.#effect_pending || this.#pending_count_update_queued) return; + this.#pending_count_update_queued = true; + queue_micro_task(() => { + this.#pending_count_update_queued = false; + if (this.#effect_pending) { + internal_set(this.#effect_pending, this.#local_pending_count); + } + }); + } + get_effect_pending() { + this.#effect_pending_subscriber(); + return get( + /** @type {Source} */ + this.#effect_pending + ); + } + /** @param {unknown} error */ + error(error) { + var onerror = this.#props.onerror; + let failed = this.#props.failed; + if (this.#is_creating_fallback || !onerror && !failed) { + throw error; + } + if (this.#main_effect) { + destroy_effect(this.#main_effect); + this.#main_effect = null; + } + if (this.#pending_effect) { + destroy_effect(this.#pending_effect); + this.#pending_effect = null; + } + if (this.#failed_effect) { + destroy_effect(this.#failed_effect); + this.#failed_effect = null; + } + if (hydrating) { + set_hydrate_node( + /** @type {TemplateNode} */ + this.#hydrate_open + ); + next(); + set_hydrate_node(skip_nodes()); + } + var did_reset = false; + var calling_on_error = false; + const reset = () => { + if (did_reset) { + svelte_boundary_reset_noop(); + return; + } + did_reset = true; + if (calling_on_error) { + svelte_boundary_reset_onerror(); + } + Batch.ensure(); + this.#local_pending_count = 0; + if (this.#failed_effect !== null) { + pause_effect(this.#failed_effect, () => { + this.#failed_effect = null; + }); + } + this.is_pending = this.has_pending_snippet(); + this.#main_effect = this.#run(() => { + this.#is_creating_fallback = false; + return branch(() => this.#children(this.#anchor)); + }); + if (this.#pending_count > 0) { + this.#show_pending_snippet(); + } else { + this.is_pending = false; + } + }; + queue_micro_task(() => { + try { + calling_on_error = true; + onerror?.(error, reset); + calling_on_error = false; + } catch (error2) { + invoke_error_boundary(error2, this.#effect && this.#effect.parent); + } + if (failed) { + this.#failed_effect = this.#run(() => { + Batch.ensure(); + this.#is_creating_fallback = true; + try { + return branch(() => { + failed( + this.#anchor, + () => error, + () => reset + ); + }); + } catch (error2) { + invoke_error_boundary( + error2, + /** @type {Effect} */ + this.#effect.parent + ); + return null; + } finally { + this.#is_creating_fallback = false; + } + }); + } + }); + } +} +function destroy_derived_effects(derived) { + var effects = derived.effects; + if (effects !== null) { + derived.effects = null; + for (var i = 0; i < effects.length; i += 1) { + destroy_effect( + /** @type {Effect} */ + effects[i] + ); + } + } +} +function get_derived_parent_effect(derived) { + var parent = derived.parent; + while (parent !== null) { + if ((parent.f & DERIVED) === 0) { + return (parent.f & DESTROYED) === 0 ? ( + /** @type {Effect} */ + parent + ) : null; + } + parent = parent.parent; + } + return null; +} +function execute_derived(derived) { + var value; + var prev_active_effect = active_effect; + set_active_effect(get_derived_parent_effect(derived)); + { + try { + derived.f &= ~WAS_MARKED; + destroy_derived_effects(derived); + value = update_reaction(derived); + } finally { + set_active_effect(prev_active_effect); + } + } + return value; +} +function update_derived(derived) { + var value = execute_derived(derived); + if (!derived.equals(value)) { + derived.wv = increment_write_version(); + if (!current_batch?.is_fork || derived.deps === null) { + derived.v = value; + if (derived.deps === null) { + set_signal_status(derived, CLEAN); + return; + } + } + } + if (is_destroying_effect) { + return; + } + if (batch_values !== null) { + if (effect_tracking() || current_batch?.is_fork) { + batch_values.set(derived, value); + } + } else { + update_derived_status(derived); + } +} +let eager_effects = /* @__PURE__ */ new Set(); +const old_values = /* @__PURE__ */ new Map(); +let eager_effects_deferred = false; +function source(v, stack) { + var signal = { + f: 0, + // TODO ideally we could skip this altogether, but it causes type errors + v, + reactions: null, + equals, + rv: 0, + wv: 0 + }; + return signal; +} +// @__NO_SIDE_EFFECTS__ +function state(v, stack) { + const s = source(v); + push_reaction_value(s); + return s; +} +// @__NO_SIDE_EFFECTS__ +function mutable_source(initial_value, immutable = false, trackable = true) { + const s = source(initial_value); + if (!immutable) { + s.equals = safe_equals; + } + return s; +} +function set(source2, value, should_proxy = false) { + if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check + // to ensure we error if state is set inside an inspect effect + (!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !includes.call(current_sources, source2))) { + state_unsafe_mutation(); + } + let new_value = should_proxy ? proxy(value) : value; + return internal_set(source2, new_value); +} +function internal_set(source2, value) { + if (!source2.equals(value)) { + var old_value = source2.v; + if (is_destroying_effect) { + old_values.set(source2, value); + } else { + old_values.set(source2, old_value); + } + source2.v = value; + var batch = Batch.ensure(); + batch.capture(source2, old_value); + if ((source2.f & DERIVED) !== 0) { + const derived = ( + /** @type {Derived} */ + source2 + ); + if ((source2.f & DIRTY) !== 0) { + execute_derived(derived); + } + update_derived_status(derived); + } + source2.wv = increment_write_version(); + mark_reactions(source2, DIRTY); + if (active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) { + if (untracked_writes === null) { + set_untracked_writes([source2]); + } else { + untracked_writes.push(source2); + } + } + if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) { + flush_eager_effects(); + } + } + return value; +} +function flush_eager_effects() { + eager_effects_deferred = false; + for (const effect of eager_effects) { + if ((effect.f & CLEAN) !== 0) { + set_signal_status(effect, MAYBE_DIRTY); + } + if (is_dirty(effect)) { + update_effect(effect); + } + } + eager_effects.clear(); +} +function increment(source2) { + set(source2, source2.v + 1); +} +function mark_reactions(signal, status) { + var reactions = signal.reactions; + if (reactions === null) return; + var length = reactions.length; + for (var i = 0; i < length; i++) { + var reaction = reactions[i]; + var flags2 = reaction.f; + var not_dirty = (flags2 & DIRTY) === 0; + if (not_dirty) { + set_signal_status(reaction, status); + } + if ((flags2 & DERIVED) !== 0) { + var derived = ( + /** @type {Derived} */ + reaction + ); + batch_values?.delete(derived); + if ((flags2 & WAS_MARKED) === 0) { + if (flags2 & CONNECTED) { + reaction.f |= WAS_MARKED; + } + mark_reactions(derived, MAYBE_DIRTY); + } + } else if (not_dirty) { + if ((flags2 & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) { + eager_block_effects.add( + /** @type {Effect} */ + reaction + ); + } + schedule_effect( + /** @type {Effect} */ + reaction + ); + } + } +} +function proxy(value) { + if (typeof value !== "object" || value === null || STATE_SYMBOL in value) { + return value; + } + const prototype = get_prototype_of(value); + if (prototype !== object_prototype && prototype !== array_prototype) { + return value; + } + var sources = /* @__PURE__ */ new Map(); + var is_proxied_array = is_array(value); + var version = /* @__PURE__ */ state(0); + var parent_version = update_version; + var with_parent = (fn) => { + if (update_version === parent_version) { + return fn(); + } + var reaction = active_reaction; + var version2 = update_version; + set_active_reaction(null); + set_update_version(parent_version); + var result = fn(); + set_active_reaction(reaction); + set_update_version(version2); + return result; + }; + if (is_proxied_array) { + sources.set("length", /* @__PURE__ */ state( + /** @type {any[]} */ + value.length + )); + } + return new Proxy( + /** @type {any} */ + value, + { + defineProperty(_, prop, descriptor) { + if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) { + state_descriptors_fixed(); + } + var s = sources.get(prop); + if (s === void 0) { + s = with_parent(() => { + var s2 = /* @__PURE__ */ state(descriptor.value); + sources.set(prop, s2); + return s2; + }); + } else { + set(s, descriptor.value, true); + } + return true; + }, + deleteProperty(target, prop) { + var s = sources.get(prop); + if (s === void 0) { + if (prop in target) { + const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); + sources.set(prop, s2); + increment(version); + } + } else { + set(s, UNINITIALIZED); + increment(version); + } + return true; + }, + get(target, prop, receiver) { + if (prop === STATE_SYMBOL) { + return value; + } + var s = sources.get(prop); + var exists = prop in target; + if (s === void 0 && (!exists || get_descriptor(target, prop)?.writable)) { + s = with_parent(() => { + var p = proxy(exists ? target[prop] : UNINITIALIZED); + var s2 = /* @__PURE__ */ state(p); + return s2; + }); + sources.set(prop, s); + } + if (s !== void 0) { + var v = get(s); + return v === UNINITIALIZED ? void 0 : v; + } + return Reflect.get(target, prop, receiver); + }, + getOwnPropertyDescriptor(target, prop) { + var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); + if (descriptor && "value" in descriptor) { + var s = sources.get(prop); + if (s) descriptor.value = get(s); + } else if (descriptor === void 0) { + var source2 = sources.get(prop); + var value2 = source2?.v; + if (source2 !== void 0 && value2 !== UNINITIALIZED) { + return { + enumerable: true, + configurable: true, + value: value2, + writable: true + }; + } + } + return descriptor; + }, + has(target, prop) { + if (prop === STATE_SYMBOL) { + return true; + } + var s = sources.get(prop); + var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop); + if (s !== void 0 || active_effect !== null && (!has || get_descriptor(target, prop)?.writable)) { + if (s === void 0) { + s = with_parent(() => { + var p = has ? proxy(target[prop]) : UNINITIALIZED; + var s2 = /* @__PURE__ */ state(p); + return s2; + }); + sources.set(prop, s); + } + var value2 = get(s); + if (value2 === UNINITIALIZED) { + return false; + } + } + return has; + }, + set(target, prop, value2, receiver) { + var s = sources.get(prop); + var has = prop in target; + if (is_proxied_array && prop === "length") { + for (var i = value2; i < /** @type {Source} */ + s.v; i += 1) { + var other_s = sources.get(i + ""); + if (other_s !== void 0) { + set(other_s, UNINITIALIZED); + } else if (i in target) { + other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); + sources.set(i + "", other_s); + } + } + } + if (s === void 0) { + if (!has || get_descriptor(target, prop)?.writable) { + s = with_parent(() => /* @__PURE__ */ state(void 0)); + set(s, proxy(value2)); + sources.set(prop, s); + } + } else { + has = s.v !== UNINITIALIZED; + var p = with_parent(() => proxy(value2)); + set(s, p); + } + var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); + if (descriptor?.set) { + descriptor.set.call(receiver, value2); + } + if (!has) { + if (is_proxied_array && typeof prop === "string") { + var ls = ( + /** @type {Source} */ + sources.get("length") + ); + var n = Number(prop); + if (Number.isInteger(n) && n >= ls.v) { + set(ls, n + 1); + } + } + increment(version); + } + return true; + }, + ownKeys(target) { + get(version); + var own_keys = Reflect.ownKeys(target).filter((key2) => { + var source3 = sources.get(key2); + return source3 === void 0 || source3.v !== UNINITIALIZED; + }); + for (var [key, source2] of sources) { + if (source2.v !== UNINITIALIZED && !(key in target)) { + own_keys.push(key); + } + } + return own_keys; + }, + setPrototypeOf() { + state_prototype_fixed(); + } + } + ); +} +var $window; +var first_child_getter; +var next_sibling_getter; +function init_operations() { + if ($window !== void 0) { + return; + } + $window = window; + var element_prototype = Element.prototype; + var node_prototype = Node.prototype; + var text_prototype = Text.prototype; + first_child_getter = get_descriptor(node_prototype, "firstChild").get; + next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get; + if (is_extensible(element_prototype)) { + element_prototype.__click = void 0; + element_prototype.__className = void 0; + element_prototype.__attributes = null; + element_prototype.__style = void 0; + element_prototype.__e = void 0; + } + if (is_extensible(text_prototype)) { + text_prototype.__t = void 0; + } +} +function create_text(value = "") { + return document.createTextNode(value); +} +// @__NO_SIDE_EFFECTS__ +function get_first_child(node) { + return ( + /** @type {TemplateNode | null} */ + first_child_getter.call(node) + ); +} +// @__NO_SIDE_EFFECTS__ +function get_next_sibling(node) { + return ( + /** @type {TemplateNode | null} */ + next_sibling_getter.call(node) + ); +} +function clear_text_content(node) { + node.textContent = ""; +} +function without_reactive_context(fn) { + var previous_reaction = active_reaction; + var previous_effect = active_effect; + set_active_reaction(null); + set_active_effect(null); + try { + return fn(); + } finally { + set_active_reaction(previous_reaction); + set_active_effect(previous_effect); + } +} +function push_effect(effect, parent_effect) { + var parent_last = parent_effect.last; + if (parent_last === null) { + parent_effect.last = parent_effect.first = effect; + } else { + parent_last.next = effect; + effect.prev = parent_last; + parent_effect.last = effect; + } +} +function create_effect(type, fn, sync) { + var parent = active_effect; + if (parent !== null && (parent.f & INERT) !== 0) { + type |= INERT; + } + var effect = { + ctx: component_context, + deps: null, + nodes: null, + f: type | DIRTY | CONNECTED, + first: null, + fn, + last: null, + next: null, + parent, + b: parent && parent.b, + prev: null, + teardown: null, + wv: 0, + ac: null + }; + if (sync) { + try { + update_effect(effect); + effect.f |= EFFECT_RAN; + } catch (e2) { + destroy_effect(effect); + throw e2; + } + } else if (fn !== null) { + schedule_effect(effect); + } + var e = effect; + if (sync && e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child + (e.f & EFFECT_PRESERVED) === 0) { + e = e.first; + if ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) { + e.f |= EFFECT_TRANSPARENT; + } + } + if (e !== null) { + e.parent = parent; + if (parent !== null) { + push_effect(e, parent); + } + if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) { + var derived = ( + /** @type {Derived} */ + active_reaction + ); + (derived.effects ??= []).push(e); + } + } + return effect; +} +function effect_tracking() { + return active_reaction !== null && !untracking; +} +function create_user_effect(fn) { + return create_effect(EFFECT | USER_EFFECT, fn, false); +} +function component_root(fn) { + Batch.ensure(); + const effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn, true); + return (options2 = {}) => { + return new Promise((fulfil) => { + if (options2.outro) { + pause_effect(effect, () => { + destroy_effect(effect); + fulfil(void 0); + }); + } else { + destroy_effect(effect); + fulfil(void 0); + } + }); + }; +} +function render_effect(fn, flags2 = 0) { + return create_effect(RENDER_EFFECT | flags2, fn, true); +} +function block(fn, flags2 = 0) { + var effect = create_effect(BLOCK_EFFECT | flags2, fn, true); + return effect; +} +function branch(fn) { + return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn, true); +} +function execute_effect_teardown(effect) { + var teardown = effect.teardown; + if (teardown !== null) { + const previously_destroying_effect = is_destroying_effect; + const previous_reaction = active_reaction; + set_is_destroying_effect(true); + set_active_reaction(null); + try { + teardown.call(null); + } finally { + set_is_destroying_effect(previously_destroying_effect); + set_active_reaction(previous_reaction); + } + } +} +function destroy_effect_children(signal, remove_dom = false) { + var effect = signal.first; + signal.first = signal.last = null; + while (effect !== null) { + const controller = effect.ac; + if (controller !== null) { + without_reactive_context(() => { + controller.abort(STALE_REACTION); + }); + } + var next2 = effect.next; + if ((effect.f & ROOT_EFFECT) !== 0) { + effect.parent = null; + } else { + destroy_effect(effect, remove_dom); + } + effect = next2; + } +} +function destroy_block_effect_children(signal) { + var effect = signal.first; + while (effect !== null) { + var next2 = effect.next; + if ((effect.f & BRANCH_EFFECT) === 0) { + destroy_effect(effect); + } + effect = next2; + } +} +function destroy_effect(effect, remove_dom = true) { + var removed = false; + if ((remove_dom || (effect.f & HEAD_EFFECT) !== 0) && effect.nodes !== null && effect.nodes.end !== null) { + remove_effect_dom( + effect.nodes.start, + /** @type {TemplateNode} */ + effect.nodes.end + ); + removed = true; + } + destroy_effect_children(effect, remove_dom && !removed); + remove_reactions(effect, 0); + set_signal_status(effect, DESTROYED); + var transitions = effect.nodes && effect.nodes.t; + if (transitions !== null) { + for (const transition of transitions) { + transition.stop(); + } + } + execute_effect_teardown(effect); + var parent = effect.parent; + if (parent !== null && parent.first !== null) { + unlink_effect(effect); + } + effect.next = effect.prev = effect.teardown = effect.ctx = effect.deps = effect.fn = effect.nodes = effect.ac = null; +} +function remove_effect_dom(node, end) { + while (node !== null) { + var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); + node.remove(); + node = next2; + } +} +function unlink_effect(effect) { + var parent = effect.parent; + var prev = effect.prev; + var next2 = effect.next; + if (prev !== null) prev.next = next2; + if (next2 !== null) next2.prev = prev; + if (parent !== null) { + if (parent.first === effect) parent.first = next2; + if (parent.last === effect) parent.last = prev; + } +} +function pause_effect(effect, callback, destroy = true) { + var transitions = []; + pause_children(effect, transitions, true); + var fn = () => { + if (destroy) destroy_effect(effect); + if (callback) callback(); + }; + var remaining = transitions.length; + if (remaining > 0) { + var check = () => --remaining || fn(); + for (var transition of transitions) { + transition.out(check); + } + } else { + fn(); + } +} +function pause_children(effect, transitions, local) { + if ((effect.f & INERT) !== 0) return; + effect.f ^= INERT; + var t = effect.nodes && effect.nodes.t; + if (t !== null) { + for (const transition of t) { + if (transition.is_global || local) { + transitions.push(transition); + } + } + } + var child = effect.first; + while (child !== null) { + var sibling = child.next; + var transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent, + // it means the parent block effect was pruned. In that case, + // transparency information was transferred to the branch effect. + (child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0; + pause_children(child, transitions, transparent ? local : false); + child = sibling; + } +} +function move_effect(effect, fragment) { + if (!effect.nodes) return; + var node = effect.nodes.start; + var end = effect.nodes.end; + while (node !== null) { + var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); + fragment.append(node); + node = next2; + } +} +let is_updating_effect = false; +let is_destroying_effect = false; +function set_is_destroying_effect(value) { + is_destroying_effect = value; +} +let active_reaction = null; +let untracking = false; +function set_active_reaction(reaction) { + active_reaction = reaction; +} +let active_effect = null; +function set_active_effect(effect) { + active_effect = effect; +} +let current_sources = null; +function push_reaction_value(value) { + if (active_reaction !== null && true) { + if (current_sources === null) { + current_sources = [value]; + } else { + current_sources.push(value); + } + } +} +let new_deps = null; +let skipped_deps = 0; +let untracked_writes = null; +function set_untracked_writes(value) { + untracked_writes = value; +} +let write_version = 1; +let read_version = 0; +let update_version = read_version; +function set_update_version(value) { + update_version = value; +} +function increment_write_version() { + return ++write_version; +} +function is_dirty(reaction) { + var flags2 = reaction.f; + if ((flags2 & DIRTY) !== 0) { + return true; + } + if (flags2 & DERIVED) { + reaction.f &= ~WAS_MARKED; + } + if ((flags2 & MAYBE_DIRTY) !== 0) { + var dependencies = ( + /** @type {Value[]} */ + reaction.deps + ); + var length = dependencies.length; + for (var i = 0; i < length; i++) { + var dependency = dependencies[i]; + if (is_dirty( + /** @type {Derived} */ + dependency + )) { + update_derived( + /** @type {Derived} */ + dependency + ); + } + if (dependency.wv > reaction.wv) { + return true; + } + } + if ((flags2 & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that + // traversal of the graph in the other batches still happens + batch_values === null) { + set_signal_status(reaction, CLEAN); + } + } + return false; +} +function schedule_possible_effect_self_invalidation(signal, effect, root2 = true) { + var reactions = signal.reactions; + if (reactions === null) return; + if (current_sources !== null && includes.call(current_sources, signal)) { + return; + } + for (var i = 0; i < reactions.length; i++) { + var reaction = reactions[i]; + if ((reaction.f & DERIVED) !== 0) { + schedule_possible_effect_self_invalidation( + /** @type {Derived} */ + reaction, + effect, + false + ); + } else if (effect === reaction) { + if (root2) { + set_signal_status(reaction, DIRTY); + } else if ((reaction.f & CLEAN) !== 0) { + set_signal_status(reaction, MAYBE_DIRTY); + } + schedule_effect( + /** @type {Effect} */ + reaction + ); + } + } +} +function update_reaction(reaction) { + var previous_deps = new_deps; + var previous_skipped_deps = skipped_deps; + var previous_untracked_writes = untracked_writes; + var previous_reaction = active_reaction; + var previous_sources = current_sources; + var previous_component_context = component_context; + var previous_untracking = untracking; + var previous_update_version = update_version; + var flags2 = reaction.f; + new_deps = /** @type {null | Value[]} */ + null; + skipped_deps = 0; + untracked_writes = null; + active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; + current_sources = null; + set_component_context(reaction.ctx); + untracking = false; + update_version = ++read_version; + if (reaction.ac !== null) { + without_reactive_context(() => { + reaction.ac.abort(STALE_REACTION); + }); + reaction.ac = null; + } + try { + reaction.f |= REACTION_IS_UPDATING; + var fn = ( + /** @type {Function} */ + reaction.fn + ); + var result = fn(); + var deps = reaction.deps; + var is_fork = current_batch?.is_fork; + if (new_deps !== null) { + var i; + if (!is_fork) { + remove_reactions(reaction, skipped_deps); + } + if (deps !== null && skipped_deps > 0) { + deps.length = skipped_deps + new_deps.length; + for (i = 0; i < new_deps.length; i++) { + deps[skipped_deps + i] = new_deps[i]; + } + } else { + reaction.deps = deps = new_deps; + } + if (effect_tracking() && (reaction.f & CONNECTED) !== 0) { + for (i = skipped_deps; i < deps.length; i++) { + (deps[i].reactions ??= []).push(reaction); + } + } + } else if (!is_fork && deps !== null && skipped_deps < deps.length) { + remove_reactions(reaction, skipped_deps); + deps.length = skipped_deps; + } + if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) { + for (i = 0; i < /** @type {Source[]} */ + untracked_writes.length; i++) { + schedule_possible_effect_self_invalidation( + untracked_writes[i], + /** @type {Effect} */ + reaction + ); + } + } + if (previous_reaction !== null && previous_reaction !== reaction) { + read_version++; + if (previous_reaction.deps !== null) { + for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) { + previous_reaction.deps[i2].rv = read_version; + } + } + if (previous_deps !== null) { + for (const dep of previous_deps) { + dep.rv = read_version; + } + } + if (untracked_writes !== null) { + if (previous_untracked_writes === null) { + previous_untracked_writes = untracked_writes; + } else { + previous_untracked_writes.push(.../** @type {Source[]} */ + untracked_writes); + } + } + } + if ((reaction.f & ERROR_VALUE) !== 0) { + reaction.f ^= ERROR_VALUE; + } + return result; + } catch (error) { + return handle_error(error); + } finally { + reaction.f ^= REACTION_IS_UPDATING; + new_deps = previous_deps; + skipped_deps = previous_skipped_deps; + untracked_writes = previous_untracked_writes; + active_reaction = previous_reaction; + current_sources = previous_sources; + set_component_context(previous_component_context); + untracking = previous_untracking; + update_version = previous_update_version; + } +} +function remove_reaction(signal, dependency) { + let reactions = dependency.reactions; + if (reactions !== null) { + var index = index_of.call(reactions, signal); + if (index !== -1) { + var new_length = reactions.length - 1; + if (new_length === 0) { + reactions = dependency.reactions = null; + } else { + reactions[index] = reactions[new_length]; + reactions.pop(); + } + } + } + if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear + // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` + // allows us to skip the expensive work of disconnecting and immediately reconnecting it + (new_deps === null || !includes.call(new_deps, dependency))) { + var derived = ( + /** @type {Derived} */ + dependency + ); + if ((derived.f & CONNECTED) !== 0) { + derived.f ^= CONNECTED; + derived.f &= ~WAS_MARKED; + } + update_derived_status(derived); + destroy_derived_effects(derived); + remove_reactions(derived, 0); + } +} +function remove_reactions(signal, start_index) { + var dependencies = signal.deps; + if (dependencies === null) return; + for (var i = start_index; i < dependencies.length; i++) { + remove_reaction(signal, dependencies[i]); + } +} +function update_effect(effect) { + var flags2 = effect.f; + if ((flags2 & DESTROYED) !== 0) { + return; + } + set_signal_status(effect, CLEAN); + var previous_effect = active_effect; + var was_updating_effect = is_updating_effect; + active_effect = effect; + is_updating_effect = true; + try { + if ((flags2 & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) { + destroy_block_effect_children(effect); + } else { + destroy_effect_children(effect); + } + execute_effect_teardown(effect); + var teardown = update_reaction(effect); + effect.teardown = typeof teardown === "function" ? teardown : null; + effect.wv = write_version; + var dep; + if (BROWSER && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) ; + } finally { + is_updating_effect = was_updating_effect; + active_effect = previous_effect; + } +} +function get(signal) { + var flags2 = signal.f; + var is_derived = (flags2 & DERIVED) !== 0; + if (active_reaction !== null && !untracking) { + var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0; + if (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) { + var deps = active_reaction.deps; + if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) { + if (signal.rv < read_version) { + signal.rv = read_version; + if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { + skipped_deps++; + } else if (new_deps === null) { + new_deps = [signal]; + } else { + new_deps.push(signal); + } + } + } else { + (active_reaction.deps ??= []).push(signal); + var reactions = signal.reactions; + if (reactions === null) { + signal.reactions = [active_reaction]; + } else if (!includes.call(reactions, active_reaction)) { + reactions.push(active_reaction); + } + } + } + } + if (is_destroying_effect && old_values.has(signal)) { + return old_values.get(signal); + } + if (is_derived) { + var derived = ( + /** @type {Derived} */ + signal + ); + if (is_destroying_effect) { + var value = derived.v; + if ((derived.f & CLEAN) === 0 && derived.reactions !== null || depends_on_old_values(derived)) { + value = execute_derived(derived); + } + old_values.set(derived, value); + return value; + } + var should_connect = (derived.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0); + var is_new = derived.deps === null; + if (is_dirty(derived)) { + if (should_connect) { + derived.f |= CONNECTED; + } + update_derived(derived); + } + if (should_connect && !is_new) { + reconnect(derived); + } + } + if (batch_values?.has(signal)) { + return batch_values.get(signal); + } + if ((signal.f & ERROR_VALUE) !== 0) { + throw signal.v; + } + return signal.v; +} +function reconnect(derived) { + if (derived.deps === null) return; + derived.f |= CONNECTED; + for (const dep of derived.deps) { + (dep.reactions ??= []).push(derived); + if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) { + reconnect( + /** @type {Derived} */ + dep + ); + } + } +} +function depends_on_old_values(derived) { + if (derived.v === UNINITIALIZED) return true; + if (derived.deps === null) return false; + for (const dep of derived.deps) { + if (old_values.has(dep)) { + return true; + } + if ((dep.f & DERIVED) !== 0 && depends_on_old_values( + /** @type {Derived} */ + dep + )) { + return true; + } + } + return false; +} +function untrack(fn) { + var previous_untracking = untracking; + try { + untracking = true; + return fn(); + } finally { + untracking = previous_untracking; + } +} +const all_registered_events = /* @__PURE__ */ new Set(); +const root_event_handles = /* @__PURE__ */ new Set(); +let last_propagated_event = null; +function handle_event_propagation(event) { + var handler_element = this; + var owner_document = ( + /** @type {Node} */ + handler_element.ownerDocument + ); + var event_name = event.type; + var path = event.composedPath?.() || []; + var current_target = ( + /** @type {null | Element} */ + path[0] || event.target + ); + last_propagated_event = event; + var path_idx = 0; + var handled_at = last_propagated_event === event && event.__root; + if (handled_at) { + var at_idx = path.indexOf(handled_at); + if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */ + window)) { + event.__root = handler_element; + return; + } + var handler_idx = path.indexOf(handler_element); + if (handler_idx === -1) { + return; + } + if (at_idx <= handler_idx) { + path_idx = at_idx; + } + } + current_target = /** @type {Element} */ + path[path_idx] || event.target; + if (current_target === handler_element) return; + define_property(event, "currentTarget", { + configurable: true, + get() { + return current_target || owner_document; + } + }); + var previous_reaction = active_reaction; + var previous_effect = active_effect; + set_active_reaction(null); + set_active_effect(null); + try { + var throw_error; + var other_errors = []; + while (current_target !== null) { + var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */ + current_target.host || null; + try { + var delegated = current_target["__" + event_name]; + if (delegated != null && (!/** @type {any} */ + current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well + // -> the target could not have been disabled because it emits the event in the first place + event.target === current_target)) { + delegated.call(current_target, event); + } + } catch (error) { + if (throw_error) { + other_errors.push(error); + } else { + throw_error = error; + } + } + if (event.cancelBubble || parent_element === handler_element || parent_element === null) { + break; + } + current_target = parent_element; + } + if (throw_error) { + for (let error of other_errors) { + queueMicrotask(() => { + throw error; + }); + } + throw throw_error; + } + } finally { + event.__root = handler_element; + delete event.currentTarget; + set_active_reaction(previous_reaction); + set_active_effect(previous_effect); + } +} +function assign_nodes(start, end) { + var effect = ( + /** @type {Effect} */ + active_effect + ); + if (effect.nodes === null) { + effect.nodes = { start, end, a: null, t: null }; + } +} +function mount(component, options2) { + return _mount(component, options2); +} +function hydrate(component, options2) { + init_operations(); + options2.intro = options2.intro ?? false; + const target = options2.target; + const was_hydrating = hydrating; + const previous_hydrate_node = hydrate_node; + try { + var anchor = /* @__PURE__ */ get_first_child(target); + while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ + anchor.data !== HYDRATION_START)) { + anchor = /* @__PURE__ */ get_next_sibling(anchor); + } + if (!anchor) { + throw HYDRATION_ERROR; + } + set_hydrating(true); + set_hydrate_node( + /** @type {Comment} */ + anchor + ); + const instance = _mount(component, { ...options2, anchor }); + set_hydrating(false); + return ( + /** @type {Exports} */ + instance + ); + } catch (error) { + if (error instanceof Error && error.message.split("\n").some((line) => line.startsWith("https://svelte.dev/e/"))) { + throw error; + } + if (error !== HYDRATION_ERROR) { + console.warn("Failed to hydrate: ", error); + } + if (options2.recover === false) { + hydration_failed(); + } + init_operations(); + clear_text_content(target); + set_hydrating(false); + return mount(component, options2); + } finally { + set_hydrating(was_hydrating); + set_hydrate_node(previous_hydrate_node); + } +} +const document_listeners = /* @__PURE__ */ new Map(); +function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) { + init_operations(); + var registered_events = /* @__PURE__ */ new Set(); + var event_handle = (events2) => { + for (var i = 0; i < events2.length; i++) { + var event_name = events2[i]; + if (registered_events.has(event_name)) continue; + registered_events.add(event_name); + var passive = is_passive_event(event_name); + target.addEventListener(event_name, handle_event_propagation, { passive }); + var n = document_listeners.get(event_name); + if (n === void 0) { + document.addEventListener(event_name, handle_event_propagation, { passive }); + document_listeners.set(event_name, 1); + } else { + document_listeners.set(event_name, n + 1); + } + } + }; + event_handle(array_from(all_registered_events)); + root_event_handles.add(event_handle); + var component = void 0; + var unmount2 = component_root(() => { + var anchor_node = anchor ?? target.appendChild(create_text()); + boundary( + /** @type {TemplateNode} */ + anchor_node, + { + pending: () => { + } + }, + (anchor_node2) => { + push({}); + var ctx = ( + /** @type {ComponentContext} */ + component_context + ); + if (context) ctx.c = context; + if (events) { + props.$$events = events; + } + if (hydrating) { + assign_nodes( + /** @type {TemplateNode} */ + anchor_node2, + null + ); + } + component = Component(anchor_node2, props) || {}; + if (hydrating) { + active_effect.nodes.end = hydrate_node; + if (hydrate_node === null || hydrate_node.nodeType !== COMMENT_NODE || /** @type {Comment} */ + hydrate_node.data !== HYDRATION_END) { + hydration_mismatch(); + throw HYDRATION_ERROR; + } + } + pop(); + } + ); + return () => { + for (var event_name of registered_events) { + target.removeEventListener(event_name, handle_event_propagation); + var n = ( + /** @type {number} */ + document_listeners.get(event_name) + ); + if (--n === 0) { + document.removeEventListener(event_name, handle_event_propagation); + document_listeners.delete(event_name); + } else { + document_listeners.set(event_name, n); + } + } + root_event_handles.delete(event_handle); + if (anchor_node !== anchor) { + anchor_node.parentNode?.removeChild(anchor_node); + } + }; + }); + mounted_components.set(component, unmount2); + return component; +} +let mounted_components = /* @__PURE__ */ new WeakMap(); +function unmount(component, options2) { + const fn = mounted_components.get(component); + if (fn) { + mounted_components.delete(component); + return fn(options2); + } + return Promise.resolve(); +} +function asClassComponent$1(component) { + return class extends Svelte4Component { + /** @param {any} options */ + constructor(options2) { + super({ + component, + ...options2 + }); + } + }; +} +class Svelte4Component { + /** @type {any} */ + #events; + /** @type {Record} */ + #instance; + /** + * @param {ComponentConstructorOptions & { + * component: any; + * }} options + */ + constructor(options2) { + var sources = /* @__PURE__ */ new Map(); + var add_source = (key, value) => { + var s = /* @__PURE__ */ mutable_source(value, false, false); + sources.set(key, s); + return s; + }; + const props = new Proxy( + { ...options2.props || {}, $$events: {} }, + { + get(target, prop) { + return get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); + }, + has(target, prop) { + if (prop === LEGACY_PROPS) return true; + get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); + return Reflect.has(target, prop); + }, + set(target, prop, value) { + set(sources.get(prop) ?? add_source(prop, value), value); + return Reflect.set(target, prop, value); + } + } + ); + this.#instance = (options2.hydrate ? hydrate : mount)(options2.component, { + target: options2.target, + anchor: options2.anchor, + props, + context: options2.context, + intro: options2.intro ?? false, + recover: options2.recover + }); + if (!options2?.props?.$$host || options2.sync === false) { + flushSync(); + } + this.#events = props.$$events; + for (const key of Object.keys(this.#instance)) { + if (key === "$set" || key === "$destroy" || key === "$on") continue; + define_property(this, key, { + get() { + return this.#instance[key]; + }, + /** @param {any} value */ + set(value) { + this.#instance[key] = value; + }, + enumerable: true + }); + } + this.#instance.$set = /** @param {Record} next */ + (next2) => { + Object.assign(props, next2); + }; + this.#instance.$destroy = () => { + unmount(this.#instance); + }; + } + /** @param {Record} props */ + $set(props) { + this.#instance.$set(props); + } + /** + * @param {string} event + * @param {(...args: any[]) => any} callback + * @returns {any} + */ + $on(event, callback) { + this.#events[event] = this.#events[event] || []; + const cb = (...args) => callback.call(this, ...args); + this.#events[event].push(cb); + return () => { + this.#events[event] = this.#events[event].filter( + /** @param {any} fn */ + (fn) => fn !== cb + ); + }; + } + $destroy() { + this.#instance.$destroy(); + } +} +let read_implementation = null; +function set_read_implementation(fn) { + read_implementation = fn; +} +function set_manifest(_) { +} +function asClassComponent(component) { + const component_constructor = asClassComponent$1(component); + const _render = (props, { context, csp } = {}) => { + const result = render(component, { props, context, csp }); + const munged = Object.defineProperties( + /** @type {LegacyRenderResult & PromiseLike} */ + {}, + { + css: { + value: { code: "", map: null } + }, + head: { + get: () => result.head + }, + html: { + get: () => result.body + }, + then: { + /** + * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. + * + * @template TResult1 + * @template [TResult2=never] + * @param { (value: LegacyRenderResult) => TResult1 } onfulfilled + * @param { (reason: unknown) => TResult2 } onrejected + */ + value: (onfulfilled, onrejected) => { + { + const user_result = onfulfilled({ + css: munged.css, + head: munged.head, + html: munged.html + }); + return Promise.resolve(user_result); + } + } + } + } + ); + return munged; + }; + component_constructor.render = _render; + return component_constructor; +} +function Root($$renderer, $$props) { + $$renderer.component(($$renderer2) => { + let { + stores, + page, + constructors, + components = [], + form, + data_0 = null, + data_1 = null + } = $$props; + { + setContext("__svelte__", stores); + } + { + stores.page.set(page); + } + const Pyramid_1 = constructors[1]; + if (constructors[1]) { + $$renderer2.push(""); + const Pyramid_0 = constructors[0]; + $$renderer2.push(""); + Pyramid_0?.($$renderer2, { + data: data_0, + form, + params: page.params, + children: ($$renderer3) => { + $$renderer3.push(""); + Pyramid_1?.($$renderer3, { data: data_1, form, params: page.params }); + $$renderer3.push(``); + }, + $$slots: { default: true } + }); + $$renderer2.push(``); + } else { + $$renderer2.push(""); + const Pyramid_0 = constructors[0]; + $$renderer2.push(""); + Pyramid_0?.($$renderer2, { data: data_0, form, params: page.params }); + $$renderer2.push(``); + } + $$renderer2.push(` `); + { + $$renderer2.push(""); + } + $$renderer2.push(``); + }); +} +const root = asClassComponent(Root); +const options = { + app_template_contains_nonce: false, + async: false, + csp: { "mode": "auto", "directives": { "upgrade-insecure-requests": false, "block-all-mixed-content": false }, "reportOnly": { "upgrade-insecure-requests": false, "block-all-mixed-content": false } }, + csrf_check_origin: true, + csrf_trusted_origins: [], + embedded: false, + env_public_prefix: "PUBLIC_", + env_private_prefix: "", + hash_routing: false, + hooks: null, + // added lazily, via `get_hooks` + preload_strategy: "modulepreload", + root, + service_worker: false, + service_worker_options: void 0, + templates: { + app: ({ head, body, assets, nonce, env }) => '\n\n \n \n \n ' + head + '\n \n \n
' + body + "
\n \n\n", + error: ({ status, message }) => '\n\n \n \n ' + message + ` + + + + +
+ ` + status + '\n
\n

' + message + "

\n
\n
\n \n\n" + }, + version_hash: "zurjbz" +}; +async function get_hooks() { + let handle; + let handleFetch; + let handleError; + let handleValidationError; + let init; + let reroute; + let transport; + return { + handle, + handleFetch, + handleError, + handleValidationError, + init, + reroute, + transport + }; +} +export { + set_public_env as a, + set_read_implementation as b, + set_manifest as c, + get_hooks as g, + options as o, + public_env as p, + read_implementation as r, + set_private_env as s +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js new file mode 100644 index 0000000..73ff856 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js @@ -0,0 +1,1188 @@ +import { json, text } from "@sveltejs/kit"; +import { SvelteKitError, HttpError } from "@sveltejs/kit/internal"; +import { with_request_store } from "@sveltejs/kit/internal/server"; +import { t as text_decoder, b as base64_encode, c as base64_decode } from "./utils.js"; +import { D as DevalueError, i as is_primitive, g as get_type, a as is_plain_object, e as enumerable_symbols, s as stringify_key, b as stringify_string } from "./utils2.js"; +const SVELTE_KIT_ASSETS = "/_svelte_kit_assets"; +const ENDPOINT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; +const PAGE_METHODS = ["GET", "POST", "HEAD"]; +function encode64(arraybuffer) { + const dv = new DataView(arraybuffer); + let binaryString = ""; + for (let i = 0; i < arraybuffer.byteLength; i++) { + binaryString += String.fromCharCode(dv.getUint8(i)); + } + return binaryToAscii(binaryString); +} +function decode64(string) { + const binaryString = asciiToBinary(string); + const arraybuffer = new ArrayBuffer(binaryString.length); + const dv = new DataView(arraybuffer); + for (let i = 0; i < arraybuffer.byteLength; i++) { + dv.setUint8(i, binaryString.charCodeAt(i)); + } + return arraybuffer; +} +const KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +function asciiToBinary(data) { + if (data.length % 4 === 0) { + data = data.replace(/==?$/, ""); + } + let output = ""; + let buffer = 0; + let accumulatedBits = 0; + for (let i = 0; i < data.length; i++) { + buffer <<= 6; + buffer |= KEY_STRING.indexOf(data[i]); + accumulatedBits += 6; + if (accumulatedBits === 24) { + output += String.fromCharCode((buffer & 16711680) >> 16); + output += String.fromCharCode((buffer & 65280) >> 8); + output += String.fromCharCode(buffer & 255); + buffer = accumulatedBits = 0; + } + } + if (accumulatedBits === 12) { + buffer >>= 4; + output += String.fromCharCode(buffer); + } else if (accumulatedBits === 18) { + buffer >>= 2; + output += String.fromCharCode((buffer & 65280) >> 8); + output += String.fromCharCode(buffer & 255); + } + return output; +} +function binaryToAscii(str) { + let out = ""; + for (let i = 0; i < str.length; i += 3) { + const groupsOfSix = [void 0, void 0, void 0, void 0]; + groupsOfSix[0] = str.charCodeAt(i) >> 2; + groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4; + if (str.length > i + 1) { + groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4; + groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2; + } + if (str.length > i + 2) { + groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6; + groupsOfSix[3] = str.charCodeAt(i + 2) & 63; + } + for (let j = 0; j < groupsOfSix.length; j++) { + if (typeof groupsOfSix[j] === "undefined") { + out += "="; + } else { + out += KEY_STRING[groupsOfSix[j]]; + } + } + } + return out; +} +const UNDEFINED = -1; +const HOLE = -2; +const NAN = -3; +const POSITIVE_INFINITY = -4; +const NEGATIVE_INFINITY = -5; +const NEGATIVE_ZERO = -6; +function parse(serialized, revivers) { + return unflatten(JSON.parse(serialized), revivers); +} +function unflatten(parsed, revivers) { + if (typeof parsed === "number") return hydrate(parsed, true); + if (!Array.isArray(parsed) || parsed.length === 0) { + throw new Error("Invalid input"); + } + const values = ( + /** @type {any[]} */ + parsed + ); + const hydrated = Array(values.length); + let hydrating = null; + function hydrate(index, standalone = false) { + if (index === UNDEFINED) return void 0; + if (index === NAN) return NaN; + if (index === POSITIVE_INFINITY) return Infinity; + if (index === NEGATIVE_INFINITY) return -Infinity; + if (index === NEGATIVE_ZERO) return -0; + if (standalone || typeof index !== "number") { + throw new Error(`Invalid input`); + } + if (index in hydrated) return hydrated[index]; + const value = values[index]; + if (!value || typeof value !== "object") { + hydrated[index] = value; + } else if (Array.isArray(value)) { + if (typeof value[0] === "string") { + const type = value[0]; + const reviver = revivers && Object.hasOwn(revivers, type) ? revivers[type] : void 0; + if (reviver) { + let i = value[1]; + if (typeof i !== "number") { + i = values.push(value[1]) - 1; + } + hydrating ??= /* @__PURE__ */ new Set(); + if (hydrating.has(i)) { + throw new Error("Invalid circular reference"); + } + hydrating.add(i); + hydrated[index] = reviver(hydrate(i)); + hydrating.delete(i); + return hydrated[index]; + } + switch (type) { + case "Date": + hydrated[index] = new Date(value[1]); + break; + case "Set": + const set = /* @__PURE__ */ new Set(); + hydrated[index] = set; + for (let i = 1; i < value.length; i += 1) { + set.add(hydrate(value[i])); + } + break; + case "Map": + const map = /* @__PURE__ */ new Map(); + hydrated[index] = map; + for (let i = 1; i < value.length; i += 2) { + map.set(hydrate(value[i]), hydrate(value[i + 1])); + } + break; + case "RegExp": + hydrated[index] = new RegExp(value[1], value[2]); + break; + case "Object": + hydrated[index] = Object(value[1]); + break; + case "BigInt": + hydrated[index] = BigInt(value[1]); + break; + case "null": + const obj = /* @__PURE__ */ Object.create(null); + hydrated[index] = obj; + for (let i = 1; i < value.length; i += 2) { + obj[value[i]] = hydrate(value[i + 1]); + } + break; + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "BigInt64Array": + case "BigUint64Array": { + if (values[value[1]][0] !== "ArrayBuffer") { + throw new Error("Invalid data"); + } + const TypedArrayConstructor = globalThis[type]; + const buffer = hydrate(value[1]); + const typedArray = new TypedArrayConstructor(buffer); + hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray; + break; + } + case "ArrayBuffer": { + const base64 = value[1]; + if (typeof base64 !== "string") { + throw new Error("Invalid ArrayBuffer encoding"); + } + const arraybuffer = decode64(base64); + hydrated[index] = arraybuffer; + break; + } + case "Temporal.Duration": + case "Temporal.Instant": + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.PlainMonthDay": + case "Temporal.PlainYearMonth": + case "Temporal.ZonedDateTime": { + const temporalName = type.slice(9); + hydrated[index] = Temporal[temporalName].from(value[1]); + break; + } + case "URL": { + const url = new URL(value[1]); + hydrated[index] = url; + break; + } + case "URLSearchParams": { + const url = new URLSearchParams(value[1]); + hydrated[index] = url; + break; + } + default: + throw new Error(`Unknown type ${type}`); + } + } else { + const array = new Array(value.length); + hydrated[index] = array; + for (let i = 0; i < value.length; i += 1) { + const n = value[i]; + if (n === HOLE) continue; + array[i] = hydrate(n); + } + } + } else { + const object = {}; + hydrated[index] = object; + for (const key in value) { + if (key === "__proto__") { + throw new Error("Cannot parse an object with a `__proto__` property"); + } + const n = value[key]; + object[key] = hydrate(n); + } + } + return hydrated[index]; + } + return hydrate(0); +} +function stringify$1(value, reducers) { + const stringified = []; + const indexes = /* @__PURE__ */ new Map(); + const custom = []; + if (reducers) { + for (const key of Object.getOwnPropertyNames(reducers)) { + custom.push({ key, fn: reducers[key] }); + } + } + const keys = []; + let p = 0; + function flatten(thing) { + if (thing === void 0) return UNDEFINED; + if (Number.isNaN(thing)) return NAN; + if (thing === Infinity) return POSITIVE_INFINITY; + if (thing === -Infinity) return NEGATIVE_INFINITY; + if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO; + if (indexes.has(thing)) return indexes.get(thing); + const index2 = p++; + indexes.set(thing, index2); + for (const { key, fn } of custom) { + const value2 = fn(thing); + if (value2) { + stringified[index2] = `["${key}",${flatten(value2)}]`; + return index2; + } + } + if (typeof thing === "function") { + throw new DevalueError(`Cannot stringify a function`, keys, thing, value); + } + let str = ""; + if (is_primitive(thing)) { + str = stringify_primitive(thing); + } else { + const type = get_type(thing); + switch (type) { + case "Number": + case "String": + case "Boolean": + str = `["Object",${stringify_primitive(thing)}]`; + break; + case "BigInt": + str = `["BigInt",${thing}]`; + break; + case "Date": + const valid = !isNaN(thing.getDate()); + str = `["Date","${valid ? thing.toISOString() : ""}"]`; + break; + case "URL": + str = `["URL",${stringify_string(thing.toString())}]`; + break; + case "URLSearchParams": + str = `["URLSearchParams",${stringify_string(thing.toString())}]`; + break; + case "RegExp": + const { source, flags } = thing; + str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; + break; + case "Array": + str = "["; + for (let i = 0; i < thing.length; i += 1) { + if (i > 0) str += ","; + if (i in thing) { + keys.push(`[${i}]`); + str += flatten(thing[i]); + keys.pop(); + } else { + str += HOLE; + } + } + str += "]"; + break; + case "Set": + str = '["Set"'; + for (const value2 of thing) { + str += `,${flatten(value2)}`; + } + str += "]"; + break; + case "Map": + str = '["Map"'; + for (const [key, value2] of thing) { + keys.push( + `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` + ); + str += `,${flatten(key)},${flatten(value2)}`; + keys.pop(); + } + str += "]"; + break; + case "Int8Array": + case "Uint8Array": + case "Uint8ClampedArray": + case "Int16Array": + case "Uint16Array": + case "Int32Array": + case "Uint32Array": + case "Float32Array": + case "Float64Array": + case "BigInt64Array": + case "BigUint64Array": { + const typedArray = thing; + str = '["' + type + '",' + flatten(typedArray.buffer); + const a = thing.byteOffset; + const b = a + thing.byteLength; + if (a > 0 || b !== typedArray.buffer.byteLength) { + const m = +/(\d+)/.exec(type)[1] / 8; + str += `,${a / m},${b / m}`; + } + str += "]"; + break; + } + case "ArrayBuffer": { + const arraybuffer = thing; + const base64 = encode64(arraybuffer); + str = `["ArrayBuffer","${base64}"]`; + break; + } + case "Temporal.Duration": + case "Temporal.Instant": + case "Temporal.PlainDate": + case "Temporal.PlainTime": + case "Temporal.PlainDateTime": + case "Temporal.PlainMonthDay": + case "Temporal.PlainYearMonth": + case "Temporal.ZonedDateTime": + str = `["${type}",${stringify_string(thing.toString())}]`; + break; + default: + if (!is_plain_object(thing)) { + throw new DevalueError( + `Cannot stringify arbitrary non-POJOs`, + keys, + thing, + value + ); + } + if (enumerable_symbols(thing).length > 0) { + throw new DevalueError( + `Cannot stringify POJOs with symbolic keys`, + keys, + thing, + value + ); + } + if (Object.getPrototypeOf(thing) === null) { + str = '["null"'; + for (const key in thing) { + keys.push(stringify_key(key)); + str += `,${stringify_string(key)},${flatten(thing[key])}`; + keys.pop(); + } + str += "]"; + } else { + str = "{"; + let started = false; + for (const key in thing) { + if (started) str += ","; + started = true; + keys.push(stringify_key(key)); + str += `${stringify_string(key)}:${flatten(thing[key])}`; + keys.pop(); + } + str += "}"; + } + } + } + stringified[index2] = str; + return index2; + } + const index = flatten(value); + if (index < 0) return `${index}`; + return `[${stringified.join(",")}]`; +} +function stringify_primitive(thing) { + const type = typeof thing; + if (type === "string") return stringify_string(thing); + if (thing instanceof String) return stringify_string(thing.toString()); + if (thing === void 0) return UNDEFINED.toString(); + if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString(); + if (type === "bigint") return `["BigInt","${thing}"]`; + return String(thing); +} +function set_nested_value(object, path_string, value) { + if (path_string.startsWith("n:")) { + path_string = path_string.slice(2); + value = value === "" ? void 0 : parseFloat(value); + } else if (path_string.startsWith("b:")) { + path_string = path_string.slice(2); + value = value === "on"; + } + deep_set(object, split_path(path_string), value); +} +function convert_formdata(data) { + const result = {}; + for (let key of data.keys()) { + const is_array = key.endsWith("[]"); + let values = data.getAll(key); + if (is_array) key = key.slice(0, -2); + if (values.length > 1 && !is_array) { + throw new Error(`Form cannot contain duplicated keys — "${key}" has ${values.length} values`); + } + values = values.filter( + (entry) => typeof entry === "string" || entry.name !== "" || entry.size > 0 + ); + if (key.startsWith("n:")) { + key = key.slice(2); + values = values.map((v) => v === "" ? void 0 : parseFloat( + /** @type {string} */ + v + )); + } else if (key.startsWith("b:")) { + key = key.slice(2); + values = values.map((v) => v === "on"); + } + set_nested_value(result, key, is_array ? values : values[0]); + } + return result; +} +const BINARY_FORM_CONTENT_TYPE = "application/x-sveltekit-formdata"; +const BINARY_FORM_VERSION = 0; +const HEADER_BYTES = 1 + 4 + 2; +async function deserialize_binary_form(request) { + if (request.headers.get("content-type") !== BINARY_FORM_CONTENT_TYPE) { + const form_data = await request.formData(); + return { data: convert_formdata(form_data), meta: {}, form_data }; + } + if (!request.body) { + throw deserialize_error("no body"); + } + const content_length = parseInt(request.headers.get("content-length") ?? ""); + if (Number.isNaN(content_length)) { + throw deserialize_error("invalid Content-Length header"); + } + const reader = request.body.getReader(); + const chunks = []; + function get_chunk(index) { + if (index in chunks) return chunks[index]; + let i = chunks.length; + while (i <= index) { + chunks[i] = reader.read().then((chunk) => chunk.value); + i++; + } + return chunks[index]; + } + async function get_buffer(offset, length) { + let start_chunk; + let chunk_start = 0; + let chunk_index; + for (chunk_index = 0; ; chunk_index++) { + const chunk = await get_chunk(chunk_index); + if (!chunk) return null; + const chunk_end = chunk_start + chunk.byteLength; + if (offset >= chunk_start && offset < chunk_end) { + start_chunk = chunk; + break; + } + chunk_start = chunk_end; + } + if (offset + length <= chunk_start + start_chunk.byteLength) { + return start_chunk.subarray(offset - chunk_start, offset + length - chunk_start); + } + const chunks2 = [start_chunk.subarray(offset - chunk_start)]; + let cursor = start_chunk.byteLength - offset + chunk_start; + while (cursor < length) { + chunk_index++; + let chunk = await get_chunk(chunk_index); + if (!chunk) return null; + if (chunk.byteLength > length - cursor) { + chunk = chunk.subarray(0, length - cursor); + } + chunks2.push(chunk); + cursor += chunk.byteLength; + } + const buffer = new Uint8Array(length); + cursor = 0; + for (const chunk of chunks2) { + buffer.set(chunk, cursor); + cursor += chunk.byteLength; + } + return buffer; + } + const header = await get_buffer(0, HEADER_BYTES); + if (!header) throw deserialize_error("too short"); + if (header[0] !== BINARY_FORM_VERSION) { + throw deserialize_error(`got version ${header[0]}, expected version ${BINARY_FORM_VERSION}`); + } + const header_view = new DataView(header.buffer, header.byteOffset, header.byteLength); + const data_length = header_view.getUint32(1, true); + if (HEADER_BYTES + data_length > content_length) { + throw deserialize_error("data overflow"); + } + const file_offsets_length = header_view.getUint16(5, true); + if (HEADER_BYTES + data_length + file_offsets_length > content_length) { + throw deserialize_error("file offset table overflow"); + } + const data_buffer = await get_buffer(HEADER_BYTES, data_length); + if (!data_buffer) throw deserialize_error("data too short"); + let file_offsets; + let files_start_offset; + if (file_offsets_length > 0) { + const file_offsets_buffer = await get_buffer(HEADER_BYTES + data_length, file_offsets_length); + if (!file_offsets_buffer) throw deserialize_error("file offset table too short"); + file_offsets = /** @type {Array} */ + JSON.parse(text_decoder.decode(file_offsets_buffer)); + files_start_offset = HEADER_BYTES + data_length + file_offsets_length; + } + const [data, meta] = parse(text_decoder.decode(data_buffer), { + File: ([name, type, size, last_modified, index]) => { + if (files_start_offset + file_offsets[index] + size > content_length) { + throw deserialize_error("file data overflow"); + } + return new Proxy( + new LazyFile( + name, + type, + size, + last_modified, + get_chunk, + files_start_offset + file_offsets[index] + ), + { + getPrototypeOf() { + return File.prototype; + } + } + ); + } + }); + void (async () => { + let has_more = true; + while (has_more) { + const chunk = await get_chunk(chunks.length); + has_more = !!chunk; + } + })(); + return { data, meta, form_data: null }; +} +function deserialize_error(message) { + return new SvelteKitError(400, "Bad Request", `Could not deserialize binary form: ${message}`); +} +class LazyFile { + /** @type {(index: number) => Promise | undefined>} */ + #get_chunk; + /** @type {number} */ + #offset; + /** + * @param {string} name + * @param {string} type + * @param {number} size + * @param {number} last_modified + * @param {(index: number) => Promise | undefined>} get_chunk + * @param {number} offset + */ + constructor(name, type, size, last_modified, get_chunk, offset) { + this.name = name; + this.type = type; + this.size = size; + this.lastModified = last_modified; + this.webkitRelativePath = ""; + this.#get_chunk = get_chunk; + this.#offset = offset; + this.arrayBuffer = this.arrayBuffer.bind(this); + this.bytes = this.bytes.bind(this); + this.slice = this.slice.bind(this); + this.stream = this.stream.bind(this); + this.text = this.text.bind(this); + } + /** @type {ArrayBuffer | undefined} */ + #buffer; + async arrayBuffer() { + this.#buffer ??= await new Response(this.stream()).arrayBuffer(); + return this.#buffer; + } + async bytes() { + return new Uint8Array(await this.arrayBuffer()); + } + /** + * @param {number=} start + * @param {number=} end + * @param {string=} contentType + */ + slice(start = 0, end = this.size, contentType = this.type) { + if (start < 0) { + start = Math.max(this.size + start, 0); + } else { + start = Math.min(start, this.size); + } + if (end < 0) { + end = Math.max(this.size + end, 0); + } else { + end = Math.min(end, this.size); + } + const size = Math.max(end - start, 0); + const file = new LazyFile( + this.name, + contentType, + size, + this.lastModified, + this.#get_chunk, + this.#offset + start + ); + return file; + } + stream() { + let cursor = 0; + let chunk_index = 0; + return new ReadableStream({ + start: async (controller) => { + let chunk_start = 0; + let start_chunk = null; + for (chunk_index = 0; ; chunk_index++) { + const chunk = await this.#get_chunk(chunk_index); + if (!chunk) return null; + const chunk_end = chunk_start + chunk.byteLength; + if (this.#offset >= chunk_start && this.#offset < chunk_end) { + start_chunk = chunk; + break; + } + chunk_start = chunk_end; + } + if (this.#offset + this.size <= chunk_start + start_chunk.byteLength) { + controller.enqueue( + start_chunk.subarray(this.#offset - chunk_start, this.#offset + this.size - chunk_start) + ); + controller.close(); + } else { + controller.enqueue(start_chunk.subarray(this.#offset - chunk_start)); + cursor = start_chunk.byteLength - this.#offset + chunk_start; + } + }, + pull: async (controller) => { + chunk_index++; + let chunk = await this.#get_chunk(chunk_index); + if (!chunk) { + controller.error("incomplete file data"); + controller.close(); + return; + } + if (chunk.byteLength > this.size - cursor) { + chunk = chunk.subarray(0, this.size - cursor); + } + controller.enqueue(chunk); + cursor += chunk.byteLength; + if (cursor >= this.size) { + controller.close(); + } + } + }); + } + async text() { + return text_decoder.decode(await this.arrayBuffer()); + } +} +const path_regex = /^[a-zA-Z_$]\w*(\.[a-zA-Z_$]\w*|\[\d+\])*$/; +function split_path(path) { + if (!path_regex.test(path)) { + throw new Error(`Invalid path ${path}`); + } + return path.split(/\.|\[|\]/).filter(Boolean); +} +function check_prototype_pollution(key) { + if (key === "__proto__" || key === "constructor" || key === "prototype") { + throw new Error( + `Invalid key "${key}"` + ); + } +} +function deep_set(object, keys, value) { + let current = object; + for (let i = 0; i < keys.length - 1; i += 1) { + const key = keys[i]; + check_prototype_pollution(key); + const is_array = /^\d+$/.test(keys[i + 1]); + const exists = Object.hasOwn(current, key); + const inner = current[key]; + if (exists && is_array !== Array.isArray(inner)) { + throw new Error(`Invalid array key ${keys[i + 1]}`); + } + if (!exists) { + current[key] = is_array ? [] : {}; + } + current = current[key]; + } + const final_key = keys[keys.length - 1]; + check_prototype_pollution(final_key); + current[final_key] = value; +} +function normalize_issue(issue, server = false) { + const normalized = { name: "", path: [], message: issue.message, server }; + if (issue.path !== void 0) { + let name = ""; + for (const segment of issue.path) { + const key = ( + /** @type {string | number} */ + typeof segment === "object" ? segment.key : segment + ); + normalized.path.push(key); + if (typeof key === "number") { + name += `[${key}]`; + } else if (typeof key === "string") { + name += name === "" ? key : "." + key; + } + } + normalized.name = name; + } + return normalized; +} +function flatten_issues(issues) { + const result = {}; + for (const issue of issues) { + (result.$ ??= []).push(issue); + let name = ""; + if (issue.path !== void 0) { + for (const key of issue.path) { + if (typeof key === "number") { + name += `[${key}]`; + } else if (typeof key === "string") { + name += name === "" ? key : "." + key; + } + (result[name] ??= []).push(issue); + } + } + } + return result; +} +function deep_get(object, path) { + let current = object; + for (const key of path) { + if (current == null || typeof current !== "object") { + return current; + } + current = current[key]; + } + return current; +} +function create_field_proxy(target, get_input, set_input, get_issues, path = []) { + const get_value = () => { + return deep_get(get_input(), path); + }; + return new Proxy(target, { + get(target2, prop) { + if (typeof prop === "symbol") return target2[prop]; + if (/^\d+$/.test(prop)) { + return create_field_proxy({}, get_input, set_input, get_issues, [ + ...path, + parseInt(prop, 10) + ]); + } + const key = build_path_string(path); + if (prop === "set") { + const set_func = function(newValue) { + set_input(path, newValue); + return newValue; + }; + return create_field_proxy(set_func, get_input, set_input, get_issues, [...path, prop]); + } + if (prop === "value") { + return create_field_proxy(get_value, get_input, set_input, get_issues, [...path, prop]); + } + if (prop === "issues" || prop === "allIssues") { + const issues_func = () => { + const all_issues = get_issues()[key === "" ? "$" : key]; + if (prop === "allIssues") { + return all_issues?.map((issue) => ({ + path: issue.path, + message: issue.message + })); + } + return all_issues?.filter((issue) => issue.name === key)?.map((issue) => ({ + path: issue.path, + message: issue.message + })); + }; + return create_field_proxy(issues_func, get_input, set_input, get_issues, [...path, prop]); + } + if (prop === "as") { + const as_func = (type, input_value) => { + const is_array = type === "file multiple" || type === "select multiple" || type === "checkbox" && typeof input_value === "string"; + const prefix = type === "number" || type === "range" ? "n:" : type === "checkbox" && !is_array ? "b:" : ""; + const base_props = { + name: prefix + key + (is_array ? "[]" : ""), + get "aria-invalid"() { + const issues = get_issues(); + return key in issues ? "true" : void 0; + } + }; + if (type !== "text" && type !== "select" && type !== "select multiple") { + base_props.type = type === "file multiple" ? "file" : type; + } + if (type === "submit" || type === "hidden") { + return Object.defineProperties(base_props, { + value: { value: input_value, enumerable: true } + }); + } + if (type === "select" || type === "select multiple") { + return Object.defineProperties(base_props, { + multiple: { value: is_array, enumerable: true }, + value: { + enumerable: true, + get() { + return get_value(); + } + } + }); + } + if (type === "checkbox" || type === "radio") { + return Object.defineProperties(base_props, { + value: { value: input_value ?? "on", enumerable: true }, + checked: { + enumerable: true, + get() { + const value = get_value(); + if (type === "radio") { + return value === input_value; + } + if (is_array) { + return (value ?? []).includes(input_value); + } + return value; + } + } + }); + } + if (type === "file" || type === "file multiple") { + return Object.defineProperties(base_props, { + multiple: { value: is_array, enumerable: true }, + files: { + enumerable: true, + get() { + const value = get_value(); + if (value instanceof File) { + if (typeof DataTransfer !== "undefined") { + const fileList = new DataTransfer(); + fileList.items.add(value); + return fileList.files; + } + return { 0: value, length: 1 }; + } + if (Array.isArray(value) && value.every((f) => f instanceof File)) { + if (typeof DataTransfer !== "undefined") { + const fileList = new DataTransfer(); + value.forEach((file) => fileList.items.add(file)); + return fileList.files; + } + const fileListLike = { length: value.length }; + value.forEach((file, index) => { + fileListLike[index] = file; + }); + return fileListLike; + } + return null; + } + } + }); + } + return Object.defineProperties(base_props, { + value: { + enumerable: true, + get() { + const value = get_value(); + return value != null ? String(value) : ""; + } + } + }); + }; + return create_field_proxy(as_func, get_input, set_input, get_issues, [...path, "as"]); + } + return create_field_proxy({}, get_input, set_input, get_issues, [...path, prop]); + } + }); +} +function build_path_string(path) { + let result = ""; + for (const segment of path) { + if (typeof segment === "number") { + result += `[${segment}]`; + } else { + result += result === "" ? segment : "." + segment; + } + } + return result; +} +function negotiate(accept, types) { + const parts = []; + accept.split(",").forEach((str, i) => { + const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str); + if (match) { + const [, type, subtype, q = "1"] = match; + parts.push({ type, subtype, q: +q, i }); + } + }); + parts.sort((a, b) => { + if (a.q !== b.q) { + return b.q - a.q; + } + if (a.subtype === "*" !== (b.subtype === "*")) { + return a.subtype === "*" ? 1 : -1; + } + if (a.type === "*" !== (b.type === "*")) { + return a.type === "*" ? 1 : -1; + } + return a.i - b.i; + }); + let accepted; + let min_priority = Infinity; + for (const mimetype of types) { + const [type, subtype] = mimetype.split("/"); + const priority = parts.findIndex( + (part) => (part.type === type || part.type === "*") && (part.subtype === subtype || part.subtype === "*") + ); + if (priority !== -1 && priority < min_priority) { + accepted = mimetype; + min_priority = priority; + } + } + return accepted; +} +function is_content_type(request, ...types) { + const type = request.headers.get("content-type")?.split(";", 1)[0].trim() ?? ""; + return types.includes(type.toLowerCase()); +} +function is_form_content_type(request) { + return is_content_type( + request, + "application/x-www-form-urlencoded", + "multipart/form-data", + "text/plain", + BINARY_FORM_CONTENT_TYPE + ); +} +function coalesce_to_error(err) { + return err instanceof Error || err && /** @type {any} */ + err.name && /** @type {any} */ + err.message ? ( + /** @type {Error} */ + err + ) : new Error(JSON.stringify(err)); +} +function normalize_error(error) { + return ( + /** @type {import('../exports/internal/index.js').Redirect | HttpError | SvelteKitError | Error} */ + error + ); +} +function get_status(error) { + return error instanceof HttpError || error instanceof SvelteKitError ? error.status : 500; +} +function get_message(error) { + return error instanceof SvelteKitError ? error.text : "Internal Error"; +} +const escape_html_attr_dict = { + "&": "&", + '"': """ + // Svelte also escapes < because the escape function could be called inside a `noscript` there + // https://github.com/sveltejs/svelte/security/advisories/GHSA-8266-84wp-wv5c + // However, that doesn't apply in SvelteKit +}; +const escape_html_dict = { + "&": "&", + "<": "<" +}; +const surrogates = ( + // high surrogate without paired low surrogate + "[\\ud800-\\udbff](?![\\udc00-\\udfff])|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\udc00-\\udfff]" +); +const escape_html_attr_regex = new RegExp( + `[${Object.keys(escape_html_attr_dict).join("")}]|` + surrogates, + "g" +); +const escape_html_regex = new RegExp( + `[${Object.keys(escape_html_dict).join("")}]|` + surrogates, + "g" +); +function escape_html(str, is_attr) { + const dict = is_attr ? escape_html_attr_dict : escape_html_dict; + const escaped_str = str.replace(is_attr ? escape_html_attr_regex : escape_html_regex, (match) => { + if (match.length === 2) { + return match; + } + return dict[match] ?? `&#${match.charCodeAt(0)};`; + }); + return escaped_str; +} +function method_not_allowed(mod, method) { + return text(`${method} method not allowed`, { + status: 405, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: allowed_methods(mod).join(", ") + } + }); +} +function allowed_methods(mod) { + const allowed = ENDPOINT_METHODS.filter((method) => method in mod); + if ("GET" in mod && !("HEAD" in mod)) { + allowed.push("HEAD"); + } + return allowed; +} +function get_global_name(options) { + return `__sveltekit_${options.version_hash}`; +} +function static_error_page(options, status, message) { + let page = options.templates.error({ status, message: escape_html(message) }); + return text(page, { + headers: { "content-type": "text/html; charset=utf-8" }, + status + }); +} +async function handle_fatal_error(event, state, options, error) { + error = error instanceof HttpError ? error : coalesce_to_error(error); + const status = get_status(error); + const body = await handle_error_and_jsonify(event, state, options, error); + const type = negotiate(event.request.headers.get("accept") || "text/html", [ + "application/json", + "text/html" + ]); + if (event.isDataRequest || type === "application/json") { + return json(body, { + status + }); + } + return static_error_page(options, status, body.message); +} +async function handle_error_and_jsonify(event, state, options, error) { + if (error instanceof HttpError) { + return { message: "Unknown Error", ...error.body }; + } + const status = get_status(error); + const message = get_message(error); + return await with_request_store( + { event, state }, + () => options.hooks.handleError({ error, event, status, message }) + ) ?? { message }; +} +function redirect_response(status, location) { + const response = new Response(void 0, { + status, + headers: { location } + }); + return response; +} +function clarify_devalue_error(event, error) { + if (error.path) { + return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error.message} (${error.path}). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#Universal-hooks-transport.`; + } + if (error.path === "") { + return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; + } + return error.message; +} +function serialize_uses(node) { + const uses = {}; + if (node.uses && node.uses.dependencies.size > 0) { + uses.dependencies = Array.from(node.uses.dependencies); + } + if (node.uses && node.uses.search_params.size > 0) { + uses.search_params = Array.from(node.uses.search_params); + } + if (node.uses && node.uses.params.size > 0) { + uses.params = Array.from(node.uses.params); + } + if (node.uses?.parent) uses.parent = 1; + if (node.uses?.route) uses.route = 1; + if (node.uses?.url) uses.url = 1; + return uses; +} +function has_prerendered_path(manifest, pathname) { + return manifest._.prerendered_routes.has(pathname) || pathname.at(-1) === "/" && manifest._.prerendered_routes.has(pathname.slice(0, -1)); +} +function format_server_error(status, error, event) { + const formatted_text = ` +\x1B[1;31m[${status}] ${event.request.method} ${event.url.pathname}\x1B[0m`; + if (status === 404) { + return formatted_text; + } + return `${formatted_text} +${error.stack}`; +} +function get_node_type(node_id) { + const parts = node_id?.split("/"); + const filename = parts?.at(-1); + if (!filename) return "unknown"; + const dot_parts = filename.split("."); + return dot_parts.slice(0, -1).join("."); +} +const INVALIDATED_PARAM = "x-sveltekit-invalidated"; +const TRAILING_SLASH_PARAM = "x-sveltekit-trailing-slash"; +function stringify(data, transport) { + const encoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.encode])); + return stringify$1(data, encoders); +} +function stringify_remote_arg(value, transport) { + if (value === void 0) return ""; + const json_string = stringify(value, transport); + const bytes = new TextEncoder().encode(json_string); + return base64_encode(bytes).replaceAll("=", "").replaceAll("+", "-").replaceAll("/", "_"); +} +function parse_remote_arg(string, transport) { + if (!string) return void 0; + const json_string = text_decoder.decode( + // no need to add back `=` characters, atob can handle it + base64_decode(string.replaceAll("-", "+").replaceAll("_", "/")) + ); + const decoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.decode])); + return parse(json_string, decoders); +} +function create_remote_key(id, payload) { + return id + "/" + payload; +} +export { + set_nested_value as A, + deep_set as B, + ENDPOINT_METHODS as E, + INVALIDATED_PARAM as I, + PAGE_METHODS as P, + SVELTE_KIT_ASSETS as S, + TRAILING_SLASH_PARAM as T, + normalize_error as a, + get_global_name as b, + serialize_uses as c, + clarify_devalue_error as d, + get_node_type as e, + escape_html as f, + get_status as g, + handle_error_and_jsonify as h, + is_form_content_type as i, + create_remote_key as j, + static_error_page as k, + stringify as l, + method_not_allowed as m, + negotiate as n, + deserialize_binary_form as o, + parse_remote_arg as p, + has_prerendered_path as q, + redirect_response as r, + stringify$1 as s, + handle_fatal_error as t, + format_server_error as u, + stringify_remote_arg as v, + parse as w, + flatten_issues as x, + create_field_proxy as y, + normalize_issue as z +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js new file mode 100644 index 0000000..78e5bde --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js @@ -0,0 +1,43 @@ +const text_encoder = new TextEncoder(); +const text_decoder = new TextDecoder(); +function get_relative_path(from, to) { + const from_parts = from.split(/[/\\]/); + const to_parts = to.split(/[/\\]/); + from_parts.pop(); + while (from_parts[0] === to_parts[0]) { + from_parts.shift(); + to_parts.shift(); + } + let i = from_parts.length; + while (i--) from_parts[i] = ".."; + return from_parts.concat(to_parts).join("/"); +} +function base64_encode(bytes) { + if (globalThis.Buffer) { + return globalThis.Buffer.from(bytes).toString("base64"); + } + let binary = ""; + for (let i = 0; i < bytes.length; i++) { + binary += String.fromCharCode(bytes[i]); + } + return btoa(binary); +} +function base64_decode(encoded) { + if (globalThis.Buffer) { + const buffer = globalThis.Buffer.from(encoded, "base64"); + return new Uint8Array(buffer); + } + const binary = atob(encoded); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return bytes; +} +export { + text_encoder as a, + base64_encode as b, + base64_decode as c, + get_relative_path as g, + text_decoder as t +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js new file mode 100644 index 0000000..f3f87a7 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js @@ -0,0 +1,98 @@ +const escaped = { + "<": "\\u003C", + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + " ": "\\t", + "\u2028": "\\u2028", + "\u2029": "\\u2029" +}; +class DevalueError extends Error { + /** + * @param {string} message + * @param {string[]} keys + * @param {any} [value] - The value that failed to be serialized + * @param {any} [root] - The root value being serialized + */ + constructor(message, keys, value, root) { + super(message); + this.name = "DevalueError"; + this.path = keys.join(""); + this.value = value; + this.root = root; + } +} +function is_primitive(thing) { + return Object(thing) !== thing; +} +const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames( + Object.prototype +).sort().join("\0"); +function is_plain_object(thing) { + const proto = Object.getPrototypeOf(thing); + return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; +} +function get_type(thing) { + return Object.prototype.toString.call(thing).slice(8, -1); +} +function get_escaped_char(char) { + switch (char) { + case '"': + return '\\"'; + case "<": + return "\\u003C"; + case "\\": + return "\\\\"; + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case " ": + return "\\t"; + case "\b": + return "\\b"; + case "\f": + return "\\f"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : ""; + } +} +function stringify_string(str) { + let result = ""; + let last_pos = 0; + const len = str.length; + for (let i = 0; i < len; i += 1) { + const char = str[i]; + const replacement = get_escaped_char(char); + if (replacement) { + result += str.slice(last_pos, i) + replacement; + last_pos = i + 1; + } + } + return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`; +} +function enumerable_symbols(object) { + return Object.getOwnPropertySymbols(object).filter( + (symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable + ); +} +const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; +function stringify_key(key) { + return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]"; +} +export { + DevalueError as D, + is_plain_object as a, + stringify_string as b, + escaped as c, + enumerable_symbols as e, + get_type as g, + is_primitive as i, + stringify_key as s +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js new file mode 100644 index 0000000..4a33088 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js @@ -0,0 +1,54 @@ +import { n as noop, t as getContext, k as escape_html } from "../../chunks/context.js"; +import "@sveltejs/kit/internal/server"; +import "@sveltejs/kit/internal"; +import { w as writable } from "../../chunks/exports.js"; +import "../../chunks/utils.js"; +function create_updated_store() { + const { set, subscribe } = writable(false); + { + return { + subscribe, + // eslint-disable-next-line @typescript-eslint/require-await + check: async () => false + }; + } +} +const is_legacy = noop.toString().includes("$$") || /function \w+\(\) \{\}/.test(noop.toString()); +if (is_legacy) { + ({ + data: {}, + form: null, + error: null, + params: {}, + route: { id: null }, + state: {}, + status: -1, + url: new URL("https://example.com") + }); +} +const stores = { + updated: /* @__PURE__ */ create_updated_store() +}; +({ + check: stores.updated.check +}); +function context() { + return getContext("__request__"); +} +const page$1 = { + get error() { + return context().page.error; + }, + get status() { + return context().page.status; + } +}; +const page = page$1; +function Error$1($$renderer, $$props) { + $$renderer.component(($$renderer2) => { + $$renderer2.push(`

${escape_html(page.status)}

${escape_html(page.error?.message)}

`); + }); +} +export { + Error$1 as default +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js new file mode 100644 index 0000000..6d138db --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js @@ -0,0 +1,9 @@ +import { x as slot } from "../../chunks/index.js"; +function _layout($$renderer, $$props) { + $$renderer.push(``); + slot($$renderer, $$props, "default", {}); + $$renderer.push(``); +} +export { + _layout as default +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js new file mode 100644 index 0000000..90d8585 --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js @@ -0,0 +1,6 @@ +function _page($$renderer) { + $$renderer.push(`

Welcome to SvelteKit

This is a minimal SvelteKit application.

`); +} +export { + _page as default +}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js new file mode 100644 index 0000000..149881b --- /dev/null +++ b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js @@ -0,0 +1,3982 @@ +import { B as BROWSER, a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js"; +import { json, text, error } from "@sveltejs/kit"; +import { Redirect, SvelteKitError, ActionFailure, HttpError } from "@sveltejs/kit/internal"; +import { with_request_store, merge_tracing, try_get_request_store } from "@sveltejs/kit/internal/server"; +import { E as ENDPOINT_METHODS, P as PAGE_METHODS, n as negotiate, m as method_not_allowed, h as handle_error_and_jsonify, g as get_status, i as is_form_content_type, a as normalize_error, s as stringify, b as get_global_name, c as serialize_uses, d as clarify_devalue_error, e as get_node_type, f as escape_html, S as SVELTE_KIT_ASSETS, j as create_remote_key, k as static_error_page, r as redirect_response, p as parse_remote_arg, l as stringify$1, o as deserialize_binary_form, q as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, t as handle_fatal_error, u as format_server_error } from "./chunks/shared.js"; +import { u as uneval } from "./chunks/index.js"; +import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, w as writable, r as readable, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, f as resolve, g as decode_pathname, h as validate_server_exports } from "./chunks/exports.js"; +import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js"; +import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js"; +function with_resolvers() { + let resolve2; + let reject; + const promise = new Promise((res, rej) => { + resolve2 = res; + reject = rej; + }); + return { promise, resolve: resolve2, reject }; +} +const NULL_BODY_STATUS = [101, 103, 204, 205, 304]; +const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer; +async function render_endpoint(event, event_state, mod, state) { + const method = ( + /** @type {import('types').HttpMethod} */ + event.request.method + ); + let handler = mod[method] || mod.fallback; + if (method === "HEAD" && !mod.HEAD && mod.GET) { + handler = mod.GET; + } + if (!handler) { + return method_not_allowed(mod, method); + } + const prerender = mod.prerender ?? state.prerender_default; + if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { + throw new Error("Cannot prerender endpoints that have mutative methods"); + } + if (state.prerendering && !state.prerendering.inside_reroute && !prerender) { + if (state.depth > 0) { + throw new Error(`${event.route.id} is not prerenderable`); + } else { + return new Response(void 0, { status: 204 }); + } + } + event_state.is_endpoint_request = true; + try { + const response = await with_request_store( + { event, state: event_state }, + () => handler( + /** @type {import('@sveltejs/kit').RequestEvent>} */ + event + ) + ); + if (!(response instanceof Response)) { + throw new Error( + `Invalid response from route ${event.url.pathname}: handler should return a Response object` + ); + } + if (state.prerendering && (!state.prerendering.inside_reroute || prerender)) { + const cloned = new Response(response.clone().body, { + status: response.status, + statusText: response.statusText, + headers: new Headers(response.headers) + }); + cloned.headers.set("x-sveltekit-prerender", String(prerender)); + if (state.prerendering.inside_reroute && prerender) { + cloned.headers.set( + "x-sveltekit-routeid", + encodeURI( + /** @type {string} */ + event.route.id + ) + ); + state.prerendering.dependencies.set(event.url.pathname, { response: cloned, body: null }); + } else { + return cloned; + } + } + return response; + } catch (e) { + if (e instanceof Redirect) { + return new Response(void 0, { + status: e.status, + headers: { location: e.location } + }); + } + throw e; + } +} +function is_endpoint_request(event) { + const { method, headers: headers2 } = event.request; + if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) { + return true; + } + if (method === "POST" && headers2.get("x-sveltekit-action") === "true") return false; + const accept = event.request.headers.get("accept") ?? "*/*"; + return negotiate(accept, ["*", "text/html"]) !== "text/html"; +} +function compact(arr) { + return arr.filter( + /** @returns {val is NonNullable} */ + (val) => val != null + ); +} +const DATA_SUFFIX = "/__data.json"; +const HTML_DATA_SUFFIX = ".html__data.json"; +function has_data_suffix(pathname) { + return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX); +} +function add_data_suffix(pathname) { + if (pathname.endsWith(".html")) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX); + return pathname.replace(/\/$/, "") + DATA_SUFFIX; +} +function strip_data_suffix(pathname) { + if (pathname.endsWith(HTML_DATA_SUFFIX)) { + return pathname.slice(0, -HTML_DATA_SUFFIX.length) + ".html"; + } + return pathname.slice(0, -DATA_SUFFIX.length); +} +const ROUTE_SUFFIX = "/__route.js"; +function has_resolution_suffix(pathname) { + return pathname.endsWith(ROUTE_SUFFIX); +} +function add_resolution_suffix(pathname) { + return pathname.replace(/\/$/, "") + ROUTE_SUFFIX; +} +function strip_resolution_suffix(pathname) { + return pathname.slice(0, -ROUTE_SUFFIX.length); +} +const noop_span = { + spanContext() { + return noop_span_context; + }, + setAttribute() { + return this; + }, + setAttributes() { + return this; + }, + addEvent() { + return this; + }, + setStatus() { + return this; + }, + updateName() { + return this; + }, + end() { + return this; + }, + isRecording() { + return false; + }, + recordException() { + return this; + }, + addLink() { + return this; + }, + addLinks() { + return this; + } +}; +const noop_span_context = { + traceId: "", + spanId: "", + traceFlags: 0 +}; +async function record_span({ name, attributes, fn }) { + { + return fn(noop_span); + } +} +function is_action_json_request(event) { + const accept = negotiate(event.request.headers.get("accept") ?? "*/*", [ + "application/json", + "text/html" + ]); + return accept === "application/json" && event.request.method === "POST"; +} +async function handle_action_json_request(event, event_state, options2, server) { + const actions = server?.actions; + if (!actions) { + const no_actions_error = new SvelteKitError( + 405, + "Method Not Allowed", + `POST method not allowed. No form actions exist for ${"this page"}` + ); + return action_json( + { + type: "error", + error: await handle_error_and_jsonify(event, event_state, options2, no_actions_error) + }, + { + status: no_actions_error.status, + headers: { + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: "GET" + } + } + ); + } + check_named_default_separate(actions); + try { + const data = await call_action(event, event_state, actions); + if (BROWSER) ; + if (data instanceof ActionFailure) { + return action_json({ + type: "failure", + status: data.status, + // @ts-expect-error we assign a string to what is supposed to be an object. That's ok + // because we don't use the object outside, and this way we have better code navigation + // through knowing where the related interface is used. + data: stringify_action_response( + data.data, + /** @type {string} */ + event.route.id, + options2.hooks.transport + ) + }); + } else { + return action_json({ + type: "success", + status: data ? 200 : 204, + // @ts-expect-error see comment above + data: stringify_action_response( + data, + /** @type {string} */ + event.route.id, + options2.hooks.transport + ) + }); + } + } catch (e) { + const err = normalize_error(e); + if (err instanceof Redirect) { + return action_json_redirect(err); + } + return action_json( + { + type: "error", + error: await handle_error_and_jsonify( + event, + event_state, + options2, + check_incorrect_fail_use(err) + ) + }, + { + status: get_status(err) + } + ); + } +} +function check_incorrect_fail_use(error2) { + return error2 instanceof ActionFailure ? new Error('Cannot "throw fail()". Use "return fail()"') : error2; +} +function action_json_redirect(redirect) { + return action_json({ + type: "redirect", + status: redirect.status, + location: redirect.location + }); +} +function action_json(data, init2) { + return json(data, init2); +} +function is_action_request(event) { + return event.request.method === "POST"; +} +async function handle_action_request(event, event_state, server) { + const actions = server?.actions; + if (!actions) { + event.setHeaders({ + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 + // "The server must generate an Allow header field in a 405 status code response" + allow: "GET" + }); + return { + type: "error", + error: new SvelteKitError( + 405, + "Method Not Allowed", + `POST method not allowed. No form actions exist for ${"this page"}` + ) + }; + } + check_named_default_separate(actions); + try { + const data = await call_action(event, event_state, actions); + if (BROWSER) ; + if (data instanceof ActionFailure) { + return { + type: "failure", + status: data.status, + data: data.data + }; + } else { + return { + type: "success", + status: 200, + // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission + data + }; + } + } catch (e) { + const err = normalize_error(e); + if (err instanceof Redirect) { + return { + type: "redirect", + status: err.status, + location: err.location + }; + } + return { + type: "error", + error: check_incorrect_fail_use(err) + }; + } +} +function check_named_default_separate(actions) { + if (actions.default && Object.keys(actions).length > 1) { + throw new Error( + "When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#named-actions" + ); + } +} +async function call_action(event, event_state, actions) { + const url = new URL(event.request.url); + let name = "default"; + for (const param of url.searchParams) { + if (param[0].startsWith("/")) { + name = param[0].slice(1); + if (name === "default") { + throw new Error('Cannot use reserved action name "default"'); + } + break; + } + } + const action = actions[name]; + if (!action) { + throw new SvelteKitError(404, "Not Found", `No action with name '${name}' found`); + } + if (!is_form_content_type(event.request)) { + throw new SvelteKitError( + 415, + "Unsupported Media Type", + `Form actions expect form-encoded data — received ${event.request.headers.get( + "content-type" + )}` + ); + } + return record_span({ + name: "sveltekit.form_action", + attributes: { + "http.route": event.route.id || "unknown" + }, + fn: async (current2) => { + const traced_event = merge_tracing(event, current2); + const result = await with_request_store( + { event: traced_event, state: event_state }, + () => action(traced_event) + ); + if (result instanceof ActionFailure) { + current2.setAttributes({ + "sveltekit.form_action.result.type": "failure", + "sveltekit.form_action.result.status": result.status + }); + } + return result; + } + }); +} +function validate_action_return(data) { + if (data instanceof Redirect) { + throw new Error("Cannot `return redirect(...)` — use `redirect(...)` instead"); + } + if (data instanceof HttpError) { + throw new Error("Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead"); + } +} +function uneval_action_response(data, route_id, transport) { + const replacer = (thing) => { + for (const key2 in transport) { + const encoded = transport[key2].encode(thing); + if (encoded) { + return `app.decode('${key2}', ${uneval(encoded, replacer)})`; + } + } + }; + return try_serialize(data, (value) => uneval(value, replacer), route_id); +} +function stringify_action_response(data, route_id, transport) { + const encoders = Object.fromEntries( + Object.entries(transport).map(([key2, value]) => [key2, value.encode]) + ); + return try_serialize(data, (value) => stringify(value, encoders), route_id); +} +function try_serialize(data, fn, route_id) { + try { + return fn(data); + } catch (e) { + const error2 = ( + /** @type {any} */ + e + ); + if (data instanceof Response) { + throw new Error( + `Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });` + ); + } + if ("path" in error2) { + let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`; + if (error2.path !== "") message += ` (data.${error2.path})`; + throw new Error(message); + } + throw error2; + } +} +function create_async_iterator() { + let resolved = -1; + let returned = -1; + const deferred = []; + return { + iterate: (transform = (x) => x) => { + return { + [Symbol.asyncIterator]() { + return { + next: async () => { + const next = deferred[++returned]; + if (!next) return { value: null, done: true }; + const value = await next.promise; + return { value: transform(value), done: false }; + } + }; + } + }; + }, + add: (promise) => { + deferred.push(with_resolvers()); + void promise.then((value) => { + deferred[++resolved].resolve(value); + }); + } + }; +} +function server_data_serializer(event, event_state, options2) { + let promise_id = 1; + let max_nodes = -1; + const iterator = create_async_iterator(); + const global = get_global_name(options2); + function get_replacer(index) { + return function replacer(thing) { + if (typeof thing?.then === "function") { + const id = promise_id++; + const promise = thing.then( + /** @param {any} data */ + (data) => ({ data }) + ).catch( + /** @param {any} error */ + async (error2) => ({ + error: await handle_error_and_jsonify(event, event_state, options2, error2) + }) + ).then( + /** + * @param {{data: any; error: any}} result + */ + async ({ data, error: error2 }) => { + let str; + try { + str = uneval(error2 ? [, error2] : [data], replacer); + } catch { + error2 = await handle_error_and_jsonify( + event, + event_state, + options2, + new Error(`Failed to serialize promise while rendering ${event.route.id}`) + ); + data = void 0; + str = uneval([, error2], replacer); + } + return { + index, + str: `${global}.resolve(${id}, ${str.includes("app.decode") ? `(app) => ${str}` : `() => ${str}`})` + }; + } + ); + iterator.add(promise); + return `${global}.defer(${id})`; + } else { + for (const key2 in options2.hooks.transport) { + const encoded = options2.hooks.transport[key2].encode(thing); + if (encoded) { + return `app.decode('${key2}', ${uneval(encoded, replacer)})`; + } + } + } + }; + } + const strings = ( + /** @type {string[]} */ + [] + ); + return { + set_max_nodes(i) { + max_nodes = i; + }, + add_node(i, node) { + try { + if (!node) { + strings[i] = "null"; + return; + } + const payload = { type: "data", data: node.data, uses: serialize_uses(node) }; + if (node.slash) payload.slash = node.slash; + strings[i] = uneval(payload, get_replacer(i)); + } catch (e) { + e.path = e.path.slice(1); + throw new Error(clarify_devalue_error( + event, + /** @type {any} */ + e + )); + } + }, + get_data(csp) { + const open = ``; + const close = `<\/script> +`; + return { + data: `[${compact(max_nodes > -1 ? strings.slice(0, max_nodes) : strings).join(",")}]`, + chunks: promise_id > 1 ? iterator.iterate(({ index, str }) => { + if (max_nodes > -1 && index >= max_nodes) { + return ""; + } + return open + str + close; + }) : null + }; + } + }; +} +function server_data_serializer_json(event, event_state, options2) { + let promise_id = 1; + const iterator = create_async_iterator(); + const reducers = { + ...Object.fromEntries( + Object.entries(options2.hooks.transport).map(([key2, value]) => [key2, value.encode]) + ), + /** @param {any} thing */ + Promise: (thing) => { + if (typeof thing?.then !== "function") { + return; + } + const id = promise_id++; + let key2 = "data"; + const promise = thing.catch( + /** @param {any} e */ + async (e) => { + key2 = "error"; + return handle_error_and_jsonify( + event, + event_state, + options2, + /** @type {any} */ + e + ); + } + ).then( + /** @param {any} value */ + async (value) => { + let str; + try { + str = stringify(value, reducers); + } catch { + const error2 = await handle_error_and_jsonify( + event, + event_state, + options2, + new Error(`Failed to serialize promise while rendering ${event.route.id}`) + ); + key2 = "error"; + str = stringify(error2, reducers); + } + return `{"type":"chunk","id":${id},"${key2}":${str}} +`; + } + ); + iterator.add(promise); + return id; + } + }; + const strings = ( + /** @type {string[]} */ + [] + ); + return { + add_node(i, node) { + try { + if (!node) { + strings[i] = "null"; + return; + } + if (node.type === "error" || node.type === "skip") { + strings[i] = JSON.stringify(node); + return; + } + strings[i] = `{"type":"data","data":${stringify(node.data, reducers)},"uses":${JSON.stringify( + serialize_uses(node) + )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ""}}`; + } catch (e) { + e.path = "data" + e.path; + throw new Error(clarify_devalue_error( + event, + /** @type {any} */ + e + )); + } + }, + get_data() { + return { + data: `{"type":"data","nodes":[${strings.join(",")}]} +`, + chunks: promise_id > 1 ? iterator.iterate() : null + }; + } + }; +} +async function load_server_data({ event, event_state, state, node, parent }) { + if (!node?.server) return null; + let is_tracking = true; + const uses = { + dependencies: /* @__PURE__ */ new Set(), + params: /* @__PURE__ */ new Set(), + parent: false, + route: false, + url: false, + search_params: /* @__PURE__ */ new Set() + }; + const load = node.server.load; + const slash = node.server.trailingSlash; + if (!load) { + return { type: "data", data: null, uses, slash }; + } + const url = make_trackable( + event.url, + () => { + if (is_tracking) { + uses.url = true; + } + }, + (param) => { + if (is_tracking) { + uses.search_params.add(param); + } + } + ); + if (state.prerendering) { + disable_search(url); + } + const result = await record_span({ + name: "sveltekit.load", + attributes: { + "sveltekit.load.node_id": node.server_id || "unknown", + "sveltekit.load.node_type": get_node_type(node.server_id), + "http.route": event.route.id || "unknown" + }, + fn: async (current2) => { + const traced_event = merge_tracing(event, current2); + const result2 = await with_request_store( + { event: traced_event, state: event_state }, + () => load.call(null, { + ...traced_event, + fetch: (info, init2) => { + new URL(info instanceof Request ? info.url : info, event.url); + return event.fetch(info, init2); + }, + /** @param {string[]} deps */ + depends: (...deps) => { + for (const dep of deps) { + const { href } = new URL(dep, event.url); + uses.dependencies.add(href); + } + }, + params: new Proxy(event.params, { + get: (target, key2) => { + if (is_tracking) { + uses.params.add(key2); + } + return target[ + /** @type {string} */ + key2 + ]; + } + }), + parent: async () => { + if (is_tracking) { + uses.parent = true; + } + return parent(); + }, + route: new Proxy(event.route, { + get: (target, key2) => { + if (is_tracking) { + uses.route = true; + } + return target[ + /** @type {'id'} */ + key2 + ]; + } + }), + url, + untrack(fn) { + is_tracking = false; + try { + return fn(); + } finally { + is_tracking = true; + } + } + }) + ); + return result2; + } + }); + return { + type: "data", + data: result ?? null, + uses, + slash + }; +} +async function load_data({ + event, + event_state, + fetched, + node, + parent, + server_data_promise, + state, + resolve_opts, + csr +}) { + const server_data_node = await server_data_promise; + const load = node?.universal?.load; + if (!load) { + return server_data_node?.data ?? null; + } + const result = await record_span({ + name: "sveltekit.load", + attributes: { + "sveltekit.load.node_id": node.universal_id || "unknown", + "sveltekit.load.node_type": get_node_type(node.universal_id), + "http.route": event.route.id || "unknown" + }, + fn: async (current2) => { + const traced_event = merge_tracing(event, current2); + return await with_request_store( + { event: traced_event, state: event_state }, + () => load.call(null, { + url: event.url, + params: event.params, + data: server_data_node?.data ?? null, + route: event.route, + fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts), + setHeaders: event.setHeaders, + depends: () => { + }, + parent, + untrack: (fn) => fn(), + tracing: traced_event.tracing + }) + ); + } + }); + return result ?? null; +} +function create_universal_fetch(event, state, fetched, csr, resolve_opts) { + const universal_fetch = async (input, init2) => { + const cloned_body = input instanceof Request && input.body ? input.clone().body : null; + const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers; + let response = await event.fetch(input, init2); + const url = new URL(input instanceof Request ? input.url : input, event.url); + const same_origin = url.origin === event.url.origin; + let dependency; + if (same_origin) { + if (state.prerendering) { + dependency = { response, body: null }; + state.prerendering.dependencies.set(url.pathname, dependency); + } + } else if (url.protocol === "https:" || url.protocol === "http:") { + const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors"; + if (mode === "no-cors") { + response = new Response("", { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } else { + const acao = response.headers.get("access-control-allow-origin"); + if (!acao || acao !== event.url.origin && acao !== "*") { + throw new Error( + `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource` + ); + } + } + } + let teed_body; + const proxy = new Proxy(response, { + get(response2, key2, receiver) { + async function push_fetched(body2, is_b64) { + const status_number = Number(response2.status); + if (isNaN(status_number)) { + throw new Error( + `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}` + ); + } + fetched.push({ + url: same_origin ? url.href.slice(event.url.origin.length) : url.href, + method: event.request.method, + request_body: ( + /** @type {string | ArrayBufferView | undefined} */ + input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body + ), + request_headers: cloned_headers, + response_body: body2, + response: response2, + is_b64 + }); + } + if (key2 === "body") { + if (response2.body === null) { + return null; + } + if (teed_body) { + return teed_body; + } + const [a, b] = response2.body.tee(); + void (async () => { + let result = new Uint8Array(); + for await (const chunk of a) { + const combined = new Uint8Array(result.length + chunk.length); + combined.set(result, 0); + combined.set(chunk, result.length); + result = combined; + } + if (dependency) { + dependency.body = new Uint8Array(result); + } + void push_fetched(base64_encode(result), true); + })(); + return teed_body = b; + } + if (key2 === "arrayBuffer") { + return async () => { + const buffer = await response2.arrayBuffer(); + const bytes = new Uint8Array(buffer); + if (dependency) { + dependency.body = bytes; + } + if (buffer instanceof ArrayBuffer) { + await push_fetched(base64_encode(bytes), true); + } + return buffer; + }; + } + async function text2() { + const body2 = await response2.text(); + if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) { + await push_fetched(void 0, false); + return void 0; + } + if (!body2 || typeof body2 === "string") { + await push_fetched(body2, false); + } + if (dependency) { + dependency.body = body2; + } + return body2; + } + if (key2 === "text") { + return text2; + } + if (key2 === "json") { + return async () => { + const body2 = await text2(); + return body2 ? JSON.parse(body2) : void 0; + }; + } + const value = Reflect.get(response2, key2, response2); + if (value instanceof Function) { + return Object.defineProperties( + /** + * @this {any} + */ + function() { + return Reflect.apply(value, this === receiver ? response2 : this, arguments); + }, + { + name: { value: value.name }, + length: { value: value.length } + } + ); + } + return value; + } + }); + if (csr) { + const get = response.headers.get; + response.headers.get = (key2) => { + const lower = key2.toLowerCase(); + const value = get.call(response.headers, lower); + if (value && !lower.startsWith("x-sveltekit-")) { + const included = resolve_opts.filterSerializedResponseHeaders(lower, value); + if (!included) { + throw new Error( + `Failed to get response header "${lower}" — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#Server-hooks-handle (at ${event.route.id})` + ); + } + } + return value; + }; + } + return proxy; + }; + return (input, init2) => { + const response = universal_fetch(input, init2); + response.catch(() => { + }); + return response; + }; +} +async function stream_to_string(stream) { + let result = ""; + const reader = stream.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + break; + } + result += text_decoder.decode(value); + } + return result; +} +function hash(...values) { + let hash2 = 5381; + for (const value of values) { + if (typeof value === "string") { + let i = value.length; + while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i); + } else if (ArrayBuffer.isView(value)) { + const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); + let i = buffer.length; + while (i) hash2 = hash2 * 33 ^ buffer[--i]; + } else { + throw new TypeError("value must be a string or TypedArray"); + } + } + return (hash2 >>> 0).toString(36); +} +const replacements = { + "<": "\\u003C", + "\u2028": "\\u2028", + "\u2029": "\\u2029" +}; +const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g"); +function serialize_data(fetched, filter, prerendering = false) { + const headers2 = {}; + let cache_control = null; + let age = null; + let varyAny = false; + for (const [key2, value] of fetched.response.headers) { + if (filter(key2, value)) { + headers2[key2] = value; + } + if (key2 === "cache-control") cache_control = value; + else if (key2 === "age") age = value; + else if (key2 === "vary" && value.trim() === "*") varyAny = true; + } + const payload = { + status: fetched.response.status, + statusText: fetched.response.statusText, + headers: headers2, + body: fetched.response_body + }; + const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]); + const attrs = [ + 'type="application/json"', + "data-sveltekit-fetched", + `data-url="${escape_html(fetched.url, true)}"` + ]; + if (fetched.is_b64) { + attrs.push("data-b64"); + } + if (fetched.request_headers || fetched.request_body) { + const values = []; + if (fetched.request_headers) { + values.push([...new Headers(fetched.request_headers)].join(",")); + } + if (fetched.request_body) { + values.push(fetched.request_body); + } + attrs.push(`data-hash="${hash(...values)}"`); + } + if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) { + const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control); + if (match) { + const ttl = +match[1] - +(age ?? "0"); + attrs.push(`data-ttl="${ttl}"`); + } + } + return ` + + diff --git a/tests/fixtures/sveltekit/example/src/routes/+page.svelte b/tests/fixtures/sveltekit/example/src/routes/+page.svelte new file mode 100644 index 0000000..7a2f8d2 --- /dev/null +++ b/tests/fixtures/sveltekit/example/src/routes/+page.svelte @@ -0,0 +1,36 @@ + + +
+

Welcome to SvelteKit

+

This is a minimal SvelteKit application.

+ + +
+ + diff --git a/tests/fixtures/sveltekit/example/svelte.config.js b/tests/fixtures/sveltekit/example/svelte.config.js new file mode 100644 index 0000000..301e785 --- /dev/null +++ b/tests/fixtures/sveltekit/example/svelte.config.js @@ -0,0 +1,10 @@ +import adapter from '@sveltejs/adapter-auto'; + +/** @type {import('@sveltejs/kit').Config} */ +const config = { + kit: { + adapter: adapter() + } +}; + +export default config; diff --git a/tests/fixtures/sveltekit/example/tsconfig.json b/tests/fixtures/sveltekit/example/tsconfig.json new file mode 100644 index 0000000..a8f10c8 --- /dev/null +++ b/tests/fixtures/sveltekit/example/tsconfig.json @@ -0,0 +1,14 @@ +{ + "extends": "./.svelte-kit/tsconfig.json", + "compilerOptions": { + "allowJs": true, + "checkJs": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "moduleResolution": "bundler" + } +} diff --git a/tests/fixtures/sveltekit/example/vite.config.ts b/tests/fixtures/sveltekit/example/vite.config.ts new file mode 100644 index 0000000..bbf8c7d --- /dev/null +++ b/tests/fixtures/sveltekit/example/vite.config.ts @@ -0,0 +1,6 @@ +import { sveltekit } from '@sveltejs/kit/vite'; +import { defineConfig } from 'vite'; + +export default defineConfig({ + plugins: [sveltekit()] +}); From 45560f32662e2ced0bd15168730032c5f2fafd77 Mon Sep 17 00:00:00 2001 From: Nick Nisi Date: Mon, 9 Feb 2026 15:21:17 -0600 Subject: [PATCH 05/12] chore: remove .svelte-kit build output from fixture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Build artifacts shouldn't be in the fixture — they're regenerated by `pnpm build` during eval runs. Added .gitignore to prevent. --- tests/fixtures/sveltekit/example/.gitignore | 2 + .../example/.svelte-kit/ambient.d.ts | 277 -- .../generated/client-optimized/app.js | 29 - .../generated/client-optimized/matchers.js | 1 - .../generated/client-optimized/nodes/0.js | 1 - .../generated/client-optimized/nodes/1.js | 1 - .../generated/client-optimized/nodes/2.js | 1 - .../.svelte-kit/generated/client/app.js | 29 - .../.svelte-kit/generated/client/matchers.js | 1 - .../.svelte-kit/generated/client/nodes/0.js | 1 - .../.svelte-kit/generated/client/nodes/1.js | 1 - .../.svelte-kit/generated/client/nodes/2.js | 1 - .../example/.svelte-kit/generated/root.js | 3 - .../example/.svelte-kit/generated/root.svelte | 68 - .../.svelte-kit/generated/server/internal.js | 53 - .../example/.svelte-kit/non-ambient.d.ts | 41 - .../output/client/.vite/manifest.json | 109 - .../_app/immutable/assets/2.Cwfcd7nv.css | 1 - .../client/_app/immutable/chunks/BShzwfeu.js | 1 - .../client/_app/immutable/chunks/B_PiQ68N.js | 1 - .../client/_app/immutable/chunks/C8WMVNin.js | 1 - .../client/_app/immutable/chunks/CE0Ev3WY.js | 1 - .../client/_app/immutable/chunks/Csl9sg0z.js | 1 - .../client/_app/immutable/chunks/jjmyhcpZ.js | 2 - .../_app/immutable/entry/app.CpUzidFU.js | 2 - .../_app/immutable/entry/start.T22yjXU7.js | 1 - .../client/_app/immutable/nodes/0.Cc7SJR4r.js | 1 - .../client/_app/immutable/nodes/1.DcKD0893.js | 1 - .../client/_app/immutable/nodes/2.BFij7fXI.js | 1 - .../output/client/_app/version.json | 1 - .../output/server/.vite/manifest.json | 119 - .../_app/immutable/assets/_page.Cwfcd7nv.css | 1 - .../output/server/chunks/context.js | 109 - .../output/server/chunks/environment.js | 36 - .../output/server/chunks/equality.js | 14 - .../output/server/chunks/exports.js | 231 - .../.svelte-kit/output/server/chunks/index.js | 1297 ------ .../output/server/chunks/internal.js | 2712 ----------- .../output/server/chunks/shared.js | 1188 ----- .../.svelte-kit/output/server/chunks/utils.js | 43 - .../output/server/chunks/utils2.js | 98 - .../server/entries/fallbacks/error.svelte.js | 54 - .../server/entries/pages/_layout.svelte.js | 9 - .../server/entries/pages/_page.svelte.js | 6 - .../.svelte-kit/output/server/index.js | 3982 ----------------- .../.svelte-kit/output/server/internal.js | 13 - .../output/server/manifest-full.js | 39 - .../.svelte-kit/output/server/manifest.js | 39 - .../.svelte-kit/output/server/nodes/0.js | 8 - .../.svelte-kit/output/server/nodes/1.js | 8 - .../.svelte-kit/output/server/nodes/2.js | 8 - .../.svelte-kit/output/server/remote-entry.js | 555 --- .../example/.svelte-kit/tsconfig.json | 46 - .../.svelte-kit/types/route_meta_data.json | 3 - .../.svelte-kit/types/src/routes/$types.d.ts | 24 - 55 files changed, 2 insertions(+), 11274 deletions(-) create mode 100644 tests/fixtures/sveltekit/example/.gitignore delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/C8WMVNin.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/internal.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/manifest-full.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/manifest.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/0.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/1.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/nodes/2.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/output/server/remote-entry.js delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/tsconfig.json delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/types/route_meta_data.json delete mode 100644 tests/fixtures/sveltekit/example/.svelte-kit/types/src/routes/$types.d.ts diff --git a/tests/fixtures/sveltekit/example/.gitignore b/tests/fixtures/sveltekit/example/.gitignore new file mode 100644 index 0000000..1a341bd --- /dev/null +++ b/tests/fixtures/sveltekit/example/.gitignore @@ -0,0 +1,2 @@ +.svelte-kit +node_modules diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts b/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts deleted file mode 100644 index 4320be1..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/ambient.d.ts +++ /dev/null @@ -1,277 +0,0 @@ - -// this file is generated — do not edit it - - -/// - -/** - * Environment variables [loaded by Vite](https://vitejs.dev/guide/env-and-mode.html#env-files) from `.env` files and `process.env`. Like [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), this module cannot be imported into client-side code. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured). - * - * _Unlike_ [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), the values exported from this module are statically injected into your bundle at build time, enabling optimisations like dead code elimination. - * - * ```ts - * import { API_KEY } from '$env/static/private'; - * ``` - * - * Note that all environment variables referenced in your code should be declared (for example in an `.env` file), even if they don't have a value until the app is deployed: - * - * ``` - * MY_FEATURE_FLAG="" - * ``` - * - * You can override `.env` values from the command line like so: - * - * ```sh - * MY_FEATURE_FLAG="enabled" npm run dev - * ``` - */ -declare module '$env/static/private' { - export const MANPATH: string; - export const GHOSTTY_RESOURCES_DIR: string; - export const LESS_TERMCAP_mb: string; - export const NIX_PROFILES: string; - export const NoDefaultCurrentDirectoryInExePath: string; - export const TERM_PROGRAM: string; - export const CLAUDE_CODE_ENTRYPOINT: string; - export const FNM_LOGLEVEL: string; - export const LESS_TERMCAP_md: string; - export const LESS_TERMCAP_me: string; - export const PYENV_ROOT: string; - export const SHELL: string; - export const TERM: string; - export const FNM_NODE_DIST_MIRROR: string; - export const HOMEBREW_REPOSITORY: string; - export const LESS_TERMCAP_mh: string; - export const RIPGREP_CONFIG_PATH: string; - export const TMPDIR: string; - export const TERM_PROGRAM_VERSION: string; - export const ZDOTDIR: string; - export const LESS_TERMCAP_ue: string; - export const PNPM_HOME: string; - export const ZSH: string; - export const FNM_COREPACK_ENABLED: string; - export const GIT_EDITOR: string; - export const USER: string; - export const LESS_TERMCAP_mr: string; - export const COMMAND_MODE: string; - export const OPENAI_API_KEY: string; - export const MANROFFOPT: string; - export const RPROMPT: string; - export const CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: string; - export const SSH_AUTH_SOCK: string; - export const CALENDLY_API_KEY: string; - export const CODE_DIR: string; - export const __CF_USER_TEXT_ENCODING: string; - export const FZF_DEFAULT_OPTS: string; - export const DOTFILES: string; - export const TMUX: string; - export const npm_config_verify_deps_before_run: string; - export const CACHEDIR: string; - export const FNM_VERSION_FILE_STRATEGY: string; - export const LESS_TERMCAP_us: string; - export const FNM_ARCH: string; - export const GOOGLE_API_KEY: string; - export const PATH: string; - export const GHOSTTY_SHELL_FEATURES: string; - export const LaunchInstanceID: string; - export const ZPLUGDIR: string; - export const __CFBundleIdentifier: string; - export const npm_command: string; - export const CONTEXT7_API_KEY: string; - export const PWD: string; - export const EDITOR: string; - export const PERPLEXITY_API_KEY: string; - export const OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: string; - export const LANG: string; - export const NODE_PATH: string; - export const KEYTIMEOUT: string; - export const VIM_TMP: string; - export const FNM_MULTISHELL_PATH: string; - export const TMUX_PANE: string; - export const XPC_FLAGS: string; - export const NIX_SSL_CERT_FILE: string; - export const ANTHROPIC_API_KEY: string; - export const RBENV_SHELL: string; - export const pnpm_config_verify_deps_before_run: string; - export const XPC_SERVICE_NAME: string; - export const HOME: string; - export const PYENV_SHELL: string; - export const SHLVL: string; - export const TERMINFO: string; - export const XDG_CONFIG_HOME: string; - export const CLAUDE_CODE_TASK_LIST_ID: string; - export const HOMEBREW_PREFIX: string; - export const FNM_DIR: string; - export const PROMPT: string; - export const LOGNAME: string; - export const PNPM_PACKAGE_NAME: string; - export const FZF_CTRL_T_COMMAND: string; - export const LESS_TERMCAP_so: string; - export const XDG_DATA_DIRS: string; - export const FZF_DEFAULT_COMMAND: string; - export const GHOSTTY_BIN_DIR: string; - export const COREPACK_ENABLE_AUTO_PIN: string; - export const npm_config_user_agent: string; - export const FNM_RESOLVE_ENGINES: string; - export const HOMEBREW_CELLAR: string; - export const INFOPATH: string; - export const REPORTTIME: string; - export const GITHUB_PERSONAL_ACCESS_TOKEN: string; - export const OSLogRateLimit: string; - export const GROK_API_KEY: string; - export const NIA_API_KEY: string; - export const SECURITYSESSIONID: string; - export const CLAUDECODE: string; - export const NODE_EXTRA_CA_CERTS: string; - export const COLORTERM: string; - export const LESS_TERMCAP_se: string; - export const NODE_ENV: string; -} - -/** - * Similar to [`$env/static/private`](https://svelte.dev/docs/kit/$env-static-private), except that it only includes environment variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. - * - * Values are replaced statically at build time. - * - * ```ts - * import { PUBLIC_BASE_URL } from '$env/static/public'; - * ``` - */ -declare module '$env/static/public' { - -} - -/** - * This module provides access to runtime environment variables, as defined by the platform you're running on. For example if you're using [`adapter-node`](https://github.com/sveltejs/kit/tree/main/packages/adapter-node) (or running [`vite preview`](https://svelte.dev/docs/kit/cli)), this is equivalent to `process.env`. This module only includes variables that _do not_ begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) _and do_ start with [`config.kit.env.privatePrefix`](https://svelte.dev/docs/kit/configuration#env) (if configured). - * - * This module cannot be imported into client-side code. - * - * ```ts - * import { env } from '$env/dynamic/private'; - * console.log(env.DEPLOYMENT_SPECIFIC_VARIABLE); - * ``` - * - * > [!NOTE] In `dev`, `$env/dynamic` always includes environment variables from `.env`. In `prod`, this behavior will depend on your adapter. - */ -declare module '$env/dynamic/private' { - export const env: { - MANPATH: string; - GHOSTTY_RESOURCES_DIR: string; - LESS_TERMCAP_mb: string; - NIX_PROFILES: string; - NoDefaultCurrentDirectoryInExePath: string; - TERM_PROGRAM: string; - CLAUDE_CODE_ENTRYPOINT: string; - FNM_LOGLEVEL: string; - LESS_TERMCAP_md: string; - LESS_TERMCAP_me: string; - PYENV_ROOT: string; - SHELL: string; - TERM: string; - FNM_NODE_DIST_MIRROR: string; - HOMEBREW_REPOSITORY: string; - LESS_TERMCAP_mh: string; - RIPGREP_CONFIG_PATH: string; - TMPDIR: string; - TERM_PROGRAM_VERSION: string; - ZDOTDIR: string; - LESS_TERMCAP_ue: string; - PNPM_HOME: string; - ZSH: string; - FNM_COREPACK_ENABLED: string; - GIT_EDITOR: string; - USER: string; - LESS_TERMCAP_mr: string; - COMMAND_MODE: string; - OPENAI_API_KEY: string; - MANROFFOPT: string; - RPROMPT: string; - CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS: string; - SSH_AUTH_SOCK: string; - CALENDLY_API_KEY: string; - CODE_DIR: string; - __CF_USER_TEXT_ENCODING: string; - FZF_DEFAULT_OPTS: string; - DOTFILES: string; - TMUX: string; - npm_config_verify_deps_before_run: string; - CACHEDIR: string; - FNM_VERSION_FILE_STRATEGY: string; - LESS_TERMCAP_us: string; - FNM_ARCH: string; - GOOGLE_API_KEY: string; - PATH: string; - GHOSTTY_SHELL_FEATURES: string; - LaunchInstanceID: string; - ZPLUGDIR: string; - __CFBundleIdentifier: string; - npm_command: string; - CONTEXT7_API_KEY: string; - PWD: string; - EDITOR: string; - PERPLEXITY_API_KEY: string; - OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE: string; - LANG: string; - NODE_PATH: string; - KEYTIMEOUT: string; - VIM_TMP: string; - FNM_MULTISHELL_PATH: string; - TMUX_PANE: string; - XPC_FLAGS: string; - NIX_SSL_CERT_FILE: string; - ANTHROPIC_API_KEY: string; - RBENV_SHELL: string; - pnpm_config_verify_deps_before_run: string; - XPC_SERVICE_NAME: string; - HOME: string; - PYENV_SHELL: string; - SHLVL: string; - TERMINFO: string; - XDG_CONFIG_HOME: string; - CLAUDE_CODE_TASK_LIST_ID: string; - HOMEBREW_PREFIX: string; - FNM_DIR: string; - PROMPT: string; - LOGNAME: string; - PNPM_PACKAGE_NAME: string; - FZF_CTRL_T_COMMAND: string; - LESS_TERMCAP_so: string; - XDG_DATA_DIRS: string; - FZF_DEFAULT_COMMAND: string; - GHOSTTY_BIN_DIR: string; - COREPACK_ENABLE_AUTO_PIN: string; - npm_config_user_agent: string; - FNM_RESOLVE_ENGINES: string; - HOMEBREW_CELLAR: string; - INFOPATH: string; - REPORTTIME: string; - GITHUB_PERSONAL_ACCESS_TOKEN: string; - OSLogRateLimit: string; - GROK_API_KEY: string; - NIA_API_KEY: string; - SECURITYSESSIONID: string; - CLAUDECODE: string; - NODE_EXTRA_CA_CERTS: string; - COLORTERM: string; - LESS_TERMCAP_se: string; - NODE_ENV: string; - [key: `PUBLIC_${string}`]: undefined; - [key: `${string}`]: string | undefined; - } -} - -/** - * Similar to [`$env/dynamic/private`](https://svelte.dev/docs/kit/$env-dynamic-private), but only includes variables that begin with [`config.kit.env.publicPrefix`](https://svelte.dev/docs/kit/configuration#env) (which defaults to `PUBLIC_`), and can therefore safely be exposed to client-side code. - * - * Note that public dynamic environment variables must all be sent from the server to the client, causing larger network requests — when possible, use `$env/static/public` instead. - * - * ```ts - * import { env } from '$env/dynamic/public'; - * console.log(env.PUBLIC_DEPLOYMENT_SPECIFIC_VARIABLE); - * ``` - */ -declare module '$env/dynamic/public' { - export const env: { - [key: `PUBLIC_${string}`]: string | undefined; - } -} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js deleted file mode 100644 index c3c7b78..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/app.js +++ /dev/null @@ -1,29 +0,0 @@ -export { matchers } from './matchers.js'; - -export const nodes = [ - () => import('./nodes/0'), - () => import('./nodes/1'), - () => import('./nodes/2') -]; - -export const server_loads = []; - -export const dictionary = { - "/": [2] - }; - -export const hooks = { - handleError: (({ error }) => { console.error(error) }), - - reroute: (() => {}), - transport: {} -}; - -export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode])); -export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode])); - -export const hash = false; - -export const decode = (type, value) => decoders[type](value); - -export { default as root } from '../root.js'; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js deleted file mode 100644 index f6bd30a..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/matchers.js +++ /dev/null @@ -1 +0,0 @@ -export const matchers = {}; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js deleted file mode 100644 index fed1375..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/0.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../src/routes/+layout.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js deleted file mode 100644 index 4f4b013..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/1.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js deleted file mode 100644 index 1cb4f85..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client-optimized/nodes/2.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../src/routes/+page.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js deleted file mode 100644 index c3c7b78..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/app.js +++ /dev/null @@ -1,29 +0,0 @@ -export { matchers } from './matchers.js'; - -export const nodes = [ - () => import('./nodes/0'), - () => import('./nodes/1'), - () => import('./nodes/2') -]; - -export const server_loads = []; - -export const dictionary = { - "/": [2] - }; - -export const hooks = { - handleError: (({ error }) => { console.error(error) }), - - reroute: (() => {}), - transport: {} -}; - -export const decoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.decode])); -export const encoders = Object.fromEntries(Object.entries(hooks.transport).map(([k, v]) => [k, v.encode])); - -export const hash = false; - -export const decode = (type, value) => decoders[type](value); - -export { default as root } from '../root.js'; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js deleted file mode 100644 index f6bd30a..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/matchers.js +++ /dev/null @@ -1 +0,0 @@ -export const matchers = {}; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js deleted file mode 100644 index fed1375..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/0.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../src/routes/+layout.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js deleted file mode 100644 index 4f4b013..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/1.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js deleted file mode 100644 index 1cb4f85..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/client/nodes/2.js +++ /dev/null @@ -1 +0,0 @@ -export { default as component } from "../../../../src/routes/+page.svelte"; \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js deleted file mode 100644 index 4d1e892..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.js +++ /dev/null @@ -1,3 +0,0 @@ -import { asClassComponent } from 'svelte/legacy'; -import Root from './root.svelte'; -export default asClassComponent(Root); \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte b/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte deleted file mode 100644 index 0795183..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/root.svelte +++ /dev/null @@ -1,68 +0,0 @@ - - - - -{#if constructors[1]} - {@const Pyramid_0 = constructors[0]} - - - - - - -{:else} - {@const Pyramid_0 = constructors[0]} - - - -{/if} - -{#if mounted} -
- {#if navigated} - {title} - {/if} -
-{/if} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js b/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js deleted file mode 100644 index 009267f..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/generated/server/internal.js +++ /dev/null @@ -1,53 +0,0 @@ - -import root from '../root.js'; -import { set_building, set_prerendering } from '__sveltekit/environment'; -import { set_assets } from '$app/paths/internal/server'; -import { set_manifest, set_read_implementation } from '__sveltekit/server'; -import { set_private_env, set_public_env } from '../../../node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/shared-server.js'; - -export const options = { - app_template_contains_nonce: false, - async: false, - csp: {"mode":"auto","directives":{"upgrade-insecure-requests":false,"block-all-mixed-content":false},"reportOnly":{"upgrade-insecure-requests":false,"block-all-mixed-content":false}}, - csrf_check_origin: true, - csrf_trusted_origins: [], - embedded: false, - env_public_prefix: 'PUBLIC_', - env_private_prefix: '', - hash_routing: false, - hooks: null, // added lazily, via `get_hooks` - preload_strategy: "modulepreload", - root, - service_worker: false, - service_worker_options: undefined, - templates: { - app: ({ head, body, assets, nonce, env }) => "\n\n\t\n\t\t\n\t\t\n\t\t" + head + "\n\t\n\t\n\t\t
" + body + "
\n\t\n\n", - error: ({ status, message }) => "\n\n\t\n\t\t\n\t\t" + message + "\n\n\t\t\n\t\n\t\n\t\t
\n\t\t\t" + status + "\n\t\t\t
\n\t\t\t\t

" + message + "

\n\t\t\t
\n\t\t
\n\t\n\n" - }, - version_hash: "zurjbz" -}; - -export async function get_hooks() { - let handle; - let handleFetch; - let handleError; - let handleValidationError; - let init; - - - let reroute; - let transport; - - - return { - handle, - handleFetch, - handleError, - handleValidationError, - init, - reroute, - transport - }; -} - -export { set_assets, set_building, set_manifest, set_prerendering, set_private_env, set_public_env, set_read_implementation }; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts b/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts deleted file mode 100644 index f2cfe55..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/non-ambient.d.ts +++ /dev/null @@ -1,41 +0,0 @@ - -// this file is generated — do not edit it - - -declare module "svelte/elements" { - export interface HTMLAttributes { - 'data-sveltekit-keepfocus'?: true | '' | 'off' | undefined | null; - 'data-sveltekit-noscroll'?: true | '' | 'off' | undefined | null; - 'data-sveltekit-preload-code'?: - | true - | '' - | 'eager' - | 'viewport' - | 'hover' - | 'tap' - | 'off' - | undefined - | null; - 'data-sveltekit-preload-data'?: true | '' | 'hover' | 'tap' | 'off' | undefined | null; - 'data-sveltekit-reload'?: true | '' | 'off' | undefined | null; - 'data-sveltekit-replacestate'?: true | '' | 'off' | undefined | null; - } -} - -export {}; - - -declare module "$app/types" { - export interface AppTypes { - RouteId(): "/"; - RouteParams(): { - - }; - LayoutParams(): { - "/": Record - }; - Pathname(): "/"; - ResolvedPathname(): `${"" | `/${string}`}${ReturnType}`; - Asset(): string & {}; - } -} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json deleted file mode 100644 index f6bef3e..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/.vite/manifest.json +++ /dev/null @@ -1,109 +0,0 @@ -{ - ".svelte-kit/generated/client-optimized/app.js": { - "file": "_app/immutable/entry/app.CpUzidFU.js", - "name": "entry/app", - "src": ".svelte-kit/generated/client-optimized/app.js", - "isEntry": true, - "imports": [ - "_B_PiQ68N.js", - "_jjmyhcpZ.js", - "_C8WMVNin.js", - "_CE0Ev3WY.js" - ], - "dynamicImports": [ - ".svelte-kit/generated/client-optimized/nodes/0.js", - ".svelte-kit/generated/client-optimized/nodes/1.js", - ".svelte-kit/generated/client-optimized/nodes/2.js" - ] - }, - ".svelte-kit/generated/client-optimized/nodes/0.js": { - "file": "_app/immutable/nodes/0.Cc7SJR4r.js", - "name": "nodes/0", - "src": ".svelte-kit/generated/client-optimized/nodes/0.js", - "isEntry": true, - "isDynamicEntry": true, - "imports": [ - "_C8WMVNin.js", - "_Csl9sg0z.js", - "_B_PiQ68N.js" - ] - }, - ".svelte-kit/generated/client-optimized/nodes/1.js": { - "file": "_app/immutable/nodes/1.DcKD0893.js", - "name": "nodes/1", - "src": ".svelte-kit/generated/client-optimized/nodes/1.js", - "isEntry": true, - "isDynamicEntry": true, - "imports": [ - "_C8WMVNin.js", - "_Csl9sg0z.js", - "_B_PiQ68N.js", - "_jjmyhcpZ.js", - "_BShzwfeu.js" - ] - }, - ".svelte-kit/generated/client-optimized/nodes/2.js": { - "file": "_app/immutable/nodes/2.BFij7fXI.js", - "name": "nodes/2", - "src": ".svelte-kit/generated/client-optimized/nodes/2.js", - "isEntry": true, - "isDynamicEntry": true, - "imports": [ - "_C8WMVNin.js", - "_Csl9sg0z.js" - ], - "css": [ - "_app/immutable/assets/2.Cwfcd7nv.css" - ] - }, - "_BShzwfeu.js": { - "file": "_app/immutable/chunks/BShzwfeu.js", - "name": "entry", - "imports": [ - "_B_PiQ68N.js", - "_CE0Ev3WY.js" - ] - }, - "_B_PiQ68N.js": { - "file": "_app/immutable/chunks/B_PiQ68N.js", - "name": "runtime" - }, - "_C8WMVNin.js": { - "file": "_app/immutable/chunks/C8WMVNin.js", - "name": "disclose-version", - "imports": [ - "_B_PiQ68N.js" - ] - }, - "_CE0Ev3WY.js": { - "file": "_app/immutable/chunks/CE0Ev3WY.js", - "name": "index-client", - "imports": [ - "_B_PiQ68N.js" - ] - }, - "_Csl9sg0z.js": { - "file": "_app/immutable/chunks/Csl9sg0z.js", - "name": "legacy", - "imports": [ - "_B_PiQ68N.js" - ] - }, - "_jjmyhcpZ.js": { - "file": "_app/immutable/chunks/jjmyhcpZ.js", - "name": "render", - "imports": [ - "_B_PiQ68N.js", - "_C8WMVNin.js" - ] - }, - "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/client/entry.js": { - "file": "_app/immutable/entry/start.T22yjXU7.js", - "name": "entry/start", - "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/client/entry.js", - "isEntry": true, - "imports": [ - "_BShzwfeu.js" - ] - } -} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css deleted file mode 100644 index bd4f0b4..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/assets/2.Cwfcd7nv.css +++ /dev/null @@ -1 +0,0 @@ -main.svelte-1uha8ag{padding:2rem;font-family:system-ui,-apple-system,sans-serif}h1.svelte-1uha8ag{color:#333}nav.svelte-1uha8ag{margin-top:2rem}a.svelte-1uha8ag{color:#06c;text-decoration:none}a.svelte-1uha8ag:hover{text-decoration:underline} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js deleted file mode 100644 index 1bbc389..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/BShzwfeu.js +++ /dev/null @@ -1 +0,0 @@ -var Qt=t=>{throw TypeError(t)};var Pe=(t,e,n)=>e.has(t)||Qt("Cannot "+n);var w=(t,e,n)=>(Pe(t,e,"read from private field"),n?n.call(t):e.get(t)),U=(t,e,n)=>e.has(t)?Qt("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n);import{aJ as Lt,aK as $e,aH as T,i as I,av as O,aG as pt,aL as Ce}from"./B_PiQ68N.js";import{o as Zt}from"./CE0Ev3WY.js";const B=[];function Nt(t,e=Lt){let n=null;const r=new Set;function a(i){if($e(t,i)&&(t=i,n)){const c=!B.length;for(const l of r)l[1](),B.push(l,t);if(c){for(let l=0;l{r.delete(l),r.size===0&&n&&(n(),n=null)}}return{set:a,update:s,subscribe:o}}class zt{constructor(e,n){this.status=e,typeof n=="string"?this.body={message:n}:n?this.body=n:this.body={message:`Error: ${e}`}}toString(){return JSON.stringify(this.body)}}class qt{constructor(e,n){this.status=e,this.location=n}}class Dt extends Error{constructor(e,n,r){super(r),this.status=e,this.text=n}}new URL("sveltekit-internal://");function je(t,e){return t==="/"||e==="ignore"?t:e==="never"?t.endsWith("/")?t.slice(0,-1):t:e==="always"&&!t.endsWith("/")?t+"/":t}function Ne(t){return t.split("%25").map(decodeURI).join("%25")}function ze(t){for(const e in t)t[e]=decodeURIComponent(t[e]);return t}function At({href:t}){return t.split("#")[0]}function qe(...t){let e=5381;for(const n of t)if(typeof n=="string"){let r=n.length;for(;r;)e=e*33^n.charCodeAt(--r)}else if(ArrayBuffer.isView(n)){const r=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);let a=r.length;for(;a;)e=e*33^r[--a]}else throw new TypeError("value must be a string or TypedArray");return(e>>>0).toString(36)}new TextEncoder;new TextDecoder;function De(t){const e=atob(t),n=new Uint8Array(e.length);for(let r=0;r((t instanceof Request?t.method:(e==null?void 0:e.method)||"GET")!=="GET"&&Y.delete(Vt(t)),Ve(t,e));const Y=new Map;function Ke(t,e){const n=Vt(t,e),r=document.querySelector(n);if(r!=null&&r.textContent){r.remove();let{body:a,...s}=JSON.parse(r.textContent);const o=r.getAttribute("data-ttl");return o&&Y.set(n,{body:a,init:s,ttl:1e3*Number(o)}),r.getAttribute("data-b64")!==null&&(a=De(a)),Promise.resolve(new Response(a,s))}return window.fetch(t,e)}function Be(t,e,n){if(Y.size>0){const r=Vt(t,n),a=Y.get(r);if(a){if(performance.now(){const a=/^\[\.\.\.(\w+)(?:=(\w+))?\]$/.exec(r);if(a)return e.push({name:a[1],matcher:a[2],optional:!1,rest:!0,chained:!0}),"(?:/([^]*))?";const s=/^\[\[(\w+)(?:=(\w+))?\]\]$/.exec(r);if(s)return e.push({name:s[1],matcher:s[2],optional:!0,rest:!1,chained:!0}),"(?:/([^/]+))?";if(!r)return;const o=r.split(/\[(.+?)\](?!\])/);return"/"+o.map((c,l)=>{if(l%2){if(c.startsWith("x+"))return Ut(String.fromCharCode(parseInt(c.slice(2),16)));if(c.startsWith("u+"))return Ut(String.fromCharCode(...c.slice(2).split("-").map(_=>parseInt(_,16))));const d=Ge.exec(c),[,u,y,f,h]=d;return e.push({name:f,matcher:h,optional:!!u,rest:!!y,chained:y?l===1&&o[0]==="":!1}),y?"([^]*?)":u?"([^/]*)?":"([^/]+?)"}return Ut(c)}).join("")}).join("")}/?$`),params:e}}function Fe(t){return t!==""&&!/^\([^)]+\)$/.test(t)}function We(t){return t.slice(1).split("/").filter(Fe)}function Ye(t,e,n){const r={},a=t.slice(1),s=a.filter(i=>i!==void 0);let o=0;for(let i=0;id).join("/"),o=0),l===void 0)if(c.rest)l="";else continue;if(!c.matcher||n[c.matcher](l)){r[c.name]=l;const d=e[i+1],u=a[i+1];d&&!d.rest&&d.optional&&u&&c.chained&&(o=0),!d&&!u&&Object.keys(r).length===s.length&&(o=0);continue}if(c.optional&&c.chained){o++;continue}return}if(!o)return r}function Ut(t){return t.normalize().replace(/[[\]]/g,"\\$&").replace(/%/g,"%25").replace(/\//g,"%2[Ff]").replace(/\?/g,"%3[Ff]").replace(/#/g,"%23").replace(/[.*+?^${}()|\\]/g,"\\$&")}function He({nodes:t,server_loads:e,dictionary:n,matchers:r}){const a=new Set(e);return Object.entries(n).map(([i,[c,l,d]])=>{const{pattern:u,params:y}=Me(i),f={id:i,exec:h=>{const _=u.exec(h);if(_)return Ye(_,y,r)},errors:[1,...d||[]].map(h=>t[h]),layouts:[0,...l||[]].map(o),leaf:s(c)};return f.errors.length=f.layouts.length=Math.max(f.errors.length,f.layouts.length),f});function s(i){const c=i<0;return c&&(i=~i),[c,t[i]]}function o(i){return i===void 0?i:[a.has(i),t[i]]}}function de(t,e=JSON.parse){try{return e(sessionStorage[t])}catch{}}function te(t,e,n=JSON.stringify){const r=n(e);try{sessionStorage[t]=r}catch{}}var ie;const A=((ie=globalThis.__sveltekit_zurjbz)==null?void 0:ie.base)??"";var ce;const Je=((ce=globalThis.__sveltekit_zurjbz)==null?void 0:ce.assets)??A??"",Xe="1770671592599",he="sveltekit:snapshot",pe="sveltekit:scroll",ge="sveltekit:states",Qe="sveltekit:pageurl",M="sveltekit:history",J="sveltekit:navigation",z={tap:1,hover:2,viewport:3,eager:4,off:-1,false:-1},Kt=location.origin;function me(t){if(t instanceof URL)return t;let e=document.baseURI;if(!e){const n=document.getElementsByTagName("base");e=n.length?n[0].href:document.URL}return new URL(t,e)}function St(){return{x:pageXOffset,y:pageYOffset}}function G(t,e){return t.getAttribute(`data-sveltekit-${e}`)}const ee={...z,"":z.hover};function _e(t){let e=t.assignedSlot??t.parentNode;return(e==null?void 0:e.nodeType)===11&&(e=e.host),e}function we(t,e){for(;t&&t!==e;){if(t.nodeName.toUpperCase()==="A"&&t.hasAttribute("href"))return t;t=_e(t)}}function Ot(t,e,n){let r;try{if(r=new URL(t instanceof SVGAElement?t.href.baseVal:t.href,document.baseURI),n&&r.hash.match(/^#[^/]/)){const i=location.hash.split("#")[1]||"/";r.hash=`#${i}${r.hash}`}}catch{}const a=t instanceof SVGAElement?t.target.baseVal:t.target,s=!r||!!a||Et(r,e,n)||(t.getAttribute("rel")||"").split(/\s+/).includes("external"),o=(r==null?void 0:r.origin)===Kt&&t.hasAttribute("download");return{url:r,external:s,target:a,download:o}}function gt(t){let e=null,n=null,r=null,a=null,s=null,o=null,i=t;for(;i&&i!==document.documentElement;)r===null&&(r=G(i,"preload-code")),a===null&&(a=G(i,"preload-data")),e===null&&(e=G(i,"keepfocus")),n===null&&(n=G(i,"noscroll")),s===null&&(s=G(i,"reload")),o===null&&(o=G(i,"replacestate")),i=_e(i);function c(l){switch(l){case"":case"true":return!0;case"off":case"false":return!1;default:return}}return{preload_code:ee[r??"off"],preload_data:ee[a??"off"],keepfocus:c(e),noscroll:c(n),reload:c(s),replace_state:c(o)}}function ne(t){const e=Nt(t);let n=!0;function r(){n=!0,e.update(o=>o)}function a(o){n=!1,e.set(o)}function s(o){let i;return e.subscribe(c=>{(i===void 0||n&&c!==i)&&o(i=c)})}return{notify:r,set:a,subscribe:s}}const ve={v:()=>{}};function Ze(){const{set:t,subscribe:e}=Nt(!1);let n;async function r(){clearTimeout(n);try{const a=await fetch(`${Je}/_app/version.json`,{headers:{pragma:"no-cache","cache-control":"no-cache"}});if(!a.ok)return!1;const o=(await a.json()).version!==Xe;return o&&(t(!0),ve.v(),clearTimeout(n)),o}catch{return!1}}return{subscribe:e,check:r}}function Et(t,e,n){return t.origin!==Kt||!t.pathname.startsWith(e)?!0:n?t.pathname!==location.pathname:!1}function Un(t){}const ye=new Set(["load","prerender","csr","ssr","trailingSlash","config"]);[...ye];const tn=new Set([...ye]);[...tn];function en(t){return t.filter(e=>e!=null)}function Bt(t){return t instanceof zt||t instanceof Dt?t.status:500}function nn(t){return t instanceof Dt?t.text:"Internal Error"}let R,X,Tt;const an=Zt.toString().includes("$$")||/function \w+\(\) \{\}/.test(Zt.toString());var nt,at,rt,ot,st,it,ct,lt,le,ft,fe,ut,ue;an?(R={data:{},form:null,error:null,params:{},route:{id:null},state:{},status:-1,url:new URL("https://example.com")},X={current:null},Tt={current:!1}):(R=new(le=class{constructor(){U(this,nt,T({}));U(this,at,T(null));U(this,rt,T(null));U(this,ot,T({}));U(this,st,T({id:null}));U(this,it,T({}));U(this,ct,T(-1));U(this,lt,T(new URL("https://example.com")))}get data(){return I(w(this,nt))}set data(e){O(w(this,nt),e)}get form(){return I(w(this,at))}set form(e){O(w(this,at),e)}get error(){return I(w(this,rt))}set error(e){O(w(this,rt),e)}get params(){return I(w(this,ot))}set params(e){O(w(this,ot),e)}get route(){return I(w(this,st))}set route(e){O(w(this,st),e)}get state(){return I(w(this,it))}set state(e){O(w(this,it),e)}get status(){return I(w(this,ct))}set status(e){O(w(this,ct),e)}get url(){return I(w(this,lt))}set url(e){O(w(this,lt),e)}},nt=new WeakMap,at=new WeakMap,rt=new WeakMap,ot=new WeakMap,st=new WeakMap,it=new WeakMap,ct=new WeakMap,lt=new WeakMap,le),X=new(fe=class{constructor(){U(this,ft,T(null))}get current(){return I(w(this,ft))}set current(e){O(w(this,ft),e)}},ft=new WeakMap,fe),Tt=new(ue=class{constructor(){U(this,ut,T(!1))}get current(){return I(w(this,ut))}set current(e){O(w(this,ut),e)}},ut=new WeakMap,ue),ve.v=()=>Tt.current=!0);function rn(t){Object.assign(R,t)}const on=new Set(["icon","shortcut icon","apple-touch-icon"]),D=de(pe)??{},Q=de(he)??{},N={url:ne({}),page:ne({}),navigating:Nt(null),updated:Ze()};function Gt(t){D[t]=St()}function sn(t,e){let n=t+1;for(;D[n];)delete D[n],n+=1;for(n=e+1;Q[n];)delete Q[n],n+=1}function Z(t,e=!1){return e?location.replace(t.href):location.href=t.href,new Promise(()=>{})}async function be(){if("serviceWorker"in navigator){const t=await navigator.serviceWorker.getRegistration(A||"/");t&&await t.update()}}function ae(){}let Mt,Pt,mt,$,$t,b;const _t=[],wt=[];let v=null;function Ct(){var t;(t=v==null?void 0:v.fork)==null||t.then(e=>e==null?void 0:e.discard()),v=null}const ht=new Map,ke=new Set,cn=new Set,H=new Set;let m={branch:[],error:null,url:null},Se=!1,vt=!1,re=!0,tt=!1,W=!1,Ee=!1,Ft=!1,Re,S,L,q;const yt=new Set,oe=new Map;async function Pn(t,e,n){var s,o,i,c,l;(s=globalThis.__sveltekit_zurjbz)!=null&&s.data&&globalThis.__sveltekit_zurjbz.data,document.URL!==location.href&&(location.href=location.href),b=t,await((i=(o=t.hooks).init)==null?void 0:i.call(o)),Mt=He(t),$=document.documentElement,$t=e,Pt=t.nodes[0],mt=t.nodes[1],Pt(),mt(),S=(c=history.state)==null?void 0:c[M],L=(l=history.state)==null?void 0:l[J],S||(S=L=Date.now(),history.replaceState({...history.state,[M]:S,[J]:L},""));const r=D[S];function a(){r&&(history.scrollRestoration="manual",scrollTo(r.x,r.y))}n?(a(),await kn($t,n)):(await F({type:"enter",url:me(b.hash?Rn(new URL(location.href)):location.href),replace_state:!0}),a()),bn()}function ln(){_t.length=0,Ft=!1}function xe(t){wt.some(e=>e==null?void 0:e.snapshot)&&(Q[t]=wt.map(e=>{var n;return(n=e==null?void 0:e.snapshot)==null?void 0:n.capture()}))}function Le(t){var e;(e=Q[t])==null||e.forEach((n,r)=>{var a,s;(s=(a=wt[r])==null?void 0:a.snapshot)==null||s.restore(n)})}function se(){Gt(S),te(pe,D),xe(L),te(he,Q)}async function fn(t,e,n,r){let a;e.invalidateAll&&Ct(),await F({type:"goto",url:me(t),keepfocus:e.keepFocus,noscroll:e.noScroll,replace_state:e.replaceState,state:e.state,redirect_count:n,nav_token:r,accept:()=>{e.invalidateAll&&(Ft=!0,a=[...oe.keys()]),e.invalidate&&e.invalidate.forEach(yn)}}),e.invalidateAll&&pt().then(pt).then(()=>{oe.forEach(({resource:s},o)=>{var i;a!=null&&a.includes(o)&&((i=s.refresh)==null||i.call(s))})})}async function un(t){if(t.id!==(v==null?void 0:v.id)){Ct();const e={};yt.add(e),v={id:t.id,token:e,promise:Ue({...t,preload:e}).then(n=>(yt.delete(e),n.type==="loaded"&&n.state.error&&Ct(),n)),fork:null}}return v.promise}async function It(t){var n;const e=(n=await Rt(t,!1))==null?void 0:n.route;e&&await Promise.all([...e.layouts,e.leaf].map(r=>r==null?void 0:r[1]()))}async function Ae(t,e,n){var a;m=t.state;const r=document.querySelector("style[data-sveltekit]");if(r&&r.remove(),Object.assign(R,t.props.page),Re=new b.root({target:e,props:{...t.props,stores:N,components:wt},hydrate:n,sync:!1}),await Promise.resolve(),Le(L),n){const s={from:null,to:{params:m.params,route:{id:((a=m.route)==null?void 0:a.id)??null},url:new URL(location.href)},willUnload:!1,type:"enter",complete:Promise.resolve()};H.forEach(o=>o(s))}vt=!0}function bt({url:t,params:e,branch:n,status:r,error:a,route:s,form:o}){let i="never";if(A&&(t.pathname===A||t.pathname===A+"/"))i="always";else for(const f of n)(f==null?void 0:f.slash)!==void 0&&(i=f.slash);t.pathname=je(t.pathname,i),t.search=t.search;const c={type:"loaded",state:{url:t,params:e,branch:n,error:a,route:s},props:{constructors:en(n).map(f=>f.node.component),page:Xt(R)}};o!==void 0&&(c.props.form=o);let l={},d=!R,u=0;for(let f=0;fi(new URL(o))))return!0;return!1}function Yt(t,e){return(t==null?void 0:t.type)==="data"?t:(t==null?void 0:t.type)==="skip"?e??null:null}function pn(t,e){if(!t)return new Set(e.searchParams.keys());const n=new Set([...t.searchParams.keys(),...e.searchParams.keys()]);for(const r of n){const a=t.searchParams.getAll(r),s=e.searchParams.getAll(r);a.every(o=>s.includes(o))&&s.every(o=>a.includes(o))&&n.delete(r)}return n}function gn({error:t,url:e,route:n,params:r}){return{type:"loaded",state:{error:t,url:e,route:n,params:r,branch:[]},props:{page:Xt(R),constructors:[]}}}async function Ue({id:t,invalidating:e,url:n,params:r,route:a,preload:s}){if((v==null?void 0:v.id)===t)return yt.delete(v.token),v.promise;const{errors:o,layouts:i,leaf:c}=a,l=[...i,c];o.forEach(g=>g==null?void 0:g().catch(()=>{})),l.forEach(g=>g==null?void 0:g[1]().catch(()=>{}));const d=m.url?t!==kt(m.url):!1,u=m.route?a.id!==m.route.id:!1,y=pn(m.url,n);let f=!1;const h=l.map(async(g,p)=>{var C;if(!g)return;const k=m.branch[p];return g[1]===(k==null?void 0:k.loader)&&!hn(f,u,d,y,(C=k.universal)==null?void 0:C.uses,r)?k:(f=!0,Wt({loader:g[1],url:n,params:r,route:a,parent:async()=>{var dt;const P={};for(let V=0;V{});const _=[];for(let g=0;gPromise.resolve({}),server_data_node:Yt(s)}),i={node:await mt(),loader:mt,universal:null,server:null,data:null};return bt({url:n,params:a,branch:[o,i],status:t,error:e,route:null})}catch(o){if(o instanceof qt)return fn(new URL(o.location,location.href),{},0);throw o}}async function _n(t){const e=t.href;if(ht.has(e))return ht.get(e);let n;try{const r=(async()=>{let a=await b.hooks.reroute({url:new URL(t),fetch:async(s,o)=>dn(s,o,t).promise})??t;if(typeof a=="string"){const s=new URL(t);b.hash?s.hash=a:s.pathname=a,a=s}return a})();ht.set(e,r),n=await r}catch{ht.delete(e);return}return n}async function Rt(t,e){if(t&&!Et(t,A,b.hash)){const n=await _n(t);if(!n)return;const r=wn(n);for(const a of Mt){const s=a.exec(r);if(s)return{id:kt(t),invalidating:e,route:a,params:ze(s),url:t}}}}function wn(t){return Ne(b.hash?t.hash.replace(/^#/,"").replace(/[?#].+/,""):t.pathname.slice(A.length))||"/"}function kt(t){return(b.hash?t.hash.replace(/^#/,""):t.pathname)+t.search}function Te({url:t,type:e,intent:n,delta:r,event:a}){let s=!1;const o=Jt(m,n,t,e);r!==void 0&&(o.navigation.delta=r),a!==void 0&&(o.navigation.event=a);const i={...o.navigation,cancel:()=>{s=!0,o.reject(new Error("navigation cancelled"))}};return tt||ke.forEach(c=>c(i)),s?null:o}async function F({type:t,url:e,popped:n,keepfocus:r,noscroll:a,replace_state:s,state:o={},redirect_count:i=0,nav_token:c={},accept:l=ae,block:d=ae,event:u}){var V;const y=q;q=c;const f=await Rt(e,!1),h=t==="enter"?Jt(m,f,e,t):Te({url:e,type:t,delta:n==null?void 0:n.delta,intent:f,event:u});if(!h){d(),q===c&&(q=y);return}const _=S,g=L;l(),tt=!0,vt&&h.navigation.type!=="enter"&&N.navigating.set(X.current=h.navigation);let p=f&&await Ue(f);if(!p){if(Et(e,A,b.hash))return await Z(e,s);p=await Ie(e,{id:null},await et(new Dt(404,"Not Found",`Not found: ${e.pathname}`),{url:e,params:{},route:{id:null}}),404,s)}if(e=(f==null?void 0:f.url)||e,q!==c)return h.reject(new Error("navigation aborted")),!1;if(p.type==="redirect"){if(i<20){await F({type:t,url:new URL(p.location,e),popped:n,keepfocus:r,noscroll:a,replace_state:s,state:o,redirect_count:i+1,nav_token:c}),h.fulfil(void 0);return}p=await Ht({status:500,error:await et(new Error("Redirect loop"),{url:e,params:{},route:{id:null}}),url:e,route:{id:null}})}else p.props.page.status>=400&&await N.updated.check()&&(await be(),await Z(e,s));if(ln(),Gt(_),xe(g),p.props.page.url.pathname!==e.pathname&&(e.pathname=p.props.page.url.pathname),o=n?n.state:o,!n){const E=s?0:1,K={[M]:S+=E,[J]:L+=E,[ge]:o};(s?history.replaceState:history.pushState).call(history,K,"",e),s||sn(S,L)}const k=f&&(v==null?void 0:v.id)===f.id?v.fork:null;v=null,p.props.page.state=o;let x;if(vt){const E=(await Promise.all(Array.from(cn,j=>j(h.navigation)))).filter(j=>typeof j=="function");if(E.length>0){let j=function(){E.forEach(xt=>{H.delete(xt)})};E.push(j),E.forEach(xt=>{H.add(xt)})}m=p.state,p.props.page&&(p.props.page.url=e);const K=k&&await k;K?x=K.commit():(Re.$set(p.props),rn(p.props.page),x=(V=Ce)==null?void 0:V()),Ee=!0}else await Ae(p,$t,!1);const{activeElement:C}=document;await x,await pt(),await pt();let P=n?n.scroll:a?St():null;if(re){const E=e.hash&&document.getElementById(Oe(e));if(P)scrollTo(P.x,P.y);else if(E){E.scrollIntoView();const{top:K,left:j}=E.getBoundingClientRect();P={x:pageXOffset+j,y:pageYOffset+K}}else scrollTo(0,0)}const dt=document.activeElement!==C&&document.activeElement!==document.body;!r&&!dt&&En(e,P),re=!0,p.props.page&&Object.assign(R,p.props.page),tt=!1,t==="popstate"&&Le(L),h.fulfil(void 0),H.forEach(E=>E(h.navigation)),N.navigating.set(X.current=null)}async function Ie(t,e,n,r,a){return t.origin===Kt&&t.pathname===location.pathname&&!Se?await Ht({status:r,error:n,url:t,route:e}):await Z(t,a)}function vn(){let t,e={element:void 0,href:void 0},n;$.addEventListener("mousemove",i=>{const c=i.target;clearTimeout(t),t=setTimeout(()=>{s(c,z.hover)},20)});function r(i){i.defaultPrevented||s(i.composedPath()[0],z.tap)}$.addEventListener("mousedown",r),$.addEventListener("touchstart",r,{passive:!0});const a=new IntersectionObserver(i=>{for(const c of i)c.isIntersecting&&(It(new URL(c.target.href)),a.unobserve(c.target))},{threshold:0});async function s(i,c){const l=we(i,$),d=l===e.element&&(l==null?void 0:l.href)===e.href&&c>=n;if(!l||d)return;const{url:u,external:y,download:f}=Ot(l,A,b.hash);if(y||f)return;const h=gt(l),_=u&&kt(m.url)===kt(u);if(!(h.reload||_))if(c<=h.preload_data){e={element:l,href:l.href},n=z.tap;const g=await Rt(u,!1);if(!g)return;un(g)}else c<=h.preload_code&&(e={element:l,href:l.href},n=c,It(u))}function o(){a.disconnect();for(const i of $.querySelectorAll("a")){const{url:c,external:l,download:d}=Ot(i,A,b.hash);if(l||d)continue;const u=gt(i);u.reload||(u.preload_code===z.viewport&&a.observe(i),u.preload_code===z.eager&&It(c))}}H.add(o),o()}function et(t,e){if(t instanceof zt)return t.body;const n=Bt(t),r=nn(t);return b.hooks.handleError({error:t,event:e,status:n,message:r})??{message:r}}function yn(t){if(typeof t=="function")_t.push(t);else{const{href:e}=new URL(t,location.href);_t.push(n=>n.href===e)}}function bn(){var e;history.scrollRestoration="manual",addEventListener("beforeunload",n=>{let r=!1;if(se(),!tt){const a=Jt(m,void 0,null,"leave"),s={...a.navigation,cancel:()=>{r=!0,a.reject(new Error("navigation cancelled"))}};ke.forEach(o=>o(s))}r?(n.preventDefault(),n.returnValue=""):history.scrollRestoration="auto"}),addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&se()}),(e=navigator.connection)!=null&&e.saveData||vn(),$.addEventListener("click",async n=>{if(n.button||n.which!==1||n.metaKey||n.ctrlKey||n.shiftKey||n.altKey||n.defaultPrevented)return;const r=we(n.composedPath()[0],$);if(!r)return;const{url:a,external:s,target:o,download:i}=Ot(r,A,b.hash);if(!a)return;if(o==="_parent"||o==="_top"){if(window.parent!==window)return}else if(o&&o!=="_self")return;const c=gt(r);if(!(r instanceof SVGAElement)&&a.protocol!==location.protocol&&!(a.protocol==="https:"||a.protocol==="http:")||i)return;const[d,u]=(b.hash?a.hash.replace(/^#/,""):a.href).split("#"),y=d===At(location);if(s||c.reload&&(!y||!u)){Te({url:a,type:"link",event:n})?tt=!0:n.preventDefault();return}if(u!==void 0&&y){const[,f]=m.url.href.split("#");if(f===u){if(n.preventDefault(),u===""||u==="top"&&r.ownerDocument.getElementById("top")===null)scrollTo({top:0});else{const h=r.ownerDocument.getElementById(decodeURIComponent(u));h&&(h.scrollIntoView(),h.focus())}return}if(W=!0,Gt(S),t(a),!c.replace_state)return;W=!1}n.preventDefault(),await new Promise(f=>{requestAnimationFrame(()=>{setTimeout(f,0)}),setTimeout(f,100)}),await F({type:"link",url:a,keepfocus:c.keepfocus,noscroll:c.noscroll,replace_state:c.replace_state??a.href===location.href,event:n})}),$.addEventListener("submit",n=>{if(n.defaultPrevented)return;const r=HTMLFormElement.prototype.cloneNode.call(n.target),a=n.submitter;if(((a==null?void 0:a.formTarget)||r.target)==="_blank"||((a==null?void 0:a.formMethod)||r.method)!=="get")return;const i=new URL((a==null?void 0:a.hasAttribute("formaction"))&&(a==null?void 0:a.formAction)||r.action);if(Et(i,A,!1))return;const c=n.target,l=gt(c);if(l.reload)return;n.preventDefault(),n.stopPropagation();const d=new FormData(c,a);i.search=new URLSearchParams(d).toString(),F({type:"form",url:i,keepfocus:l.keepfocus,noscroll:l.noscroll,replace_state:l.replace_state??i.href===location.href,event:n})}),addEventListener("popstate",async n=>{var r;if(!jt){if((r=n.state)!=null&&r[M]){const a=n.state[M];if(q={},a===S)return;const s=D[a],o=n.state[ge]??{},i=new URL(n.state[Qe]??location.href),c=n.state[J],l=m.url?At(location)===At(m.url):!1;if(c===L&&(Ee||l)){o!==R.state&&(R.state=o),t(i),D[S]=St(),s&&scrollTo(s.x,s.y),S=a;return}const u=a-S;await F({type:"popstate",url:i,popped:{state:o,scroll:s,delta:u},accept:()=>{S=a,L=c},block:()=>{history.go(-u)},nav_token:q,event:n})}else if(!W){const a=new URL(location.href);t(a),b.hash&&location.reload()}}}),addEventListener("hashchange",()=>{W&&(W=!1,history.replaceState({...history.state,[M]:++S,[J]:L},"",location.href))});for(const n of document.querySelectorAll("link"))on.has(n.rel)&&(n.href=n.href);addEventListener("pageshow",n=>{n.persisted&&N.navigating.set(X.current=null)});function t(n){m.url=R.url=n,N.page.set(Xt(R)),N.page.notify()}}async function kn(t,{status:e=200,error:n,node_ids:r,params:a,route:s,server_route:o,data:i,form:c}){Se=!0;const l=new URL(location.href);let d;({params:a={},route:s={id:null}}=await Rt(l,!1)||{}),d=Mt.find(({id:f})=>f===s.id);let u,y=!0;try{const f=r.map(async(_,g)=>{const p=i[g];return p!=null&&p.uses&&(p.uses=Sn(p.uses)),Wt({loader:b.nodes[_],url:l,params:a,route:s,parent:async()=>{const k={};for(let x=0;x{const i=history.state;jt=!0,location.replace(`#${r}`),b.hash&&location.replace(t.hash),history.replaceState(i,"",t.hash),scrollTo(s,o),jt=!1})}else{const s=document.body,o=s.getAttribute("tabindex");s.tabIndex=-1,s.focus({preventScroll:!0,focusVisible:!1}),o!==null?s.setAttribute("tabindex",o):s.removeAttribute("tabindex")}const a=getSelection();if(a&&a.type!=="None"){const s=[];for(let o=0;o{if(a.rangeCount===s.length){for(let o=0;o{a=d,s=u});return o.catch(()=>{}),{navigation:{from:{params:t.params,route:{id:((c=t.route)==null?void 0:c.id)??null},url:t.url},to:n&&{params:(e==null?void 0:e.params)??null,route:{id:((l=e==null?void 0:e.route)==null?void 0:l.id)??null},url:n},willUnload:!e,type:r,complete:o},fulfil:a,reject:s}}function Xt(t){return{data:t.data,error:t.error,form:t.form,params:t.params,route:t.route,state:t.state,status:t.status,url:t.url}}function Rn(t){const e=new URL(t);return e.hash=decodeURIComponent(t.hash),e}function Oe(t){let e;if(b.hash){const[,,n]=t.hash.split("#",3);e=n??""}else e=t.hash.slice(1);return decodeURIComponent(e)}export{Pn as a,Un as l,R as p,N as s}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js deleted file mode 100644 index 7a7a219..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/B_PiQ68N.js +++ /dev/null @@ -1 +0,0 @@ -var lt=Object.defineProperty;var pn=e=>{throw TypeError(e)};var at=(e,n,t)=>n in e?lt(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t;var Q=(e,n,t)=>at(e,typeof n!="symbol"?n+"":n,t),Ke=(e,n,t)=>n.has(e)||pn("Cannot "+t);var d=(e,n,t)=>(Ke(e,n,"read from private field"),t?t.call(e):n.get(e)),F=(e,n,t)=>n.has(e)?pn("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(e):n.set(e,t),K=(e,n,t,r)=>(Ke(e,n,"write to private field"),r?r.call(e,t):n.set(e,t),t),ce=(e,n,t)=>(Ke(e,n,"access private method"),t);var ut=Array.isArray,ot=Array.prototype.indexOf,we=Array.prototype.includes,Zt=Array.from,Jt=Object.defineProperty,be=Object.getOwnPropertyDescriptor,ct=Object.getOwnPropertyDescriptors,_t=Object.prototype,vt=Array.prototype,bn=Object.getPrototypeOf,hn=Object.isExtensible;const Wt=()=>{};function Xt(e){return e()}function dt(e){for(var n=0;n{e=r,n=s});return{promise:t,resolve:e,reject:n}}const A=2,Me=4,Oe=8,Rn=1<<24,G=16,U=32,oe=64,Sn=128,N=512,E=1024,x=2048,q=4096,L=8192,$=16384,rn=32768,je=65536,wn=1<<17,xn=1<<18,De=1<<19,kn=1<<20,ie=32768,$e=1<<21,sn=1<<22,Z=1<<23,Ae=Symbol("$state"),Qt=Symbol("legacy props"),_e=new class extends Error{constructor(){super(...arguments);Q(this,"name","StaleReactionError");Q(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}},Ve=3,On=8;function pt(){throw new Error("https://svelte.dev/e/async_derived_orphan")}function ht(e){throw new Error("https://svelte.dev/e/effect_in_teardown")}function wt(){throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function yt(e){throw new Error("https://svelte.dev/e/effect_orphan")}function gt(){throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function nr(){throw new Error("https://svelte.dev/e/hydration_failed")}function tr(e){throw new Error("https://svelte.dev/e/props_invalid_value")}function mt(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function Et(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Tt(){throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function rr(){throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}const sr=1,fr=2,ir=4,lr=8,ar=16,ur=1,or=2,bt="[",At="[!",Rt="]",fn={},T=Symbol();function ln(e){console.warn("https://svelte.dev/e/hydration_mismatch")}function cr(){console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}let le=!1;function _r(e){le=e}let m;function ye(e){if(e===null)throw ln(),fn;return m=e}function vr(){return ye(X(m))}function dr(e){if(le){if(X(m)!==null)throw ln(),fn;m=e}}function pr(e=1){if(le){for(var n=e,t=m;n--;)t=X(t);m=t}}function hr(e=!0){for(var n=0,t=m;;){if(t.nodeType===On){var r=t.data;if(r===Rt){if(n===0)return t;n-=1}else(r===bt||r===At)&&(n+=1)}var s=X(t);e&&t.remove(),t=s}}function wr(e){if(!e||e.nodeType!==On)throw ln(),fn;return e.data}function Dn(e){return e===this.v}function St(e,n){return e!=e?n==n:e!==n||e!==null&&typeof e=="object"||typeof e=="function"}function Pn(e){return!St(e,this.v)}let Be=!1;function yr(){Be=!0}let S=null;function Le(e){S=e}function gr(e,n=!1,t){S={p:S,i:!1,c:null,e:null,s:e,x:null,l:Be&&!n?{s:null,u:null,$:[]}:null}}function mr(e){var n=S,t=n.e;if(t!==null){n.e=null;for(var r of t)$n(r)}return n.i=!0,S=n.p,{}}function Pe(){return!Be||S!==null&&S.l===null}let ne=[];function Nn(){var e=ne;ne=[],dt(e)}function yn(e){if(ne.length===0&&!Re){var n=ne;queueMicrotask(()=>{n===ne&&Nn()})}ne.push(e)}function xt(){for(;ne.length>0;)Nn()}function kt(e){var n=w;if(n===null)return v.f|=Z,e;if(n.f&rn)qe(e,n);else{if(!(n.f&Sn))throw e;n.b.error(e)}}function qe(e,n){for(;n!==null;){if(n.f&Sn)try{n.b.error(e);return}catch(t){e=t}n=n.parent}throw e}const Ot=-7169;function y(e,n){e.f=e.f&Ot|n}function an(e){e.f&N||e.deps===null?y(e,E):y(e,q)}function In(e){if(e!==null)for(const n of e)!(n.f&A)||!(n.f&ie)||(n.f^=ie,In(n.deps))}function Dt(e,n,t){e.f&x?n.add(e):e.f&q&&t.add(e),In(e.deps),y(e,E)}const Fe=new Set;let p=null,b=null,k=[],He=null,Ze=!1,Re=!1;var ve,de,re,pe,xe,ke,se,B,he,Y,Je,We,Fn;const vn=class vn{constructor(){F(this,Y);Q(this,"committed",!1);Q(this,"current",new Map);Q(this,"previous",new Map);F(this,ve,new Set);F(this,de,new Set);F(this,re,0);F(this,pe,0);F(this,xe,null);F(this,ke,new Set);F(this,se,new Set);F(this,B,new Map);Q(this,"is_fork",!1);F(this,he,!1)}is_deferred(){return this.is_fork||d(this,pe)>0}skip_effect(n){d(this,B).has(n)||d(this,B).set(n,{d:[],m:[]})}unskip_effect(n){var t=d(this,B).get(n);if(t){d(this,B).delete(n);for(var r of t.d)y(r,x),H(r);for(r of t.m)y(r,q),H(r)}}process(n){var s;k=[],this.apply();var t=[],r=[];for(const f of n)ce(this,Y,Je).call(this,f,t,r);if(this.is_deferred()){ce(this,Y,We).call(this,r),ce(this,Y,We).call(this,t);for(const[f,i]of d(this,B))Ln(f,i)}else{for(const f of d(this,ve))f();d(this,ve).clear(),d(this,re)===0&&ce(this,Y,Fn).call(this),p=null,gn(r),gn(t),(s=d(this,xe))==null||s.resolve()}b=null}capture(n,t){t!==T&&!this.previous.has(n)&&this.previous.set(n,t),n.f&Z||(this.current.set(n,n.v),b==null||b.set(n,n.v))}activate(){p=this,this.apply()}deactivate(){p===this&&(p=null,b=null)}flush(){if(this.activate(),k.length>0){if(Cn(),p!==null&&p!==this)return}else d(this,re)===0&&this.process([]);this.deactivate()}discard(){for(const n of d(this,de))n(this);d(this,de).clear()}increment(n){K(this,re,d(this,re)+1),n&&K(this,pe,d(this,pe)+1)}decrement(n){K(this,re,d(this,re)-1),n&&K(this,pe,d(this,pe)-1),!d(this,he)&&(K(this,he,!0),yn(()=>{K(this,he,!1),this.is_deferred()?k.length>0&&this.flush():this.revive()}))}revive(){for(const n of d(this,ke))d(this,se).delete(n),y(n,x),H(n);for(const n of d(this,se))y(n,q),H(n);this.flush()}oncommit(n){d(this,ve).add(n)}ondiscard(n){d(this,de).add(n)}settled(){return(d(this,xe)??K(this,xe,An())).promise}static ensure(){if(p===null){const n=p=new vn;Fe.add(p),Re||yn(()=>{p===n&&n.flush()})}return p}apply(){}};ve=new WeakMap,de=new WeakMap,re=new WeakMap,pe=new WeakMap,xe=new WeakMap,ke=new WeakMap,se=new WeakMap,B=new WeakMap,he=new WeakMap,Y=new WeakSet,Je=function(n,t,r){n.f^=E;for(var s=n.first,f=null;s!==null;){var i=s.f,u=(i&(U|oe))!==0,l=u&&(i&E)!==0,a=l||(i&L)!==0||d(this,B).has(s);if(!a&&s.fn!==null){u?s.f^=E:f!==null&&i&(Me|Oe|Rn)?f.b.defer_effect(s):i&Me?t.push(s):Ne(s)&&(i&G&&d(this,se).add(s),Se(s));var o=s.first;if(o!==null){s=o;continue}}var _=s.parent;for(s=s.next;s===null&&_!==null;)_===f&&(f=null),s=_.next,_=_.parent}},We=function(n){for(var t=0;t1){this.previous.clear();var n=b,t=!0;for(const f of Fe){if(f===this){t=!1;continue}const i=[];for(const[l,a]of this.current){if(f.current.has(l))if(t&&a!==f.current.get(l))f.current.set(l,a);else continue;i.push(l)}if(i.length===0)continue;const u=[...f.current.keys()].filter(l=>!this.current.has(l));if(u.length>0){var r=k;k=[];const l=new Set,a=new Map;for(const o of i)Mn(o,u,l,a);if(k.length>0){p=f,f.apply();for(const o of k)ce(s=f,Y,Je).call(s,o,[],[]);f.deactivate()}k=r}}p=null,b=n}this.committed=!0,Fe.delete(this)};let ge=vn;function Pt(e){var n=Re;Re=!0;try{for(var t;;){if(xt(),k.length===0&&(p==null||p.flush(),k.length===0))return He=null,t;Cn()}}finally{Re=n}}function Cn(){Ze=!0;var e=null;try{for(var n=0;k.length>0;){var t=ge.ensure();if(n++>1e3){var r,s;Nt()}t.process(k),J.clear()}}finally{k=[],Ze=!1,He=null}}function Nt(){try{gt()}catch(e){qe(e,He)}}let C=null;function gn(e){var n=e.length;if(n!==0){for(var t=0;t0)){J.clear();for(const s of C){if(s.f&($|L))continue;const f=[s];let i=s.parent;for(;i!==null;)C.has(i)&&(C.delete(i),f.push(i)),i=i.parent;for(let u=f.length-1;u>=0;u--){const l=f[u];l.f&($|L)||Se(l)}}C.clear()}}C=null}}function Mn(e,n,t,r){if(!t.has(e)&&(t.add(e),e.reactions!==null))for(const s of e.reactions){const f=s.f;f&A?Mn(s,n,t,r):f&(sn|G)&&!(f&x)&&jn(s,n,r)&&(y(s,x),H(s))}}function jn(e,n,t){const r=t.get(e);if(r!==void 0)return r;if(e.deps!==null)for(const s of e.deps){if(we.call(n,s))return!0;if(s.f&A&&jn(s,n,t))return t.set(s,!0),!0}return t.set(e,!1),!1}function H(e){for(var n=He=e;n.parent!==null;){n=n.parent;var t=n.f;if(Ze&&n===w&&t&G&&!(t&xn))return;if(t&(oe|U)){if(!(t&E))return;n.f^=E}}k.push(n)}function Ln(e,n){if(!(e.f&U&&e.f&E)){e.f&x?n.d.push(e):e.f&q&&n.m.push(e),y(e,E);for(var t=e.first;t!==null;)Ln(t,n),t=t.next}}function It(e,n,t,r){const s=Pe()?un:Mt;var f=e.filter(c=>!c.settled);if(t.length===0&&f.length===0){r(n.map(s));return}var i=p,u=w,l=Ft(),a=f.length===1?f[0].promise:f.length>1?Promise.all(f.map(c=>c.promise)):null;function o(c){l();try{r(c)}catch(g){u.f&$||qe(g,u)}i==null||i.deactivate(),Xe()}if(t.length===0){a.then(()=>o(n.map(s)));return}function _(){l(),Promise.all(t.map(c=>Ct(c))).then(c=>o([...n.map(s),...c])).catch(c=>qe(c,u))}a?a.then(_):_()}function Ft(){var e=w,n=v,t=S,r=p;return function(f=!0){me(e),W(n),Le(t),f&&(r==null||r.activate())}}function Xe(){me(null),W(null),Le(null)}function un(e){var n=A|x,t=v!==null&&v.f&A?v:null;return w!==null&&(w.f|=De),{ctx:S,deps:null,effects:null,equals:Dn,f:n,fn:e,reactions:null,rv:0,v:T,wv:0,parent:t??w,ac:null}}function Ct(e,n,t){let r=w;r===null&&pt();var s=r.b,f=void 0,i=cn(T),u=!v,l=new Map;return Vt(()=>{var g;var a=An();f=a.promise;try{Promise.resolve(e()).then(a.resolve,a.reject).then(()=>{o===p&&o.committed&&o.deactivate(),Xe()})}catch(h){a.reject(h),Xe()}var o=p;if(u){var _=s.is_rendered();s.update_pending_count(1),o.increment(_),(g=l.get(o))==null||g.reject(_e),l.delete(o),l.set(o,a)}const c=(h,j=void 0)=>{if(o.activate(),j)j!==_e&&(i.f|=Z,en(i,j));else{i.f&Z&&(i.f^=Z),en(i,h);for(const[R,Ie]of l){if(l.delete(R),R===o)break;Ie.reject(_e)}}u&&(s.update_pending_count(-1),o.decrement(_))};a.promise.then(c,h=>c(null,h||"unknown"))}),Ut(()=>{for(const a of l.values())a.reject(_e)}),new Promise(a=>{function o(_){function c(){_===f?a(i):o(f)}_.then(c,c)}o(f)})}function Er(e){const n=un(e);return et(n),n}function Mt(e){const n=un(e);return n.equals=Pn,n}function qn(e){var n=e.effects;if(n!==null){e.effects=null;for(var t=0;t0&&!Un&&Lt()}return n}function Lt(){Un=!1;for(const e of Qe)e.f&E&&y(e,q),Ne(e)&&Se(e);Qe.clear()}function ze(e){ee(e,e.v+1)}function Vn(e,n){var t=e.reactions;if(t!==null)for(var r=Pe(),s=t.length,f=0;f{if(fe===f)return u();var l=v,a=fe;W(null),Tn(f);var o=u();return W(l),Tn(a),o};return r&&t.set("length",z(e.length)),new Proxy(e,{defineProperty(u,l,a){(!("value"in a)||a.configurable===!1||a.enumerable===!1||a.writable===!1)&&mt();var o=t.get(l);return o===void 0?o=i(()=>{var _=z(a.value);return t.set(l,_),_}):ee(o,a.value,!0),!0},deleteProperty(u,l){var a=t.get(l);if(a===void 0){if(l in u){const o=i(()=>z(T));t.set(l,o),ze(s)}}else ee(a,T),ze(s);return!0},get(u,l,a){var g;if(l===Ae)return e;var o=t.get(l),_=l in u;if(o===void 0&&(!_||(g=be(u,l))!=null&&g.writable)&&(o=i(()=>{var h=Ee(_?u[l]:T),j=z(h);return j}),t.set(l,o)),o!==void 0){var c=Te(o);return c===T?void 0:c}return Reflect.get(u,l,a)},getOwnPropertyDescriptor(u,l){var a=Reflect.getOwnPropertyDescriptor(u,l);if(a&&"value"in a){var o=t.get(l);o&&(a.value=Te(o))}else if(a===void 0){var _=t.get(l),c=_==null?void 0:_.v;if(_!==void 0&&c!==T)return{enumerable:!0,configurable:!0,value:c,writable:!0}}return a},has(u,l){var c;if(l===Ae)return!0;var a=t.get(l),o=a!==void 0&&a.v!==T||Reflect.has(u,l);if(a!==void 0||w!==null&&(!o||(c=be(u,l))!=null&&c.writable)){a===void 0&&(a=i(()=>{var g=o?Ee(u[l]):T,h=z(g);return h}),t.set(l,a));var _=Te(a);if(_===T)return!1}return o},set(u,l,a,o){var dn;var _=t.get(l),c=l in u;if(r&&l==="length")for(var g=a;g<_.v;g+=1){var h=t.get(g+"");h!==void 0?ee(h,T):g in u&&(h=i(()=>z(T)),t.set(g+"",h))}if(_===void 0)(!c||(dn=be(u,l))!=null&&dn.writable)&&(_=i(()=>z(void 0)),ee(_,Ee(a)),t.set(l,_));else{c=_.v!==T;var j=i(()=>Ee(a));ee(_,j)}var R=Reflect.getOwnPropertyDescriptor(u,l);if(R!=null&&R.set&&R.set.call(o,a),!c){if(r&&typeof l=="string"){var Ie=t.get("length"),Ge=Number(l);Number.isInteger(Ge)&&Ge>=Ie.v&&ee(Ie,Ge+1)}ze(s)}return!0},ownKeys(u){Te(s);var l=Reflect.ownKeys(u).filter(_=>{var c=t.get(_);return c===void 0||c.v!==T});for(var[a,o]of t)o.v!==T&&!(a in u)&&l.push(a);return l},setPrototypeOf(){Et()}})}var mn,qt,Bn,Hn;function br(){if(mn===void 0){mn=window,qt=/Firefox/.test(navigator.userAgent);var e=Element.prototype,n=Node.prototype,t=Text.prototype;Bn=be(n,"firstChild").get,Hn=be(n,"nextSibling").get,hn(e)&&(e.__click=void 0,e.__className=void 0,e.__attributes=null,e.__style=void 0,e.__e=void 0),hn(t)&&(t.__t=void 0)}}function Ye(e=""){return document.createTextNode(e)}function nn(e){return Bn.call(e)}function X(e){return Hn.call(e)}function Ar(e,n){if(!le)return nn(e);var t=nn(m);if(t===null)t=m.appendChild(Ye());else if(n&&t.nodeType!==Ve){var r=Ye();return t==null||t.before(r),ye(r),r}return n&&_n(t),ye(t),t}function Rr(e,n=!1){if(!le){var t=nn(e);return t instanceof Comment&&t.data===""?X(t):t}if(n){if((m==null?void 0:m.nodeType)!==Ve){var r=Ye();return m==null||m.before(r),ye(r),r}_n(m)}return m}function Sr(e,n=1,t=!1){let r=le?m:e;for(var s;n--;)s=r,r=X(r);if(!le)return r;if(t){if((r==null?void 0:r.nodeType)!==Ve){var f=Ye();return r===null?s==null||s.after(f):r.before(f),ye(f),f}_n(r)}return ye(r),r}function xr(e){e.textContent=""}function kr(){return!1}function _n(e){if(e.nodeValue.length<65536)return;let n=e.nextSibling;for(;n!==null&&n.nodeType===Ve;)n.remove(),e.nodeValue+=n.nodeValue,n=e.nextSibling}function Gn(e){var n=v,t=w;W(null),me(null);try{return e()}finally{W(n),me(t)}}function Kn(e){w===null&&(v===null&&yt(),wt()),ue&&ht()}function Yt(e,n){var t=n.last;t===null?n.last=n.first=e:(t.next=e,e.prev=t,n.last=e)}function V(e,n,t){var r=w;r!==null&&r.f&L&&(e|=L);var s={ctx:S,deps:null,nodes:null,f:e|x|N,first:null,fn:n,last:null,next:null,parent:r,b:r&&r.b,prev:null,teardown:null,wv:0,ac:null};if(t)try{Se(s),s.f|=rn}catch(u){throw ae(s),u}else n!==null&&H(s);var f=s;if(t&&f.deps===null&&f.teardown===null&&f.nodes===null&&f.first===f.last&&!(f.f&De)&&(f=f.first,e&G&&e&je&&f!==null&&(f.f|=je)),f!==null&&(f.parent=r,r!==null&&Yt(f,r),v!==null&&v.f&A&&!(e&oe))){var i=v;(i.effects??(i.effects=[])).push(f)}return s}function zn(){return v!==null&&!M}function Ut(e){const n=V(Oe,null,!1);return y(n,E),n.teardown=e,n}function Or(e){Kn();var n=w.f,t=!v&&(n&U)!==0&&(n&rn)===0;if(t){var r=S;(r.e??(r.e=[])).push(e)}else return $n(e)}function $n(e){return V(Me|kn,e,!1)}function Dr(e){return Kn(),V(Oe|kn,e,!0)}function Pr(e){ge.ensure();const n=V(oe|De,e,!0);return(t={})=>new Promise(r=>{t.outro?Gt(n,()=>{ae(n),r(void 0)}):(ae(n),r(void 0))})}function Nr(e){return V(Me,e,!1)}function Vt(e){return V(sn|De,e,!0)}function Ir(e,n=0){return V(Oe|n,e,!0)}function Fr(e,n=[],t=[],r=[]){It(r,n,t,s=>{V(Oe,()=>e(...s.map(Te)),!0)})}function Cr(e,n=0){var t=V(G|n,e,!0);return t}function Mr(e){return V(U|De,e,!0)}function Zn(e){var n=e.teardown;if(n!==null){const t=ue,r=v;En(!0),W(null);try{n.call(null)}finally{En(t),W(r)}}}function Jn(e,n=!1){var t=e.first;for(e.first=e.last=null;t!==null;){const s=t.ac;s!==null&&Gn(()=>{s.abort(_e)});var r=t.next;t.f&oe?t.parent=null:ae(t,n),t=r}}function Bt(e){for(var n=e.first;n!==null;){var t=n.next;n.f&U||ae(n),n=t}}function ae(e,n=!0){var t=!1;(n||e.f&xn)&&e.nodes!==null&&e.nodes.end!==null&&(Ht(e.nodes.start,e.nodes.end),t=!0),Jn(e,n&&!t),Ue(e,0),y(e,$);var r=e.nodes&&e.nodes.t;if(r!==null)for(const f of r)f.stop();Zn(e);var s=e.parent;s!==null&&s.first!==null&&Wn(e),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=null}function Ht(e,n){for(;e!==null;){var t=e===n?null:X(e);e.remove(),e=t}}function Wn(e){var n=e.parent,t=e.prev,r=e.next;t!==null&&(t.next=r),r!==null&&(r.prev=t),n!==null&&(n.first===e&&(n.first=r),n.last===e&&(n.last=t))}function Gt(e,n,t=!0){var r=[];Xn(e,r,!0);var s=()=>{t&&ae(e),n&&n()},f=r.length;if(f>0){var i=()=>--f||s();for(var u of r)u.out(i)}else s()}function Xn(e,n,t){if(!(e.f&L)){e.f^=L;var r=e.nodes&&e.nodes.t;if(r!==null)for(const u of r)(u.is_global||t)&&n.push(u);for(var s=e.first;s!==null;){var f=s.next,i=(s.f&je)!==0||(s.f&U)!==0&&(e.f&G)!==0;Xn(s,n,i?t:!1),s=f}}}function jr(e){Qn(e,!0)}function Qn(e,n){if(e.f&L){e.f^=L,e.f&E||(y(e,x),H(e));for(var t=e.first;t!==null;){var r=t.next,s=(t.f&je)!==0||(t.f&U)!==0;Qn(t,s?n:!1),t=r}var f=e.nodes&&e.nodes.t;if(f!==null)for(const i of f)(i.is_global||n)&&i.in()}}function Lr(e,n){if(e.nodes)for(var t=e.nodes.start,r=e.nodes.end;t!==null;){var s=t===r?null:X(t);n.append(t),t=s}}let Ce=!1,ue=!1;function En(e){ue=e}let v=null,M=!1;function W(e){v=e}let w=null;function me(e){w=e}let I=null;function et(e){v!==null&&(I===null?I=[e]:I.push(e))}let O=null,D=0,P=null;function Kt(e){P=e}let nt=1,te=0,fe=te;function Tn(e){fe=e}function tt(){return++nt}function Ne(e){var n=e.f;if(n&x)return!0;if(n&A&&(e.f&=~ie),n&q){for(var t=e.deps,r=t.length,s=0;se.wv)return!0}n&N&&b===null&&y(e,E)}return!1}function rt(e,n,t=!0){var r=e.reactions;if(r!==null&&!(I!==null&&we.call(I,e)))for(var s=0;s{e.ac.abort(_e)}),e.ac=null);try{e.f|=$e;var o=e.fn,_=o(),c=e.deps,g=p==null?void 0:p.is_fork;if(O!==null){var h;if(g||Ue(e,D),c!==null&&D>0)for(c.length=D+O.length,h=0;h",""),n.content}function t(r,n){var e=l;e.nodes===null&&(e.nodes={start:r,end:n,a:null,t:null})}function M(r,n){var e=(n&p)!==0,_=(n&T)!==0,a,m=!r.startsWith("");return()=>{if(d)return t(o,null),o;a===void 0&&(a=w(m?r:""+r),e||(a=f(a)));var s=_||E?document.importNode(a,!0):a.cloneNode(!0);if(e){var c=f(s),v=s.lastChild;t(c,v)}else t(s,s);return s}}function F(r=""){if(!d){var n=i(r+"");return t(n,n),n}var e=o;return e.nodeType!==x?(e.before(e=i()),y(e)):N(e),t(e,e),e}function L(){if(d)return t(o,null),o;var r=document.createDocumentFragment(),n=document.createComment(""),e=i();return r.append(n,e),t(n,e),r}function O(r,n){if(d){var e=l;(!(e.f&h)||e.nodes.end===null)&&(e.nodes.end=o),g();return}r!==null&&r.before(n)}const A="5";var u;typeof window<"u"&&((u=window.__svelte??(window.__svelte={})).v??(u.v=new Set)).add(A);export{O as a,t as b,L as c,M as f,F as t}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js deleted file mode 100644 index e23b8da..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/CE0Ev3WY.js +++ /dev/null @@ -1 +0,0 @@ -import{u as o,c as t,l as c,b as u}from"./B_PiQ68N.js";function l(n){throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function r(n){t===null&&l(),c&&t.l!==null?a(t).m.push(n):o(()=>{const e=u(n);if(typeof e=="function")return e})}function a(n){var e=n.l;return e.u??(e.u={a:[],b:[],m:[]})}export{r as o}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js deleted file mode 100644 index fa3c840..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/Csl9sg0z.js +++ /dev/null @@ -1 +0,0 @@ -import{e}from"./B_PiQ68N.js";e(); diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js deleted file mode 100644 index a071743..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/chunks/jjmyhcpZ.js +++ /dev/null @@ -1,2 +0,0 @@ -var De=Object.defineProperty;var ue=s=>{throw TypeError(s)};var ke=(s,e,i)=>e in s?De(s,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):s[e]=i;var Z=(s,e,i)=>ke(s,typeof e!="symbol"?e+"":e,i),ee=(s,e,i)=>e.has(s)||ue("Cannot "+i);var t=(s,e,i)=>(ee(s,e,"read from private field"),i?i.call(s):e.get(s)),h=(s,e,i)=>e.has(s)?ue("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(s):e.set(s,i),n=(s,e,i,a)=>(ee(s,e,"write to private field"),a?a.call(s,i):e.set(s,i),i),c=(s,e,i)=>(ee(s,e,"access private method"),i);import{D as Ae,i as me,F as Oe,G as be,b as Fe,H as _e,I as j,z as A,h as O,v as H,J as Ye,K as k,L as te,M as se,q as Ee,N as Ie,O as G,P as J,Q as de,R as Me,S as Te,c as we,U as Be,V as ce,W as Ce,X as pe,Y as Le,Z as Pe,_ as ie,B as K,$ as Ve,a0 as He,a1 as ge,a2 as qe,a3 as xe,a as We,a4 as oe,a5 as $e,a6 as je,a7 as Ue,a8 as ze,a9 as Ge,aa as re,w as Je,ab as Ke,ac as Qe,ad as ne,ae as W,af as Xe,ag as Ze,ah as et,ai as tt,p as st,aj as it,ak as rt,m as nt}from"./B_PiQ68N.js";import{b as at}from"./C8WMVNin.js";function ht(s){let e=0,i=be(0),a;return()=>{Ae()&&(me(i),Oe(()=>(e===0&&(a=Fe(()=>s(()=>_e(i)))),e+=1,()=>{j(()=>{e-=1,e===0&&(a==null||a(),a=void 0,_e(i))})})))}}var ft=je|Ue|ze;function ot(s,e,i){new lt(s,e,i)}var p,q,y,F,m,v,d,b,w,N,Y,R,C,I,L,P,S,Q,f,Re,Se,ae,U,z,he;class lt{constructor(e,i,a){h(this,f);Z(this,"parent");Z(this,"is_pending",!1);h(this,p);h(this,q,O?A:null);h(this,y);h(this,F);h(this,m);h(this,v,null);h(this,d,null);h(this,b,null);h(this,w,null);h(this,N,null);h(this,Y,0);h(this,R,0);h(this,C,!1);h(this,I,!1);h(this,L,new Set);h(this,P,new Set);h(this,S,null);h(this,Q,ht(()=>(n(this,S,be(t(this,Y))),()=>{n(this,S,null)})));n(this,p,e),n(this,y,i),n(this,F,a),this.parent=H.b,this.is_pending=!!t(this,y).pending,n(this,m,Ye(()=>{if(H.b=this,O){const r=t(this,q);We(),r.nodeType===oe&&r.data===$e?c(this,f,Se).call(this):(c(this,f,Re).call(this),t(this,R)===0&&(this.is_pending=!1))}else{var l=c(this,f,ae).call(this);try{n(this,v,k(()=>a(l)))}catch(r){this.error(r)}t(this,R)>0?c(this,f,z).call(this):this.is_pending=!1}return()=>{var r;(r=t(this,N))==null||r.remove()}},ft)),O&&n(this,p,A)}defer_effect(e){Ie(e,t(this,L),t(this,P))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!t(this,y).pending}update_pending_count(e){c(this,f,he).call(this,e),n(this,Y,t(this,Y)+e),!(!t(this,S)||t(this,C))&&(n(this,C,!0),j(()=>{n(this,C,!1),t(this,S)&&Pe(t(this,S),t(this,Y))}))}get_effect_pending(){return t(this,Q).call(this),me(t(this,S))}error(e){var i=t(this,y).onerror;let a=t(this,y).failed;if(t(this,I)||!i&&!a)throw e;t(this,v)&&(ie(t(this,v)),n(this,v,null)),t(this,d)&&(ie(t(this,d)),n(this,d,null)),t(this,b)&&(ie(t(this,b)),n(this,b,null)),O&&(K(t(this,q)),Ve(),K(He()));var l=!1,r=!1;const _=()=>{if(l){xe();return}l=!0,r&&qe(),te.ensure(),n(this,Y,0),t(this,b)!==null&&se(t(this,b),()=>{n(this,b,null)}),this.is_pending=this.has_pending_snippet(),n(this,v,c(this,f,U).call(this,()=>(n(this,I,!1),k(()=>t(this,F).call(this,t(this,p)))))),t(this,R)>0?c(this,f,z).call(this):this.is_pending=!1};j(()=>{try{r=!0,i==null||i(e,_),r=!1}catch(g){ge(g,t(this,m)&&t(this,m).parent)}a&&n(this,b,c(this,f,U).call(this,()=>{te.ensure(),n(this,I,!0);try{return k(()=>{a(t(this,p),()=>e,()=>_)})}catch(g){return ge(g,t(this,m).parent),null}finally{n(this,I,!1)}}))})}}p=new WeakMap,q=new WeakMap,y=new WeakMap,F=new WeakMap,m=new WeakMap,v=new WeakMap,d=new WeakMap,b=new WeakMap,w=new WeakMap,N=new WeakMap,Y=new WeakMap,R=new WeakMap,C=new WeakMap,I=new WeakMap,L=new WeakMap,P=new WeakMap,S=new WeakMap,Q=new WeakMap,f=new WeakSet,Re=function(){try{n(this,v,k(()=>t(this,F).call(this,t(this,p))))}catch(e){this.error(e)}},Se=function(){const e=t(this,y).pending;e&&(n(this,d,k(()=>e(t(this,p)))),j(()=>{var i=c(this,f,ae).call(this);n(this,v,c(this,f,U).call(this,()=>(te.ensure(),k(()=>t(this,F).call(this,i))))),t(this,R)>0?c(this,f,z).call(this):(se(t(this,d),()=>{n(this,d,null)}),this.is_pending=!1)}))},ae=function(){var e=t(this,p);return this.is_pending&&(n(this,N,Ee()),t(this,p).before(t(this,N)),e=t(this,N)),e},U=function(e){var i=H,a=Te,l=we;G(t(this,m)),J(t(this,m)),de(t(this,m).ctx);try{return e()}catch(r){return Me(r),null}finally{G(i),J(a),de(l)}},z=function(){const e=t(this,y).pending;t(this,v)!==null&&(n(this,w,document.createDocumentFragment()),t(this,w).append(t(this,N)),Be(t(this,v),t(this,w))),t(this,d)===null&&n(this,d,k(()=>e(t(this,p))))},he=function(e){var i;if(!this.has_pending_snippet()){this.parent&&c(i=this.parent,f,he).call(i,e);return}if(n(this,R,t(this,R)+e),t(this,R)===0){this.is_pending=!1;for(const a of t(this,L))ce(a,Ce),pe(a);for(const a of t(this,P))ce(a,Le),pe(a);t(this,L).clear(),t(this,P).clear(),t(this,d)&&se(t(this,d),()=>{n(this,d,null)}),t(this,w)&&(t(this,p).before(t(this,w)),n(this,w,null))}};const ut=["touchstart","touchmove"];function _t(s){return ut.includes(s)}const dt=new Set,ve=new Set;let ye=null;function $(s){var le;var e=this,i=e.ownerDocument,a=s.type,l=((le=s.composedPath)==null?void 0:le.call(s))||[],r=l[0]||s.target;ye=s;var _=0,g=ye===s&&s.__root;if(g){var D=l.indexOf(g);if(D!==-1&&(e===document||e===window)){s.__root=e;return}var M=l.indexOf(e);if(M===-1)return;D<=M&&(_=D)}if(r=l[_]||s.target,r!==e){Ge(s,"currentTarget",{configurable:!0,get(){return r||i}});var X=Te,E=H;J(null),G(null);try{for(var o,u=[];r!==null;){var T=r.assignedSlot||r.parentNode||r.host||null;try{var V=r["__"+a];V!=null&&(!r.disabled||s.target===r)&&V.call(r,s)}catch(x){o?u.push(x):o=x}if(s.cancelBubble||T===e||T===null)break;r=T}if(o){for(let x of u)queueMicrotask(()=>{throw x});throw o}}finally{s.__root=e,delete s.currentTarget,J(X),G(E)}}}function yt(s,e){var i=e==null?"":typeof e=="object"?e+"":e;i!==(s.__t??(s.__t=s.nodeValue))&&(s.__t=i,s.nodeValue=i+"")}function ct(s,e){return Ne(s,e)}function mt(s,e){re(),e.intro=e.intro??!1;const i=e.target,a=O,l=A;try{for(var r=Je(i);r&&(r.nodeType!==oe||r.data!==Ke);)r=Qe(r);if(!r)throw ne;W(!0),K(r);const _=Ne(s,{...e,anchor:r});return W(!1),_}catch(_){if(_ instanceof Error&&_.message.split(` -`).some(g=>g.startsWith("https://svelte.dev/e/")))throw _;return _!==ne&&console.warn("Failed to hydrate: ",_),e.recover===!1&&Xe(),re(),Ze(i),W(!1),ct(s,e)}finally{W(a),K(l)}}const B=new Map;function Ne(s,{target:e,anchor:i,props:a={},events:l,context:r,intro:_=!0}){re();var g=new Set,D=E=>{for(var o=0;o{var E=i??e.appendChild(Ee());return ot(E,{pending:()=>{}},o=>{st({});var u=we;if(r&&(u.c=r),l&&(a.$$events=l),O&&at(o,null),M=s(o,a)||{},O&&(H.nodes.end=A,A===null||A.nodeType!==oe||A.data!==it))throw rt(),ne;nt()}),()=>{var T;for(var o of g){e.removeEventListener(o,$);var u=B.get(o);--u===0?(document.removeEventListener(o,$),B.delete(o)):B.set(o,u)}ve.delete(D),E!==i&&((T=E.parentNode)==null||T.removeChild(E))}});return fe.set(M,X),M}let fe=new WeakMap;function bt(s,e){const i=fe.get(s);return i?(fe.delete(s),i(e)):Promise.resolve()}export{mt as h,ct as m,yt as s,bt as u}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js deleted file mode 100644 index d58ecbd..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/app.CpUzidFU.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["../nodes/0.Cc7SJR4r.js","../chunks/C8WMVNin.js","../chunks/B_PiQ68N.js","../chunks/Csl9sg0z.js","../nodes/1.DcKD0893.js","../chunks/jjmyhcpZ.js","../chunks/BShzwfeu.js","../chunks/CE0Ev3WY.js","../nodes/2.BFij7fXI.js","../assets/2.Cwfcd7nv.css"])))=>i.map(i=>d[i]); -var ye=Object.defineProperty;var X=t=>{throw TypeError(t)};var Ee=(t,e,r)=>e in t?ye(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var $=(t,e,r)=>Ee(t,typeof e!="symbol"?e+"":e,r),ee=(t,e,r)=>e.has(t)||X("Cannot "+r);var n=(t,e,r)=>(ee(t,e,"read from private field"),r?r.call(t):e.get(t)),w=(t,e,r)=>e.has(t)?X("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),M=(t,e,r,i)=>(ee(t,e,"write to private field"),i?i.call(t,r):e.set(t,r),r);import{al as te,am as Pe,_ as z,M as Se,q as re,K as se,h as U,z as Re,U as we,an as Ae,a as ce,J as oe,a6 as fe,ao as Oe,a5 as ke,a0 as Ie,B as Te,ae,ap as xe,F as Le,b as ue,I as De,aq as le,ar as Be,as as Ce,at as je,i as E,au as Me,av as D,aw as qe,v as Fe,ax as Ue,ay as Ne,l as Ye,az as ze,aA as Ve,k as pe,aB as Ge,aC as He,aD as de,aE as Je,a9 as Ke,aF as We,p as Ze,d as Qe,u as Xe,aG as $e,f as q,s as et,m as tt,aH as V,n as rt,o as st,t as at,aI as p}from"../chunks/B_PiQ68N.js";import{h as nt,m as it,u as ct,s as ot}from"../chunks/jjmyhcpZ.js";import{a as x,f as he,c as G,t as ft}from"../chunks/C8WMVNin.js";import{o as ut}from"../chunks/CE0Ev3WY.js";var S,A,b,T,B,C,N;class _e{constructor(e,r=!0){$(this,"anchor");w(this,S,new Map);w(this,A,new Map);w(this,b,new Map);w(this,T,new Set);w(this,B,!0);w(this,C,()=>{var e=te;if(n(this,S).has(e)){var r=n(this,S).get(e),i=n(this,A).get(r);if(i)Pe(i),n(this,T).delete(r);else{var c=n(this,b).get(r);c&&(n(this,A).set(r,c.effect),n(this,b).delete(r),c.fragment.lastChild.remove(),this.anchor.before(c.fragment),i=c.effect)}for(const[o,a]of n(this,S)){if(n(this,S).delete(o),o===e)break;const s=n(this,b).get(a);s&&(z(s.effect),n(this,b).delete(a))}for(const[o,a]of n(this,A)){if(o===r||n(this,T).has(o))continue;const s=()=>{if(Array.from(n(this,S).values()).includes(o)){var l=document.createDocumentFragment();we(a,l),l.append(re()),n(this,b).set(o,{effect:a,fragment:l})}else z(a);n(this,T).delete(o),n(this,A).delete(o)};n(this,B)||!i?(n(this,T).add(o),Se(a,s,!1)):s()}}});w(this,N,e=>{n(this,S).delete(e);const r=Array.from(n(this,S).values());for(const[i,c]of n(this,b))r.includes(i)||(z(c.effect),n(this,b).delete(i))});this.anchor=e,M(this,B,r)}ensure(e,r){var i=te,c=Ae();if(r&&!n(this,A).has(e)&&!n(this,b).has(e))if(c){var o=document.createDocumentFragment(),a=re();o.append(a),n(this,b).set(e,{effect:se(()=>r(a)),fragment:o})}else n(this,A).set(e,se(()=>r(this.anchor)));if(n(this,S).set(i,e),c){for(const[s,f]of n(this,A))s===e?i.unskip_effect(f):i.skip_effect(f);for(const[s,f]of n(this,b))s===e?i.unskip_effect(f.effect):i.skip_effect(f.effect);i.oncommit(n(this,C)),i.ondiscard(n(this,N))}else U&&(this.anchor=Re),n(this,C).call(this)}}S=new WeakMap,A=new WeakMap,b=new WeakMap,T=new WeakMap,B=new WeakMap,C=new WeakMap,N=new WeakMap;function H(t,e,r=!1){U&&ce();var i=new _e(t),c=r?fe:0;function o(a,s){if(U){const l=Oe(t)===ke;if(a===l){var f=Ie();Te(f),i.anchor=f,ae(!1),i.ensure(a,s),ae(!0);return}}i.ensure(a,s)}oe(()=>{var a=!1;e((s,f=!0)=>{a=!0,o(f,s)}),a||o(!1,null)},c)}function J(t,e,r){U&&ce();var i=new _e(t);oe(()=>{var c=e()??null;i.ensure(c,c&&(o=>r(o,c)))},fe)}function ne(t,e){return t===e||(t==null?void 0:t[le])===e}function K(t={},e,r,i){return xe(()=>{var c,o;return Le(()=>{c=o,o=[],ue(()=>{t!==r(...o)&&(e(t,...o),c&&ne(r(...c),t)&&e(null,...c))})}),()=>{De(()=>{o&&ne(r(...o),t)&&e(null,...o)})}}),t}let F=!1;function lt(t){var e=F;try{return F=!1,[t(),F]}finally{F=e}}function W(t,e,r,i){var R;var c=!Ye||(r&ze)!==0,o=(r&Ne)!==0,a=(r&He)!==0,s=i,f=!0,l=()=>(f&&(f=!1,s=a?ue(i):i),s),_;if(o){var L=le in t||de in t;_=((R=Be(t,e))==null?void 0:R.set)??(L&&e in t?u=>t[e]=u:void 0)}var k,m=!1;o?[k,m]=lt(()=>t[e]):k=t[e],k===void 0&&i!==void 0&&(k=l(),_&&(c&&Ce(),_(k)));var v;if(c?v=()=>{var u=t[e];return u===void 0?l():(f=!0,u)}:v=()=>{var u=t[e];return u!==void 0&&(s=void 0),u===void 0?s:u},c&&!(r&je))return v;if(_){var d=t.$$legacy;return function(u,h){return arguments.length>0?((!c||!h||d||m)&&_(h?v():u),u):v()}}var P=!1,g=(r&Ve?pe:Ge)(()=>(P=!1,v()));o&&E(g);var I=Fe;return function(u,h){if(arguments.length>0){const Y=h?E(g):c&&o?Me(u):u;return D(g,Y),P=!0,s!==void 0&&(s=Y),u}return qe&&P||I.f&Ue?g.v:E(g)}}function dt(t){return class extends ht{constructor(e){super({component:t,...e})}}}var O,y;class ht{constructor(e){w(this,O);w(this,y);var o;var r=new Map,i=(a,s)=>{var f=We(s,!1,!1);return r.set(a,f),f};const c=new Proxy({...e.props||{},$$events:{}},{get(a,s){return E(r.get(s)??i(s,Reflect.get(a,s)))},has(a,s){return s===de?!0:(E(r.get(s)??i(s,Reflect.get(a,s))),Reflect.has(a,s))},set(a,s,f){return D(r.get(s)??i(s,f),f),Reflect.set(a,s,f)}});M(this,y,(e.hydrate?nt:it)(e.component,{target:e.target,anchor:e.anchor,props:c,context:e.context,intro:e.intro??!1,recover:e.recover})),(!((o=e==null?void 0:e.props)!=null&&o.$$host)||e.sync===!1)&&Je(),M(this,O,c.$$events);for(const a of Object.keys(n(this,y)))a==="$set"||a==="$destroy"||a==="$on"||Ke(this,a,{get(){return n(this,y)[a]},set(s){n(this,y)[a]=s},enumerable:!0});n(this,y).$set=a=>{Object.assign(c,a)},n(this,y).$destroy=()=>{ct(n(this,y))}}$set(e){n(this,y).$set(e)}$on(e,r){n(this,O)[e]=n(this,O)[e]||[];const i=(...c)=>r.call(this,...c);return n(this,O)[e].push(i),()=>{n(this,O)[e]=n(this,O)[e].filter(c=>c!==i)}}$destroy(){n(this,y).$destroy()}}O=new WeakMap,y=new WeakMap;const _t="modulepreload",vt=function(t,e){return new URL(t,e).href},ie={},Z=function(e,r,i){let c=Promise.resolve();if(r&&r.length>0){const a=document.getElementsByTagName("link"),s=document.querySelector("meta[property=csp-nonce]"),f=(s==null?void 0:s.nonce)||(s==null?void 0:s.getAttribute("nonce"));c=Promise.allSettled(r.map(l=>{if(l=vt(l,i),l in ie)return;ie[l]=!0;const _=l.endsWith(".css"),L=_?'[rel="stylesheet"]':"";if(!!i)for(let v=a.length-1;v>=0;v--){const d=a[v];if(d.href===l&&(!_||d.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${l}"]${L}`))return;const m=document.createElement("link");if(m.rel=_?"stylesheet":_t,_||(m.as="script"),m.crossOrigin="",m.href=l,f&&m.setAttribute("nonce",f),document.head.appendChild(m),_)return new Promise((v,d)=>{m.addEventListener("load",v),m.addEventListener("error",()=>d(new Error(`Unable to preload CSS for ${l}`)))})}))}function o(a){const s=new Event("vite:preloadError",{cancelable:!0});if(s.payload=a,window.dispatchEvent(s),!s.defaultPrevented)throw a}return c.then(a=>{for(const s of a||[])s.status==="rejected"&&o(s.reason);return e().catch(o)})},At={};var mt=he('
'),gt=he(" ",1);function bt(t,e){Ze(e,!0);let r=W(e,"components",23,()=>[]),i=W(e,"data_0",3,null),c=W(e,"data_1",3,null);Qe(()=>e.stores.page.set(e.page)),Xe(()=>{e.stores,e.page,e.constructors,r(),e.form,i(),c(),e.stores.page.notify()});let o=V(!1),a=V(!1),s=V(null);ut(()=>{const d=e.stores.page.subscribe(()=>{E(o)&&(D(a,!0),$e().then(()=>{D(s,document.title||"untitled page",!0)}))});return D(o,!0),d});const f=p(()=>e.constructors[1]);var l=gt(),_=q(l);{var L=d=>{const P=p(()=>e.constructors[0]);var g=G(),I=q(g);J(I,()=>E(P),(R,u)=>{K(u(R,{get data(){return i()},get form(){return e.form},get params(){return e.page.params},children:(h,Y)=>{var Q=G(),me=q(Q);J(me,()=>E(f),(ge,be)=>{K(be(ge,{get data(){return c()},get form(){return e.form},get params(){return e.page.params}}),j=>r()[1]=j,()=>{var j;return(j=r())==null?void 0:j[1]})}),x(h,Q)},$$slots:{default:!0}}),h=>r()[0]=h,()=>{var h;return(h=r())==null?void 0:h[0]})}),x(d,g)},k=d=>{const P=p(()=>e.constructors[0]);var g=G(),I=q(g);J(I,()=>E(P),(R,u)=>{K(u(R,{get data(){return i()},get form(){return e.form},get params(){return e.page.params}}),h=>r()[0]=h,()=>{var h;return(h=r())==null?void 0:h[0]})}),x(d,g)};H(_,d=>{e.constructors[1]?d(L):d(k,!1)})}var m=et(_,2);{var v=d=>{var P=mt(),g=rt(P);{var I=R=>{var u=ft();at(()=>ot(u,E(s))),x(R,u)};H(g,R=>{E(a)&&R(I)})}st(P),x(d,P)};H(m,d=>{E(o)&&d(v)})}x(t,l),tt()}const Ot=dt(bt),kt=[()=>Z(()=>import("../nodes/0.Cc7SJR4r.js"),__vite__mapDeps([0,1,2,3]),import.meta.url),()=>Z(()=>import("../nodes/1.DcKD0893.js"),__vite__mapDeps([4,1,2,3,5,6,7]),import.meta.url),()=>Z(()=>import("../nodes/2.BFij7fXI.js"),__vite__mapDeps([8,1,2,3,9]),import.meta.url)],It=[],Tt={"/":[2]},ve={handleError:({error:t})=>{console.error(t)},reroute:()=>{},transport:{}},yt=Object.fromEntries(Object.entries(ve.transport).map(([t,e])=>[t,e.decode])),xt=Object.fromEntries(Object.entries(ve.transport).map(([t,e])=>[t,e.encode])),Lt=!1,Dt=(t,e)=>yt[t](e);export{Dt as decode,yt as decoders,Tt as dictionary,xt as encoders,Lt as hash,ve as hooks,At as matchers,kt as nodes,Ot as root,It as server_loads}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js deleted file mode 100644 index 0d629ba..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/entry/start.T22yjXU7.js +++ /dev/null @@ -1 +0,0 @@ -import{l as o,a as r}from"../chunks/BShzwfeu.js";export{o as load_css,r as start}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js deleted file mode 100644 index 5725fba..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/0.Cc7SJR4r.js +++ /dev/null @@ -1 +0,0 @@ -import{c as o,a as s}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";import{h as l,a as d,f as m}from"../chunks/B_PiQ68N.js";function c(f,a,t,e,u){var i;l&&d();var n=(i=a.$$slots)==null?void 0:i[t],r=!1;n===!0&&(n=a.children,r=!0),n===void 0||n(f,r?()=>e:e)}function v(f,a){var t=o(),e=m(t);c(e,a,"default",{}),s(f,t)}export{v as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js deleted file mode 100644 index 116149e..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/1.DcKD0893.js +++ /dev/null @@ -1 +0,0 @@ -import{a as b,f as k}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";import{c as x,d as $,u as i,b as y,r as l,g as j,i as v,j as E,k as q,p as w,f as z,t as A,m as B,n as u,o as m,s as C}from"../chunks/B_PiQ68N.js";import{s as g}from"../chunks/jjmyhcpZ.js";import{s as D,p as _}from"../chunks/BShzwfeu.js";function F(a=!1){const e=x,t=e.l.u;if(!t)return;let r=()=>E(e.s);if(a){let o=0,s={};const p=q(()=>{let n=!1;const c=e.s;for(const f in c)c[f]!==s[f]&&(s[f]=c[f],n=!0);return n&&o++,o});r=()=>v(p)}t.b.length&&$(()=>{d(e,r),l(t.b)}),i(()=>{const o=y(()=>t.m.map(j));return()=>{for(const s of o)typeof s=="function"&&s()}}),t.a.length&&i(()=>{d(e,r),l(t.a)})}function d(a,e){if(a.l.s)for(const t of a.l.s)v(t);e()}const G={get error(){return _.error},get status(){return _.status}};D.updated.check;const h=G;var H=k("

",1);function N(a,e){w(e,!1),F();var t=H(),r=z(t),o=u(r,!0);m(r);var s=C(r,2),p=u(s,!0);m(s),A(()=>{var n;g(o,h.status),g(p,(n=h.error)==null?void 0:n.message)}),b(a,t),B()}export{N as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js deleted file mode 100644 index 58828a4..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/immutable/nodes/2.BFij7fXI.js +++ /dev/null @@ -1 +0,0 @@ -import{a as s,f as t}from"../chunks/C8WMVNin.js";import"../chunks/Csl9sg0z.js";var i=t('

Welcome to SvelteKit

This is a minimal SvelteKit application.

');function n(a){var e=i();s(a,e)}export{n as component}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json deleted file mode 100644 index 88188f8..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/client/_app/version.json +++ /dev/null @@ -1 +0,0 @@ -{"version":"1770671592599"} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json deleted file mode 100644 index ea6666b..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/.vite/manifest.json +++ /dev/null @@ -1,119 +0,0 @@ -{ - ".svelte-kit/generated/server/internal.js": { - "file": "internal.js", - "name": "internal", - "src": ".svelte-kit/generated/server/internal.js", - "isEntry": true, - "imports": [ - "_internal.js", - "_environment.js" - ] - }, - "_context.js": { - "file": "chunks/context.js", - "name": "context" - }, - "_environment.js": { - "file": "chunks/environment.js", - "name": "environment" - }, - "_equality.js": { - "file": "chunks/equality.js", - "name": "equality" - }, - "_exports.js": { - "file": "chunks/exports.js", - "name": "exports", - "imports": [ - "_context.js", - "_equality.js" - ] - }, - "_index.js": { - "file": "chunks/index.js", - "name": "index", - "imports": [ - "_context.js", - "_utils2.js" - ] - }, - "_internal.js": { - "file": "chunks/internal.js", - "name": "internal", - "imports": [ - "_index.js", - "_environment.js", - "_context.js", - "_equality.js" - ] - }, - "_shared.js": { - "file": "chunks/shared.js", - "name": "shared", - "imports": [ - "_utils.js", - "_utils2.js" - ] - }, - "_utils.js": { - "file": "chunks/utils.js", - "name": "utils" - }, - "_utils2.js": { - "file": "chunks/utils2.js", - "name": "utils" - }, - "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/app/server/remote/index.js": { - "file": "remote-entry.js", - "name": "remote-entry", - "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/app/server/remote/index.js", - "isEntry": true, - "imports": [ - "_shared.js", - "_environment.js" - ] - }, - "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte": { - "file": "entries/fallbacks/error.svelte.js", - "name": "entries/fallbacks/error.svelte", - "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/components/svelte-5/error.svelte", - "isEntry": true, - "imports": [ - "_context.js", - "_exports.js", - "_utils.js" - ] - }, - "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/server/index.js": { - "file": "index.js", - "name": "index", - "src": "node_modules/.pnpm/@sveltejs+kit@2.50.2_@sveltejs+vite-plugin-svelte@4.0.4_svelte@5.50.0_vite@5.4.21__svel_602216b61db0b7ab394bc72da2e3f4cb/node_modules/@sveltejs/kit/src/runtime/server/index.js", - "isEntry": true, - "imports": [ - "_environment.js", - "_shared.js", - "_index.js", - "_exports.js", - "_utils.js", - "_internal.js" - ] - }, - "src/routes/+layout.svelte": { - "file": "entries/pages/_layout.svelte.js", - "name": "entries/pages/_layout.svelte", - "src": "src/routes/+layout.svelte", - "isEntry": true, - "imports": [ - "_index.js" - ] - }, - "src/routes/+page.svelte": { - "file": "entries/pages/_page.svelte.js", - "name": "entries/pages/_page.svelte", - "src": "src/routes/+page.svelte", - "isEntry": true, - "css": [ - "_app/immutable/assets/_page.Cwfcd7nv.css" - ] - } -} \ No newline at end of file diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css deleted file mode 100644 index bd4f0b4..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/_app/immutable/assets/_page.Cwfcd7nv.css +++ /dev/null @@ -1 +0,0 @@ -main.svelte-1uha8ag{padding:2rem;font-family:system-ui,-apple-system,sans-serif}h1.svelte-1uha8ag{color:#333}nav.svelte-1uha8ag{margin-top:2rem}a.svelte-1uha8ag{color:#06c;text-decoration:none}a.svelte-1uha8ag:hover{text-decoration:underline} diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js deleted file mode 100644 index 989c4e5..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/context.js +++ /dev/null @@ -1,109 +0,0 @@ -var is_array = Array.isArray; -var index_of = Array.prototype.indexOf; -var includes = Array.prototype.includes; -var array_from = Array.from; -var define_property = Object.defineProperty; -var get_descriptor = Object.getOwnPropertyDescriptor; -var object_prototype = Object.prototype; -var array_prototype = Array.prototype; -var get_prototype_of = Object.getPrototypeOf; -var is_extensible = Object.isExtensible; -const noop = () => { -}; -function run_all(arr) { - for (var i = 0; i < arr.length; i++) { - arr[i](); - } -} -function deferred() { - var resolve; - var reject; - var promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve, reject }; -} -function lifecycle_outside_component(name) { - { - throw new Error(`https://svelte.dev/e/lifecycle_outside_component`); - } -} -const ATTR_REGEX = /[&"<]/g; -const CONTENT_REGEX = /[&<]/g; -function escape_html(value, is_attr) { - const str = String(value ?? ""); - const pattern = is_attr ? ATTR_REGEX : CONTENT_REGEX; - pattern.lastIndex = 0; - let escaped = ""; - let last = 0; - while (pattern.test(str)) { - const i = pattern.lastIndex - 1; - const ch = str[i]; - escaped += str.substring(last, i) + (ch === "&" ? "&" : ch === '"' ? """ : "<"); - last = i + 1; - } - return escaped + str.substring(last); -} -var ssr_context = null; -function set_ssr_context(v) { - ssr_context = v; -} -function getContext(key) { - const context_map = get_or_init_context_map(); - const result = ( - /** @type {T} */ - context_map.get(key) - ); - return result; -} -function setContext(key, context) { - get_or_init_context_map().set(key, context); - return context; -} -function get_or_init_context_map(name) { - if (ssr_context === null) { - lifecycle_outside_component(); - } - return ssr_context.c ??= new Map(get_parent_context(ssr_context) || void 0); -} -function push(fn) { - ssr_context = { p: ssr_context, c: null, r: null }; -} -function pop() { - ssr_context = /** @type {SSRContext} */ - ssr_context.p; -} -function get_parent_context(ssr_context2) { - let parent = ssr_context2.p; - while (parent !== null) { - const context_map = parent.c; - if (context_map !== null) { - return context_map; - } - parent = parent.p; - } - return null; -} -export { - array_prototype as a, - get_prototype_of as b, - is_array as c, - deferred as d, - is_extensible as e, - index_of as f, - get_descriptor as g, - define_property as h, - includes as i, - array_from as j, - escape_html as k, - set_ssr_context as l, - ssr_context as m, - noop as n, - object_prototype as o, - push as p, - pop as q, - run_all as r, - setContext as s, - getContext as t -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js deleted file mode 100644 index 421fed0..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/environment.js +++ /dev/null @@ -1,36 +0,0 @@ -const BROWSER = false; -let base = ""; -let assets = base; -const app_dir = "_app"; -const relative = true; -const initial = { base, assets }; -function override(paths) { - base = paths.base; - assets = paths.assets; -} -function reset() { - base = initial.base; - assets = initial.assets; -} -function set_assets(path) { - assets = initial.assets = path; -} -let prerendering = false; -function set_building() { -} -function set_prerendering() { - prerendering = true; -} -export { - BROWSER as B, - assets as a, - base as b, - app_dir as c, - reset as d, - set_building as e, - set_prerendering as f, - override as o, - prerendering as p, - relative as r, - set_assets as s -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js deleted file mode 100644 index 3c6fc90..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/equality.js +++ /dev/null @@ -1,14 +0,0 @@ -function equals(value) { - return value === this.v; -} -function safe_not_equal(a, b) { - return a != a ? b == b : a !== b || a !== null && typeof a === "object" || typeof a === "function"; -} -function safe_equals(value) { - return !safe_not_equal(value, this.v); -} -export { - safe_not_equal as a, - equals as e, - safe_equals as s -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js deleted file mode 100644 index 6f03fa9..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/exports.js +++ /dev/null @@ -1,231 +0,0 @@ -import { n as noop } from "./context.js"; -import { a as safe_not_equal } from "./equality.js"; -const SCHEME = /^[a-z][a-z\d+\-.]+:/i; -const internal = new URL("sveltekit-internal://"); -function resolve(base, path) { - if (path[0] === "/" && path[1] === "/") return path; - let url = new URL(base, internal); - url = new URL(path, url); - return url.protocol === internal.protocol ? url.pathname + url.search + url.hash : url.href; -} -function normalize_path(path, trailing_slash) { - if (path === "/" || trailing_slash === "ignore") return path; - if (trailing_slash === "never") { - return path.endsWith("/") ? path.slice(0, -1) : path; - } else if (trailing_slash === "always" && !path.endsWith("/")) { - return path + "/"; - } - return path; -} -function decode_pathname(pathname) { - return pathname.split("%25").map(decodeURI).join("%25"); -} -function decode_params(params) { - for (const key in params) { - params[key] = decodeURIComponent(params[key]); - } - return params; -} -function make_trackable(url, callback, search_params_callback, allow_hash = false) { - const tracked = new URL(url); - Object.defineProperty(tracked, "searchParams", { - value: new Proxy(tracked.searchParams, { - get(obj, key) { - if (key === "get" || key === "getAll" || key === "has") { - return (param, ...rest) => { - search_params_callback(param); - return obj[key](param, ...rest); - }; - } - callback(); - const value = Reflect.get(obj, key); - return typeof value === "function" ? value.bind(obj) : value; - } - }), - enumerable: true, - configurable: true - }); - const tracked_url_properties = ["href", "pathname", "search", "toString", "toJSON"]; - if (allow_hash) tracked_url_properties.push("hash"); - for (const property of tracked_url_properties) { - Object.defineProperty(tracked, property, { - get() { - callback(); - return url[property]; - }, - enumerable: true, - configurable: true - }); - } - { - tracked[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { - return inspect(url, opts); - }; - tracked.searchParams[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { - return inspect(url.searchParams, opts); - }; - } - if (!allow_hash) { - disable_hash(tracked); - } - return tracked; -} -function disable_hash(url) { - allow_nodejs_console_log(url); - Object.defineProperty(url, "hash", { - get() { - throw new Error( - "Cannot access event.url.hash. Consider using `page.url.hash` inside a component instead" - ); - } - }); -} -function disable_search(url) { - allow_nodejs_console_log(url); - for (const property of ["search", "searchParams"]) { - Object.defineProperty(url, property, { - get() { - throw new Error(`Cannot access url.${property} on a page with prerendering enabled`); - } - }); - } -} -function allow_nodejs_console_log(url) { - { - url[Symbol.for("nodejs.util.inspect.custom")] = (depth, opts, inspect) => { - return inspect(new URL(url), opts); - }; - } -} -const subscriber_queue = []; -function readable(value, start) { - return { - subscribe: writable(value, start).subscribe - }; -} -function writable(value, start = noop) { - let stop = null; - const subscribers = /* @__PURE__ */ new Set(); - function set(new_value) { - if (safe_not_equal(value, new_value)) { - value = new_value; - if (stop) { - const run_queue = !subscriber_queue.length; - for (const subscriber of subscribers) { - subscriber[1](); - subscriber_queue.push(subscriber, value); - } - if (run_queue) { - for (let i = 0; i < subscriber_queue.length; i += 2) { - subscriber_queue[i][0](subscriber_queue[i + 1]); - } - subscriber_queue.length = 0; - } - } - } - } - function update(fn) { - set(fn( - /** @type {T} */ - value - )); - } - function subscribe(run, invalidate = noop) { - const subscriber = [run, invalidate]; - subscribers.add(subscriber); - if (subscribers.size === 1) { - stop = start(set, update) || noop; - } - run( - /** @type {T} */ - value - ); - return () => { - subscribers.delete(subscriber); - if (subscribers.size === 0 && stop) { - stop(); - stop = null; - } - }; - } - return { set, update, subscribe }; -} -function validator(expected) { - function validate(module, file) { - if (!module) return; - for (const key in module) { - if (key[0] === "_" || expected.has(key)) continue; - const values = [...expected.values()]; - const hint = hint_for_supported_files(key, file?.slice(file.lastIndexOf("."))) ?? `valid exports are ${values.join(", ")}, or anything with a '_' prefix`; - throw new Error(`Invalid export '${key}'${file ? ` in ${file}` : ""} (${hint})`); - } - } - return validate; -} -function hint_for_supported_files(key, ext = ".js") { - const supported_files = []; - if (valid_layout_exports.has(key)) { - supported_files.push(`+layout${ext}`); - } - if (valid_page_exports.has(key)) { - supported_files.push(`+page${ext}`); - } - if (valid_layout_server_exports.has(key)) { - supported_files.push(`+layout.server${ext}`); - } - if (valid_page_server_exports.has(key)) { - supported_files.push(`+page.server${ext}`); - } - if (valid_server_exports.has(key)) { - supported_files.push(`+server${ext}`); - } - if (supported_files.length > 0) { - return `'${key}' is a valid export in ${supported_files.slice(0, -1).join(", ")}${supported_files.length > 1 ? " or " : ""}${supported_files.at(-1)}`; - } -} -const valid_layout_exports = /* @__PURE__ */ new Set([ - "load", - "prerender", - "csr", - "ssr", - "trailingSlash", - "config" -]); -const valid_page_exports = /* @__PURE__ */ new Set([...valid_layout_exports, "entries"]); -const valid_layout_server_exports = /* @__PURE__ */ new Set([...valid_layout_exports]); -const valid_page_server_exports = /* @__PURE__ */ new Set([...valid_layout_server_exports, "actions", "entries"]); -const valid_server_exports = /* @__PURE__ */ new Set([ - "GET", - "POST", - "PATCH", - "PUT", - "DELETE", - "OPTIONS", - "HEAD", - "fallback", - "prerender", - "trailingSlash", - "config", - "entries" -]); -const validate_layout_exports = validator(valid_layout_exports); -const validate_page_exports = validator(valid_page_exports); -const validate_layout_server_exports = validator(valid_layout_server_exports); -const validate_page_server_exports = validator(valid_page_server_exports); -const validate_server_exports = validator(valid_server_exports); -export { - SCHEME as S, - decode_params as a, - validate_layout_exports as b, - validate_page_server_exports as c, - disable_search as d, - validate_page_exports as e, - resolve as f, - decode_pathname as g, - validate_server_exports as h, - make_trackable as m, - normalize_path as n, - readable as r, - validate_layout_server_exports as v, - writable as w -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js deleted file mode 100644 index 7da5071..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/index.js +++ /dev/null @@ -1,1297 +0,0 @@ -import { k as escape_html, n as noop, l as set_ssr_context, m as ssr_context, p as push, q as pop } from "./context.js"; -import { i as is_primitive, g as get_type, D as DevalueError, a as is_plain_object, e as enumerable_symbols, s as stringify_key, b as stringify_string, c as escaped } from "./utils2.js"; -const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$"; -const unsafe_chars = /[<\b\f\n\r\t\0\u2028\u2029]/g; -const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/; -function uneval(value, replacer) { - const counts = /* @__PURE__ */ new Map(); - const keys = []; - const custom = /* @__PURE__ */ new Map(); - function walk(thing) { - if (!is_primitive(thing)) { - if (counts.has(thing)) { - counts.set(thing, counts.get(thing) + 1); - return; - } - counts.set(thing, 1); - if (replacer) { - const str2 = replacer(thing, (value2) => uneval(value2, replacer)); - if (typeof str2 === "string") { - custom.set(thing, str2); - return; - } - } - if (typeof thing === "function") { - throw new DevalueError(`Cannot stringify a function`, keys, thing, value); - } - const type = get_type(thing); - switch (type) { - case "Number": - case "BigInt": - case "String": - case "Boolean": - case "Date": - case "RegExp": - case "URL": - case "URLSearchParams": - return; - case "Array": - thing.forEach((value2, i) => { - keys.push(`[${i}]`); - walk(value2); - keys.pop(); - }); - break; - case "Set": - Array.from(thing).forEach(walk); - break; - case "Map": - for (const [key, value2] of thing) { - keys.push( - `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` - ); - walk(value2); - keys.pop(); - } - break; - case "Int8Array": - case "Uint8Array": - case "Uint8ClampedArray": - case "Int16Array": - case "Uint16Array": - case "Int32Array": - case "Uint32Array": - case "Float32Array": - case "Float64Array": - case "BigInt64Array": - case "BigUint64Array": - walk(thing.buffer); - return; - case "ArrayBuffer": - return; - case "Temporal.Duration": - case "Temporal.Instant": - case "Temporal.PlainDate": - case "Temporal.PlainTime": - case "Temporal.PlainDateTime": - case "Temporal.PlainMonthDay": - case "Temporal.PlainYearMonth": - case "Temporal.ZonedDateTime": - return; - default: - if (!is_plain_object(thing)) { - throw new DevalueError( - `Cannot stringify arbitrary non-POJOs`, - keys, - thing, - value - ); - } - if (enumerable_symbols(thing).length > 0) { - throw new DevalueError( - `Cannot stringify POJOs with symbolic keys`, - keys, - thing, - value - ); - } - for (const key in thing) { - keys.push(stringify_key(key)); - walk(thing[key]); - keys.pop(); - } - } - } - } - walk(value); - const names = /* @__PURE__ */ new Map(); - Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => { - names.set(entry[0], get_name(i)); - }); - function stringify(thing) { - if (names.has(thing)) { - return names.get(thing); - } - if (is_primitive(thing)) { - return stringify_primitive(thing); - } - if (custom.has(thing)) { - return custom.get(thing); - } - const type = get_type(thing); - switch (type) { - case "Number": - case "String": - case "Boolean": - return `Object(${stringify(thing.valueOf())})`; - case "RegExp": - return `new RegExp(${stringify_string(thing.source)}, "${thing.flags}")`; - case "Date": - return `new Date(${thing.getTime()})`; - case "URL": - return `new URL(${stringify_string(thing.toString())})`; - case "URLSearchParams": - return `new URLSearchParams(${stringify_string(thing.toString())})`; - case "Array": - const members = ( - /** @type {any[]} */ - thing.map( - (v, i) => i in thing ? stringify(v) : "" - ) - ); - const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ","; - return `[${members.join(",")}${tail}]`; - case "Set": - case "Map": - return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`; - case "Int8Array": - case "Uint8Array": - case "Uint8ClampedArray": - case "Int16Array": - case "Uint16Array": - case "Int32Array": - case "Uint32Array": - case "Float32Array": - case "Float64Array": - case "BigInt64Array": - case "BigUint64Array": { - let str2 = `new ${type}`; - if (counts.get(thing.buffer) === 1) { - const array = new thing.constructor(thing.buffer); - str2 += `([${array}])`; - } else { - str2 += `([${stringify(thing.buffer)}])`; - } - const a = thing.byteOffset; - const b = a + thing.byteLength; - if (a > 0 || b !== thing.buffer.byteLength) { - const m = +/(\d+)/.exec(type)[1] / 8; - str2 += `.subarray(${a / m},${b / m})`; - } - return str2; - } - case "ArrayBuffer": { - const ui8 = new Uint8Array(thing); - return `new Uint8Array([${ui8.toString()}]).buffer`; - } - case "Temporal.Duration": - case "Temporal.Instant": - case "Temporal.PlainDate": - case "Temporal.PlainTime": - case "Temporal.PlainDateTime": - case "Temporal.PlainMonthDay": - case "Temporal.PlainYearMonth": - case "Temporal.ZonedDateTime": - return `${type}.from(${stringify_string(thing.toString())})`; - default: - const keys2 = Object.keys(thing); - const obj = keys2.map((key) => `${safe_key(key)}:${stringify(thing[key])}`).join(","); - const proto = Object.getPrototypeOf(thing); - if (proto === null) { - return keys2.length > 0 ? `{${obj},__proto__:null}` : `{__proto__:null}`; - } - return `{${obj}}`; - } - } - const str = stringify(value); - if (names.size) { - const params = []; - const statements = []; - const values = []; - names.forEach((name, thing) => { - params.push(name); - if (custom.has(thing)) { - values.push( - /** @type {string} */ - custom.get(thing) - ); - return; - } - if (is_primitive(thing)) { - values.push(stringify_primitive(thing)); - return; - } - const type = get_type(thing); - switch (type) { - case "Number": - case "String": - case "Boolean": - values.push(`Object(${stringify(thing.valueOf())})`); - break; - case "RegExp": - values.push(thing.toString()); - break; - case "Date": - values.push(`new Date(${thing.getTime()})`); - break; - case "Array": - values.push(`Array(${thing.length})`); - thing.forEach((v, i) => { - statements.push(`${name}[${i}]=${stringify(v)}`); - }); - break; - case "Set": - values.push(`new Set`); - statements.push( - `${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}` - ); - break; - case "Map": - values.push(`new Map`); - statements.push( - `${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}` - ); - break; - case "ArrayBuffer": - values.push( - `new Uint8Array([${new Uint8Array(thing).join(",")}]).buffer` - ); - break; - default: - values.push( - Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}" - ); - Object.keys(thing).forEach((key) => { - statements.push( - `${name}${safe_prop(key)}=${stringify(thing[key])}` - ); - }); - } - }); - statements.push(`return ${str}`); - return `(function(${params.join(",")}){${statements.join( - ";" - )}}(${values.join(",")}))`; - } else { - return str; - } -} -function get_name(num) { - let name = ""; - do { - name = chars[num % chars.length] + name; - num = ~~(num / chars.length) - 1; - } while (num >= 0); - return reserved.test(name) ? `${name}0` : name; -} -function escape_unsafe_char(c) { - return escaped[c] || c; -} -function escape_unsafe_chars(str) { - return str.replace(unsafe_chars, escape_unsafe_char); -} -function safe_key(key) { - return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escape_unsafe_chars(JSON.stringify(key)); -} -function safe_prop(key) { - return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escape_unsafe_chars(JSON.stringify(key))}]`; -} -function stringify_primitive(thing) { - if (typeof thing === "string") return stringify_string(thing); - if (thing === void 0) return "void 0"; - if (thing === 0 && 1 / thing < 0) return "-0"; - const str = String(thing); - if (typeof thing === "number") return str.replace(/^(-)?0\./, "$1."); - if (typeof thing === "bigint") return thing + "n"; - return str; -} -const DERIVED = 1 << 1; -const EFFECT = 1 << 2; -const RENDER_EFFECT = 1 << 3; -const MANAGED_EFFECT = 1 << 24; -const BLOCK_EFFECT = 1 << 4; -const BRANCH_EFFECT = 1 << 5; -const ROOT_EFFECT = 1 << 6; -const BOUNDARY_EFFECT = 1 << 7; -const CONNECTED = 1 << 9; -const CLEAN = 1 << 10; -const DIRTY = 1 << 11; -const MAYBE_DIRTY = 1 << 12; -const INERT = 1 << 13; -const DESTROYED = 1 << 14; -const EFFECT_RAN = 1 << 15; -const EFFECT_TRANSPARENT = 1 << 16; -const EAGER_EFFECT = 1 << 17; -const HEAD_EFFECT = 1 << 18; -const EFFECT_PRESERVED = 1 << 19; -const USER_EFFECT = 1 << 20; -const WAS_MARKED = 1 << 15; -const REACTION_IS_UPDATING = 1 << 21; -const ASYNC = 1 << 22; -const ERROR_VALUE = 1 << 23; -const STATE_SYMBOL = Symbol("$state"); -const LEGACY_PROPS = Symbol("legacy props"); -const STALE_REACTION = new class StaleReactionError extends Error { - name = "StaleReactionError"; - message = "The reaction that called `getAbortSignal()` was re-run or destroyed"; -}(); -const COMMENT_NODE = 8; -const HYDRATION_START = "["; -const HYDRATION_START_ELSE = "[!"; -const HYDRATION_END = "]"; -const HYDRATION_ERROR = {}; -const ELEMENT_IS_NAMESPACED = 1; -const ELEMENT_PRESERVE_ATTRIBUTE_CASE = 1 << 1; -const ELEMENT_IS_INPUT = 1 << 2; -const UNINITIALIZED = Symbol(); -const DOM_BOOLEAN_ATTRIBUTES = [ - "allowfullscreen", - "async", - "autofocus", - "autoplay", - "checked", - "controls", - "default", - "disabled", - "formnovalidate", - "indeterminate", - "inert", - "ismap", - "loop", - "multiple", - "muted", - "nomodule", - "novalidate", - "open", - "playsinline", - "readonly", - "required", - "reversed", - "seamless", - "selected", - "webkitdirectory", - "defer", - "disablepictureinpicture", - "disableremoteplayback" -]; -function is_boolean_attribute(name) { - return DOM_BOOLEAN_ATTRIBUTES.includes(name); -} -const PASSIVE_EVENTS = ["touchstart", "touchmove"]; -function is_passive_event(name) { - return PASSIVE_EVENTS.includes(name); -} -function r(e) { - var t, f, n = ""; - if ("string" == typeof e || "number" == typeof e) n += e; - else if ("object" == typeof e) if (Array.isArray(e)) { - var o = e.length; - for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f); - } else for (f in e) e[f] && (n && (n += " "), n += f); - return n; -} -function clsx$1() { - for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t); - return n; -} -const replacements = { - translate: /* @__PURE__ */ new Map([ - [true, "yes"], - [false, "no"] - ]) -}; -function attr(name, value, is_boolean = false) { - if (name === "hidden" && value !== "until-found") { - is_boolean = true; - } - if (value == null || !value && is_boolean) return ""; - const normalized = name in replacements && replacements[name].get(value) || value; - const assignment = is_boolean ? "" : `="${escape_html(normalized, true)}"`; - return ` ${name}${assignment}`; -} -function clsx(value) { - if (typeof value === "object") { - return clsx$1(value); - } else { - return value ?? ""; - } -} -const whitespace = [..." \n\r\f \v\uFEFF"]; -function to_class(value, hash, directives) { - var classname = value == null ? "" : "" + value; - if (hash) { - classname = classname ? classname + " " + hash : hash; - } - if (directives) { - for (var key in directives) { - if (directives[key]) { - classname = classname ? classname + " " + key : key; - } else if (classname.length) { - var len = key.length; - var a = 0; - while ((a = classname.indexOf(key, a)) >= 0) { - var b = a + len; - if ((a === 0 || whitespace.includes(classname[a - 1])) && (b === classname.length || whitespace.includes(classname[b]))) { - classname = (a === 0 ? "" : classname.substring(0, a)) + classname.substring(b + 1); - } else { - a = b; - } - } - } - } - } - return classname === "" ? null : classname; -} -function append_styles(styles, important = false) { - var separator = important ? " !important;" : ";"; - var css = ""; - for (var key in styles) { - var value = styles[key]; - if (value != null && value !== "") { - css += " " + key + ": " + value + separator; - } - } - return css; -} -function to_css_name(name) { - if (name[0] !== "-" || name[1] !== "-") { - return name.toLowerCase(); - } - return name; -} -function to_style(value, styles) { - if (styles) { - var new_style = ""; - var normal_styles; - var important_styles; - if (Array.isArray(styles)) { - normal_styles = styles[0]; - important_styles = styles[1]; - } else { - normal_styles = styles; - } - if (value) { - value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim(); - var in_str = false; - var in_apo = 0; - var in_comment = false; - var reserved_names = []; - if (normal_styles) { - reserved_names.push(...Object.keys(normal_styles).map(to_css_name)); - } - if (important_styles) { - reserved_names.push(...Object.keys(important_styles).map(to_css_name)); - } - var start_index = 0; - var name_index = -1; - const len = value.length; - for (var i = 0; i < len; i++) { - var c = value[i]; - if (in_comment) { - if (c === "/" && value[i - 1] === "*") { - in_comment = false; - } - } else if (in_str) { - if (in_str === c) { - in_str = false; - } - } else if (c === "/" && value[i + 1] === "*") { - in_comment = true; - } else if (c === '"' || c === "'") { - in_str = c; - } else if (c === "(") { - in_apo++; - } else if (c === ")") { - in_apo--; - } - if (!in_comment && in_str === false && in_apo === 0) { - if (c === ":" && name_index === -1) { - name_index = i; - } else if (c === ";" || i === len - 1) { - if (name_index !== -1) { - var name = to_css_name(value.substring(start_index, name_index).trim()); - if (!reserved_names.includes(name)) { - if (c !== ";") { - i++; - } - var property = value.substring(start_index, i).trim(); - new_style += " " + property + ";"; - } - } - start_index = i + 1; - name_index = -1; - } - } - } - } - if (normal_styles) { - new_style += append_styles(normal_styles); - } - if (important_styles) { - new_style += append_styles(important_styles, true); - } - new_style = new_style.trim(); - return new_style === "" ? null : new_style; - } - return value == null ? null : String(value); -} -const BLOCK_OPEN = ``; -const BLOCK_CLOSE = ``; -let controller = null; -function abort() { - controller?.abort(STALE_REACTION); - controller = null; -} -function await_invalid() { - const error = new Error(`await_invalid -Encountered asynchronous work while rendering synchronously. -https://svelte.dev/e/await_invalid`); - error.name = "Svelte error"; - throw error; -} -function invalid_csp() { - const error = new Error(`invalid_csp -\`csp.nonce\` was set while \`csp.hash\` was \`true\`. These options cannot be used simultaneously. -https://svelte.dev/e/invalid_csp`); - error.name = "Svelte error"; - throw error; -} -function server_context_required() { - const error = new Error(`server_context_required -Could not resolve \`render\` context. -https://svelte.dev/e/server_context_required`); - error.name = "Svelte error"; - throw error; -} -function unresolved_hydratable(key, stack) { - { - console.warn(`https://svelte.dev/e/unresolved_hydratable`); - } -} -function get_render_context() { - const store = als?.getStore(); - { - server_context_required(); - } - return store; -} -let als = null; -let text_encoder; -let crypto; -async function sha256(data) { - text_encoder ??= new TextEncoder(); - crypto ??= globalThis.crypto?.subtle?.digest ? globalThis.crypto : ( - // @ts-ignore - we don't install node types in the prod build - // don't use 'node:crypto' because static analysers will think we rely on node when we don't - (await import( - /* @vite-ignore */ - "node:crypto" - )).webcrypto - ); - const hash_buffer = await crypto.subtle.digest("SHA-256", text_encoder.encode(data)); - return base64_encode(hash_buffer); -} -function base64_encode(bytes) { - if (globalThis.Buffer) { - return globalThis.Buffer.from(bytes).toString("base64"); - } - let binary = ""; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} -class Renderer { - /** - * The contents of the renderer. - * @type {RendererItem[]} - */ - #out = []; - /** - * Any `onDestroy` callbacks registered during execution of this renderer. - * @type {(() => void)[] | undefined} - */ - #on_destroy = void 0; - /** - * Whether this renderer is a component body. - * @type {boolean} - */ - #is_component_body = false; - /** - * The type of string content that this renderer is accumulating. - * @type {RendererType} - */ - type; - /** @type {Renderer | undefined} */ - #parent; - /** - * Asynchronous work associated with this renderer - * @type {Promise | undefined} - */ - promise = void 0; - /** - * State which is associated with the content tree as a whole. - * It will be re-exposed, uncopied, on all children. - * @type {SSRState} - * @readonly - */ - global; - /** - * State that is local to the branch it is declared in. - * It will be shallow-copied to all children. - * - * @type {{ select_value: string | undefined }} - */ - local; - /** - * @param {SSRState} global - * @param {Renderer | undefined} [parent] - */ - constructor(global, parent) { - this.#parent = parent; - this.global = global; - this.local = parent ? { ...parent.local } : { select_value: void 0 }; - this.type = parent ? parent.type : "body"; - } - /** - * @param {(renderer: Renderer) => void} fn - */ - head(fn) { - const head = new Renderer(this.global, this); - head.type = "head"; - this.#out.push(head); - head.child(fn); - } - /** - * @param {Array>} blockers - * @param {(renderer: Renderer) => void} fn - */ - async_block(blockers, fn) { - this.#out.push(BLOCK_OPEN); - this.async(blockers, fn); - this.#out.push(BLOCK_CLOSE); - } - /** - * @param {Array>} blockers - * @param {(renderer: Renderer) => void} fn - */ - async(blockers, fn) { - let callback = fn; - if (blockers.length > 0) { - const context = ssr_context; - callback = (renderer) => { - return Promise.all(blockers).then(() => { - const previous_context = ssr_context; - try { - set_ssr_context(context); - return fn(renderer); - } finally { - set_ssr_context(previous_context); - } - }); - }; - } - this.child(callback); - } - /** - * @param {Array<() => void>} thunks - */ - run(thunks) { - const context = ssr_context; - let promise = Promise.resolve(thunks[0]()); - const promises = [promise]; - for (const fn of thunks.slice(1)) { - promise = promise.then(() => { - const previous_context = ssr_context; - set_ssr_context(context); - try { - return fn(); - } finally { - set_ssr_context(previous_context); - } - }); - promises.push(promise); - } - promise.catch(noop); - this.promise = promise; - return promises; - } - /** - * @param {(renderer: Renderer) => MaybePromise} fn - */ - child_block(fn) { - this.#out.push(BLOCK_OPEN); - this.child(fn); - this.#out.push(BLOCK_CLOSE); - } - /** - * Create a child renderer. The child renderer inherits the state from the parent, - * but has its own content. - * @param {(renderer: Renderer) => MaybePromise} fn - */ - child(fn) { - const child = new Renderer(this.global, this); - this.#out.push(child); - const parent = ssr_context; - set_ssr_context({ - ...ssr_context, - p: parent, - c: null, - r: child - }); - const result = fn(child); - set_ssr_context(parent); - if (result instanceof Promise) { - if (child.global.mode === "sync") { - await_invalid(); - } - result.catch(() => { - }); - child.promise = result; - } - return child; - } - /** - * Create a component renderer. The component renderer inherits the state from the parent, - * but has its own content. It is treated as an ordering boundary for ondestroy callbacks. - * @param {(renderer: Renderer) => MaybePromise} fn - * @param {Function} [component_fn] - * @returns {void} - */ - component(fn, component_fn) { - push(); - const child = this.child(fn); - child.#is_component_body = true; - pop(); - } - /** - * @param {Record} attrs - * @param {(renderer: Renderer) => void} fn - * @param {string | undefined} [css_hash] - * @param {Record | undefined} [classes] - * @param {Record | undefined} [styles] - * @param {number | undefined} [flags] - * @param {boolean | undefined} [is_rich] - * @returns {void} - */ - select(attrs, fn, css_hash, classes, styles, flags, is_rich) { - const { value, ...select_attrs } = attrs; - this.push(``); - this.child((renderer) => { - renderer.local.select_value = value; - fn(renderer); - }); - this.push(`${is_rich ? "" : ""}`); - } - /** - * @param {Record} attrs - * @param {string | number | boolean | ((renderer: Renderer) => void)} body - * @param {string | undefined} [css_hash] - * @param {Record | undefined} [classes] - * @param {Record | undefined} [styles] - * @param {number | undefined} [flags] - * @param {boolean | undefined} [is_rich] - */ - option(attrs, body, css_hash, classes, styles, flags, is_rich) { - this.#out.push(` { - if ("value" in attrs) { - value = attrs.value; - } - if (value === this.local.select_value) { - renderer.#out.push(" selected"); - } - renderer.#out.push(`>${body2}${is_rich ? "" : ""}`); - if (head) { - renderer.head((child) => child.push(head)); - } - }; - if (typeof body === "function") { - this.child((renderer) => { - const r2 = new Renderer(this.global, this); - body(r2); - if (this.global.mode === "async") { - return r2.#collect_content_async().then((content) => { - close(renderer, content.body.replaceAll("", ""), content); - }); - } else { - const content = r2.#collect_content(); - close(renderer, content.body.replaceAll("", ""), content); - } - }); - } else { - close(this, body, { body }); - } - } - /** - * @param {(renderer: Renderer) => void} fn - */ - title(fn) { - const path = this.get_path(); - const close = (head) => { - this.global.set_title(head, path); - }; - this.child((renderer) => { - const r2 = new Renderer(renderer.global, renderer); - fn(r2); - if (renderer.global.mode === "async") { - return r2.#collect_content_async().then((content) => { - close(content.head); - }); - } else { - const content = r2.#collect_content(); - close(content.head); - } - }); - } - /** - * @param {string | (() => Promise)} content - */ - push(content) { - if (typeof content === "function") { - this.child(async (renderer) => renderer.push(await content())); - } else { - this.#out.push(content); - } - } - /** - * @param {() => void} fn - */ - on_destroy(fn) { - (this.#on_destroy ??= []).push(fn); - } - /** - * @returns {number[]} - */ - get_path() { - return this.#parent ? [...this.#parent.get_path(), this.#parent.#out.indexOf(this)] : []; - } - /** - * @deprecated this is needed for legacy component bindings - */ - copy() { - const copy = new Renderer(this.global, this.#parent); - copy.#out = this.#out.map((item) => item instanceof Renderer ? item.copy() : item); - copy.promise = this.promise; - return copy; - } - /** - * @param {Renderer} other - * @deprecated this is needed for legacy component bindings - */ - subsume(other) { - if (this.global.mode !== other.global.mode) { - throw new Error( - "invariant: A renderer cannot switch modes. If you're seeing this, there's a compiler bug. File an issue!" - ); - } - this.local = other.local; - this.#out = other.#out.map((item) => { - if (item instanceof Renderer) { - item.subsume(item); - } - return item; - }); - this.promise = other.promise; - this.type = other.type; - } - get length() { - return this.#out.length; - } - /** - * Only available on the server and when compiling with the `server` option. - * Takes a component and returns an object with `body` and `head` properties on it, which you can use to populate the HTML when server-rendering your app. - * @template {Record} Props - * @param {Component} component - * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} [options] - * @returns {RenderOutput} - */ - static render(component, options = {}) { - let sync; - const result = ( - /** @type {RenderOutput} */ - {} - ); - Object.defineProperties(result, { - html: { - get: () => { - return (sync ??= Renderer.#render(component, options)).body; - } - }, - head: { - get: () => { - return (sync ??= Renderer.#render(component, options)).head; - } - }, - body: { - get: () => { - return (sync ??= Renderer.#render(component, options)).body; - } - }, - hashes: { - value: { - script: "" - } - }, - then: { - value: ( - /** - * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. - * - * @template TResult1 - * @template [TResult2=never] - * @param { (value: SyncRenderOutput) => TResult1 } onfulfilled - * @param { (reason: unknown) => TResult2 } onrejected - */ - (onfulfilled, onrejected) => { - { - const result2 = sync ??= Renderer.#render(component, options); - const user_result = onfulfilled({ - head: result2.head, - body: result2.body, - html: result2.body, - hashes: { script: [] } - }); - return Promise.resolve(user_result); - } - } - ) - } - }); - return result; - } - /** - * Collect all of the `onDestroy` callbacks registered during rendering. In an async context, this is only safe to call - * after awaiting `collect_async`. - * - * Child renderers are "porous" and don't affect execution order, but component body renderers - * create ordering boundaries. Within a renderer, callbacks run in order until hitting a component boundary. - * @returns {Iterable<() => void>} - */ - *#collect_on_destroy() { - for (const component of this.#traverse_components()) { - yield* component.#collect_ondestroy(); - } - } - /** - * Performs a depth-first search of renderers, yielding the deepest components first, then additional components as we backtrack up the tree. - * @returns {Iterable} - */ - *#traverse_components() { - for (const child of this.#out) { - if (typeof child !== "string") { - yield* child.#traverse_components(); - } - } - if (this.#is_component_body) { - yield this; - } - } - /** - * @returns {Iterable<() => void>} - */ - *#collect_ondestroy() { - if (this.#on_destroy) { - for (const fn of this.#on_destroy) { - yield fn; - } - } - for (const child of this.#out) { - if (child instanceof Renderer && !child.#is_component_body) { - yield* child.#collect_ondestroy(); - } - } - } - /** - * Render a component. Throws if any of the children are performing asynchronous work. - * - * @template {Record} Props - * @param {Component} component - * @param {{ props?: Omit; context?: Map; idPrefix?: string }} options - * @returns {AccumulatedContent} - */ - static #render(component, options) { - var previous_context = ssr_context; - try { - const renderer = Renderer.#open_render("sync", component, options); - const content = renderer.#collect_content(); - return Renderer.#close_render(content, renderer); - } finally { - abort(); - set_ssr_context(previous_context); - } - } - /** - * Render a component. - * - * @template {Record} Props - * @param {Component} component - * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} options - * @returns {Promise} - */ - static async #render_async(component, options) { - const previous_context = ssr_context; - try { - const renderer = Renderer.#open_render("async", component, options); - const content = await renderer.#collect_content_async(); - const hydratables = await renderer.#collect_hydratables(); - if (hydratables !== null) { - content.head = hydratables + content.head; - } - return Renderer.#close_render(content, renderer); - } finally { - set_ssr_context(previous_context); - abort(); - } - } - /** - * Collect all of the code from the `out` array and return it as a string, or a promise resolving to a string. - * @param {AccumulatedContent} content - * @returns {AccumulatedContent} - */ - #collect_content(content = { head: "", body: "" }) { - for (const item of this.#out) { - if (typeof item === "string") { - content[this.type] += item; - } else if (item instanceof Renderer) { - item.#collect_content(content); - } - } - return content; - } - /** - * Collect all of the code from the `out` array and return it as a string. - * @param {AccumulatedContent} content - * @returns {Promise} - */ - async #collect_content_async(content = { head: "", body: "" }) { - await this.promise; - for (const item of this.#out) { - if (typeof item === "string") { - content[this.type] += item; - } else if (item instanceof Renderer) { - await item.#collect_content_async(content); - } - } - return content; - } - async #collect_hydratables() { - const ctx = get_render_context().hydratable; - for (const [_, key] of ctx.unresolved_promises) { - unresolved_hydratable(key, ctx.lookup.get(key)?.stack ?? ""); - } - for (const comparison of ctx.comparisons) { - await comparison; - } - return await this.#hydratable_block(ctx); - } - /** - * @template {Record} Props - * @param {'sync' | 'async'} mode - * @param {import('svelte').Component} component - * @param {{ props?: Omit; context?: Map; idPrefix?: string; csp?: Csp }} options - * @returns {Renderer} - */ - static #open_render(mode, component, options) { - const renderer = new Renderer( - new SSRState(mode, options.idPrefix ? options.idPrefix + "-" : "", options.csp) - ); - renderer.push(BLOCK_OPEN); - push(); - if (options.context) ssr_context.c = options.context; - ssr_context.r = renderer; - component(renderer, options.props ?? {}); - pop(); - renderer.push(BLOCK_CLOSE); - return renderer; - } - /** - * @param {AccumulatedContent} content - * @param {Renderer} renderer - * @returns {AccumulatedContent & { hashes: { script: Sha256Source[] } }} - */ - static #close_render(content, renderer) { - for (const cleanup of renderer.#collect_on_destroy()) { - cleanup(); - } - let head = content.head + renderer.global.get_title(); - let body = content.body; - for (const { hash, code } of renderer.global.css) { - head += ``; - } - return { - head, - body, - hashes: { - script: renderer.global.csp.script_hashes - } - }; - } - /** - * @param {HydratableContext} ctx - */ - async #hydratable_block(ctx) { - if (ctx.lookup.size === 0) { - return null; - } - let entries = []; - let has_promises = false; - for (const [k, v] of ctx.lookup) { - if (v.promises) { - has_promises = true; - for (const p of v.promises) await p; - } - entries.push(`[${uneval(k)},${v.serialized}]`); - } - let prelude = `const h = (window.__svelte ??= {}).h ??= new Map();`; - if (has_promises) { - prelude = `const r = (v) => Promise.resolve(v); - ${prelude}`; - } - const body = ` - { - ${prelude} - - for (const [k, v] of [ - ${entries.join(",\n ")} - ]) { - h.set(k, v); - } - } - `; - let csp_attr = ""; - if (this.global.csp.nonce) { - csp_attr = ` nonce="${this.global.csp.nonce}"`; - } else if (this.global.csp.hash) { - const hash = await sha256(body); - this.global.csp.script_hashes.push(`sha256-${hash}`); - } - return ` - ${body}<\/script>`; - } -} -class SSRState { - /** @readonly @type {Csp & { script_hashes: Sha256Source[] }} */ - csp; - /** @readonly @type {'sync' | 'async'} */ - mode; - /** @readonly @type {() => string} */ - uid; - /** @readonly @type {Set<{ hash: string; code: string }>} */ - css = /* @__PURE__ */ new Set(); - /** @type {{ path: number[], value: string }} */ - #title = { path: [], value: "" }; - /** - * @param {'sync' | 'async'} mode - * @param {string} id_prefix - * @param {Csp} csp - */ - constructor(mode, id_prefix = "", csp = { hash: false }) { - this.mode = mode; - this.csp = { ...csp, script_hashes: [] }; - let uid = 1; - this.uid = () => `${id_prefix}s${uid++}`; - } - get_title() { - return this.#title.value; - } - /** - * Performs a depth-first (lexicographic) comparison using the path. Rejects sets - * from earlier than or equal to the current value. - * @param {string} value - * @param {number[]} path - */ - set_title(value, path) { - const current = this.#title.path; - let i = 0; - let l = Math.min(path.length, current.length); - while (i < l && path[i] === current[i]) i += 1; - if (path[i] === void 0) return; - if (current[i] === void 0 || path[i] > current[i]) { - this.#title.path = path; - this.#title.value = value; - } - } -} -const INVALID_ATTR_NAME_CHAR_REGEX = /[\s'">/=\u{FDD0}-\u{FDEF}\u{FFFE}\u{FFFF}\u{1FFFE}\u{1FFFF}\u{2FFFE}\u{2FFFF}\u{3FFFE}\u{3FFFF}\u{4FFFE}\u{4FFFF}\u{5FFFE}\u{5FFFF}\u{6FFFE}\u{6FFFF}\u{7FFFE}\u{7FFFF}\u{8FFFE}\u{8FFFF}\u{9FFFE}\u{9FFFF}\u{AFFFE}\u{AFFFF}\u{BFFFE}\u{BFFFF}\u{CFFFE}\u{CFFFF}\u{DFFFE}\u{DFFFF}\u{EFFFE}\u{EFFFF}\u{FFFFE}\u{FFFFF}\u{10FFFE}\u{10FFFF}]/u; -function render(component, options = {}) { - if (options.csp?.hash && options.csp.nonce) { - invalid_csp(); - } - return Renderer.render( - /** @type {Component} */ - component, - options - ); -} -function attributes(attrs, css_hash, classes, styles, flags = 0) { - if (styles) { - attrs.style = to_style(attrs.style, styles); - } - if (attrs.class) { - attrs.class = clsx(attrs.class); - } - if (css_hash || classes) { - attrs.class = to_class(attrs.class, css_hash, classes); - } - let attr_str = ""; - let name; - const is_html = (flags & ELEMENT_IS_NAMESPACED) === 0; - const lowercase = (flags & ELEMENT_PRESERVE_ATTRIBUTE_CASE) === 0; - const is_input = (flags & ELEMENT_IS_INPUT) !== 0; - for (name in attrs) { - if (typeof attrs[name] === "function") continue; - if (name[0] === "$" && name[1] === "$") continue; - if (INVALID_ATTR_NAME_CHAR_REGEX.test(name)) continue; - var value = attrs[name]; - if (lowercase) { - name = name.toLowerCase(); - } - if (is_input) { - if (name === "defaultvalue" || name === "defaultchecked") { - name = name === "defaultvalue" ? "value" : "checked"; - if (attrs[name]) continue; - } - } - attr_str += attr(name, value, is_html && is_boolean_attribute(name)); - } - return attr_str; -} -function slot(renderer, $$props, name, slot_props, fallback_fn) { - var slot_fn = $$props.$$slots?.[name]; - if (slot_fn === true) { - slot_fn = $$props["children"]; - } - if (slot_fn !== void 0) { - slot_fn(renderer, slot_props); - } -} -export { - ASYNC as A, - BOUNDARY_EFFECT as B, - COMMENT_NODE as C, - DIRTY as D, - ERROR_VALUE as E, - HYDRATION_ERROR as H, - INERT as I, - LEGACY_PROPS as L, - MAYBE_DIRTY as M, - ROOT_EFFECT as R, - STATE_SYMBOL as S, - UNINITIALIZED as U, - WAS_MARKED as W, - HYDRATION_END as a, - HYDRATION_START as b, - HYDRATION_START_ELSE as c, - EFFECT_RAN as d, - CONNECTED as e, - CLEAN as f, - DERIVED as g, - EFFECT as h, - BLOCK_EFFECT as i, - BRANCH_EFFECT as j, - RENDER_EFFECT as k, - MANAGED_EFFECT as l, - HEAD_EFFECT as m, - DESTROYED as n, - EFFECT_TRANSPARENT as o, - EFFECT_PRESERVED as p, - EAGER_EFFECT as q, - STALE_REACTION as r, - USER_EFFECT as s, - REACTION_IS_UPDATING as t, - uneval as u, - is_passive_event as v, - render as w, - slot as x -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js deleted file mode 100644 index 160cf7c..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/internal.js +++ /dev/null @@ -1,2712 +0,0 @@ -import { H as HYDRATION_ERROR, C as COMMENT_NODE, a as HYDRATION_END, b as HYDRATION_START, c as HYDRATION_START_ELSE, B as BOUNDARY_EFFECT, E as ERROR_VALUE, d as EFFECT_RAN, e as CONNECTED, f as CLEAN, M as MAYBE_DIRTY, D as DIRTY, g as DERIVED, W as WAS_MARKED, I as INERT, h as EFFECT, i as BLOCK_EFFECT, U as UNINITIALIZED, j as BRANCH_EFFECT, R as ROOT_EFFECT, k as RENDER_EFFECT, l as MANAGED_EFFECT, m as HEAD_EFFECT, n as DESTROYED, A as ASYNC, o as EFFECT_TRANSPARENT, p as EFFECT_PRESERVED, q as EAGER_EFFECT, S as STATE_SYMBOL, r as STALE_REACTION, s as USER_EFFECT, t as REACTION_IS_UPDATING, v as is_passive_event, L as LEGACY_PROPS, w as render } from "./index.js"; -import { B as BROWSER } from "./environment.js"; -import { r as run_all, d as deferred, i as includes, o as object_prototype, a as array_prototype, g as get_descriptor, b as get_prototype_of, c as is_array, e as is_extensible, f as index_of, h as define_property, j as array_from, s as setContext } from "./context.js"; -import { s as safe_equals, e as equals } from "./equality.js"; -let public_env = {}; -function set_private_env(environment) { -} -function set_public_env(environment) { - public_env = environment; -} -function effect_update_depth_exceeded() { - { - throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); - } -} -function hydration_failed() { - { - throw new Error(`https://svelte.dev/e/hydration_failed`); - } -} -function state_descriptors_fixed() { - { - throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); - } -} -function state_prototype_fixed() { - { - throw new Error(`https://svelte.dev/e/state_prototype_fixed`); - } -} -function state_unsafe_mutation() { - { - throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); - } -} -function svelte_boundary_reset_onerror() { - { - throw new Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`); - } -} -function hydration_mismatch(location) { - { - console.warn(`https://svelte.dev/e/hydration_mismatch`); - } -} -function svelte_boundary_reset_noop() { - { - console.warn(`https://svelte.dev/e/svelte_boundary_reset_noop`); - } -} -let hydrating = false; -function set_hydrating(value) { - hydrating = value; -} -let hydrate_node; -function set_hydrate_node(node) { - if (node === null) { - hydration_mismatch(); - throw HYDRATION_ERROR; - } - return hydrate_node = node; -} -function hydrate_next() { - return set_hydrate_node(/* @__PURE__ */ get_next_sibling(hydrate_node)); -} -function next(count = 1) { - if (hydrating) { - var i = count; - var node = hydrate_node; - while (i--) { - node = /** @type {TemplateNode} */ - /* @__PURE__ */ get_next_sibling(node); - } - hydrate_node = node; - } -} -function skip_nodes(remove = true) { - var depth = 0; - var node = hydrate_node; - while (true) { - if (node.nodeType === COMMENT_NODE) { - var data = ( - /** @type {Comment} */ - node.data - ); - if (data === HYDRATION_END) { - if (depth === 0) return node; - depth -= 1; - } else if (data === HYDRATION_START || data === HYDRATION_START_ELSE) { - depth += 1; - } - } - var next2 = ( - /** @type {TemplateNode} */ - /* @__PURE__ */ get_next_sibling(node) - ); - if (remove) node.remove(); - node = next2; - } -} -let tracing_mode_flag = false; -let component_context = null; -function set_component_context(context) { - component_context = context; -} -function push(props, runes = false, fn) { - component_context = { - p: component_context, - i: false, - c: null, - e: null, - s: props, - x: null, - l: null - }; -} -function pop(component) { - var context = ( - /** @type {ComponentContext} */ - component_context - ); - var effects = context.e; - if (effects !== null) { - context.e = null; - for (var fn of effects) { - create_user_effect(fn); - } - } - context.i = true; - component_context = context.p; - return ( - /** @type {T} */ - {} - ); -} -function is_runes() { - return true; -} -let micro_tasks = []; -function run_micro_tasks() { - var tasks = micro_tasks; - micro_tasks = []; - run_all(tasks); -} -function queue_micro_task(fn) { - if (micro_tasks.length === 0 && !is_flushing_sync) { - var tasks = micro_tasks; - queueMicrotask(() => { - if (tasks === micro_tasks) run_micro_tasks(); - }); - } - micro_tasks.push(fn); -} -function flush_tasks() { - while (micro_tasks.length > 0) { - run_micro_tasks(); - } -} -function handle_error(error) { - var effect = active_effect; - if (effect === null) { - active_reaction.f |= ERROR_VALUE; - return error; - } - if ((effect.f & EFFECT_RAN) === 0) { - if ((effect.f & BOUNDARY_EFFECT) === 0) { - throw error; - } - effect.b.error(error); - } else { - invoke_error_boundary(error, effect); - } -} -function invoke_error_boundary(error, effect) { - while (effect !== null) { - if ((effect.f & BOUNDARY_EFFECT) !== 0) { - try { - effect.b.error(error); - return; - } catch (e) { - error = e; - } - } - effect = effect.parent; - } - throw error; -} -const STATUS_MASK = -7169; -function set_signal_status(signal, status) { - signal.f = signal.f & STATUS_MASK | status; -} -function update_derived_status(derived) { - if ((derived.f & CONNECTED) !== 0 || derived.deps === null) { - set_signal_status(derived, CLEAN); - } else { - set_signal_status(derived, MAYBE_DIRTY); - } -} -function clear_marked(deps) { - if (deps === null) return; - for (const dep of deps) { - if ((dep.f & DERIVED) === 0 || (dep.f & WAS_MARKED) === 0) { - continue; - } - dep.f ^= WAS_MARKED; - clear_marked( - /** @type {Derived} */ - dep.deps - ); - } -} -function defer_effect(effect, dirty_effects, maybe_dirty_effects) { - if ((effect.f & DIRTY) !== 0) { - dirty_effects.add(effect); - } else if ((effect.f & MAYBE_DIRTY) !== 0) { - maybe_dirty_effects.add(effect); - } - clear_marked(effect.deps); - set_signal_status(effect, CLEAN); -} -const batches = /* @__PURE__ */ new Set(); -let current_batch = null; -let batch_values = null; -let queued_root_effects = []; -let last_scheduled_effect = null; -let is_flushing = false; -let is_flushing_sync = false; -class Batch { - committed = false; - /** - * The current values of any sources that are updated in this batch - * They keys of this map are identical to `this.#previous` - * @type {Map} - */ - current = /* @__PURE__ */ new Map(); - /** - * The values of any sources that are updated in this batch _before_ those updates took place. - * They keys of this map are identical to `this.#current` - * @type {Map} - */ - previous = /* @__PURE__ */ new Map(); - /** - * When the batch is committed (and the DOM is updated), we need to remove old branches - * and append new ones by calling the functions added inside (if/each/key/etc) blocks - * @type {Set<() => void>} - */ - #commit_callbacks = /* @__PURE__ */ new Set(); - /** - * If a fork is discarded, we need to destroy any effects that are no longer needed - * @type {Set<(batch: Batch) => void>} - */ - #discard_callbacks = /* @__PURE__ */ new Set(); - /** - * The number of async effects that are currently in flight - */ - #pending = 0; - /** - * The number of async effects that are currently in flight, _not_ inside a pending boundary - */ - #blocking_pending = 0; - /** - * A deferred that resolves when the batch is committed, used with `settled()` - * TODO replace with Promise.withResolvers once supported widely enough - * @type {{ promise: Promise, resolve: (value?: any) => void, reject: (reason: unknown) => void } | null} - */ - #deferred = null; - /** - * Deferred effects (which run after async work has completed) that are DIRTY - * @type {Set} - */ - #dirty_effects = /* @__PURE__ */ new Set(); - /** - * Deferred effects that are MAYBE_DIRTY - * @type {Set} - */ - #maybe_dirty_effects = /* @__PURE__ */ new Set(); - /** - * A map of branches that still exist, but will be destroyed when this batch - * is committed — we skip over these during `process`. - * The value contains child effects that were dirty/maybe_dirty before being reset, - * so they can be rescheduled if the branch survives. - * @type {Map} - */ - #skipped_branches = /* @__PURE__ */ new Map(); - is_fork = false; - #decrement_queued = false; - is_deferred() { - return this.is_fork || this.#blocking_pending > 0; - } - /** - * Add an effect to the #skipped_branches map and reset its children - * @param {Effect} effect - */ - skip_effect(effect) { - if (!this.#skipped_branches.has(effect)) { - this.#skipped_branches.set(effect, { d: [], m: [] }); - } - } - /** - * Remove an effect from the #skipped_branches map and reschedule - * any tracked dirty/maybe_dirty child effects - * @param {Effect} effect - */ - unskip_effect(effect) { - var tracked = this.#skipped_branches.get(effect); - if (tracked) { - this.#skipped_branches.delete(effect); - for (var e of tracked.d) { - set_signal_status(e, DIRTY); - schedule_effect(e); - } - for (e of tracked.m) { - set_signal_status(e, MAYBE_DIRTY); - schedule_effect(e); - } - } - } - /** - * - * @param {Effect[]} root_effects - */ - process(root_effects) { - queued_root_effects = []; - this.apply(); - var effects = []; - var render_effects = []; - for (const root2 of root_effects) { - this.#traverse_effect_tree(root2, effects, render_effects); - } - if (this.is_deferred()) { - this.#defer_effects(render_effects); - this.#defer_effects(effects); - for (const [e, t] of this.#skipped_branches) { - reset_branch(e, t); - } - } else { - for (const fn of this.#commit_callbacks) fn(); - this.#commit_callbacks.clear(); - if (this.#pending === 0) { - this.#commit(); - } - current_batch = null; - flush_queued_effects(render_effects); - flush_queued_effects(effects); - this.#deferred?.resolve(); - } - batch_values = null; - } - /** - * Traverse the effect tree, executing effects or stashing - * them for later execution as appropriate - * @param {Effect} root - * @param {Effect[]} effects - * @param {Effect[]} render_effects - */ - #traverse_effect_tree(root2, effects, render_effects) { - root2.f ^= CLEAN; - var effect = root2.first; - var pending_boundary = null; - while (effect !== null) { - var flags2 = effect.f; - var is_branch = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0; - var is_skippable_branch = is_branch && (flags2 & CLEAN) !== 0; - var skip = is_skippable_branch || (flags2 & INERT) !== 0 || this.#skipped_branches.has(effect); - if (!skip && effect.fn !== null) { - if (is_branch) { - effect.f ^= CLEAN; - } else if (pending_boundary !== null && (flags2 & (EFFECT | RENDER_EFFECT | MANAGED_EFFECT)) !== 0) { - pending_boundary.b.defer_effect(effect); - } else if ((flags2 & EFFECT) !== 0) { - effects.push(effect); - } else if (is_dirty(effect)) { - if ((flags2 & BLOCK_EFFECT) !== 0) this.#maybe_dirty_effects.add(effect); - update_effect(effect); - } - var child = effect.first; - if (child !== null) { - effect = child; - continue; - } - } - var parent = effect.parent; - effect = effect.next; - while (effect === null && parent !== null) { - if (parent === pending_boundary) { - pending_boundary = null; - } - effect = parent.next; - parent = parent.parent; - } - } - } - /** - * @param {Effect[]} effects - */ - #defer_effects(effects) { - for (var i = 0; i < effects.length; i += 1) { - defer_effect(effects[i], this.#dirty_effects, this.#maybe_dirty_effects); - } - } - /** - * Associate a change to a given source with the current - * batch, noting its previous and current values - * @param {Source} source - * @param {any} value - */ - capture(source2, value) { - if (value !== UNINITIALIZED && !this.previous.has(source2)) { - this.previous.set(source2, value); - } - if ((source2.f & ERROR_VALUE) === 0) { - this.current.set(source2, source2.v); - batch_values?.set(source2, source2.v); - } - } - activate() { - current_batch = this; - this.apply(); - } - deactivate() { - if (current_batch !== this) return; - current_batch = null; - batch_values = null; - } - flush() { - this.activate(); - if (queued_root_effects.length > 0) { - flush_effects(); - if (current_batch !== null && current_batch !== this) { - return; - } - } else if (this.#pending === 0) { - this.process([]); - } - this.deactivate(); - } - discard() { - for (const fn of this.#discard_callbacks) fn(this); - this.#discard_callbacks.clear(); - } - #commit() { - if (batches.size > 1) { - this.previous.clear(); - var previous_batch_values = batch_values; - var is_earlier = true; - for (const batch of batches) { - if (batch === this) { - is_earlier = false; - continue; - } - const sources = []; - for (const [source2, value] of this.current) { - if (batch.current.has(source2)) { - if (is_earlier && value !== batch.current.get(source2)) { - batch.current.set(source2, value); - } else { - continue; - } - } - sources.push(source2); - } - if (sources.length === 0) { - continue; - } - const others = [...batch.current.keys()].filter((s) => !this.current.has(s)); - if (others.length > 0) { - var prev_queued_root_effects = queued_root_effects; - queued_root_effects = []; - const marked = /* @__PURE__ */ new Set(); - const checked = /* @__PURE__ */ new Map(); - for (const source2 of sources) { - mark_effects(source2, others, marked, checked); - } - if (queued_root_effects.length > 0) { - current_batch = batch; - batch.apply(); - for (const root2 of queued_root_effects) { - batch.#traverse_effect_tree(root2, [], []); - } - batch.deactivate(); - } - queued_root_effects = prev_queued_root_effects; - } - } - current_batch = null; - batch_values = previous_batch_values; - } - this.committed = true; - batches.delete(this); - } - /** - * - * @param {boolean} blocking - */ - increment(blocking) { - this.#pending += 1; - if (blocking) this.#blocking_pending += 1; - } - /** - * - * @param {boolean} blocking - */ - decrement(blocking) { - this.#pending -= 1; - if (blocking) this.#blocking_pending -= 1; - if (this.#decrement_queued) return; - this.#decrement_queued = true; - queue_micro_task(() => { - this.#decrement_queued = false; - if (!this.is_deferred()) { - this.revive(); - } else if (queued_root_effects.length > 0) { - this.flush(); - } - }); - } - revive() { - for (const e of this.#dirty_effects) { - this.#maybe_dirty_effects.delete(e); - set_signal_status(e, DIRTY); - schedule_effect(e); - } - for (const e of this.#maybe_dirty_effects) { - set_signal_status(e, MAYBE_DIRTY); - schedule_effect(e); - } - this.flush(); - } - /** @param {() => void} fn */ - oncommit(fn) { - this.#commit_callbacks.add(fn); - } - /** @param {(batch: Batch) => void} fn */ - ondiscard(fn) { - this.#discard_callbacks.add(fn); - } - settled() { - return (this.#deferred ??= deferred()).promise; - } - static ensure() { - if (current_batch === null) { - const batch = current_batch = new Batch(); - batches.add(current_batch); - if (!is_flushing_sync) { - queue_micro_task(() => { - if (current_batch !== batch) { - return; - } - batch.flush(); - }); - } - } - return current_batch; - } - apply() { - return; - } -} -function flushSync(fn) { - var was_flushing_sync = is_flushing_sync; - is_flushing_sync = true; - try { - var result; - if (fn) ; - while (true) { - flush_tasks(); - if (queued_root_effects.length === 0) { - current_batch?.flush(); - if (queued_root_effects.length === 0) { - last_scheduled_effect = null; - return ( - /** @type {T} */ - result - ); - } - } - flush_effects(); - } - } finally { - is_flushing_sync = was_flushing_sync; - } -} -function flush_effects() { - is_flushing = true; - var source_stacks = null; - try { - var flush_count = 0; - while (queued_root_effects.length > 0) { - var batch = Batch.ensure(); - if (flush_count++ > 1e3) { - var updates, entry; - if (BROWSER) ; - infinite_loop_guard(); - } - batch.process(queued_root_effects); - old_values.clear(); - if (BROWSER) ; - } - } finally { - queued_root_effects = []; - is_flushing = false; - last_scheduled_effect = null; - } -} -function infinite_loop_guard() { - try { - effect_update_depth_exceeded(); - } catch (error) { - invoke_error_boundary(error, last_scheduled_effect); - } -} -let eager_block_effects = null; -function flush_queued_effects(effects) { - var length = effects.length; - if (length === 0) return; - var i = 0; - while (i < length) { - var effect = effects[i++]; - if ((effect.f & (DESTROYED | INERT)) === 0 && is_dirty(effect)) { - eager_block_effects = /* @__PURE__ */ new Set(); - update_effect(effect); - if (effect.deps === null && effect.first === null && effect.nodes === null) { - if (effect.teardown === null && effect.ac === null) { - unlink_effect(effect); - } else { - effect.fn = null; - } - } - if (eager_block_effects?.size > 0) { - old_values.clear(); - for (const e of eager_block_effects) { - if ((e.f & (DESTROYED | INERT)) !== 0) continue; - const ordered_effects = [e]; - let ancestor = e.parent; - while (ancestor !== null) { - if (eager_block_effects.has(ancestor)) { - eager_block_effects.delete(ancestor); - ordered_effects.push(ancestor); - } - ancestor = ancestor.parent; - } - for (let j = ordered_effects.length - 1; j >= 0; j--) { - const e2 = ordered_effects[j]; - if ((e2.f & (DESTROYED | INERT)) !== 0) continue; - update_effect(e2); - } - } - eager_block_effects.clear(); - } - } - } - eager_block_effects = null; -} -function mark_effects(value, sources, marked, checked) { - if (marked.has(value)) return; - marked.add(value); - if (value.reactions !== null) { - for (const reaction of value.reactions) { - const flags2 = reaction.f; - if ((flags2 & DERIVED) !== 0) { - mark_effects( - /** @type {Derived} */ - reaction, - sources, - marked, - checked - ); - } else if ((flags2 & (ASYNC | BLOCK_EFFECT)) !== 0 && (flags2 & DIRTY) === 0 && depends_on(reaction, sources, checked)) { - set_signal_status(reaction, DIRTY); - schedule_effect( - /** @type {Effect} */ - reaction - ); - } - } - } -} -function depends_on(reaction, sources, checked) { - const depends = checked.get(reaction); - if (depends !== void 0) return depends; - if (reaction.deps !== null) { - for (const dep of reaction.deps) { - if (includes.call(sources, dep)) { - return true; - } - if ((dep.f & DERIVED) !== 0 && depends_on( - /** @type {Derived} */ - dep, - sources, - checked - )) { - checked.set( - /** @type {Derived} */ - dep, - true - ); - return true; - } - } - } - checked.set(reaction, false); - return false; -} -function schedule_effect(signal) { - var effect = last_scheduled_effect = signal; - while (effect.parent !== null) { - effect = effect.parent; - var flags2 = effect.f; - if (is_flushing && effect === active_effect && (flags2 & BLOCK_EFFECT) !== 0 && (flags2 & HEAD_EFFECT) === 0) { - return; - } - if ((flags2 & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { - if ((flags2 & CLEAN) === 0) return; - effect.f ^= CLEAN; - } - } - queued_root_effects.push(effect); -} -function reset_branch(effect, tracked) { - if ((effect.f & BRANCH_EFFECT) !== 0 && (effect.f & CLEAN) !== 0) { - return; - } - if ((effect.f & DIRTY) !== 0) { - tracked.d.push(effect); - } else if ((effect.f & MAYBE_DIRTY) !== 0) { - tracked.m.push(effect); - } - set_signal_status(effect, CLEAN); - var e = effect.first; - while (e !== null) { - reset_branch(e, tracked); - e = e.next; - } -} -function createSubscriber(start) { - let subscribers = 0; - let version = source(0); - let stop; - return () => { - if (effect_tracking()) { - get(version); - render_effect(() => { - if (subscribers === 0) { - stop = untrack(() => start(() => increment(version))); - } - subscribers += 1; - return () => { - queue_micro_task(() => { - subscribers -= 1; - if (subscribers === 0) { - stop?.(); - stop = void 0; - increment(version); - } - }); - }; - }); - } - }; -} -var flags = EFFECT_TRANSPARENT | EFFECT_PRESERVED | BOUNDARY_EFFECT; -function boundary(node, props, children) { - new Boundary(node, props, children); -} -class Boundary { - /** @type {Boundary | null} */ - parent; - is_pending = false; - /** @type {TemplateNode} */ - #anchor; - /** @type {TemplateNode | null} */ - #hydrate_open = hydrating ? hydrate_node : null; - /** @type {BoundaryProps} */ - #props; - /** @type {((anchor: Node) => void)} */ - #children; - /** @type {Effect} */ - #effect; - /** @type {Effect | null} */ - #main_effect = null; - /** @type {Effect | null} */ - #pending_effect = null; - /** @type {Effect | null} */ - #failed_effect = null; - /** @type {DocumentFragment | null} */ - #offscreen_fragment = null; - /** @type {TemplateNode | null} */ - #pending_anchor = null; - #local_pending_count = 0; - #pending_count = 0; - #pending_count_update_queued = false; - #is_creating_fallback = false; - /** @type {Set} */ - #dirty_effects = /* @__PURE__ */ new Set(); - /** @type {Set} */ - #maybe_dirty_effects = /* @__PURE__ */ new Set(); - /** - * A source containing the number of pending async deriveds/expressions. - * Only created if `$effect.pending()` is used inside the boundary, - * otherwise updating the source results in needless `Batch.ensure()` - * calls followed by no-op flushes - * @type {Source | null} - */ - #effect_pending = null; - #effect_pending_subscriber = createSubscriber(() => { - this.#effect_pending = source(this.#local_pending_count); - return () => { - this.#effect_pending = null; - }; - }); - /** - * @param {TemplateNode} node - * @param {BoundaryProps} props - * @param {((anchor: Node) => void)} children - */ - constructor(node, props, children) { - this.#anchor = node; - this.#props = props; - this.#children = children; - this.parent = /** @type {Effect} */ - active_effect.b; - this.is_pending = !!this.#props.pending; - this.#effect = block(() => { - active_effect.b = this; - if (hydrating) { - const comment = this.#hydrate_open; - hydrate_next(); - const server_rendered_pending = ( - /** @type {Comment} */ - comment.nodeType === COMMENT_NODE && /** @type {Comment} */ - comment.data === HYDRATION_START_ELSE - ); - if (server_rendered_pending) { - this.#hydrate_pending_content(); - } else { - this.#hydrate_resolved_content(); - if (this.#pending_count === 0) { - this.is_pending = false; - } - } - } else { - var anchor = this.#get_anchor(); - try { - this.#main_effect = branch(() => children(anchor)); - } catch (error) { - this.error(error); - } - if (this.#pending_count > 0) { - this.#show_pending_snippet(); - } else { - this.is_pending = false; - } - } - return () => { - this.#pending_anchor?.remove(); - }; - }, flags); - if (hydrating) { - this.#anchor = hydrate_node; - } - } - #hydrate_resolved_content() { - try { - this.#main_effect = branch(() => this.#children(this.#anchor)); - } catch (error) { - this.error(error); - } - } - #hydrate_pending_content() { - const pending = this.#props.pending; - if (!pending) return; - this.#pending_effect = branch(() => pending(this.#anchor)); - queue_micro_task(() => { - var anchor = this.#get_anchor(); - this.#main_effect = this.#run(() => { - Batch.ensure(); - return branch(() => this.#children(anchor)); - }); - if (this.#pending_count > 0) { - this.#show_pending_snippet(); - } else { - pause_effect( - /** @type {Effect} */ - this.#pending_effect, - () => { - this.#pending_effect = null; - } - ); - this.is_pending = false; - } - }); - } - #get_anchor() { - var anchor = this.#anchor; - if (this.is_pending) { - this.#pending_anchor = create_text(); - this.#anchor.before(this.#pending_anchor); - anchor = this.#pending_anchor; - } - return anchor; - } - /** - * Defer an effect inside a pending boundary until the boundary resolves - * @param {Effect} effect - */ - defer_effect(effect) { - defer_effect(effect, this.#dirty_effects, this.#maybe_dirty_effects); - } - /** - * Returns `false` if the effect exists inside a boundary whose pending snippet is shown - * @returns {boolean} - */ - is_rendered() { - return !this.is_pending && (!this.parent || this.parent.is_rendered()); - } - has_pending_snippet() { - return !!this.#props.pending; - } - /** - * @param {() => Effect | null} fn - */ - #run(fn) { - var previous_effect = active_effect; - var previous_reaction = active_reaction; - var previous_ctx = component_context; - set_active_effect(this.#effect); - set_active_reaction(this.#effect); - set_component_context(this.#effect.ctx); - try { - return fn(); - } catch (e) { - handle_error(e); - return null; - } finally { - set_active_effect(previous_effect); - set_active_reaction(previous_reaction); - set_component_context(previous_ctx); - } - } - #show_pending_snippet() { - const pending = ( - /** @type {(anchor: Node) => void} */ - this.#props.pending - ); - if (this.#main_effect !== null) { - this.#offscreen_fragment = document.createDocumentFragment(); - this.#offscreen_fragment.append( - /** @type {TemplateNode} */ - this.#pending_anchor - ); - move_effect(this.#main_effect, this.#offscreen_fragment); - } - if (this.#pending_effect === null) { - this.#pending_effect = branch(() => pending(this.#anchor)); - } - } - /** - * Updates the pending count associated with the currently visible pending snippet, - * if any, such that we can replace the snippet with content once work is done - * @param {1 | -1} d - */ - #update_pending_count(d) { - if (!this.has_pending_snippet()) { - if (this.parent) { - this.parent.#update_pending_count(d); - } - return; - } - this.#pending_count += d; - if (this.#pending_count === 0) { - this.is_pending = false; - for (const e of this.#dirty_effects) { - set_signal_status(e, DIRTY); - schedule_effect(e); - } - for (const e of this.#maybe_dirty_effects) { - set_signal_status(e, MAYBE_DIRTY); - schedule_effect(e); - } - this.#dirty_effects.clear(); - this.#maybe_dirty_effects.clear(); - if (this.#pending_effect) { - pause_effect(this.#pending_effect, () => { - this.#pending_effect = null; - }); - } - if (this.#offscreen_fragment) { - this.#anchor.before(this.#offscreen_fragment); - this.#offscreen_fragment = null; - } - } - } - /** - * Update the source that powers `$effect.pending()` inside this boundary, - * and controls when the current `pending` snippet (if any) is removed. - * Do not call from inside the class - * @param {1 | -1} d - */ - update_pending_count(d) { - this.#update_pending_count(d); - this.#local_pending_count += d; - if (!this.#effect_pending || this.#pending_count_update_queued) return; - this.#pending_count_update_queued = true; - queue_micro_task(() => { - this.#pending_count_update_queued = false; - if (this.#effect_pending) { - internal_set(this.#effect_pending, this.#local_pending_count); - } - }); - } - get_effect_pending() { - this.#effect_pending_subscriber(); - return get( - /** @type {Source} */ - this.#effect_pending - ); - } - /** @param {unknown} error */ - error(error) { - var onerror = this.#props.onerror; - let failed = this.#props.failed; - if (this.#is_creating_fallback || !onerror && !failed) { - throw error; - } - if (this.#main_effect) { - destroy_effect(this.#main_effect); - this.#main_effect = null; - } - if (this.#pending_effect) { - destroy_effect(this.#pending_effect); - this.#pending_effect = null; - } - if (this.#failed_effect) { - destroy_effect(this.#failed_effect); - this.#failed_effect = null; - } - if (hydrating) { - set_hydrate_node( - /** @type {TemplateNode} */ - this.#hydrate_open - ); - next(); - set_hydrate_node(skip_nodes()); - } - var did_reset = false; - var calling_on_error = false; - const reset = () => { - if (did_reset) { - svelte_boundary_reset_noop(); - return; - } - did_reset = true; - if (calling_on_error) { - svelte_boundary_reset_onerror(); - } - Batch.ensure(); - this.#local_pending_count = 0; - if (this.#failed_effect !== null) { - pause_effect(this.#failed_effect, () => { - this.#failed_effect = null; - }); - } - this.is_pending = this.has_pending_snippet(); - this.#main_effect = this.#run(() => { - this.#is_creating_fallback = false; - return branch(() => this.#children(this.#anchor)); - }); - if (this.#pending_count > 0) { - this.#show_pending_snippet(); - } else { - this.is_pending = false; - } - }; - queue_micro_task(() => { - try { - calling_on_error = true; - onerror?.(error, reset); - calling_on_error = false; - } catch (error2) { - invoke_error_boundary(error2, this.#effect && this.#effect.parent); - } - if (failed) { - this.#failed_effect = this.#run(() => { - Batch.ensure(); - this.#is_creating_fallback = true; - try { - return branch(() => { - failed( - this.#anchor, - () => error, - () => reset - ); - }); - } catch (error2) { - invoke_error_boundary( - error2, - /** @type {Effect} */ - this.#effect.parent - ); - return null; - } finally { - this.#is_creating_fallback = false; - } - }); - } - }); - } -} -function destroy_derived_effects(derived) { - var effects = derived.effects; - if (effects !== null) { - derived.effects = null; - for (var i = 0; i < effects.length; i += 1) { - destroy_effect( - /** @type {Effect} */ - effects[i] - ); - } - } -} -function get_derived_parent_effect(derived) { - var parent = derived.parent; - while (parent !== null) { - if ((parent.f & DERIVED) === 0) { - return (parent.f & DESTROYED) === 0 ? ( - /** @type {Effect} */ - parent - ) : null; - } - parent = parent.parent; - } - return null; -} -function execute_derived(derived) { - var value; - var prev_active_effect = active_effect; - set_active_effect(get_derived_parent_effect(derived)); - { - try { - derived.f &= ~WAS_MARKED; - destroy_derived_effects(derived); - value = update_reaction(derived); - } finally { - set_active_effect(prev_active_effect); - } - } - return value; -} -function update_derived(derived) { - var value = execute_derived(derived); - if (!derived.equals(value)) { - derived.wv = increment_write_version(); - if (!current_batch?.is_fork || derived.deps === null) { - derived.v = value; - if (derived.deps === null) { - set_signal_status(derived, CLEAN); - return; - } - } - } - if (is_destroying_effect) { - return; - } - if (batch_values !== null) { - if (effect_tracking() || current_batch?.is_fork) { - batch_values.set(derived, value); - } - } else { - update_derived_status(derived); - } -} -let eager_effects = /* @__PURE__ */ new Set(); -const old_values = /* @__PURE__ */ new Map(); -let eager_effects_deferred = false; -function source(v, stack) { - var signal = { - f: 0, - // TODO ideally we could skip this altogether, but it causes type errors - v, - reactions: null, - equals, - rv: 0, - wv: 0 - }; - return signal; -} -// @__NO_SIDE_EFFECTS__ -function state(v, stack) { - const s = source(v); - push_reaction_value(s); - return s; -} -// @__NO_SIDE_EFFECTS__ -function mutable_source(initial_value, immutable = false, trackable = true) { - const s = source(initial_value); - if (!immutable) { - s.equals = safe_equals; - } - return s; -} -function set(source2, value, should_proxy = false) { - if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check - // to ensure we error if state is set inside an inspect effect - (!untracking || (active_reaction.f & EAGER_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | ASYNC | EAGER_EFFECT)) !== 0 && (current_sources === null || !includes.call(current_sources, source2))) { - state_unsafe_mutation(); - } - let new_value = should_proxy ? proxy(value) : value; - return internal_set(source2, new_value); -} -function internal_set(source2, value) { - if (!source2.equals(value)) { - var old_value = source2.v; - if (is_destroying_effect) { - old_values.set(source2, value); - } else { - old_values.set(source2, old_value); - } - source2.v = value; - var batch = Batch.ensure(); - batch.capture(source2, old_value); - if ((source2.f & DERIVED) !== 0) { - const derived = ( - /** @type {Derived} */ - source2 - ); - if ((source2.f & DIRTY) !== 0) { - execute_derived(derived); - } - update_derived_status(derived); - } - source2.wv = increment_write_version(); - mark_reactions(source2, DIRTY); - if (active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) { - if (untracked_writes === null) { - set_untracked_writes([source2]); - } else { - untracked_writes.push(source2); - } - } - if (!batch.is_fork && eager_effects.size > 0 && !eager_effects_deferred) { - flush_eager_effects(); - } - } - return value; -} -function flush_eager_effects() { - eager_effects_deferred = false; - for (const effect of eager_effects) { - if ((effect.f & CLEAN) !== 0) { - set_signal_status(effect, MAYBE_DIRTY); - } - if (is_dirty(effect)) { - update_effect(effect); - } - } - eager_effects.clear(); -} -function increment(source2) { - set(source2, source2.v + 1); -} -function mark_reactions(signal, status) { - var reactions = signal.reactions; - if (reactions === null) return; - var length = reactions.length; - for (var i = 0; i < length; i++) { - var reaction = reactions[i]; - var flags2 = reaction.f; - var not_dirty = (flags2 & DIRTY) === 0; - if (not_dirty) { - set_signal_status(reaction, status); - } - if ((flags2 & DERIVED) !== 0) { - var derived = ( - /** @type {Derived} */ - reaction - ); - batch_values?.delete(derived); - if ((flags2 & WAS_MARKED) === 0) { - if (flags2 & CONNECTED) { - reaction.f |= WAS_MARKED; - } - mark_reactions(derived, MAYBE_DIRTY); - } - } else if (not_dirty) { - if ((flags2 & BLOCK_EFFECT) !== 0 && eager_block_effects !== null) { - eager_block_effects.add( - /** @type {Effect} */ - reaction - ); - } - schedule_effect( - /** @type {Effect} */ - reaction - ); - } - } -} -function proxy(value) { - if (typeof value !== "object" || value === null || STATE_SYMBOL in value) { - return value; - } - const prototype = get_prototype_of(value); - if (prototype !== object_prototype && prototype !== array_prototype) { - return value; - } - var sources = /* @__PURE__ */ new Map(); - var is_proxied_array = is_array(value); - var version = /* @__PURE__ */ state(0); - var parent_version = update_version; - var with_parent = (fn) => { - if (update_version === parent_version) { - return fn(); - } - var reaction = active_reaction; - var version2 = update_version; - set_active_reaction(null); - set_update_version(parent_version); - var result = fn(); - set_active_reaction(reaction); - set_update_version(version2); - return result; - }; - if (is_proxied_array) { - sources.set("length", /* @__PURE__ */ state( - /** @type {any[]} */ - value.length - )); - } - return new Proxy( - /** @type {any} */ - value, - { - defineProperty(_, prop, descriptor) { - if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) { - state_descriptors_fixed(); - } - var s = sources.get(prop); - if (s === void 0) { - s = with_parent(() => { - var s2 = /* @__PURE__ */ state(descriptor.value); - sources.set(prop, s2); - return s2; - }); - } else { - set(s, descriptor.value, true); - } - return true; - }, - deleteProperty(target, prop) { - var s = sources.get(prop); - if (s === void 0) { - if (prop in target) { - const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); - sources.set(prop, s2); - increment(version); - } - } else { - set(s, UNINITIALIZED); - increment(version); - } - return true; - }, - get(target, prop, receiver) { - if (prop === STATE_SYMBOL) { - return value; - } - var s = sources.get(prop); - var exists = prop in target; - if (s === void 0 && (!exists || get_descriptor(target, prop)?.writable)) { - s = with_parent(() => { - var p = proxy(exists ? target[prop] : UNINITIALIZED); - var s2 = /* @__PURE__ */ state(p); - return s2; - }); - sources.set(prop, s); - } - if (s !== void 0) { - var v = get(s); - return v === UNINITIALIZED ? void 0 : v; - } - return Reflect.get(target, prop, receiver); - }, - getOwnPropertyDescriptor(target, prop) { - var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); - if (descriptor && "value" in descriptor) { - var s = sources.get(prop); - if (s) descriptor.value = get(s); - } else if (descriptor === void 0) { - var source2 = sources.get(prop); - var value2 = source2?.v; - if (source2 !== void 0 && value2 !== UNINITIALIZED) { - return { - enumerable: true, - configurable: true, - value: value2, - writable: true - }; - } - } - return descriptor; - }, - has(target, prop) { - if (prop === STATE_SYMBOL) { - return true; - } - var s = sources.get(prop); - var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop); - if (s !== void 0 || active_effect !== null && (!has || get_descriptor(target, prop)?.writable)) { - if (s === void 0) { - s = with_parent(() => { - var p = has ? proxy(target[prop]) : UNINITIALIZED; - var s2 = /* @__PURE__ */ state(p); - return s2; - }); - sources.set(prop, s); - } - var value2 = get(s); - if (value2 === UNINITIALIZED) { - return false; - } - } - return has; - }, - set(target, prop, value2, receiver) { - var s = sources.get(prop); - var has = prop in target; - if (is_proxied_array && prop === "length") { - for (var i = value2; i < /** @type {Source} */ - s.v; i += 1) { - var other_s = sources.get(i + ""); - if (other_s !== void 0) { - set(other_s, UNINITIALIZED); - } else if (i in target) { - other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); - sources.set(i + "", other_s); - } - } - } - if (s === void 0) { - if (!has || get_descriptor(target, prop)?.writable) { - s = with_parent(() => /* @__PURE__ */ state(void 0)); - set(s, proxy(value2)); - sources.set(prop, s); - } - } else { - has = s.v !== UNINITIALIZED; - var p = with_parent(() => proxy(value2)); - set(s, p); - } - var descriptor = Reflect.getOwnPropertyDescriptor(target, prop); - if (descriptor?.set) { - descriptor.set.call(receiver, value2); - } - if (!has) { - if (is_proxied_array && typeof prop === "string") { - var ls = ( - /** @type {Source} */ - sources.get("length") - ); - var n = Number(prop); - if (Number.isInteger(n) && n >= ls.v) { - set(ls, n + 1); - } - } - increment(version); - } - return true; - }, - ownKeys(target) { - get(version); - var own_keys = Reflect.ownKeys(target).filter((key2) => { - var source3 = sources.get(key2); - return source3 === void 0 || source3.v !== UNINITIALIZED; - }); - for (var [key, source2] of sources) { - if (source2.v !== UNINITIALIZED && !(key in target)) { - own_keys.push(key); - } - } - return own_keys; - }, - setPrototypeOf() { - state_prototype_fixed(); - } - } - ); -} -var $window; -var first_child_getter; -var next_sibling_getter; -function init_operations() { - if ($window !== void 0) { - return; - } - $window = window; - var element_prototype = Element.prototype; - var node_prototype = Node.prototype; - var text_prototype = Text.prototype; - first_child_getter = get_descriptor(node_prototype, "firstChild").get; - next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get; - if (is_extensible(element_prototype)) { - element_prototype.__click = void 0; - element_prototype.__className = void 0; - element_prototype.__attributes = null; - element_prototype.__style = void 0; - element_prototype.__e = void 0; - } - if (is_extensible(text_prototype)) { - text_prototype.__t = void 0; - } -} -function create_text(value = "") { - return document.createTextNode(value); -} -// @__NO_SIDE_EFFECTS__ -function get_first_child(node) { - return ( - /** @type {TemplateNode | null} */ - first_child_getter.call(node) - ); -} -// @__NO_SIDE_EFFECTS__ -function get_next_sibling(node) { - return ( - /** @type {TemplateNode | null} */ - next_sibling_getter.call(node) - ); -} -function clear_text_content(node) { - node.textContent = ""; -} -function without_reactive_context(fn) { - var previous_reaction = active_reaction; - var previous_effect = active_effect; - set_active_reaction(null); - set_active_effect(null); - try { - return fn(); - } finally { - set_active_reaction(previous_reaction); - set_active_effect(previous_effect); - } -} -function push_effect(effect, parent_effect) { - var parent_last = parent_effect.last; - if (parent_last === null) { - parent_effect.last = parent_effect.first = effect; - } else { - parent_last.next = effect; - effect.prev = parent_last; - parent_effect.last = effect; - } -} -function create_effect(type, fn, sync) { - var parent = active_effect; - if (parent !== null && (parent.f & INERT) !== 0) { - type |= INERT; - } - var effect = { - ctx: component_context, - deps: null, - nodes: null, - f: type | DIRTY | CONNECTED, - first: null, - fn, - last: null, - next: null, - parent, - b: parent && parent.b, - prev: null, - teardown: null, - wv: 0, - ac: null - }; - if (sync) { - try { - update_effect(effect); - effect.f |= EFFECT_RAN; - } catch (e2) { - destroy_effect(effect); - throw e2; - } - } else if (fn !== null) { - schedule_effect(effect); - } - var e = effect; - if (sync && e.deps === null && e.teardown === null && e.nodes === null && e.first === e.last && // either `null`, or a singular child - (e.f & EFFECT_PRESERVED) === 0) { - e = e.first; - if ((type & BLOCK_EFFECT) !== 0 && (type & EFFECT_TRANSPARENT) !== 0 && e !== null) { - e.f |= EFFECT_TRANSPARENT; - } - } - if (e !== null) { - e.parent = parent; - if (parent !== null) { - push_effect(e, parent); - } - if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0 && (type & ROOT_EFFECT) === 0) { - var derived = ( - /** @type {Derived} */ - active_reaction - ); - (derived.effects ??= []).push(e); - } - } - return effect; -} -function effect_tracking() { - return active_reaction !== null && !untracking; -} -function create_user_effect(fn) { - return create_effect(EFFECT | USER_EFFECT, fn, false); -} -function component_root(fn) { - Batch.ensure(); - const effect = create_effect(ROOT_EFFECT | EFFECT_PRESERVED, fn, true); - return (options2 = {}) => { - return new Promise((fulfil) => { - if (options2.outro) { - pause_effect(effect, () => { - destroy_effect(effect); - fulfil(void 0); - }); - } else { - destroy_effect(effect); - fulfil(void 0); - } - }); - }; -} -function render_effect(fn, flags2 = 0) { - return create_effect(RENDER_EFFECT | flags2, fn, true); -} -function block(fn, flags2 = 0) { - var effect = create_effect(BLOCK_EFFECT | flags2, fn, true); - return effect; -} -function branch(fn) { - return create_effect(BRANCH_EFFECT | EFFECT_PRESERVED, fn, true); -} -function execute_effect_teardown(effect) { - var teardown = effect.teardown; - if (teardown !== null) { - const previously_destroying_effect = is_destroying_effect; - const previous_reaction = active_reaction; - set_is_destroying_effect(true); - set_active_reaction(null); - try { - teardown.call(null); - } finally { - set_is_destroying_effect(previously_destroying_effect); - set_active_reaction(previous_reaction); - } - } -} -function destroy_effect_children(signal, remove_dom = false) { - var effect = signal.first; - signal.first = signal.last = null; - while (effect !== null) { - const controller = effect.ac; - if (controller !== null) { - without_reactive_context(() => { - controller.abort(STALE_REACTION); - }); - } - var next2 = effect.next; - if ((effect.f & ROOT_EFFECT) !== 0) { - effect.parent = null; - } else { - destroy_effect(effect, remove_dom); - } - effect = next2; - } -} -function destroy_block_effect_children(signal) { - var effect = signal.first; - while (effect !== null) { - var next2 = effect.next; - if ((effect.f & BRANCH_EFFECT) === 0) { - destroy_effect(effect); - } - effect = next2; - } -} -function destroy_effect(effect, remove_dom = true) { - var removed = false; - if ((remove_dom || (effect.f & HEAD_EFFECT) !== 0) && effect.nodes !== null && effect.nodes.end !== null) { - remove_effect_dom( - effect.nodes.start, - /** @type {TemplateNode} */ - effect.nodes.end - ); - removed = true; - } - destroy_effect_children(effect, remove_dom && !removed); - remove_reactions(effect, 0); - set_signal_status(effect, DESTROYED); - var transitions = effect.nodes && effect.nodes.t; - if (transitions !== null) { - for (const transition of transitions) { - transition.stop(); - } - } - execute_effect_teardown(effect); - var parent = effect.parent; - if (parent !== null && parent.first !== null) { - unlink_effect(effect); - } - effect.next = effect.prev = effect.teardown = effect.ctx = effect.deps = effect.fn = effect.nodes = effect.ac = null; -} -function remove_effect_dom(node, end) { - while (node !== null) { - var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); - node.remove(); - node = next2; - } -} -function unlink_effect(effect) { - var parent = effect.parent; - var prev = effect.prev; - var next2 = effect.next; - if (prev !== null) prev.next = next2; - if (next2 !== null) next2.prev = prev; - if (parent !== null) { - if (parent.first === effect) parent.first = next2; - if (parent.last === effect) parent.last = prev; - } -} -function pause_effect(effect, callback, destroy = true) { - var transitions = []; - pause_children(effect, transitions, true); - var fn = () => { - if (destroy) destroy_effect(effect); - if (callback) callback(); - }; - var remaining = transitions.length; - if (remaining > 0) { - var check = () => --remaining || fn(); - for (var transition of transitions) { - transition.out(check); - } - } else { - fn(); - } -} -function pause_children(effect, transitions, local) { - if ((effect.f & INERT) !== 0) return; - effect.f ^= INERT; - var t = effect.nodes && effect.nodes.t; - if (t !== null) { - for (const transition of t) { - if (transition.is_global || local) { - transitions.push(transition); - } - } - } - var child = effect.first; - while (child !== null) { - var sibling = child.next; - var transparent = (child.f & EFFECT_TRANSPARENT) !== 0 || // If this is a branch effect without a block effect parent, - // it means the parent block effect was pruned. In that case, - // transparency information was transferred to the branch effect. - (child.f & BRANCH_EFFECT) !== 0 && (effect.f & BLOCK_EFFECT) !== 0; - pause_children(child, transitions, transparent ? local : false); - child = sibling; - } -} -function move_effect(effect, fragment) { - if (!effect.nodes) return; - var node = effect.nodes.start; - var end = effect.nodes.end; - while (node !== null) { - var next2 = node === end ? null : /* @__PURE__ */ get_next_sibling(node); - fragment.append(node); - node = next2; - } -} -let is_updating_effect = false; -let is_destroying_effect = false; -function set_is_destroying_effect(value) { - is_destroying_effect = value; -} -let active_reaction = null; -let untracking = false; -function set_active_reaction(reaction) { - active_reaction = reaction; -} -let active_effect = null; -function set_active_effect(effect) { - active_effect = effect; -} -let current_sources = null; -function push_reaction_value(value) { - if (active_reaction !== null && true) { - if (current_sources === null) { - current_sources = [value]; - } else { - current_sources.push(value); - } - } -} -let new_deps = null; -let skipped_deps = 0; -let untracked_writes = null; -function set_untracked_writes(value) { - untracked_writes = value; -} -let write_version = 1; -let read_version = 0; -let update_version = read_version; -function set_update_version(value) { - update_version = value; -} -function increment_write_version() { - return ++write_version; -} -function is_dirty(reaction) { - var flags2 = reaction.f; - if ((flags2 & DIRTY) !== 0) { - return true; - } - if (flags2 & DERIVED) { - reaction.f &= ~WAS_MARKED; - } - if ((flags2 & MAYBE_DIRTY) !== 0) { - var dependencies = ( - /** @type {Value[]} */ - reaction.deps - ); - var length = dependencies.length; - for (var i = 0; i < length; i++) { - var dependency = dependencies[i]; - if (is_dirty( - /** @type {Derived} */ - dependency - )) { - update_derived( - /** @type {Derived} */ - dependency - ); - } - if (dependency.wv > reaction.wv) { - return true; - } - } - if ((flags2 & CONNECTED) !== 0 && // During time traveling we don't want to reset the status so that - // traversal of the graph in the other batches still happens - batch_values === null) { - set_signal_status(reaction, CLEAN); - } - } - return false; -} -function schedule_possible_effect_self_invalidation(signal, effect, root2 = true) { - var reactions = signal.reactions; - if (reactions === null) return; - if (current_sources !== null && includes.call(current_sources, signal)) { - return; - } - for (var i = 0; i < reactions.length; i++) { - var reaction = reactions[i]; - if ((reaction.f & DERIVED) !== 0) { - schedule_possible_effect_self_invalidation( - /** @type {Derived} */ - reaction, - effect, - false - ); - } else if (effect === reaction) { - if (root2) { - set_signal_status(reaction, DIRTY); - } else if ((reaction.f & CLEAN) !== 0) { - set_signal_status(reaction, MAYBE_DIRTY); - } - schedule_effect( - /** @type {Effect} */ - reaction - ); - } - } -} -function update_reaction(reaction) { - var previous_deps = new_deps; - var previous_skipped_deps = skipped_deps; - var previous_untracked_writes = untracked_writes; - var previous_reaction = active_reaction; - var previous_sources = current_sources; - var previous_component_context = component_context; - var previous_untracking = untracking; - var previous_update_version = update_version; - var flags2 = reaction.f; - new_deps = /** @type {null | Value[]} */ - null; - skipped_deps = 0; - untracked_writes = null; - active_reaction = (flags2 & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; - current_sources = null; - set_component_context(reaction.ctx); - untracking = false; - update_version = ++read_version; - if (reaction.ac !== null) { - without_reactive_context(() => { - reaction.ac.abort(STALE_REACTION); - }); - reaction.ac = null; - } - try { - reaction.f |= REACTION_IS_UPDATING; - var fn = ( - /** @type {Function} */ - reaction.fn - ); - var result = fn(); - var deps = reaction.deps; - var is_fork = current_batch?.is_fork; - if (new_deps !== null) { - var i; - if (!is_fork) { - remove_reactions(reaction, skipped_deps); - } - if (deps !== null && skipped_deps > 0) { - deps.length = skipped_deps + new_deps.length; - for (i = 0; i < new_deps.length; i++) { - deps[skipped_deps + i] = new_deps[i]; - } - } else { - reaction.deps = deps = new_deps; - } - if (effect_tracking() && (reaction.f & CONNECTED) !== 0) { - for (i = skipped_deps; i < deps.length; i++) { - (deps[i].reactions ??= []).push(reaction); - } - } - } else if (!is_fork && deps !== null && skipped_deps < deps.length) { - remove_reactions(reaction, skipped_deps); - deps.length = skipped_deps; - } - if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) { - for (i = 0; i < /** @type {Source[]} */ - untracked_writes.length; i++) { - schedule_possible_effect_self_invalidation( - untracked_writes[i], - /** @type {Effect} */ - reaction - ); - } - } - if (previous_reaction !== null && previous_reaction !== reaction) { - read_version++; - if (previous_reaction.deps !== null) { - for (let i2 = 0; i2 < previous_skipped_deps; i2 += 1) { - previous_reaction.deps[i2].rv = read_version; - } - } - if (previous_deps !== null) { - for (const dep of previous_deps) { - dep.rv = read_version; - } - } - if (untracked_writes !== null) { - if (previous_untracked_writes === null) { - previous_untracked_writes = untracked_writes; - } else { - previous_untracked_writes.push(.../** @type {Source[]} */ - untracked_writes); - } - } - } - if ((reaction.f & ERROR_VALUE) !== 0) { - reaction.f ^= ERROR_VALUE; - } - return result; - } catch (error) { - return handle_error(error); - } finally { - reaction.f ^= REACTION_IS_UPDATING; - new_deps = previous_deps; - skipped_deps = previous_skipped_deps; - untracked_writes = previous_untracked_writes; - active_reaction = previous_reaction; - current_sources = previous_sources; - set_component_context(previous_component_context); - untracking = previous_untracking; - update_version = previous_update_version; - } -} -function remove_reaction(signal, dependency) { - let reactions = dependency.reactions; - if (reactions !== null) { - var index = index_of.call(reactions, signal); - if (index !== -1) { - var new_length = reactions.length - 1; - if (new_length === 0) { - reactions = dependency.reactions = null; - } else { - reactions[index] = reactions[new_length]; - reactions.pop(); - } - } - } - if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear - // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` - // allows us to skip the expensive work of disconnecting and immediately reconnecting it - (new_deps === null || !includes.call(new_deps, dependency))) { - var derived = ( - /** @type {Derived} */ - dependency - ); - if ((derived.f & CONNECTED) !== 0) { - derived.f ^= CONNECTED; - derived.f &= ~WAS_MARKED; - } - update_derived_status(derived); - destroy_derived_effects(derived); - remove_reactions(derived, 0); - } -} -function remove_reactions(signal, start_index) { - var dependencies = signal.deps; - if (dependencies === null) return; - for (var i = start_index; i < dependencies.length; i++) { - remove_reaction(signal, dependencies[i]); - } -} -function update_effect(effect) { - var flags2 = effect.f; - if ((flags2 & DESTROYED) !== 0) { - return; - } - set_signal_status(effect, CLEAN); - var previous_effect = active_effect; - var was_updating_effect = is_updating_effect; - active_effect = effect; - is_updating_effect = true; - try { - if ((flags2 & (BLOCK_EFFECT | MANAGED_EFFECT)) !== 0) { - destroy_block_effect_children(effect); - } else { - destroy_effect_children(effect); - } - execute_effect_teardown(effect); - var teardown = update_reaction(effect); - effect.teardown = typeof teardown === "function" ? teardown : null; - effect.wv = write_version; - var dep; - if (BROWSER && tracing_mode_flag && (effect.f & DIRTY) !== 0 && effect.deps !== null) ; - } finally { - is_updating_effect = was_updating_effect; - active_effect = previous_effect; - } -} -function get(signal) { - var flags2 = signal.f; - var is_derived = (flags2 & DERIVED) !== 0; - if (active_reaction !== null && !untracking) { - var destroyed = active_effect !== null && (active_effect.f & DESTROYED) !== 0; - if (!destroyed && (current_sources === null || !includes.call(current_sources, signal))) { - var deps = active_reaction.deps; - if ((active_reaction.f & REACTION_IS_UPDATING) !== 0) { - if (signal.rv < read_version) { - signal.rv = read_version; - if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { - skipped_deps++; - } else if (new_deps === null) { - new_deps = [signal]; - } else { - new_deps.push(signal); - } - } - } else { - (active_reaction.deps ??= []).push(signal); - var reactions = signal.reactions; - if (reactions === null) { - signal.reactions = [active_reaction]; - } else if (!includes.call(reactions, active_reaction)) { - reactions.push(active_reaction); - } - } - } - } - if (is_destroying_effect && old_values.has(signal)) { - return old_values.get(signal); - } - if (is_derived) { - var derived = ( - /** @type {Derived} */ - signal - ); - if (is_destroying_effect) { - var value = derived.v; - if ((derived.f & CLEAN) === 0 && derived.reactions !== null || depends_on_old_values(derived)) { - value = execute_derived(derived); - } - old_values.set(derived, value); - return value; - } - var should_connect = (derived.f & CONNECTED) === 0 && !untracking && active_reaction !== null && (is_updating_effect || (active_reaction.f & CONNECTED) !== 0); - var is_new = derived.deps === null; - if (is_dirty(derived)) { - if (should_connect) { - derived.f |= CONNECTED; - } - update_derived(derived); - } - if (should_connect && !is_new) { - reconnect(derived); - } - } - if (batch_values?.has(signal)) { - return batch_values.get(signal); - } - if ((signal.f & ERROR_VALUE) !== 0) { - throw signal.v; - } - return signal.v; -} -function reconnect(derived) { - if (derived.deps === null) return; - derived.f |= CONNECTED; - for (const dep of derived.deps) { - (dep.reactions ??= []).push(derived); - if ((dep.f & DERIVED) !== 0 && (dep.f & CONNECTED) === 0) { - reconnect( - /** @type {Derived} */ - dep - ); - } - } -} -function depends_on_old_values(derived) { - if (derived.v === UNINITIALIZED) return true; - if (derived.deps === null) return false; - for (const dep of derived.deps) { - if (old_values.has(dep)) { - return true; - } - if ((dep.f & DERIVED) !== 0 && depends_on_old_values( - /** @type {Derived} */ - dep - )) { - return true; - } - } - return false; -} -function untrack(fn) { - var previous_untracking = untracking; - try { - untracking = true; - return fn(); - } finally { - untracking = previous_untracking; - } -} -const all_registered_events = /* @__PURE__ */ new Set(); -const root_event_handles = /* @__PURE__ */ new Set(); -let last_propagated_event = null; -function handle_event_propagation(event) { - var handler_element = this; - var owner_document = ( - /** @type {Node} */ - handler_element.ownerDocument - ); - var event_name = event.type; - var path = event.composedPath?.() || []; - var current_target = ( - /** @type {null | Element} */ - path[0] || event.target - ); - last_propagated_event = event; - var path_idx = 0; - var handled_at = last_propagated_event === event && event.__root; - if (handled_at) { - var at_idx = path.indexOf(handled_at); - if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */ - window)) { - event.__root = handler_element; - return; - } - var handler_idx = path.indexOf(handler_element); - if (handler_idx === -1) { - return; - } - if (at_idx <= handler_idx) { - path_idx = at_idx; - } - } - current_target = /** @type {Element} */ - path[path_idx] || event.target; - if (current_target === handler_element) return; - define_property(event, "currentTarget", { - configurable: true, - get() { - return current_target || owner_document; - } - }); - var previous_reaction = active_reaction; - var previous_effect = active_effect; - set_active_reaction(null); - set_active_effect(null); - try { - var throw_error; - var other_errors = []; - while (current_target !== null) { - var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */ - current_target.host || null; - try { - var delegated = current_target["__" + event_name]; - if (delegated != null && (!/** @type {any} */ - current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well - // -> the target could not have been disabled because it emits the event in the first place - event.target === current_target)) { - delegated.call(current_target, event); - } - } catch (error) { - if (throw_error) { - other_errors.push(error); - } else { - throw_error = error; - } - } - if (event.cancelBubble || parent_element === handler_element || parent_element === null) { - break; - } - current_target = parent_element; - } - if (throw_error) { - for (let error of other_errors) { - queueMicrotask(() => { - throw error; - }); - } - throw throw_error; - } - } finally { - event.__root = handler_element; - delete event.currentTarget; - set_active_reaction(previous_reaction); - set_active_effect(previous_effect); - } -} -function assign_nodes(start, end) { - var effect = ( - /** @type {Effect} */ - active_effect - ); - if (effect.nodes === null) { - effect.nodes = { start, end, a: null, t: null }; - } -} -function mount(component, options2) { - return _mount(component, options2); -} -function hydrate(component, options2) { - init_operations(); - options2.intro = options2.intro ?? false; - const target = options2.target; - const was_hydrating = hydrating; - const previous_hydrate_node = hydrate_node; - try { - var anchor = /* @__PURE__ */ get_first_child(target); - while (anchor && (anchor.nodeType !== COMMENT_NODE || /** @type {Comment} */ - anchor.data !== HYDRATION_START)) { - anchor = /* @__PURE__ */ get_next_sibling(anchor); - } - if (!anchor) { - throw HYDRATION_ERROR; - } - set_hydrating(true); - set_hydrate_node( - /** @type {Comment} */ - anchor - ); - const instance = _mount(component, { ...options2, anchor }); - set_hydrating(false); - return ( - /** @type {Exports} */ - instance - ); - } catch (error) { - if (error instanceof Error && error.message.split("\n").some((line) => line.startsWith("https://svelte.dev/e/"))) { - throw error; - } - if (error !== HYDRATION_ERROR) { - console.warn("Failed to hydrate: ", error); - } - if (options2.recover === false) { - hydration_failed(); - } - init_operations(); - clear_text_content(target); - set_hydrating(false); - return mount(component, options2); - } finally { - set_hydrating(was_hydrating); - set_hydrate_node(previous_hydrate_node); - } -} -const document_listeners = /* @__PURE__ */ new Map(); -function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) { - init_operations(); - var registered_events = /* @__PURE__ */ new Set(); - var event_handle = (events2) => { - for (var i = 0; i < events2.length; i++) { - var event_name = events2[i]; - if (registered_events.has(event_name)) continue; - registered_events.add(event_name); - var passive = is_passive_event(event_name); - target.addEventListener(event_name, handle_event_propagation, { passive }); - var n = document_listeners.get(event_name); - if (n === void 0) { - document.addEventListener(event_name, handle_event_propagation, { passive }); - document_listeners.set(event_name, 1); - } else { - document_listeners.set(event_name, n + 1); - } - } - }; - event_handle(array_from(all_registered_events)); - root_event_handles.add(event_handle); - var component = void 0; - var unmount2 = component_root(() => { - var anchor_node = anchor ?? target.appendChild(create_text()); - boundary( - /** @type {TemplateNode} */ - anchor_node, - { - pending: () => { - } - }, - (anchor_node2) => { - push({}); - var ctx = ( - /** @type {ComponentContext} */ - component_context - ); - if (context) ctx.c = context; - if (events) { - props.$$events = events; - } - if (hydrating) { - assign_nodes( - /** @type {TemplateNode} */ - anchor_node2, - null - ); - } - component = Component(anchor_node2, props) || {}; - if (hydrating) { - active_effect.nodes.end = hydrate_node; - if (hydrate_node === null || hydrate_node.nodeType !== COMMENT_NODE || /** @type {Comment} */ - hydrate_node.data !== HYDRATION_END) { - hydration_mismatch(); - throw HYDRATION_ERROR; - } - } - pop(); - } - ); - return () => { - for (var event_name of registered_events) { - target.removeEventListener(event_name, handle_event_propagation); - var n = ( - /** @type {number} */ - document_listeners.get(event_name) - ); - if (--n === 0) { - document.removeEventListener(event_name, handle_event_propagation); - document_listeners.delete(event_name); - } else { - document_listeners.set(event_name, n); - } - } - root_event_handles.delete(event_handle); - if (anchor_node !== anchor) { - anchor_node.parentNode?.removeChild(anchor_node); - } - }; - }); - mounted_components.set(component, unmount2); - return component; -} -let mounted_components = /* @__PURE__ */ new WeakMap(); -function unmount(component, options2) { - const fn = mounted_components.get(component); - if (fn) { - mounted_components.delete(component); - return fn(options2); - } - return Promise.resolve(); -} -function asClassComponent$1(component) { - return class extends Svelte4Component { - /** @param {any} options */ - constructor(options2) { - super({ - component, - ...options2 - }); - } - }; -} -class Svelte4Component { - /** @type {any} */ - #events; - /** @type {Record} */ - #instance; - /** - * @param {ComponentConstructorOptions & { - * component: any; - * }} options - */ - constructor(options2) { - var sources = /* @__PURE__ */ new Map(); - var add_source = (key, value) => { - var s = /* @__PURE__ */ mutable_source(value, false, false); - sources.set(key, s); - return s; - }; - const props = new Proxy( - { ...options2.props || {}, $$events: {} }, - { - get(target, prop) { - return get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); - }, - has(target, prop) { - if (prop === LEGACY_PROPS) return true; - get(sources.get(prop) ?? add_source(prop, Reflect.get(target, prop))); - return Reflect.has(target, prop); - }, - set(target, prop, value) { - set(sources.get(prop) ?? add_source(prop, value), value); - return Reflect.set(target, prop, value); - } - } - ); - this.#instance = (options2.hydrate ? hydrate : mount)(options2.component, { - target: options2.target, - anchor: options2.anchor, - props, - context: options2.context, - intro: options2.intro ?? false, - recover: options2.recover - }); - if (!options2?.props?.$$host || options2.sync === false) { - flushSync(); - } - this.#events = props.$$events; - for (const key of Object.keys(this.#instance)) { - if (key === "$set" || key === "$destroy" || key === "$on") continue; - define_property(this, key, { - get() { - return this.#instance[key]; - }, - /** @param {any} value */ - set(value) { - this.#instance[key] = value; - }, - enumerable: true - }); - } - this.#instance.$set = /** @param {Record} next */ - (next2) => { - Object.assign(props, next2); - }; - this.#instance.$destroy = () => { - unmount(this.#instance); - }; - } - /** @param {Record} props */ - $set(props) { - this.#instance.$set(props); - } - /** - * @param {string} event - * @param {(...args: any[]) => any} callback - * @returns {any} - */ - $on(event, callback) { - this.#events[event] = this.#events[event] || []; - const cb = (...args) => callback.call(this, ...args); - this.#events[event].push(cb); - return () => { - this.#events[event] = this.#events[event].filter( - /** @param {any} fn */ - (fn) => fn !== cb - ); - }; - } - $destroy() { - this.#instance.$destroy(); - } -} -let read_implementation = null; -function set_read_implementation(fn) { - read_implementation = fn; -} -function set_manifest(_) { -} -function asClassComponent(component) { - const component_constructor = asClassComponent$1(component); - const _render = (props, { context, csp } = {}) => { - const result = render(component, { props, context, csp }); - const munged = Object.defineProperties( - /** @type {LegacyRenderResult & PromiseLike} */ - {}, - { - css: { - value: { code: "", map: null } - }, - head: { - get: () => result.head - }, - html: { - get: () => result.body - }, - then: { - /** - * this is not type-safe, but honestly it's the best I can do right now, and it's a straightforward function. - * - * @template TResult1 - * @template [TResult2=never] - * @param { (value: LegacyRenderResult) => TResult1 } onfulfilled - * @param { (reason: unknown) => TResult2 } onrejected - */ - value: (onfulfilled, onrejected) => { - { - const user_result = onfulfilled({ - css: munged.css, - head: munged.head, - html: munged.html - }); - return Promise.resolve(user_result); - } - } - } - } - ); - return munged; - }; - component_constructor.render = _render; - return component_constructor; -} -function Root($$renderer, $$props) { - $$renderer.component(($$renderer2) => { - let { - stores, - page, - constructors, - components = [], - form, - data_0 = null, - data_1 = null - } = $$props; - { - setContext("__svelte__", stores); - } - { - stores.page.set(page); - } - const Pyramid_1 = constructors[1]; - if (constructors[1]) { - $$renderer2.push(""); - const Pyramid_0 = constructors[0]; - $$renderer2.push(""); - Pyramid_0?.($$renderer2, { - data: data_0, - form, - params: page.params, - children: ($$renderer3) => { - $$renderer3.push(""); - Pyramid_1?.($$renderer3, { data: data_1, form, params: page.params }); - $$renderer3.push(``); - }, - $$slots: { default: true } - }); - $$renderer2.push(``); - } else { - $$renderer2.push(""); - const Pyramid_0 = constructors[0]; - $$renderer2.push(""); - Pyramid_0?.($$renderer2, { data: data_0, form, params: page.params }); - $$renderer2.push(``); - } - $$renderer2.push(` `); - { - $$renderer2.push(""); - } - $$renderer2.push(``); - }); -} -const root = asClassComponent(Root); -const options = { - app_template_contains_nonce: false, - async: false, - csp: { "mode": "auto", "directives": { "upgrade-insecure-requests": false, "block-all-mixed-content": false }, "reportOnly": { "upgrade-insecure-requests": false, "block-all-mixed-content": false } }, - csrf_check_origin: true, - csrf_trusted_origins: [], - embedded: false, - env_public_prefix: "PUBLIC_", - env_private_prefix: "", - hash_routing: false, - hooks: null, - // added lazily, via `get_hooks` - preload_strategy: "modulepreload", - root, - service_worker: false, - service_worker_options: void 0, - templates: { - app: ({ head, body, assets, nonce, env }) => '\n\n \n \n \n ' + head + '\n \n \n
' + body + "
\n \n\n", - error: ({ status, message }) => '\n\n \n \n ' + message + ` - - - - -
- ` + status + '\n
\n

' + message + "

\n
\n
\n \n\n" - }, - version_hash: "zurjbz" -}; -async function get_hooks() { - let handle; - let handleFetch; - let handleError; - let handleValidationError; - let init; - let reroute; - let transport; - return { - handle, - handleFetch, - handleError, - handleValidationError, - init, - reroute, - transport - }; -} -export { - set_public_env as a, - set_read_implementation as b, - set_manifest as c, - get_hooks as g, - options as o, - public_env as p, - read_implementation as r, - set_private_env as s -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js deleted file mode 100644 index 73ff856..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/shared.js +++ /dev/null @@ -1,1188 +0,0 @@ -import { json, text } from "@sveltejs/kit"; -import { SvelteKitError, HttpError } from "@sveltejs/kit/internal"; -import { with_request_store } from "@sveltejs/kit/internal/server"; -import { t as text_decoder, b as base64_encode, c as base64_decode } from "./utils.js"; -import { D as DevalueError, i as is_primitive, g as get_type, a as is_plain_object, e as enumerable_symbols, s as stringify_key, b as stringify_string } from "./utils2.js"; -const SVELTE_KIT_ASSETS = "/_svelte_kit_assets"; -const ENDPOINT_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; -const PAGE_METHODS = ["GET", "POST", "HEAD"]; -function encode64(arraybuffer) { - const dv = new DataView(arraybuffer); - let binaryString = ""; - for (let i = 0; i < arraybuffer.byteLength; i++) { - binaryString += String.fromCharCode(dv.getUint8(i)); - } - return binaryToAscii(binaryString); -} -function decode64(string) { - const binaryString = asciiToBinary(string); - const arraybuffer = new ArrayBuffer(binaryString.length); - const dv = new DataView(arraybuffer); - for (let i = 0; i < arraybuffer.byteLength; i++) { - dv.setUint8(i, binaryString.charCodeAt(i)); - } - return arraybuffer; -} -const KEY_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -function asciiToBinary(data) { - if (data.length % 4 === 0) { - data = data.replace(/==?$/, ""); - } - let output = ""; - let buffer = 0; - let accumulatedBits = 0; - for (let i = 0; i < data.length; i++) { - buffer <<= 6; - buffer |= KEY_STRING.indexOf(data[i]); - accumulatedBits += 6; - if (accumulatedBits === 24) { - output += String.fromCharCode((buffer & 16711680) >> 16); - output += String.fromCharCode((buffer & 65280) >> 8); - output += String.fromCharCode(buffer & 255); - buffer = accumulatedBits = 0; - } - } - if (accumulatedBits === 12) { - buffer >>= 4; - output += String.fromCharCode(buffer); - } else if (accumulatedBits === 18) { - buffer >>= 2; - output += String.fromCharCode((buffer & 65280) >> 8); - output += String.fromCharCode(buffer & 255); - } - return output; -} -function binaryToAscii(str) { - let out = ""; - for (let i = 0; i < str.length; i += 3) { - const groupsOfSix = [void 0, void 0, void 0, void 0]; - groupsOfSix[0] = str.charCodeAt(i) >> 2; - groupsOfSix[1] = (str.charCodeAt(i) & 3) << 4; - if (str.length > i + 1) { - groupsOfSix[1] |= str.charCodeAt(i + 1) >> 4; - groupsOfSix[2] = (str.charCodeAt(i + 1) & 15) << 2; - } - if (str.length > i + 2) { - groupsOfSix[2] |= str.charCodeAt(i + 2) >> 6; - groupsOfSix[3] = str.charCodeAt(i + 2) & 63; - } - for (let j = 0; j < groupsOfSix.length; j++) { - if (typeof groupsOfSix[j] === "undefined") { - out += "="; - } else { - out += KEY_STRING[groupsOfSix[j]]; - } - } - } - return out; -} -const UNDEFINED = -1; -const HOLE = -2; -const NAN = -3; -const POSITIVE_INFINITY = -4; -const NEGATIVE_INFINITY = -5; -const NEGATIVE_ZERO = -6; -function parse(serialized, revivers) { - return unflatten(JSON.parse(serialized), revivers); -} -function unflatten(parsed, revivers) { - if (typeof parsed === "number") return hydrate(parsed, true); - if (!Array.isArray(parsed) || parsed.length === 0) { - throw new Error("Invalid input"); - } - const values = ( - /** @type {any[]} */ - parsed - ); - const hydrated = Array(values.length); - let hydrating = null; - function hydrate(index, standalone = false) { - if (index === UNDEFINED) return void 0; - if (index === NAN) return NaN; - if (index === POSITIVE_INFINITY) return Infinity; - if (index === NEGATIVE_INFINITY) return -Infinity; - if (index === NEGATIVE_ZERO) return -0; - if (standalone || typeof index !== "number") { - throw new Error(`Invalid input`); - } - if (index in hydrated) return hydrated[index]; - const value = values[index]; - if (!value || typeof value !== "object") { - hydrated[index] = value; - } else if (Array.isArray(value)) { - if (typeof value[0] === "string") { - const type = value[0]; - const reviver = revivers && Object.hasOwn(revivers, type) ? revivers[type] : void 0; - if (reviver) { - let i = value[1]; - if (typeof i !== "number") { - i = values.push(value[1]) - 1; - } - hydrating ??= /* @__PURE__ */ new Set(); - if (hydrating.has(i)) { - throw new Error("Invalid circular reference"); - } - hydrating.add(i); - hydrated[index] = reviver(hydrate(i)); - hydrating.delete(i); - return hydrated[index]; - } - switch (type) { - case "Date": - hydrated[index] = new Date(value[1]); - break; - case "Set": - const set = /* @__PURE__ */ new Set(); - hydrated[index] = set; - for (let i = 1; i < value.length; i += 1) { - set.add(hydrate(value[i])); - } - break; - case "Map": - const map = /* @__PURE__ */ new Map(); - hydrated[index] = map; - for (let i = 1; i < value.length; i += 2) { - map.set(hydrate(value[i]), hydrate(value[i + 1])); - } - break; - case "RegExp": - hydrated[index] = new RegExp(value[1], value[2]); - break; - case "Object": - hydrated[index] = Object(value[1]); - break; - case "BigInt": - hydrated[index] = BigInt(value[1]); - break; - case "null": - const obj = /* @__PURE__ */ Object.create(null); - hydrated[index] = obj; - for (let i = 1; i < value.length; i += 2) { - obj[value[i]] = hydrate(value[i + 1]); - } - break; - case "Int8Array": - case "Uint8Array": - case "Uint8ClampedArray": - case "Int16Array": - case "Uint16Array": - case "Int32Array": - case "Uint32Array": - case "Float32Array": - case "Float64Array": - case "BigInt64Array": - case "BigUint64Array": { - if (values[value[1]][0] !== "ArrayBuffer") { - throw new Error("Invalid data"); - } - const TypedArrayConstructor = globalThis[type]; - const buffer = hydrate(value[1]); - const typedArray = new TypedArrayConstructor(buffer); - hydrated[index] = value[2] !== void 0 ? typedArray.subarray(value[2], value[3]) : typedArray; - break; - } - case "ArrayBuffer": { - const base64 = value[1]; - if (typeof base64 !== "string") { - throw new Error("Invalid ArrayBuffer encoding"); - } - const arraybuffer = decode64(base64); - hydrated[index] = arraybuffer; - break; - } - case "Temporal.Duration": - case "Temporal.Instant": - case "Temporal.PlainDate": - case "Temporal.PlainTime": - case "Temporal.PlainDateTime": - case "Temporal.PlainMonthDay": - case "Temporal.PlainYearMonth": - case "Temporal.ZonedDateTime": { - const temporalName = type.slice(9); - hydrated[index] = Temporal[temporalName].from(value[1]); - break; - } - case "URL": { - const url = new URL(value[1]); - hydrated[index] = url; - break; - } - case "URLSearchParams": { - const url = new URLSearchParams(value[1]); - hydrated[index] = url; - break; - } - default: - throw new Error(`Unknown type ${type}`); - } - } else { - const array = new Array(value.length); - hydrated[index] = array; - for (let i = 0; i < value.length; i += 1) { - const n = value[i]; - if (n === HOLE) continue; - array[i] = hydrate(n); - } - } - } else { - const object = {}; - hydrated[index] = object; - for (const key in value) { - if (key === "__proto__") { - throw new Error("Cannot parse an object with a `__proto__` property"); - } - const n = value[key]; - object[key] = hydrate(n); - } - } - return hydrated[index]; - } - return hydrate(0); -} -function stringify$1(value, reducers) { - const stringified = []; - const indexes = /* @__PURE__ */ new Map(); - const custom = []; - if (reducers) { - for (const key of Object.getOwnPropertyNames(reducers)) { - custom.push({ key, fn: reducers[key] }); - } - } - const keys = []; - let p = 0; - function flatten(thing) { - if (thing === void 0) return UNDEFINED; - if (Number.isNaN(thing)) return NAN; - if (thing === Infinity) return POSITIVE_INFINITY; - if (thing === -Infinity) return NEGATIVE_INFINITY; - if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO; - if (indexes.has(thing)) return indexes.get(thing); - const index2 = p++; - indexes.set(thing, index2); - for (const { key, fn } of custom) { - const value2 = fn(thing); - if (value2) { - stringified[index2] = `["${key}",${flatten(value2)}]`; - return index2; - } - } - if (typeof thing === "function") { - throw new DevalueError(`Cannot stringify a function`, keys, thing, value); - } - let str = ""; - if (is_primitive(thing)) { - str = stringify_primitive(thing); - } else { - const type = get_type(thing); - switch (type) { - case "Number": - case "String": - case "Boolean": - str = `["Object",${stringify_primitive(thing)}]`; - break; - case "BigInt": - str = `["BigInt",${thing}]`; - break; - case "Date": - const valid = !isNaN(thing.getDate()); - str = `["Date","${valid ? thing.toISOString() : ""}"]`; - break; - case "URL": - str = `["URL",${stringify_string(thing.toString())}]`; - break; - case "URLSearchParams": - str = `["URLSearchParams",${stringify_string(thing.toString())}]`; - break; - case "RegExp": - const { source, flags } = thing; - str = flags ? `["RegExp",${stringify_string(source)},"${flags}"]` : `["RegExp",${stringify_string(source)}]`; - break; - case "Array": - str = "["; - for (let i = 0; i < thing.length; i += 1) { - if (i > 0) str += ","; - if (i in thing) { - keys.push(`[${i}]`); - str += flatten(thing[i]); - keys.pop(); - } else { - str += HOLE; - } - } - str += "]"; - break; - case "Set": - str = '["Set"'; - for (const value2 of thing) { - str += `,${flatten(value2)}`; - } - str += "]"; - break; - case "Map": - str = '["Map"'; - for (const [key, value2] of thing) { - keys.push( - `.get(${is_primitive(key) ? stringify_primitive(key) : "..."})` - ); - str += `,${flatten(key)},${flatten(value2)}`; - keys.pop(); - } - str += "]"; - break; - case "Int8Array": - case "Uint8Array": - case "Uint8ClampedArray": - case "Int16Array": - case "Uint16Array": - case "Int32Array": - case "Uint32Array": - case "Float32Array": - case "Float64Array": - case "BigInt64Array": - case "BigUint64Array": { - const typedArray = thing; - str = '["' + type + '",' + flatten(typedArray.buffer); - const a = thing.byteOffset; - const b = a + thing.byteLength; - if (a > 0 || b !== typedArray.buffer.byteLength) { - const m = +/(\d+)/.exec(type)[1] / 8; - str += `,${a / m},${b / m}`; - } - str += "]"; - break; - } - case "ArrayBuffer": { - const arraybuffer = thing; - const base64 = encode64(arraybuffer); - str = `["ArrayBuffer","${base64}"]`; - break; - } - case "Temporal.Duration": - case "Temporal.Instant": - case "Temporal.PlainDate": - case "Temporal.PlainTime": - case "Temporal.PlainDateTime": - case "Temporal.PlainMonthDay": - case "Temporal.PlainYearMonth": - case "Temporal.ZonedDateTime": - str = `["${type}",${stringify_string(thing.toString())}]`; - break; - default: - if (!is_plain_object(thing)) { - throw new DevalueError( - `Cannot stringify arbitrary non-POJOs`, - keys, - thing, - value - ); - } - if (enumerable_symbols(thing).length > 0) { - throw new DevalueError( - `Cannot stringify POJOs with symbolic keys`, - keys, - thing, - value - ); - } - if (Object.getPrototypeOf(thing) === null) { - str = '["null"'; - for (const key in thing) { - keys.push(stringify_key(key)); - str += `,${stringify_string(key)},${flatten(thing[key])}`; - keys.pop(); - } - str += "]"; - } else { - str = "{"; - let started = false; - for (const key in thing) { - if (started) str += ","; - started = true; - keys.push(stringify_key(key)); - str += `${stringify_string(key)}:${flatten(thing[key])}`; - keys.pop(); - } - str += "}"; - } - } - } - stringified[index2] = str; - return index2; - } - const index = flatten(value); - if (index < 0) return `${index}`; - return `[${stringified.join(",")}]`; -} -function stringify_primitive(thing) { - const type = typeof thing; - if (type === "string") return stringify_string(thing); - if (thing instanceof String) return stringify_string(thing.toString()); - if (thing === void 0) return UNDEFINED.toString(); - if (thing === 0 && 1 / thing < 0) return NEGATIVE_ZERO.toString(); - if (type === "bigint") return `["BigInt","${thing}"]`; - return String(thing); -} -function set_nested_value(object, path_string, value) { - if (path_string.startsWith("n:")) { - path_string = path_string.slice(2); - value = value === "" ? void 0 : parseFloat(value); - } else if (path_string.startsWith("b:")) { - path_string = path_string.slice(2); - value = value === "on"; - } - deep_set(object, split_path(path_string), value); -} -function convert_formdata(data) { - const result = {}; - for (let key of data.keys()) { - const is_array = key.endsWith("[]"); - let values = data.getAll(key); - if (is_array) key = key.slice(0, -2); - if (values.length > 1 && !is_array) { - throw new Error(`Form cannot contain duplicated keys — "${key}" has ${values.length} values`); - } - values = values.filter( - (entry) => typeof entry === "string" || entry.name !== "" || entry.size > 0 - ); - if (key.startsWith("n:")) { - key = key.slice(2); - values = values.map((v) => v === "" ? void 0 : parseFloat( - /** @type {string} */ - v - )); - } else if (key.startsWith("b:")) { - key = key.slice(2); - values = values.map((v) => v === "on"); - } - set_nested_value(result, key, is_array ? values : values[0]); - } - return result; -} -const BINARY_FORM_CONTENT_TYPE = "application/x-sveltekit-formdata"; -const BINARY_FORM_VERSION = 0; -const HEADER_BYTES = 1 + 4 + 2; -async function deserialize_binary_form(request) { - if (request.headers.get("content-type") !== BINARY_FORM_CONTENT_TYPE) { - const form_data = await request.formData(); - return { data: convert_formdata(form_data), meta: {}, form_data }; - } - if (!request.body) { - throw deserialize_error("no body"); - } - const content_length = parseInt(request.headers.get("content-length") ?? ""); - if (Number.isNaN(content_length)) { - throw deserialize_error("invalid Content-Length header"); - } - const reader = request.body.getReader(); - const chunks = []; - function get_chunk(index) { - if (index in chunks) return chunks[index]; - let i = chunks.length; - while (i <= index) { - chunks[i] = reader.read().then((chunk) => chunk.value); - i++; - } - return chunks[index]; - } - async function get_buffer(offset, length) { - let start_chunk; - let chunk_start = 0; - let chunk_index; - for (chunk_index = 0; ; chunk_index++) { - const chunk = await get_chunk(chunk_index); - if (!chunk) return null; - const chunk_end = chunk_start + chunk.byteLength; - if (offset >= chunk_start && offset < chunk_end) { - start_chunk = chunk; - break; - } - chunk_start = chunk_end; - } - if (offset + length <= chunk_start + start_chunk.byteLength) { - return start_chunk.subarray(offset - chunk_start, offset + length - chunk_start); - } - const chunks2 = [start_chunk.subarray(offset - chunk_start)]; - let cursor = start_chunk.byteLength - offset + chunk_start; - while (cursor < length) { - chunk_index++; - let chunk = await get_chunk(chunk_index); - if (!chunk) return null; - if (chunk.byteLength > length - cursor) { - chunk = chunk.subarray(0, length - cursor); - } - chunks2.push(chunk); - cursor += chunk.byteLength; - } - const buffer = new Uint8Array(length); - cursor = 0; - for (const chunk of chunks2) { - buffer.set(chunk, cursor); - cursor += chunk.byteLength; - } - return buffer; - } - const header = await get_buffer(0, HEADER_BYTES); - if (!header) throw deserialize_error("too short"); - if (header[0] !== BINARY_FORM_VERSION) { - throw deserialize_error(`got version ${header[0]}, expected version ${BINARY_FORM_VERSION}`); - } - const header_view = new DataView(header.buffer, header.byteOffset, header.byteLength); - const data_length = header_view.getUint32(1, true); - if (HEADER_BYTES + data_length > content_length) { - throw deserialize_error("data overflow"); - } - const file_offsets_length = header_view.getUint16(5, true); - if (HEADER_BYTES + data_length + file_offsets_length > content_length) { - throw deserialize_error("file offset table overflow"); - } - const data_buffer = await get_buffer(HEADER_BYTES, data_length); - if (!data_buffer) throw deserialize_error("data too short"); - let file_offsets; - let files_start_offset; - if (file_offsets_length > 0) { - const file_offsets_buffer = await get_buffer(HEADER_BYTES + data_length, file_offsets_length); - if (!file_offsets_buffer) throw deserialize_error("file offset table too short"); - file_offsets = /** @type {Array} */ - JSON.parse(text_decoder.decode(file_offsets_buffer)); - files_start_offset = HEADER_BYTES + data_length + file_offsets_length; - } - const [data, meta] = parse(text_decoder.decode(data_buffer), { - File: ([name, type, size, last_modified, index]) => { - if (files_start_offset + file_offsets[index] + size > content_length) { - throw deserialize_error("file data overflow"); - } - return new Proxy( - new LazyFile( - name, - type, - size, - last_modified, - get_chunk, - files_start_offset + file_offsets[index] - ), - { - getPrototypeOf() { - return File.prototype; - } - } - ); - } - }); - void (async () => { - let has_more = true; - while (has_more) { - const chunk = await get_chunk(chunks.length); - has_more = !!chunk; - } - })(); - return { data, meta, form_data: null }; -} -function deserialize_error(message) { - return new SvelteKitError(400, "Bad Request", `Could not deserialize binary form: ${message}`); -} -class LazyFile { - /** @type {(index: number) => Promise | undefined>} */ - #get_chunk; - /** @type {number} */ - #offset; - /** - * @param {string} name - * @param {string} type - * @param {number} size - * @param {number} last_modified - * @param {(index: number) => Promise | undefined>} get_chunk - * @param {number} offset - */ - constructor(name, type, size, last_modified, get_chunk, offset) { - this.name = name; - this.type = type; - this.size = size; - this.lastModified = last_modified; - this.webkitRelativePath = ""; - this.#get_chunk = get_chunk; - this.#offset = offset; - this.arrayBuffer = this.arrayBuffer.bind(this); - this.bytes = this.bytes.bind(this); - this.slice = this.slice.bind(this); - this.stream = this.stream.bind(this); - this.text = this.text.bind(this); - } - /** @type {ArrayBuffer | undefined} */ - #buffer; - async arrayBuffer() { - this.#buffer ??= await new Response(this.stream()).arrayBuffer(); - return this.#buffer; - } - async bytes() { - return new Uint8Array(await this.arrayBuffer()); - } - /** - * @param {number=} start - * @param {number=} end - * @param {string=} contentType - */ - slice(start = 0, end = this.size, contentType = this.type) { - if (start < 0) { - start = Math.max(this.size + start, 0); - } else { - start = Math.min(start, this.size); - } - if (end < 0) { - end = Math.max(this.size + end, 0); - } else { - end = Math.min(end, this.size); - } - const size = Math.max(end - start, 0); - const file = new LazyFile( - this.name, - contentType, - size, - this.lastModified, - this.#get_chunk, - this.#offset + start - ); - return file; - } - stream() { - let cursor = 0; - let chunk_index = 0; - return new ReadableStream({ - start: async (controller) => { - let chunk_start = 0; - let start_chunk = null; - for (chunk_index = 0; ; chunk_index++) { - const chunk = await this.#get_chunk(chunk_index); - if (!chunk) return null; - const chunk_end = chunk_start + chunk.byteLength; - if (this.#offset >= chunk_start && this.#offset < chunk_end) { - start_chunk = chunk; - break; - } - chunk_start = chunk_end; - } - if (this.#offset + this.size <= chunk_start + start_chunk.byteLength) { - controller.enqueue( - start_chunk.subarray(this.#offset - chunk_start, this.#offset + this.size - chunk_start) - ); - controller.close(); - } else { - controller.enqueue(start_chunk.subarray(this.#offset - chunk_start)); - cursor = start_chunk.byteLength - this.#offset + chunk_start; - } - }, - pull: async (controller) => { - chunk_index++; - let chunk = await this.#get_chunk(chunk_index); - if (!chunk) { - controller.error("incomplete file data"); - controller.close(); - return; - } - if (chunk.byteLength > this.size - cursor) { - chunk = chunk.subarray(0, this.size - cursor); - } - controller.enqueue(chunk); - cursor += chunk.byteLength; - if (cursor >= this.size) { - controller.close(); - } - } - }); - } - async text() { - return text_decoder.decode(await this.arrayBuffer()); - } -} -const path_regex = /^[a-zA-Z_$]\w*(\.[a-zA-Z_$]\w*|\[\d+\])*$/; -function split_path(path) { - if (!path_regex.test(path)) { - throw new Error(`Invalid path ${path}`); - } - return path.split(/\.|\[|\]/).filter(Boolean); -} -function check_prototype_pollution(key) { - if (key === "__proto__" || key === "constructor" || key === "prototype") { - throw new Error( - `Invalid key "${key}"` - ); - } -} -function deep_set(object, keys, value) { - let current = object; - for (let i = 0; i < keys.length - 1; i += 1) { - const key = keys[i]; - check_prototype_pollution(key); - const is_array = /^\d+$/.test(keys[i + 1]); - const exists = Object.hasOwn(current, key); - const inner = current[key]; - if (exists && is_array !== Array.isArray(inner)) { - throw new Error(`Invalid array key ${keys[i + 1]}`); - } - if (!exists) { - current[key] = is_array ? [] : {}; - } - current = current[key]; - } - const final_key = keys[keys.length - 1]; - check_prototype_pollution(final_key); - current[final_key] = value; -} -function normalize_issue(issue, server = false) { - const normalized = { name: "", path: [], message: issue.message, server }; - if (issue.path !== void 0) { - let name = ""; - for (const segment of issue.path) { - const key = ( - /** @type {string | number} */ - typeof segment === "object" ? segment.key : segment - ); - normalized.path.push(key); - if (typeof key === "number") { - name += `[${key}]`; - } else if (typeof key === "string") { - name += name === "" ? key : "." + key; - } - } - normalized.name = name; - } - return normalized; -} -function flatten_issues(issues) { - const result = {}; - for (const issue of issues) { - (result.$ ??= []).push(issue); - let name = ""; - if (issue.path !== void 0) { - for (const key of issue.path) { - if (typeof key === "number") { - name += `[${key}]`; - } else if (typeof key === "string") { - name += name === "" ? key : "." + key; - } - (result[name] ??= []).push(issue); - } - } - } - return result; -} -function deep_get(object, path) { - let current = object; - for (const key of path) { - if (current == null || typeof current !== "object") { - return current; - } - current = current[key]; - } - return current; -} -function create_field_proxy(target, get_input, set_input, get_issues, path = []) { - const get_value = () => { - return deep_get(get_input(), path); - }; - return new Proxy(target, { - get(target2, prop) { - if (typeof prop === "symbol") return target2[prop]; - if (/^\d+$/.test(prop)) { - return create_field_proxy({}, get_input, set_input, get_issues, [ - ...path, - parseInt(prop, 10) - ]); - } - const key = build_path_string(path); - if (prop === "set") { - const set_func = function(newValue) { - set_input(path, newValue); - return newValue; - }; - return create_field_proxy(set_func, get_input, set_input, get_issues, [...path, prop]); - } - if (prop === "value") { - return create_field_proxy(get_value, get_input, set_input, get_issues, [...path, prop]); - } - if (prop === "issues" || prop === "allIssues") { - const issues_func = () => { - const all_issues = get_issues()[key === "" ? "$" : key]; - if (prop === "allIssues") { - return all_issues?.map((issue) => ({ - path: issue.path, - message: issue.message - })); - } - return all_issues?.filter((issue) => issue.name === key)?.map((issue) => ({ - path: issue.path, - message: issue.message - })); - }; - return create_field_proxy(issues_func, get_input, set_input, get_issues, [...path, prop]); - } - if (prop === "as") { - const as_func = (type, input_value) => { - const is_array = type === "file multiple" || type === "select multiple" || type === "checkbox" && typeof input_value === "string"; - const prefix = type === "number" || type === "range" ? "n:" : type === "checkbox" && !is_array ? "b:" : ""; - const base_props = { - name: prefix + key + (is_array ? "[]" : ""), - get "aria-invalid"() { - const issues = get_issues(); - return key in issues ? "true" : void 0; - } - }; - if (type !== "text" && type !== "select" && type !== "select multiple") { - base_props.type = type === "file multiple" ? "file" : type; - } - if (type === "submit" || type === "hidden") { - return Object.defineProperties(base_props, { - value: { value: input_value, enumerable: true } - }); - } - if (type === "select" || type === "select multiple") { - return Object.defineProperties(base_props, { - multiple: { value: is_array, enumerable: true }, - value: { - enumerable: true, - get() { - return get_value(); - } - } - }); - } - if (type === "checkbox" || type === "radio") { - return Object.defineProperties(base_props, { - value: { value: input_value ?? "on", enumerable: true }, - checked: { - enumerable: true, - get() { - const value = get_value(); - if (type === "radio") { - return value === input_value; - } - if (is_array) { - return (value ?? []).includes(input_value); - } - return value; - } - } - }); - } - if (type === "file" || type === "file multiple") { - return Object.defineProperties(base_props, { - multiple: { value: is_array, enumerable: true }, - files: { - enumerable: true, - get() { - const value = get_value(); - if (value instanceof File) { - if (typeof DataTransfer !== "undefined") { - const fileList = new DataTransfer(); - fileList.items.add(value); - return fileList.files; - } - return { 0: value, length: 1 }; - } - if (Array.isArray(value) && value.every((f) => f instanceof File)) { - if (typeof DataTransfer !== "undefined") { - const fileList = new DataTransfer(); - value.forEach((file) => fileList.items.add(file)); - return fileList.files; - } - const fileListLike = { length: value.length }; - value.forEach((file, index) => { - fileListLike[index] = file; - }); - return fileListLike; - } - return null; - } - } - }); - } - return Object.defineProperties(base_props, { - value: { - enumerable: true, - get() { - const value = get_value(); - return value != null ? String(value) : ""; - } - } - }); - }; - return create_field_proxy(as_func, get_input, set_input, get_issues, [...path, "as"]); - } - return create_field_proxy({}, get_input, set_input, get_issues, [...path, prop]); - } - }); -} -function build_path_string(path) { - let result = ""; - for (const segment of path) { - if (typeof segment === "number") { - result += `[${segment}]`; - } else { - result += result === "" ? segment : "." + segment; - } - } - return result; -} -function negotiate(accept, types) { - const parts = []; - accept.split(",").forEach((str, i) => { - const match = /([^/ \t]+)\/([^; \t]+)[ \t]*(?:;[ \t]*q=([0-9.]+))?/.exec(str); - if (match) { - const [, type, subtype, q = "1"] = match; - parts.push({ type, subtype, q: +q, i }); - } - }); - parts.sort((a, b) => { - if (a.q !== b.q) { - return b.q - a.q; - } - if (a.subtype === "*" !== (b.subtype === "*")) { - return a.subtype === "*" ? 1 : -1; - } - if (a.type === "*" !== (b.type === "*")) { - return a.type === "*" ? 1 : -1; - } - return a.i - b.i; - }); - let accepted; - let min_priority = Infinity; - for (const mimetype of types) { - const [type, subtype] = mimetype.split("/"); - const priority = parts.findIndex( - (part) => (part.type === type || part.type === "*") && (part.subtype === subtype || part.subtype === "*") - ); - if (priority !== -1 && priority < min_priority) { - accepted = mimetype; - min_priority = priority; - } - } - return accepted; -} -function is_content_type(request, ...types) { - const type = request.headers.get("content-type")?.split(";", 1)[0].trim() ?? ""; - return types.includes(type.toLowerCase()); -} -function is_form_content_type(request) { - return is_content_type( - request, - "application/x-www-form-urlencoded", - "multipart/form-data", - "text/plain", - BINARY_FORM_CONTENT_TYPE - ); -} -function coalesce_to_error(err) { - return err instanceof Error || err && /** @type {any} */ - err.name && /** @type {any} */ - err.message ? ( - /** @type {Error} */ - err - ) : new Error(JSON.stringify(err)); -} -function normalize_error(error) { - return ( - /** @type {import('../exports/internal/index.js').Redirect | HttpError | SvelteKitError | Error} */ - error - ); -} -function get_status(error) { - return error instanceof HttpError || error instanceof SvelteKitError ? error.status : 500; -} -function get_message(error) { - return error instanceof SvelteKitError ? error.text : "Internal Error"; -} -const escape_html_attr_dict = { - "&": "&", - '"': """ - // Svelte also escapes < because the escape function could be called inside a `noscript` there - // https://github.com/sveltejs/svelte/security/advisories/GHSA-8266-84wp-wv5c - // However, that doesn't apply in SvelteKit -}; -const escape_html_dict = { - "&": "&", - "<": "<" -}; -const surrogates = ( - // high surrogate without paired low surrogate - "[\\ud800-\\udbff](?![\\udc00-\\udfff])|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\udc00-\\udfff]" -); -const escape_html_attr_regex = new RegExp( - `[${Object.keys(escape_html_attr_dict).join("")}]|` + surrogates, - "g" -); -const escape_html_regex = new RegExp( - `[${Object.keys(escape_html_dict).join("")}]|` + surrogates, - "g" -); -function escape_html(str, is_attr) { - const dict = is_attr ? escape_html_attr_dict : escape_html_dict; - const escaped_str = str.replace(is_attr ? escape_html_attr_regex : escape_html_regex, (match) => { - if (match.length === 2) { - return match; - } - return dict[match] ?? `&#${match.charCodeAt(0)};`; - }); - return escaped_str; -} -function method_not_allowed(mod, method) { - return text(`${method} method not allowed`, { - status: 405, - headers: { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: allowed_methods(mod).join(", ") - } - }); -} -function allowed_methods(mod) { - const allowed = ENDPOINT_METHODS.filter((method) => method in mod); - if ("GET" in mod && !("HEAD" in mod)) { - allowed.push("HEAD"); - } - return allowed; -} -function get_global_name(options) { - return `__sveltekit_${options.version_hash}`; -} -function static_error_page(options, status, message) { - let page = options.templates.error({ status, message: escape_html(message) }); - return text(page, { - headers: { "content-type": "text/html; charset=utf-8" }, - status - }); -} -async function handle_fatal_error(event, state, options, error) { - error = error instanceof HttpError ? error : coalesce_to_error(error); - const status = get_status(error); - const body = await handle_error_and_jsonify(event, state, options, error); - const type = negotiate(event.request.headers.get("accept") || "text/html", [ - "application/json", - "text/html" - ]); - if (event.isDataRequest || type === "application/json") { - return json(body, { - status - }); - } - return static_error_page(options, status, body.message); -} -async function handle_error_and_jsonify(event, state, options, error) { - if (error instanceof HttpError) { - return { message: "Unknown Error", ...error.body }; - } - const status = get_status(error); - const message = get_message(error); - return await with_request_store( - { event, state }, - () => options.hooks.handleError({ error, event, status, message }) - ) ?? { message }; -} -function redirect_response(status, location) { - const response = new Response(void 0, { - status, - headers: { location } - }); - return response; -} -function clarify_devalue_error(event, error) { - if (error.path) { - return `Data returned from \`load\` while rendering ${event.route.id} is not serializable: ${error.message} (${error.path}). If you need to serialize/deserialize custom types, use transport hooks: https://svelte.dev/docs/kit/hooks#Universal-hooks-transport.`; - } - if (error.path === "") { - return `Data returned from \`load\` while rendering ${event.route.id} is not a plain object`; - } - return error.message; -} -function serialize_uses(node) { - const uses = {}; - if (node.uses && node.uses.dependencies.size > 0) { - uses.dependencies = Array.from(node.uses.dependencies); - } - if (node.uses && node.uses.search_params.size > 0) { - uses.search_params = Array.from(node.uses.search_params); - } - if (node.uses && node.uses.params.size > 0) { - uses.params = Array.from(node.uses.params); - } - if (node.uses?.parent) uses.parent = 1; - if (node.uses?.route) uses.route = 1; - if (node.uses?.url) uses.url = 1; - return uses; -} -function has_prerendered_path(manifest, pathname) { - return manifest._.prerendered_routes.has(pathname) || pathname.at(-1) === "/" && manifest._.prerendered_routes.has(pathname.slice(0, -1)); -} -function format_server_error(status, error, event) { - const formatted_text = ` -\x1B[1;31m[${status}] ${event.request.method} ${event.url.pathname}\x1B[0m`; - if (status === 404) { - return formatted_text; - } - return `${formatted_text} -${error.stack}`; -} -function get_node_type(node_id) { - const parts = node_id?.split("/"); - const filename = parts?.at(-1); - if (!filename) return "unknown"; - const dot_parts = filename.split("."); - return dot_parts.slice(0, -1).join("."); -} -const INVALIDATED_PARAM = "x-sveltekit-invalidated"; -const TRAILING_SLASH_PARAM = "x-sveltekit-trailing-slash"; -function stringify(data, transport) { - const encoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.encode])); - return stringify$1(data, encoders); -} -function stringify_remote_arg(value, transport) { - if (value === void 0) return ""; - const json_string = stringify(value, transport); - const bytes = new TextEncoder().encode(json_string); - return base64_encode(bytes).replaceAll("=", "").replaceAll("+", "-").replaceAll("/", "_"); -} -function parse_remote_arg(string, transport) { - if (!string) return void 0; - const json_string = text_decoder.decode( - // no need to add back `=` characters, atob can handle it - base64_decode(string.replaceAll("-", "+").replaceAll("_", "/")) - ); - const decoders = Object.fromEntries(Object.entries(transport).map(([k, v]) => [k, v.decode])); - return parse(json_string, decoders); -} -function create_remote_key(id, payload) { - return id + "/" + payload; -} -export { - set_nested_value as A, - deep_set as B, - ENDPOINT_METHODS as E, - INVALIDATED_PARAM as I, - PAGE_METHODS as P, - SVELTE_KIT_ASSETS as S, - TRAILING_SLASH_PARAM as T, - normalize_error as a, - get_global_name as b, - serialize_uses as c, - clarify_devalue_error as d, - get_node_type as e, - escape_html as f, - get_status as g, - handle_error_and_jsonify as h, - is_form_content_type as i, - create_remote_key as j, - static_error_page as k, - stringify as l, - method_not_allowed as m, - negotiate as n, - deserialize_binary_form as o, - parse_remote_arg as p, - has_prerendered_path as q, - redirect_response as r, - stringify$1 as s, - handle_fatal_error as t, - format_server_error as u, - stringify_remote_arg as v, - parse as w, - flatten_issues as x, - create_field_proxy as y, - normalize_issue as z -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js deleted file mode 100644 index 78e5bde..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils.js +++ /dev/null @@ -1,43 +0,0 @@ -const text_encoder = new TextEncoder(); -const text_decoder = new TextDecoder(); -function get_relative_path(from, to) { - const from_parts = from.split(/[/\\]/); - const to_parts = to.split(/[/\\]/); - from_parts.pop(); - while (from_parts[0] === to_parts[0]) { - from_parts.shift(); - to_parts.shift(); - } - let i = from_parts.length; - while (i--) from_parts[i] = ".."; - return from_parts.concat(to_parts).join("/"); -} -function base64_encode(bytes) { - if (globalThis.Buffer) { - return globalThis.Buffer.from(bytes).toString("base64"); - } - let binary = ""; - for (let i = 0; i < bytes.length; i++) { - binary += String.fromCharCode(bytes[i]); - } - return btoa(binary); -} -function base64_decode(encoded) { - if (globalThis.Buffer) { - const buffer = globalThis.Buffer.from(encoded, "base64"); - return new Uint8Array(buffer); - } - const binary = atob(encoded); - const bytes = new Uint8Array(binary.length); - for (let i = 0; i < binary.length; i++) { - bytes[i] = binary.charCodeAt(i); - } - return bytes; -} -export { - text_encoder as a, - base64_encode as b, - base64_decode as c, - get_relative_path as g, - text_decoder as t -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js deleted file mode 100644 index f3f87a7..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/chunks/utils2.js +++ /dev/null @@ -1,98 +0,0 @@ -const escaped = { - "<": "\\u003C", - "\\": "\\\\", - "\b": "\\b", - "\f": "\\f", - "\n": "\\n", - "\r": "\\r", - " ": "\\t", - "\u2028": "\\u2028", - "\u2029": "\\u2029" -}; -class DevalueError extends Error { - /** - * @param {string} message - * @param {string[]} keys - * @param {any} [value] - The value that failed to be serialized - * @param {any} [root] - The root value being serialized - */ - constructor(message, keys, value, root) { - super(message); - this.name = "DevalueError"; - this.path = keys.join(""); - this.value = value; - this.root = root; - } -} -function is_primitive(thing) { - return Object(thing) !== thing; -} -const object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames( - Object.prototype -).sort().join("\0"); -function is_plain_object(thing) { - const proto = Object.getPrototypeOf(thing); - return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names; -} -function get_type(thing) { - return Object.prototype.toString.call(thing).slice(8, -1); -} -function get_escaped_char(char) { - switch (char) { - case '"': - return '\\"'; - case "<": - return "\\u003C"; - case "\\": - return "\\\\"; - case "\n": - return "\\n"; - case "\r": - return "\\r"; - case " ": - return "\\t"; - case "\b": - return "\\b"; - case "\f": - return "\\f"; - case "\u2028": - return "\\u2028"; - case "\u2029": - return "\\u2029"; - default: - return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : ""; - } -} -function stringify_string(str) { - let result = ""; - let last_pos = 0; - const len = str.length; - for (let i = 0; i < len; i += 1) { - const char = str[i]; - const replacement = get_escaped_char(char); - if (replacement) { - result += str.slice(last_pos, i) + replacement; - last_pos = i + 1; - } - } - return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`; -} -function enumerable_symbols(object) { - return Object.getOwnPropertySymbols(object).filter( - (symbol) => Object.getOwnPropertyDescriptor(object, symbol).enumerable - ); -} -const is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/; -function stringify_key(key) { - return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]"; -} -export { - DevalueError as D, - is_plain_object as a, - stringify_string as b, - escaped as c, - enumerable_symbols as e, - get_type as g, - is_primitive as i, - stringify_key as s -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js deleted file mode 100644 index 4a33088..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/fallbacks/error.svelte.js +++ /dev/null @@ -1,54 +0,0 @@ -import { n as noop, t as getContext, k as escape_html } from "../../chunks/context.js"; -import "@sveltejs/kit/internal/server"; -import "@sveltejs/kit/internal"; -import { w as writable } from "../../chunks/exports.js"; -import "../../chunks/utils.js"; -function create_updated_store() { - const { set, subscribe } = writable(false); - { - return { - subscribe, - // eslint-disable-next-line @typescript-eslint/require-await - check: async () => false - }; - } -} -const is_legacy = noop.toString().includes("$$") || /function \w+\(\) \{\}/.test(noop.toString()); -if (is_legacy) { - ({ - data: {}, - form: null, - error: null, - params: {}, - route: { id: null }, - state: {}, - status: -1, - url: new URL("https://example.com") - }); -} -const stores = { - updated: /* @__PURE__ */ create_updated_store() -}; -({ - check: stores.updated.check -}); -function context() { - return getContext("__request__"); -} -const page$1 = { - get error() { - return context().page.error; - }, - get status() { - return context().page.status; - } -}; -const page = page$1; -function Error$1($$renderer, $$props) { - $$renderer.component(($$renderer2) => { - $$renderer2.push(`

${escape_html(page.status)}

${escape_html(page.error?.message)}

`); - }); -} -export { - Error$1 as default -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js deleted file mode 100644 index 6d138db..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_layout.svelte.js +++ /dev/null @@ -1,9 +0,0 @@ -import { x as slot } from "../../chunks/index.js"; -function _layout($$renderer, $$props) { - $$renderer.push(``); - slot($$renderer, $$props, "default", {}); - $$renderer.push(``); -} -export { - _layout as default -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js deleted file mode 100644 index 90d8585..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/entries/pages/_page.svelte.js +++ /dev/null @@ -1,6 +0,0 @@ -function _page($$renderer) { - $$renderer.push(`

Welcome to SvelteKit

This is a minimal SvelteKit application.

`); -} -export { - _page as default -}; diff --git a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js b/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js deleted file mode 100644 index 149881b..0000000 --- a/tests/fixtures/sveltekit/example/.svelte-kit/output/server/index.js +++ /dev/null @@ -1,3982 +0,0 @@ -import { B as BROWSER, a as assets, b as base, c as app_dir, r as relative, o as override, d as reset } from "./chunks/environment.js"; -import { json, text, error } from "@sveltejs/kit"; -import { Redirect, SvelteKitError, ActionFailure, HttpError } from "@sveltejs/kit/internal"; -import { with_request_store, merge_tracing, try_get_request_store } from "@sveltejs/kit/internal/server"; -import { E as ENDPOINT_METHODS, P as PAGE_METHODS, n as negotiate, m as method_not_allowed, h as handle_error_and_jsonify, g as get_status, i as is_form_content_type, a as normalize_error, s as stringify, b as get_global_name, c as serialize_uses, d as clarify_devalue_error, e as get_node_type, f as escape_html, S as SVELTE_KIT_ASSETS, j as create_remote_key, k as static_error_page, r as redirect_response, p as parse_remote_arg, l as stringify$1, o as deserialize_binary_form, q as has_prerendered_path, T as TRAILING_SLASH_PARAM, I as INVALIDATED_PARAM, t as handle_fatal_error, u as format_server_error } from "./chunks/shared.js"; -import { u as uneval } from "./chunks/index.js"; -import { m as make_trackable, d as disable_search, a as decode_params, S as SCHEME, w as writable, r as readable, v as validate_layout_server_exports, b as validate_layout_exports, c as validate_page_server_exports, e as validate_page_exports, n as normalize_path, f as resolve, g as decode_pathname, h as validate_server_exports } from "./chunks/exports.js"; -import { b as base64_encode, t as text_decoder, a as text_encoder, g as get_relative_path } from "./chunks/utils.js"; -import { p as public_env, r as read_implementation, o as options, s as set_private_env, a as set_public_env, g as get_hooks, b as set_read_implementation } from "./chunks/internal.js"; -function with_resolvers() { - let resolve2; - let reject; - const promise = new Promise((res, rej) => { - resolve2 = res; - reject = rej; - }); - return { promise, resolve: resolve2, reject }; -} -const NULL_BODY_STATUS = [101, 103, 204, 205, 304]; -const IN_WEBCONTAINER = !!globalThis.process?.versions?.webcontainer; -async function render_endpoint(event, event_state, mod, state) { - const method = ( - /** @type {import('types').HttpMethod} */ - event.request.method - ); - let handler = mod[method] || mod.fallback; - if (method === "HEAD" && !mod.HEAD && mod.GET) { - handler = mod.GET; - } - if (!handler) { - return method_not_allowed(mod, method); - } - const prerender = mod.prerender ?? state.prerender_default; - if (prerender && (mod.POST || mod.PATCH || mod.PUT || mod.DELETE)) { - throw new Error("Cannot prerender endpoints that have mutative methods"); - } - if (state.prerendering && !state.prerendering.inside_reroute && !prerender) { - if (state.depth > 0) { - throw new Error(`${event.route.id} is not prerenderable`); - } else { - return new Response(void 0, { status: 204 }); - } - } - event_state.is_endpoint_request = true; - try { - const response = await with_request_store( - { event, state: event_state }, - () => handler( - /** @type {import('@sveltejs/kit').RequestEvent>} */ - event - ) - ); - if (!(response instanceof Response)) { - throw new Error( - `Invalid response from route ${event.url.pathname}: handler should return a Response object` - ); - } - if (state.prerendering && (!state.prerendering.inside_reroute || prerender)) { - const cloned = new Response(response.clone().body, { - status: response.status, - statusText: response.statusText, - headers: new Headers(response.headers) - }); - cloned.headers.set("x-sveltekit-prerender", String(prerender)); - if (state.prerendering.inside_reroute && prerender) { - cloned.headers.set( - "x-sveltekit-routeid", - encodeURI( - /** @type {string} */ - event.route.id - ) - ); - state.prerendering.dependencies.set(event.url.pathname, { response: cloned, body: null }); - } else { - return cloned; - } - } - return response; - } catch (e) { - if (e instanceof Redirect) { - return new Response(void 0, { - status: e.status, - headers: { location: e.location } - }); - } - throw e; - } -} -function is_endpoint_request(event) { - const { method, headers: headers2 } = event.request; - if (ENDPOINT_METHODS.includes(method) && !PAGE_METHODS.includes(method)) { - return true; - } - if (method === "POST" && headers2.get("x-sveltekit-action") === "true") return false; - const accept = event.request.headers.get("accept") ?? "*/*"; - return negotiate(accept, ["*", "text/html"]) !== "text/html"; -} -function compact(arr) { - return arr.filter( - /** @returns {val is NonNullable} */ - (val) => val != null - ); -} -const DATA_SUFFIX = "/__data.json"; -const HTML_DATA_SUFFIX = ".html__data.json"; -function has_data_suffix(pathname) { - return pathname.endsWith(DATA_SUFFIX) || pathname.endsWith(HTML_DATA_SUFFIX); -} -function add_data_suffix(pathname) { - if (pathname.endsWith(".html")) return pathname.replace(/\.html$/, HTML_DATA_SUFFIX); - return pathname.replace(/\/$/, "") + DATA_SUFFIX; -} -function strip_data_suffix(pathname) { - if (pathname.endsWith(HTML_DATA_SUFFIX)) { - return pathname.slice(0, -HTML_DATA_SUFFIX.length) + ".html"; - } - return pathname.slice(0, -DATA_SUFFIX.length); -} -const ROUTE_SUFFIX = "/__route.js"; -function has_resolution_suffix(pathname) { - return pathname.endsWith(ROUTE_SUFFIX); -} -function add_resolution_suffix(pathname) { - return pathname.replace(/\/$/, "") + ROUTE_SUFFIX; -} -function strip_resolution_suffix(pathname) { - return pathname.slice(0, -ROUTE_SUFFIX.length); -} -const noop_span = { - spanContext() { - return noop_span_context; - }, - setAttribute() { - return this; - }, - setAttributes() { - return this; - }, - addEvent() { - return this; - }, - setStatus() { - return this; - }, - updateName() { - return this; - }, - end() { - return this; - }, - isRecording() { - return false; - }, - recordException() { - return this; - }, - addLink() { - return this; - }, - addLinks() { - return this; - } -}; -const noop_span_context = { - traceId: "", - spanId: "", - traceFlags: 0 -}; -async function record_span({ name, attributes, fn }) { - { - return fn(noop_span); - } -} -function is_action_json_request(event) { - const accept = negotiate(event.request.headers.get("accept") ?? "*/*", [ - "application/json", - "text/html" - ]); - return accept === "application/json" && event.request.method === "POST"; -} -async function handle_action_json_request(event, event_state, options2, server) { - const actions = server?.actions; - if (!actions) { - const no_actions_error = new SvelteKitError( - 405, - "Method Not Allowed", - `POST method not allowed. No form actions exist for ${"this page"}` - ); - return action_json( - { - type: "error", - error: await handle_error_and_jsonify(event, event_state, options2, no_actions_error) - }, - { - status: no_actions_error.status, - headers: { - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: "GET" - } - } - ); - } - check_named_default_separate(actions); - try { - const data = await call_action(event, event_state, actions); - if (BROWSER) ; - if (data instanceof ActionFailure) { - return action_json({ - type: "failure", - status: data.status, - // @ts-expect-error we assign a string to what is supposed to be an object. That's ok - // because we don't use the object outside, and this way we have better code navigation - // through knowing where the related interface is used. - data: stringify_action_response( - data.data, - /** @type {string} */ - event.route.id, - options2.hooks.transport - ) - }); - } else { - return action_json({ - type: "success", - status: data ? 200 : 204, - // @ts-expect-error see comment above - data: stringify_action_response( - data, - /** @type {string} */ - event.route.id, - options2.hooks.transport - ) - }); - } - } catch (e) { - const err = normalize_error(e); - if (err instanceof Redirect) { - return action_json_redirect(err); - } - return action_json( - { - type: "error", - error: await handle_error_and_jsonify( - event, - event_state, - options2, - check_incorrect_fail_use(err) - ) - }, - { - status: get_status(err) - } - ); - } -} -function check_incorrect_fail_use(error2) { - return error2 instanceof ActionFailure ? new Error('Cannot "throw fail()". Use "return fail()"') : error2; -} -function action_json_redirect(redirect) { - return action_json({ - type: "redirect", - status: redirect.status, - location: redirect.location - }); -} -function action_json(data, init2) { - return json(data, init2); -} -function is_action_request(event) { - return event.request.method === "POST"; -} -async function handle_action_request(event, event_state, server) { - const actions = server?.actions; - if (!actions) { - event.setHeaders({ - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405 - // "The server must generate an Allow header field in a 405 status code response" - allow: "GET" - }); - return { - type: "error", - error: new SvelteKitError( - 405, - "Method Not Allowed", - `POST method not allowed. No form actions exist for ${"this page"}` - ) - }; - } - check_named_default_separate(actions); - try { - const data = await call_action(event, event_state, actions); - if (BROWSER) ; - if (data instanceof ActionFailure) { - return { - type: "failure", - status: data.status, - data: data.data - }; - } else { - return { - type: "success", - status: 200, - // @ts-expect-error this will be removed upon serialization, so `undefined` is the same as omission - data - }; - } - } catch (e) { - const err = normalize_error(e); - if (err instanceof Redirect) { - return { - type: "redirect", - status: err.status, - location: err.location - }; - } - return { - type: "error", - error: check_incorrect_fail_use(err) - }; - } -} -function check_named_default_separate(actions) { - if (actions.default && Object.keys(actions).length > 1) { - throw new Error( - "When using named actions, the default action cannot be used. See the docs for more info: https://svelte.dev/docs/kit/form-actions#named-actions" - ); - } -} -async function call_action(event, event_state, actions) { - const url = new URL(event.request.url); - let name = "default"; - for (const param of url.searchParams) { - if (param[0].startsWith("/")) { - name = param[0].slice(1); - if (name === "default") { - throw new Error('Cannot use reserved action name "default"'); - } - break; - } - } - const action = actions[name]; - if (!action) { - throw new SvelteKitError(404, "Not Found", `No action with name '${name}' found`); - } - if (!is_form_content_type(event.request)) { - throw new SvelteKitError( - 415, - "Unsupported Media Type", - `Form actions expect form-encoded data — received ${event.request.headers.get( - "content-type" - )}` - ); - } - return record_span({ - name: "sveltekit.form_action", - attributes: { - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - const result = await with_request_store( - { event: traced_event, state: event_state }, - () => action(traced_event) - ); - if (result instanceof ActionFailure) { - current2.setAttributes({ - "sveltekit.form_action.result.type": "failure", - "sveltekit.form_action.result.status": result.status - }); - } - return result; - } - }); -} -function validate_action_return(data) { - if (data instanceof Redirect) { - throw new Error("Cannot `return redirect(...)` — use `redirect(...)` instead"); - } - if (data instanceof HttpError) { - throw new Error("Cannot `return error(...)` — use `error(...)` or `return fail(...)` instead"); - } -} -function uneval_action_response(data, route_id, transport) { - const replacer = (thing) => { - for (const key2 in transport) { - const encoded = transport[key2].encode(thing); - if (encoded) { - return `app.decode('${key2}', ${uneval(encoded, replacer)})`; - } - } - }; - return try_serialize(data, (value) => uneval(value, replacer), route_id); -} -function stringify_action_response(data, route_id, transport) { - const encoders = Object.fromEntries( - Object.entries(transport).map(([key2, value]) => [key2, value.encode]) - ); - return try_serialize(data, (value) => stringify(value, encoders), route_id); -} -function try_serialize(data, fn, route_id) { - try { - return fn(data); - } catch (e) { - const error2 = ( - /** @type {any} */ - e - ); - if (data instanceof Response) { - throw new Error( - `Data returned from action inside ${route_id} is not serializable. Form actions need to return plain objects or fail(). E.g. return { success: true } or return fail(400, { message: "invalid" });` - ); - } - if ("path" in error2) { - let message = `Data returned from action inside ${route_id} is not serializable: ${error2.message}`; - if (error2.path !== "") message += ` (data.${error2.path})`; - throw new Error(message); - } - throw error2; - } -} -function create_async_iterator() { - let resolved = -1; - let returned = -1; - const deferred = []; - return { - iterate: (transform = (x) => x) => { - return { - [Symbol.asyncIterator]() { - return { - next: async () => { - const next = deferred[++returned]; - if (!next) return { value: null, done: true }; - const value = await next.promise; - return { value: transform(value), done: false }; - } - }; - } - }; - }, - add: (promise) => { - deferred.push(with_resolvers()); - void promise.then((value) => { - deferred[++resolved].resolve(value); - }); - } - }; -} -function server_data_serializer(event, event_state, options2) { - let promise_id = 1; - let max_nodes = -1; - const iterator = create_async_iterator(); - const global = get_global_name(options2); - function get_replacer(index) { - return function replacer(thing) { - if (typeof thing?.then === "function") { - const id = promise_id++; - const promise = thing.then( - /** @param {any} data */ - (data) => ({ data }) - ).catch( - /** @param {any} error */ - async (error2) => ({ - error: await handle_error_and_jsonify(event, event_state, options2, error2) - }) - ).then( - /** - * @param {{data: any; error: any}} result - */ - async ({ data, error: error2 }) => { - let str; - try { - str = uneval(error2 ? [, error2] : [data], replacer); - } catch { - error2 = await handle_error_and_jsonify( - event, - event_state, - options2, - new Error(`Failed to serialize promise while rendering ${event.route.id}`) - ); - data = void 0; - str = uneval([, error2], replacer); - } - return { - index, - str: `${global}.resolve(${id}, ${str.includes("app.decode") ? `(app) => ${str}` : `() => ${str}`})` - }; - } - ); - iterator.add(promise); - return `${global}.defer(${id})`; - } else { - for (const key2 in options2.hooks.transport) { - const encoded = options2.hooks.transport[key2].encode(thing); - if (encoded) { - return `app.decode('${key2}', ${uneval(encoded, replacer)})`; - } - } - } - }; - } - const strings = ( - /** @type {string[]} */ - [] - ); - return { - set_max_nodes(i) { - max_nodes = i; - }, - add_node(i, node) { - try { - if (!node) { - strings[i] = "null"; - return; - } - const payload = { type: "data", data: node.data, uses: serialize_uses(node) }; - if (node.slash) payload.slash = node.slash; - strings[i] = uneval(payload, get_replacer(i)); - } catch (e) { - e.path = e.path.slice(1); - throw new Error(clarify_devalue_error( - event, - /** @type {any} */ - e - )); - } - }, - get_data(csp) { - const open = ``; - const close = `<\/script> -`; - return { - data: `[${compact(max_nodes > -1 ? strings.slice(0, max_nodes) : strings).join(",")}]`, - chunks: promise_id > 1 ? iterator.iterate(({ index, str }) => { - if (max_nodes > -1 && index >= max_nodes) { - return ""; - } - return open + str + close; - }) : null - }; - } - }; -} -function server_data_serializer_json(event, event_state, options2) { - let promise_id = 1; - const iterator = create_async_iterator(); - const reducers = { - ...Object.fromEntries( - Object.entries(options2.hooks.transport).map(([key2, value]) => [key2, value.encode]) - ), - /** @param {any} thing */ - Promise: (thing) => { - if (typeof thing?.then !== "function") { - return; - } - const id = promise_id++; - let key2 = "data"; - const promise = thing.catch( - /** @param {any} e */ - async (e) => { - key2 = "error"; - return handle_error_and_jsonify( - event, - event_state, - options2, - /** @type {any} */ - e - ); - } - ).then( - /** @param {any} value */ - async (value) => { - let str; - try { - str = stringify(value, reducers); - } catch { - const error2 = await handle_error_and_jsonify( - event, - event_state, - options2, - new Error(`Failed to serialize promise while rendering ${event.route.id}`) - ); - key2 = "error"; - str = stringify(error2, reducers); - } - return `{"type":"chunk","id":${id},"${key2}":${str}} -`; - } - ); - iterator.add(promise); - return id; - } - }; - const strings = ( - /** @type {string[]} */ - [] - ); - return { - add_node(i, node) { - try { - if (!node) { - strings[i] = "null"; - return; - } - if (node.type === "error" || node.type === "skip") { - strings[i] = JSON.stringify(node); - return; - } - strings[i] = `{"type":"data","data":${stringify(node.data, reducers)},"uses":${JSON.stringify( - serialize_uses(node) - )}${node.slash ? `,"slash":${JSON.stringify(node.slash)}` : ""}}`; - } catch (e) { - e.path = "data" + e.path; - throw new Error(clarify_devalue_error( - event, - /** @type {any} */ - e - )); - } - }, - get_data() { - return { - data: `{"type":"data","nodes":[${strings.join(",")}]} -`, - chunks: promise_id > 1 ? iterator.iterate() : null - }; - } - }; -} -async function load_server_data({ event, event_state, state, node, parent }) { - if (!node?.server) return null; - let is_tracking = true; - const uses = { - dependencies: /* @__PURE__ */ new Set(), - params: /* @__PURE__ */ new Set(), - parent: false, - route: false, - url: false, - search_params: /* @__PURE__ */ new Set() - }; - const load = node.server.load; - const slash = node.server.trailingSlash; - if (!load) { - return { type: "data", data: null, uses, slash }; - } - const url = make_trackable( - event.url, - () => { - if (is_tracking) { - uses.url = true; - } - }, - (param) => { - if (is_tracking) { - uses.search_params.add(param); - } - } - ); - if (state.prerendering) { - disable_search(url); - } - const result = await record_span({ - name: "sveltekit.load", - attributes: { - "sveltekit.load.node_id": node.server_id || "unknown", - "sveltekit.load.node_type": get_node_type(node.server_id), - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - const result2 = await with_request_store( - { event: traced_event, state: event_state }, - () => load.call(null, { - ...traced_event, - fetch: (info, init2) => { - new URL(info instanceof Request ? info.url : info, event.url); - return event.fetch(info, init2); - }, - /** @param {string[]} deps */ - depends: (...deps) => { - for (const dep of deps) { - const { href } = new URL(dep, event.url); - uses.dependencies.add(href); - } - }, - params: new Proxy(event.params, { - get: (target, key2) => { - if (is_tracking) { - uses.params.add(key2); - } - return target[ - /** @type {string} */ - key2 - ]; - } - }), - parent: async () => { - if (is_tracking) { - uses.parent = true; - } - return parent(); - }, - route: new Proxy(event.route, { - get: (target, key2) => { - if (is_tracking) { - uses.route = true; - } - return target[ - /** @type {'id'} */ - key2 - ]; - } - }), - url, - untrack(fn) { - is_tracking = false; - try { - return fn(); - } finally { - is_tracking = true; - } - } - }) - ); - return result2; - } - }); - return { - type: "data", - data: result ?? null, - uses, - slash - }; -} -async function load_data({ - event, - event_state, - fetched, - node, - parent, - server_data_promise, - state, - resolve_opts, - csr -}) { - const server_data_node = await server_data_promise; - const load = node?.universal?.load; - if (!load) { - return server_data_node?.data ?? null; - } - const result = await record_span({ - name: "sveltekit.load", - attributes: { - "sveltekit.load.node_id": node.universal_id || "unknown", - "sveltekit.load.node_type": get_node_type(node.universal_id), - "http.route": event.route.id || "unknown" - }, - fn: async (current2) => { - const traced_event = merge_tracing(event, current2); - return await with_request_store( - { event: traced_event, state: event_state }, - () => load.call(null, { - url: event.url, - params: event.params, - data: server_data_node?.data ?? null, - route: event.route, - fetch: create_universal_fetch(event, state, fetched, csr, resolve_opts), - setHeaders: event.setHeaders, - depends: () => { - }, - parent, - untrack: (fn) => fn(), - tracing: traced_event.tracing - }) - ); - } - }); - return result ?? null; -} -function create_universal_fetch(event, state, fetched, csr, resolve_opts) { - const universal_fetch = async (input, init2) => { - const cloned_body = input instanceof Request && input.body ? input.clone().body : null; - const cloned_headers = input instanceof Request && [...input.headers].length ? new Headers(input.headers) : init2?.headers; - let response = await event.fetch(input, init2); - const url = new URL(input instanceof Request ? input.url : input, event.url); - const same_origin = url.origin === event.url.origin; - let dependency; - if (same_origin) { - if (state.prerendering) { - dependency = { response, body: null }; - state.prerendering.dependencies.set(url.pathname, dependency); - } - } else if (url.protocol === "https:" || url.protocol === "http:") { - const mode = input instanceof Request ? input.mode : init2?.mode ?? "cors"; - if (mode === "no-cors") { - response = new Response("", { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } else { - const acao = response.headers.get("access-control-allow-origin"); - if (!acao || acao !== event.url.origin && acao !== "*") { - throw new Error( - `CORS error: ${acao ? "Incorrect" : "No"} 'Access-Control-Allow-Origin' header is present on the requested resource` - ); - } - } - } - let teed_body; - const proxy = new Proxy(response, { - get(response2, key2, receiver) { - async function push_fetched(body2, is_b64) { - const status_number = Number(response2.status); - if (isNaN(status_number)) { - throw new Error( - `response.status is not a number. value: "${response2.status}" type: ${typeof response2.status}` - ); - } - fetched.push({ - url: same_origin ? url.href.slice(event.url.origin.length) : url.href, - method: event.request.method, - request_body: ( - /** @type {string | ArrayBufferView | undefined} */ - input instanceof Request && cloned_body ? await stream_to_string(cloned_body) : init2?.body - ), - request_headers: cloned_headers, - response_body: body2, - response: response2, - is_b64 - }); - } - if (key2 === "body") { - if (response2.body === null) { - return null; - } - if (teed_body) { - return teed_body; - } - const [a, b] = response2.body.tee(); - void (async () => { - let result = new Uint8Array(); - for await (const chunk of a) { - const combined = new Uint8Array(result.length + chunk.length); - combined.set(result, 0); - combined.set(chunk, result.length); - result = combined; - } - if (dependency) { - dependency.body = new Uint8Array(result); - } - void push_fetched(base64_encode(result), true); - })(); - return teed_body = b; - } - if (key2 === "arrayBuffer") { - return async () => { - const buffer = await response2.arrayBuffer(); - const bytes = new Uint8Array(buffer); - if (dependency) { - dependency.body = bytes; - } - if (buffer instanceof ArrayBuffer) { - await push_fetched(base64_encode(bytes), true); - } - return buffer; - }; - } - async function text2() { - const body2 = await response2.text(); - if (body2 === "" && NULL_BODY_STATUS.includes(response2.status)) { - await push_fetched(void 0, false); - return void 0; - } - if (!body2 || typeof body2 === "string") { - await push_fetched(body2, false); - } - if (dependency) { - dependency.body = body2; - } - return body2; - } - if (key2 === "text") { - return text2; - } - if (key2 === "json") { - return async () => { - const body2 = await text2(); - return body2 ? JSON.parse(body2) : void 0; - }; - } - const value = Reflect.get(response2, key2, response2); - if (value instanceof Function) { - return Object.defineProperties( - /** - * @this {any} - */ - function() { - return Reflect.apply(value, this === receiver ? response2 : this, arguments); - }, - { - name: { value: value.name }, - length: { value: value.length } - } - ); - } - return value; - } - }); - if (csr) { - const get = response.headers.get; - response.headers.get = (key2) => { - const lower = key2.toLowerCase(); - const value = get.call(response.headers, lower); - if (value && !lower.startsWith("x-sveltekit-")) { - const included = resolve_opts.filterSerializedResponseHeaders(lower, value); - if (!included) { - throw new Error( - `Failed to get response header "${lower}" — it must be included by the \`filterSerializedResponseHeaders\` option: https://svelte.dev/docs/kit/hooks#Server-hooks-handle (at ${event.route.id})` - ); - } - } - return value; - }; - } - return proxy; - }; - return (input, init2) => { - const response = universal_fetch(input, init2); - response.catch(() => { - }); - return response; - }; -} -async function stream_to_string(stream) { - let result = ""; - const reader = stream.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - break; - } - result += text_decoder.decode(value); - } - return result; -} -function hash(...values) { - let hash2 = 5381; - for (const value of values) { - if (typeof value === "string") { - let i = value.length; - while (i) hash2 = hash2 * 33 ^ value.charCodeAt(--i); - } else if (ArrayBuffer.isView(value)) { - const buffer = new Uint8Array(value.buffer, value.byteOffset, value.byteLength); - let i = buffer.length; - while (i) hash2 = hash2 * 33 ^ buffer[--i]; - } else { - throw new TypeError("value must be a string or TypedArray"); - } - } - return (hash2 >>> 0).toString(36); -} -const replacements = { - "<": "\\u003C", - "\u2028": "\\u2028", - "\u2029": "\\u2029" -}; -const pattern = new RegExp(`[${Object.keys(replacements).join("")}]`, "g"); -function serialize_data(fetched, filter, prerendering = false) { - const headers2 = {}; - let cache_control = null; - let age = null; - let varyAny = false; - for (const [key2, value] of fetched.response.headers) { - if (filter(key2, value)) { - headers2[key2] = value; - } - if (key2 === "cache-control") cache_control = value; - else if (key2 === "age") age = value; - else if (key2 === "vary" && value.trim() === "*") varyAny = true; - } - const payload = { - status: fetched.response.status, - statusText: fetched.response.statusText, - headers: headers2, - body: fetched.response_body - }; - const safe_payload = JSON.stringify(payload).replace(pattern, (match) => replacements[match]); - const attrs = [ - 'type="application/json"', - "data-sveltekit-fetched", - `data-url="${escape_html(fetched.url, true)}"` - ]; - if (fetched.is_b64) { - attrs.push("data-b64"); - } - if (fetched.request_headers || fetched.request_body) { - const values = []; - if (fetched.request_headers) { - values.push([...new Headers(fetched.request_headers)].join(",")); - } - if (fetched.request_body) { - values.push(fetched.request_body); - } - attrs.push(`data-hash="${hash(...values)}"`); - } - if (!prerendering && fetched.method === "GET" && cache_control && !varyAny) { - const match = /s-maxage=(\d+)/g.exec(cache_control) ?? /max-age=(\d+)/g.exec(cache_control); - if (match) { - const ttl = +match[1] - +(age ?? "0"); - attrs.push(`data-ttl="${ttl}"`); - } - } - return `