{"version":3,"sources":["../../../src/server/web/edge-route-module-wrapper.ts"],"sourcesContent":["import type {\n  AppRouteRouteHandlerContext,\n  AppRouteRouteModule,\n} from '../route-modules/app-route/module'\n\nimport './globals'\n\nimport { adapter, type NextRequestHint, type EdgeHandler } from './adapter'\nimport {\n  IncrementalCache,\n  type CacheHandler as IncrementalCacheHandler,\n} from '../lib/incremental-cache'\nimport type { CacheHandler } from '../lib/cache-handlers/types'\nimport { initializeCacheHandlers, setCacheHandler } from '../use-cache/handlers'\nimport { RouteMatcher } from '../route-matchers/route-matcher'\nimport type { NextFetchEvent } from './spec-extension/fetch-event'\nimport { internal_getCurrentFunctionWaitUntil } from './internal-edge-wait-until'\nimport { getServerUtils } from '../server-utils'\nimport { searchParamsToUrlQuery } from '../../shared/lib/router/utils/querystring'\nimport { CloseController, trackStreamConsumed } from './web-on-close'\nimport { getEdgePreviewProps } from './get-edge-preview-props'\nimport { WebNextRequest } from '../../server/base-http/web'\n\nexport interface WrapOptions {\n  page: string\n  cacheHandlers?: Record<string, CacheHandler>\n  incrementalCacheHandler?: typeof IncrementalCacheHandler\n}\n\n/**\n * EdgeRouteModuleWrapper is a wrapper around a route module.\n *\n * Note that this class should only be used in the edge runtime.\n */\nexport class EdgeRouteModuleWrapper {\n  private readonly matcher: RouteMatcher\n\n  /**\n   * The constructor is wrapped with private to ensure that it can only be\n   * constructed by the static wrap method.\n   *\n   * @param routeModule the route module to wrap\n   */\n  private constructor(\n    private readonly routeModule: AppRouteRouteModule,\n    private readonly cacheHandlers: Record<string, CacheHandler>\n  ) {\n    // TODO: (wyattjoh) possibly allow the module to define it's own matcher\n    this.matcher = new RouteMatcher(routeModule.definition)\n  }\n\n  /**\n   * This will wrap a module with the EdgeModuleWrapper and return a function\n   * that can be used as a handler for the edge runtime.\n   *\n   * @param module the module to wrap\n   * @param options any options that should be passed to the adapter and\n   *                override the ones passed from the runtime\n   * @returns a function that can be used as a handler for the edge runtime\n   */\n  public static wrap(\n    routeModule: AppRouteRouteModule,\n    options: WrapOptions\n  ): EdgeHandler {\n    // Create the module wrapper.\n    const wrapper = new EdgeRouteModuleWrapper(\n      routeModule,\n      options.cacheHandlers ?? {}\n    )\n\n    // Return the wrapping function.\n    return (opts) => {\n      return adapter({\n        ...opts,\n        IncrementalCache,\n        incrementalCacheHandler: options.incrementalCacheHandler,\n        // Bind the handler method to the wrapper so it still has context.\n        handler: wrapper.handler.bind(wrapper),\n        page: options.page,\n      })\n    }\n  }\n\n  private async handler(\n    request: NextRequestHint,\n    evt: NextFetchEvent\n  ): Promise<Response> {\n    const utils = getServerUtils({\n      pageIsDynamic: this.matcher.isDynamic,\n      page: this.matcher.definition.pathname,\n      basePath: request.nextUrl.basePath,\n      // We don't need the `handleRewrite` util, so can just pass an empty object\n      rewrites: {},\n      // only used for rewrites, so setting an arbitrary default value here\n      caseSensitive: false,\n    })\n\n    const { nextConfig } = this.routeModule.getNextConfigEdge(\n      new WebNextRequest(request)\n    )\n    initializeCacheHandlers(nextConfig.cacheMaxMemorySize)\n    for (const [kind, cacheHandler] of Object.entries(this.cacheHandlers)) {\n      setCacheHandler(kind, cacheHandler)\n    }\n\n    const { params } = utils.normalizeDynamicRouteParams(\n      searchParamsToUrlQuery(request.nextUrl.searchParams),\n      false\n    )\n\n    const waitUntil = evt.waitUntil.bind(evt)\n    const closeController = new CloseController()\n\n    const previewProps = getEdgePreviewProps()\n\n    // Create the context for the handler. This contains the params from the\n    // match (if any).\n    const context: AppRouteRouteHandlerContext = {\n      params,\n      previewProps,\n      renderOpts: {\n        supportsDynamicResponse: true,\n        waitUntil,\n        onClose: closeController.onClose.bind(closeController),\n        onAfterTaskError: undefined,\n        cacheComponents: !!process.env.__NEXT_CACHE_COMPONENTS,\n        experimental: {\n          authInterrupts: !!process.env.__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS,\n        },\n        cacheLifeProfiles: nextConfig.cacheLife,\n      },\n      sharedContext: {\n        buildId: '', // TODO: Populate this properly.\n      },\n    }\n\n    // Get the response from the handler.\n    let res = await this.routeModule.handle(request, context)\n\n    const waitUntilPromises = [internal_getCurrentFunctionWaitUntil()]\n    if (context.renderOpts.pendingWaitUntil) {\n      waitUntilPromises.push(context.renderOpts.pendingWaitUntil)\n    }\n    evt.waitUntil(Promise.all(waitUntilPromises))\n\n    if (!res.body) {\n      // we can delay running it until a bit later --\n      // if it's needed, we'll have a `waitUntil` lock anyway.\n      setTimeout(() => closeController.dispatchClose(), 0)\n    } else {\n      // NOTE: if this is a streaming response, onClose may be called later,\n      // so we can't rely on `closeController.listeners` -- it might be 0 at this point.\n      const trackedBody = trackStreamConsumed(res.body, () =>\n        closeController.dispatchClose()\n      )\n      res = new Response(trackedBody, {\n        status: res.status,\n        statusText: res.statusText,\n        headers: res.headers,\n      })\n    }\n\n    return res\n  }\n}\n"],"names":["EdgeRouteModuleWrapper","routeModule","cacheHandlers","matcher","RouteMatcher","definition","wrap","options","wrapper","opts","adapter","IncrementalCache","incrementalCacheHandler","handler","bind","page","request","evt","utils","getServerUtils","pageIsDynamic","isDynamic","pathname","basePath","nextUrl","rewrites","caseSensitive","nextConfig","getNextConfigEdge","WebNextRequest","initializeCacheHandlers","cacheMaxMemorySize","kind","cacheHandler","Object","entries","setCacheHandler","params","normalizeDynamicRouteParams","searchParamsToUrlQuery","searchParams","waitUntil","closeController","CloseController","previewProps","getEdgePreviewProps","context","renderOpts","supportsDynamicResponse","onClose","onAfterTaskError","undefined","cacheComponents","process","env","__NEXT_CACHE_COMPONENTS","experimental","authInterrupts","__NEXT_EXPERIMENTAL_AUTH_INTERRUPTS","cacheLifeProfiles","cacheLife","sharedContext","buildId","res","handle","waitUntilPromises","internal_getCurrentFunctionWaitUntil","pendingWaitUntil","push","Promise","all","body","setTimeout","dispatchClose","trackedBody","trackStreamConsumed","Response","status","statusText","headers"],"mappings":";;;;+BAkCaA;;;eAAAA;;;QA7BN;yBAEyD;kCAIzD;0BAEkD;8BAC5B;uCAEwB;6BACtB;6BACQ;4BACc;qCACjB;qBAC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