@gigadrive/network-config 5.5.3 → 5.5.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/dist/nextjs-adapter.d.mts +0 -10
- package/dist/nextjs-adapter.d.ts +0 -10
- package/dist/nextjs-adapter.js +51 -4
- package/dist/nextjs-adapter.js.map +1 -1
- package/dist/nextjs-adapter.mjs +51 -4
- package/dist/nextjs-adapter.mjs.map +1 -1
- package/dist/nextjs-image-loader.js +14 -2
- package/dist/nextjs-image-loader.js.map +1 -1
- package/dist/nextjs-image-loader.mjs +14 -2
- package/dist/nextjs-image-loader.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nextjs-adapter.ts","../src/manifest-schema.ts","../src/nextjs-constants.ts"],"sourcesContent":["import { Schema } from 'effect';\nimport type { NextAdapter } from 'next';\nimport { access, mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { StaticAssetHeaders, StaticAssetManifestEntry, StaticAssetManifestV1 } from './asset-manifest';\nimport type { NormalizedImagePolicy } from './image-policy';\nimport { decodeJson, decodeUnknown, HttpHeadersSchema } from './manifest-schema';\nimport { MAXIMUM_ENTRY_PAGE_PATHS } from './nextjs-constants';\nimport type {\n GigadriveNextBuildManifestV1,\n GigadriveNextBuildManifestV2Export,\n GigadriveNextBuildManifestV2Standalone,\n GigadriveNextPrerenderManifestV1,\n GigadriveNextPrerenderOutput,\n GigadriveNextServerDescriptor,\n GigadriveNextStaticAssetPrefix,\n JsonValue,\n} from './nextjs-manifest';\n\ntype BuildCompleteContext = Parameters<NonNullable<NextAdapter['onBuildComplete']>>[0];\ntype NextRouteOutput =\n | BuildCompleteContext['outputs']['pages'][number]\n | BuildCompleteContext['outputs']['pagesApi'][number]\n | BuildCompleteContext['outputs']['appPages'][number]\n | BuildCompleteContext['outputs']['appRoutes'][number]\n | NonNullable<BuildCompleteContext['outputs']['middleware']>;\ntype NextPrerenderOutput = BuildCompleteContext['outputs']['prerenders'][number];\ntype NextStaticFileOutput = BuildCompleteContext['outputs']['staticFiles'][number];\n\nconst PRODUCTION_BUILD_PHASE = 'phase-production-build';\nconst NEXT_ASSET_MANIFEST_PATH = '.gigadrive/assets/nextjs.json';\nconst NEXT_PRERENDER_MANIFEST_PATH = '.gigadrive/nextjs-prerenders.json';\nconst HTML_CONTENT_TYPE = 'text/html; charset=utf-8';\nconst DEFAULT_RSC_CONTENT_TYPE = 'text/x-component';\nconst INTERNAL_STATIC_RESPONSE_HEADERS = new Set(['x-next-cache-tags', 'x-nextjs-prerender']);\nconst NextStaticFileMetaSchema = Schema.Struct({\n status: Schema.optional(Schema.Int.pipe(Schema.between(100, 599))),\n headers: Schema.mutable(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n});\nconst runtimeDirectory = typeof __dirname === 'string' ? __dirname : path.dirname(fileURLToPath(import.meta.url));\n\nconst runtimeModulePath = (environmentName: string, fileName: string): string =>\n process.env[environmentName] ?? path.join(runtimeDirectory, fileName);\n\nconst CACHE_HANDLER_PATH = () => runtimeModulePath('GIGADRIVE_NEXT_CACHE_HANDLER_PATH', 'nextjs-cache-handler.js');\nconst CACHE_COMPONENTS_HANDLER_PATH = () =>\n runtimeModulePath('GIGADRIVE_NEXT_CACHE_COMPONENTS_HANDLER_PATH', 'nextjs-cache-components-handler.js');\nconst IMAGE_LOADER_PATH = () => runtimeModulePath('GIGADRIVE_NEXT_IMAGE_LOADER_PATH', 'nextjs-image-loader.js');\n\nconst toJsonValue = (value: unknown): JsonValue => {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : (JSON.parse(serialized) as JsonValue);\n};\n\n/**\n * Next 16.2 introduced the adapter hooks (`modifyConfig` + `onBuildComplete`) and\n * the `cacheHandler`/`cacheHandlers`/`cacheComponents` config fields we inject.\n * Earlier releases keep the legacy standalone-only behavior with no injection.\n */\nconst supportsManagedRuntime = (nextVersion: string | undefined): boolean => {\n if (!nextVersion) return false;\n const [majorPart, minorPart] = nextVersion.split('.');\n const major = Number.parseInt(majorPart ?? '', 10);\n const minor = Number.parseInt(minorPart ?? '', 10);\n return Number.isFinite(major) && Number.isFinite(minor) && (major > 16 || (major === 16 && minor >= 2));\n};\n\n/**\n * Highest Next major validated to allow `output: 'standalone'` together with an\n * adapter. Next's own build source warns the combination \"might not be allowed\"\n * in a future release. We always emit `output: 'standalone'` on the managed path\n * (there is no per-route fallback to degrade to), so if a future major forbids\n * it the build fails loudly at `next build` rather than silently misdeploying.\n * The network canary drift test tracks releases past this bound.\n */\nconst MANAGED_STANDALONE_VALIDATED_MAX_MAJOR = 16;\n\nconst toPortableRelativePath = (from: string, to: string, allowCurrentDirectory = false): string => {\n const resolvedFrom = path.resolve(from);\n const resolvedTo = path.resolve(path.isAbsolute(to) ? to : path.join(from, to));\n const relativePath = path.relative(resolvedFrom, resolvedTo).replaceAll(path.sep, '/');\n const normalized = relativePath === '' ? '.' : relativePath;\n if (\n (!allowCurrentDirectory && normalized === '.') ||\n normalized.startsWith('/') ||\n /^[A-Za-z]:/.test(normalized) ||\n normalized.split('/').some((segment) => segment === '..')\n ) {\n throw new Error(`Next.js adapter output is outside the repository root: ${to}`);\n }\n return normalized;\n};\n\nasync function resolveReadablePath(repoRoot: string, filePath: string, resolvedRoot?: string) {\n const absolutePath = path.resolve(path.isAbsolute(filePath) ? filePath : path.join(repoRoot, filePath));\n const portablePath = toPortableRelativePath(repoRoot, absolutePath);\n await access(absolutePath);\n // Validate the symlink-resolved location as well; the call throws when the\n // real path escapes the repository root.\n const resolvedPath = await realpath(absolutePath);\n void toPortableRelativePath(resolvedRoot ?? (await realpath(repoRoot)), resolvedPath);\n const fileStat = await stat(absolutePath);\n return { portablePath, fileStat };\n}\n\nasync function requireReadableFile(repoRoot: string, filePath: string, resolvedRoot?: string): Promise<string> {\n const { portablePath, fileStat } = await resolveReadablePath(repoRoot, filePath, resolvedRoot);\n if (!fileStat.isFile()) throw new Error(`Next.js adapter output is not a readable file: ${filePath}`);\n return portablePath;\n}\n\nasync function mapInBatches<Input, Output>(\n values: Input[],\n mapper: (value: Input) => Promise<Output>,\n batchSize = 64\n): Promise<Output[]> {\n const results: Output[] = [];\n for (let index = 0; index < values.length; index += batchSize) {\n results.push(...(await Promise.all(values.slice(index, index + batchSize).map((value) => mapper(value)))));\n }\n return results;\n}\n\nconst isInsideDirectory = (directory: string, filePath: string): boolean => {\n const relativePath = path.relative(path.resolve(directory), path.resolve(filePath));\n return relativePath !== '' && !relativePath.startsWith('..') && !path.isAbsolute(relativePath);\n};\n\nconst isDynamicRoutePathname = (pathname: string): boolean => pathname.includes('[');\n\n// Next reports the Pages Router root as `<basePath>/index`, while its public URL\n// is the base path itself (or `/` when no base path is configured).\nconst normalizeStaticFilePathname = (pathname: string, basePath: string): string =>\n pathname === `${basePath}/index` ? basePath || '/' : pathname;\n\nconst getStaticStatus = (pathname: string, basePath: string, locales: readonly string[]): number | undefined => {\n const routePathname = basePath && pathname.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) : pathname;\n const segments = routePathname.split('/').filter(Boolean);\n const [firstSegment, secondSegment] = segments;\n const statusPage =\n segments.length === 1\n ? firstSegment\n : segments.length === 2 && firstSegment && locales.includes(firstSegment)\n ? secondSegment\n : undefined;\n return statusPage === '404' ? 404 : statusPage === '500' ? 500 : undefined;\n};\n\nconst hasContentType = (headers: StaticAssetHeaders): boolean =>\n Object.keys(headers).some((name) => name.toLowerCase() === 'content-type');\n\nconst getPublicStaticResponseHeaders = (headers: Record<string, unknown>): StaticAssetHeaders | undefined => {\n const publicHeaders = Object.fromEntries(\n Object.entries(headers).filter(([name]) => !INTERNAL_STATIC_RESPONSE_HEADERS.has(name.toLowerCase()))\n );\n return decodeUnknown(HttpHeadersSchema, publicHeaders);\n};\n\nasync function getStaticFileResponseMetadata(\n projectDir: string,\n resolvedProjectDir: string,\n output: NextStaticFileOutput,\n rscContentType: string,\n basePath: string,\n locales: readonly string[]\n): Promise<Pick<StaticAssetManifestEntry, 'status' | 'headers'> | undefined> {\n if (output.filePath.endsWith('.body')) {\n const metaPath = `${output.filePath.slice(0, -'.body'.length)}.meta`;\n await requireReadableFile(projectDir, metaPath, resolvedProjectDir);\n const meta = decodeJson(NextStaticFileMetaSchema, await readFile(metaPath, 'utf8'));\n const headers = meta ? getPublicStaticResponseHeaders(meta.headers) : undefined;\n if (!meta || !headers || !hasContentType(headers)) return undefined;\n return {\n ...(meta.status !== undefined ? { status: meta.status } : {}),\n headers,\n };\n }\n if (output.filePath.endsWith('.html')) {\n const status = getStaticStatus(output.pathname, basePath, locales);\n return {\n ...(status !== undefined ? { status } : {}),\n headers: { 'content-type': HTML_CONTENT_TYPE },\n };\n }\n if (output.pathname.endsWith('.rsc')) return { headers: { 'content-type': rscContentType } };\n return {};\n}\n\nconst serializeStaticFileAsset = async (\n projectDir: string,\n resolvedProjectDir: string,\n basePath: string,\n rscContentType: string,\n locales: readonly string[],\n output: NextStaticFileOutput\n): Promise<StaticAssetManifestEntry | undefined> => {\n const [source, responseMetadata] = await Promise.all([\n requireReadableFile(projectDir, output.filePath, resolvedProjectDir),\n getStaticFileResponseMetadata(projectDir, resolvedProjectDir, output, rscContentType, basePath, locales),\n ]);\n if (!responseMetadata) return undefined;\n return {\n source,\n path: normalizeStaticFilePathname(output.pathname, basePath),\n ...responseMetadata,\n ...(output.immutableHash ? { immutable: true } : {}),\n };\n};\n\nasync function serializeAssetManifest(\n projectDir: string,\n resolvedProjectDir: string,\n distDir: string,\n basePath: string,\n rscContentType: string,\n locales: readonly string[],\n staticFiles: NextStaticFileOutput[]\n): Promise<StaticAssetManifestV1> {\n const staticDirectory = path.join(distDir, 'static');\n const staticEntries = await mapInBatches(\n staticFiles.filter(\n // The complete immutable subtree is already represented by a prefix.\n (output) => !isInsideDirectory(staticDirectory, output.filePath) && !isDynamicRoutePathname(output.pathname)\n ),\n (output) => serializeStaticFileAsset(projectDir, resolvedProjectDir, basePath, rscContentType, locales, output)\n );\n const assetsByPath = new Map<string, StaticAssetManifestEntry>();\n for (const entry of staticEntries) {\n if (!entry) continue;\n if (assetsByPath.has(entry.path)) throw new Error(`Duplicate Next.js static asset path: ${entry.path}`);\n assetsByPath.set(entry.path, entry);\n }\n return { version: 1, assets: [...assetsByPath.values()] };\n}\n\nconst getEntryPagePaths = (prerenders: GigadriveNextPrerenderOutput[]): string[] =>\n [\n ...new Set(\n prerenders\n .filter((output) => output.fallback?.postponedState === undefined)\n .map((output) => output.pathname)\n .filter((pathname) => pathname.startsWith('/') && !isDynamicRoutePathname(pathname))\n ),\n ]\n .sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right))\n .slice(0, MAXIMUM_ENTRY_PAGE_PATHS);\n\nconst NextPrerenderMetaSchema = Schema.Struct({\n routeCache: Schema.optional(Schema.Struct({ key: Schema.String })),\n});\n\n/**\n * Reads the runtime cache key Next recorded beside a prerender's HTML. Newer\n * Next versions scope keys by source route, so the pathname alone would miss the\n * entry. Using Next's own value avoids depending on how a version builds it.\n */\nconst readPrerenderCacheKey = async (repoRoot: string, htmlPath: string): Promise<string | undefined> => {\n if (!htmlPath.endsWith('.html')) return undefined;\n const metaPath = path.resolve(repoRoot, htmlPath.replace(/\\.html$/, '.meta'));\n const content = await readFile(metaPath, 'utf8').catch(() => undefined);\n return content === undefined ? undefined : decodeJson(NextPrerenderMetaSchema, content)?.routeCache?.key;\n};\n\nconst serializePrerenderOutput = async (\n repoRoot: string,\n resolvedRepoRoot: string,\n output: NextPrerenderOutput\n): Promise<GigadriveNextPrerenderOutput> => {\n const { bypassFor, ...prerenderConfig } = output.config;\n const cacheKey = output.fallback?.filePath\n ? await readPrerenderCacheKey(repoRoot, output.fallback.filePath)\n : undefined;\n const serializedOutput = {\n id: output.id,\n type: 'PRERENDER' as const,\n pathname: output.pathname,\n ...(output.route !== undefined ? { route: output.route } : {}),\n parentOutputId: output.parentOutputId,\n groupId: output.groupId,\n ...(cacheKey !== undefined ? { cacheKey } : {}),\n ...(output.pprChain ? { pprChain: output.pprChain } : {}),\n ...(output.parentFallbackMode !== undefined ? { parentFallbackMode: toJsonValue(output.parentFallbackMode) } : {}),\n ...(output.fallback\n ? {\n fallback: {\n ...(output.fallback.filePath\n ? { filePath: await requireReadableFile(repoRoot, output.fallback.filePath, resolvedRepoRoot) }\n : {}),\n ...(output.fallback.initialStatus !== undefined ? { initialStatus: output.fallback.initialStatus } : {}),\n ...(output.fallback.initialHeaders ? { initialHeaders: output.fallback.initialHeaders } : {}),\n ...(output.fallback.initialExpiration !== undefined\n ? { initialExpiration: output.fallback.initialExpiration }\n : {}),\n ...(output.fallback.initialRevalidate !== undefined\n ? { initialRevalidate: output.fallback.initialRevalidate }\n : {}),\n ...(output.fallback.postponedState !== undefined ? { postponedState: output.fallback.postponedState } : {}),\n },\n }\n : {}),\n config: {\n ...prerenderConfig,\n ...(bypassFor ? { bypassFor: toJsonValue(bypassFor) as JsonValue[] } : {}),\n },\n };\n if (output.routeType !== undefined) {\n return {\n ...serializedOutput,\n routeType: output.routeType,\n response: output.response,\n compute: output.compute,\n ...(output.htmlSize !== undefined ? { htmlSize: output.htmlSize } : {}),\n };\n }\n return serializedOutput;\n};\n\n/**\n * Collapses per-route runtime config onto the one standalone server. `maxDuration`\n * becomes the max across routes (one function honors one limit); `env` is the union\n * of every route's declared env (the single server runs them all in-process).\n */\nconst aggregateServerDescriptor = (outputs: NextRouteOutput[]): GigadriveNextServerDescriptor => {\n let maxDuration: number | undefined;\n const env: Record<string, string> = {};\n for (const output of outputs) {\n if (output.config.maxDuration !== undefined) {\n maxDuration = Math.max(maxDuration ?? 0, output.config.maxDuration);\n }\n if (output.config.env) Object.assign(env, output.config.env);\n }\n return {\n ...(maxDuration !== undefined ? { maxDuration } : {}),\n ...(Object.keys(env).length > 0 ? { env } : {}),\n };\n};\n\ntype CollectBuildTracesModule = {\n collectBuildTraces: (options: {\n dir: string;\n config: BuildCompleteContext['config'];\n distDir: string;\n edgeRuntimeRoutes: Record<string, never>;\n staticPages: string[];\n outputFileTracingRoot: string;\n }) => Promise<void>;\n};\n\n/**\n * Ignore globs that Turbopack's native server tracer applies on top of the\n * shared `collectBuildTraces` ignore list (see `ignores()` in Next's\n * `crates/next-api/src/next_server_nft.rs`). The JavaScript\n * `collectBuildTraces` fallback only carries the webpack-era ignores, so\n * tracing Next's server entries with it follows dev-only require edges —\n * `router-server` → `setup-dev-bundler` → hot reloaders → the application's\n * build toolchain (webpack, terser, esbuild, swc, babel plugins) — that\n * Turbopack severs natively, roughly quadrupling the standalone output.\n *\n * Passing these through `outputFileTracingExcludes['next-server']` reuses\n * `collectBuildTraces`' own extension point for the shared ignores, so they\n * apply during trace traversal exactly like Turbopack's graph-level ignores.\n * Only Next-internal dev/build-only modules are listed — never application\n * packages — so application dependencies are excluded solely when their every\n * require path runs through one of these modules, matching the native trace.\n * If a future Next release moves one of these files the glob simply stops\n * matching and the trace grows back; nothing breaks at runtime.\n */\nconst TURBOPACK_SERVER_TRACE_IGNORES = [\n // client components with a NODE_ENV guard the tracer cannot evaluate\n '**/next/dist/next-devtools/userspace/use-app-dev-rendering-indicator.js',\n '**/next/dist/client/dev/hot-reloader/app/hot-reloader-app.js',\n // server/lib/router-server.js requires this statically but only uses it in dev\n '**/next/dist/server/lib/router-utils/setup-dev-bundler.js',\n // server/next.js requires this statically but only uses it in dev\n '**/next/dist/server/dev/next-dev-server.js',\n // build-time-only browser support data pulled in via next/dist/compiled/babel*\n '**/next/dist/compiled/browserslist/**',\n '**/next/dist/compiled/jest-worker/**/*',\n '**/node_modules/react{,-dom,-server-dom-turbopack}/**/*.development.js',\n];\n\n/**\n * Next 16.3 stopped emitting the aggregated `next-server.js.nft.json` /\n * `next-minimal-server.js.nft.json` traces from Turbopack builds whenever an\n * adapter is configured, yet `next build` still runs the `output: 'standalone'`\n * writer after `onBuildComplete` — and that writer reads exactly this file, so\n * the build dies with ENOENT. Next 16.2 and all webpack builds still emit the\n * file, making this a no-op there. When the file is missing, regenerate both\n * aggregate traces with Next's own `collectBuildTraces` (the module the webpack\n * pipeline runs); without `buildTraceContext` it only writes the two aggregate\n * trace files and leaves Turbopack's per-entry traces untouched. The\n * regeneration also merges `TURBOPACK_SERVER_TRACE_IGNORES` into the config's\n * `outputFileTracingExcludes` so the fallback prunes the same dev-only require\n * edges as Turbopack's native tracer instead of dragging the application's\n * build toolchain into the standalone output.\n */\nasync function ensureStandaloneServerTraces(\n projectDir: string,\n repoRoot: string,\n distDir: string,\n config: BuildCompleteContext['config']\n): Promise<void> {\n const aggregateTracePath = path.join(distDir, 'next-server.js.nft.json');\n try {\n await access(aggregateTracePath);\n return;\n } catch {\n // Missing — Next will crash in its standalone writer unless we regenerate it.\n }\n let collectBuildTracesModule: CollectBuildTracesModule;\n try {\n const projectRequire = createRequire(path.join(projectDir, 'package.json'));\n collectBuildTracesModule = projectRequire('next/dist/build/collect-build-traces') as CollectBuildTracesModule;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Next.js did not emit ${aggregateTracePath} and the Gigadrive adapter could not load ` +\n `next/dist/build/collect-build-traces from the project to regenerate it: ${message}`\n );\n }\n const { outputFileTracingExcludes = {} } = config as {\n outputFileTracingExcludes?: Record<string, string[]>;\n };\n const tracingConfig = {\n ...config,\n outputFileTracingExcludes: {\n ...outputFileTracingExcludes,\n 'next-server': [...(outputFileTracingExcludes['next-server'] ?? []), ...TURBOPACK_SERVER_TRACE_IGNORES],\n },\n };\n try {\n await collectBuildTracesModule.collectBuildTraces({\n dir: projectDir,\n config: tracingConfig,\n distDir,\n edgeRuntimeRoutes: {},\n staticPages: [],\n outputFileTracingRoot: (config as { outputFileTracingRoot?: string }).outputFileTracingRoot ?? repoRoot,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Regenerating the Next.js standalone server traces (${aggregateTracePath}) failed: ${message}`);\n }\n}\n\nconst normalizeImages = (config: BuildCompleteContext['config']): NormalizedImagePolicy | undefined => {\n if (config.images.unoptimized) return undefined;\n return {\n localPatterns: config.images.localPatterns ?? [{ pathname: '/**' }],\n remotePatterns: config.images.remotePatterns.map((pattern) => {\n if (pattern instanceof URL) {\n return {\n protocol: pattern.protocol === 'http:' ? ('http' as const) : ('https' as const),\n hostname: pattern.hostname,\n port: pattern.port,\n pathname: pattern.pathname,\n search: pattern.search,\n };\n }\n return { ...pattern };\n }),\n widths: [...new Set([...config.images.deviceSizes, ...config.images.imageSizes])].sort((a, b) => a - b),\n heights: [],\n qualities: config.images.qualities ?? [75],\n formats: config.images.formats,\n minimumCacheTTL: config.images.minimumCacheTTL,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n contentSecurityPolicy: config.images.contentSecurityPolicy,\n contentDispositionType: config.images.contentDispositionType,\n maximumRedirects: config.images.maximumRedirects,\n maximumResponseBody: config.images.maximumResponseBody,\n variants: {},\n };\n};\n\n/**\n * Next.js deployment adapter used automatically by Gigadrive Network build workers.\n *\n * Next 16.2 and newer run the entire deployment as a single `output: 'standalone'`\n * server (one function per deployment) while the injected cache handlers, image\n * loader, and this hook's `onBuildComplete` metadata keep ISR, PPR, `use cache`,\n * and image optimization working through the platform's durable runtime-cache and\n * edge image services. Older releases retain the legacy standalone behavior without\n * the managed-runtime injections.\n */\nconst gigadriveNextAdapter: NextAdapter = {\n name: 'Gigadrive Network',\n\n modifyConfig(config, { phase, nextVersion }) {\n if (phase !== PRODUCTION_BUILD_PHASE) return config;\n\n const deploymentId = config.deploymentId ?? process.env.GIGADRIVE_DEPLOYMENT_ID;\n if (!supportsManagedRuntime(nextVersion)) {\n return {\n ...config,\n ...(deploymentId ? { deploymentId } : {}),\n output: config.output === 'export' ? 'export' : 'standalone',\n };\n }\n if (config.output === 'export') {\n return { ...config, ...(deploymentId ? { deploymentId } : {}) };\n }\n\n const injectCacheHandler = config.cacheHandler === undefined;\n const injectCacheComponentHandlers = config.cacheHandlers === undefined;\n const images = config.images;\n const injectImageLoader =\n images !== undefined && images.unoptimized !== true && images.loader === 'default' && !images.loaderFile;\n\n return {\n ...config,\n ...(deploymentId ? { deploymentId } : {}),\n // Run the whole deployment as one standalone Next server rather than a\n // serverless function per route. `onBuildComplete` still fires under\n // standalone (Next >= 16.2), and the standalone server natively honors the\n // injected cache handlers and resumes PPR from its incremental cache, so\n // ISR/PPR/`use cache` stay durable via the remote runtime-cache service.\n // Validated on Next 16.2.x (see MANAGED_STANDALONE_VALIDATED_MAX_MAJOR);\n // a future major that forbids adapter + standalone fails loudly at build.\n output: 'standalone',\n ...(injectCacheHandler ? { cacheHandler: CACHE_HANDLER_PATH() } : {}),\n ...(injectCacheComponentHandlers\n ? {\n cacheHandlers: {\n default: CACHE_COMPONENTS_HANDLER_PATH(),\n remote: CACHE_COMPONENTS_HANDLER_PATH(),\n },\n }\n : {}),\n ...(injectCacheHandler || injectCacheComponentHandlers ? { cacheMaxMemorySize: 0 } : {}),\n ...(injectImageLoader\n ? {\n images: {\n ...images,\n loader: 'custom',\n loaderFile: IMAGE_LOADER_PATH(),\n },\n }\n : {}),\n };\n },\n\n async onBuildComplete({ projectDir, repoRoot, distDir, config, nextVersion, buildId, routing, outputs }) {\n const metadataDirectory = path.join(projectDir, '.gigadrive');\n await mkdir(metadataDirectory, { recursive: true });\n const manifestPath = path.join(metadataDirectory, 'nextjs.json');\n const writeManifest = (manifest: unknown) =>\n writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n\n if (!supportsManagedRuntime(nextVersion)) {\n const manifest: GigadriveNextBuildManifestV1 = {\n version: 1,\n output: config.output === 'export' ? 'export' : 'standalone',\n distDir: toPortableRelativePath(projectDir, distDir),\n repoRootToProject: toPortableRelativePath(repoRoot, projectDir, true),\n nextVersion,\n buildId,\n };\n await writeManifest(manifest);\n return;\n }\n\n const portableDistDir = toPortableRelativePath(projectDir, distDir);\n const repoRootToProject = toPortableRelativePath(repoRoot, projectDir, true);\n\n if (config.output === 'export') {\n const manifest: GigadriveNextBuildManifestV2Export = {\n version: 2,\n mode: 'export',\n distDir: portableDistDir,\n repoRootToProject,\n nextVersion,\n buildId,\n };\n await writeManifest(manifest);\n return;\n }\n\n if (config.output === 'standalone') {\n await ensureStandaloneServerTraces(projectDir, repoRoot, distDir, config);\n }\n\n const [resolvedRepoRoot, resolvedProjectDir] = await Promise.all([realpath(repoRoot), realpath(projectDir)]);\n const prerenders = await mapInBatches(outputs.prerenders, (output) =>\n serializePrerenderOutput(repoRoot, resolvedRepoRoot, output)\n );\n const assetManifest = await serializeAssetManifest(\n projectDir,\n resolvedProjectDir,\n distDir,\n config.basePath,\n routing.rsc.contentTypeHeader ?? DEFAULT_RSC_CONTENT_TYPE,\n config.i18n?.locales ?? [],\n outputs.staticFiles\n );\n const prerenderManifest: GigadriveNextPrerenderManifestV1 = {\n version: 1,\n seedMethods: ['GET', 'HEAD'],\n prerenders,\n };\n await mkdir(path.join(metadataDirectory, 'assets'), { recursive: true });\n await Promise.all([\n writeFile(path.join(projectDir, NEXT_ASSET_MANIFEST_PATH), `${JSON.stringify(assetManifest)}\\n`, 'utf8'),\n writeFile(path.join(projectDir, NEXT_PRERENDER_MANIFEST_PATH), `${JSON.stringify(prerenderManifest)}\\n`, 'utf8'),\n ]);\n const server = aggregateServerDescriptor([\n ...outputs.pages,\n ...outputs.pagesApi,\n ...outputs.appPages,\n ...outputs.appRoutes,\n ...(outputs.middleware ? [outputs.middleware] : []),\n ]);\n const images = normalizeImages(config);\n // `.next/static` is thousands of content-hashed, immutable chunks. Register\n // the whole subtree as one edge-served prefix instead of enumerating files.\n const staticAssets: GigadriveNextStaticAssetPrefix[] = [\n { sourceDir: `${portableDistDir}/static`, urlPrefix: '_next/static', immutable: true },\n ];\n\n const manifest: GigadriveNextBuildManifestV2Standalone = {\n version: 2,\n mode: 'standalone-v2',\n distDir: portableDistDir,\n repoRootToProject,\n nextVersion,\n buildId,\n server,\n config: {\n basePath: config.basePath,\n trailingSlash: config.trailingSlash,\n cacheComponents: config.cacheComponents,\n ...(config.i18n ? { i18n: toJsonValue(config.i18n) } : {}),\n ...(images ? { images } : {}),\n },\n routing: {\n beforeMiddleware: toJsonValue(routing.beforeMiddleware) as JsonValue[],\n beforeFiles: toJsonValue(routing.beforeFiles) as JsonValue[],\n afterFiles: toJsonValue(routing.afterFiles) as JsonValue[],\n dynamicRoutes: toJsonValue(routing.dynamicRoutes) as JsonValue[],\n onMatch: toJsonValue(routing.onMatch) as JsonValue[],\n fallback: toJsonValue(routing.fallback) as JsonValue[],\n shouldNormalizeNextData: routing.shouldNormalizeNextData,\n rsc: toJsonValue(routing.rsc),\n },\n outputs: {\n prerenders: [],\n prerenderManifest: NEXT_PRERENDER_MANIFEST_PATH,\n assetManifest: NEXT_ASSET_MANIFEST_PATH,\n entryPagePaths: getEntryPagePaths(prerenders),\n staticAssets,\n middleware: outputs.middleware\n ? {\n present: true,\n matchers: (outputs.middleware.config.matchers ?? []).map(({ source, sourceRegex, has, missing }) => ({\n source,\n sourceRegex,\n has,\n missing,\n })),\n }\n : { present: false, matchers: [] },\n },\n };\n await writeManifest(manifest);\n },\n};\n\nexport { MANAGED_STANDALONE_VALIDATED_MAX_MAJOR };\nexport default gigadriveNextAdapter;\n","import { Option, Schema } from 'effect';\n\nconst HTTP_HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst HTTP_HEADER_VALUE = /^[\\t\\x20-\\x7e\\x80-\\xff]*$/;\nconst URL_PATHNAME_FORBIDDEN_CHARACTER = /[\\x00-\\x1f\\x7f?#\\\\]/;\n\nconst isUrlDotSegment = (segment: string): boolean => {\n const decodedDots = segment.replace(/%2e/gi, '.');\n return decodedDots === '.' || decodedDots === '..';\n};\n\nconst isPortableRelativePath = (value: string, allowCurrentDirectory = false): boolean => {\n const normalized = value.replaceAll('\\\\', '/').replace(/^\\.\\//, '').replace(/\\/+$/, '');\n return (\n (allowCurrentDirectory || (normalized !== '' && normalized !== '.')) &&\n !normalized.startsWith('/') &&\n !/^[A-Za-z]:/.test(normalized) &&\n !normalized.includes(':') &&\n !normalized.split('/').includes('..')\n );\n};\n\nexport const PortableRelativePathSchema = Schema.String.pipe(Schema.filter((value) => isPortableRelativePath(value)));\n\nexport const RepositoryRelativePathSchema = Schema.String.pipe(\n Schema.filter((value) => isPortableRelativePath(value, true))\n);\n\nexport const UrlPathnameSchema = Schema.String.pipe(\n Schema.filter(\n (value) =>\n value.startsWith('/') && !URL_PATHNAME_FORBIDDEN_CHARACTER.test(value) && !value.split('/').some(isUrlDotSegment)\n )\n);\n\nexport const HttpHeaderValueSchema = Schema.String.pipe(Schema.pattern(HTTP_HEADER_VALUE));\nexport const HttpHeadersSchema = Schema.mutable(\n Schema.Record({\n key: Schema.String,\n value: Schema.Union(HttpHeaderValueSchema, Schema.mutable(Schema.Array(HttpHeaderValueSchema))),\n })\n).pipe(Schema.filter((headers) => Object.keys(headers).every((name) => HTTP_HEADER_NAME.test(name))));\nexport const HttpSingleValueHeadersSchema = Schema.mutable(\n Schema.Record({ key: Schema.String, value: HttpHeaderValueSchema })\n).pipe(Schema.filter((headers) => Object.keys(headers).every((name) => HTTP_HEADER_NAME.test(name))));\n\n/**\n * Decode an unknown value with an Effect schema.\n *\n * @param schema - Schema used to validate and decode the value.\n * @param value - Unknown input to decode.\n * @returns The decoded value, or `undefined` when validation fails.\n * @example\n * decodeUnknown(Schema.String, 'value');\n */\nexport const decodeUnknown = <A, I>(schema: Schema.Schema<A, I, never>, value: unknown): A | undefined =>\n Schema.decodeUnknownOption(schema, { onExcessProperty: 'preserve' })(value).pipe(Option.getOrUndefined);\n\n/**\n * Decode a JSON string with an Effect schema.\n *\n * @param schema - Schema used to validate and decode the parsed JSON value.\n * @param content - JSON string to parse and decode.\n * @returns The decoded value, or `undefined` when parsing or validation fails.\n * @example\n * decodeJson(Schema.Struct({ version: Schema.Number }), '{\"version\":1}');\n */\nexport const decodeJson = <A, I>(schema: Schema.Schema<A, I, never>, content: string): A | undefined =>\n decodeUnknown(Schema.parseJson(schema), content);\n","/**\n * A representative sample is enough for cache warming. The complete prerender\n * table stays in its sidecar so it cannot expand gateway configuration by\n * thousands of paths.\n */\nexport const MAXIMUM_ENTRY_PAGE_PATHS = 50;\n"],"mappings":";AAAA,SAAS,UAAAA,eAAc;AAEvB,SAAS,QAAQ,OAAO,UAAU,UAAU,MAAM,iBAAiB;AACnE,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AACjB,SAAS,qBAAqB;;;ACL9B,SAAS,QAAQ,cAAc;AAE/B,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,mCAAmC;AAEzC,IAAM,kBAAkB,CAAC,YAA6B;AACpD,QAAM,cAAc,QAAQ,QAAQ,SAAS,GAAG;AAChD,SAAO,gBAAgB,OAAO,gBAAgB;AAChD;AAEA,IAAM,yBAAyB,CAAC,OAAe,wBAAwB,UAAmB;AACxF,QAAM,aAAa,MAAM,WAAW,MAAM,GAAG,EAAE,QAAQ,SAAS,EAAE,EAAE,QAAQ,QAAQ,EAAE;AACtF,UACG,yBAA0B,eAAe,MAAM,eAAe,QAC/D,CAAC,WAAW,WAAW,GAAG,KAC1B,CAAC,aAAa,KAAK,UAAU,KAC7B,CAAC,WAAW,SAAS,GAAG,KACxB,CAAC,WAAW,MAAM,GAAG,EAAE,SAAS,IAAI;AAExC;AAEO,IAAM,6BAA6B,OAAO,OAAO,KAAK,OAAO,OAAO,CAAC,UAAU,uBAAuB,KAAK,CAAC,CAAC;AAE7G,IAAM,+BAA+B,OAAO,OAAO;AAAA,EACxD,OAAO,OAAO,CAAC,UAAU,uBAAuB,OAAO,IAAI,CAAC;AAC9D;AAEO,IAAM,oBAAoB,OAAO,OAAO;AAAA,EAC7C,OAAO;AAAA,IACL,CAAC,UACC,MAAM,WAAW,GAAG,KAAK,CAAC,iCAAiC,KAAK,KAA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AAA,MACA;AAAA,MACA;AAAA,MACA,QAAQ;AAAA,QACN,UAAU,OAAO;AAAA,QACjB,eAAe,OAAO;AAAA,QACtB,iBAAiB,OAAO;AAAA,QACxB,GAAI,OAAO,OAAO,EAAE,MAAM,YAAY,OAAO,IAAI,EAAE,IAAI,CAAC;AAAA,QACxD,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;AAAA,MAC7B;AAAA,MACA,SAAS;AAAA,QACP,kBAAkB,YAAY,QAAQ,gBAAgB;AAAA,QACtD,aAAa,YAAY,QAAQ,WAAW;AAAA,QAC5C,YAAY,YAAY,QAAQ,UAAU;AAAA,QAC1C,eAAe,YAAY,QAAQ,aAAa;AAAA,QAChD,SAAS,YAAY,QAAQ,OAAO;AAAA,QACpC,UAAU,YAAY,QAAQ,QAAQ;AAAA,QACtC,yBAAyB,QAAQ;AAAA,QACjC,KAAK,YAAY,QAAQ,GAAG;AAAA,MAC9B;AAAA,MACA,SAAS;AAAA,QACP,YAAY,CAAC;AAAA,QACb,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,gBAAgB,kBAAkB,UAAU;AAAA,QAC5C;AAAA,QACA,YAAY,QAAQ,aAChB;AAAA,UACE,SAAS;AAAA,UACT,WAAW,QAAQ,WAAW,OAAO,YAAY,CAAC,GAAG,IAAI,CAAC,EAAE,QAAQ,aAAa,KAAK,QAAQ,OAAO;AAAA,YACnG;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF,EAAE;AAAA,QACJ,IACA,EAAE,SAAS,OAAO,UAAU,CAAC,EAAE;AAAA,MACrC;AAAA,IACF;AACA,UAAM,cAAc,QAAQ;AAAA,EAC9B;AACF;AAGA,IAAO,yBAAQ;","names":["Schema","Schema","manifest"]}
|
|
1
|
+
{"version":3,"sources":["../src/nextjs-adapter.ts","../src/manifest-schema.ts","../src/nextjs-constants.ts"],"sourcesContent":["import { Schema } from 'effect';\nimport type { NextAdapter } from 'next';\nimport { access, mkdir, readFile, realpath, stat, writeFile } from 'node:fs/promises';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { StaticAssetHeaders, StaticAssetManifestEntry, StaticAssetManifestV1 } from './asset-manifest';\nimport type { NormalizedImagePolicy } from './image-policy';\nimport { decodeJson, decodeUnknown, HttpHeadersSchema } from './manifest-schema';\nimport { MAXIMUM_ENTRY_PAGE_PATHS } from './nextjs-constants';\nimport type {\n GigadriveNextBuildManifestV1,\n GigadriveNextBuildManifestV2Export,\n GigadriveNextBuildManifestV2Standalone,\n GigadriveNextPrerenderManifestV1,\n GigadriveNextPrerenderOutput,\n GigadriveNextServerDescriptor,\n GigadriveNextStaticAssetPrefix,\n JsonValue,\n} from './nextjs-manifest';\n\ntype BuildCompleteContext = Parameters<NonNullable<NextAdapter['onBuildComplete']>>[0];\ntype NextConfigComplete = Parameters<NonNullable<NextAdapter['modifyConfig']>>[0];\ntype ModifyConfigContext = Parameters<NonNullable<NextAdapter['modifyConfig']>>[1];\n/**\n * What Next 15 passes to `onBuildComplete`. Next 15 loads the adapter through\n * `experimental.adapterPath` (which `NEXT_ADAPTER_PATH` sets) but with an older\n * contract: `modifyConfig(config)` gets no context, and `onBuildComplete` gets\n * neither the project, the dist directory, the config nor the Next version.\n */\ntype Next15BuildCompleteContext = { readonly routes: unknown; readonly outputs: unknown };\ntype NextRouteOutput =\n | BuildCompleteContext['outputs']['pages'][number]\n | BuildCompleteContext['outputs']['pagesApi'][number]\n | BuildCompleteContext['outputs']['appPages'][number]\n | BuildCompleteContext['outputs']['appRoutes'][number]\n | NonNullable<BuildCompleteContext['outputs']['middleware']>;\ntype NextPrerenderOutput = BuildCompleteContext['outputs']['prerenders'][number];\ntype NextStaticFileOutput = BuildCompleteContext['outputs']['staticFiles'][number];\n\nconst PRODUCTION_BUILD_PHASE = 'phase-production-build';\nconst NEXT_ASSET_MANIFEST_PATH = '.gigadrive/assets/nextjs.json';\nconst NEXT_PRERENDER_MANIFEST_PATH = '.gigadrive/nextjs-prerenders.json';\nconst HTML_CONTENT_TYPE = 'text/html; charset=utf-8';\nconst DEFAULT_RSC_CONTENT_TYPE = 'text/x-component';\nconst INTERNAL_STATIC_RESPONSE_HEADERS = new Set(['x-next-cache-tags', 'x-nextjs-prerender']);\nconst NextStaticFileMetaSchema = Schema.Struct({\n status: Schema.optional(Schema.Int.pipe(Schema.between(100, 599))),\n headers: Schema.mutable(Schema.Record({ key: Schema.String, value: Schema.Unknown })),\n});\nconst runtimeDirectory = typeof __dirname === 'string' ? __dirname : path.dirname(fileURLToPath(import.meta.url));\n\nconst runtimeModulePath = (environmentName: string, fileName: string): string =>\n process.env[environmentName] ?? path.join(runtimeDirectory, fileName);\n\nconst CACHE_HANDLER_PATH = () => runtimeModulePath('GIGADRIVE_NEXT_CACHE_HANDLER_PATH', 'nextjs-cache-handler.js');\nconst CACHE_COMPONENTS_HANDLER_PATH = () =>\n runtimeModulePath('GIGADRIVE_NEXT_CACHE_COMPONENTS_HANDLER_PATH', 'nextjs-cache-components-handler.js');\nconst IMAGE_LOADER_PATH = () => runtimeModulePath('GIGADRIVE_NEXT_IMAGE_LOADER_PATH', 'nextjs-image-loader.js');\n\nconst toJsonValue = (value: unknown): JsonValue => {\n const serialized = JSON.stringify(value);\n return serialized === undefined ? null : (JSON.parse(serialized) as JsonValue);\n};\n\n/**\n * Next 16.2 introduced the adapter hooks (`modifyConfig` + `onBuildComplete`) and\n * the `cacheHandler`/`cacheHandlers`/`cacheComponents` config fields we inject.\n * Earlier releases keep the legacy standalone-only behavior with no injection.\n */\nconst supportsManagedRuntime = (nextVersion: string | undefined): boolean => {\n if (!nextVersion) return false;\n const [majorPart, minorPart] = nextVersion.split('.');\n const major = Number.parseInt(majorPart ?? '', 10);\n const minor = Number.parseInt(minorPart ?? '', 10);\n return Number.isFinite(major) && Number.isFinite(minor) && (major > 16 || (major === 16 && minor >= 2));\n};\n\n/**\n * Highest Next major validated to allow `output: 'standalone'` together with an\n * adapter. Next's own build source warns the combination \"might not be allowed\"\n * in a future release. We always emit `output: 'standalone'` on the managed path\n * (there is no per-route fallback to degrade to), so if a future major forbids\n * it the build fails loudly at `next build` rather than silently misdeploying.\n * The network canary drift test tracks releases past this bound.\n */\nconst MANAGED_STANDALONE_VALIDATED_MAX_MAJOR = 16;\n\nconst toPortableRelativePath = (from: string, to: string, allowCurrentDirectory = false): string => {\n const resolvedFrom = path.resolve(from);\n const resolvedTo = path.resolve(path.isAbsolute(to) ? to : path.join(from, to));\n const relativePath = path.relative(resolvedFrom, resolvedTo).replaceAll(path.sep, '/');\n const normalized = relativePath === '' ? '.' : relativePath;\n if (\n (!allowCurrentDirectory && normalized === '.') ||\n normalized.startsWith('/') ||\n /^[A-Za-z]:/.test(normalized) ||\n normalized.split('/').some((segment) => segment === '..')\n ) {\n throw new Error(`Next.js adapter output is outside the repository root: ${to}`);\n }\n return normalized;\n};\n\nasync function resolveReadablePath(repoRoot: string, filePath: string, resolvedRoot?: string) {\n const absolutePath = path.resolve(path.isAbsolute(filePath) ? filePath : path.join(repoRoot, filePath));\n const portablePath = toPortableRelativePath(repoRoot, absolutePath);\n await access(absolutePath);\n // Validate the symlink-resolved location as well; the call throws when the\n // real path escapes the repository root.\n const resolvedPath = await realpath(absolutePath);\n void toPortableRelativePath(resolvedRoot ?? (await realpath(repoRoot)), resolvedPath);\n const fileStat = await stat(absolutePath);\n return { portablePath, fileStat };\n}\n\nasync function requireReadableFile(repoRoot: string, filePath: string, resolvedRoot?: string): Promise<string> {\n const { portablePath, fileStat } = await resolveReadablePath(repoRoot, filePath, resolvedRoot);\n if (!fileStat.isFile()) throw new Error(`Next.js adapter output is not a readable file: ${filePath}`);\n return portablePath;\n}\n\nasync function mapInBatches<Input, Output>(\n values: Input[],\n mapper: (value: Input) => Promise<Output>,\n batchSize = 64\n): Promise<Output[]> {\n const results: Output[] = [];\n for (let index = 0; index < values.length; index += batchSize) {\n results.push(...(await Promise.all(values.slice(index, index + batchSize).map((value) => mapper(value)))));\n }\n return results;\n}\n\nconst isInsideDirectory = (directory: string, filePath: string): boolean => {\n const relativePath = path.relative(path.resolve(directory), path.resolve(filePath));\n return relativePath !== '' && !relativePath.startsWith('..') && !path.isAbsolute(relativePath);\n};\n\nconst isDynamicRoutePathname = (pathname: string): boolean => pathname.includes('[');\n\n// Next reports the Pages Router root as `<basePath>/index`, while its public URL\n// is the base path itself (or `/` when no base path is configured).\nconst normalizeStaticFilePathname = (pathname: string, basePath: string): string =>\n pathname === `${basePath}/index` ? basePath || '/' : pathname;\n\nconst getStaticStatus = (pathname: string, basePath: string, locales: readonly string[]): number | undefined => {\n const routePathname = basePath && pathname.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) : pathname;\n const segments = routePathname.split('/').filter(Boolean);\n const [firstSegment, secondSegment] = segments;\n const statusPage =\n segments.length === 1\n ? firstSegment\n : segments.length === 2 && firstSegment && locales.includes(firstSegment)\n ? secondSegment\n : undefined;\n return statusPage === '404' ? 404 : statusPage === '500' ? 500 : undefined;\n};\n\nconst hasContentType = (headers: StaticAssetHeaders): boolean =>\n Object.keys(headers).some((name) => name.toLowerCase() === 'content-type');\n\nconst getPublicStaticResponseHeaders = (headers: Record<string, unknown>): StaticAssetHeaders | undefined => {\n const publicHeaders = Object.fromEntries(\n Object.entries(headers).filter(([name]) => !INTERNAL_STATIC_RESPONSE_HEADERS.has(name.toLowerCase()))\n );\n return decodeUnknown(HttpHeadersSchema, publicHeaders);\n};\n\nasync function getStaticFileResponseMetadata(\n projectDir: string,\n resolvedProjectDir: string,\n output: NextStaticFileOutput,\n rscContentType: string,\n basePath: string,\n locales: readonly string[]\n): Promise<Pick<StaticAssetManifestEntry, 'status' | 'headers'> | undefined> {\n if (output.filePath.endsWith('.body')) {\n const metaPath = `${output.filePath.slice(0, -'.body'.length)}.meta`;\n await requireReadableFile(projectDir, metaPath, resolvedProjectDir);\n const meta = decodeJson(NextStaticFileMetaSchema, await readFile(metaPath, 'utf8'));\n const headers = meta ? getPublicStaticResponseHeaders(meta.headers) : undefined;\n if (!meta || !headers || !hasContentType(headers)) return undefined;\n return {\n ...(meta.status !== undefined ? { status: meta.status } : {}),\n headers,\n };\n }\n if (output.filePath.endsWith('.html')) {\n const status = getStaticStatus(output.pathname, basePath, locales);\n return {\n ...(status !== undefined ? { status } : {}),\n headers: { 'content-type': HTML_CONTENT_TYPE },\n };\n }\n if (output.pathname.endsWith('.rsc')) return { headers: { 'content-type': rscContentType } };\n return {};\n}\n\nconst serializeStaticFileAsset = async (\n projectDir: string,\n resolvedProjectDir: string,\n basePath: string,\n rscContentType: string,\n locales: readonly string[],\n output: NextStaticFileOutput\n): Promise<StaticAssetManifestEntry | undefined> => {\n const [source, responseMetadata] = await Promise.all([\n requireReadableFile(projectDir, output.filePath, resolvedProjectDir),\n getStaticFileResponseMetadata(projectDir, resolvedProjectDir, output, rscContentType, basePath, locales),\n ]);\n if (!responseMetadata) return undefined;\n return {\n source,\n path: normalizeStaticFilePathname(output.pathname, basePath),\n ...responseMetadata,\n ...(output.immutableHash ? { immutable: true } : {}),\n };\n};\n\nasync function serializeAssetManifest(\n projectDir: string,\n resolvedProjectDir: string,\n distDir: string,\n basePath: string,\n rscContentType: string,\n locales: readonly string[],\n staticFiles: NextStaticFileOutput[]\n): Promise<StaticAssetManifestV1> {\n const staticDirectory = path.join(distDir, 'static');\n const staticEntries = await mapInBatches(\n staticFiles.filter(\n // The complete immutable subtree is already represented by a prefix.\n (output) => !isInsideDirectory(staticDirectory, output.filePath) && !isDynamicRoutePathname(output.pathname)\n ),\n (output) => serializeStaticFileAsset(projectDir, resolvedProjectDir, basePath, rscContentType, locales, output)\n );\n const assetsByPath = new Map<string, StaticAssetManifestEntry>();\n for (const entry of staticEntries) {\n if (!entry) continue;\n if (assetsByPath.has(entry.path)) throw new Error(`Duplicate Next.js static asset path: ${entry.path}`);\n assetsByPath.set(entry.path, entry);\n }\n return { version: 1, assets: [...assetsByPath.values()] };\n}\n\nconst getEntryPagePaths = (prerenders: GigadriveNextPrerenderOutput[]): string[] =>\n [\n ...new Set(\n prerenders\n .filter((output) => output.fallback?.postponedState === undefined)\n .map((output) => output.pathname)\n .filter((pathname) => pathname.startsWith('/') && !isDynamicRoutePathname(pathname))\n ),\n ]\n .sort((left, right) => left.split('/').length - right.split('/').length || left.localeCompare(right))\n .slice(0, MAXIMUM_ENTRY_PAGE_PATHS);\n\nconst NextPrerenderMetaSchema = Schema.Struct({\n routeCache: Schema.optional(Schema.Struct({ key: Schema.String })),\n});\n\n/**\n * Reads the runtime cache key Next recorded beside a prerender's HTML. Newer\n * Next versions scope keys by source route, so the pathname alone would miss the\n * entry. Using Next's own value avoids depending on how a version builds it.\n */\nconst readPrerenderCacheKey = async (repoRoot: string, htmlPath: string): Promise<string | undefined> => {\n if (!htmlPath.endsWith('.html')) return undefined;\n const metaPath = path.resolve(repoRoot, htmlPath.replace(/\\.html$/, '.meta'));\n const content = await readFile(metaPath, 'utf8').catch(() => undefined);\n return content === undefined ? undefined : decodeJson(NextPrerenderMetaSchema, content)?.routeCache?.key;\n};\n\nconst serializePrerenderOutput = async (\n repoRoot: string,\n resolvedRepoRoot: string,\n output: NextPrerenderOutput\n): Promise<GigadriveNextPrerenderOutput> => {\n const { bypassFor, ...prerenderConfig } = output.config;\n const cacheKey = output.fallback?.filePath\n ? await readPrerenderCacheKey(repoRoot, output.fallback.filePath)\n : undefined;\n const serializedOutput = {\n id: output.id,\n type: 'PRERENDER' as const,\n pathname: output.pathname,\n ...(output.route !== undefined ? { route: output.route } : {}),\n parentOutputId: output.parentOutputId,\n groupId: output.groupId,\n ...(cacheKey !== undefined ? { cacheKey } : {}),\n ...(output.pprChain ? { pprChain: output.pprChain } : {}),\n ...(output.parentFallbackMode !== undefined ? { parentFallbackMode: toJsonValue(output.parentFallbackMode) } : {}),\n ...(output.fallback\n ? {\n fallback: {\n ...(output.fallback.filePath\n ? { filePath: await requireReadableFile(repoRoot, output.fallback.filePath, resolvedRepoRoot) }\n : {}),\n ...(output.fallback.initialStatus !== undefined ? { initialStatus: output.fallback.initialStatus } : {}),\n ...(output.fallback.initialHeaders ? { initialHeaders: output.fallback.initialHeaders } : {}),\n ...(output.fallback.initialExpiration !== undefined\n ? { initialExpiration: output.fallback.initialExpiration }\n : {}),\n ...(output.fallback.initialRevalidate !== undefined\n ? { initialRevalidate: output.fallback.initialRevalidate }\n : {}),\n ...(output.fallback.postponedState !== undefined ? { postponedState: output.fallback.postponedState } : {}),\n },\n }\n : {}),\n config: {\n ...prerenderConfig,\n ...(bypassFor ? { bypassFor: toJsonValue(bypassFor) as JsonValue[] } : {}),\n },\n };\n if (output.routeType !== undefined) {\n return {\n ...serializedOutput,\n routeType: output.routeType,\n response: output.response,\n compute: output.compute,\n ...(output.htmlSize !== undefined ? { htmlSize: output.htmlSize } : {}),\n };\n }\n return serializedOutput;\n};\n\n/**\n * Collapses per-route runtime config onto the one standalone server. `maxDuration`\n * becomes the max across routes (one function honors one limit); `env` is the union\n * of every route's declared env (the single server runs them all in-process).\n */\nconst aggregateServerDescriptor = (outputs: NextRouteOutput[]): GigadriveNextServerDescriptor => {\n let maxDuration: number | undefined;\n const env: Record<string, string> = {};\n for (const output of outputs) {\n if (output.config.maxDuration !== undefined) {\n maxDuration = Math.max(maxDuration ?? 0, output.config.maxDuration);\n }\n if (output.config.env) Object.assign(env, output.config.env);\n }\n return {\n ...(maxDuration !== undefined ? { maxDuration } : {}),\n ...(Object.keys(env).length > 0 ? { env } : {}),\n };\n};\n\ntype CollectBuildTracesModule = {\n collectBuildTraces: (options: {\n dir: string;\n config: BuildCompleteContext['config'];\n distDir: string;\n edgeRuntimeRoutes: Record<string, never>;\n staticPages: string[];\n outputFileTracingRoot: string;\n }) => Promise<void>;\n};\n\n/**\n * Ignore globs that Turbopack's native server tracer applies on top of the\n * shared `collectBuildTraces` ignore list (see `ignores()` in Next's\n * `crates/next-api/src/next_server_nft.rs`). The JavaScript\n * `collectBuildTraces` fallback only carries the webpack-era ignores, so\n * tracing Next's server entries with it follows dev-only require edges —\n * `router-server` → `setup-dev-bundler` → hot reloaders → the application's\n * build toolchain (webpack, terser, esbuild, swc, babel plugins) — that\n * Turbopack severs natively, roughly quadrupling the standalone output.\n *\n * Passing these through `outputFileTracingExcludes['next-server']` reuses\n * `collectBuildTraces`' own extension point for the shared ignores, so they\n * apply during trace traversal exactly like Turbopack's graph-level ignores.\n * Only Next-internal dev/build-only modules are listed — never application\n * packages — so application dependencies are excluded solely when their every\n * require path runs through one of these modules, matching the native trace.\n * If a future Next release moves one of these files the glob simply stops\n * matching and the trace grows back; nothing breaks at runtime.\n */\nconst TURBOPACK_SERVER_TRACE_IGNORES = [\n // client components with a NODE_ENV guard the tracer cannot evaluate\n '**/next/dist/next-devtools/userspace/use-app-dev-rendering-indicator.js',\n '**/next/dist/client/dev/hot-reloader/app/hot-reloader-app.js',\n // server/lib/router-server.js requires this statically but only uses it in dev\n '**/next/dist/server/lib/router-utils/setup-dev-bundler.js',\n // server/next.js requires this statically but only uses it in dev\n '**/next/dist/server/dev/next-dev-server.js',\n // build-time-only browser support data pulled in via next/dist/compiled/babel*\n '**/next/dist/compiled/browserslist/**',\n '**/next/dist/compiled/jest-worker/**/*',\n '**/node_modules/react{,-dom,-server-dom-turbopack}/**/*.development.js',\n];\n\n/**\n * Next 16.3 stopped emitting the aggregated `next-server.js.nft.json` /\n * `next-minimal-server.js.nft.json` traces from Turbopack builds whenever an\n * adapter is configured, yet `next build` still runs the `output: 'standalone'`\n * writer after `onBuildComplete` — and that writer reads exactly this file, so\n * the build dies with ENOENT. Next 16.2 and all webpack builds still emit the\n * file, making this a no-op there. When the file is missing, regenerate both\n * aggregate traces with Next's own `collectBuildTraces` (the module the webpack\n * pipeline runs); without `buildTraceContext` it only writes the two aggregate\n * trace files and leaves Turbopack's per-entry traces untouched. The\n * regeneration also merges `TURBOPACK_SERVER_TRACE_IGNORES` into the config's\n * `outputFileTracingExcludes` so the fallback prunes the same dev-only require\n * edges as Turbopack's native tracer instead of dragging the application's\n * build toolchain into the standalone output.\n */\nasync function ensureStandaloneServerTraces(\n projectDir: string,\n repoRoot: string,\n distDir: string,\n config: BuildCompleteContext['config']\n): Promise<void> {\n const aggregateTracePath = path.join(distDir, 'next-server.js.nft.json');\n try {\n await access(aggregateTracePath);\n return;\n } catch {\n // Missing — Next will crash in its standalone writer unless we regenerate it.\n }\n let collectBuildTracesModule: CollectBuildTracesModule;\n try {\n const projectRequire = createRequire(path.join(projectDir, 'package.json'));\n collectBuildTracesModule = projectRequire('next/dist/build/collect-build-traces') as CollectBuildTracesModule;\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Next.js did not emit ${aggregateTracePath} and the Gigadrive adapter could not load ` +\n `next/dist/build/collect-build-traces from the project to regenerate it: ${message}`\n );\n }\n const { outputFileTracingExcludes = {} } = config as {\n outputFileTracingExcludes?: Record<string, string[]>;\n };\n const tracingConfig = {\n ...config,\n outputFileTracingExcludes: {\n ...outputFileTracingExcludes,\n 'next-server': [...(outputFileTracingExcludes['next-server'] ?? []), ...TURBOPACK_SERVER_TRACE_IGNORES],\n },\n };\n try {\n await collectBuildTracesModule.collectBuildTraces({\n dir: projectDir,\n config: tracingConfig,\n distDir,\n edgeRuntimeRoutes: {},\n staticPages: [],\n outputFileTracingRoot: (config as { outputFileTracingRoot?: string }).outputFileTracingRoot ?? repoRoot,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`Regenerating the Next.js standalone server traces (${aggregateTracePath}) failed: ${message}`);\n }\n}\n\nconst normalizeImages = (config: BuildCompleteContext['config']): NormalizedImagePolicy | undefined => {\n if (config.images.unoptimized) return undefined;\n return {\n localPatterns: config.images.localPatterns ?? [{ pathname: '/**' }],\n remotePatterns: config.images.remotePatterns.map((pattern) => {\n if (pattern instanceof URL) {\n return {\n protocol: pattern.protocol === 'http:' ? ('http' as const) : ('https' as const),\n hostname: pattern.hostname,\n port: pattern.port,\n pathname: pattern.pathname,\n search: pattern.search,\n };\n }\n return { ...pattern };\n }),\n widths: [...new Set([...config.images.deviceSizes, ...config.images.imageSizes])].sort((a, b) => a - b),\n heights: [],\n qualities: config.images.qualities ?? [75],\n formats: config.images.formats,\n minimumCacheTTL: config.images.minimumCacheTTL,\n dangerouslyAllowSVG: config.images.dangerouslyAllowSVG,\n contentSecurityPolicy: config.images.contentSecurityPolicy,\n contentDispositionType: config.images.contentDispositionType,\n maximumRedirects: config.images.maximumRedirects,\n maximumResponseBody: config.images.maximumResponseBody,\n variants: {},\n };\n};\n\n/**\n * Next.js deployment adapter used automatically by Gigadrive Network build workers.\n *\n * Next 16.2 and newer run the entire deployment as a single `output: 'standalone'`\n * server (one function per deployment) while the injected cache handlers, image\n * loader, and this hook's `onBuildComplete` metadata keep ISR, PPR, `use cache`,\n * and image optimization working through the platform's durable runtime-cache and\n * edge image services. Older releases retain the legacy standalone behavior without\n * the managed-runtime injections.\n */\n/**\n * The config this adapter returned to Next 15, kept for its `onBuildComplete`,\n * which receives none of it. Next 15 calls `modifyConfig` only for production\n * builds and servers, in the same process as the build, and keeps normalizing\n * the returned object (an export build moves `distDir` back to `.next`).\n */\nlet next15Config: NextConfigComplete | undefined;\n\n/**\n * The application directory of a Next 15 build. Next looks for its config file\n * in parent directories too, so a shared config can sit above the application.\n * Every output it reports lives under `<application>/<distDir>/server/`.\n */\nconst findNext15ProjectDir = (outputs: unknown, distDir: string): string | undefined => {\n const marker = `${path.sep}${path.normalize(distDir)}${path.sep}server${path.sep}`;\n const lists = typeof outputs === 'object' && outputs !== null ? Object.values(outputs) : [];\n for (const list of lists) {\n for (const output of Array.isArray(list) ? list : []) {\n const filePath: unknown =\n typeof output === 'object' && output !== null && 'filePath' in output ? output.filePath : undefined;\n const index = typeof filePath === 'string' ? filePath.indexOf(marker) : -1;\n if (typeof filePath === 'string' && index > 0) return filePath.slice(0, index);\n }\n }\n return undefined;\n};\n\n/** Reads the version of the Next.js the project at `projectDir` resolves. */\nconst readNextVersion = (projectDir: string): string => {\n const nextPackage: unknown = createRequire(path.join(projectDir, 'package.json'))('next/package.json');\n return typeof nextPackage === 'object' &&\n nextPackage !== null &&\n 'version' in nextPackage &&\n typeof nextPackage.version === 'string'\n ? nextPackage.version\n : '0.0.0';\n};\n\n/**\n * Writes the legacy standalone manifest for a Next 15 build from the config its\n * `modifyConfig` returned and the outputs of the build. Its build id is the one\n * Next wrote before calling `onBuildComplete`.\n */\nconst writeNext15Manifest = async (config: NextConfigComplete | undefined, outputs: unknown) => {\n const configuredDistDir = config?.distDir ?? '.next';\n const projectDir =\n findNext15ProjectDir(outputs, configuredDistDir) ??\n (config?.configFile ? path.dirname(config.configFile) : process.cwd());\n const distDir = path.resolve(projectDir, configuredDistDir);\n const repoRoot = config?.outputFileTracingRoot || projectDir;\n const buildId = (await readFile(path.join(distDir, 'BUILD_ID'), 'utf8')).trim();\n const manifest: GigadriveNextBuildManifestV1 = {\n version: 1,\n output: config?.output === 'export' ? 'export' : 'standalone',\n distDir: toPortableRelativePath(projectDir, distDir),\n repoRootToProject: toPortableRelativePath(repoRoot, projectDir, true),\n nextVersion: readNextVersion(projectDir),\n buildId,\n };\n await mkdir(path.join(projectDir, '.gigadrive'), { recursive: true });\n await writeFile(path.join(projectDir, '.gigadrive', 'nextjs.json'), `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n};\n\nconst gigadriveNextAdapter: NextAdapter = {\n name: 'Gigadrive Network',\n\n modifyConfig(config, context?: ModifyConfigContext) {\n // Next 15 passes no context. It only calls this for production builds and\n // servers, and an unknown version takes the legacy standalone path below.\n const { phase, nextVersion } = context ?? { phase: PRODUCTION_BUILD_PHASE, nextVersion: undefined };\n if (phase !== PRODUCTION_BUILD_PHASE) return config;\n\n const deploymentId = config.deploymentId ?? process.env.GIGADRIVE_DEPLOYMENT_ID;\n if (!supportsManagedRuntime(nextVersion)) {\n const legacyConfig = {\n ...config,\n ...(deploymentId ? { deploymentId } : {}),\n output: config.output === 'export' ? ('export' as const) : ('standalone' as const),\n };\n if (!context) next15Config = legacyConfig;\n return legacyConfig;\n }\n if (config.output === 'export') {\n return { ...config, ...(deploymentId ? { deploymentId } : {}) };\n }\n\n const injectCacheHandler = config.cacheHandler === undefined;\n const injectCacheComponentHandlers = config.cacheHandlers === undefined;\n const images = config.images;\n const injectImageLoader =\n images !== undefined && images.unoptimized !== true && images.loader === 'default' && !images.loaderFile;\n\n return {\n ...config,\n ...(deploymentId ? { deploymentId } : {}),\n // Run the whole deployment as one standalone Next server rather than a\n // serverless function per route. `onBuildComplete` still fires under\n // standalone (Next >= 16.2), and the standalone server natively honors the\n // injected cache handlers and resumes PPR from its incremental cache, so\n // ISR/PPR/`use cache` stay durable via the remote runtime-cache service.\n // Validated on Next 16.2.x (see MANAGED_STANDALONE_VALIDATED_MAX_MAJOR);\n // a future major that forbids adapter + standalone fails loudly at build.\n output: 'standalone',\n ...(injectCacheHandler ? { cacheHandler: CACHE_HANDLER_PATH() } : {}),\n ...(injectCacheComponentHandlers\n ? {\n cacheHandlers: {\n default: CACHE_COMPONENTS_HANDLER_PATH(),\n remote: CACHE_COMPONENTS_HANDLER_PATH(),\n },\n }\n : {}),\n ...(injectCacheHandler || injectCacheComponentHandlers ? { cacheMaxMemorySize: 0 } : {}),\n ...(injectImageLoader\n ? {\n images: {\n ...images,\n loader: 'custom',\n loaderFile: IMAGE_LOADER_PATH(),\n },\n // Next calls a custom loader without its image config, so the\n // loader reads `images.qualities` from this inlined value to pick\n // the quality Next's own loader would.\n env: { ...config.env, GIGADRIVE_NEXT_IMAGE_QUALITIES: (images.qualities ?? []).join(',') },\n }\n : {}),\n };\n },\n\n async onBuildComplete(context: BuildCompleteContext | Next15BuildCompleteContext) {\n if (!('projectDir' in context)) {\n await writeNext15Manifest(next15Config, context.outputs);\n return;\n }\n const { projectDir, repoRoot, distDir, config, nextVersion, buildId, routing, outputs } = context;\n const metadataDirectory = path.join(projectDir, '.gigadrive');\n await mkdir(metadataDirectory, { recursive: true });\n const manifestPath = path.join(metadataDirectory, 'nextjs.json');\n const writeManifest = (manifest: unknown) =>\n writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\\n`, 'utf8');\n\n if (!supportsManagedRuntime(nextVersion)) {\n const manifest: GigadriveNextBuildManifestV1 = {\n version: 1,\n output: config.output === 'export' ? 'export' : 'standalone',\n distDir: toPortableRelativePath(projectDir, distDir),\n repoRootToProject: toPortableRelativePath(repoRoot, projectDir, true),\n nextVersion,\n buildId,\n };\n await writeManifest(manifest);\n return;\n }\n\n const portableDistDir = toPortableRelativePath(projectDir, distDir);\n const repoRootToProject = toPortableRelativePath(repoRoot, projectDir, true);\n\n if (config.output === 'export') {\n const manifest: GigadriveNextBuildManifestV2Export = {\n version: 2,\n mode: 'export',\n distDir: portableDistDir,\n repoRootToProject,\n nextVersion,\n buildId,\n };\n await writeManifest(manifest);\n return;\n }\n\n if (config.output === 'standalone') {\n await ensureStandaloneServerTraces(projectDir, repoRoot, distDir, config);\n }\n\n const [resolvedRepoRoot, resolvedProjectDir] = await Promise.all([realpath(repoRoot), realpath(projectDir)]);\n const prerenders = await mapInBatches(outputs.prerenders, (output) =>\n serializePrerenderOutput(repoRoot, resolvedRepoRoot, output)\n );\n const assetManifest = await serializeAssetManifest(\n projectDir,\n resolvedProjectDir,\n distDir,\n config.basePath,\n routing.rsc.contentTypeHeader ?? DEFAULT_RSC_CONTENT_TYPE,\n config.i18n?.locales ?? [],\n outputs.staticFiles\n );\n const prerenderManifest: GigadriveNextPrerenderManifestV1 = {\n version: 1,\n seedMethods: ['GET', 'HEAD'],\n prerenders,\n };\n await mkdir(path.join(metadataDirectory, 'assets'), { recursive: true });\n await Promise.all([\n writeFile(path.join(projectDir, NEXT_ASSET_MANIFEST_PATH), `${JSON.stringify(assetManifest)}\\n`, 'utf8'),\n writeFile(path.join(projectDir, NEXT_PRERENDER_MANIFEST_PATH), `${JSON.stringify(prerenderManifest)}\\n`, 'utf8'),\n ]);\n const server = aggregateServerDescriptor([\n ...outputs.pages,\n ...outputs.pagesApi,\n ...outputs.appPages,\n ...outputs.appRoutes,\n ...(outputs.middleware ? [outputs.middleware] : []),\n ]);\n const images = normalizeImages(config);\n // `.next/static` is thousands of content-hashed, immutable chunks. Register\n // the whole subtree as one edge-served prefix instead of enumerating files.\n const staticAssets: GigadriveNextStaticAssetPrefix[] = [\n { sourceDir: `${portableDistDir}/static`, urlPrefix: '_next/static', immutable: true },\n ];\n\n const manifest: GigadriveNextBuildManifestV2Standalone = {\n version: 2,\n mode: 'standalone-v2',\n distDir: portableDistDir,\n repoRootToProject,\n nextVersion,\n buildId,\n server,\n config: {\n basePath: config.basePath,\n trailingSlash: config.trailingSlash,\n cacheComponents: config.cacheComponents,\n ...(config.i18n ? { i18n: toJsonValue(config.i18n) } : {}),\n ...(images ? { images } : {}),\n },\n routing: {\n beforeMiddleware: toJsonValue(routing.beforeMiddleware) as JsonValue[],\n beforeFiles: toJsonValue(routing.beforeFiles) as JsonValue[],\n afterFiles: toJsonValue(routing.afterFiles) as JsonValue[],\n dynamicRoutes: toJsonValue(routing.dynamicRoutes) as JsonValue[],\n onMatch: toJsonValue(routing.onMatch) as JsonValue[],\n fallback: toJsonValue(routing.fallback) as JsonValue[],\n shouldNormalizeNextData: routing.shouldNormalizeNextData,\n rsc: toJsonValue(routing.rsc),\n },\n outputs: {\n prerenders: [],\n prerenderManifest: NEXT_PRERENDER_MANIFEST_PATH,\n assetManifest: NEXT_ASSET_MANIFEST_PATH,\n entryPagePaths: getEntryPagePaths(prerenders),\n staticAssets,\n middleware: outputs.middleware\n ? {\n present: true,\n matchers: (outputs.middleware.config.matchers ?? []).map(({ source, sourceRegex, has, missing }) => ({\n source,\n sourceRegex,\n has,\n missing,\n })),\n }\n : { present: false, matchers: [] },\n },\n };\n await writeManifest(manifest);\n },\n};\n\nexport { MANAGED_STANDALONE_VALIDATED_MAX_MAJOR };\nexport default gigadriveNextAdapter;\n","import { Option, Schema } from 'effect';\n\nconst HTTP_HEADER_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/;\nconst HTTP_HEADER_VALUE = /^[\\t\\x20-\\x7e\\x80-\\xff]*$/;\nconst URL_PATHNAME_FORBIDDEN_CHARACTER = /[\\x00-\\x1f\\x7f?#\\\\]/;\n\nconst isUrlDotSegment = (segment: string): boolean => {\n const decodedDots = segment.replace(/%2e/gi, '.');\n return decodedDots === '.' || decodedDots === '..';\n};\n\nconst isPortableRelativePath = (value: string, allowCurrentDirectory = false): boolean => {\n const normalized = value.replaceAll('\\\\', '/').replace(/^\\.\\//, '').replace(/\\/+$/, '');\n return (\n (allowCurrentDirectory || (normalized !== '' && normalized !== '.')) &&\n !normalized.startsWith('/') &&\n !/^[A-Za-z]:/.test(normalized) &&\n !normalized.includes(':') &&\n !normalized.split('/').includes('..')\n );\n};\n\nexport const PortableRelativePathSchema = Schema.String.pipe(Schema.filter((value) => isPortableRelativePath(value)));\n\nexport const RepositoryRelativePathSchema = Schema.String.pipe(\n Schema.filter((value) => isPortableRelativePath(value, true))\n);\n\nexport const UrlPathnameSchema = Schema.String.pipe(\n Schema.filter(\n (value) =>\n value.startsWith('/') && !URL_PATHNAME_FORBIDDEN_CHARACTER.test(value) && !value.split('/').some(isUrlDotSegment)\n )\n);\n\nexport const HttpHeaderValueSchema = Schema.String.pipe(Schema.pattern(HTTP_HEADER_VALUE));\nexport const HttpHeadersSchema = Schema.mutable(\n Schema.Record({\n key: Schema.String,\n value: Schema.Union(HttpHeaderValueSchema, Schema.mutable(Schema.Array(HttpHeaderValueSchema))),\n })\n).pipe(Schema.filter((headers) => Object.keys(headers).every((name) => HTTP_HEADER_NAME.test(name))));\nexport const HttpSingleValueHeadersSchema = Schema.mutable(\n Schema.Record({ key: Schema.String, value: HttpHeaderValueSchema })\n).pipe(Schema.filter((headers) => Object.keys(headers).every((name) => HTTP_HEADER_NAME.test(name))));\n\n/**\n * Decode an unknown value with an Effect schema.\n *\n * @param schema - Schema used to validate and decode the value.\n * @param value - Unknown input to decode.\n * @returns The decoded value, or `undefined` when validation fails.\n * @example\n * decodeUnknown(Schema.String, 'value');\n */\nexport const decodeUnknown = <A, I>(schema: Schema.Schema<A, I, never>, value: unknown): A | undefined =>\n Schema.decodeUnknownOption(schema, { onExcessProperty: 'preserve' })(value).pipe(Option.getOrUndefined);\n\n/**\n * Decode a JSON string with an Effect schema.\n *\n * @param schema - Schema used to validate and decode the parsed JSON value.\n * @param content - JSON string to parse and decode.\n * @returns The decoded value, or `undefined` when parsing or validation fails.\n * @example\n * decodeJson(Schema.Struct({ version: Schema.Number }), '{\"version\":1}');\n */\nexport const decodeJson = <A, I>(schema: Schema.Schema<A, I, never>, content: string): A | undefined =>\n decodeUnknown(Schema.parseJson(schema), content);\n","/**\n * A representative sample is enough for cache warming. The complete prerender\n * table stays in its sidecar so it cannot expand gateway configuration by\n * thousands of paths.\n */\nexport const MAXIMUM_ENTRY_PAGE_PATHS = 50;\n"],"mappings":";AAAA,SAAS,UAAAA,eAAc;AAEvB,SAAS,QAAQ,OAAO,UAAU,UAAU,MAAM,iBAAiB;AACnE,SAAS,qBAAqB;AAC9B,OAAO,UAAU;AACjB,SAAS,qBAAqB;;;ACL9B,SAAS,QAAQ,cAAc;AAE/B,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,mCAAmC;AAEzC,IAAM,kBAAkB,CAAC,YAA6B;AACpD,QAAM,cAAc,QAAQ,QAAQ,SAAS,GAAG;AAChD,SAAO,gBAAgB,OAAO,gBAAgB;AAChD;AAEA,IAAM,yBAAyB,CAAC,OAAe,wBAAwB,UAAmB;AACxF,QAAM,aAAa,MAAM,WAAW,MAAM,GAAG,EAAE,QAAQ,SAAS,EAAE,EAAE,QAAQ,QAAQ,EAAE;AACtF,UACG,yBAA0B,eAAe,MAAM,eAAe,QAC/D,CAAC,WAAW,WAAW,GAAG,KAC1B,CAAC,aAAa,KAAK,UAAU,KAC7B,CAAC,WAAW,SAAS,GAAG,KACxB,CAAC,WAAW,MAAM,GAAG,EAAE,SAAS,IAAI;AAExC;AAEO,IAAM,6BAA6B,O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BAAgB;AAAA,QACtD,aAAa,YAAY,QAAQ,WAAW;AAAA,QAC5C,YAAY,YAAY,QAAQ,UAAU;AAAA,QAC1C,eAAe,YAAY,QAAQ,aAAa;AAAA,QAChD,SAAS,YAAY,QAAQ,OAAO;AAAA,QACpC,UAAU,YAAY,QAAQ,QAAQ;AAAA,QACtC,yBAAyB,QAAQ;AAAA,QACjC,KAAK,YAAY,QAAQ,GAAG;AAAA,MAC9B;AAAA,MACA,SAAS;AAAA,QACP,YAAY,CAAC;AAAA,QACb,mBAAmB;AAAA,QACnB,eAAe;AAAA,QACf,gBAAgB,kBAAkB,UAAU;AAAA,QAC5C;AAAA,QACA,YAAY,QAAQ,aAChB;AAAA,UACE,SAAS;AAAA,UACT,WAAW,QAAQ,WAAW,OAAO,YAAY,CAAC,GAAG,IAAI,CAAC,EAAE,QAAQ,aAAa,KAAK,QAAQ,OAAO;AAAA,YACnG;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,UACF,EAAE;AAAA,QACJ,IACA,EAAE,SAAS,OAAO,UAAU,CAAC,EAAE;AAAA,MACrC;AAAA,IACF;AACA,UAAM,cAAc,QAAQ;AAAA,EAC9B;AACF;AAGA,IAAO,yBAAQ;","names":["Schema","Schema","manifest"]}
|
|
@@ -23,6 +23,16 @@ __export(nextjs_image_loader_exports, {
|
|
|
23
23
|
default: () => gigadriveNextImageLoader
|
|
24
24
|
});
|
|
25
25
|
module.exports = __toCommonJS(nextjs_image_loader_exports);
|
|
26
|
+
var configuredQualities = () => (process.env.GIGADRIVE_NEXT_IMAGE_QUALITIES ?? "").split(",").map(Number).filter((quality) => Number.isInteger(quality) && quality > 0);
|
|
27
|
+
var DEFAULT_QUALITY = 75;
|
|
28
|
+
var resolveQuality = (quality, qualities) => {
|
|
29
|
+
const requested = quality || DEFAULT_QUALITY;
|
|
30
|
+
if (!qualities.length) return requested;
|
|
31
|
+
return qualities.reduce(
|
|
32
|
+
(closest, candidate) => Math.abs(candidate - requested) < Math.abs(closest - requested) ? candidate : closest,
|
|
33
|
+
qualities[0]
|
|
34
|
+
);
|
|
35
|
+
};
|
|
26
36
|
var sourcePathname = (source) => source.startsWith("http://") || source.startsWith("https://") ? new URL(source).pathname : source.split(/[?#]/, 1)[0];
|
|
27
37
|
var filenameHint = (source) => {
|
|
28
38
|
const candidate = sourcePathname(source).split("/").filter(Boolean).at(-1) ?? "image";
|
|
@@ -41,8 +51,10 @@ var stripDeploymentMarker = (src) => {
|
|
|
41
51
|
function gigadriveNextImageLoader({ src, width, quality }) {
|
|
42
52
|
if (isSvgSource(src)) return src;
|
|
43
53
|
const stableSrc = stripDeploymentMarker(src);
|
|
44
|
-
const parameters = new URLSearchParams({
|
|
45
|
-
|
|
54
|
+
const parameters = new URLSearchParams({
|
|
55
|
+
width: String(width),
|
|
56
|
+
quality: String(resolveQuality(quality, configuredQualities()))
|
|
57
|
+
});
|
|
46
58
|
const optimizerUrl = `/_gigadrive/image/${encodeURIComponent(stableSrc)}/${encodeURIComponent(filenameHint(stableSrc))}?${parameters}`;
|
|
47
59
|
return optimizerUrl.length > MAXIMUM_OPTIMIZER_URL_LENGTH ? src : optimizerUrl;
|
|
48
60
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nextjs-image-loader.ts"],"sourcesContent":["interface NextImageLoaderOptions {\n src: string;\n width: number;\n quality?: number;\n}\n\n/** The path portion of a source, with any query string or fragment removed. */\nconst sourcePathname = (source: string): string =>\n source.startsWith('http://') || source.startsWith('https://') ? new URL(source).pathname : source.split(/[?#]/, 1)[0];\n\nconst filenameHint = (source: string): string => {\n const candidate = sourcePathname(source).split('/').filter(Boolean).at(-1) ?? 'image';\n return /\\.(?:avif|bmp|gif|hei[cf]|jpe?g|pbm|png|svg|tga|tiff?|webp)$/i.test(candidate)\n ? candidate\n : `${candidate || 'image'}.png`;\n};\n\nconst isSvgSource = (source: string): boolean => /\\.svg$/i.test(sourcePathname(source));\n\n// Conservative bound below common CDN/proxy URL limits (~4-8 KB). The encoded\n// source is embedded in the optimizer path, so an oversized source URL cannot\n// be shortened losslessly — such images are served unoptimized instead.\nconst MAXIMUM_OPTIMIZER_URL_LENGTH = 2000;\n\n/**\n * Removes Next's `dpl` deployment marker from a local source.\n *\n * Next appends `?dpl=<deploymentId>` to local asset sources whenever a\n * deployment id is configured. The Gigadrive optimizer resolves the deployment\n * from the request hostname and never reads `dpl`, so keeping it only changes\n * the optimizer URL on every deploy — invalidating the CDN's image cache for\n * files whose content-hashed names already guarantee freshness, and forcing a\n * full re-optimization burst after each release.\n */\nconst stripDeploymentMarker = (src: string): string => {\n if (!src.startsWith('/') || !src.includes('?')) return src;\n const [pathname, query] = src.split('?', 2);\n const parameters = new URLSearchParams(query);\n parameters.delete('dpl');\n const remaining = parameters.toString();\n return remaining ? `${pathname}?${remaining}` : pathname;\n};\n\n/** Builds the stable app-host URL consumed by Gigadrive's managed image optimizer. */\nexport default function gigadriveNextImageLoader({ src, width, quality }: NextImageLoaderOptions): string {\n // No optimizer backend can rasterize SVG, so routing one through the optimizer\n // is always a pass-through: a wasted redirect and an extra request for bytes\n // the origin already serves. Next's own get-img-props marks `.svg` unoptimized\n // before any loader runs, but that bypass is skipped once a custom loaderFile\n // is configured — which is exactly what this adapter injects.\n if (isSvgSource(src)) return src;\n\n const stableSrc = stripDeploymentMarker(src);\n const parameters = new URLSearchParams({
|
|
1
|
+
{"version":3,"sources":["../src/nextjs-image-loader.ts"],"sourcesContent":["interface NextImageLoaderOptions {\n src: string;\n width: number;\n quality?: number;\n}\n\n/**\n * `images.qualities` as the adapter inlined it at build. Next calls a custom\n * loader without its image config (`get-img-props`), so the adapter passes the\n * list through `env`, which Next inlines for this exact `process.env` read.\n */\nconst configuredQualities = (): number[] =>\n (process.env.GIGADRIVE_NEXT_IMAGE_QUALITIES ?? '')\n .split(',')\n .map(Number)\n .filter((quality) => Number.isInteger(quality) && quality > 0);\n\n/** The quality Next's own loader uses when an image sets none. */\nconst DEFAULT_QUALITY = 75;\n\n/**\n * The quality to encode at, chosen the way Next's default loader does\n * (`findClosestQuality`): the requested one, or 75, snapped to the closest of\n * `images.qualities` when the app restricts them. Without it the optimizer\n * encodes at its own, higher default, which made Gigadrive's images about 40%\n * larger than the same images on Vercel.\n */\nconst resolveQuality = (quality: number | undefined, qualities: readonly number[]): number => {\n const requested = quality || DEFAULT_QUALITY;\n if (!qualities.length) return requested;\n return qualities.reduce(\n (closest, candidate) => (Math.abs(candidate - requested) < Math.abs(closest - requested) ? candidate : closest),\n qualities[0]\n );\n};\n\n/** The path portion of a source, with any query string or fragment removed. */\nconst sourcePathname = (source: string): string =>\n source.startsWith('http://') || source.startsWith('https://') ? new URL(source).pathname : source.split(/[?#]/, 1)[0];\n\nconst filenameHint = (source: string): string => {\n const candidate = sourcePathname(source).split('/').filter(Boolean).at(-1) ?? 'image';\n return /\\.(?:avif|bmp|gif|hei[cf]|jpe?g|pbm|png|svg|tga|tiff?|webp)$/i.test(candidate)\n ? candidate\n : `${candidate || 'image'}.png`;\n};\n\nconst isSvgSource = (source: string): boolean => /\\.svg$/i.test(sourcePathname(source));\n\n// Conservative bound below common CDN/proxy URL limits (~4-8 KB). The encoded\n// source is embedded in the optimizer path, so an oversized source URL cannot\n// be shortened losslessly — such images are served unoptimized instead.\nconst MAXIMUM_OPTIMIZER_URL_LENGTH = 2000;\n\n/**\n * Removes Next's `dpl` deployment marker from a local source.\n *\n * Next appends `?dpl=<deploymentId>` to local asset sources whenever a\n * deployment id is configured. The Gigadrive optimizer resolves the deployment\n * from the request hostname and never reads `dpl`, so keeping it only changes\n * the optimizer URL on every deploy — invalidating the CDN's image cache for\n * files whose content-hashed names already guarantee freshness, and forcing a\n * full re-optimization burst after each release.\n */\nconst stripDeploymentMarker = (src: string): string => {\n if (!src.startsWith('/') || !src.includes('?')) return src;\n const [pathname, query] = src.split('?', 2);\n const parameters = new URLSearchParams(query);\n parameters.delete('dpl');\n const remaining = parameters.toString();\n return remaining ? `${pathname}?${remaining}` : pathname;\n};\n\n/** Builds the stable app-host URL consumed by Gigadrive's managed image optimizer. */\nexport default function gigadriveNextImageLoader({ src, width, quality }: NextImageLoaderOptions): string {\n // No optimizer backend can rasterize SVG, so routing one through the optimizer\n // is always a pass-through: a wasted redirect and an extra request for bytes\n // the origin already serves. Next's own get-img-props marks `.svg` unoptimized\n // before any loader runs, but that bypass is skipped once a custom loaderFile\n // is configured — which is exactly what this adapter injects.\n if (isSvgSource(src)) return src;\n\n const stableSrc = stripDeploymentMarker(src);\n const parameters = new URLSearchParams({\n width: String(width),\n quality: String(resolveQuality(quality, configuredQualities())),\n });\n const optimizerUrl = `/_gigadrive/image/${encodeURIComponent(stableSrc)}/${encodeURIComponent(filenameHint(stableSrc))}?${parameters}`;\n return optimizerUrl.length > MAXIMUM_OPTIMIZER_URL_LENGTH ? src : optimizerUrl;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAWA,IAAM,sBAAsB,OACzB,QAAQ,IAAI,kCAAkC,IAC5C,MAAM,GAAG,EACT,IAAI,MAAM,EACV,OAAO,CAAC,YAAY,OAAO,UAAU,OAAO,KAAK,UAAU,CAAC;AAGjE,IAAM,kBAAkB;AASxB,IAAM,iBAAiB,CAAC,SAA6B,cAAyC;AAC5F,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAU,OAAQ,QAAO;AAC9B,SAAO,UAAU;AAAA,IACf,CAAC,SAAS,cAAe,KAAK,IAAI,YAAY,SAAS,IAAI,KAAK,IAAI,UAAU,SAAS,IAAI,YAAY;AAAA,IACvG,UAAU,CAAC;AAAA,EACb;AACF;AAGA,IAAM,iBAAiB,CAAC,WACtB,OAAO,WAAW,SAAS,KAAK,OAAO,WAAW,UAAU,IAAI,IAAI,IAAI,MAAM,EAAE,WAAW,OAAO,MAAM,QAAQ,CAAC,EAAE,CAAC;AAEtH,IAAM,eAAe,CAAC,WAA2B;AAC/C,QAAM,YAAY,eAAe,MAAM,EAAE,MAAM,GAAG,EAAE,OAAO,OAAO,EAAE,GAAG,EAAE,KAAK;AAC9E,SAAO,gEAAgE,KAAK,SAAS,IACjF,YACA,GAAG,aAAa,OAAO;AAC7B;AAEA,IAAM,cAAc,CAAC,WAA4B,UAAU,KAAK,eAAe,MAAM,CAAC;AAKtF,IAAM,+BAA+B;AAYrC,IAAM,wBAAwB,CAAC,QAAwB;AACrD,MAAI,CAAC,IAAI,WAAW,GAAG,KAAK,CAAC,IAAI,SAAS,GAAG,EAAG,QAAO;AACvD,QAAM,CAAC,UAAU,KAAK,IAAI,IAAI,MAAM,KAAK,CAAC;AAC1C,QAAM,aAAa,IAAI,gBAAgB,KAAK;AAC5C,aAAW,OAAO,KAAK;AACvB,QAAM,YAAY,WAAW,SAAS;AACtC,SAAO,YAAY,GAAG,QAAQ,IAAI,SAAS,KAAK;AAClD;AAGe,SAAR,yBAA0C,EAAE,KAAK,OAAO,QAAQ,GAAmC;AAMxG,MAAI,YAAY,GAAG,EAAG,QAAO;AAE7B,QAAM,YAAY,sBAAsB,GAAG;AAC3C,QAAM,aAAa,IAAI,gBAAgB;AAAA,IACrC,OAAO,OAAO,KAAK;AAAA,IACnB,SAAS,OAAO,eAAe,SAAS,oBAAoB,CAAC,CAAC;AAAA,EAChE,CAAC;AACD,QAAM,eAAe,qBAAqB,mBAAmB,SAAS,CAAC,IAAI,mBAAmB,aAAa,SAAS,CAAC,CAAC,IAAI,UAAU;AACpI,SAAO,aAAa,SAAS,+BAA+B,MAAM;AACpE;","names":[]}
|
|
@@ -1,4 +1,14 @@
|
|
|
1
1
|
// src/nextjs-image-loader.ts
|
|
2
|
+
var configuredQualities = () => (process.env.GIGADRIVE_NEXT_IMAGE_QUALITIES ?? "").split(",").map(Number).filter((quality) => Number.isInteger(quality) && quality > 0);
|
|
3
|
+
var DEFAULT_QUALITY = 75;
|
|
4
|
+
var resolveQuality = (quality, qualities) => {
|
|
5
|
+
const requested = quality || DEFAULT_QUALITY;
|
|
6
|
+
if (!qualities.length) return requested;
|
|
7
|
+
return qualities.reduce(
|
|
8
|
+
(closest, candidate) => Math.abs(candidate - requested) < Math.abs(closest - requested) ? candidate : closest,
|
|
9
|
+
qualities[0]
|
|
10
|
+
);
|
|
11
|
+
};
|
|
2
12
|
var sourcePathname = (source) => source.startsWith("http://") || source.startsWith("https://") ? new URL(source).pathname : source.split(/[?#]/, 1)[0];
|
|
3
13
|
var filenameHint = (source) => {
|
|
4
14
|
const candidate = sourcePathname(source).split("/").filter(Boolean).at(-1) ?? "image";
|
|
@@ -17,8 +27,10 @@ var stripDeploymentMarker = (src) => {
|
|
|
17
27
|
function gigadriveNextImageLoader({ src, width, quality }) {
|
|
18
28
|
if (isSvgSource(src)) return src;
|
|
19
29
|
const stableSrc = stripDeploymentMarker(src);
|
|
20
|
-
const parameters = new URLSearchParams({
|
|
21
|
-
|
|
30
|
+
const parameters = new URLSearchParams({
|
|
31
|
+
width: String(width),
|
|
32
|
+
quality: String(resolveQuality(quality, configuredQualities()))
|
|
33
|
+
});
|
|
22
34
|
const optimizerUrl = `/_gigadrive/image/${encodeURIComponent(stableSrc)}/${encodeURIComponent(filenameHint(stableSrc))}?${parameters}`;
|
|
23
35
|
return optimizerUrl.length > MAXIMUM_OPTIMIZER_URL_LENGTH ? src : optimizerUrl;
|
|
24
36
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/nextjs-image-loader.ts"],"sourcesContent":["interface NextImageLoaderOptions {\n src: string;\n width: number;\n quality?: number;\n}\n\n/** The path portion of a source, with any query string or fragment removed. */\nconst sourcePathname = (source: string): string =>\n source.startsWith('http://') || source.startsWith('https://') ? new URL(source).pathname : source.split(/[?#]/, 1)[0];\n\nconst filenameHint = (source: string): string => {\n const candidate = sourcePathname(source).split('/').filter(Boolean).at(-1) ?? 'image';\n return /\\.(?:avif|bmp|gif|hei[cf]|jpe?g|pbm|png|svg|tga|tiff?|webp)$/i.test(candidate)\n ? candidate\n : `${candidate || 'image'}.png`;\n};\n\nconst isSvgSource = (source: string): boolean => /\\.svg$/i.test(sourcePathname(source));\n\n// Conservative bound below common CDN/proxy URL limits (~4-8 KB). The encoded\n// source is embedded in the optimizer path, so an oversized source URL cannot\n// be shortened losslessly — such images are served unoptimized instead.\nconst MAXIMUM_OPTIMIZER_URL_LENGTH = 2000;\n\n/**\n * Removes Next's `dpl` deployment marker from a local source.\n *\n * Next appends `?dpl=<deploymentId>` to local asset sources whenever a\n * deployment id is configured. The Gigadrive optimizer resolves the deployment\n * from the request hostname and never reads `dpl`, so keeping it only changes\n * the optimizer URL on every deploy — invalidating the CDN's image cache for\n * files whose content-hashed names already guarantee freshness, and forcing a\n * full re-optimization burst after each release.\n */\nconst stripDeploymentMarker = (src: string): string => {\n if (!src.startsWith('/') || !src.includes('?')) return src;\n const [pathname, query] = src.split('?', 2);\n const parameters = new URLSearchParams(query);\n parameters.delete('dpl');\n const remaining = parameters.toString();\n return remaining ? `${pathname}?${remaining}` : pathname;\n};\n\n/** Builds the stable app-host URL consumed by Gigadrive's managed image optimizer. */\nexport default function gigadriveNextImageLoader({ src, width, quality }: NextImageLoaderOptions): string {\n // No optimizer backend can rasterize SVG, so routing one through the optimizer\n // is always a pass-through: a wasted redirect and an extra request for bytes\n // the origin already serves. Next's own get-img-props marks `.svg` unoptimized\n // before any loader runs, but that bypass is skipped once a custom loaderFile\n // is configured — which is exactly what this adapter injects.\n if (isSvgSource(src)) return src;\n\n const stableSrc = stripDeploymentMarker(src);\n const parameters = new URLSearchParams({
|
|
1
|
+
{"version":3,"sources":["../src/nextjs-image-loader.ts"],"sourcesContent":["interface NextImageLoaderOptions {\n src: string;\n width: number;\n quality?: number;\n}\n\n/**\n * `images.qualities` as the adapter inlined it at build. Next calls a custom\n * loader without its image config (`get-img-props`), so the adapter passes the\n * list through `env`, which Next inlines for this exact `process.env` read.\n */\nconst configuredQualities = (): number[] =>\n (process.env.GIGADRIVE_NEXT_IMAGE_QUALITIES ?? '')\n .split(',')\n .map(Number)\n .filter((quality) => Number.isInteger(quality) && quality > 0);\n\n/** The quality Next's own loader uses when an image sets none. */\nconst DEFAULT_QUALITY = 75;\n\n/**\n * The quality to encode at, chosen the way Next's default loader does\n * (`findClosestQuality`): the requested one, or 75, snapped to the closest of\n * `images.qualities` when the app restricts them. Without it the optimizer\n * encodes at its own, higher default, which made Gigadrive's images about 40%\n * larger than the same images on Vercel.\n */\nconst resolveQuality = (quality: number | undefined, qualities: readonly number[]): number => {\n const requested = quality || DEFAULT_QUALITY;\n if (!qualities.length) return requested;\n return qualities.reduce(\n (closest, candidate) => (Math.abs(candidate - requested) < Math.abs(closest - requested) ? candidate : closest),\n qualities[0]\n );\n};\n\n/** The path portion of a source, with any query string or fragment removed. */\nconst sourcePathname = (source: string): string =>\n source.startsWith('http://') || source.startsWith('https://') ? new URL(source).pathname : source.split(/[?#]/, 1)[0];\n\nconst filenameHint = (source: string): string => {\n const candidate = sourcePathname(source).split('/').filter(Boolean).at(-1) ?? 'image';\n return /\\.(?:avif|bmp|gif|hei[cf]|jpe?g|pbm|png|svg|tga|tiff?|webp)$/i.test(candidate)\n ? candidate\n : `${candidate || 'image'}.png`;\n};\n\nconst isSvgSource = (source: string): boolean => /\\.svg$/i.test(sourcePathname(source));\n\n// Conservative bound below common CDN/proxy URL limits (~4-8 KB). The encoded\n// source is embedded in the optimizer path, so an oversized source URL cannot\n// be shortened losslessly — such images are served unoptimized instead.\nconst MAXIMUM_OPTIMIZER_URL_LENGTH = 2000;\n\n/**\n * Removes Next's `dpl` deployment marker from a local source.\n *\n * Next appends `?dpl=<deploymentId>` to local asset sources whenever a\n * deployment id is configured. The Gigadrive optimizer resolves the deployment\n * from the request hostname and never reads `dpl`, so keeping it only changes\n * the optimizer URL on every deploy — invalidating the CDN's image cache for\n * files whose content-hashed names already guarantee freshness, and forcing a\n * full re-optimization burst after each release.\n */\nconst stripDeploymentMarker = (src: string): string => {\n if (!src.startsWith('/') || !src.includes('?')) return src;\n const [pathname, query] = src.split('?', 2);\n const parameters = new URLSearchParams(query);\n parameters.delete('dpl');\n const remaining = parameters.toString();\n return remaining ? `${pathname}?${remaining}` : pathname;\n};\n\n/** Builds the stable app-host URL consumed by Gigadrive's managed image optimizer. */\nexport default function gigadriveNextImageLoader({ src, width, quality }: NextImageLoaderOptions): string {\n // No optimizer backend can rasterize SVG, so routing one through the optimizer\n // is always a pass-through: a wasted redirect and an extra request for bytes\n // the origin already serves. Next's own get-img-props marks `.svg` unoptimized\n // before any loader runs, but that bypass is skipped once a custom loaderFile\n // is configured — which is exactly what this adapter injects.\n if (isSvgSource(src)) return src;\n\n const stableSrc = stripDeploymentMarker(src);\n const parameters = new URLSearchParams({\n width: String(width),\n quality: String(resolveQuality(quality, configuredQualities())),\n });\n const optimizerUrl = `/_gigadrive/image/${encodeURIComponent(stableSrc)}/${encodeURIComponent(filenameHint(stableSrc))}?${parameters}`;\n return optimizerUrl.length > MAXIMUM_OPTIMIZER_URL_LENGTH ? src : optimizerUrl;\n}\n"],"mappings":";AAWA,IAAM,sBAAsB,OACzB,QAAQ,IAAI,kCAAkC,IAC5C,MAAM,GAAG,EACT,IAAI,MAAM,EACV,OAAO,CAAC,YAAY,OAAO,UAAU,OAAO,KAAK,UAAU,CAAC;AAGjE,IAAM,kBAAkB;AASxB,IAAM,iBAAiB,CAAC,SAA6B,cAAyC;AAC5F,QAAM,YAAY,WAAW;AAC7B,MAAI,CAAC,UAAU,OAAQ,QAAO;AAC9B,SAAO,UAAU;AAAA,IACf,CAAC,SAAS,cAAe,KAAK,IAAI,YAAY,SAAS,IAAI,KAAK,IAAI,UAAU,SAAS,IAAI,YAAY;AAAA,IACvG,UAAU,CAAC;AAAA,EACb;AACF;AAGA,IAAM,iBAAiB,CAAC,WACtB,OAAO,WAAW,SAAS,KAAK,OAAO,WAAW,UAAU,IAAI,IAAI,IAAI,MAAM,EAAE,WAAW,OAAO,MAAM,QAAQ,CAAC,EAAE,CAAC;AAEtH,IAAM,eAAe,CAAC,WAA2B;AAC/C,QAAM,YAAY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