{"version":3,"sources":["../src/workflows.ts","../src/routing/specificity.ts","../src/server-http.ts","../src/search-params.ts","../src/secret-compare.ts","../src/utils/runtime-env.ts","../src/utils/decode.ts","../src/utils.ts","../src/plugins/route-pattern.ts"],"sourcesContent":["import {\n  createFarmRequestBodyErrorResponse,\n  readFarmRequestBody,\n  resolveFarmServerConfig,\n  type FarmServerConfig,\n  type ResolvedFarmServerConfig,\n} from \"./server-http\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { farmSecretsMatch } from \"./secret-compare\";\nimport { isFarmDeployedRuntime, readFarmEnvironmentValue } from \"./utils/runtime-env\";\nimport { decodeRouteSegment } from \"./utils/decode\";\nimport { toPosixPath } from \"./utils\";\nimport { validateConfigRouteSource } from \"./plugins/route-pattern\";\nimport {\n  isAbsolute as isAbsolutePath,\n  normalize as normalizePath,\n  relative as relativeFilePath,\n  resolve as resolvePath,\n  sep as pathSeparator,\n} from \"node:path\";\n\nexport type FarmWorkflowSchedule = string | string[];\n\nexport interface FarmWorkflowsUserConfig {\n  /** Enable or disable Farm workflow discovery. Enabled by default. */\n  enabled?: boolean;\n  /** Directory or directories to scan for workflow modules. */\n  dir?: string | string[];\n  /** Alias for dir. */\n  dirs?: string[];\n  /** HTTP route used for manual and URL-based cron invocation. */\n  route?: string;\n  /** Environment variable that stores the optional runner secret. */\n  secretEnv?: string;\n  /** Inline runner secret. Prefer secretEnv for deployed apps. */\n  secret?: string;\n  /**\n   * Serve the workflow route without a secret in a deployed runtime.\n   * Defaults to false: without a secret the route is public, so production\n   * requests are rejected unless this is explicitly enabled.\n   */\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowsResolvedConfig {\n  enabled: boolean;\n  dirs: string[];\n  route: string;\n  secretEnv: string;\n  secret?: string;\n  allowUnsecured?: boolean;\n}\n\nexport interface FarmWorkflowLogger {\n  info: (...args: unknown[]) => void;\n  warn: (...args: unknown[]) => void;\n  error: (...args: unknown[]) => void;\n}\n\nexport interface FarmWorkflowRunContext<TPayload = unknown> {\n  id: string;\n  name: string;\n  payload: TPayload;\n  scheduledTime?: number | string;\n  request?: Request;\n  event?: unknown;\n  env: Record<string, string | undefined>;\n  data: Map<string, unknown>;\n  log: FarmWorkflowLogger;\n}\n\nexport interface FarmWorkflowDefinition<TPayload = unknown, TResult = unknown> {\n  kind?: \"farm-workflow\";\n  id?: string;\n  description?: string;\n  schedule?: FarmWorkflowSchedule;\n  timezone?: string;\n  run: (ctx: FarmWorkflowRunContext<TPayload>) => TResult | Promise<TResult>;\n}\n\nexport interface FarmCronDefinition<\n  TPayload = unknown,\n  TResult = unknown,\n> extends FarmWorkflowDefinition<TPayload, TResult> {\n  schedule: FarmWorkflowSchedule;\n}\n\nexport interface FarmDiscoveredWorkflow {\n  id: string;\n  filePath: string;\n  description?: string;\n  schedule: string[];\n  timezone?: string;\n  routePath: string;\n}\n\nexport interface PreparedFarmWorkflows {\n  workflows: FarmDiscoveredWorkflow[];\n  tasks: Record<string, { handler: string; description: string }>;\n  scheduledTasks: Record<string, string | string[]>;\n  handlerPath?: string;\n  manifestPath?: string;\n}\n\nexport interface FarmWorkflowHTTPHandlerOptions {\n  workflows: FarmDiscoveredWorkflow[];\n  config: FarmWorkflowsResolvedConfig;\n  loadModule: (workflow: FarmDiscoveredWorkflow) => Promise<Record<string, any>>;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}\n\nexport const DEFAULT_FARM_WORKFLOW_DIRS = [\"src/jobs\", \"src/workflows\", \"src/cron\"];\nexport const DEFAULT_FARM_WORKFLOW_ROUTE = \"/api/_farm/workflows\";\nexport const DEFAULT_FARM_WORKFLOW_SECRET_ENV = \"CRON_SECRET\";\nconst MISSING_FARM_WORKFLOW_SECRET_ERROR =\n  \"Workflow route requires a secret. Set the CRON_SECRET environment variable, configure workflows.secret, or set workflows.allowUnsecured to true.\";\n\nexport function defineWorkflow<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function defineTask<const TPayload = unknown, TResult = unknown>(\n  definition: FarmWorkflowDefinition<TPayload, TResult>,\n): FarmWorkflowDefinition<TPayload, TResult> {\n  return defineWorkflow(definition);\n}\n\n/**\n * @deprecated Configure `cron` in `farm.config.ts` and point it at an API route.\n */\nexport function defineCron<const TPayload = unknown, TResult = unknown>(\n  definition: FarmCronDefinition<TPayload, TResult>,\n): FarmCronDefinition<TPayload, TResult> {\n  return {\n    ...definition,\n    kind: \"farm-workflow\",\n  };\n}\n\nexport function resolveWorkflowsConfig(\n  workflows: FarmWorkflowsUserConfig | boolean | undefined,\n): FarmWorkflowsResolvedConfig {\n  if (workflows === false) {\n    return {\n      enabled: false,\n      dirs: [...DEFAULT_FARM_WORKFLOW_DIRS],\n      route: DEFAULT_FARM_WORKFLOW_ROUTE,\n      secretEnv: DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    };\n  }\n\n  const options = workflows && typeof workflows === \"object\" ? workflows : {};\n  const dirs = normalizeWorkflowDirs(options);\n\n  return {\n    enabled: options.enabled ?? true,\n    dirs,\n    route: normalizeWorkflowRoute(options.route || DEFAULT_FARM_WORKFLOW_ROUTE),\n    secretEnv: options.secretEnv || DEFAULT_FARM_WORKFLOW_SECRET_ENV,\n    secret: options.secret,\n    allowUnsecured: options.allowUnsecured === true,\n  };\n}\n\nexport async function discoverFarmWorkflows(\n  config: {\n    root?: string;\n    workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  },\n  options: {\n    loadModule?: (filePath: string) => Promise<Record<string, any>>;\n  } = {},\n): Promise<FarmDiscoveredWorkflow[]> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  if (!workflowConfig.enabled) return [];\n\n  const root = config.root || process.cwd();\n  const files = await findWorkflowFiles(root, workflowConfig.dirs);\n  const workflows: FarmDiscoveredWorkflow[] = [];\n  const seenIds = new Map<string, string>();\n\n  for (const filePath of files) {\n    const module = options.loadModule\n      ? await options.loadModule(filePath)\n      : await loadWorkflowModule(filePath, root);\n    const definition = resolveWorkflowDefinition(module);\n    if (!definition) continue;\n\n    const id = normalizeWorkflowId(\n      definition.id || workflowIdFromFile(root, workflowConfig.dirs, filePath),\n    );\n    const previousPath = seenIds.get(id);\n    if (previousPath) {\n      throw new Error(\n        `Duplicate Farm workflow id \"${id}\" found in ${relativePath(root, previousPath)} and ${relativePath(root, filePath)}.`,\n      );\n    }\n    seenIds.set(id, filePath);\n\n    workflows.push({\n      id,\n      filePath,\n      description: definition.description,\n      schedule: normalizeSchedule(definition.schedule),\n      timezone: definition.timezone,\n      routePath: joinRoute(workflowConfig.route, encodeURIComponent(id)),\n    });\n  }\n\n  return workflows;\n}\n\nexport function createFarmWorkflowRequestHandler(options: FarmWorkflowHTTPHandlerOptions) {\n  const workflowsById = new Map(options.workflows.map((workflow) => [workflow.id, workflow]));\n\n  return async function handleFarmWorkflowRequest(request: Request): Promise<Response | null> {\n    const url = new URL(request.url);\n    const route = normalizeWorkflowRoute(options.config.route);\n    if (url.pathname !== route && !url.pathname.startsWith(`${route}/`)) {\n      return null;\n    }\n\n    if (url.pathname === route) {\n      const secretError = verifyWorkflowSecret(request, options.config);\n      if (secretError) return secretError;\n\n      return Response.json({\n        workflows: options.workflows.map(toWorkflowMetadata),\n      });\n    }\n\n    const id = decodeRouteSegment(url.pathname.slice(route.length + 1));\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const secretError = verifyWorkflowSecret(request, options.config);\n    if (secretError) return secretError;\n\n    const workflow = workflowsById.get(id);\n    if (!workflow) {\n      return Response.json({ error: `Workflow \"${id}\" was not found.` }, { status: 404 });\n    }\n\n    let payload: unknown;\n    try {\n      payload = await readWorkflowPayload(\n        request,\n        resolveFarmServerConfig(options.server).bodySizeLimit,\n      );\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) {\n        return Response.json({ error: \"Invalid workflow request body.\" }, { status: 400 });\n      }\n      throw error;\n    }\n    const module = await options.loadModule(workflow);\n    const result = await runFarmWorkflowModule(module, {\n      id: workflow.id,\n      name: workflow.id,\n      payload,\n      request,\n      scheduledTime: readScheduledTime(payload),\n    });\n\n    return Response.json({\n      id: workflow.id,\n      ok: true,\n      result: result ?? null,\n    });\n  };\n}\n\nexport async function runFarmWorkflowModule(\n  module: Record<string, any>,\n  context: {\n    id: string;\n    name?: string;\n    payload?: unknown;\n    scheduledTime?: number | string;\n    request?: Request;\n    event?: unknown;\n    env?: Record<string, string | undefined>;\n  },\n): Promise<unknown> {\n  const definition = resolveWorkflowDefinition(module);\n  if (!definition) {\n    throw new Error(`Farm workflow \"${context.id}\" does not export a workflow definition.`);\n  }\n\n  return await definition.run({\n    id: context.id,\n    name: context.name || context.id,\n    payload: context.payload,\n    scheduledTime: context.scheduledTime,\n    request: context.request,\n    event: context.event,\n    env: context.env || process.env,\n    data: new Map<string, unknown>(),\n    log: console,\n  });\n}\n\nexport async function prepareFarmWorkflowsForNitro(config: {\n  root?: string;\n  distDir?: string;\n  workflows?: FarmWorkflowsResolvedConfig | FarmWorkflowsUserConfig | boolean;\n  server?: FarmServerConfig | ResolvedFarmServerConfig;\n}): Promise<PreparedFarmWorkflows> {\n  const workflowConfig = isResolvedWorkflowConfig(config.workflows)\n    ? config.workflows\n    : resolveWorkflowsConfig(config.workflows);\n  const root = config.root || process.cwd();\n  const distDir = config.distDir || \".farm\";\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const generatedDir = path.join(root, distDir, \".nitro\", \"farm-workflows\");\n  const workflows = await discoverFarmWorkflows({\n    root,\n    workflows: workflowConfig,\n  });\n\n  if (workflows.length === 0) {\n    await fs.rm(generatedDir, { recursive: true, force: true });\n    return {\n      workflows,\n      tasks: {},\n      scheduledTasks: {},\n    };\n  }\n\n  await fs.rm(generatedDir, { recursive: true, force: true });\n  await fs.mkdir(generatedDir, { recursive: true });\n\n  const tasks: PreparedFarmWorkflows[\"tasks\"] = {};\n  const scheduledTasks = createScheduledTasks(workflows);\n\n  const wrapperNames = resolveWorkflowWrapperFileNames(workflows.map((workflow) => workflow.id));\n  for (const workflow of workflows) {\n    const wrapperPath = toPosixPath(\n      path.join(generatedDir, `${wrapperNames.get(workflow.id)}.mjs`),\n    );\n    await fs.writeFile(wrapperPath, createNitroTaskWrapper(workflow), \"utf8\");\n    tasks[workflow.id] = {\n      handler: wrapperPath,\n      description: workflow.description || `Farm workflow ${workflow.id}`,\n    };\n  }\n\n  const handlerPath = toPosixPath(path.join(generatedDir, \"http-handler.mjs\"));\n  await fs.writeFile(\n    handlerPath,\n    createNitroWorkflowHTTPHandler(\n      workflowConfig,\n      workflows,\n      resolveFarmServerConfig(config.server),\n    ),\n    \"utf8\",\n  );\n\n  const manifestPath = path.join(generatedDir, \"manifest.json\");\n  await fs.writeFile(\n    manifestPath,\n    JSON.stringify(\n      {\n        route: workflowConfig.route,\n        secretEnv: workflowConfig.secretEnv,\n        trigger: {\n          method: \"GET\",\n          authorization: `Bearer $${workflowConfig.secretEnv}`,\n        },\n        workflows: workflows.map(toWorkflowMetadata),\n      },\n      null,\n      2,\n    ),\n    \"utf8\",\n  );\n\n  return {\n    workflows,\n    tasks,\n    scheduledTasks,\n    handlerPath,\n    manifestPath,\n  };\n}\n\nexport function createFarmWorkflowVercelCrons(\n  workflows: FarmDiscoveredWorkflow[],\n): Array<{ path: string; schedule: string }> {\n  return workflows.flatMap((workflow) =>\n    workflow.schedule.map((schedule) => ({\n      path: workflow.routePath,\n      schedule,\n    })),\n  );\n}\n\nexport function applyFarmWorkflowVercelCrons(\n  vercelConfig: Record<string, any>,\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, any> {\n  const crons = createFarmWorkflowVercelCrons(workflows);\n  if (crons.length === 0) return vercelConfig;\n\n  const existingCrons = Array.isArray(vercelConfig.crons) ? vercelConfig.crons : [];\n  const seen = new Set(existingCrons.map((cron) => `${cron.path}:${cron.schedule}`));\n  const nextCrons = [...existingCrons];\n  for (const cron of crons) {\n    const key = `${cron.path}:${cron.schedule}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    nextCrons.push(cron);\n  }\n  return {\n    ...vercelConfig,\n    crons: nextCrons,\n  };\n}\n\nfunction isResolvedWorkflowConfig(value: unknown): value is FarmWorkflowsResolvedConfig {\n  return (\n    !!value &&\n    typeof value === \"object\" &&\n    \"dirs\" in value &&\n    Array.isArray((value as FarmWorkflowsResolvedConfig).dirs) &&\n    typeof (value as FarmWorkflowsResolvedConfig).route === \"string\"\n  );\n}\n\nfunction normalizeWorkflowDirs(options: FarmWorkflowsUserConfig): string[] {\n  const rawDirs =\n    options.dirs ||\n    (Array.isArray(options.dir) ? options.dir : options.dir ? [options.dir] : undefined);\n  const dirs = rawDirs && rawDirs.length > 0 ? rawDirs : DEFAULT_FARM_WORKFLOW_DIRS;\n  return [...new Set(dirs.map(normalizeWorkflowDir).filter(Boolean))];\n}\n\nfunction normalizeWorkflowDir(value: string): string {\n  const dir = value.trim();\n  if (!dir) return \"\";\n  return isAbsolutePath(dir) ? normalizePath(dir) : trimSlashes(dir);\n}\n\nfunction normalizeWorkflowRoute(route: string): string {\n  const trimmed = route.trim();\n  if (!trimmed || trimmed === \"/\") return DEFAULT_FARM_WORKFLOW_ROUTE;\n  const normalized = `/${trimSlashes(trimmed)}`;\n  validateConfigRouteSource(normalized, \"workflows.route\");\n  return normalized;\n}\n\nfunction normalizeWorkflowId(id: string): string {\n  const normalized = id\n    .replace(/\\\\/g, \"/\")\n    .replace(/\\.(tsx?|jsx?|mjs|cjs)$/, \"\")\n    .replace(/\\/index$/, \"\")\n    .replace(/[^a-zA-Z0-9._/-]+/g, \"-\")\n    .replace(/^\\/+|\\/+$/g, \"\")\n    .replace(/\\/+/g, \"/\");\n  return normalized || \"workflow\";\n}\n\nfunction normalizeSchedule(schedule: FarmWorkflowSchedule | undefined): string[] {\n  if (!schedule) return [];\n  return (Array.isArray(schedule) ? schedule : [schedule])\n    .map((value) => value.trim())\n    .filter(Boolean);\n}\n\nfunction resolveWorkflowDefinition(\n  module: Record<string, any>,\n): FarmWorkflowDefinition | FarmCronDefinition | null {\n  const candidates = [module.default, module.workflow, module.cron, module.task, module.job];\n  for (const candidate of candidates) {\n    if (candidate && typeof candidate === \"object\" && typeof candidate.run === \"function\") {\n      return candidate as FarmWorkflowDefinition;\n    }\n  }\n  return null;\n}\n\nasync function findWorkflowFiles(root: string, dirs: string[]): Promise<string[]> {\n  const path = await import(\"path\");\n  const files: string[] = [];\n\n  for (const dir of dirs) {\n    const absoluteDir = path.isAbsolute(dir) ? dir : path.join(root, dir);\n    if (!(await pathExists(absoluteDir))) continue;\n    await walkWorkflowDir(absoluteDir, files);\n  }\n\n  return files.sort();\n}\n\nasync function walkWorkflowDir(dir: string, files: string[]): Promise<void> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const entries = await fs.readdir(dir, { withFileTypes: true });\n  for (const entry of entries) {\n    const filePath = path.join(dir, entry.name);\n    if (entry.isDirectory()) {\n      if (entry.name === \"node_modules\" || entry.name.startsWith(\".\")) continue;\n      await walkWorkflowDir(filePath, files);\n      continue;\n    }\n    if (isWorkflowFile(entry.name)) {\n      files.push(filePath);\n    }\n  }\n}\n\nasync function pathExists(filePath: string): Promise<boolean> {\n  const fs = await import(\"fs/promises\");\n  return fs\n    .access(filePath)\n    .then(() => true)\n    .catch(() => false);\n}\n\nfunction isWorkflowFile(fileName: string): boolean {\n  return /\\.(?:ts|tsx|js|jsx|mjs|cjs)$/.test(fileName) && !/\\.d\\.[cm]?ts$/.test(fileName);\n}\n\nasync function loadWorkflowModule(filePath: string, root: string): Promise<Record<string, any>> {\n  const fs = await import(\"fs/promises\");\n  const path = await import(\"path\");\n  const { pathToFileURL } = await import(\"url\");\n  const { build } = await import(\"esbuild\");\n  const outDir = path.join(root, \".farm\", \".workflow-loader\");\n  await fs.mkdir(outDir, { recursive: true });\n  const outfile = path.join(\n    outDir,\n    `workflow-${Date.now()}-${Math.random().toString(36).slice(2)}.mjs`,\n  );\n\n  await build({\n    absWorkingDir: root,\n    entryPoints: [filePath],\n    outfile,\n    bundle: true,\n    format: \"esm\",\n    platform: \"node\",\n    target: `node${process.versions.node.split(\".\")[0]}`,\n    packages: \"external\",\n    external: [\"@farm.js/core\", \"@farm.js/core/*\", \"nitro\", \"nitro/*\"],\n    jsx: \"automatic\",\n    logLevel: \"silent\",\n    sourcemap: \"inline\",\n  });\n\n  try {\n    return await import(/* @vite-ignore */ `${pathToFileURL(outfile).href}?t=${Date.now()}`);\n  } finally {\n    await fs.unlink(outfile).catch(() => undefined);\n  }\n}\n\nfunction workflowIdFromFile(root: string, dirs: string[], filePath: string): string {\n  for (const dir of dirs) {\n    const scanRoot = isAbsolutePath(dir) ? dir : resolvePath(root, dir);\n    const candidate = relativeFilePath(scanRoot, filePath);\n    if (candidate && candidate !== \"..\" && !candidate.startsWith(`..${pathSeparator}`)) {\n      return normalizeWorkflowId(candidate);\n    }\n  }\n\n  return normalizeWorkflowId(relativeFilePath(root, filePath));\n}\n\nfunction createScheduledTasks(\n  workflows: FarmDiscoveredWorkflow[],\n): Record<string, string | string[]> {\n  const scheduleMap = new Map<string, string[]>();\n  for (const workflow of workflows) {\n    for (const schedule of workflow.schedule) {\n      const taskIds = scheduleMap.get(schedule) || [];\n      taskIds.push(workflow.id);\n      scheduleMap.set(schedule, taskIds);\n    }\n  }\n\n  return Object.fromEntries(\n    [...scheduleMap.entries()].map(([schedule, taskIds]) => [\n      schedule,\n      taskIds.length === 1 ? taskIds[0] : taskIds,\n    ]),\n  );\n}\n\nfunction createNitroTaskWrapper(workflow: FarmDiscoveredWorkflow): string {\n  const normalizedPath = workflow.filePath.replace(/\\\\/g, \"/\");\n  return `\nimport { defineTask } from \"nitro/runtime\";\nimport { runFarmWorkflowModule } from \"@farm.js/core/workflows\";\nimport * as workflowModule from ${JSON.stringify(normalizedPath)};\n\nexport default defineTask({\n  meta: {\n    description: ${JSON.stringify(workflow.description || `Farm workflow ${workflow.id}`)}\n  },\n  async run(event) {\n    const payload = event?.payload || {};\n    const env = event?.context?.cloudflare?.env || event?.context?.env || process.env;\n    return await runFarmWorkflowModule(workflowModule, {\n      id: ${JSON.stringify(workflow.id)},\n      name: event?.name || ${JSON.stringify(workflow.id)},\n      payload,\n      scheduledTime: payload.scheduledTime,\n      request: event?.context?.request,\n      event,\n      env\n    });\n  }\n});\n`.trim();\n}\n\nfunction createNitroWorkflowHTTPHandler(\n  config: FarmWorkflowsResolvedConfig,\n  workflows: FarmDiscoveredWorkflow[],\n  server: ResolvedFarmServerConfig,\n): string {\n  return `\nimport { H3 } from \"h3\";\nimport { runTask } from \"nitro/runtime\";\nimport {\n  createFarmRequestBodyErrorResponse,\n  farmSecretsMatch,\n  readFarmRequestBody,\n  searchParamsToObject\n} from \"@farm.js/core/internal/production-runtime\";\n\nconst route = ${JSON.stringify(config.route)};\nconst secretEnv = ${JSON.stringify(config.secretEnv)};\nconst inlineSecret = ${JSON.stringify(config.secret || \"\")};\nconst allowUnsecured = ${JSON.stringify(config.allowUnsecured === true)};\nconst bodySizeLimit = ${JSON.stringify(server.bodySizeLimit)};\nconst workflows = ${JSON.stringify(workflows.map(toWorkflowMetadata))};\nconst workflowIds = new Set(workflows.map((workflow) => workflow.id));\n\nfunction json(value, status = 200) {\n  return new Response(JSON.stringify(value), {\n    status,\n    headers: { \"content-type\": \"application/json\" }\n  });\n}\n\nfunction decodeRouteSegment(segment) {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction getHeader(event, name) {\n  return event.req.headers.get(name);\n}\n\nfunction getSecret() {\n  // Match the dev-path verifyWorkflowSecret's resolution (readFarmEnvironmentValue):\n  // runtime bindings on globalThis.__env__ first, then process.env. Reading\n  // process.env alone misses a Cloudflare Workers secret, so a correctly\n  // configured deployment would see no secret and reject every request with 401.\n  const runtimeBindings = globalThis.__env__;\n  const runtimeSecret =\n    runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings[secretEnv] : undefined;\n  const resolved =\n    typeof runtimeSecret === \"string\"\n      ? runtimeSecret\n      : typeof process !== \"undefined\"\n        ? process.env?.[secretEnv]\n        : undefined;\n  return inlineSecret || resolved || \"\";\n}\n\nfunction verifySecret(event) {\n  const secret = getSecret();\n  if (!secret) {\n    if (allowUnsecured) return null;\n    return json({ error: ${JSON.stringify(MISSING_FARM_WORKFLOW_SECRET_ERROR)} }, 401);\n  }\n  const authorization = getHeader(event, \"authorization\") || \"\";\n  const headerSecret = getHeader(event, \"x-farm-workflow-secret\") || \"\";\n  const bearer = authorization.match(/^Bearer\\\\s+(.+)$/i)?.[1] || \"\";\n  if (farmSecretsMatch(headerSecret, secret) || farmSecretsMatch(bearer, secret)) return null;\n  return json({ error: \"Unauthorized workflow request.\" }, 401);\n}\n\nasync function readPayload(event) {\n  if (event.req.method === \"GET\" || event.req.method === \"HEAD\") {\n    return searchParamsToObject(event.url.searchParams);\n  }\n  const bytes = await readFarmRequestBody(event.req, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (getHeader(event, \"content-type\") || \"\").split(\";\", 1)[0].trim().toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n  return { text };\n}\n\nexport default new H3()\n  .get(route, (event) => {\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n    return { workflows };\n  })\n  .all(route + \"/:id\", async (event) => {\n    const id = decodeRouteSegment(event.context.params?.id || \"\");\n\n    // Verify the secret before consulting the workflow id map so the\n    // existing-vs-missing distinction is not disclosed to callers without\n    // the secret (a 401 for unknown ids would otherwise become a 404 oracle).\n    const unauthorized = verifySecret(event);\n    if (unauthorized) return unauthorized;\n\n    if (!workflowIds.has(id)) {\n      return json({ error: \"Workflow \" + id + \" was not found.\" }, 404);\n    }\n\n    let payload;\n    try {\n      payload = await readPayload(event);\n    } catch (error) {\n      const response = createFarmRequestBodyErrorResponse(error);\n      if (response) return response;\n      if (error instanceof SyntaxError) return json({ error: \"Invalid workflow request body.\" }, 400);\n      throw error;\n    }\n    const result = await runTask(id, {\n      payload,\n      context: {\n        source: \"http\",\n        request: event.req,\n        route,\n        url: event.url.href,\n        method: event.req.method\n      }\n    });\n    return {\n      id,\n      ok: true,\n      result: result ?? null\n    };\n  });\n`.trim();\n}\n\nfunction toWorkflowMetadata(workflow: FarmDiscoveredWorkflow) {\n  return {\n    id: workflow.id,\n    description: workflow.description || null,\n    schedule: workflow.schedule,\n    timezone: workflow.timezone || null,\n    path: workflow.routePath,\n  };\n}\n\nasync function readWorkflowPayload(request: Request, bodySizeLimit: number): Promise<unknown> {\n  const url = new URL(request.url);\n  if (request.method === \"GET\" || request.method === \"HEAD\") {\n    return searchParamsToObject(url.searchParams);\n  }\n\n  const bytes = await readFarmRequestBody(request, bodySizeLimit);\n  const text = new TextDecoder().decode(bytes);\n  if (!text) return {};\n  const contentType = (request.headers.get(\"content-type\") || \"\")\n    .split(\";\", 1)[0]\n    .trim()\n    .toLowerCase();\n  if (\n    contentType === \"application/json\" ||\n    (contentType.startsWith(\"application/\") && contentType.endsWith(\"+json\"))\n  ) {\n    return JSON.parse(text);\n  }\n\n  return { text };\n}\n\nfunction readScheduledTime(payload: unknown): number | string | undefined {\n  return payload && typeof payload === \"object\" && \"scheduledTime\" in payload\n    ? (payload as { scheduledTime?: number | string }).scheduledTime\n    : undefined;\n}\n\nfunction verifyWorkflowSecret(\n  request: Request,\n  config: FarmWorkflowsResolvedConfig,\n): Response | null {\n  const secret = config.secret || readFarmEnvironmentValue(config.secretEnv) || \"\";\n  if (!secret) {\n    // No secret configured. Local development stays convenient, but a deployed\n    // runtime must not expose a route that lists and executes workflows to\n    // anonymous callers. Opt back in explicitly with .\n    if (config.allowUnsecured === true || !isFarmDeployedRuntime()) return null;\n    return Response.json(\n      {\n        error: MISSING_FARM_WORKFLOW_SECRET_ERROR,\n      },\n      { status: 401 },\n    );\n  }\n\n  const authorization = request.headers.get(\"authorization\") || \"\";\n  const bearer = authorization.match(/^Bearer\\s+(.+)$/i)?.[1] || \"\";\n  const headerSecret = request.headers.get(\"x-farm-workflow-secret\") || \"\";\n  if (farmSecretsMatch(bearer, secret) || farmSecretsMatch(headerSecret, secret)) return null;\n\n  return Response.json({ error: \"Unauthorized workflow request.\" }, { status: 401 });\n}\n\nfunction joinRoute(...parts: string[]): string {\n  return `/${parts\n    .map((part) => trimSlashes(part))\n    .filter(Boolean)\n    .join(\"/\")}`;\n}\n\nfunction trimSlashes(value: string): string {\n  return value.replace(/^\\/+|\\/+$/g, \"\");\n}\n\n/**\n * Wrapper file names for a set of workflow ids.\n *\n * `safeFileName` is not injective: it maps `a/b` and `a-b` onto the same string,\n * and macOS and Windows additionally fold `Daily` onto `daily` on their default\n * case-insensitive filesystems. Two workflows would then share one generated\n * wrapper and both run whichever was written last. Only ids that actually\n * collide are disambiguated, so ordinary ids keep a readable wrapper; every id\n * in a colliding group gets a digest of the exact id appended, which keeps the\n * result independent of discovery order.\n */\nfunction resolveWorkflowWrapperFileNames(ids: readonly string[]): Map<string, string> {\n  const groups = new Map<string, number>();\n  for (const id of ids) {\n    const key = safeFileName(id).toLowerCase();\n    groups.set(key, (groups.get(key) ?? 0) + 1);\n  }\n\n  const resolved = new Map<string, string>();\n  const claimed = new Map<string, string>();\n  for (const id of ids) {\n    const base = safeFileName(id);\n    const key = base.toLowerCase();\n    const fileName = (groups.get(key) ?? 0) > 1 ? `${key}-${workflowIdFingerprint(id)}` : base;\n    const claimedBy = claimed.get(fileName.toLowerCase());\n    if (claimedBy !== undefined) {\n      throw new Error(\n        `Farm workflows ${JSON.stringify(claimedBy)} and ${JSON.stringify(id)} generate the same wrapper file ${JSON.stringify(`${fileName}.mjs`)}. Rename one of them.`,\n      );\n    }\n    claimed.set(fileName.toLowerCase(), id);\n    resolved.set(id, fileName);\n  }\n  return resolved;\n}\n\n/**\n * FNV-1a. This module is bundled into server runtimes that do not provide\n * node:crypto, and the digest only needs to separate file names.\n */\nfunction workflowIdFingerprint(value: string): string {\n  let hash = 0x811c9dc5;\n  for (let index = 0; index < value.length; index += 1) {\n    hash ^= value.charCodeAt(index);\n    hash = Math.imul(hash, 0x01000193);\n  }\n  return (hash >>> 0).toString(16).padStart(8, \"0\");\n}\n\nfunction safeFileName(value: string): string {\n  return value.replace(/[^a-zA-Z0-9._-]+/g, \"-\") || \"workflow\";\n}\n\nfunction relativePath(root: string, filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\").replace(`${root.replace(/\\\\/g, \"/\")}/`, \"\");\n}\n","export type RouteSegmentSpecificity = \"static\" | \"dynamic\" | \"catch-all\" | \"optional-catch-all\";\n\nexport class AmbiguousRouteError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = \"AmbiguousRouteError\";\n  }\n}\n\nexport class NonTerminalCatchAllRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"NonTerminalCatchAllRouteError\";\n  }\n}\n\nexport class DuplicateRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"DuplicateRouteParameterError\";\n  }\n}\n\nexport class ReservedRouteParameterError extends AmbiguousRouteError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"ReservedRouteParameterError\";\n  }\n}\n\nexport class BrowserUnstableRouteError extends TypeError {\n  constructor(message: string) {\n    super(message);\n    this.name = \"BrowserUnstableRouteError\";\n  }\n}\n\nconst SEGMENT_RANK: Record<RouteSegmentSpecificity, number> = {\n  static: 4,\n  dynamic: 3,\n  \"catch-all\": 1,\n  \"optional-catch-all\": 0,\n};\n\n// Ending a route is more specific than consuming the same path through a\n// catch-all, while a following static or dynamic segment remains more specific.\nconst ROUTE_END_RANK = 2;\n\n/** Sort route patterns from the most specific segment sequence to the least specific. */\nexport function compareRouteSpecificity(\n  left: readonly RouteSegmentSpecificity[],\n  right: readonly RouteSegmentSpecificity[],\n): number {\n  const length = Math.max(left.length, right.length);\n\n  for (let index = 0; index < length; index++) {\n    const leftRank = index < left.length ? SEGMENT_RANK[left[index]!] : ROUTE_END_RANK;\n    const rightRank = index < right.length ? SEGMENT_RANK[right[index]!] : ROUTE_END_RANK;\n    if (leftRank !== rightRank) return rightRank - leftRank;\n  }\n\n  return 0;\n}\n\nexport type RoutePatternSyntax = \"page\" | \"router\" | \"api\";\n\nconst ROUTER_PARAMETER_NAME = \"[A-Za-z0-9_$-]+\";\nconst PAGE_PARAMETER_PATTERN = /^(?:\\[\\[\\.\\.\\.(.+)\\]\\]|\\[\\.\\.\\.(.+)\\]|\\[(.+)\\])$/;\nconst ROUTER_PARAMETER_PATTERN =\n  /^(?:\\[\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]\\]|\\[\\.\\.\\.([A-Za-z0-9_$-]+)\\]|\\[([A-Za-z0-9_$-]+)\\]|:([A-Za-z0-9_$-]+)|\\*([A-Za-z0-9_$-]+)\\??)$/;\nconst RESERVED_PARAMETER_NAMES = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport function assertBrowserStableRoutePath(pattern: string): void {\n  if (pattern.includes(\"\\\\\") || hasControlCharacter(pattern)) {\n    throw new BrowserUnstableRouteError(\n      `Route path \"${pattern}\" cannot contain backslashes or control characters.`,\n    );\n  }\n\n  for (const segment of pattern.split(\"/\").filter(Boolean)) {\n    if (\n      (segment.startsWith(\"(\") && segment.endsWith(\")\")) ||\n      (segment.startsWith(\"[\") && segment.endsWith(\"]\"))\n    ) {\n      continue;\n    }\n\n    let decoded = segment;\n    try {\n      decoded = decodeURIComponent(segment);\n    } catch {\n      // Malformed escapes stay literal in browser pathnames.\n    }\n    if (\n      decoded === \".\" ||\n      decoded === \"..\" ||\n      decoded.includes(\"/\") ||\n      decoded.includes(\"\\\\\") ||\n      hasControlCharacter(decoded)\n    ) {\n      throw new BrowserUnstableRouteError(\n        `Route path \"${pattern}\" contains browser-unstable segment \"${segment}\".`,\n      );\n    }\n  }\n}\n\nfunction hasControlCharacter(value: string): boolean {\n  return Array.from(value).some((character) => {\n    const code = character.charCodeAt(0);\n    return code <= 31 || (code >= 127 && code <= 159);\n  });\n}\n\nexport function assertUniqueRouteParameters(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): void {\n  const parameterPattern = syntax === \"router\" ? ROUTER_PARAMETER_PATTERN : PAGE_PARAMETER_PATTERN;\n  const names = new Set<string>();\n\n  for (const segment of splitRoutePattern(pattern, syntax)) {\n    const match = parameterPattern.exec(segment);\n    const name = match?.slice(1).find(Boolean);\n    if (!name) continue;\n    if (RESERVED_PARAMETER_NAMES.has(name)) {\n      throw new ReservedRouteParameterError(\n        `Route parameter \"${name}\" in route \"${pattern}\" is reserved. Use a different parameter name.`,\n      );\n    }\n    if (names.has(name)) {\n      throw new DuplicateRouteParameterError(\n        `Duplicate route parameter \"${name}\" in route \"${pattern}\". Each dynamic segment must use a unique name.`,\n      );\n    }\n    names.add(name);\n  }\n}\n\nfunction splitRoutePattern(pattern: string, syntax: RoutePatternSyntax): string[] {\n  return pattern\n    .replace(/\\\\/g, \"/\")\n    .split(\"/\")\n    .filter(Boolean)\n    .filter((segment) =>\n      syntax === \"api\" ? true : !(segment.startsWith(\"(\") && segment.endsWith(\")\")),\n    );\n}\n\nexport function assertTerminalCatchAll(pattern: string, syntax: RoutePatternSyntax = \"page\"): void {\n  const segments = splitRoutePattern(pattern, syntax);\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const catchAllPattern = new RegExp(\n    syntax === \"router\"\n      ? `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]|\\\\*${parameterName}\\\\??)$`\n      : `^(?:\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]|\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\])$`,\n  );\n  const catchAllIndex = segments.findIndex((segment) => catchAllPattern.test(segment));\n  if (catchAllIndex >= 0 && catchAllIndex !== segments.length - 1) {\n    throw new NonTerminalCatchAllRouteError(\n      `Catch-all segment \"${segments[catchAllIndex]}\" must be the final segment in route \"${pattern}\".`,\n    );\n  }\n}\n\n/** Return the URL-matching shape of a route without its parameter names. */\nexport function getRoutePatternShape(pattern: string, syntax: RoutePatternSyntax = \"page\"): string {\n  assertTerminalCatchAll(pattern, syntax);\n  const segments = splitRoutePattern(pattern, syntax).map((segment) => {\n    const specificity = getPatternSegmentSpecificity(segment, syntax);\n    if (specificity !== \"static\") return specificity;\n\n    try {\n      return `static:${decodeURIComponent(segment)}`;\n    } catch {\n      return `static:${segment}`;\n    }\n  });\n\n  return segments.length === 0 ? \"/\" : JSON.stringify(segments);\n}\n\n/** Return the specificity of every URL-consuming segment in a route pattern. */\nexport function getRoutePatternSpecificity(\n  pattern: string,\n  syntax: RoutePatternSyntax = \"page\",\n): RouteSegmentSpecificity[] {\n  assertTerminalCatchAll(pattern, syntax);\n  return splitRoutePattern(pattern, syntax).map((segment) =>\n    getPatternSegmentSpecificity(segment, syntax),\n  );\n}\n\nfunction getPatternSegmentSpecificity(\n  segment: string,\n  syntax: RoutePatternSyntax,\n): RouteSegmentSpecificity {\n  const parameterName = syntax === \"router\" ? ROUTER_PARAMETER_NAME : \".+\";\n  const supportsColonAndStar = syntax === \"router\";\n  if (\n    new RegExp(`^\\\\[\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}\\\\?$`).test(segment))\n  ) {\n    return \"optional-catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[\\\\.\\\\.\\\\.${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^\\\\*${parameterName}$`).test(segment))\n  ) {\n    return \"catch-all\";\n  }\n  if (\n    new RegExp(`^\\\\[${parameterName}\\\\]$`).test(segment) ||\n    (supportsColonAndStar && new RegExp(`^:${parameterName}$`).test(segment))\n  ) {\n    return \"dynamic\";\n  }\n\n  return \"static\";\n}\n","import { assertBrowserStableRoutePath } from \"./routing/specificity\";\n\ninterface FarmNodeAbortRequest {\n  aborted?: boolean;\n  once(event: \"aborted\", listener: () => void): unknown;\n  off(event: \"aborted\", listener: () => void): unknown;\n}\n\ninterface FarmNodeAbortResponse {\n  writableEnded: boolean;\n  once(event: \"close\" | \"finish\", listener: () => void): unknown;\n  off(event: \"close\" | \"finish\", listener: () => void): unknown;\n}\n\n/** Share disconnect semantics between development and production Node requests. */\nexport function createFarmNodeRequestAbortSignal(\n  req: FarmNodeAbortRequest,\n  res: FarmNodeAbortResponse,\n): AbortSignal {\n  const controller = new AbortController();\n  let disposed = false;\n  const dispose = () => {\n    if (disposed) return;\n    disposed = true;\n    req.off(\"aborted\", abort);\n    res.off(\"close\", abortOnEarlyClose);\n    res.off(\"finish\", dispose);\n    controller.signal.removeEventListener(\"abort\", dispose);\n  };\n  const abort = () => controller.abort();\n  const abortOnEarlyClose = () => {\n    if (!res.writableEnded) abort();\n    dispose();\n  };\n\n  if (req.aborted) {\n    controller.abort();\n    return controller.signal;\n  }\n\n  req.once(\"aborted\", abort);\n  res.once(\"close\", abortOnEarlyClose);\n  res.once(\"finish\", dispose);\n  controller.signal.addEventListener(\"abort\", dispose, { once: true });\n  return controller.signal;\n}\n\nexport const DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT = 10_000_000;\nexport const DEFAULT_FARM_SERVER_HEADERS_TIMEOUT = 60_000;\nexport const DEFAULT_FARM_SERVER_REQUEST_TIMEOUT = 300_000;\nexport const DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT = 5_000;\nexport const DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT = 30_000;\nconst MAX_FARM_SERVER_TIMEOUT = 2_147_483_647;\n\nexport type FarmServerDuration = number | `${number}${\"ms\" | \"s\" | \"m\" | \"h\"}`;\n\nexport interface FarmServerHealthConfig {\n  /** Liveness endpoint. It remains healthy while a production process drains. */\n  livenessPath?: string;\n  /** Readiness endpoint. It returns 503 until startup completes and while draining. */\n  readinessPath?: string;\n}\n\nexport interface ResolvedFarmServerHealthConfig {\n  enabled: boolean;\n  livenessPath: string;\n  readinessPath: string;\n}\n\nexport interface FarmServerConfig {\n  /** Maximum request body size for API routes, integrations, workflows, and uploads. */\n  bodySizeLimit?: number | string;\n  /** Trust proxy-provided client address and request authority headers. Enable only behind a trusted proxy. */\n  trustProxy?: boolean;\n  /** Maximum time for a Node client to send complete request headers. */\n  headersTimeout?: FarmServerDuration;\n  /** Maximum time for a Node client to send the complete request. */\n  requestTimeout?: FarmServerDuration;\n  /** How long an idle Node keep-alive connection remains open after a response. */\n  keepAliveTimeout?: FarmServerDuration;\n  /** Maximum time the Node adapter drains traffic before forcing shutdown. */\n  gracefulShutdownTimeout?: FarmServerDuration;\n  /** Production liveness and readiness endpoints. Set to false to disable them. */\n  health?: false | FarmServerHealthConfig;\n}\n\nexport interface ResolvedFarmServerConfig {\n  bodySizeLimit: number;\n  trustProxy: boolean;\n  headersTimeout: number;\n  requestTimeout: number;\n  keepAliveTimeout: number;\n  gracefulShutdownTimeout: number;\n  health: ResolvedFarmServerHealthConfig;\n}\n\nexport type FarmRequestBodyErrorCode = \"BODY_TOO_LARGE\" | \"INVALID_CONTENT_LENGTH\";\n\n/** Apply the weak entity-tag comparison required by If-None-Match. */\nexport function matchesFarmIfNoneMatch(\n  value: string | readonly string[] | null | undefined,\n  etag: string,\n): boolean {\n  const expected = parseEntityTag(trimOptionalWhitespace(etag));\n  if (!expected) return false;\n\n  const values = Array.isArray(value) ? value : [value];\n  const combined = values\n    .filter((header): header is string => typeof header === \"string\")\n    .join(\",\");\n  const fieldValue = trimOptionalWhitespace(combined);\n  if (!fieldValue) return false;\n  if (fieldValue === \"*\") return true;\n\n  let matched = false;\n  let hasEntityTag = false;\n  for (const candidate of splitEntityTags(fieldValue)) {\n    const token = trimOptionalWhitespace(candidate);\n    if (!token) continue;\n\n    const parsed = parseEntityTag(token);\n    if (!parsed) return false;\n    hasEntityTag = true;\n    if (parsed === expected) matched = true;\n  }\n\n  return hasEntityTag && matched;\n}\n\nfunction trimOptionalWhitespace(value: string): string {\n  return value.replace(/^[\\t ]+|[\\t ]+$/g, \"\");\n}\n\nfunction parseEntityTag(value: string): string | null {\n  const opaqueTag = value.startsWith(\"W/\") ? value.slice(2) : value;\n  if (opaqueTag.length < 2 || opaqueTag[0] !== '\"' || opaqueTag.at(-1) !== '\"') return null;\n\n  for (let index = 1; index < opaqueTag.length - 1; index++) {\n    const code = opaqueTag.charCodeAt(index);\n    if (code === 0x21 || (code >= 0x23 && code <= 0x7e) || code >= 0x80) continue;\n    return null;\n  }\n\n  return opaqueTag;\n}\n\nfunction splitEntityTags(value: string): string[] {\n  const tags: string[] = [];\n  let start = 0;\n  let quoted = false;\n\n  for (let index = 0; index < value.length; index++) {\n    const character = value[index];\n    if (character === '\"') {\n      quoted = !quoted;\n    } else if (character === \",\" && !quoted) {\n      tags.push(value.slice(start, index));\n      start = index + 1;\n    }\n  }\n\n  tags.push(value.slice(start));\n  return tags;\n}\n\nexport class FarmRequestBodyError extends Error {\n  readonly code: FarmRequestBodyErrorCode;\n  readonly status: number;\n\n  constructor(code: FarmRequestBodyErrorCode, status: number, message: string) {\n    super(message);\n    this.name = \"FarmRequestBodyError\";\n    this.code = code;\n    this.status = status;\n  }\n}\n\nexport function resolveFarmServerConfig(\n  config: FarmServerConfig | ResolvedFarmServerConfig | undefined,\n): ResolvedFarmServerConfig {\n  const headersTimeout = parseFarmServerDuration(\n    config?.headersTimeout ?? DEFAULT_FARM_SERVER_HEADERS_TIMEOUT,\n    \"server.headersTimeout\",\n  );\n  const requestTimeout = parseFarmServerDuration(\n    config?.requestTimeout ?? DEFAULT_FARM_SERVER_REQUEST_TIMEOUT,\n    \"server.requestTimeout\",\n  );\n  if (headersTimeout > requestTimeout) {\n    throw new TypeError(\"server.headersTimeout must not exceed server.requestTimeout\");\n  }\n\n  return Object.freeze({\n    bodySizeLimit: parseBodySizeLimit(\n      config?.bodySizeLimit ?? DEFAULT_FARM_SERVER_BODY_SIZE_LIMIT,\n      \"server.bodySizeLimit\",\n    ),\n    trustProxy: config?.trustProxy === true,\n    headersTimeout,\n    requestTimeout,\n    keepAliveTimeout: parseFarmServerDuration(\n      config?.keepAliveTimeout ?? DEFAULT_FARM_SERVER_KEEP_ALIVE_TIMEOUT,\n      \"server.keepAliveTimeout\",\n    ),\n    gracefulShutdownTimeout: parseFarmServerDuration(\n      config?.gracefulShutdownTimeout ?? DEFAULT_FARM_SERVER_GRACEFUL_SHUTDOWN_TIMEOUT,\n      \"server.gracefulShutdownTimeout\",\n    ),\n    health: resolveFarmServerHealthConfig(config?.health),\n  });\n}\n\nexport function parseFarmServerDuration(\n  value: FarmServerDuration,\n  optionName = \"duration\",\n): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    if (value > MAX_FARM_SERVER_TIMEOUT) {\n      throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(ms|s|m|h)$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be milliseconds or a duration such as \"30s\" or \"2m\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2];\n  const multiplier = unit === \"ms\" ? 1 : unit === \"s\" ? 1_000 : unit === \"m\" ? 60_000 : 3_600_000;\n  const milliseconds = Math.floor(amount * multiplier);\n  if (!Number.isSafeInteger(milliseconds) || milliseconds <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n  if (milliseconds > MAX_FARM_SERVER_TIMEOUT) {\n    throw new TypeError(`${optionName} must not exceed ${MAX_FARM_SERVER_TIMEOUT} milliseconds`);\n  }\n  return milliseconds;\n}\n\nfunction resolveFarmServerHealthConfig(\n  config: false | FarmServerHealthConfig | ResolvedFarmServerHealthConfig | undefined,\n): ResolvedFarmServerHealthConfig {\n  if (config === false || (config && \"enabled\" in config && config.enabled === false)) {\n    return Object.freeze({\n      enabled: false,\n      livenessPath: \"/_farm/health/live\",\n      readinessPath: \"/_farm/health/ready\",\n    });\n  }\n\n  const livenessPath = normalizeHealthPath(\n    config?.livenessPath ?? \"/_farm/health/live\",\n    \"server.health.livenessPath\",\n  );\n  const readinessPath = normalizeHealthPath(\n    config?.readinessPath ?? \"/_farm/health/ready\",\n    \"server.health.readinessPath\",\n  );\n  if (livenessPath === readinessPath) {\n    throw new TypeError(\"server.health livenessPath and readinessPath must be different\");\n  }\n\n  return Object.freeze({ enabled: true, livenessPath, readinessPath });\n}\n\nfunction normalizeHealthPath(value: string, optionName: string): string {\n  const path = value.trim();\n  if (!path.startsWith(\"/\") || path.includes(\"?\") || path.includes(\"#\") || path.includes(\"*\")) {\n    throw new TypeError(`${optionName} must be an absolute pathname without a query or wildcard`);\n  }\n  const normalized = path.length > 1 ? path.replace(/\\/+$/, \"\") || \"/\" : path;\n  assertBrowserStableRoutePath(normalized);\n  return normalized;\n}\n\nexport function parseBodySizeLimit(value: number | string, optionName = \"bodySizeLimit\"): number {\n  if (typeof value === \"number\") {\n    if (!Number.isSafeInteger(value) || value <= 0) {\n      throw new TypeError(`${optionName} must be a positive safe integer`);\n    }\n    return value;\n  }\n\n  const match = value\n    .trim()\n    .toLowerCase()\n    .match(/^(\\d+(?:\\.\\d+)?)\\s*(b|kb|mb|gb|kib|mib|gib)?$/);\n  if (!match) {\n    throw new TypeError(`${optionName} must be bytes or a size string such as \"500kb\" or \"10mb\"`);\n  }\n\n  const amount = Number(match[1]);\n  const unit = match[2] ?? \"b\";\n  const multiplier: Record<string, number> = {\n    b: 1,\n    kb: 1_000,\n    mb: 1_000_000,\n    gb: 1_000_000_000,\n    kib: 1_024,\n    mib: 1_048_576,\n    gib: 1_073_741_824,\n  };\n  const bytes = Math.floor(amount * multiplier[unit]);\n\n  if (!Number.isSafeInteger(bytes) || bytes <= 0) {\n    throw new TypeError(`${optionName} must resolve to a positive safe integer`);\n  }\n\n  return bytes;\n}\n\nexport async function bufferFarmRequestBody(request: Request, limit: number): Promise<Request> {\n  if (request.method === \"GET\" || request.method === \"HEAD\" || request.body === null) {\n    return request;\n  }\n\n  const bytes = await readFarmRequestBody(request, limit);\n  const body = new Uint8Array(bytes.byteLength);\n  body.set(bytes);\n  return new Request(request, {\n    // oxlint-disable-next-line unicorn/no-invalid-fetch-options -- GET and HEAD return above.\n    body: body.buffer,\n  });\n}\n\nexport async function readFarmRequestBody(request: Request, limit: number): Promise<Uint8Array> {\n  try {\n    validateContentLength(request.headers.get(\"content-length\"), limit);\n  } catch (error) {\n    // A cloned Request is a tee branch: its cancellation may wait for the\n    // untouched branch. Rejection must not wait for producer-owned cleanup.\n    void request.body?.cancel(error).catch(() => {});\n    throw error;\n  }\n  throwIfAborted(request.signal);\n  if (!request.body) return new Uint8Array();\n\n  const reader = request.body.getReader();\n  const chunks: Uint8Array[] = [];\n  let total = 0;\n  const cancelBodyRead = () => {\n    void reader.cancel(request.signal.reason).catch(() => {});\n  };\n  request.signal.addEventListener(\"abort\", cancelBodyRead, { once: true });\n\n  try {\n    while (true) {\n      throwIfAborted(request.signal);\n      const { done, value } = await reader.read();\n      // Cancellation resolves a pending read as EOF, not necessarily an error.\n      throwIfAborted(request.signal);\n      if (done) break;\n      if (!value) continue;\n\n      total += value.byteLength;\n      if (total > limit) {\n        const error = new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n        void reader.cancel(error).catch(() => {});\n        throw error;\n      }\n      chunks.push(value);\n    }\n  } catch (error) {\n    if (request.signal.aborted) throwIfAborted(request.signal);\n    throw error;\n  } finally {\n    request.signal.removeEventListener(\"abort\", cancelBodyRead);\n    reader.releaseLock();\n  }\n\n  const body = new Uint8Array(total);\n  let offset = 0;\n  for (const chunk of chunks) {\n    body.set(chunk, offset);\n    offset += chunk.byteLength;\n  }\n  return body;\n}\n\nexport async function readNodeRequestBody(\n  request: {\n    headers: Record<string, string | string[] | undefined>;\n    on(event: \"data\", listener: (chunk: unknown) => void): unknown;\n    on(event: \"end\", listener: () => void): unknown;\n    on(event: \"error\", listener: (error: Error) => void): unknown;\n    removeListener?(event: string, listener: (...args: any[]) => void): unknown;\n    resume?(): unknown;\n  },\n  limit: number,\n): Promise<Buffer> {\n  const rawContentLength = request.headers[\"content-length\"];\n  const contentLength = Array.isArray(rawContentLength) ? rawContentLength[0] : rawContentLength;\n  try {\n    validateContentLength(contentLength, limit);\n  } catch (error) {\n    request.resume?.();\n    throw error;\n  }\n\n  return await new Promise<Buffer>((resolve, reject) => {\n    const chunks: Buffer[] = [];\n    let total = 0;\n    let settled = false;\n\n    const cleanup = () => {\n      request.removeListener?.(\"data\", onData);\n      request.removeListener?.(\"end\", onEnd);\n      request.removeListener?.(\"error\", onError);\n    };\n    const rejectOnce = (error: Error) => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      request.resume?.();\n      reject(error);\n    };\n    const onData = (chunk: unknown) => {\n      const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as any);\n      total += bytes.byteLength;\n      if (total > limit) {\n        rejectOnce(new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\"));\n        return;\n      }\n      chunks.push(bytes);\n    };\n    const onEnd = () => {\n      if (settled) return;\n      settled = true;\n      cleanup();\n      resolve(Buffer.concat(chunks, total));\n    };\n    const onError = (error: Error) => rejectOnce(error);\n\n    request.on(\"data\", onData);\n    request.on(\"end\", onEnd);\n    request.on(\"error\", onError);\n  });\n}\n\nexport function createFarmRequestBodyErrorResponse(error: unknown): Response | null {\n  if (!(error instanceof FarmRequestBodyError)) return null;\n\n  return new Response(error.status === 413 ? \"Payload Too Large\" : \"Bad Request\", {\n    status: error.status,\n    headers: {\n      \"cache-control\": \"no-store\",\n      \"content-type\": \"text/plain; charset=utf-8\",\n      \"x-content-type-options\": \"nosniff\",\n    },\n  });\n}\n\nfunction validateContentLength(value: string | null | undefined, limit: number): void {\n  const contentLength = value?.trim();\n  if (!contentLength) return;\n  if (!/^\\d+$/.test(contentLength)) {\n    throw new FarmRequestBodyError(\"INVALID_CONTENT_LENGTH\", 400, \"Invalid content-length header\");\n  }\n  if (Number(contentLength) > limit) {\n    throw new FarmRequestBodyError(\"BODY_TOO_LARGE\", 413, \"Request body is too large\");\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal): void {\n  if (!signal.aborted) return;\n  if (signal.reason !== undefined) throw signal.reason;\n  throw new DOMException(\"The operation was aborted\", \"AbortError\");\n}\n","/**\n * Convert URLSearchParams into the object handed to routes as `search` /\n * `searchParams`: single keys stay strings and repeated keys collect into\n * arrays, in order. The dev renderer, the production SSR entry, the SPA\n * page-data endpoint, and the generated client hydration runtime all share\n * this helper so every environment agrees on one representation.\n */\nexport function searchParamsToObject(\n  searchParams: URLSearchParams,\n): Record<string, string | string[] | undefined> {\n  const output: Record<string, string | string[] | undefined> = {};\n\n  searchParams.forEach((value, key) => {\n    // Keys come from the request URL. Writing \"__proto__\" onto a plain object\n    // replaces its prototype instead of adding an entry, so a crafted query\n    // string could reshape the object handed to pages and workflow handlers.\n    // The API route helper (entriesToObject in api/runtime.ts) already skips\n    // these names; keep both representations consistent.\n    if (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") return;\n    const existing = Object.prototype.hasOwnProperty.call(output, key) ? output[key] : undefined;\n    if (existing !== undefined) {\n      if (Array.isArray(existing)) {\n        existing.push(value);\n      } else {\n        output[key] = [existing, value];\n      }\n    } else {\n      output[key] = value;\n    }\n  });\n\n  return output;\n}\n","/**\n * Compare a caller-supplied secret against the configured one without leaking\n * how much of it matched.\n *\n * `===` on strings stops at the first differing character, so the time it takes\n * to reject a guess grows with the length of the correct prefix. Over enough\n * requests that recovers a cron or workflow secret one character at a time. This\n * always inspects every position instead.\n *\n * Deliberately not node:crypto's `timingSafeEqual`: these callers are bundled\n * into the generated Nitro runtime, which also targets edge and browser-like\n * environments where importing node:crypto breaks the build.\n */\nexport function farmSecretsMatch(provided: string, expected: string): boolean {\n  if (typeof provided !== \"string\" || typeof expected !== \"string\") return false;\n  // An unset secret must never authorize a request, including an empty guess.\n  if (expected.length === 0) return false;\n\n  // Folding the lengths in rejects a wrong-length guess without an early return.\n  let mismatch = provided.length ^ expected.length;\n  const length = Math.max(provided.length, expected.length);\n  for (let index = 0; index < length; index += 1) {\n    const providedCode = index < provided.length ? provided.charCodeAt(index) : 0;\n    const expectedCode = index < expected.length ? expected.charCodeAt(index) : 0;\n    mismatch |= providedCode ^ expectedCode;\n  }\n\n  return mismatch === 0;\n}\n","/**\n * Environment access that works across the runtimes Farm targets.\n *\n * Serverless and edge runtimes (Cloudflare Workers in particular) expose\n * bindings on `globalThis.__env__` rather than `process.env`, so security\n * checks that read `process.env` directly see an empty value there and can\n * silently take an \"unconfigured\" code path in a deployed environment.\n */\nexport function getFarmRuntimeBindings(): Record<string, unknown> | undefined {\n  const runtimeBindings = (\n    globalThis as typeof globalThis & {\n      __env__?: Record<string, unknown>;\n    }\n  ).__env__;\n  return runtimeBindings && typeof runtimeBindings === \"object\" ? runtimeBindings : undefined;\n}\n\nexport function readFarmEnvironmentValue(name: string): string | undefined {\n  const runtimeValue = getFarmRuntimeBindings()?.[name];\n  if (typeof runtimeValue === \"string\") return runtimeValue;\n  return typeof process !== \"undefined\" ? process.env?.[name] : undefined;\n}\n\n/**\n * True when the process looks like a deployed runtime rather than local\n * development: either NODE_ENV is production, or runtime bindings are present\n * (a deployed worker where NODE_ENV is frequently unset).\n */\nexport function isFarmDeployedRuntime(): boolean {\n  if (getFarmRuntimeBindings()) return true;\n  return readFarmEnvironmentValue(\"NODE_ENV\") === \"production\";\n}\n","/**\n * Decode a percent-encoded path segment, falling back to the raw value.\n *\n * Request paths are not guaranteed to be validly percent-encoded, so\n * `decodeURIComponent` can throw on input that is still a legal URL: a\n * latin-1 escape such as `caf%E9` from an old link, or a truncated `%ZZ`\n * from a crawler. A malformed segment simply will not match a known route,\n * which is a 404, so it must not throw out of route matching.\n */\nexport function decodeRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n","import type { RouteSegment, ParsedRoute } from \"./types\";\nimport path from \"path\";\nimport {\n  assertBrowserStableRoutePath,\n  assertTerminalCatchAll,\n  assertUniqueRouteParameters,\n} from \"./routing/specificity\";\nimport { searchParamsToObject } from \"./search-params\";\nimport { decodeRouteSegment } from \"./utils/decode\";\n\nexport function parseRoutePath(filePath: string): ParsedRoute {\n  const segments: RouteSegment[] = [];\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  const pathParts = normalizedPath.split(\"/\").filter(Boolean);\n\n  const fileName = pathParts.pop() || \"\";\n  const fileType = getRouteType(fileName);\n  const routePath = `/${pathParts.join(\"/\")}`;\n  assertBrowserStableRoutePath(routePath);\n  assertTerminalCatchAll(routePath);\n  assertUniqueRouteParameters(routePath);\n\n  for (const part of pathParts) {\n    // Route groups like `(marketing)` organize files without adding URL\n    // segments. Mirrors isRouteGroup in router.ts for programmatic routes.\n    if (part.startsWith(\"(\") && part.endsWith(\")\")) continue;\n    if (part.startsWith(\"[\") && part.endsWith(\"]\")) {\n      let segment = part.slice(1, -1);\n      const isDynamic = true;\n      let isOptional = false;\n      let isCatchAll = false;\n\n      if (segment.startsWith(\"[\") && segment.endsWith(\"]\")) {\n        isOptional = true;\n        segment = segment.slice(1, -1);\n        if (segment.startsWith(\"...\")) {\n          segment = segment.slice(3);\n          isCatchAll = true;\n        }\n      } else if (segment.startsWith(\"...\")) {\n        segment = segment.slice(3);\n        isCatchAll = true;\n      }\n\n      segments.push({ segment, isDynamic, isOptional, isCatchAll });\n    } else {\n      segments.push({\n        segment: part,\n        isDynamic: false,\n        isOptional: false,\n        isCatchAll: false,\n      });\n    }\n  }\n\n  return {\n    segments,\n    filePath: normalizedPath,\n    type: fileType,\n  };\n}\n\nfunction getRouteType(fileName: string): ParsedRoute[\"type\"] {\n  const baseName = fileName.replace(/\\.(tsx?|jsx?|vue|svelte|mdx?|markdown)$/, \"\");\n\n  switch (baseName) {\n    case \"page\":\n      return \"page\";\n    case \"layout\":\n      return \"layout\";\n    case \"loading\":\n      return \"loading\";\n    case \"error\":\n      return \"error\";\n    case \"not-found\":\n      return \"not-found\";\n    default:\n      return \"page\";\n  }\n}\n\nexport function segmentsToPattern(segments: RouteSegment[]): string {\n  if (segments.length === 0) return \"/\";\n\n  return (\n    \"/\" +\n    segments\n      .map((segment) => {\n        if (!segment.isDynamic) return segment.segment;\n\n        if (segment.isCatchAll) {\n          return segment.isOptional ? `*${segment.segment}?` : `*${segment.segment}`;\n        }\n\n        return `:${segment.segment}`;\n      })\n      .join(\"/\")\n  );\n}\n\nexport function matchRoute(\n  url: string,\n  segments: RouteSegment[],\n): { params: Record<string, string>; matches: boolean } {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  const params: Record<string, string> = {};\n  if (segments.length === 0) {\n    return { params, matches: urlParts.length === 0 };\n  }\n\n  let urlIndex = 0;\n  let segmentIndex = 0;\n\n  while (segmentIndex < segments.length && urlIndex <= urlParts.length) {\n    const segment = segments[segmentIndex];\n\n    if (!segment.isDynamic) {\n      if (urlParts[urlIndex] !== segment.segment) {\n        return { params: {}, matches: false };\n      }\n      urlIndex++;\n      segmentIndex++;\n    } else if (segment.isCatchAll) {\n      const remainingParts = urlParts.slice(urlIndex);\n\n      if (remainingParts.length === 0 && !segment.isOptional) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = remainingParts.join(\"/\");\n      urlIndex = urlParts.length;\n      segmentIndex++;\n    } else {\n      if (urlIndex >= urlParts.length) {\n        return { params: {}, matches: false };\n      }\n\n      params[segment.segment] = urlParts[urlIndex];\n      urlIndex++;\n      segmentIndex++;\n    }\n  }\n\n  const matches = segmentIndex === segments.length && urlIndex === urlParts.length;\n\n  return { params, matches };\n}\n\n/** Match a route segment chain as an owner of the pathname or one of its descendants. */\nexport function matchRoutePrefix(url: string, segments: RouteSegment[]): boolean {\n  const urlParts = url.split(\"/\").filter(Boolean).map(decodeRouteSegment);\n  let urlIndex = 0;\n\n  for (const segment of segments) {\n    if (segment.isCatchAll) {\n      return segment.isOptional || urlIndex < urlParts.length;\n    }\n\n    const urlPart = urlParts[urlIndex];\n    if (urlPart === undefined) return false;\n    if (!segment.isDynamic && segment.segment !== urlPart) return false;\n    urlIndex++;\n  }\n\n  return true;\n}\n\nexport function resolveAppPath(root: string, ...paths: string[]): string {\n  return path.resolve(root, ...paths);\n}\n\n/**\n * Convert an absolute module path inside the project root to a root-relative\n * URL path with forward slashes (e.g. `/src/app/page.tsx`), for values the\n * client passes to dynamic `import()`. On Windows the naive root-prefix slice\n * yields `\\src\\app\\page.tsx`, which is not a valid module specifier. Returns\n * undefined for paths outside the root so callers keep their own fallbacks.\n */\nexport function toRootRelativeUrlPath(\n  absolutePath: string,\n  projectRoot: string,\n): string | undefined {\n  if (absolutePath === projectRoot) return \"\";\n  if (absolutePath.startsWith(`${projectRoot}/`) || absolutePath.startsWith(`${projectRoot}\\\\`)) {\n    return absolutePath.slice(projectRoot.length).replace(/\\\\/g, \"/\");\n  }\n  return undefined;\n}\n\n/**\n * Normalize a filesystem path to forward slashes. Node's fs accepts these on\n * every platform, and module ids handed to bundlers (e.g. Nitro handler and\n * task entries) must not contain backslashes.\n */\nexport function toPosixPath(filePath: string): string {\n  return filePath.replace(/\\\\/g, \"/\");\n}\n\nexport function toViteModuleId(filePath: string, root: string): string {\n  if (!path.isAbsolute(filePath)) return filePath;\n\n  const relativePath = path.relative(root, filePath);\n  if (relativePath && !relativePath.startsWith(\"..\") && !path.isAbsolute(relativePath)) {\n    return `/${relativePath.split(path.sep).join(\"/\")}`;\n  }\n\n  const normalizedPath = filePath.replace(/\\\\/g, \"/\");\n  return normalizedPath.startsWith(\"/\") ? `/@fs${normalizedPath}` : `/@fs/${normalizedPath}`;\n}\n\nexport async function fileExists(filePath: string): Promise<boolean> {\n  try {\n    const fs = await import(\"fs/promises\");\n    await fs.access(filePath);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport async function globFiles(pattern: string, cwd: string): Promise<string[]> {\n  const glob = await import(\"fast-glob\");\n  return glob.default(pattern, { cwd, absolute: false });\n}\n\nexport function parseSearchParams(\n  searchParams: URLSearchParams,\n): Record<string, string | string[]> {\n  return searchParamsToObject(searchParams) as Record<string, string | string[]>;\n}\n\nexport const logger = {\n  info: (message: string) => console.log(`[info] ${message}`),\n  success: (message: string) => console.log(`[success] ${message}`),\n  warn: (message: string) => console.warn(`⚠️  ${message}`),\n  error: (message: string) => console.error(`❌ ${message}`),\n  ready: (message: string) => console.log(`${message}`),\n  event: (message: string) => console.log(`  ${message}`),\n};\n","import { localizeFarmHref, resolveFarmLocalePath } from \"../i18n/routing\";\nimport type { ResolvedFarmI18nConfig } from \"../i18n/types\";\nimport { assertBrowserStableRoutePath } from \"../routing/specificity\";\n\ntype ConfigRoutePatternToken =\n  | { kind: \"param\"; name: string; captureIndex: number; catchAll: boolean }\n  | { kind: \"wildcard\"; captureIndex: number };\n\nexport interface CompiledConfigRoutePattern {\n  regex: RegExp;\n  tokens: ConfigRoutePatternToken[];\n}\n\nexport function validateConfigRouteSource(source: string, field = \"Config route source\"): string {\n  if (typeof source !== \"string\" || source.length === 0) {\n    throw new TypeError(`${field} must be a non-empty pathname pattern.`);\n  }\n  if (source.trim() !== source) {\n    throw new Error(`${field} cannot contain leading or trailing whitespace.`);\n  }\n  if (!source.startsWith(\"/\")) {\n    throw new Error(`${field} must start with \"/\".`);\n  }\n  if (source.includes(\"?\") || source.includes(\"#\")) {\n    throw new Error(`${field} must be a pathname without a query string or hash.`);\n  }\n  if (\n    source.includes(\"\\\\\") ||\n    Array.from(source).some((character) => {\n      const code = character.charCodeAt(0);\n      return code <= 31 || (code >= 127 && code <= 159);\n    })\n  ) {\n    throw new Error(`${field} cannot contain backslashes or control characters.`);\n  }\n  assertBrowserStableRoutePath(source);\n  return source;\n}\n\nexport function resolveConfigRoutePathname(\n  pathname: string,\n  i18n?: ResolvedFarmI18nConfig,\n): { pathname: string; locale?: string } {\n  if (!i18n?.enabled) return { pathname: normalizeConfigRoutePathname(pathname) };\n  const match = resolveFarmLocalePath(pathname, i18n);\n  return { pathname: normalizeConfigRoutePathname(match.pathname), locale: match.locale };\n}\n\n/**\n * Drop a trailing slash before matching, mirroring `normalizeRuntimePath` in\n * the generated production matcher. Without this a request for `/old/` misses\n * a `/old` rule in dev while matching it in a built app.\n */\nfunction normalizeConfigRoutePathname(pathname: string): string {\n  if (!pathname || pathname === \"/\") return \"/\";\n  return pathname.endsWith(\"/\") ? pathname.replace(/\\/+$/, \"\") || \"/\" : pathname;\n}\n\nexport function localizeConfigRouteDestination(\n  destination: string,\n  locale: string | undefined,\n  i18n?: ResolvedFarmI18nConfig,\n): string {\n  return locale && i18n?.enabled ? localizeFarmHref(destination, locale, i18n) : destination;\n}\n\n/**\n * Append a catch-all capture, absorbing the separator that precedes it.\n *\n * The production matcher works on split segments and lets a non-terminal\n * catch-all consume zero of them (`minConsume = 0`), so `/x/*` + `/y` matches\n * `/x/y` and `/files/:path*` matches `/files`. Emitting a bare `(.*)` after a\n * literal `/` instead demands at least that separator, so the same rule was\n * inert in dev. Folding the slash into the optional group is how path-to-regexp\n * expresses the same thing, and it keeps one capture group so capture indexes\n * are unchanged (a non-participating group reads back as \"\").\n */\nfunction appendCatchAll(pattern: string): string {\n  return pattern.endsWith(\"/\") ? `${pattern.slice(0, -1)}(?:/(.*))?` : `${pattern}(.*)`;\n}\n\nfunction escapeRegexCharacter(character: string): string {\n  return /[\\\\^$.*+?()[\\]{}|]/.test(character) ? `\\\\${character}` : character;\n}\n\nexport function compileConfigRoutePattern(source: string): CompiledConfigRoutePattern {\n  validateConfigRouteSource(source);\n  const tokens: ConfigRoutePatternToken[] = [];\n  let pattern = \"\";\n  let captureIndex = 1;\n\n  for (let index = 0; index < source.length; ) {\n    const rest = source.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      tokens.push({\n        kind: \"param\",\n        name: parameter[1],\n        captureIndex,\n        catchAll: parameter[2] === \"*\",\n      });\n      pattern = parameter[2] ? appendCatchAll(pattern) : `${pattern}([^/]+)`;\n      captureIndex += 1;\n      index += parameter[0].length;\n      continue;\n    }\n\n    if (source[index] === \"*\") {\n      tokens.push({ kind: \"wildcard\", captureIndex });\n      pattern = appendCatchAll(pattern);\n      captureIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    pattern += escapeRegexCharacter(source[index]);\n    index += 1;\n  }\n\n  return { regex: new RegExp(`^${pattern}$`), tokens };\n}\n\nexport function interpolateConfigRouteDestination(\n  destination: string,\n  match: RegExpMatchArray,\n  tokens: readonly ConfigRoutePatternToken[],\n): string {\n  const namedCaptures = new Map<string, string>();\n  const wildcardCaptures: string[] = [];\n  const captures = new Map<number, string>();\n\n  for (const token of tokens) {\n    const value = normalizeConfigRouteCapture(\n      match[token.captureIndex] || \"\",\n      token.kind === \"wildcard\" || token.catchAll,\n    );\n    captures.set(token.captureIndex, value);\n    if (token.kind === \"param\") {\n      namedCaptures.set(token.name, value);\n    } else {\n      wildcardCaptures.push(value);\n    }\n  }\n\n  let result = \"\";\n  let wildcardIndex = 0;\n  for (let index = 0; index < destination.length; ) {\n    const rest = destination.slice(index);\n    const parameter = rest.match(/^:([A-Za-z0-9_]+)(\\*)?/);\n    if (parameter) {\n      const value = namedCaptures.get(parameter[1]);\n      result += value === undefined ? parameter[0] : value;\n      index += parameter[0].length;\n      continue;\n    }\n\n    const capture = rest.match(/^\\$(\\d+)/);\n    if (capture) {\n      result += captures.get(Number(capture[1])) ?? \"\";\n      index += capture[0].length;\n      continue;\n    }\n\n    if (destination[index] === \"*\") {\n      result += wildcardCaptures[wildcardIndex] || \"\";\n      wildcardIndex += 1;\n      index += 1;\n      continue;\n    }\n\n    result += destination[index];\n    index += 1;\n  }\n\n  return result;\n}\n\nfunction normalizeConfigRouteCapture(value: string, catchAll: boolean): string {\n  const segments = catchAll ? value.split(\"/\").filter(Boolean) : [value];\n  return segments\n    .map((segment) => encodeConfigRouteSegment(decodeConfigRouteSegment(segment)))\n    .join(\"/\");\n}\n\nfunction decodeConfigRouteSegment(segment: string): string {\n  try {\n    return decodeURIComponent(segment);\n  } catch {\n    return segment;\n  }\n}\n\nfunction encodeConfigRouteSegment(segment: string): string {\n  return encodeURIComponent(segment).replace(\n    /[!'()*]/g,\n    (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`,\n  );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BO,IAAM,6BAAN,MAAM,mCAAkC,UAAU;AAAA,EACvD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AALyD;AAAlD,IAAM,4BAAN;AA0CA,SAAS,6BAA6B,SAAuB;AAClE,MAAI,QAAQ,SAAS,IAAI,KAAK,oBAAoB,OAAO,GAAG;AAC1D,UAAM,IAAI;AAAA,MACR,eAAe,OAAO;AAAA,IACxB;AAAA,EACF;AAEA,aAAW,WAAW,QAAQ,MAAM,GAAG,EAAE,OAAO,OAAO,GAAG;AACxD,QACG,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,KAC/C,QAAQ,WAAW,GAAG,KAAK,QAAQ,SAAS,GAAG,GAChD;AACA;AAAA,IACF;AAEA,QAAI,UAAU;AACd,QAAI;AACF,gBAAU,mBAAmB,OAA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