@boon4681/giri 0.0.3-alpha-2 → 0.0.3-alpha-3

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/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/loader/_es5.ts","../src/generator/schema/program.ts","../src/generator/schema/json-schema.ts","../src/generator/schema/responses.ts","../src/generator/schema/index.ts","../src/cli.ts","../src/app.ts","../src/loader/loader.ts","../src/config/schema.ts","../src/routes.ts","../src/types.ts","../src/validation.ts","../src/generator/sync.ts","../src/generator/app-types.ts","../src/generator/util.ts","../src/generator/manifest.ts","../src/generator/openapi.ts","../src/generator/param-types.ts","../src/generator/route-meta.ts","../src/generator/inputs.ts","../src/generator/route-types.ts","../src/generator/tsconfig.ts","../src/generator/cache.ts","../src/generator/watch.ts","../src/loader/import-graph.ts","../src/loader/module-loader.ts","../src/lifecycle.ts","../src/logger.ts"],"sourcesContent":["const _ = '';\r\nexport default _;","import ts from 'typescript';\nimport type { GiriPaths } from '../../types';\n\r\nconst DEFAULT_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2022,\r\n module: ts.ModuleKind.NodeNext,\r\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\r\n strict: true,\r\n skipLibCheck: true,\r\n noEmit: true,\r\n};\n\n/**\n * Build a `ts.Program` rooted at the given route files, using the project's own\n * `tsconfig.json` (so `paths`, `rootDirs`, and the user's TS settings apply). The\n * walker reads types from this program; nothing is emitted.\n */\nexport function createSchemaProgram(\n paths: GiriPaths,\n routeFiles: string[],\n): ts.Program {\n let options: ts.CompilerOptions = { ...DEFAULT_OPTIONS };\n\n const configPath = ts.findConfigFile(paths.cwd, ts.sys.fileExists, 'tsconfig.json');\n if (configPath) {\r\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, {\r\n ...ts.sys,\r\n onUnRecoverableConfigFileDiagnostic: () => {},\r\n });\r\n if (parsed) {\n options = { ...parsed.options, noEmit: true };\n }\n }\n\n return ts.createProgram(routeFiles, options);\n}\n","import ts from 'typescript';\r\n\r\nexport type JSONSchema = Record<string, unknown>;\r\n\r\nexport interface WalkContext {\r\n checker: ts.TypeChecker;\r\n /** Node used to resolve property types in context. */\r\n location: ts.Node;\r\n /** Shared `$defs` bucket for recursive types. */\r\n defs: Record<string, JSONSchema>;\r\n /** Type ids currently being walked, mapped to their `$defs` name (cycle guard). */\r\n inProgress: Map<number, string>;\r\n /** `$defs` names that were referenced via `$ref` (i.e. proved recursive). */\r\n usedDefs: Set<string>;\r\n /** Non-fatal notes (e.g. bigint serialization caveats). */\r\n warnings: string[];\r\n}\r\n\r\nexport function createWalkContext(checker: ts.TypeChecker, location: ts.Node): WalkContext {\r\n return {\r\n checker,\r\n location,\r\n defs: {},\r\n inProgress: new Map(),\r\n usedDefs: new Set(),\r\n warnings: [],\r\n };\r\n}\r\n\r\nfunction typeId(type: ts.Type): number {\r\n return (type as ts.Type & { id: number }).id;\r\n}\r\n\r\nfunction intrinsicName(type: ts.Type): string | undefined {\r\n return (type as ts.Type & { intrinsicName?: string }).intrinsicName;\r\n}\r\n\r\nfunction isDateType(type: ts.Type): boolean {\r\n const symbol = type.getSymbol() ?? type.aliasSymbol;\r\n return symbol?.getName() === 'Date';\r\n}\r\n\r\nfunction literalValuesOf(types: ts.Type[]): unknown[] | undefined {\r\n const values: unknown[] = [];\r\n for (const member of types) {\r\n if (member.isStringLiteral() || member.isNumberLiteral()) {\r\n values.push(member.value);\r\n } else if (member.flags & ts.TypeFlags.BooleanLiteral) {\r\n values.push(intrinsicName(member) === 'true');\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n return values;\r\n}\r\n\r\nfunction walkUnion(type: ts.UnionType, ctx: WalkContext): JSONSchema {\r\n const flag = (ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.Never);\r\n const members = type.types.filter((member) => !(member.flags & flag));\r\n\r\n if (members.length === 1) {\r\n return walkType(members[0], ctx);\r\n }\r\n\r\n const enumValues = literalValuesOf(members);\r\n if (enumValues) {\r\n return { enum: enumValues };\r\n }\r\n\r\n return { anyOf: members.map((member) => walkType(member, ctx)) };\r\n}\r\n\r\nfunction buildObjectSchema(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const { checker } = ctx;\r\n\r\n const indexInfo =\r\n checker.getIndexInfoOfType(type, ts.IndexKind.String) ??\r\n checker.getIndexInfoOfType(type, ts.IndexKind.Number);\r\n\r\n const properties: Record<string, JSONSchema> = {};\r\n const required: string[] = [];\r\n\r\n for (const symbol of checker.getPropertiesOfType(type)) {\r\n const name = symbol.getName();\r\n const propType = checker.getTypeOfSymbolAtLocation(symbol, ctx.location);\r\n const optional =\r\n Boolean(symbol.getFlags() & ts.SymbolFlags.Optional) ||\r\n Boolean(propType.flags & ts.TypeFlags.Union &&\r\n (propType as ts.UnionType).types.some((t) => t.flags & ts.TypeFlags.Undefined));\r\n\r\n properties[name] = walkType(propType, ctx);\r\n if (!optional) {\r\n required.push(name);\r\n }\r\n }\r\n\r\n const schema: JSONSchema = { type: 'object' };\r\n if (Object.keys(properties).length > 0) {\r\n schema.properties = properties;\r\n }\r\n if (required.length > 0) {\r\n schema.required = required;\r\n }\r\n if (indexInfo) {\r\n schema.additionalProperties = walkType(indexInfo.type, ctx);\r\n } else if (Object.keys(properties).length > 0) {\r\n schema.additionalProperties = false;\r\n }\r\n return schema;\r\n}\r\n\r\nfunction defName(type: ts.Type): string {\r\n const symbol = type.getSymbol() ?? type.aliasSymbol;\r\n const name = symbol?.getName();\r\n if (name && name !== '__type' && name !== '__object') {\r\n return name;\r\n }\r\n return `Anonymous${typeId(type)}`;\r\n}\r\n\r\nfunction walkObject(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const { checker } = ctx;\r\n\r\n if (isDateType(type)) {\r\n return { type: 'string', format: 'date-time' };\r\n }\r\n if (checker.isArrayType(type)) {\r\n const [element] = checker.getTypeArguments(type as ts.TypeReference);\r\n return { type: 'array', items: element ? walkType(element, ctx) : {} };\r\n }\r\n if (checker.isTupleType(type)) {\r\n const elements = checker.getTypeArguments(type as ts.TypeReference);\r\n return { type: 'array', items: elements.map((element) => walkType(element, ctx)) };\r\n }\r\n\r\n const id = typeId(type);\r\n const existing = ctx.inProgress.get(id);\r\n if (existing) {\r\n ctx.usedDefs.add(existing);\r\n return { $ref: `#/$defs/${existing}` };\r\n }\r\n\r\n const name = defName(type);\r\n ctx.inProgress.set(id, name);\r\n const schema = buildObjectSchema(type, ctx);\r\n ctx.inProgress.delete(id);\r\n\r\n if (ctx.usedDefs.has(name)) {\r\n ctx.defs[name] = schema;\r\n return { $ref: `#/$defs/${name}` };\r\n }\r\n return schema;\r\n}\r\n\r\n/** Translate a TypeScript type into the JSON Schema that `JSON.stringify` would produce. */\r\nexport function walkType(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const flags = type.flags;\r\n\r\n if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {\r\n return {};\r\n }\r\n if (flags & ts.TypeFlags.Null) {\r\n return { type: 'null' };\r\n }\r\n if (flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) {\r\n return {};\r\n }\r\n if (flags & (ts.TypeFlags.BigInt | ts.TypeFlags.BigIntLiteral)) {\r\n ctx.warnings.push('bigint is not JSON-serializable (JSON.stringify throws); documented as string.');\r\n return { type: 'string' };\r\n }\r\n if (type.isStringLiteral()) {\r\n return { type: 'string', const: type.value };\r\n }\r\n if (type.isNumberLiteral()) {\r\n return { type: 'number', const: type.value };\r\n }\r\n if (flags & ts.TypeFlags.BooleanLiteral) {\r\n return { type: 'boolean', const: intrinsicName(type) === 'true' };\r\n }\r\n if (flags & ts.TypeFlags.String) {\r\n return { type: 'string' };\r\n }\r\n if (flags & ts.TypeFlags.Number) {\r\n return { type: 'number' };\r\n }\r\n if (flags & ts.TypeFlags.Boolean) {\r\n return { type: 'boolean' };\r\n }\r\n if (type.isUnion()) {\r\n return walkUnion(type, ctx);\r\n }\r\n if (flags & ts.TypeFlags.Object || type.isIntersection()) {\r\n return walkObject(type, ctx);\r\n }\r\n\r\n return {};\r\n}\r\n","import ts from 'typescript';\nimport { createWalkContext, walkType, type JSONSchema } from './json-schema';\n\nexport interface ResponseSchema {\n /** Numeric HTTP status, or 'default' when the handler returns a non-literal status. */\n status: number | 'default';\n format: 'json' | 'text';\n schema: JSONSchema;\n}\n\nexport interface RouteResponses {\n responses: ResponseSchema[];\n /** Statuses/returns the walker could not turn into a schema (e.g. a raw `Response`). */\n opaque: boolean;\n warnings: string[];\n $defs: Record<string, JSONSchema>;\n}\n\nfunction findHandleFunction(\n source: ts.SourceFile,\n): ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | undefined {\n let found: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | undefined;\n\n const isExported = (node: ts.Node): boolean =>\n ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n\n for (const statement of source.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === 'handle' && isExported(statement)) {\n found = statement;\n }\n if (ts.isVariableStatement(statement) && isExported(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (\n ts.isIdentifier(declaration.name) &&\n declaration.name.text === 'handle' &&\n declaration.initializer &&\n (ts.isArrowFunction(declaration.initializer) ||\n ts.isFunctionExpression(declaration.initializer))\n ) {\n found = declaration.initializer;\n }\n }\n }\n }\n\n return found;\n}\n\nfunction collectReturnExpressions(\n fn: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration,\n): ts.Expression[] {\n if (ts.isArrowFunction(fn) && !ts.isBlock(fn.body)) {\n return [fn.body];\n }\n if (!fn.body) {\n return [];\n }\n\n const expressions: ts.Expression[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) {\n return;\n }\n if (ts.isReturnStatement(node) && node.expression) {\n expressions.push(node.expression);\n }\n ts.forEachChild(node, visit);\n };\n ts.forEachChild(fn.body, visit);\n return expressions;\n}\n\ninterface ResponseHit {\n status: number | 'default';\n format: 'json' | 'text';\n data: ts.Type;\n}\n\nfunction propertyType(\n checker: ts.TypeChecker,\n type: ts.Type,\n name: string,\n location: ts.Node,\n): ts.Type | undefined {\n const symbol = checker.getPropertyOfType(type, name);\n return symbol ? checker.getTypeOfSymbolAtLocation(symbol, location) : undefined;\n}\n\nfunction isTypedResponse(checker: ts.TypeChecker, type: ts.Type): boolean {\n return Boolean(\n checker.getPropertyOfType(type, 'data') &&\n checker.getPropertyOfType(type, 'status') &&\n checker.getPropertyOfType(type, 'format'),\n );\n}\n\nfunction firstParameterName(\n fn: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration,\n): string | undefined {\n const [first] = fn.parameters;\n return first && ts.isIdentifier(first.name) ? first.name.text : undefined;\n}\n\n/**\n * Read a `c.json(data, status?)` / `c.text(data, status?)` call directly. Reading the\n * status from the argument (default 200) sidesteps contextual typing: a `: Handle`\n * annotation otherwise widens an omitted status from its `= 200` default down to\n * `StatusCode`. Data still comes from the argument's own type.\n */\nfunction readFromCall(\n checker: ts.TypeChecker,\n expression: ts.Expression,\n contextName: string | undefined,\n): ResponseHit | undefined {\n if (!ts.isCallExpression(expression) || !ts.isPropertyAccessExpression(expression.expression)) {\n return undefined;\n }\n const method = expression.expression.name.text;\n if (method !== 'json' && method !== 'text') {\n return undefined;\n }\n const target = expression.expression.expression;\n const directContextCall = contextName && ts.isIdentifier(target) && target.text === contextName;\n if (!directContextCall && !isTypedResponse(checker, checker.getTypeAtLocation(expression))) {\n return undefined;\n }\n\n const [dataArg, statusArg] = expression.arguments;\n if (!dataArg) {\n return undefined;\n }\n\n let status: number | 'default' = 200;\n if (statusArg) {\n const statusType = checker.getTypeAtLocation(statusArg);\n status = statusType.isNumberLiteral() ? statusType.value : 'default';\n }\n\n return { status, format: method === 'text' ? 'text' : 'json', data: checker.getTypeAtLocation(dataArg) };\n}\n\n/** Fallback for non-`c.json` returns: read `{ data, status, format }` off the type itself. */\nfunction readFromType(checker: ts.TypeChecker, type: ts.Type, location: ts.Node): ResponseHit | undefined {\n const dataType = propertyType(checker, type, 'data', location);\n const statusType = propertyType(checker, type, 'status', location);\n const formatType = propertyType(checker, type, 'format', location);\n if (!dataType || !statusType || !formatType) {\n return undefined;\n }\n\n const status = statusType.isNumberLiteral() ? statusType.value : 'default';\n const format = formatType.isStringLiteral() && formatType.value === 'text' ? 'text' : 'json';\n return { status, format, data: dataType };\n}\n\nfunction constituents(type: ts.Type): ts.Type[] {\n return type.isUnion() ? type.types : [type];\n}\n\n/**\n * Extract per-status response schemas for a route's `handle` export by typing each of\n * its return expressions and unwrapping giri's `TypedResponse<data, status, format>`.\n */\nexport function extractRouteResponses(program: ts.Program, file: string): RouteResponses {\n const result: RouteResponses = { responses: [], opaque: false, warnings: [], $defs: {} };\n const source = program.getSourceFile(file);\n if (!source) {\n return result;\n }\n\n const checker = program.getTypeChecker();\n const fn = findHandleFunction(source);\n if (!fn) {\n return result;\n }\n\n const ctx = createWalkContext(checker, fn);\n const contextName = firstParameterName(fn);\n const byStatus = new Map<number | 'default', { format: 'json' | 'text'; schemas: JSONSchema[] }>();\n\n const record = (hit: ResponseHit): void => {\n const schema = walkType(hit.data, ctx);\n const bucket = byStatus.get(hit.status) ?? { format: hit.format, schemas: [] };\n bucket.schemas.push(schema);\n byStatus.set(hit.status, bucket);\n };\n\n for (const expression of collectReturnExpressions(fn)) {\n const fromCall = readFromCall(checker, expression, contextName);\n if (fromCall) {\n record(fromCall);\n continue;\n }\n\n let matched = false;\n for (const member of constituents(checker.getTypeAtLocation(expression))) {\n const hit = readFromType(checker, member, expression);\n if (hit) {\n record(hit);\n matched = true;\n }\n }\n if (!matched) {\n result.opaque = true;\n }\n }\n\n for (const [status, { format, schemas }] of byStatus) {\n const schema = schemas.length === 1 ? schemas[0] : { anyOf: schemas };\n result.responses.push({ status, format, schema });\n }\n result.responses.sort((a, b) => Number(a.status) - Number(b.status));\n result.warnings = ctx.warnings;\n result.$defs = ctx.defs;\n return result;\n}\n","export { createSchemaProgram } from './program';\nexport { extractRouteResponses } from './responses';\nexport type { ResponseSchema, RouteResponses } from './responses';\nexport { walkType, createWalkContext } from './json-schema';\r\nexport type { JSONSchema, WalkContext } from './json-schema';\r\n","#!/usr/bin/env node\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path';\nimport * as prompts from '@clack/prompts';\nimport { buildGiriApp, registerAliasResolver } from './app';\nimport { findConfigPath, load, safeRegister } from './loader/loader';\nimport { createWatchUpdater, syncProject } from './generator';\nimport { loadLifecycle, runInit } from './lifecycle';\nimport { color, formatError, log, muted } from './logger';\nimport type { Services, GiriConfig, GiriFetchHandler } from './types';\n\ninterface ParsedFlags {\n port?: number;\n hostname?: string;\n watch: boolean;\n}\n\ntype PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\ninterface AdapterChoice {\n value: string;\n label: string;\n hint: string;\n available: boolean;\n /** Import line added to `giri.config.ts`. */\n importLine: string;\n /** The adapter expression placed in `defineConfig({ adapter: … })`. */\n expr: string;\n /** Runtime deps this backend needs, installed alongside the framework. */\n deps: string[];\n}\n\nconst ADAPTERS: AdapterChoice[] = [\n {\n value: 'hono',\n label: 'Hono',\n hint: 'recommended, ships today',\n available: true,\n importLine: 'import { hono } from \"@boon4681/giri/adapters/hono\";',\n expr: 'hono()',\n deps: ['hono', '@hono/node-server'],\n }\n];\n\ninterface InitFlags {\n adapter?: string;\n packageManager?: PackageManager;\n /** undefined = ask; true/false = forced by --install / --no-install. */\n install?: boolean;\n /** Non-interactive: take defaults (Hono, detected PM, install). */\n yes: boolean;\n}\n\nfunction help(): void {\n console.log(`giri\n\nUsage:\n giri init [--adapter hono] [--pm npm|yarn|pnpm|bun] [--no-install] [-y]\n giri sync\n giri serve [--port 3000] [--host 127.0.0.1] [--no-watch]\n giri build\n`);\n}\n\nfunction parseInitFlags(args: string[]): InitFlags {\n const flags: InitFlags = { yes: false };\n const managers: PackageManager[] = ['npm', 'yarn', 'pnpm', 'bun'];\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--adapter' || arg === '-a') {\n flags.adapter = args[++index];\n } else if (arg === '--pm' || arg === '--package-manager') {\n const value = args[++index];\n if (!managers.includes(value as PackageManager)) {\n throw new Error(`Unknown package manager: ${value} (expected ${managers.join(', ')})`);\n }\n flags.packageManager = value as PackageManager;\n } else if (arg === '--install') {\n flags.install = true;\n } else if (arg === '--no-install') {\n flags.install = false;\n } else if (arg === '-y' || arg === '--yes') {\n flags.yes = true;\n } else {\n throw new Error(`Unknown option: ${arg}`);\n }\n }\n\n return flags;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const flags: ParsedFlags = { watch: true };\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--port' || arg === '-p') {\n flags.port = Number(args[++index]);\n } else if (arg === '--host' || arg === '--hostname') {\n flags.hostname = args[++index];\n } else if (arg === '--no-watch') {\n flags.watch = false;\n } else {\n throw new Error(`Unknown option: ${arg}`);\n }\n }\n\n return flags;\n}\n\nasync function ensureGitignore(cwd: string): Promise<void> {\n const file = join(cwd, '.gitignore');\n const entry = '.giri';\n if (!existsSync(file)) {\n await writeFile(file, `${entry}\\n`);\n return;\n }\n\n const content = await readFile(file, 'utf8');\n if (!content.split(/\\r?\\n/).includes(entry)) {\n await appendFile(file, `${content.endsWith('\\n') ? '' : '\\n'}${entry}\\n`);\n }\n}\n\nasync function ensureTsConfig(cwd: string): Promise<void> {\n const file = join(cwd, 'tsconfig.json');\n if (existsSync(file)) {\n return;\n }\n\n await writeFile(\n file,\n `${JSON.stringify(\n {\n extends: './.giri/tsconfig.json',\n compilerOptions: {\n target: 'ES2022',\n lib: ['ES2022', 'DOM'],\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n esModuleInterop: true,\n forceConsistentCasingInFileNames: true,\n skipLibCheck: true,\n types: ['node'],\n },\n },\n null,\n 2,\n )}\\n`,\n );\n}\n\nasync function missingDeps(cwd: string, candidates: string[]): Promise<string[]> {\n let pkg: Record<string, unknown> = {};\n try {\n pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) as Record<string, unknown>;\n } catch { }\n\n const present = new Set<string>();\n for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\n const map = pkg[field];\n if (map && typeof map === 'object') {\n for (const name of Object.keys(map as Record<string, unknown>)) {\n present.add(name);\n }\n }\n }\n\n return candidates.filter((name) => !present.has(name));\n}\n\n/** Guess the package manager from the user agent npm/yarn/pnpm/bun set when invoking the CLI. */\nfunction detectPackageManager(): PackageManager {\n const ua = process.env.npm_config_user_agent ?? '';\n if (ua.startsWith('yarn')) return 'yarn';\n if (ua.startsWith('pnpm')) return 'pnpm';\n if (ua.startsWith('bun')) return 'bun';\n return 'npm';\n}\n\nfunction installArgs(pm: PackageManager, deps: string[], dev: boolean): string[] {\n if (pm === 'npm') return ['install', ...(dev ? ['--save-dev'] : []), ...deps];\n if (pm === 'bun') return ['add', ...(dev ? ['--dev'] : []), ...deps];\n return ['add', ...(dev ? ['--dev'] : []), ...deps]; // yarn, pnpm\n}\n\n/** Run a package-manager command, streaming its output. On Windows the binaries are `.cmd` shims. */\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) {\n resolvePromise();\n } else {\n reject(new Error(`${cmd} ${args.join(' ')} exited with code ${code}`));\n }\n });\n });\n}\n\nfunction configSource(adapter: AdapterChoice): string {\n return [\n 'import { defineConfig } from \"@boon4681/giri\";',\n adapter.importLine,\n '',\n 'export default defineConfig({',\n ` adapter: ${adapter.expr},`,\n '});',\n '',\n ].join('\\n');\n}\n\n/** Prompt for the adapter (or take the default in non-interactive mode). Null = the user cancelled. */\nasync function selectAdapter(interactive: boolean): Promise<AdapterChoice | null> {\n if (!interactive || ADAPTERS.length === 1) {\n return ADAPTERS[0];\n }\n\n const picked = await prompts.select({\n message: 'Which backend adapter?',\n initialValue: 'hono',\n options: ADAPTERS.map((adapter) => ({\n value: adapter.value,\n label: adapter.label,\n hint: adapter.hint,\n })),\n });\n if (prompts.isCancel(picked)) {\n return null;\n }\n return ADAPTERS.find((adapter) => adapter.value === picked) ?? null;\n}\n\nasync function initProject(cwd: string, flags: InitFlags): Promise<void> {\n if (!existsSync(join(cwd, 'package.json'))) {\n throw new Error(\n 'No package.json found. Run `giri init` inside an existing project - set one up first ' +\n '(e.g. `npm init -y` and install typescript), then re-run.',\n );\n }\n\n const interactive = Boolean(process.stdout.isTTY) && !flags.yes;\n prompts.intro('giri init');\n\n let adapter: AdapterChoice | null;\n if (flags.adapter) {\n adapter = ADAPTERS.find((choice) => choice.value === flags.adapter) ?? null;\n if (!adapter) {\n prompts.cancel(`Unknown adapter \"${flags.adapter}\". Available: ${ADAPTERS.map((a) => a.value).join(', ')}.`);\n return;\n }\n } else {\n adapter = await selectAdapter(interactive);\n if (!adapter) {\n prompts.cancel('Cancelled.');\n return;\n }\n }\n\n if (!adapter.available) {\n prompts.cancel(`The ${adapter.label} adapter isn't available yet - only Hono ships today.`);\n return;\n }\n\n const configPath = join(cwd, 'giri.config.ts');\n if (!existsSync(configPath)) {\n await writeFile(configPath, configSource(adapter));\n }\n\n const routePath = join(cwd, 'src', 'routes', '+get.ts');\n if (!existsSync(routePath)) {\n await mkdir(join(cwd, 'src', 'routes'), { recursive: true });\n await writeFile(\n routePath,\n [\n 'import type { Handle } from \"@boon4681/giri\";',\n '',\n 'export const handle: Handle = (c) => c.json({ ok: true });',\n '',\n ].join('\\n'),\n );\n }\n\n await ensureGitignore(cwd);\n await ensureTsConfig(cwd);\n prompts.log.success(`scaffolded a ${adapter.label} project`);\n\n const pm = flags.packageManager ?? detectPackageManager();\n const deps = await missingDeps(cwd, ['@boon4681/giri', ...adapter.deps, 'zod']);\n const devDeps = await missingDeps(cwd, ['typescript', '@types/node']);\n\n if (deps.length === 0 && devDeps.length === 0) {\n prompts.outro('All dependencies already present. Run `giri serve` to start the dev server.');\n return;\n }\n\n const planLines = [\n ...(deps.length ? [` ${pm} ${installArgs(pm, deps, false).join(' ')}`] : []),\n ...(devDeps.length ? [` ${pm} ${installArgs(pm, devDeps, true).join(' ')}`] : []),\n ];\n\n let install = flags.install;\n if (install === undefined) {\n if (!interactive) {\n install = flags.yes;\n } else {\n const answer = await prompts.confirm({ message: `Install dependencies with ${pm}?` });\n if (prompts.isCancel(answer)) {\n prompts.cancel('Cancelled - files written, skipped install.');\n return;\n }\n install = answer;\n }\n }\n\n if (install) {\n try {\n if (deps.length) {\n prompts.log.step(`Installing ${deps.join(', ')}`);\n await runCommand(pm, installArgs(pm, deps, false), cwd);\n }\n if (devDeps.length) {\n prompts.log.step(`Installing dev deps ${devDeps.join(', ')}`);\n await runCommand(pm, installArgs(pm, devDeps, true), cwd);\n }\n } catch (error) {\n prompts.log.error(error instanceof Error ? error.message : String(error));\n prompts.outro(`Install failed - run these yourself, then \\`giri serve\\`:\\n${planLines.join('\\n')}`);\n return;\n }\n prompts.outro('Ready. Run `giri serve` to start the dev server.');\n return;\n }\n\n prompts.outro(`Next:\\n${planLines.join('\\n')}\\n giri serve`);\n}\n\nfunction displayHost(address: string): string {\n if (!address || address === '::' || address === '0.0.0.0') {\n return 'localhost';\n }\n return address.includes(':') ? `[${address}]` : address;\n}\n\nasync function serveProject(config: GiriConfig, flags: ParsedFlags): Promise<void> {\n Error.stackTraceLimit = 30;\n\n const { watch } = await import('chokidar');\n let stop: (() => Promise<void>) | undefined;\n const boot = async (cfg: GiriConfig): Promise<void> => {\n const closers: Array<() => void | Promise<void>> = [];\n closers.push(registerAliasResolver(cfg.alias, resolve(process.cwd())));\n\n const lifecycle = await loadLifecycle();\n // Project sync and lifecycle initialization are independent. Running them together hides\n // schema-generation time behind database connections/migrations instead of making startup\n // pay both costs serially.\n const sync = syncProject(cfg).then((initial) => {\n log.success(\n `synced ${initial.routes.length} route${initial.routes.length === 1 ? '' : 's'} ${muted(`at ${initial.paths.outDir}`)}`,\n 'sync',\n );\n return initial;\n });\n const [initial, services]: [Awaited<ReturnType<typeof syncProject>>, Services] =\n await Promise.all([sync, runInit(lifecycle)]);\n\n const loader = await safeRegister();\n closers.push(loader.unregister);\n let current = await buildGiriApp(cfg, {\n services,\n lazy: true,\n loaderRegistered: true,\n aliasResolverRegistered: true,\n });\n\n const port = flags.port ?? cfg.server?.port ?? 3000;\n const hostname = flags.hostname ?? cfg.server?.hostname;\n\n if (flags.watch) {\n // Watch the whole `src/`, not just `src/routes`: a route's imports (auth.ts, db.ts, …)\n // and `main.ts` live here, and editing them must rebuild too.\n const srcDir = resolve(current.paths.routesDir, '..');\n if (existsSync(srcDir)) {\n let timer: NodeJS.Timeout | undefined;\n let syncing = false;\n const changed = new Set<string>();\n const updater = createWatchUpdater(cfg, initial);\n const hmrCount = new Map<string, number>();\n const bump = (key: string): number => {\n const next = (hmrCount.get(key) ?? 0) + 1;\n hmrCount.set(key, next);\n return next;\n };\n\n // Drain queued changes, applying each through the incremental updater (it falls back\n // to a full sync for structural changes). Serialized so two drains never overlap;\n // changes arriving mid-drain are picked up by the loop or the trailing re-check.\n const flush = async (): Promise<void> => {\n if (syncing) {\n return;\n }\n syncing = true;\n try {\n while (changed.size > 0) {\n const batch = [...changed];\n changed.clear();\n let rebuild = false;\n let fullSync = false;\n const dirtySet = new Set<string>();\n for (const name of batch) {\n const outcome = await updater.apply(name || null, {\n deferMetadata: true,\n });\n if (outcome === 'skip') {\n continue;\n }\n rebuild = true;\n if (name) {\n dirtySet.add(resolve(srcDir, name));\n }\n const rel = name ? `src/${name.replace(/\\\\/g, '/')}` : 'src';\n log.change(outcome === 'full' ? 'sync' : 'update', rel, bump(rel));\n if (outcome === 'full') {\n fullSync = true;\n break;\n }\n }\n if (rebuild) {\n current = await buildGiriApp(cfg, {\n services,\n dirty: fullSync ? undefined : dirtySet,\n lazy: true,\n loaderRegistered: true,\n aliasResolverRegistered: true,\n });\n }\n }\n } catch (error) {\n log.error(formatError(error), 'watch');\n } finally {\n syncing = false;\n }\n if (changed.size > 0) {\n void flush();\n }\n };\n\n // ignoreInitial: boot() already built the whole project (syncProject + buildGiriApp);\n // replaying an `add` for every existing file here would re-run a full rebuild storm and\n // race with the config-restart below. We only want events for edits made after boot.\n const watcher = watch(srcDir, { persistent: true, ignoreInitial: true });\n // chokidar emits absolute paths; the updater (and its log labels) expect paths relative\n // to the watched `src/`, matching the relative form used everywhere else.\n const onFileChange = (filename: string): void => {\n changed.add(isAbsolute(filename) ? relative(srcDir, filename) : filename);\n clearTimeout(timer);\n timer = setTimeout(() => void flush(), 150);\n };\n watcher.on('change', onFileChange);\n watcher.on('add', onFileChange);\n watcher.on('unlink', onFileChange);\n closers.push(() => {\n clearTimeout(timer);\n watcher.close();\n });\n }\n }\n\n const handler: GiriFetchHandler = (request) => cfg.adapter.fetch(current.app, request);\n\n const server = cfg.adapter.serve(handler, { port, hostname }, (info) => {\n log.ready(`http://${displayHost(info.address)}:${info.port}`);\n });\n\n stop = async () => {\n for (const close of closers) {\n await close();\n }\n try {\n await server.close();\n } catch { }\n if (lifecycle.teardown) {\n await lifecycle.teardown(services);\n }\n };\n };\n\n await boot(config);\n const configPath = flags.watch ? findConfigPath(resolve(process.cwd())) : undefined;\n if (configPath) {\n let timer: NodeJS.Timeout | undefined;\n let restarting = false;\n const configName = basename(configPath);\n\n const restart = async (): Promise<void> => {\n if (restarting) {\n return;\n }\n restarting = true;\n try {\n log.info(`${color.green('restart')} ${configName} changed`, 'config');\n delete require.cache[configPath];\n const next = await load({ throwOnError: true });\n await stop?.();\n await boot(next);\n } catch (error) {\n log.error(error instanceof Error ? error.message : String(error), 'config');\n log.info('kept the previous server running — fix the config and save again', 'config');\n } finally {\n restarting = false;\n }\n };\n // Watch the config FILE directly, never its parent directory: `dirname(configPath)` is the\n // project root, and watching that recursively would scan all of node_modules (tens of seconds\n // on a real project) — which both stalls startup and, on Windows, starves the nested src\n // watcher so edits stop being detected. ignoreInitial avoids a spurious restart from the\n // initial `add` event.\n const configWatcher = watch(configPath, { persistent: true, ignoreInitial: true });\n configWatcher.on('all', () => {\n clearTimeout(timer);\n timer = setTimeout(() => void restart(), 150);\n });\n }\n\n registerShutdown(() => stop?.());\n}\n\nfunction registerShutdown(cleanup: () => void | Promise<void>): void {\n let shuttingDown = false;\n const shutdown = async (): Promise<void> => {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n try {\n await cleanup();\n } catch (error) {\n log.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n } finally {\n process.exit(process.exitCode ?? 0);\n }\n };\n\n process.once('SIGINT', () => void shutdown());\n process.once('SIGTERM', () => void shutdown());\n}\n\nasync function main(): Promise<void> {\n const [command = 'help', ...args] = process.argv.slice(2);\n const cwd = resolve(process.cwd());\n\n if (command === 'help' || command === '--help' || command === '-h') {\n help();\n return;\n }\n\n if (command === 'init') {\n await initProject(cwd, parseInitFlags(args));\n return;\n }\n\n if (command === 'build') {\n log.warn('build is planned, but is currently a no-op', 'build');\n return;\n }\n\n const config = await load();\n\n if (command === 'sync') {\n const result = await syncProject(config);\n log.success(\n `synced ${result.routes.length} route${result.routes.length === 1 ? '' : 's'} ${muted(`at ${result.paths.outDir}`)}`,\n 'sync',\n );\n return;\n }\n\n if (command === 'serve') {\n await serveProject(config, parseFlags(args));\n return;\n }\n\n throw new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error) => {\n log.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n});\n","import Module from 'node:module';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { safeRegister } from './loader/loader';\nimport { assertRouteHandleExport, scanRoutes, type ScannedRoute } from './routes';\nimport type {\n GiriBodySchema,\n GiriConfig,\n GiriInputSchema,\n GiriPaths,\n GiriRouteRegistration,\n Handle,\n Middleware,\n RouteInput,\n Services,\n} from './types';\nimport { isGiriBodySchema, isGiriInputSchema } from './validation';\n\nexport interface BuildGiriAppOptions {\n cwd?: string;\n services?: Services;\n /** Files that changed since last build — only these are purged from require.cache before loading. */\n dirty?: Set<string>;\n /** Defer route-module evaluation until the adapter first reads its runtime fields. */\n lazy?: boolean;\n /** The caller owns a persistent TypeScript loader for lazy route evaluation. */\n loaderRegistered?: boolean;\n /** The caller owns a persistent project-alias resolver for lazy route evaluation. */\n aliasResolverRegistered?: boolean;\n}\n\nexport interface BuiltGiriApp<App> {\n app: App;\n routes: ScannedRoute[];\n paths: GiriPaths;\n}\n\ninterface RouteModule {\n handle?: Handle;\n middleware?: Middleware | Middleware[];\n body?: unknown;\n query?: unknown;\n config?: {\n skipInherited?: boolean;\n };\n}\n\nfunction loadModule(file: string, force = true): unknown {\n const resolved = require.resolve(file);\n if (force) {\n delete require.cache[resolved];\n }\n return require(resolved);\n}\n\nfunction interopDefault(value: unknown): unknown {\n if (value && typeof value === 'object' && 'default' in value) {\n return (value as { default: unknown }).default;\n }\n return value;\n}\n\nfunction normalizeMiddleware(value: unknown, file: string): Middleware[] {\n const exported = interopDefault(value);\n if (exported === undefined) {\n return [];\n }\n if (typeof exported === 'function') {\n return [exported as Middleware];\n }\n if (Array.isArray(exported)) {\n for (const middleware of exported) {\n if (typeof middleware !== 'function') {\n throw new Error(`Middleware export in ${file} must contain only functions.`);\n }\n }\n return exported as Middleware[];\n }\n throw new Error(`Middleware export in ${file} must be a function or an array of functions.`);\n}\n\nfunction assertBodySchema(value: unknown, file: string): asserts value is GiriBodySchema {\n if (!isGiriBodySchema(value)) {\n throw new Error(\n `${file}: \"body\" must be wrapped with a validator, e.g. \\`export const body = zod.body({ json: ... })\\` from @boon4681/giri/validators/zod.`,\n );\n }\n}\n\nfunction assertQuerySchema(value: unknown, file: string): asserts value is GiriInputSchema {\n if (!isGiriInputSchema(value)) {\n throw new Error(\n `${file}: \"query\" must be wrapped with a validator, e.g. \\`export const query = zod.query(...)\\` from @boon4681/giri/validators/zod.`,\n );\n }\n}\n\nfunction routeInput(routeModule: RouteModule, file: string): RouteInput | undefined {\n const input: RouteInput = {};\n if (routeModule.body !== undefined) {\n assertBodySchema(routeModule.body, file);\n input.body = routeModule.body;\n }\n if (routeModule.query !== undefined) {\n assertQuerySchema(routeModule.query, file);\n input.query = routeModule.query;\n }\n return input.body || input.query ? input : undefined;\n}\n\nfunction aliasValues(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\nfunction resolveAliasTarget(cwd: string, target: string, capture = ''): string {\n const replaced = target.includes('*') ? target.replaceAll('*', capture) : target;\n return isAbsolute(replaced) ? replaced : resolve(cwd, replaced);\n}\n\nfunction matchAlias(request: string, key: string): string | undefined {\n if (key.includes('*')) {\n const [prefix, suffix = ''] = key.split('*');\n if (request.startsWith(prefix) && request.endsWith(suffix)) {\n return request.slice(prefix.length, request.length - suffix.length);\n }\n return undefined;\n }\n \n return request === key ? '' : undefined;\n}\n\nexport function resolveAliasRequest(\n request: string,\n alias: GiriConfig['alias'],\n cwd: string,\n): string | undefined {\n for (const [key, value] of Object.entries(alias ?? {})) {\n const capture = matchAlias(request, key);\n if (capture === undefined) {\n continue;\n }\n\n const [target] = aliasValues(value);\n if (!target) {\n continue;\n }\n\n return resolveAliasTarget(cwd, target, capture);\n }\n\n return undefined;\n}\n\nexport function registerAliasResolver(alias: GiriConfig['alias'], cwd: string): () => void {\n if (!alias || Object.keys(alias).length === 0) {\n return () => { };\n }\n\n const moduleWithResolver = Module as typeof Module & {\n _resolveFilename: (request: string, parent: unknown, isMain: boolean, options: unknown) => string;\n };\n const originalResolveFilename = moduleWithResolver._resolveFilename;\n\n moduleWithResolver._resolveFilename = function resolveWithGiriAlias(\n request,\n parent,\n isMain,\n options,\n ) {\n return originalResolveFilename.call(\n this,\n resolveAliasRequest(request, alias, cwd) ?? request,\n parent,\n isMain,\n options,\n );\n };\n\n return () => {\n moduleWithResolver._resolveFilename = originalResolveFilename;\n };\n}\n\nconst GIRI_ALIAS_PREFIX = '$giri/';\nlet giriOutDir: string | undefined;\nlet giriResolverInstalled = false;\n\n/**\n * Install a process-lifetime resolver for the internal `$giri/*` alias\n */\nexport function ensureGiriAliasResolver(outDir: string): void {\n giriOutDir = outDir;\n if (giriResolverInstalled) {\n return;\n }\n giriResolverInstalled = true;\n\n const moduleWithResolver = Module as typeof Module & {\n _resolveFilename: (request: string, parent: unknown, isMain: boolean, options: unknown) => string;\n };\n const originalResolveFilename = moduleWithResolver._resolveFilename;\n\n moduleWithResolver._resolveFilename = function resolveWithGiriInternalAlias(\n request,\n parent,\n isMain,\n options,\n ) {\n const mapped =\n typeof request === 'string' && request.startsWith(GIRI_ALIAS_PREFIX) && giriOutDir\n ? join(giriOutDir, request.slice(GIRI_ALIAS_PREFIX.length))\n : request;\n return originalResolveFilename.call(this, mapped, parent, isMain, options);\n };\n}\n\nexport function resolveGiriPaths(config: Pick<GiriConfig, 'outDir'>, cwd = process.cwd()): GiriPaths {\n return {\n cwd: resolve(cwd),\n routesDir: resolve(cwd, 'src/routes'),\n outDir: resolve(cwd, config.outDir ?? '.giri'),\n };\n}\n\nexport async function buildGiriApp<App>(\n config: GiriConfig<App>,\n options: BuildGiriAppOptions = {},\n): Promise<BuiltGiriApp<App>> {\n const paths = resolveGiriPaths(config, options.cwd);\n const routes = await scanRoutes(paths.routesDir);\n if (options.lazy) {\n for (const route of routes) {\n assertRouteHandleExport(route.file);\n }\n }\n const app = config.adapter.createApp();\n // Install the persistent `$giri` resolver BEFORE esbuild-register: it patches\n // `_resolveFilename` too, and its unregister() restores whatever it captured\n ensureGiriAliasResolver(paths.outDir);\n if (options.lazy && (!options.loaderRegistered || !options.aliasResolverRegistered)) {\n throw new Error('Lazy route loading requires persistent loader and alias registrations.');\n }\n const loader = options.loaderRegistered ? undefined : await safeRegister();\n const unregisterAliasResolver = options.aliasResolverRegistered\n ? undefined\n : registerAliasResolver(config.alias, paths.cwd);\n\n try {\n const dirty = options.dirty;\n const forceReload = dirty === undefined;\n const isDirty = (file: string): boolean => forceReload || dirty.has(file);\n const sharedCache = new Map<string, unknown>();\n const loadShared = (file: string): unknown => {\n if (!sharedCache.has(file)) {\n sharedCache.set(file, loadModule(file, isDirty(file)));\n }\n return sharedCache.get(file);\n };\n\n const runtimeFor = (route: ScannedRoute): GiriRouteRegistration => {\n const routeModule = loadModule(route.file, isDirty(route.file)) as RouteModule;\n if (typeof routeModule.handle !== 'function') {\n throw new Error(`${route.file} must export a named handle function.`);\n }\n\n const folderMiddleware = routeModule.config?.skipInherited\n ? []\n : route.sharedFiles.flatMap((file) =>\n normalizeMiddleware((loadShared(file) as { middleware?: unknown }).middleware, file),\n );\n const verbMiddleware = normalizeMiddleware(routeModule.middleware, route.file);\n\n return {\n method: route.method,\n path: route.path,\n handle: routeModule.handle,\n middleware: [...folderMiddleware, ...verbMiddleware],\n input: routeInput(routeModule, route.file),\n services: options.services,\n cookieSecret: config.cookieSecret,\n };\n };\n\n for (const route of routes) {\n if (!options.lazy) {\n config.adapter.register(app, runtimeFor(route));\n continue;\n }\n\n let runtime: GiriRouteRegistration | undefined;\n const getRuntime = (): GiriRouteRegistration => {\n runtime ??= runtimeFor(route);\n return runtime;\n };\n config.adapter.register(app, {\n method: route.method,\n path: route.path,\n get handle() {\n return getRuntime().handle;\n },\n get middleware() {\n return getRuntime().middleware;\n },\n get input() {\n return getRuntime().input;\n },\n services: options.services,\n cookieSecret: config.cookieSecret,\n });\n }\n } finally {\n unregisterAliasResolver?.();\n loader?.unregister();\n }\n\n return { app, routes, paths };\n}\n","import { cancel, log, spinner } from '@clack/prompts';\nimport { existsSync } from 'node:fs';\nimport { join, resolve, sep } from 'node:path';\nimport { exit } from 'node:process';\nimport { configSchema } from '../config/schema';\nimport { Value } from \"@sinclair/typebox/value\"\nimport { Static } from '@sinclair/typebox';\n\nconst assertES5 = async (unregister: () => void) => {\n try {\n require('./_es5.ts');\n } catch (e: any) {\n if ('errors' in e && Array.isArray(e.errors) && e.errors.length > 0) {\n const es5Error = (e.errors as any[]).filter((it) => it.text?.includes(`(\"es5\") is not supported yet`)).length > 0;\n if (es5Error) {\n log.error(\n `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`\n );\n exit(1);\n }\n }\n log.error(e);\n exit(1);\n }\n};\n\nexport const safeRegister = async () => {\n const { register } = await import('esbuild-register/dist/node');\n let res: { unregister: () => void };\n try {\n res = register({\n format: 'cjs',\n loader: 'ts',\n });\n } catch {\n // tsx fallback\n res = {\n unregister: () => { },\n };\n }\n\n // has to be outside try catch to be able to run with tsx\n await assertES5(res.unregister);\n return res;\n}\n\nexport const findConfigPath = (cwd: string = resolve()): string | undefined => {\n for (const name of ['giri.config.ts', 'giri.config.js']) {\n const path = resolve(cwd, name);\n if (existsSync(path)) {\n return path;\n }\n }\n return undefined;\n};\n\nexport const load = async (opts: { throwOnError?: boolean } = {}) => {\n const fail = (message: string): never => {\n if (opts.throwOnError) {\n throw new Error(message);\n }\n log.error(message);\n exit(1);\n };\n\n const path = findConfigPath();\n if (!path) {\n fail(\"Config file not found.\")\n }\n\n const { unregister } = await safeRegister();\n let content: unknown;\n try {\n const required = require(`${path}`);\n content = required.default ?? required;\n } finally { }\n unregister();\n // get response and then check by each dialect independently\n const res = Value.Check(configSchema, content);\n if (!res) {\n const messages = [...Value.Errors(configSchema, content)].map((error) => error.message);\n if (!opts.throwOnError) {\n for (const message of messages) {\n log.error(message);\n }\n }\n fail(messages.join('\\n'));\n }\n return content as Static<typeof configSchema>\n}\n","import { Static, Type } from \"@sinclair/typebox\";\n\nexport const configSchema = Type.Object({\n adapter: Type.Any(),\n alias: Type.Optional(Type.Record(\n Type.String(),\n Type.Union([Type.String(), Type.Array(Type.String())]),\n )),\n outDir: Type.Optional(Type.String()),\n server: Type.Optional(Type.Object({\n port: Type.Optional(Type.Number()),\n hostname: Type.Optional(Type.String()),\n }, { additionalProperties: false })),\n errorSchema: Type.Optional(Type.Any()),\n cookieSecret: Type.Optional(Type.String()),\n}, { additionalProperties: false })","import { existsSync, readFileSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport ts from 'typescript';\nimport type { HttpMethod } from './types';\n\nconst METHOD_ORDER: HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\nconst METHOD_FROM_FILE = new Map<string, HttpMethod>(\n METHOD_ORDER.map((method) => [`+${method.toLowerCase()}`, method]),\n);\n\nexport interface RouteParam {\n name: string;\n catchAll: boolean;\n}\n\nexport interface ScannedRoute {\n method: HttpMethod;\n path: string;\n file: string;\n routeDir: string;\n routeSegments: string[];\n params: RouteParam[];\n /** The `+shared.ts` chain folder-cascading config. */\n sharedFiles: string[];\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.split(sep).join('/');\n}\n\nfunction isRouteSourceFile(fileName: string): boolean {\n return /\\.(?:[cm]?[jt]s|[jt]sx)$/.test(fileName) && !fileName.endsWith('.d.ts');\n}\n\nfunction methodFromFile(fileName: string): HttpMethod | undefined {\n if (!isRouteSourceFile(fileName)) {\n return undefined;\n }\n const stem = fileName.replace(/\\.(?:[cm]?[jt]s|[jt]sx)$/, '').toLowerCase();\n return METHOD_FROM_FILE.get(stem);\n}\n\nfunction hasExportModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n}\n\nfunction hasDeclareModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword) ?? false);\n}\n\nfunction propertyName(node: ts.Node): string | undefined {\n if (ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {\n return node.text;\n }\n if (ts.isPropertyAccessExpression(node)) {\n return node.name.text;\n }\n if (ts.isElementAccessExpression(node) && node.argumentExpression) {\n const argument = node.argumentExpression;\n if (ts.isStringLiteralLike(argument)) {\n return argument.text;\n }\n }\n return undefined;\n}\n\nfunction isExportsObject(node: ts.Expression): boolean {\n return ts.isIdentifier(node) && node.text === 'exports';\n}\n\nfunction isModuleExports(node: ts.Expression): boolean {\n return ts.isPropertyAccessExpression(node) &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === 'module' &&\n node.name.text === 'exports';\n}\n\nfunction isCommonJsHandleTarget(node: ts.Expression): boolean {\n if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) {\n return false;\n }\n return propertyName(node) === 'handle' &&\n (isExportsObject(node.expression) || isModuleExports(node.expression));\n}\n\nfunction objectExportsHandle(node: ts.Expression): boolean {\n if (!ts.isObjectLiteralExpression(node)) {\n return false;\n }\n return node.properties.some((property) => {\n if (ts.isShorthandPropertyAssignment(property)) {\n return property.name.text === 'handle';\n }\n return (\n (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) &&\n propertyName(property.name) === 'handle'\n );\n });\n}\n\nfunction hasNamedHandleExport(source: ts.SourceFile): boolean {\n for (const statement of source.statements) {\n if (\n hasExportModifier(statement) &&\n !hasDeclareModifier(statement) &&\n ts.isFunctionDeclaration(statement) &&\n statement.name?.text === 'handle'\n ) {\n return true;\n }\n\n if (\n hasExportModifier(statement) &&\n !hasDeclareModifier(statement) &&\n ts.isVariableStatement(statement)\n ) {\n if (statement.declarationList.declarations.some(\n (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'handle',\n )) {\n return true;\n }\n }\n\n if (\n ts.isExportDeclaration(statement) &&\n !statement.isTypeOnly &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n if (statement.exportClause.elements.some(\n (element) => !element.isTypeOnly && element.name.text === 'handle',\n )) {\n return true;\n }\n }\n\n if (!ts.isExpressionStatement(statement) || !ts.isBinaryExpression(statement.expression)) {\n continue;\n }\n const assignment = statement.expression;\n if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {\n continue;\n }\n if (\n isCommonJsHandleTarget(assignment.left) ||\n (isModuleExports(assignment.left) && objectExportsHandle(assignment.right))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction parseSource(file: string): ts.SourceFile {\n return ts.createSourceFile(\n file,\n readFileSync(file, 'utf8'),\n ts.ScriptTarget.Latest,\n true,\n );\n}\n\nfunction parseDiagnostics(source: ts.SourceFile): readonly ts.DiagnosticWithLocation[] {\n return (\n source as ts.SourceFile & {\n parseDiagnostics?: readonly ts.DiagnosticWithLocation[];\n }\n ).parseDiagnostics ?? [];\n}\n\nfunction formatSyntaxDiagnostic(diagnostic: ts.DiagnosticWithLocation): string {\n const position = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n');\n return `${diagnostic.file.fileName}:${position.line + 1}:${position.character + 1} - error TS${diagnostic.code}: ${message}`;\n}\n\n/** Verify a TypeScript/JavaScript source file parses before accepting a watch update. */\nexport function assertSourceSyntax(file: string): void {\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/i.test(file)) {\n return;\n }\n const diagnostics = parseDiagnostics(parseSource(file));\n if (diagnostics.length > 0) {\n throw new SyntaxError(diagnostics.map(formatSyntaxDiagnostic).join('\\n'));\n }\n}\n\n/** Verify the route declares a named handle export without evaluating the module. */\nexport function assertRouteHandleExport(file: string): void {\n const source = parseSource(file);\n const diagnostics = parseDiagnostics(source);\n if (diagnostics.length > 0) {\n throw new SyntaxError(diagnostics.map(formatSyntaxDiagnostic).join('\\n'));\n }\n if (!hasNamedHandleExport(source)) {\n throw new Error(`${file} must export a named handle function.`);\n }\n}\n\nfunction sharedFileIn(dir: string, cache?: Map<string, string | undefined>): string | undefined {\n if (cache?.has(dir)) {\n return cache.get(dir);\n }\n for (const ext of ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts']) {\n const file = join(dir, `+shared.${ext}`);\n if (existsSync(file)) {\n cache?.set(dir, file);\n return file;\n }\n }\n cache?.set(dir, undefined);\n return undefined;\n}\n\nfunction physicalRouteSegments(routesDir: string, routeDir: string): string[] {\n const rel = relative(routesDir, routeDir);\n if (!rel) {\n return [];\n }\n return normalizeSlashes(rel).split('/').filter(Boolean);\n}\n\nfunction urlSegment(segment: string): { value?: string; param?: RouteParam } {\n if (/^\\(.+\\)$/.test(segment)) {\n return {};\n }\n\n const catchAll = /^\\[\\.\\.\\.(.+)\\]$/.exec(segment);\n if (catchAll) {\n const name = catchAll[1];\n return {\n value: `:${name}{.*}`,\n param: { name, catchAll: true },\n };\n }\n\n const param = /^\\[(.+)\\]$/.exec(segment);\n if (param) {\n const name = param[1];\n return {\n value: `:${name}`,\n param: { name, catchAll: false },\n };\n }\n\n return { value: segment };\n}\n\nexport function pathFromSegments(segments: string[]): { path: string; params: RouteParam[] } {\n const pathSegments: string[] = [];\n const params: RouteParam[] = [];\n\n for (const segment of segments) {\n const converted = urlSegment(segment);\n if (converted.value) {\n pathSegments.push(converted.value);\n }\n if (converted.param) {\n params.push(converted.param);\n }\n }\n\n return {\n path: pathSegments.length > 0 ? `/${pathSegments.join('/')}` : '/',\n params,\n };\n}\n\n/**\n * Every directory under `routesDir` (including itself), so `$types` can be generated for a\n * folder the moment it's created\n */\nexport async function scanRouteFolders(routesDir: string): Promise<string[]> {\n if (!existsSync(routesDir)) {\n return [];\n }\n const folders = [routesDir];\n const walk = async (dir: string): Promise<void> => {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n if (entry.isDirectory() && entry.name !== 'node_modules') {\n const full = join(dir, entry.name);\n folders.push(full);\n await walk(full);\n }\n }\n };\n await walk(routesDir);\n return folders;\n}\n\n/** Folder-derived params for any directory under `routesDir` (used for middleware `$types`). */\nexport function routeParamsForDir(routesDir: string, dir: string): RouteParam[] {\n return pathFromSegments(physicalRouteSegments(routesDir, dir)).params;\n}\n\n/** The ordered `+shared.ts` chain that applies to a directory. */\nexport function sharedFilesForDir(\n routesDir: string,\n dir: string,\n cache?: Map<string, string | undefined>,\n): string[] {\n const segments = physicalRouteSegments(routesDir, dir);\n const dirs = [routesDir];\n\n let current = routesDir;\n for (const segment of segments) {\n current = join(current, segment);\n dirs.push(current);\n }\n\n return dirs.map((currentDir) => sharedFileIn(currentDir, cache)).filter((file): file is string => Boolean(file));\n}\n\nexport async function scanRoutes(routesDir: string): Promise<ScannedRoute[]> {\n if (!existsSync(routesDir)) {\n return [];\n }\n\n const files = await glob('**/+*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}', {\n cwd: routesDir,\n absolute: true,\n onlyFiles: true,\n });\n\n const routes: ScannedRoute[] = [];\n const sharedCache = new Map<string, string | undefined>();\n\n for (const file of files) {\n const method = methodFromFile(basename(file));\n if (!method) {\n continue;\n }\n \n const routeDir = dirname(file);\n const routeSegments = physicalRouteSegments(routesDir, routeDir);\n const { path, params } = pathFromSegments(routeSegments);\n\n routes.push({\n method,\n path,\n file,\n routeDir,\n routeSegments,\n params,\n sharedFiles: sharedFilesForDir(routesDir, routeDir, sharedCache),\n });\n }\n\n return routes.sort((left, right) => {\n const pathOrder = left.path.localeCompare(right.path);\n if (pathOrder !== 0) {\n return pathOrder;\n }\n return METHOD_ORDER.indexOf(left.method) - METHOD_ORDER.indexOf(right.method);\n });\n}\n","export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';\n\nexport type StatusCode = number;\n\nexport type ResponseFormat = 'json' | 'text' | 'html';\n\nexport const typedResponseBrand: unique symbol = Symbol.for('giri.typed-response') as never;\nexport const nativeContextBrand: unique symbol = Symbol.for('giri.native-context') as never;\n\nexport interface TypedResponse<\n T,\n S extends StatusCode = StatusCode,\n F extends ResponseFormat = ResponseFormat,\n> {\n readonly [typedResponseBrand]: {\n data: T;\n status: S;\n format: F;\n };\n readonly data: T;\n readonly status: S;\n readonly format: F;\n readonly headers?: HeadersInit;\n}\n\nexport type HandlerResponse = Response | TypedResponse<unknown, StatusCode, ResponseFormat>;\n\nexport interface ValidatedInput {\n /**\n * The validated request body. For a single declared content-type it's that schema's\n * output; for several it's a discriminated union `{ type; data }` (see `ValidBody`).\n */\n body?: unknown;\n query?: unknown;\n}\n\n/** Attributes for a `Set-Cookie` header. `path` defaults to `/`. */\nexport interface CookieOptions {\n domain?: string;\n path?: string;\n /** Lifetime in seconds. */\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none';\n partitioned?: boolean;\n priority?: 'Low' | 'Medium' | 'High' | 'low' | 'medium' | 'high';\n}\n\n/**\n * Cookie read/write, implemented per adapter with its runtime's native helpers. giri core\n * supplies the {@link CookieSink} (where to read from / write to); the adapter owns encoding.\n */\nexport interface CookieJar {\n get(name: string): string | undefined;\n all(): Record<string, string>;\n set(name: string, value: string, options?: CookieOptions): void;\n delete(name: string, options?: CookieOptions): void;\n getSigned(name: string): Promise<string | false | undefined>;\n setSigned(name: string, value: string, options?: CookieOptions): Promise<void>;\n}\n\n/** What core hands an adapter's cookie jar: the request to read from, the response sink to write to. */\nexport interface CookieSink {\n /** The incoming request, for reading the `Cookie` header. */\n request: Request;\n /** Append one already-serialized `Set-Cookie` header value to the response. */\n append(setCookieHeader: string): void;\n /** The configured `cookieSecret`, if any (for signed cookies). */\n secret?: string;\n}\n\n/** Builds a {@link CookieJar} bound to one request's {@link CookieSink}. Each adapter provides one. */\nexport type CookieJarFactory = (sink: CookieSink) => CookieJar;\n\nexport interface GiriRequest<Input extends ValidatedInput = ValidatedInput> {\n raw: Request;\n url: URL;\n method: string;\n header(name: string): string | null;\n json<T = unknown>(): Promise<T>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n formData(): Promise<FormData>;\n valid<K extends keyof Input & ('body' | 'query')>(key: K): Input[K];\n /** Read a request cookie by name, or `undefined` if absent. */\n cookie(name: string): string | undefined;\n /** All request cookies as a name: value map. */\n cookies(): Record<string, string>;\n /**\n * Read and verify a signed cookie. Resolves to the original value, `false` if the\n * signature was tampered with, or `undefined` if the cookie is absent. Requires\n * `cookieSecret` in `giri.config`.\n */\n signedCookie(name: string): Promise<string | false | undefined>;\n}\n\ndeclare global {\n /**\n * Global registration surface for app-wide types. `giri sync` augments\n * `Giri.Register[\"app\"]` from `src/main.ts` `init()` return type so `c.app` is\n * typed without per-route generics (the registration pattern).\n */\n namespace Giri {\n interface Register {}\n }\n}\n\n/**\n * The app-wide services container, the type of `c.app`. `giri sync` infers it from\n * `src/main.ts`'s `init()` return type (via the global `Giri.Register` augmentation);\n * until then it falls back to an open record. Leave `init` unannotated (its return is\n * the source of truth) and annotate `teardown`'s parameter with this:\n *\n * ```ts\n * export const init = () => ({ db }); // inferred\n * export const teardown = (services: Services) => services.db.close();\n * ```\n */\nexport type Services = Giri.Register extends { app: infer A }\n ? A\n : Record<string, unknown>;\n\nexport interface Context<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> {\n params: Params;\n /** App-wide services from `src/main.ts`'s `init()`, seeded into every request. */\n app: Services;\n req: GiriRequest<Input>;\n // Context vars (`c.set`/`c.get`). Keys declared by middleware (`Vars`) are typed;\n // any other key stays open (`unknown`) so untracked keys still work.\n set<K extends keyof Vars & string>(key: K, value: Vars[K]): void;\n set<K extends string>(key: K, value: unknown): void;\n get<K extends keyof Vars & string>(key: K): Vars[K];\n get<V = unknown>(key: string): V;\n json<T, S extends StatusCode = 200>(\n data: T,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<T, S, 'json'>;\n text<S extends StatusCode = 200>(\n text: string,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<string, S, 'text'>;\n /** An HTML response (`text/html`). Like `text`, the body is a string. */\n html<S extends StatusCode = 200>(\n html: string,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<string, S, 'html'>;\n /** A raw-body response - string, stream, buffer, FormData, … (not documented in OpenAPI). */\n body(data: BodyInit | null, status?: StatusCode, headers?: HeadersInit): Response;\n /** Alias of `body`, mirroring Hono's `c.newResponse`. */\n newResponse(data: BodyInit | null, status?: StatusCode, headers?: HeadersInit): Response;\n /** A redirect (defaults to 302) with the `Location` header set. */\n redirect(location: string, status?: StatusCode): Response;\n /** A 404 Not Found response. */\n notFound(): Response;\n /**\n * Set a response header applied to whatever this handler returns. Pass `{ append: true }` to add\n * another value (e.g. `Set-Cookie`); omit `value` to delete. Mirrors Hono's `c.header`.\n */\n header(name: string, value?: string, options?: { append?: boolean }): void;\n /** Default status for `body`/`redirect`, and for `json`/`text`/`html` when no status arg is given. */\n status(code: StatusCode): void;\n /**\n * Set a response cookie via `Set-Cookie`. Pass `value: null` to delete it (send the\n * same `path`/`domain` you set it with). Stacks with other cookies set this request.\n */\n cookie(name: string, value: string | null, options?: CookieOptions): void;\n /** Set an HMAC-signed cookie. Requires `cookieSecret` in `giri.config`. */\n signedCookie(name: string, value: string, options?: CookieOptions): Promise<void>;\n}\n\nexport type Handle<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> = (c: Context<Params, Input, Vars>) => HandlerResponse | Promise<HandlerResponse>;\n\nexport type Next = () => Promise<HandlerResponse | void>;\n\n/** An OpenAPI security requirement, e.g. `{ bearerAuth: [] }`. */\nexport type SecurityRequirement = Record<string, string[]>;\n\nexport interface MiddlewareOpenApi {\n /** Security requirements this middleware enforces */\n security?: SecurityRequirement[];\n /** Optional scheme definitions, merged into `components.securitySchemes` so the doc is self-contained. */\n securitySchemes?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface MiddlewareOptions {\n openapi?: MiddlewareOpenApi;\n}\n\nexport interface Middleware<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> {\n (c: Context<Params, Input, Vars>, next: Next): HandlerResponse | void | Promise<HandlerResponse | void>;\n openapi?: MiddlewareOpenApi;\n}\n\n/** The context vars a middleware injects (its `Vars` type parameter). */\nexport type VarsOf<M> = M extends Middleware<Record<string, string>, ValidatedInput, infer V>\n ? V\n : {};\n\n/** Intersect the injected vars of a tuple of middleware (built with `stack(...)`). */\nexport type MergeStack<T> = T extends readonly [infer Head, ...infer Rest]\n ? VarsOf<Head> & MergeStack<Rest>\n : {};\n\n/**\n * Merge the injected vars of a `middleware` export. A `stack(...)` tuple is merged element-wise;\n * a single bare middleware (`export const middleware = fromHono(...)`) contributes its own vars; a\n * plain `Middleware[]` (not a `stack(...)` tuple) contributes nothing - its element types are lost.\n */\nexport type InferStackVars<T> = T extends readonly [unknown, ...unknown[]]\n ? MergeStack<T>\n : T extends Middleware<Record<string, string>, ValidatedInput, any>\n ? VarsOf<T>\n : {};\n\n/**\n * The vars injected by a module own `middleware` export (a `stack(...)`). Used by the\n * generated per-method handle so a verb file's own `export const middleware` types\n * `c.get`/`c.set`, on top of the folder's `+shared.ts` chain.\n */\nexport type MiddlewareVarsOf<M> = M extends { middleware: infer Stack }\n ? InferStackVars<Stack>\n : {};\n\n/** A JSON Schema object (JSON Schema 2020-12 / OpenAPI 3.1 dialect). */\nexport type JsonSchema = Record<string, unknown>;\n\nexport const inputSchemaBrand: unique symbol = Symbol.for('giri.input-schema') as never;\n\nexport type InputValidationResult<Output = unknown> =\n | { ok: true; value: Output }\n | { ok: false; issues: unknown };\n\n/**\n * A input schema every wrapper form (`body`/`query`) export takes. A vendor\n * adapter (`@boon4681/giri/validators/zod`, `@boon4681/giri/validators/valibot`, …) returns one; build a\n * custom one with `defineInputSchema`. giri core depends only on this interface, never\n * on a validator library. `validate` is the runtime check; `toJsonSchema` feeds OpenAPI.\n */\nexport interface GiriInputSchema<Output = unknown> {\n readonly [inputSchemaBrand]: true;\n validate(value: unknown): InputValidationResult<Output> | Promise<InputValidationResult<Output>>;\n toJsonSchema(): JsonSchema;\n}\n\n/** Extract the validated output type of a giri input schema: `Infer<typeof body>`. */\nexport type Infer<T> = T extends GiriInputSchema<infer Output> ? Output : never;\n\nexport type BodyContentType = 'json' | 'form' | 'urlencoded' | 'text';\n\nexport const bodySchemaBrand: unique symbol = Symbol.for('giri.body-schema') as never;\n\n/**\n * A request body declared as a set of accepted content-types wrapped form `body`\n * takes (`zod.body({ json, form })`). One key means that encoding only; several mean the\n * endpoint accepts any of them, dispatched at runtime on the request `Content-Type`.\n * Each entry is a plain `GiriInputSchema`, so `validate`/`toJsonSchema` work per content-type.\n */\nexport interface GiriBodySchema<\n Outputs extends Partial<Record<BodyContentType, unknown>> = Partial<Record<BodyContentType, unknown>>,\n> {\n readonly [bodySchemaBrand]: true;\n readonly contents: { [K in keyof Outputs & BodyContentType]: GiriInputSchema<Outputs[K]> };\n}\n\n/** True when `T` is a union of more than one member. */\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;\n\n/**\n * The validated body a handler receives. A single declared content-type yields that\n * schema's output directly; several yield a discriminated union keyed by content-type.\n */\nexport type ValidBody<B> = B extends GiriBodySchema<infer Outputs>\n ? IsUnion<keyof Outputs> extends true\n ? { [K in keyof Outputs]: { type: K; data: Outputs[K] } }[keyof Outputs]\n : Outputs[keyof Outputs]\n : never;\n\n/** The validated query a handler receives. */\nexport type ValidQuery<Q> = Q extends GiriInputSchema<infer Output> ? Output : never;\n\n/** Drop keys whose value resolved to `never` (an input the route didn't declare). */\ntype PruneNever<T> = { [K in keyof T as [T[K]] extends [never] ? never : K]: T[K] };\n\n/**\n * Derive a route's `ValidatedInput` from a module's `body`/`query` exports. The generated\n * per-method `$types` handle (`POST`, `GET`, …) uses this so handlers infer `c.req.valid`\n * with no manual generic.\n */\nexport type RouteInputOf<M> = PruneNever<{\n body: M extends { body: infer B } ? ValidBody<B> : never;\n query: M extends { query: infer Q } ? ValidQuery<Q> : never;\n}>;\n\nexport interface RouteInput {\n body?: GiriBodySchema;\n query?: GiriInputSchema;\n}\n\nexport interface RouteOpenApi {\n /** Omit this route from the generated `openapi.json` (it still serves normally). */\n hidden?: boolean;\n /**\n * OpenAPI tags - the grouping in doc viewers. On a `+shared.ts` they apply to every route in the\n * folder; the chain is merged and de-duplicated, so a route's tags add to\n * its folders'.\n */\n tags?: string[];\n /** Short operation summary. Cascades down the chain (a verb file overrides its folders). */\n summary?: string;\n /** Longer operation description. Cascades down the chain (a verb file overrides its folders). */\n description?: string;\n /** Marks the operation(s) deprecated. On a `+shared.ts` it deprecates the whole folder. */\n deprecated?: boolean;\n /** Unique operationId. Verb-file only - it is never inherited from a `+shared.ts`. */\n operationId?: string;\n}\n\nexport type RouteOpenApiConfig = RouteOpenApi | boolean;\n\nexport interface GiriRouteRegistration {\n method: HttpMethod;\n path: string;\n handle: Handle;\n middleware: Middleware[];\n input?: RouteInput;\n /** App-wide services to seed onto `c.app` (same instance for every route). */\n services?: Services;\n /** Secret for signing/verifying cookies (`c.signedCookie`), from `config.cookieSecret`. */\n cookieSecret?: string;\n}\n\nexport type GiriFetchHandler = (req: Request) => Response | Promise<Response>;\n\nexport interface GiriServeOptions {\n port: number;\n hostname?: string;\n}\n\nexport interface GiriServerInfo {\n address: string;\n port: number;\n}\n\nexport interface GiriServer {\n close(): void | Promise<void>;\n}\n\nexport interface GiriAdapter<App> {\n name?: string;\n createApp(): App;\n register(app: App, route: GiriRouteRegistration): void;\n fetch(app: App, req: Request): Promise<Response>;\n /**\n * Bind the configured backend's runtime to a port and start serving.\n * giri core stays runtime-agnostic: it hands the adapter a request handler\n * (so hot-reload keeps working) and the adapter owns the actual server.\n */\n serve(\n handler: GiriFetchHandler,\n options: GiriServeOptions,\n onListen?: (info: GiriServerInfo) => void,\n ): GiriServer;\n}\n\nexport interface GiriConfig<App = unknown> {\n adapter: GiriAdapter<App>;\n alias?: Record<string, string | string[]>;\n outDir?: string;\n server?: {\n port?: number;\n hostname?: string;\n };\n errorSchema?: unknown;\n /** Secret used to sign/verify cookies via `c.signedCookie` / `c.req.signedCookie`. */\n cookieSecret?: string;\n}\n\nexport interface GiriPaths {\n cwd: string;\n routesDir: string;\n outDir: string;\n}\n","import {\n type BodyContentType,\n type GiriBodySchema,\n type GiriInputSchema,\n type InputValidationResult,\n type RouteInput,\n type TypedResponse,\n type ValidatedInput,\n bodySchemaBrand,\n inputSchemaBrand,\n} from './types';\nimport { createTypedResponse } from './context';\n\ninterface PreparedInput {\n ok: true;\n validated: ValidatedInput;\n}\n\ninterface FailedInput {\n ok: false;\n response: TypedResponse<{ message: string; issues: unknown }, 400 | 415, 'json'>;\n}\n\nexport type PreparedRequestInput = PreparedInput | FailedInput;\n\n/**\n * Build a giri input schema from a `validate` + `toJsonSchema` pair. Vendor adapters use\n * this; you can call it directly to make a custom validator. The brand is a global symbol,\n * so a hand-rolled `{ [Symbol.for(\"giri.input-schema\")]: true, validate, toJsonSchema }` works too.\n */\nexport function defineInputSchema<Output>(\n schema: Omit<GiriInputSchema<Output>, typeof inputSchemaBrand>,\n): GiriInputSchema<Output> {\n return { [inputSchemaBrand]: true, ...schema };\n}\n\nexport function isGiriInputSchema(value: unknown): value is GiriInputSchema {\n return Boolean(\n value &&\n typeof value === 'object' &&\n (value as Record<symbol, unknown>)[inputSchemaBrand] === true,\n );\n}\n\n/**\n * Build a giri body schema from per-content-type input schemas. Validator adapters use this `zod.body({ json, form })`\n */\nexport function defineBodySchema<Outputs extends Partial<Record<BodyContentType, unknown>>>(\n contents: GiriBodySchema<Outputs>['contents'],\n): GiriBodySchema<Outputs> {\n return { [bodySchemaBrand]: true, contents };\n}\n\nexport function isGiriBodySchema(value: unknown): value is GiriBodySchema {\n return Boolean(\n value &&\n typeof value === 'object' &&\n (value as Record<symbol, unknown>)[bodySchemaBrand] === true,\n );\n}\n\nconst MIME_TO_CONTENT_TYPE: Record<string, BodyContentType> = {\n 'application/json': 'json',\n 'multipart/form-data': 'form',\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'text/plain': 'text',\n};\n\nfunction contentTypeFromHeader(header: string | null): BodyContentType | undefined {\n if (!header) {\n return undefined;\n }\n const mime = header.split(';', 1)[0].trim().toLowerCase();\n return MIME_TO_CONTENT_TYPE[mime];\n}\n\n/** Flatten a `FormData` into a plain object, collapsing repeated fields into arrays. */\nfunction formDataObject(form: FormData): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n form.forEach((value, key) => {\n const current = result[key];\n if (current === undefined) {\n result[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n result[key] = [current, value];\n }\n });\n return result;\n}\n\nasync function readRawBody(request: Request, contentType: BodyContentType): Promise<unknown> {\n const cloned = request.clone();\n if (contentType === 'json') {\n return cloned.json();\n }\n if (contentType === 'text') {\n return cloned.text();\n }\n return formDataObject(await cloned.formData());\n}\n\nfunction queryObject(url: URL): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n for (const [key, value] of url.searchParams) {\n const current = result[key];\n if (current === undefined) {\n result[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n result[key] = [current, value];\n }\n }\n return result;\n}\n\nasync function runValidation(\n schema: GiriInputSchema,\n value: unknown,\n label: string,\n): Promise<InputValidationResult> {\n if (!isGiriInputSchema(schema)) {\n throw new Error(\n `giri: ${label} schema must be wrapped with a validator, e.g. \\`export const ${label} = zod(...)\\` from @boon4681/giri/validators/zod.`,\n );\n }\n return schema.validate(value);\n}\n\nexport async function prepareRequestInput(request: Request, input?: RouteInput): Promise<PreparedRequestInput> {\n const validated: ValidatedInput = {};\n\n if (input?.query) {\n const query = queryObject(new URL(request.url));\n const result = await runValidation(input.query, query, 'query');\n if (!result.ok) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid query parameters.', issues: result.issues },\n 400,\n 'json',\n ),\n };\n }\n validated.query = result.value;\n }\n\n if (input?.body) {\n const contents = input.body.contents as Record<BodyContentType, GiriInputSchema>;\n const declared = Object.keys(contents) as BodyContentType[];\n const requested = contentTypeFromHeader(request.headers.get('content-type'));\n // Pick the schema matching the request's content-type; fall back to JSON when the\n // header is missing/unrecognized but JSON is on offer (so header-less posts still work).\n const chosen: BodyContentType | undefined =\n requested && contents[requested] ? requested : contents.json ? 'json' : undefined;\n\n if (!chosen) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Unsupported media type.', issues: { accepted: declared } },\n 415,\n 'json',\n ),\n };\n }\n\n let rawBody: unknown;\n try {\n rawBody = await readRawBody(request, chosen);\n } catch (error) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid request body.', issues: error },\n 400,\n 'json',\n ),\n };\n }\n\n const result = await runValidation(contents[chosen], rawBody, 'body');\n if (!result.ok) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid request body.', issues: result.issues },\n 400,\n 'json',\n ),\n };\n }\n\n validated.body = declared.length > 1 ? { type: chosen, data: result.value } : result.value;\n }\n\n return { ok: true, validated };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { resolveGiriPaths } from '../app';\nimport {\n routeParamsForDir,\n scanRouteFolders,\n scanRoutes,\n sharedFilesForDir,\n type ScannedRoute,\n} from '../routes';\nimport type { GiriConfig, GiriPaths, HttpMethod } from '../types';\nimport { writeAppTypes } from './app-types';\nimport type { RouteInputSchemas } from './inputs';\nimport { writeManifest } from './manifest';\nimport { writeOpenApi } from './openapi';\nimport { writeParamTypes, type TypeFolder } from './param-types';\nimport { extractRouteMeta, type RouteOpenApiMeta, type RouteSecurity } from './route-meta';\nimport { writeRouteTypes } from './route-types';\nimport type { RouteResponses } from './schema';\nimport { writeTsConfig } from './tsconfig';\nimport { assertSafeOutDir, pruneDir, slash, typeFilePath } from './util';\nimport {\n readSyncCache,\n SYNC_CACHE_NAME,\n syncFingerprint,\n writeSyncCache,\n} from './cache';\n\n/** A `$types.d.ts` for every folder under `routes/` even empty/new ones. */\nasync function typeFolders(paths: GiriPaths, routes: ScannedRoute[]): Promise<TypeFolder[]> {\n // `scanRoutes` (tinyglobby) yields forward-slash paths while `scanRouteFolders` yields\n // native-separator paths, so key the map on a slash-normalized dir to match either form.\n const verbsByDir = new Map<string, { method: HttpMethod; file: string }[]>();\n for (const route of routes) {\n const key = slash(route.routeDir);\n const list = verbsByDir.get(key) ?? [];\n list.push({ method: route.method, file: route.file });\n verbsByDir.set(key, list);\n }\n\n const dirs = await scanRouteFolders(paths.routesDir);\n const sharedCache = new Map<string, string | undefined>();\n return dirs.map((dir) => ({\n dir,\n params: routeParamsForDir(paths.routesDir, dir),\n sharedFiles: sharedFilesForDir(paths.routesDir, dir, sharedCache),\n verbs: verbsByDir.get(slash(dir)) ?? [],\n }));\n}\n\n/** The per-route metadata maps feeding `manifest.json` / `openapi.json`. */\nexport interface SyncData {\n responsesByFile: Map<string, RouteResponses>;\n inputsByFile: Map<string, RouteInputSchemas>;\n securityByFile: Map<string, RouteSecurity>;\n hiddenFiles: Set<string>;\n openapiByFile: Map<string, RouteOpenApiMeta>;\n}\n\nexport interface SyncResult {\n paths: GiriPaths;\n routes: ScannedRoute[];\n folders: TypeFolder[];\n /** Aggregated route metadata, so a watcher can update one route and re-serialize. */\n data: SyncData;\n}\n\n/**\n * Walk each route's `handle` return type into per-status JSON Schema. Best-effort: a\n * broken project (or missing TypeScript) must not break `sync`, so failures yield an\n * empty map and the manifest simply omits `responses`.\n */\nasync function extractResponses(paths: GiriPaths, routes: ScannedRoute[]): Promise<Map<string, RouteResponses>> {\n const byFile = new Map<string, RouteResponses>();\n if (routes.length === 0) {\n return byFile;\n }\n\n try {\n const { createSchemaProgram, extractRouteResponses } = await import('./schema/index.js');\n const files = [...new Set(routes.map((route) => route.file))];\n // Include the generated global app.d.ts so `c.app` resolves to its real type.\n const appTypes = join(paths.outDir, 'types', 'app.d.ts');\n const roots = existsSync(appTypes) ? [...files, appTypes] : files;\n const program = createSchemaProgram(paths, roots);\n for (const file of files) {\n byFile.set(file, extractRouteResponses(program, file));\n }\n } catch (error) {\n console.warn(`giri: skipped response schema generation (${(error as Error).message}).`);\n }\n\n return byFile;\n}\n\ninterface RuntimeMeta {\n inputsByFile: Map<string, RouteInputSchemas>;\n securityByFile: Map<string, RouteSecurity>;\n hiddenFiles: Set<string>;\n openapiByFile: Map<string, RouteOpenApiMeta>;\n}\n\n/** Load route modules once to derive input schemas, middleware security, and openapi metadata. */\nasync function extractMeta(\n config: Pick<GiriConfig, 'alias'>,\n paths: GiriPaths,\n routes: ScannedRoute[],\n): Promise<RuntimeMeta> {\n const inputsByFile = new Map<string, RouteInputSchemas>();\n const securityByFile = new Map<string, RouteSecurity>();\n const hiddenFiles = new Set<string>();\n const openapiByFile = new Map<string, RouteOpenApiMeta>();\n if (routes.length === 0) {\n return { inputsByFile, securityByFile, hiddenFiles, openapiByFile };\n }\n\n try {\n const meta = await extractRouteMeta(config, paths, routes);\n for (const [file, entry] of meta) {\n if (entry.input) {\n inputsByFile.set(file, entry.input);\n }\n if (entry.security) {\n securityByFile.set(file, entry.security);\n }\n if (entry.hidden) {\n hiddenFiles.add(file);\n }\n if (entry.openapi) {\n openapiByFile.set(file, entry.openapi);\n }\n }\n } catch (error) {\n console.warn(`giri: skipped input/security generation (${(error as Error).message}).`);\n }\n\n return { inputsByFile, securityByFile, hiddenFiles, openapiByFile };\n}\n\n/**\n * Scan `routes/` and (re)generate the whole `.giri/` payload. Each artifact has its own\n * module under `src/generator/`. Files are overwritten **in place** (no upfront wipe), so\n * the editor never sees `tsconfig`/`$types` vanish during a slow regeneration; orphaned\n * files from removed routes are pruned at the end.\n */\nexport async function syncProject<App>(\n config: Pick<GiriConfig<App>, 'alias' | 'outDir'>,\n options: { cwd?: string } = {},\n): Promise<SyncResult> {\n const paths = resolveGiriPaths(config, options.cwd);\n assertSafeOutDir(paths);\n const hadOutDir = existsSync(paths.outDir);\n const routes = await scanRoutes(paths.routesDir);\n const folders = await typeFolders(paths, routes);\n const fingerprint = await syncFingerprint(config, paths);\n const cached = await readSyncCache(paths, fingerprint);\n\n const generatedFiles = [\n join(paths.outDir, 'tsconfig.json'),\n join(paths.outDir, 'manifest.json'),\n join(paths.outDir, 'openapi.json'),\n join(paths.outDir, 'routes.d.ts'),\n join(paths.outDir, 'types', 'app.d.ts'),\n ...folders.map((folder) => typeFilePath(paths, folder.dir)),\n ];\n if (cached && generatedFiles.every(existsSync)) {\n return { paths, routes, folders, data: cached };\n }\n\n await mkdir(paths.outDir, { recursive: true });\n await writeParamTypes(paths, folders);\n await writeRouteTypes(paths, routes);\n await writeAppTypes(paths);\n await writeTsConfig(paths, config);\n\n // Response schemas need the generated tsconfig + $types to resolve, so extract last.\n const data: SyncData = cached ?? {\n responsesByFile: await extractResponses(paths, routes),\n ...await extractMeta(config, paths, routes),\n };\n await writeManifest(paths, routes, data);\n await writeOpenApi(paths, routes, data);\n await writeSyncCache(paths, fingerprint, data);\n\n if (hadOutDir) {\n await pruneDir(\n paths.outDir,\n new Set([\n join(paths.outDir, 'tsconfig.json'),\n join(paths.outDir, 'manifest.json'),\n join(paths.outDir, 'openapi.json'),\n join(paths.outDir, 'routes.d.ts'),\n join(paths.outDir, SYNC_CACHE_NAME),\n join(paths.outDir, 'types', 'app.d.ts'),\n ...folders.map((folder) => typeFilePath(paths, folder.dir)),\n ]),\n );\n }\n\n return { paths, routes, folders, data };\n}\n","import { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { GiriPaths } from '../types';\nimport { GENERATED_HEADER, slash, writeGenerated } from './util';\n\nconst MAIN_EXTENSIONS = ['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'];\n\nfunction findMainFile(cwd: string): string | undefined {\n for (const ext of MAIN_EXTENSIONS) {\n const file = join(cwd, 'src', `main.${ext}`);\n if (existsSync(file)) {\n return file;\n }\n }\n return undefined;\n}\n\nfunction moduleSpecifier(fromDir: string, target: string): string {\n let path = slash(relative(fromDir, target)).replace(/\\.(?:[cm]?[jt]sx?)$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport async function writeAppTypes(paths: GiriPaths): Promise<void> {\n const file = join(paths.outDir, 'types', 'app.d.ts');\n const mainFile = findMainFile(paths.cwd);\n\n if (!mainFile) {\n await writeGenerated(file, [GENERATED_HEADER, 'export {};', ''].join('\\n'));\n return;\n }\n\n const spec = moduleSpecifier(join(paths.outDir, 'types'), mainFile);\n await writeGenerated(\n file,\n [\n GENERATED_HEADER,\n 'declare global {',\n ' namespace Giri {',\n ' interface Register {',\n ` app: typeof import(${JSON.stringify(spec)}) extends {`,\n ' init: (...args: any[]) => infer R;',\n ' }',\n ' ? Awaited<R>',\n ' : Record<string, unknown>;',\n ' }',\n ' }',\n '}',\n 'export {};',\n '',\n ].join('\\n'),\n );\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readdir, rm, rmdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type { GiriPaths } from '../types';\n\nexport const GENERATED_HEADER = '// Generated by giri sync. Do not edit.';\n\nexport function slash(path: string): string {\n return path.split(sep).join('/');\n}\n\nexport function importPath(fromFile: string, toFile: string): string {\n let path = slash(relative(dirname(fromFile), toFile)).replace(/\\.d\\.ts$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport function relativeConfigPath(fromDir: string, toPath: string): string {\n let path = slash(relative(fromDir, toPath));\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\n/** A relative ESM module specifier from `fromDir` to a source file (extension stripped). */\nexport function moduleSpecifier(fromDir: string, target: string): string {\n let path = slash(relative(fromDir, target)).replace(/\\.(?:[cm]?[jt]sx?)$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport function typeFilePath(paths: GiriPaths, routeDir: string): string {\n // Mirror the folder's source directory (relative to the project root) under\n // `<outDir>/types/`. Combined with `rootDirs: [\"..\", \"./types\"]`, this lets a file's\n const sourceDir = relative(paths.cwd, routeDir);\n return join(paths.outDir, 'types', sourceDir, '$types.d.ts');\n}\n\nexport function assertSafeOutDir(paths: GiriPaths): void {\n const rel = relative(paths.cwd, paths.outDir);\n if (!rel || rel.startsWith('..') || rel.includes(`..${sep}`)) {\n throw new Error(`Refusing to sync outside the project root: ${paths.outDir}`);\n }\n}\n\nconst writeCache = new Map<string, string>();\n\n/** Write a generated file, skipping the write when its content is unchanged and still on disk. */\nexport async function writeGenerated(path: string, content: string): Promise<void> {\n if (writeCache.get(path) === content && existsSync(path)) {\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content);\n writeCache.set(path, content);\n}\n\nexport async function writeJson(path: string, value: unknown): Promise<void> {\n await writeGenerated(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Remove generated files no longer in `keep`, plus any directories left empty. Lets sync\n * overwrite in place (no upfront wipe), so the editor never sees `tsconfig`/`$types`\n * disappear during a slow regeneration.\n */\nexport async function pruneDir(dir: string, keep: Set<string>): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n await pruneDir(full, keep);\n await rmdir(full).catch(() => {}); // succeeds only if now empty\n } else if (!keep.has(full)) {\n await rm(full, { force: true });\n writeCache.delete(full); // a recreated file with identical content must write again\n }\n }\n}\n","import { join, relative } from 'node:path';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport type { RouteInputSchemas } from './inputs';\nimport type { RouteSecurity } from './route-meta';\nimport type { RouteResponses } from './schema';\nimport { slash, typeFilePath, writeJson } from './util';\n\nexport interface ManifestData {\n responsesByFile?: Map<string, RouteResponses>;\n inputsByFile?: Map<string, RouteInputSchemas>;\n securityByFile?: Map<string, RouteSecurity>;\n hiddenFiles?: Set<string>;\n}\n\n/** Emits `manifest.json`: the machine-readable route table consumed by tooling. */\nexport async function writeManifest(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: ManifestData = {},\n): Promise<void> {\n const manifest = {\n version: 1,\n routes: routes.map((route) => {\n const responses = data.responsesByFile?.get(route.file);\n const input = data.inputsByFile?.get(route.file);\n const security = data.securityByFile?.get(route.file);\n return {\n method: route.method,\n path: route.path,\n file: slash(relative(paths.cwd, route.file)),\n params: route.params,\n shared: route.sharedFiles.map((file) => slash(relative(paths.cwd, file))),\n types: slash(relative(paths.cwd, typeFilePath(paths, route.routeDir))),\n ...(data.hiddenFiles?.has(route.file) ? { hidden: true } : {}),\n ...(input ? { input } : {}),\n ...(security && security.security.length > 0 ? { security: security.security } : {}),\n responses: responses?.responses ?? [],\n ...(responses && Object.keys(responses.$defs).length > 0\n ? { $defs: responses.$defs }\n : {}),\n };\n }),\n };\n\n await writeJson(join(paths.outDir, 'manifest.json'), manifest);\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport type { RouteInputSchemas } from './inputs';\nimport type { RouteOpenApiMeta, RouteSecurity } from './route-meta';\nimport type { JSONSchema, ResponseSchema, RouteResponses } from './schema';\nimport { writeJson } from './util';\n\nexport interface OpenApiData {\n responsesByFile?: Map<string, RouteResponses>;\n inputsByFile?: Map<string, RouteInputSchemas>;\n securityByFile?: Map<string, RouteSecurity>;\n hiddenFiles?: Set<string>;\n openapiByFile?: Map<string, RouteOpenApiMeta>;\n}\n\ntype JsonObject = Record<string, unknown>;\n\nconst REASON: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n};\n\nfunction toOpenApiPath(path: string): string {\n return path.replace(/:([A-Za-z0-9_]+)(?:\\{[^}]*\\})?/g, '{$1}');\n}\n\n/** Rewrite walker-local `#/$defs/X` refs to the document-level `#/components/schemas/X`. */\nfunction rewriteRefs(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(rewriteRefs);\n }\n if (value && typeof value === 'object') {\n const out: JsonObject = {};\n for (const [key, child] of Object.entries(value)) {\n if (key === '$ref' && typeof child === 'string' && child.startsWith('#/$defs/')) {\n out.$ref = child.replace('#/$defs/', '#/components/schemas/');\n } else {\n out[key] = rewriteRefs(child);\n }\n }\n return out;\n }\n return value;\n}\n\nfunction mediaTypeFor(format: 'json' | 'text'): string {\n return format === 'text' ? 'text/plain' : 'application/json';\n}\n\nconst BODY_MEDIA_TYPE: Record<string, string> = {\n json: 'application/json',\n form: 'multipart/form-data',\n urlencoded: 'application/x-www-form-urlencoded',\n text: 'text/plain',\n};\n\nfunction buildResponses(responses: ResponseSchema[]): JsonObject {\n if (responses.length === 0) {\n return { default: { description: 'Response' } };\n }\n\n const out: JsonObject = {};\n for (const response of responses) {\n const key = response.status === 'default' ? 'default' : String(response.status);\n const description =\n (typeof response.status === 'number' && REASON[response.status]) || 'Response';\n out[key] = {\n description,\n content: { [mediaTypeFor(response.format)]: { schema: rewriteRefs(response.schema) } },\n };\n }\n return out;\n}\n\nfunction pathParameters(route: ScannedRoute): JsonObject[] {\n const seen = new Set<string>();\n const params: JsonObject[] = [];\n for (const param of route.params) {\n if (seen.has(param.name)) {\n continue;\n }\n seen.add(param.name);\n params.push({ name: param.name, in: 'path', required: true, schema: { type: 'string' } });\n }\n return params;\n}\n\nfunction queryParameters(query: JSONSchema | undefined): JsonObject[] {\n if (!query || query.type !== 'object' || typeof query.properties !== 'object') {\n return [];\n }\n const properties = query.properties as Record<string, JSONSchema>;\n const required = Array.isArray(query.required) ? (query.required as string[]) : [];\n return Object.entries(properties).map(([name, schema]) => ({\n name,\n in: 'query',\n required: required.includes(name),\n schema: rewriteRefs(schema),\n }));\n}\n\nfunction readProjectInfo(cwd: string): { title: string; version: string } {\n const file = join(cwd, 'package.json');\n if (existsSync(file)) {\n try {\n const pkg = JSON.parse(readFileSync(file, 'utf8')) as { name?: string; version?: string };\n return { title: pkg.name ?? 'giri API', version: pkg.version ?? '0.0.0' };\n } catch {\n // fall through to defaults\n }\n }\n return { title: 'giri API', version: '0.0.0' };\n}\n\n/** Assemble an OpenAPI 3.1 document from the scanned routes + generated schemas. */\nexport function buildOpenApiDocument(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: OpenApiData = {},\n): OpenAPIV3_1.Document {\n const documentPaths: JsonObject = {};\n const schemas: JsonObject = {};\n const securitySchemes: JsonObject = {};\n const tagOrder: string[] = [];\n\n for (const route of routes) {\n if (data.hiddenFiles?.has(route.file)) {\n continue; // excluded from the doc via `openapi`/`+shared.ts`\n }\n const responses = data.responsesByFile?.get(route.file);\n const input = data.inputsByFile?.get(route.file);\n const security = data.securityByFile?.get(route.file);\n const meta = data.openapiByFile?.get(route.file);\n\n for (const [name, schema] of Object.entries(responses?.$defs ?? {})) {\n schemas[name] = rewriteRefs(schema);\n }\n\n const operation: JsonObject = {};\n if (meta?.tags && meta.tags.length > 0) {\n operation.tags = meta.tags;\n for (const tag of meta.tags) {\n if (!tagOrder.includes(tag)) {\n tagOrder.push(tag);\n }\n }\n }\n if (meta?.summary) {\n operation.summary = meta.summary;\n }\n if (meta?.description) {\n operation.description = meta.description;\n }\n if (meta?.operationId) {\n operation.operationId = meta.operationId;\n }\n if (meta?.deprecated) {\n operation.deprecated = true;\n }\n operation.responses = buildResponses(responses?.responses ?? []);\n\n const parameters = [...pathParameters(route), ...queryParameters(input?.query)];\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n if (input?.body) {\n const content: JsonObject = {};\n for (const [contentType, schema] of Object.entries(input.body)) {\n content[BODY_MEDIA_TYPE[contentType] ?? contentType] = {\n schema: rewriteRefs(schema),\n };\n }\n if (Object.keys(content).length > 0) {\n operation.requestBody = { required: true, content };\n }\n }\n if (security && security.security.length > 0) {\n operation.security = security.security;\n }\n if (security) {\n Object.assign(securitySchemes, security.securitySchemes);\n }\n\n const openApiPath = toOpenApiPath(route.path);\n const pathItem = (documentPaths[openApiPath] as JsonObject) ?? {};\n pathItem[route.method.toLowerCase()] = operation;\n documentPaths[openApiPath] = pathItem;\n }\n\n const document: JsonObject = {\n openapi: '3.1.0',\n info: readProjectInfo(paths.cwd),\n paths: documentPaths,\n };\n if (tagOrder.length > 0) {\n document.tags = tagOrder.map((name) => ({ name }));\n }\n const components: JsonObject = {};\n if (Object.keys(schemas).length > 0) {\n components.schemas = schemas;\n }\n if (Object.keys(securitySchemes).length > 0) {\n components.securitySchemes = securitySchemes;\n }\n if (Object.keys(components).length > 0) {\n document.components = components;\n }\n return document as unknown as OpenAPIV3_1.Document;\n}\n\n/** Emit `.giri/openapi.json`. */\nexport async function writeOpenApi(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: OpenApiData = {},\n): Promise<void> {\n await writeJson(join(paths.outDir, 'openapi.json'), buildOpenApiDocument(paths, routes, data));\n}\n","import { dirname } from 'node:path';\nimport type { RouteParam } from '../routes';\nimport type { GiriPaths, HttpMethod } from '../types';\nimport { GENERATED_HEADER, importPath, moduleSpecifier, typeFilePath, writeGenerated } from './util';\n\nexport interface TypeFolder {\n dir: string;\n params: RouteParam[];\n /** The `+shared.ts` chain whose injected vars apply here. */\n sharedFiles: string[];\n /** The verb files (`+get.ts`, `+post.ts`, …) in this folder, one method-named handle each. */\n verbs: { method: HttpMethod; file: string }[];\n}\n\nfunction paramsType(params: RouteParam[]): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const unique = new Map<string, RouteParam>();\n for (const param of params) {\n unique.set(param.name, param);\n }\n\n const fields = [...unique.values()]\n .map((param) => ` ${JSON.stringify(param.name)}: string;`)\n .join('\\n');\n return `{\\n${fields}\\n}`;\n}\n\n/** Merge the injected vars of the folder's `+shared.ts` middleware chain */\nfunction middlewareVarsType(typesDir: string, sharedFile: string): string {\n const spec = JSON.stringify(moduleSpecifier(typesDir, sharedFile));\n return `(typeof import(${spec}) extends { middleware: infer M } ? import(\"@boon4681/giri\").InferStackVars<M> : {})`;\n}\n\nfunction ownSharedFile(dir: string, sharedFiles: string[]): string | undefined {\n for (let index = sharedFiles.length - 1; index >= 0; index -= 1) {\n if (dirname(sharedFiles[index]) === dir) {\n return sharedFiles[index];\n }\n }\n return undefined;\n}\n\nfunction varsType(paths: GiriPaths, file: string, dir: string, sharedFiles: string[]): string {\n const typesDir = dirname(file);\n const parts: string[] = [];\n if (dir !== paths.routesDir) {\n parts.push(`import(${JSON.stringify(importPath(file, typeFilePath(paths, dirname(dir))))}).Vars`);\n }\n\n const ownShared = ownSharedFile(dir, sharedFiles);\n if (ownShared) {\n parts.push(middlewareVarsType(typesDir, ownShared));\n }\n\n return parts.length > 0 ? parts.join('\\n & ') : '{}';\n}\n\nfunction methodExports(typesDir: string, verbs: TypeFolder['verbs']): string[] {\n return verbs.map(({ method, file }) => {\n const spec = JSON.stringify(moduleSpecifier(typesDir, file));\n const input = `import(\"@boon4681/giri\").RouteInputOf<typeof import(${spec})>`;\n const vars = `Vars & import(\"@boon4681/giri\").MiddlewareVarsOf<typeof import(${spec})>`;\n return `export type ${method} = import(\"@boon4681/giri\").Handle<Params, ${input}, ${vars}>;`;\n });\n}\n\nexport async function writeParamTypes(paths: GiriPaths, folders: TypeFolder[]): Promise<void> {\n await Promise.all(folders.map(({ dir, params, sharedFiles, verbs }) => {\n const file = typeFilePath(paths, dir);\n const typesDir = dirname(file);\n const lines = [\n GENERATED_HEADER,\n `export type Params = ${paramsType(params)};`,\n 'export type RouteParams = Params;',\n `export type Vars = ${varsType(paths, file, dir, sharedFiles)};`,\n 'export type Middleware<Injects extends Record<string, unknown> = {}> =',\n ' import(\"@boon4681/giri\").Middleware<Params, import(\"@boon4681/giri\").ValidatedInput, Injects>;',\n 'export type Handle<Input extends import(\"@boon4681/giri\").ValidatedInput = import(\"@boon4681/giri\").ValidatedInput> =',\n ' import(\"@boon4681/giri\").Handle<Params, Input, Vars>;',\n ];\n if (verbs.length > 0) {\n lines.push(...methodExports(typesDir, verbs));\n }\n lines.push('');\n return writeGenerated(file, lines.join('\\n'));\n }));\n}\n","import { readFileSync } from 'node:fs';\nimport ts from 'typescript';\nimport { registerAliasResolver } from '../app';\nimport { safeRegister } from '../loader/loader';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriConfig, GiriPaths, Middleware, SecurityRequirement } from '../types';\nimport { bodyToJsonSchemas, inputToJsonSchema, type RouteInputSchemas } from './inputs';\n\nexport interface RouteSecurity {\n /** Operation-level `security` requirements, e.g. `[{ bearerAuth: [] }]`. */\n security: SecurityRequirement[];\n /** Scheme definitions to merge into `components.securitySchemes`. */\n securitySchemes: Record<string, unknown>;\n}\n\n/** Resolved OpenAPI operation metadata (everything on `openapi` except `hidden`). */\nexport interface RouteOpenApiMeta {\n tags?: string[];\n summary?: string;\n description?: string;\n deprecated?: boolean;\n operationId?: string;\n}\n\nexport interface RouteMeta {\n input?: RouteInputSchemas;\n security?: RouteSecurity;\n /** Excluded from `openapi.json` (via `openapi`/`+shared.ts` resolution). */\n hidden?: boolean;\n /** Operation metadata (tags/summary/…) resolved down the `+shared.ts` chain. */\n openapi?: RouteOpenApiMeta;\n}\n\ntype StaticOpenApi =\n | boolean\n | {\n hidden?: boolean;\n tags?: string[];\n summary?: string;\n description?: string;\n deprecated?: boolean;\n operationId?: string;\n };\n\ninterface StaticModuleMeta {\n openapi?: StaticOpenApi;\n middlewareSecurity: boolean;\n}\n\nfunction loadModule(file: string): Record<string, unknown> {\n const resolved = require.resolve(file);\n delete require.cache[resolved];\n return require(resolved) as Record<string, unknown>;\n}\n\nfunction interopDefault(value: unknown): unknown {\n if (value && typeof value === 'object' && 'default' in value) {\n return (value as { default: unknown }).default;\n }\n return value;\n}\n\nfunction middlewareFunctions(value: unknown): Middleware[] {\n const exported = interopDefault(value);\n if (typeof exported === 'function') {\n return [exported as Middleware];\n }\n if (Array.isArray(exported)) {\n return exported.filter((fn): fn is Middleware => typeof fn === 'function');\n }\n return [];\n}\n\nfunction readInput(routeModule: Record<string, unknown>): RouteInputSchemas | undefined {\n const input: RouteInputSchemas = {};\n const body = bodyToJsonSchemas(routeModule.body);\n const query = inputToJsonSchema(routeModule.query);\n if (body) {\n input.body = body;\n }\n if (query) {\n input.query = query;\n }\n return input.body || input.query ? input : undefined;\n}\n\nfunction hasExportModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (\n ts.isParenthesizedExpression(current) ||\n ts.isAsExpression(current) ||\n ts.isSatisfiesExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction staticBoolean(expression: ts.Expression): boolean | undefined {\n const value = unwrapExpression(expression);\n if (value.kind === ts.SyntaxKind.TrueKeyword) {\n return true;\n }\n if (value.kind === ts.SyntaxKind.FalseKeyword) {\n return false;\n }\n return undefined;\n}\n\nfunction staticString(expression: ts.Expression): string | undefined {\n const value = unwrapExpression(expression);\n return ts.isStringLiteralLike(value) ? value.text : undefined;\n}\n\nfunction staticStringArray(expression: ts.Expression): string[] | undefined {\n const value = unwrapExpression(expression);\n if (!ts.isArrayLiteralExpression(value)) {\n return undefined;\n }\n\n const strings: string[] = [];\n for (const element of value.elements) {\n const string = staticString(element);\n if (string === undefined) {\n return undefined;\n }\n strings.push(string);\n }\n return strings;\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return undefined;\n}\n\nfunction collectImportedNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if (!ts.isImportDeclaration(statement)) {\n continue;\n }\n const clause = statement.importClause;\n if (!clause) {\n continue;\n }\n if (clause.name) {\n names.add(clause.name.text);\n }\n const bindings = clause.namedBindings;\n if (bindings && ts.isNamespaceImport(bindings)) {\n names.add(bindings.name.text);\n }\n if (bindings && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) {\n names.add(element.name.text);\n }\n }\n }\n return names;\n}\n\nfunction expressionReferencesImportedMiddleware(expression: ts.Expression, importedNames: Set<string>): boolean {\n let found = false;\n const allowedImportedHelpers = new Set(['stack', 'fromHono']);\n const visit = (node: ts.Node): void => {\n if (found) {\n return;\n }\n if (ts.isIdentifier(node) && importedNames.has(node.text) && !allowedImportedHelpers.has(node.text)) {\n found = true;\n return;\n }\n ts.forEachChild(node, visit);\n };\n visit(expression);\n return found;\n}\n\nfunction parseStaticOpenApi(expression: ts.Expression): StaticOpenApi | undefined {\n const value = unwrapExpression(expression);\n const boolean = staticBoolean(value);\n if (boolean !== undefined) {\n return boolean;\n }\n if (!ts.isObjectLiteralExpression(value)) {\n return undefined;\n }\n\n const openapi: Exclude<StaticOpenApi, boolean> = {};\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property)) {\n return undefined;\n }\n const name = propertyName(property.name);\n if (!name) {\n return undefined;\n }\n if (name === 'hidden') {\n const hidden = staticBoolean(property.initializer);\n if (hidden === undefined) {\n return undefined;\n }\n openapi.hidden = hidden;\n } else if (name === 'tags') {\n const tags = staticStringArray(property.initializer);\n if (!tags) {\n return undefined;\n }\n openapi.tags = tags;\n } else if (name === 'summary' || name === 'description' || name === 'operationId') {\n const string = staticString(property.initializer);\n if (string === undefined) {\n return undefined;\n }\n openapi[name] = string;\n } else if (name === 'deprecated') {\n const deprecated = staticBoolean(property.initializer);\n if (deprecated === undefined) {\n return undefined;\n }\n openapi.deprecated = deprecated;\n } else {\n return undefined;\n }\n }\n\n return openapi;\n}\n\nfunction readStaticModuleMeta(file: string): StaticModuleMeta | undefined {\n let source: ts.SourceFile;\n try {\n source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);\n } catch {\n return undefined;\n }\n\n const importedNames = collectImportedNames(source);\n const sourceText = source.getFullText();\n const canSkipMiddlewareRuntime =\n !sourceText.includes('defineMiddleware') &&\n !sourceText.includes('.openapi');\n const meta: StaticModuleMeta = { middlewareSecurity: false };\n for (const statement of source.statements) {\n if (\n ts.isImportDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement) ||\n ts.isEmptyStatement(statement) ||\n !hasExportModifier(statement)\n ) {\n continue;\n }\n\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === 'handle') {\n continue;\n }\n\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) {\n return undefined;\n }\n const name = declaration.name.text;\n if (name === 'openapi') {\n if (!declaration.initializer) {\n return undefined;\n }\n const openapi = parseStaticOpenApi(declaration.initializer);\n if (openapi === undefined) {\n return undefined;\n }\n meta.openapi = openapi;\n } else if (name === 'handle') {\n if (\n !declaration.initializer ||\n (!ts.isArrowFunction(declaration.initializer) &&\n !ts.isFunctionExpression(declaration.initializer))\n ) {\n return undefined;\n }\n continue;\n } else if (name === 'middleware') {\n if (\n !declaration.initializer ||\n !canSkipMiddlewareRuntime ||\n expressionReferencesImportedMiddleware(declaration.initializer, importedNames)\n ) {\n return undefined;\n }\n meta.middlewareSecurity = false;\n continue;\n } else {\n return undefined;\n }\n }\n continue;\n }\n\n return undefined;\n }\n\n return meta;\n}\n\nfunction resolveStaticOpenApi(route: ScannedRoute, routeModule: StaticModuleMeta, loadShared: (file: string) => StaticModuleMeta | undefined): { hidden: boolean; meta: RouteOpenApiMeta } | undefined {\n let hidden = false;\n const tags: string[] = [];\n const meta: RouteOpenApiMeta = {};\n\n const apply = (value: StaticOpenApi | undefined, isVerb: boolean): void => {\n if (value === false) {\n hidden = true;\n return;\n }\n if (value === true) {\n hidden = false;\n return;\n }\n if (!value) {\n return;\n }\n if (typeof value.hidden === 'boolean') {\n hidden = value.hidden;\n }\n if (value.tags) {\n tags.push(...value.tags);\n }\n if (typeof value.summary === 'string') {\n meta.summary = value.summary;\n }\n if (typeof value.description === 'string') {\n meta.description = value.description;\n }\n if (typeof value.deprecated === 'boolean') {\n meta.deprecated = value.deprecated;\n }\n if (isVerb && typeof value.operationId === 'string') {\n meta.operationId = value.operationId;\n }\n };\n\n for (const file of route.sharedFiles) {\n const shared = loadShared(file);\n if (!shared) {\n return undefined;\n }\n apply(shared.openapi, false);\n }\n apply(routeModule.openapi, true);\n\n if (tags.length > 0) {\n meta.tags = [...new Set(tags)];\n }\n return { hidden, meta };\n}\n\nfunction extractStaticMeta(\n route: ScannedRoute,\n routeModule: StaticModuleMeta,\n loadShared: (file: string) => StaticModuleMeta | undefined,\n): RouteMeta | undefined {\n const openapi = resolveStaticOpenApi(route, routeModule, loadShared);\n if (!openapi) {\n return undefined;\n }\n\n const meta: RouteMeta = {};\n if (openapi.hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi.meta).length > 0) {\n meta.openapi = openapi.meta;\n }\n return meta;\n}\n\nfunction extractRuntimeSharedMeta(\n route: ScannedRoute,\n routeModule: StaticModuleMeta,\n loadShared: (file: string) => Record<string, unknown>,\n): RouteMeta {\n const meta: RouteMeta = {};\n const security = collectSecurity(route, {}, loadShared);\n const { hidden, meta: openapi } = resolveOpenApi(route, { openapi: routeModule.openapi }, loadShared);\n if (security) {\n meta.security = security;\n }\n if (hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi).length > 0) {\n meta.openapi = openapi;\n }\n return meta;\n}\n\n/**\n * Resolve the `openapi` export down a route's `+shared.ts` chain. `tags` are\n * merged and de-duplicated so a folder groups its routes; scalar fields (summary/description/\n * deprecated) override (verb wins); `operationId` is taken only from the verb file.\n */\nfunction resolveOpenApi(\n route: ScannedRoute,\n routeModule: Record<string, unknown>,\n loadShared: (file: string) => Record<string, unknown>,\n): { hidden: boolean; meta: RouteOpenApiMeta } {\n let hidden = false;\n const tags: string[] = [];\n const meta: RouteOpenApiMeta = {};\n\n const apply = (value: unknown, isVerb: boolean): void => {\n if (value === false) {\n hidden = true;\n return;\n }\n if (value === true) {\n hidden = false;\n return;\n }\n if (!value || typeof value !== 'object') {\n return;\n }\n const o = value as Record<string, unknown>;\n if ('hidden' in o) {\n hidden = Boolean(o.hidden);\n }\n if (Array.isArray(o.tags)) {\n tags.push(...o.tags.filter((tag): tag is string => typeof tag === 'string'));\n }\n if (typeof o.summary === 'string') {\n meta.summary = o.summary;\n }\n if (typeof o.description === 'string') {\n meta.description = o.description;\n }\n if (typeof o.deprecated === 'boolean') {\n meta.deprecated = o.deprecated;\n }\n if (isVerb && typeof o.operationId === 'string') {\n meta.operationId = o.operationId;\n }\n };\n\n for (const file of route.sharedFiles) {\n apply(loadShared(file).openapi, false);\n }\n apply(routeModule.openapi, true);\n\n if (tags.length > 0) {\n meta.tags = [...new Set(tags)];\n }\n return { hidden, meta };\n}\n\nfunction collectSecurity(\n route: ScannedRoute,\n routeModule: Record<string, unknown>,\n loadShared: (file: string) => Record<string, unknown>,\n): RouteSecurity | undefined {\n const skipInherited = Boolean(\n (routeModule.config as { skipInherited?: boolean } | undefined)?.skipInherited,\n );\n\n const middleware: Middleware[] = [];\n if (!skipInherited) {\n for (const file of route.sharedFiles) {\n middleware.push(...middlewareFunctions(loadShared(file).middleware));\n }\n }\n middleware.push(...middlewareFunctions(routeModule.middleware));\n\n const security: SecurityRequirement[] = [];\n const securitySchemes: Record<string, unknown> = {};\n for (const fn of middleware) {\n const openapi = fn.openapi;\n if (openapi?.security) {\n for (const requirement of openapi.security) {\n if (!security.some((seen) => JSON.stringify(seen) === JSON.stringify(requirement))) {\n security.push(requirement);\n }\n }\n }\n if (openapi?.securitySchemes) {\n Object.assign(securitySchemes, openapi.securitySchemes);\n }\n }\n\n return security.length > 0 || Object.keys(securitySchemes).length > 0\n ? { security, securitySchemes }\n : undefined;\n}\n\n/**\n * Load each route module once (with import aliases active) to derive runtime metadata:\n * input JSON Schemas from `body`/`query`, and OpenAPI `security` from the middleware\n * actually applied to the route (folder chain + verb, honoring `skipInherited`).\n */\nexport async function extractRouteMeta(\n config: Pick<GiriConfig, 'alias'>,\n paths: GiriPaths,\n routes: ScannedRoute[],\n): Promise<Map<string, RouteMeta>> {\n const byFile = new Map<string, RouteMeta>();\n const remainingRoutes: ScannedRoute[] = [];\n const runtimeSharedRoutes: { route: ScannedRoute; routeModule: StaticModuleMeta }[] = [];\n const staticCache = new Map<string, StaticModuleMeta | undefined>();\n const loadStatic = (file: string): StaticModuleMeta | undefined => {\n if (!staticCache.has(file)) {\n staticCache.set(file, readStaticModuleMeta(file));\n }\n return staticCache.get(file);\n };\n\n for (const route of routes) {\n const routeModule = loadStatic(route.file);\n if (!routeModule) {\n remainingRoutes.push(route);\n continue;\n }\n const meta = extractStaticMeta(route, routeModule, loadStatic);\n if (meta) {\n if (meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n continue;\n }\n runtimeSharedRoutes.push({ route, routeModule });\n }\n\n if (remainingRoutes.length === 0 && runtimeSharedRoutes.length === 0) {\n return byFile;\n }\n\n const { unregister } = await safeRegister();\n const unregisterAlias = registerAliasResolver(config.alias, paths.cwd);\n const sharedCache = new Map<string, Record<string, unknown>>();\n const loadShared = (file: string): Record<string, unknown> => {\n if (!sharedCache.has(file)) {\n try {\n sharedCache.set(file, loadModule(file));\n } catch {\n sharedCache.set(file, {});\n }\n }\n return sharedCache.get(file)!;\n };\n\n try {\n for (const { route, routeModule } of runtimeSharedRoutes) {\n const meta = extractRuntimeSharedMeta(route, routeModule, loadShared);\n if (meta.input || meta.security || meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n }\n for (const route of remainingRoutes) {\n try {\n const routeModule = loadModule(route.file);\n const meta: RouteMeta = {};\n const input = readInput(routeModule);\n const security = collectSecurity(route, routeModule, loadShared);\n const { hidden, meta: openapi } = resolveOpenApi(route, routeModule, loadShared);\n if (input) {\n meta.input = input;\n }\n if (security) {\n meta.security = security;\n }\n if (hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi).length > 0) {\n meta.openapi = openapi;\n }\n if (meta.input || meta.security || meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n } catch {\n // A route that fails to load just contributes no metadata.\n }\n }\n } finally {\n unregisterAlias();\n unregister();\n }\n\n return byFile;\n}\n","import { isGiriBodySchema, isGiriInputSchema } from '../validation';\nimport type { BodyContentType } from '../types';\nimport type { JSONSchema } from './schema';\n\nexport interface RouteInputSchemas {\n /** JSON Schema per declared body content-type (`json`, `form`, …). */\n body?: Partial<Record<BodyContentType, JSONSchema>>;\n query?: JSONSchema;\n}\n\nfunction sanitize(schema: JSONSchema): JSONSchema {\n // `$schema` is meaningful standalone but noise once embedded in OpenAPI.\n const { $schema, ...rest } = schema;\n void $schema;\n return rest;\n}\n\n/**\n * Convert a declared input to JSON Schema by asking the wrapper.\n */\nexport function inputToJsonSchema(schema: unknown): JSONSchema | undefined {\n if (!isGiriInputSchema(schema)) {\n return undefined;\n }\n return sanitize(schema.toJsonSchema());\n}\n\n/**\n * Convert a declared body (`zod.body({ json, form })`) to a JSON Schema per content-type.\n * Returns `undefined` when the value isn't a giri body schema or carries no schemas.\n */\nexport function bodyToJsonSchemas(\n value: unknown,\n): Partial<Record<BodyContentType, JSONSchema>> | undefined {\n if (!isGiriBodySchema(value)) {\n return undefined;\n }\n const out: Partial<Record<BodyContentType, JSONSchema>> = {};\n for (const [contentType, schema] of Object.entries(value.contents)) {\n const json = inputToJsonSchema(schema);\n if (json) {\n out[contentType as BodyContentType] = json;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n","import { join } from 'node:path';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport { GENERATED_HEADER, importPath, typeFilePath, writeGenerated } from './util';\n\n/** Emits `routes.d.ts`: a `RouteParams` map keyed by `\"METHOD path\"` for the whole app. */\nexport async function writeRouteTypes(paths: GiriPaths, routes: ScannedRoute[]): Promise<void> {\n const file = join(paths.outDir, 'routes.d.ts');\n const lines = [\n GENERATED_HEADER,\n 'export interface RouteParams {',\n ];\n\n for (const route of routes) {\n const typeFile = typeFilePath(paths, route.routeDir);\n lines.push(\n ` ${JSON.stringify(`${route.method} ${route.path}`)}: import(${JSON.stringify(\n importPath(file, typeFile),\n )}).Params;`,\n );\n }\n\n lines.push('}', '');\n await writeGenerated(file, lines.join('\\n'));\n}\n","import { join, resolve } from 'node:path';\nimport type { GiriConfig, GiriPaths } from '../types';\nimport { relativeConfigPath, writeJson } from './util';\n\nfunction normalizeAlias(alias: GiriConfig['alias'], paths: GiriPaths): Record<string, string[]> {\n const result: Record<string, string[]> = {};\n for (const [key, value] of Object.entries(alias ?? {})) {\n const targets = Array.isArray(value) ? value : [value];\n // Alias values are written relative to the project root (the same base the\n // runtime resolver in app.ts uses), but the generated tsconfig lives in\n // outDir, so re-base each target onto outDir to keep them relative.\n result[key] = targets.map((target) =>\n relativeConfigPath(paths.outDir, resolve(paths.cwd, target)),\n );\n }\n return result;\n}\n\n/** Emits the `.giri/tsconfig.json` the project extends: rootDirs merge, aliases, plugin. */\nexport async function writeTsConfig(paths: GiriPaths, config: Pick<GiriConfig, 'alias'>): Promise<void> {\n const file = join(paths.outDir, 'tsconfig.json');\n await writeJson(file, {\n compilerOptions: {\n rootDirs: [\n '..',\n './types',\n ],\n paths: {\n // The tsconfig lives in outDir, so `$giri/*` maps to its own folder.\n '$giri/*': ['./*'],\n ...normalizeAlias(config.alias, paths),\n },\n plugins: [\n {\n name: '@boon4681/giri/tsc',\n },\n ],\n },\n include: [\n relativeConfigPath(paths.outDir, join(paths.cwd, 'src')),\n relativeConfigPath(paths.outDir, join(paths.cwd, 'giri.config.ts')),\n './types/**/*.d.ts',\n ],\n });\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, relative, resolve, sep } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport type { GiriConfig, GiriPaths } from '../types';\nimport type { SyncData } from './sync';\nimport { slash, writeJson } from './util';\n\nconst CACHE_VERSION = 1;\nexport const SYNC_CACHE_NAME = '.sync-cache.json';\n\ninterface SyncCache {\n version: number;\n fingerprint: string;\n data: {\n responsesByFile: [string, unknown][];\n inputsByFile: [string, unknown][];\n securityByFile: [string, unknown][];\n hiddenFiles: string[];\n openapiByFile: [string, unknown][];\n };\n}\n\nfunction stableConfig(config: Pick<GiriConfig, 'alias' | 'outDir'>): unknown {\n const alias = Object.entries(config.alias ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]);\n return { alias, outDir: config.outDir ?? '.giri' };\n}\n\n/** Hash inputs that can affect generated route types, schemas, or OpenAPI metadata. */\nexport async function syncFingerprint(\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\n paths: GiriPaths,\n): Promise<string> {\n const outRelative = slash(relative(paths.cwd, paths.outDir));\n const ignore = ['**/node_modules/**', '**/.git/**'];\n if (outRelative && !outRelative.startsWith('..')) {\n ignore.push(`${outRelative}/**`);\n }\n\n const files = await glob([\n 'src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json}',\n 'giri.config.{ts,js,mts,cts,mjs,cjs}',\n 'tsconfig*.json',\n 'package.json',\n 'package-lock.json',\n 'npm-shrinkwrap.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'bun.lock',\n 'bun.lockb',\n ], {\n cwd: paths.cwd,\n absolute: false,\n onlyFiles: true,\n dot: true,\n ignore,\n });\n\n const hash = createHash('sha256');\n hash.update(JSON.stringify(stableConfig(config)));\n for (const file of files.sort()) {\n hash.update('\\0');\n hash.update(slash(file));\n hash.update('\\0');\n hash.update(await readFile(resolve(paths.cwd, file)));\n }\n return hash.digest('hex');\n}\n\nfunction cachePath(paths: GiriPaths): string {\n return join(paths.outDir, SYNC_CACHE_NAME);\n}\n\nfunction serializePath(paths: GiriPaths, file: string): string {\n return slash(relative(paths.cwd, file));\n}\n\nfunction deserializePath(paths: GiriPaths, file: string): string {\n return slash(resolve(paths.cwd, file.split('/').join(sep)));\n}\n\nfunction serializeMap<T>(paths: GiriPaths, values: Map<string, T>): [string, T][] {\n return [...values].map(([file, value]) => [serializePath(paths, file), value]);\n}\n\nfunction deserializeMap<T>(paths: GiriPaths, values: [string, T][]): Map<string, T> {\n return new Map(values.map(([file, value]) => [deserializePath(paths, file), value]));\n}\n\nexport async function readSyncCache(\n paths: GiriPaths,\n fingerprint: string,\n): Promise<SyncData | undefined> {\n const file = cachePath(paths);\n if (!existsSync(file)) {\n return undefined;\n }\n\n try {\n const cache = JSON.parse(await readFile(file, 'utf8')) as SyncCache;\n if (cache.version !== CACHE_VERSION || cache.fingerprint !== fingerprint) {\n return undefined;\n }\n return {\n responsesByFile: deserializeMap(paths, cache.data.responsesByFile),\n inputsByFile: deserializeMap(paths, cache.data.inputsByFile),\n securityByFile: deserializeMap(paths, cache.data.securityByFile),\n hiddenFiles: new Set(cache.data.hiddenFiles.map((entry) => deserializePath(paths, entry))),\n openapiByFile: deserializeMap(paths, cache.data.openapiByFile),\n } as SyncData;\n } catch {\n return undefined;\n }\n}\n\nexport async function writeSyncCache(\n paths: GiriPaths,\n fingerprint: string,\n data: SyncData,\n): Promise<void> {\n const cache: SyncCache = {\n version: CACHE_VERSION,\n fingerprint,\n data: {\n responsesByFile: serializeMap(paths, data.responsesByFile),\n inputsByFile: serializeMap(paths, data.inputsByFile),\n securityByFile: serializeMap(paths, data.securityByFile),\n hiddenFiles: [...data.hiddenFiles].map((file) => serializePath(paths, file)),\n openapiByFile: serializeMap(paths, data.openapiByFile),\n },\n };\n await writeJson(cachePath(paths), cache);\n}\n","import { existsSync, statSync } from 'node:fs';\r\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { buildImportGraph } from '../loader/import-graph';\r\nimport {\r\n collectDependents,\r\n purgeGeneratedModules,\r\n purgeModules,\r\n purgeProjectModules,\r\n} from '../loader/module-loader';\r\nimport {\n assertRouteHandleExport,\n assertSourceSyntax,\n type ScannedRoute,\n} from '../routes';\nimport type { GiriConfig } from '../types';\r\nimport { writeManifest } from './manifest';\nimport { writeOpenApi } from './openapi';\nimport { extractRouteMeta } from './route-meta';\nimport { syncFingerprint, writeSyncCache } from './cache';\nimport { syncProject, type SyncResult } from './sync';\nimport { slash } from './util';\n\r\nexport type ChangeOutcome = 'incremental' | 'full' | 'skip';\n\nexport interface WatchApplyOptions {\n /** Let runtime HMR continue while OpenAPI/response metadata refreshes in the background. */\n deferMetadata?: boolean;\n}\n\nexport interface WatchUpdater {\n /**\r\n * Apply one watch event. Returns 'incremental'/'full' for real changes, or 'skip' for\r\n * directory notifications (the real edit always arrives as a separate file event).\r\n */\r\n apply(filename: string | null, options?: WatchApplyOptions): Promise<ChangeOutcome>;\n /** Wait for deferred metadata work, primarily for tests and controlled shutdowns. */\n settled(): Promise<void>;\n}\n\r\nexport function createWatchUpdater(\r\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\r\n initial: SyncResult,\r\n): WatchUpdater {\r\n const paths = initial.paths;\r\n let routes = initial.routes;\n const data = initial.data;\n let metadataQueue = Promise.resolve();\n\n const fullResync = async (): Promise<ChangeOutcome> => {\n await metadataQueue;\n purgeProjectModules(paths.cwd);\n const result = await syncProject(config, { cwd: paths.cwd });\r\n routes = result.routes;\r\n data.responsesByFile = result.data.responsesByFile;\r\n data.inputsByFile = result.data.inputsByFile;\r\n data.securityByFile = result.data.securityByFile;\r\n data.hiddenFiles = result.data.hiddenFiles;\r\n data.openapiByFile = result.data.openapiByFile;\r\n purgeGeneratedModules(paths.outDir);\r\n return 'full';\r\n };\r\n\r\n /** Recompute affected routes in one TypeScript program and one metadata-loading pass. */\n const reextractRoutes = async (affected: ScannedRoute[]): Promise<void> => {\n if (affected.length === 0) {\n return;\n }\n\n try {\n const { createSchemaProgram, extractRouteResponses } = await import('./schema/index.js');\n const appTypes = join(paths.outDir, 'types', 'app.d.ts');\n const files = affected.map((route) => route.file);\n const program = createSchemaProgram(\n paths,\n existsSync(appTypes) ? [...files, appTypes] : files,\n );\n for (const route of affected) {\n data.responsesByFile.set(\n route.file,\n extractRouteResponses(program, route.file),\n );\n }\n } catch {\n // keep the previous response schema on failure (e.g. mid-save / type error)\n }\n\n try {\n const meta = await extractRouteMeta(config, paths, affected);\n for (const route of affected) {\n const key = route.file;\n const entry = meta.get(key);\n data.inputsByFile.delete(key);\n data.securityByFile.delete(key);\n data.hiddenFiles.delete(key);\n data.openapiByFile.delete(key);\n if (entry?.input) {\n data.inputsByFile.set(key, entry.input);\n }\n if (entry?.security) {\n data.securityByFile.set(key, entry.security);\n }\n if (entry?.hidden) {\n data.hiddenFiles.add(key);\n }\n if (entry?.openapi) {\n data.openapiByFile.set(key, entry.openapi);\n }\n }\n } catch {\n // keep previous metadata on failure\n }\r\n };\r\n\r\n return {\n settled: () => metadataQueue,\n async apply(filename, options = {}) {\n if (!filename) {\r\n return fullResync();\r\n }\r\n // Filenames arrive relative to the watched `src/` (the parent of routes).\r\n const abs = resolve(dirname(paths.routesDir), filename);\r\n const file = slash(abs);\r\n if (!existsSync(abs)) {\r\n return fullResync();\r\n }\r\n\r\n // Ignore directory notifications. Windows' recursive fs.watch emits a `change` for a\r\n // folder whenever a file inside it is touched - including the access-time bumps from\r\n // the schema TypeScript program reading every route - which would otherwise trigger a\r\n // full resync per folder (a rebuild storm). The real edit always arrives as a file event.\r\n if (statSync(abs).isDirectory()) {\n return 'skip';\n }\n\n // TypeScript can still produce a partial AST for malformed source. Reject its parse\n // diagnostics before logging an update or replacing the last working app.\n assertSourceSyntax(abs);\n\n const isRoute = routes.some((candidate) => slash(candidate.file) === file);\n const isShared = routes.some((route) =>\n route.sharedFiles.some((shared) => slash(shared) === file),\n );\n const isMethodFile =\n /^\\+(?:get|post|put|patch|delete|options|head)\\.(?:[cm]?[jt]s|[jt]sx)$/i\n .test(basename(file));\n const isNewRouteStructure =\n file.startsWith(`${slash(paths.routesDir)}/`) &&\n /^\\+(?:get|post|put|patch|delete|options|head|shared)\\.(?:[cm]?[jt]s|[jt]sx)$/i\n .test(basename(file)) &&\n !isRoute &&\n !isShared;\n\n if (isRoute || (isNewRouteStructure && isMethodFile)) {\n assertRouteHandleExport(abs);\n }\n\n if (isNewRouteStructure) {\n return fullResync();\n }\n\n const graph = await buildImportGraph(config, paths.cwd);\n if (!graph.nodes.has(file) && !isRoute && !isShared) {\n return fullResync();\n }\n\n const dependents = collectDependents(graph, file);\r\n const affected = routes.filter((route) =>\n dependents.has(slash(route.file)) ||\n route.sharedFiles.some((shared) => dependents.has(slash(shared))),\n );\n purgeModules(dependents);\n const refreshMetadata = async (): Promise<void> => {\n await reextractRoutes(affected);\n await writeManifest(paths, routes, data);\n await writeOpenApi(paths, routes, data);\n await writeSyncCache(paths, await syncFingerprint(config, paths), data);\n purgeGeneratedModules(paths.outDir);\n };\n const task = metadataQueue.then(refreshMetadata);\n metadataQueue = task.catch((error) => {\n console.error('giri: deferred metadata update failed', error);\n });\n if (!options.deferMetadata) {\n await task;\n }\n return 'incremental';\n },\n };\r\n}\r\n","/**\n * Build the project's import graph from **source**, not from Node's `require.cache`.\n *\n * The watcher needs to know which routes (transitively) import a changed file so it can\n * rebuild just those. The require.cache only records edges for modules that were actually\n * evaluated at runtime, but `syncProject` resolves most routes statically and never `require`s\n * them - so those import edges are missing and a helper edit would fall back to a full resync.\n * Parsing the imports ourselves makes the graph independent of runtime evaluation.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport ts from 'typescript';\nimport { glob } from 'tinyglobby';\nimport { resolveAliasRequest } from '../app';\nimport type { GiriConfig } from '../types';\nimport type { ModuleGraph } from './module-loader';\n\nconst RESOLVE_EXTS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];\nconst JS_EXT = /\\.(?:c|m)?jsx?$/;\n\nconst toSlash = (path: string): string => path.split(sep).join('/');\n\n/** Resolve a module base (no/with extension) to a real file, trying extensions then `index.*`. */\nfunction probeFile(base: string): string | undefined {\n if (existsSync(base) && statSync(base).isFile()) {\n return base;\n }\n for (const ext of RESOLVE_EXTS) {\n const candidate = base + ext;\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n for (const ext of RESOLVE_EXTS) {\n const candidate = join(base, `index${ext}`);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return undefined;\n}\n\n/** Resolve one import specifier to an absolute project file, or `undefined` for bare/external. */\nfunction resolveSpecifier(\n specifier: string,\n fromFile: string,\n alias: GiriConfig['alias'],\n cwd: string,\n): string | undefined {\n let target: string;\n if (specifier.startsWith('.')) {\n target = resolve(dirname(fromFile), specifier);\n } else {\n const aliased = resolveAliasRequest(specifier, alias, cwd);\n if (aliased === undefined) {\n return undefined; // bare import (node_modules) - not part of the project graph\n }\n target = aliased;\n }\n\n const resolved = probeFile(target);\n if (resolved) {\n return resolved;\n }\n // A `.js`/`.mjs` specifier in TS source usually points at its `.ts` sibling.\n if (JS_EXT.test(target)) {\n return probeFile(target.replace(JS_EXT, ''));\n }\n return undefined;\n}\n\n/** Collect every static/dynamic import + `require()`/`export … from` specifier in a source file. */\nfunction importSpecifiers(file: string): string[] {\n let source: ts.SourceFile;\n try {\n source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, false);\n } catch {\n return [];\n }\n\n const specifiers: string[] = [];\n const visit = (node: ts.Node): void => {\n if (\n (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&\n node.moduleSpecifier &&\n ts.isStringLiteral(node.moduleSpecifier)\n ) {\n specifiers.push(node.moduleSpecifier.text);\n } else if (\n ts.isImportEqualsDeclaration(node) &&\n ts.isExternalModuleReference(node.moduleReference) &&\n ts.isStringLiteralLike(node.moduleReference.expression)\n ) {\n specifiers.push(node.moduleReference.expression.text);\n } else if (ts.isCallExpression(node)) {\n const isRequire = ts.isIdentifier(node.expression) && node.expression.text === 'require';\n const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;\n const [first] = node.arguments;\n if ((isRequire || isDynamicImport) && first && ts.isStringLiteralLike(first)) {\n specifiers.push(first.text);\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return specifiers;\n}\n\n/**\n * Statically scan every project source file under `cwd` (skipping `node_modules` and the\n * generated `outDir`) and resolve its imports into a `dep -> importers` graph keyed on\n * forward-slash paths, matching what `collectDependents` consumes. Type-only imports are\n * included on purpose: a route's response schema can depend on an imported type.\n */\nexport async function buildImportGraph(\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\n cwd: string,\n): Promise<ModuleGraph> {\n const root = resolve(cwd);\n const outDir = resolve(root, config.outDir ?? '.giri') + sep;\n const outRel = relative(root, outDir).split(sep).join('/').replace(/\\/$/, '');\n const files = await glob('**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}', {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n ignore: ['**/node_modules/**', '**/.git/**', outRel ? `${outRel}/**` : '.giri/**'],\n });\n\n const importers = new Map<string, Set<string>>();\n const nodes = new Set<string>();\n for (const file of files) {\n if (file.startsWith(outDir)) {\n continue;\n }\n // Standalone files are still graph nodes. Without this, a +shared.ts that only imports\n // external packages is mistaken for an unknown structural change and forces a full sync.\n nodes.add(toSlash(file));\n for (const specifier of importSpecifiers(file)) {\n const dep = resolveSpecifier(specifier, file, config.alias, root);\n if (!dep || dep.startsWith(outDir)) {\n continue;\n }\n const from = toSlash(file);\n const to = toSlash(dep);\n nodes.add(to);\n let set = importers.get(to);\n if (!set) {\n set = new Set();\n importers.set(to, set);\n }\n set.add(from);\n }\n }\n return { importers, nodes };\n}\n","/**\r\n * `require.cache` helpers for the dev watcher: purge stale modules so the next build re-evaluates\r\n * them. The import graph itself is built statically in `import-graph.ts` (require.cache only\r\n * records edges for modules that were actually evaluated, which misses statically-synced routes).\r\n */\r\nimport { resolve, sep } from 'node:path';\r\n\r\nexport interface ModuleGraph {\r\n importers: Map<string, Set<string>>;\r\n nodes: Set<string>;\r\n}\r\n\r\nconst toSlash = (path: string): string => path.split(sep).join('/');\r\n\r\nconst isProjectModule = (id: string, root: string): boolean => {\r\n return id.startsWith(root) && !id.includes(`${sep}node_modules${sep}`) && !id.includes(`${sep}.giri${sep}`);\r\n}\r\n\r\nexport const collectDependents = (graph: ModuleGraph, start: string): Set<string> => {\r\n const out = new Set<string>([start]);\r\n const stack = [start];\r\n while (stack.length > 0) {\r\n const current = stack.pop()!;\r\n for (const importer of graph.importers.get(current) ?? []) {\r\n if (!out.has(importer)) {\r\n out.add(importer);\r\n stack.push(importer);\r\n }\r\n }\r\n }\r\n return out;\r\n};\r\n\r\nexport const purgeModules = (files: Set<string>): void => {\r\n for (const id of Object.keys(require.cache)) {\r\n if (files.has(toSlash(id))) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Drop every cached module under the project root (skipping `node_modules` and `.giri`).\r\n */\r\nexport const purgeProjectModules = (cwd: string): void => {\r\n const root = resolve(cwd) + sep;\r\n for (const id of Object.keys(require.cache)) {\r\n if (isProjectModule(id, root)) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};\r\n\r\nexport const purgeGeneratedModules = (outDir: string): void => {\r\n const root = resolve(outDir) + sep;\r\n for (const id of Object.keys(require.cache)) {\r\n if (resolve(id).startsWith(root)) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};","import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { safeRegister } from './loader/loader';\nimport type { Services } from './types';\n\nconst MAIN_EXTENSIONS = ['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'];\n\nexport interface GiriLifecycle {\n /** Absolute path to the resolved `src/main.ts`, if one exists. */\n file?: string;\n /** Runtime startup: build the app's service container, awaited before serving. */\n init?: () => Services | Promise<Services>;\n /** Graceful shutdown: receives the container from `init`, run on process exit. */\n teardown?: (services: Services) => void | Promise<void>;\n}\n\nfunction resolveMainFile(cwd: string): string | undefined {\n for (const ext of MAIN_EXTENSIONS) {\n const file = join(cwd, 'src', `main.${ext}`);\n if (existsSync(file)) {\n return file;\n }\n }\n return undefined;\n}\n\n/**\n * Load the optional `src/main.ts` lifecycle module. Absent file ⇒ empty lifecycle\n * (serve immediately). `init`/`teardown` are validated to be functions if present.\n */\nexport async function loadLifecycle(cwd = process.cwd()): Promise<GiriLifecycle> {\n const file = resolveMainFile(resolve(cwd));\n if (!file) {\n return {};\n }\n\n const { unregister } = await safeRegister();\n try {\n const resolved = require.resolve(file);\n delete require.cache[resolved];\n const loaded = require(resolved) as Partial<GiriLifecycle>;\n\n const lifecycle: GiriLifecycle = { file };\n if (loaded.init !== undefined) {\n if (typeof loaded.init !== 'function') {\n throw new Error(`${file}: \"init\" must be a function.`);\n }\n lifecycle.init = loaded.init;\n }\n if (loaded.teardown !== undefined) {\n if (typeof loaded.teardown !== 'function') {\n throw new Error(`${file}: \"teardown\" must be a function.`);\n }\n lifecycle.teardown = loaded.teardown;\n }\n return lifecycle;\n } finally {\n unregister();\n }\n}\n\n/** Run `init()` once and normalize its result into a service container. */\nexport async function runInit(lifecycle: GiriLifecycle): Promise<Services> {\n if (!lifecycle.init) {\n return {} as Services;\n }\n const services = await lifecycle.init();\n return (services ?? {}) as Services;\n}\n","/**\n * A tiny, dependency-free logger styled after Vite's dev output:\n * `HH:MM:SS [giri] (scope) message`. Colors auto-disable for non-TTY output, `NO_COLOR`,\n * or `TERM=dumb`, so piped/CI logs stay clean.\n */\n\nconst noColor =\n !process.stdout.isTTY ||\n process.env.NO_COLOR !== undefined ||\n process.env.TERM === 'dumb' ||\n process.env.FORCE_COLOR === '0';\n\nfunction paint(open: number, close: number): (text: string) => string {\n return (text) => (noColor ? text : `\\x1b[${open}m${text}\\x1b[${close}m`);\n}\n\nexport const color = {\n dim: paint(2, 22),\n bold: paint(1, 22),\n red: paint(31, 39),\n green: paint(32, 39),\n yellow: paint(33, 39),\n blue: paint(34, 39),\n magenta: paint(35, 39),\n cyan: paint(36, 39),\n gray: paint(90, 39),\n};\n\n/** Green for paths/values, like Vite highlights updated files. */\nexport const highlight = (text: string): string => color.green(text);\n/** Dim for secondary details (counts, durations). */\nexport const muted = (text: string): string => color.dim(text);\n\nfunction timestamp(): string {\n const now = new Date();\n const pad = (n: number): string => String(n).padStart(2, '0');\n return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;\n}\n\nconst TAG = 'giri';\n\nfunction line(tag: string, message: string, scope?: string): string {\n const parts = [color.gray(timestamp()), tag];\n if (scope) {\n parts.push(color.dim(`(${scope})`));\n }\n parts.push(message);\n return parts.join(' ');\n}\n\nconst tag = {\n info: color.bold(color.cyan(`[${TAG}]`)),\n warn: color.bold(color.yellow(`[${TAG}]`)),\n error: color.bold(color.red(`[${TAG}]`)),\n};\n\n/** Preserve stack frames for real errors while still accepting arbitrary thrown values. */\nexport function formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? `${error.name}: ${error.message}`;\n }\n return String(error);\n}\n\nexport const log = {\n info(message: string, scope?: string): void {\n console.log(line(tag.info, message, scope));\n },\n success(message: string, scope?: string): void {\n console.log(line(tag.info, color.green(message), scope));\n },\n warn(message: string, scope?: string): void {\n console.warn(line(tag.warn, color.yellow(message), scope));\n },\n error(message: string, scope?: string): void {\n console.error(line(tag.error, color.red(message), scope));\n },\n ready(url: string): void {\n console.log(line(tag.info, `${color.green('ready')} on ${color.cyan(url)}`));\n },\n change(verb: string, path: string, count?: number): void {\n const suffix = count && count > 1 ? ` ${color.dim(`(x${count})`)}` : '';\n console.log(line(tag.info, `${color.green(verb)} ${highlight(path)}${suffix}`, 'watch'));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,GACC;AADP;AAAA;AAAA;AAAA,IAAM,IAAI;AACV,IAAO,cAAQ;AAAA;AAAA;;;ACgBR,SAAS,oBACZ,OACA,YACU;AACV,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AC;AACxD,QAAM,UAAM,4BAAQ,QAAQ,IAAI,CAAC;AAEjC,MAAI,YAAY,UAAU,YAAY,YAAY,YAAY,MAAM;AAChE,SAAK;AACL;AAAA,EACJ;AAEA,MAAI,YAAY,QAAQ;AACpB,UAAM,YAAY,KAAK,eAAe,IAAI,CAAC;AAC3C;AAAA,EACJ;AAEA,MAAI,YAAY,SAAS;AACrB,IAAAA,KAAI,KAAK,8CAA8C,OAAO;AAC9D;AAAA,EACJ;AAEA,QAAM,SAAS,MAAM,KAAK;AAE1B,MAAI,YAAY,QAAQ;AACpB,UAAM,SAAS,MAAM,YAAY,MAAM;AACvC,IAAAA,KAAI;AAAA,MACA,UAAU,OAAO,OAAO,MAAM,SAAS,OAAO,OAAO,WAAW,IAAI,KAAK,GAAG,IAAI,MAAM,MAAM,OAAO,MAAM,MAAM,EAAE,CAAC;AAAA,MAClH;AAAA,IACJ;AACA;AAAA,EACJ;AAEA,MAAI,YAAY,SAAS;AACrB,UAAM,aAAa,QAAQ,WAAW,IAAI,CAAC;AAC3C;AAAA,EACJ;AAEA,QAAM,IAAI,MAAM,oBAAoB,OAAO,EAAE;AACjD;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACpB,EAAAA,KAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAChE,UAAQ,WAAW;AACvB,CAAC;","names":["ts","import_typescript","ts","import_typescript","ts","import_typescript","import_node_fs","import_promises","import_node_path","import_node_path","import_node_fs","import_node_path","ts","Module","import_node_fs","import_promises","import_node_path","import_node_fs","import_node_path","import_node_fs","import_promises","import_node_path","moduleSpecifier","import_node_path","import_node_fs","import_node_path","tag","import_node_path","import_node_fs","import_typescript","loadModule","interopDefault","hasExportModifier","ts","propertyName","tag","import_node_path","import_node_path","import_node_fs","import_promises","import_node_path","import_tinyglobby","createSchemaProgram","extractRouteResponses","import_node_fs","import_node_path","import_node_fs","import_node_path","import_typescript","import_tinyglobby","ts","import_node_path","toSlash","createSchemaProgram","extractRouteResponses","import_node_fs","import_node_path","MAIN_EXTENSIONS","tag","log","initial","log"]}
1
+ {"version":3,"sources":["../src/loader/_es5.ts","../src/generator/schema/program.ts","../src/generator/schema/json-schema.ts","../src/generator/schema/responses.ts","../src/generator/schema/index.ts","../src/cli.ts","../src/app.ts","../src/loader/loader.ts","../src/config/schema.ts","../src/routes.ts","../src/types.ts","../src/validation.ts","../src/generator/sync.ts","../src/generator/app-types.ts","../src/generator/util.ts","../src/generator/manifest.ts","../src/generator/openapi.ts","../src/generator/param-types.ts","../src/generator/route-meta.ts","../src/generator/inputs.ts","../src/generator/schema/route-openapi.ts","../src/generator/route-types.ts","../src/generator/tsconfig.ts","../src/generator/cache.ts","../src/generator/watch.ts","../src/loader/import-graph.ts","../src/loader/module-loader.ts","../src/lifecycle.ts","../src/logger.ts"],"sourcesContent":["const _ = '';\r\nexport default _;","import ts from 'typescript';\nimport type { GiriPaths } from '../../types';\n\r\nconst DEFAULT_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2022,\r\n module: ts.ModuleKind.NodeNext,\r\n moduleResolution: ts.ModuleResolutionKind.NodeNext,\r\n strict: true,\r\n skipLibCheck: true,\r\n noEmit: true,\r\n};\n\n/**\n * Build a `ts.Program` rooted at the given route files, using the project's own\n * `tsconfig.json` (so `paths`, `rootDirs`, and the user's TS settings apply). The\n * walker reads types from this program; nothing is emitted.\n */\nexport function createSchemaProgram(\n paths: GiriPaths,\n routeFiles: string[],\n): ts.Program {\n let options: ts.CompilerOptions = { ...DEFAULT_OPTIONS };\n\n const configPath = ts.findConfigFile(paths.cwd, ts.sys.fileExists, 'tsconfig.json');\n if (configPath) {\r\n const parsed = ts.getParsedCommandLineOfConfigFile(configPath, {}, {\r\n ...ts.sys,\r\n onUnRecoverableConfigFileDiagnostic: () => {},\r\n });\r\n if (parsed) {\n options = { ...parsed.options, noEmit: true };\n }\n }\n\n return ts.createProgram(routeFiles, options);\n}\n","import ts from 'typescript';\r\n\r\nexport type JSONSchema = Record<string, unknown>;\r\n\r\nexport interface WalkContext {\r\n checker: ts.TypeChecker;\r\n /** Node used to resolve property types in context. */\r\n location: ts.Node;\r\n /** Shared `$defs` bucket for recursive types. */\r\n defs: Record<string, JSONSchema>;\r\n /** Type ids currently being walked, mapped to their `$defs` name (cycle guard). */\r\n inProgress: Map<number, string>;\r\n /** `$defs` names that were referenced via `$ref` (i.e. proved recursive). */\r\n usedDefs: Set<string>;\r\n /** Non-fatal notes (e.g. bigint serialization caveats). */\r\n warnings: string[];\r\n}\r\n\r\nexport function createWalkContext(checker: ts.TypeChecker, location: ts.Node): WalkContext {\r\n return {\r\n checker,\r\n location,\r\n defs: {},\r\n inProgress: new Map(),\r\n usedDefs: new Set(),\r\n warnings: [],\r\n };\r\n}\r\n\r\nfunction typeId(type: ts.Type): number {\r\n return (type as ts.Type & { id: number }).id;\r\n}\r\n\r\nfunction intrinsicName(type: ts.Type): string | undefined {\r\n return (type as ts.Type & { intrinsicName?: string }).intrinsicName;\r\n}\r\n\r\nfunction isDateType(type: ts.Type): boolean {\r\n const symbol = type.getSymbol() ?? type.aliasSymbol;\r\n return symbol?.getName() === 'Date';\r\n}\r\n\r\nfunction literalValuesOf(types: ts.Type[]): unknown[] | undefined {\r\n const values: unknown[] = [];\r\n for (const member of types) {\r\n if (member.isStringLiteral() || member.isNumberLiteral()) {\r\n values.push(member.value);\r\n } else if (member.flags & ts.TypeFlags.BooleanLiteral) {\r\n values.push(intrinsicName(member) === 'true');\r\n } else {\r\n return undefined;\r\n }\r\n }\r\n return values;\r\n}\r\n\r\nfunction walkUnion(type: ts.UnionType, ctx: WalkContext): JSONSchema {\r\n const flag = (ts.TypeFlags.Undefined | ts.TypeFlags.Void | ts.TypeFlags.Never);\r\n const members = type.types.filter((member) => !(member.flags & flag));\r\n\r\n if (members.length === 1) {\r\n return walkType(members[0], ctx);\r\n }\r\n\r\n const enumValues = literalValuesOf(members);\r\n if (enumValues) {\r\n return { enum: enumValues };\r\n }\r\n\r\n return { anyOf: members.map((member) => walkType(member, ctx)) };\r\n}\r\n\r\nfunction buildObjectSchema(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const { checker } = ctx;\r\n\r\n const indexInfo =\r\n checker.getIndexInfoOfType(type, ts.IndexKind.String) ??\r\n checker.getIndexInfoOfType(type, ts.IndexKind.Number);\r\n\r\n const properties: Record<string, JSONSchema> = {};\r\n const required: string[] = [];\r\n\r\n for (const symbol of checker.getPropertiesOfType(type)) {\r\n const name = symbol.getName();\r\n const propType = checker.getTypeOfSymbolAtLocation(symbol, ctx.location);\r\n const optional =\r\n Boolean(symbol.getFlags() & ts.SymbolFlags.Optional) ||\r\n Boolean(propType.flags & ts.TypeFlags.Union &&\r\n (propType as ts.UnionType).types.some((t) => t.flags & ts.TypeFlags.Undefined));\r\n\r\n properties[name] = walkType(propType, ctx);\r\n if (!optional) {\r\n required.push(name);\r\n }\r\n }\r\n\r\n const schema: JSONSchema = { type: 'object' };\r\n if (Object.keys(properties).length > 0) {\r\n schema.properties = properties;\r\n }\r\n if (required.length > 0) {\r\n schema.required = required;\r\n }\r\n if (indexInfo) {\r\n schema.additionalProperties = walkType(indexInfo.type, ctx);\r\n } else if (Object.keys(properties).length > 0) {\r\n schema.additionalProperties = false;\r\n }\r\n return schema;\r\n}\r\n\r\nfunction defName(type: ts.Type): string {\r\n const symbol = type.getSymbol() ?? type.aliasSymbol;\r\n const name = symbol?.getName();\r\n if (name && name !== '__type' && name !== '__object') {\r\n return name;\r\n }\r\n return `Anonymous${typeId(type)}`;\r\n}\r\n\r\nfunction walkObject(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const { checker } = ctx;\r\n\r\n if (isDateType(type)) {\r\n return { type: 'string', format: 'date-time' };\r\n }\r\n if (checker.isArrayType(type)) {\r\n const [element] = checker.getTypeArguments(type as ts.TypeReference);\r\n return { type: 'array', items: element ? walkType(element, ctx) : {} };\r\n }\r\n if (checker.isTupleType(type)) {\r\n const elements = checker.getTypeArguments(type as ts.TypeReference);\r\n return { type: 'array', items: elements.map((element) => walkType(element, ctx)) };\r\n }\r\n\r\n const id = typeId(type);\r\n const existing = ctx.inProgress.get(id);\r\n if (existing) {\r\n ctx.usedDefs.add(existing);\r\n return { $ref: `#/$defs/${existing}` };\r\n }\r\n\r\n const name = defName(type);\r\n ctx.inProgress.set(id, name);\r\n const schema = buildObjectSchema(type, ctx);\r\n ctx.inProgress.delete(id);\r\n\r\n if (ctx.usedDefs.has(name)) {\r\n ctx.defs[name] = schema;\r\n return { $ref: `#/$defs/${name}` };\r\n }\r\n return schema;\r\n}\r\n\r\n/** Translate a TypeScript type into the JSON Schema that `JSON.stringify` would produce. */\r\nexport function walkType(type: ts.Type, ctx: WalkContext): JSONSchema {\r\n const flags = type.flags;\r\n\r\n if (flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {\r\n return {};\r\n }\r\n if (flags & ts.TypeFlags.Null) {\r\n return { type: 'null' };\r\n }\r\n if (flags & (ts.TypeFlags.Undefined | ts.TypeFlags.Void)) {\r\n return {};\r\n }\r\n if (flags & (ts.TypeFlags.BigInt | ts.TypeFlags.BigIntLiteral)) {\r\n ctx.warnings.push('bigint is not JSON-serializable (JSON.stringify throws); documented as string.');\r\n return { type: 'string' };\r\n }\r\n if (type.isStringLiteral()) {\r\n return { type: 'string', const: type.value };\r\n }\r\n if (type.isNumberLiteral()) {\r\n return { type: 'number', const: type.value };\r\n }\r\n if (flags & ts.TypeFlags.BooleanLiteral) {\r\n return { type: 'boolean', const: intrinsicName(type) === 'true' };\r\n }\r\n if (flags & ts.TypeFlags.String) {\r\n return { type: 'string' };\r\n }\r\n if (flags & ts.TypeFlags.Number) {\r\n return { type: 'number' };\r\n }\r\n if (flags & ts.TypeFlags.Boolean) {\r\n return { type: 'boolean' };\r\n }\r\n if (type.isUnion()) {\r\n return walkUnion(type, ctx);\r\n }\r\n if (flags & ts.TypeFlags.Object || type.isIntersection()) {\r\n return walkObject(type, ctx);\r\n }\r\n\r\n return {};\r\n}\r\n","import ts from 'typescript';\nimport { createWalkContext, walkType, type JSONSchema } from './json-schema';\n\nexport interface ResponseSchema {\n /** Numeric HTTP status, or 'default' when the handler returns a non-literal status. */\n status: number | 'default';\n format: 'json' | 'text';\n schema: JSONSchema;\n}\n\nexport interface RouteResponses {\n responses: ResponseSchema[];\n /** Statuses/returns the walker could not turn into a schema (e.g. a raw `Response`). */\n opaque: boolean;\n warnings: string[];\n $defs: Record<string, JSONSchema>;\n}\n\nfunction findHandleFunction(\n source: ts.SourceFile,\n): ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | undefined {\n let found: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration | undefined;\n\n const isExported = (node: ts.Node): boolean =>\n ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n\n for (const statement of source.statements) {\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === 'handle' && isExported(statement)) {\n found = statement;\n }\n if (ts.isVariableStatement(statement) && isExported(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (\n ts.isIdentifier(declaration.name) &&\n declaration.name.text === 'handle' &&\n declaration.initializer &&\n (ts.isArrowFunction(declaration.initializer) ||\n ts.isFunctionExpression(declaration.initializer))\n ) {\n found = declaration.initializer;\n }\n }\n }\n }\n\n return found;\n}\n\nfunction collectReturnExpressions(\n fn: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration,\n): ts.Expression[] {\n if (ts.isArrowFunction(fn) && !ts.isBlock(fn.body)) {\n return [fn.body];\n }\n if (!fn.body) {\n return [];\n }\n\n const expressions: ts.Expression[] = [];\n const visit = (node: ts.Node): void => {\n if (ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isArrowFunction(node)) {\n return;\n }\n if (ts.isReturnStatement(node) && node.expression) {\n expressions.push(node.expression);\n }\n ts.forEachChild(node, visit);\n };\n ts.forEachChild(fn.body, visit);\n return expressions;\n}\n\ninterface ResponseHit {\n status: number | 'default';\n format: 'json' | 'text';\n data: ts.Type;\n}\n\nfunction propertyType(\n checker: ts.TypeChecker,\n type: ts.Type,\n name: string,\n location: ts.Node,\n): ts.Type | undefined {\n const symbol = checker.getPropertyOfType(type, name);\n return symbol ? checker.getTypeOfSymbolAtLocation(symbol, location) : undefined;\n}\n\nfunction isTypedResponse(checker: ts.TypeChecker, type: ts.Type): boolean {\n return Boolean(\n checker.getPropertyOfType(type, 'data') &&\n checker.getPropertyOfType(type, 'status') &&\n checker.getPropertyOfType(type, 'format'),\n );\n}\n\nfunction firstParameterName(\n fn: ts.ArrowFunction | ts.FunctionExpression | ts.FunctionDeclaration,\n): string | undefined {\n const [first] = fn.parameters;\n return first && ts.isIdentifier(first.name) ? first.name.text : undefined;\n}\n\n/**\n * Read a `c.json(data, status?)` / `c.text(data, status?)` call directly. Reading the\n * status from the argument (default 200) sidesteps contextual typing: a `: Handle`\n * annotation otherwise widens an omitted status from its `= 200` default down to\n * `StatusCode`. Data still comes from the argument's own type.\n */\nfunction readFromCall(\n checker: ts.TypeChecker,\n expression: ts.Expression,\n contextName: string | undefined,\n): ResponseHit | undefined {\n if (!ts.isCallExpression(expression) || !ts.isPropertyAccessExpression(expression.expression)) {\n return undefined;\n }\n const method = expression.expression.name.text;\n if (method !== 'json' && method !== 'text') {\n return undefined;\n }\n const target = expression.expression.expression;\n const directContextCall = contextName && ts.isIdentifier(target) && target.text === contextName;\n if (!directContextCall && !isTypedResponse(checker, checker.getTypeAtLocation(expression))) {\n return undefined;\n }\n\n const [dataArg, statusArg] = expression.arguments;\n if (!dataArg) {\n return undefined;\n }\n\n let status: number | 'default' = 200;\n if (statusArg) {\n const statusType = checker.getTypeAtLocation(statusArg);\n status = statusType.isNumberLiteral() ? statusType.value : 'default';\n }\n\n return { status, format: method === 'text' ? 'text' : 'json', data: checker.getTypeAtLocation(dataArg) };\n}\n\n/** Fallback for non-`c.json` returns: read `{ data, status, format }` off the type itself. */\nfunction readFromType(checker: ts.TypeChecker, type: ts.Type, location: ts.Node): ResponseHit | undefined {\n const dataType = propertyType(checker, type, 'data', location);\n const statusType = propertyType(checker, type, 'status', location);\n const formatType = propertyType(checker, type, 'format', location);\n if (!dataType || !statusType || !formatType) {\n return undefined;\n }\n\n const status = statusType.isNumberLiteral() ? statusType.value : 'default';\n const format = formatType.isStringLiteral() && formatType.value === 'text' ? 'text' : 'json';\n return { status, format, data: dataType };\n}\n\nfunction constituents(type: ts.Type): ts.Type[] {\n return type.isUnion() ? type.types : [type];\n}\n\n/**\n * Extract per-status response schemas for a route's `handle` export by typing each of\n * its return expressions and unwrapping giri's `TypedResponse<data, status, format>`.\n */\nexport function extractRouteResponses(program: ts.Program, file: string): RouteResponses {\n const result: RouteResponses = { responses: [], opaque: false, warnings: [], $defs: {} };\n const source = program.getSourceFile(file);\n if (!source) {\n return result;\n }\n\n const checker = program.getTypeChecker();\n const fn = findHandleFunction(source);\n if (!fn) {\n return result;\n }\n\n const ctx = createWalkContext(checker, fn);\n const contextName = firstParameterName(fn);\n const byStatus = new Map<number | 'default', { format: 'json' | 'text'; schemas: JSONSchema[] }>();\n\n const record = (hit: ResponseHit): void => {\n const schema = walkType(hit.data, ctx);\n const bucket = byStatus.get(hit.status) ?? { format: hit.format, schemas: [] };\n bucket.schemas.push(schema);\n byStatus.set(hit.status, bucket);\n };\n\n for (const expression of collectReturnExpressions(fn)) {\n const fromCall = readFromCall(checker, expression, contextName);\n if (fromCall) {\n record(fromCall);\n continue;\n }\n\n let matched = false;\n for (const member of constituents(checker.getTypeAtLocation(expression))) {\n const hit = readFromType(checker, member, expression);\n if (hit) {\n record(hit);\n matched = true;\n }\n }\n if (!matched) {\n result.opaque = true;\n }\n }\n\n for (const [status, { format, schemas }] of byStatus) {\n const schema = schemas.length === 1 ? schemas[0] : { anyOf: schemas };\n result.responses.push({ status, format, schema });\n }\n result.responses.sort((a, b) => Number(a.status) - Number(b.status));\n result.warnings = ctx.warnings;\n result.$defs = ctx.defs;\n return result;\n}\n","export { createSchemaProgram } from './program';\nexport { extractRouteResponses } from './responses';\nexport type { ResponseSchema, RouteResponses } from './responses';\nexport { walkType, createWalkContext } from './json-schema';\r\nexport type { JSONSchema, WalkContext } from './json-schema';\r\n","#!/usr/bin/env node\nimport { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { basename, isAbsolute, join, relative, resolve } from 'node:path';\nimport * as prompts from '@clack/prompts';\nimport { buildGiriApp, registerAliasResolver } from './app';\nimport { findConfigPath, load, safeRegister } from './loader/loader';\nimport { createWatchUpdater, syncProject } from './generator';\nimport { loadLifecycle, runInit } from './lifecycle';\nimport { color, formatError, log, muted } from './logger';\nimport type { Services, GiriConfig, GiriFetchHandler } from './types';\n\ninterface ParsedFlags {\n port?: number;\n hostname?: string;\n watch: boolean;\n}\n\ntype PackageManager = 'npm' | 'yarn' | 'pnpm' | 'bun';\n\ninterface AdapterChoice {\n value: string;\n label: string;\n hint: string;\n available: boolean;\n /** Import line added to `giri.config.ts`. */\n importLine: string;\n /** The adapter expression placed in `defineConfig({ adapter: … })`. */\n expr: string;\n /** Runtime deps this backend needs, installed alongside the framework. */\n deps: string[];\n}\n\nconst ADAPTERS: AdapterChoice[] = [\n {\n value: 'hono',\n label: 'Hono',\n hint: 'recommended, ships today',\n available: true,\n importLine: 'import { hono } from \"@boon4681/giri/adapters/hono\";',\n expr: 'hono()',\n deps: ['hono', '@hono/node-server'],\n }\n];\n\ninterface InitFlags {\n adapter?: string;\n packageManager?: PackageManager;\n /** undefined = ask; true/false = forced by --install / --no-install. */\n install?: boolean;\n /** Non-interactive: take defaults (Hono, detected PM, install). */\n yes: boolean;\n}\n\nfunction help(): void {\n console.log(`giri\n\nUsage:\n giri init [--adapter hono] [--pm npm|yarn|pnpm|bun] [--no-install] [-y]\n giri sync\n giri serve [--port 3000] [--host 127.0.0.1] [--no-watch]\n giri build\n`);\n}\n\nfunction parseInitFlags(args: string[]): InitFlags {\n const flags: InitFlags = { yes: false };\n const managers: PackageManager[] = ['npm', 'yarn', 'pnpm', 'bun'];\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--adapter' || arg === '-a') {\n flags.adapter = args[++index];\n } else if (arg === '--pm' || arg === '--package-manager') {\n const value = args[++index];\n if (!managers.includes(value as PackageManager)) {\n throw new Error(`Unknown package manager: ${value} (expected ${managers.join(', ')})`);\n }\n flags.packageManager = value as PackageManager;\n } else if (arg === '--install') {\n flags.install = true;\n } else if (arg === '--no-install') {\n flags.install = false;\n } else if (arg === '-y' || arg === '--yes') {\n flags.yes = true;\n } else {\n throw new Error(`Unknown option: ${arg}`);\n }\n }\n\n return flags;\n}\n\nfunction parseFlags(args: string[]): ParsedFlags {\n const flags: ParsedFlags = { watch: true };\n\n for (let index = 0; index < args.length; index += 1) {\n const arg = args[index];\n if (arg === '--port' || arg === '-p') {\n flags.port = Number(args[++index]);\n } else if (arg === '--host' || arg === '--hostname') {\n flags.hostname = args[++index];\n } else if (arg === '--no-watch') {\n flags.watch = false;\n } else {\n throw new Error(`Unknown option: ${arg}`);\n }\n }\n\n return flags;\n}\n\nasync function ensureGitignore(cwd: string): Promise<void> {\n const file = join(cwd, '.gitignore');\n const entry = '.giri';\n if (!existsSync(file)) {\n await writeFile(file, `${entry}\\n`);\n return;\n }\n\n const content = await readFile(file, 'utf8');\n if (!content.split(/\\r?\\n/).includes(entry)) {\n await appendFile(file, `${content.endsWith('\\n') ? '' : '\\n'}${entry}\\n`);\n }\n}\n\nasync function ensureTsConfig(cwd: string): Promise<void> {\n const file = join(cwd, 'tsconfig.json');\n if (existsSync(file)) {\n return;\n }\n\n await writeFile(\n file,\n `${JSON.stringify(\n {\n extends: './.giri/tsconfig.json',\n compilerOptions: {\n target: 'ES2022',\n lib: ['ES2022', 'DOM'],\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n esModuleInterop: true,\n forceConsistentCasingInFileNames: true,\n skipLibCheck: true,\n types: ['node'],\n },\n },\n null,\n 2,\n )}\\n`,\n );\n}\n\nasync function missingDeps(cwd: string, candidates: string[]): Promise<string[]> {\n let pkg: Record<string, unknown> = {};\n try {\n pkg = JSON.parse(await readFile(join(cwd, 'package.json'), 'utf8')) as Record<string, unknown>;\n } catch { }\n\n const present = new Set<string>();\n for (const field of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) {\n const map = pkg[field];\n if (map && typeof map === 'object') {\n for (const name of Object.keys(map as Record<string, unknown>)) {\n present.add(name);\n }\n }\n }\n\n return candidates.filter((name) => !present.has(name));\n}\n\n/** Guess the package manager from the user agent npm/yarn/pnpm/bun set when invoking the CLI. */\nfunction detectPackageManager(): PackageManager {\n const ua = process.env.npm_config_user_agent ?? '';\n if (ua.startsWith('yarn')) return 'yarn';\n if (ua.startsWith('pnpm')) return 'pnpm';\n if (ua.startsWith('bun')) return 'bun';\n return 'npm';\n}\n\nfunction installArgs(pm: PackageManager, deps: string[], dev: boolean): string[] {\n if (pm === 'npm') return ['install', ...(dev ? ['--save-dev'] : []), ...deps];\n if (pm === 'bun') return ['add', ...(dev ? ['--dev'] : []), ...deps];\n return ['add', ...(dev ? ['--dev'] : []), ...deps]; // yarn, pnpm\n}\n\n/** Run a package-manager command, streaming its output. On Windows the binaries are `.cmd` shims. */\nfunction runCommand(cmd: string, args: string[], cwd: string): Promise<void> {\n return new Promise((resolvePromise, reject) => {\n const child = spawn(cmd, args, { cwd, stdio: 'inherit', shell: process.platform === 'win32' });\n child.on('error', reject);\n child.on('close', (code) => {\n if (code === 0) {\n resolvePromise();\n } else {\n reject(new Error(`${cmd} ${args.join(' ')} exited with code ${code}`));\n }\n });\n });\n}\n\nfunction configSource(adapter: AdapterChoice): string {\n return [\n 'import { defineConfig } from \"@boon4681/giri\";',\n adapter.importLine,\n '',\n 'export default defineConfig({',\n ` adapter: ${adapter.expr},`,\n '});',\n '',\n ].join('\\n');\n}\n\n/** Prompt for the adapter (or take the default in non-interactive mode). Null = the user cancelled. */\nasync function selectAdapter(interactive: boolean): Promise<AdapterChoice | null> {\n if (!interactive || ADAPTERS.length === 1) {\n return ADAPTERS[0];\n }\n\n const picked = await prompts.select({\n message: 'Which backend adapter?',\n initialValue: 'hono',\n options: ADAPTERS.map((adapter) => ({\n value: adapter.value,\n label: adapter.label,\n hint: adapter.hint,\n })),\n });\n if (prompts.isCancel(picked)) {\n return null;\n }\n return ADAPTERS.find((adapter) => adapter.value === picked) ?? null;\n}\n\nasync function initProject(cwd: string, flags: InitFlags): Promise<void> {\n if (!existsSync(join(cwd, 'package.json'))) {\n throw new Error(\n 'No package.json found. Run `giri init` inside an existing project - set one up first ' +\n '(e.g. `npm init -y` and install typescript), then re-run.',\n );\n }\n\n const interactive = Boolean(process.stdout.isTTY) && !flags.yes;\n prompts.intro('giri init');\n\n let adapter: AdapterChoice | null;\n if (flags.adapter) {\n adapter = ADAPTERS.find((choice) => choice.value === flags.adapter) ?? null;\n if (!adapter) {\n prompts.cancel(`Unknown adapter \"${flags.adapter}\". Available: ${ADAPTERS.map((a) => a.value).join(', ')}.`);\n return;\n }\n } else {\n adapter = await selectAdapter(interactive);\n if (!adapter) {\n prompts.cancel('Cancelled.');\n return;\n }\n }\n\n if (!adapter.available) {\n prompts.cancel(`The ${adapter.label} adapter isn't available yet - only Hono ships today.`);\n return;\n }\n\n const configPath = join(cwd, 'giri.config.ts');\n if (!existsSync(configPath)) {\n await writeFile(configPath, configSource(adapter));\n }\n\n const routePath = join(cwd, 'src', 'routes', '+get.ts');\n if (!existsSync(routePath)) {\n await mkdir(join(cwd, 'src', 'routes'), { recursive: true });\n await writeFile(\n routePath,\n [\n 'import type { Handle } from \"@boon4681/giri\";',\n '',\n 'export const handle: Handle = (c) => c.json({ ok: true });',\n '',\n ].join('\\n'),\n );\n }\n\n await ensureGitignore(cwd);\n await ensureTsConfig(cwd);\n prompts.log.success(`scaffolded a ${adapter.label} project`);\n\n const pm = flags.packageManager ?? detectPackageManager();\n const deps = await missingDeps(cwd, ['@boon4681/giri', ...adapter.deps, 'zod']);\n const devDeps = await missingDeps(cwd, ['typescript', '@types/node']);\n\n if (deps.length === 0 && devDeps.length === 0) {\n prompts.outro('All dependencies already present. Run `giri serve` to start the dev server.');\n return;\n }\n\n const planLines = [\n ...(deps.length ? [` ${pm} ${installArgs(pm, deps, false).join(' ')}`] : []),\n ...(devDeps.length ? [` ${pm} ${installArgs(pm, devDeps, true).join(' ')}`] : []),\n ];\n\n let install = flags.install;\n if (install === undefined) {\n if (!interactive) {\n install = flags.yes;\n } else {\n const answer = await prompts.confirm({ message: `Install dependencies with ${pm}?` });\n if (prompts.isCancel(answer)) {\n prompts.cancel('Cancelled - files written, skipped install.');\n return;\n }\n install = answer;\n }\n }\n\n if (install) {\n try {\n if (deps.length) {\n prompts.log.step(`Installing ${deps.join(', ')}`);\n await runCommand(pm, installArgs(pm, deps, false), cwd);\n }\n if (devDeps.length) {\n prompts.log.step(`Installing dev deps ${devDeps.join(', ')}`);\n await runCommand(pm, installArgs(pm, devDeps, true), cwd);\n }\n } catch (error) {\n prompts.log.error(error instanceof Error ? error.message : String(error));\n prompts.outro(`Install failed - run these yourself, then \\`giri serve\\`:\\n${planLines.join('\\n')}`);\n return;\n }\n prompts.outro('Ready. Run `giri serve` to start the dev server.');\n return;\n }\n\n prompts.outro(`Next:\\n${planLines.join('\\n')}\\n giri serve`);\n}\n\nfunction displayHost(address: string): string {\n if (!address || address === '::' || address === '0.0.0.0') {\n return 'localhost';\n }\n return address.includes(':') ? `[${address}]` : address;\n}\n\nasync function serveProject(config: GiriConfig, flags: ParsedFlags): Promise<void> {\n Error.stackTraceLimit = 30;\n\n const { watch } = await import('chokidar');\n let stop: (() => Promise<void>) | undefined;\n const boot = async (cfg: GiriConfig): Promise<void> => {\n const closers: Array<() => void | Promise<void>> = [];\n closers.push(registerAliasResolver(cfg.alias, resolve(process.cwd())));\n\n const lifecycle = await loadLifecycle();\n // Project sync and lifecycle initialization are independent. Running them together hides\n // schema-generation time behind database connections/migrations instead of making startup\n // pay both costs serially.\n const sync = syncProject(cfg).then((initial) => {\n log.success(\n `synced ${initial.routes.length} route${initial.routes.length === 1 ? '' : 's'} ${muted(`at ${initial.paths.outDir}`)}`,\n 'sync',\n );\n return initial;\n });\n const [initial, services]: [Awaited<ReturnType<typeof syncProject>>, Services] =\n await Promise.all([sync, runInit(lifecycle)]);\n\n const loader = await safeRegister();\n closers.push(loader.unregister);\n let current = await buildGiriApp(cfg, {\n services,\n lazy: true,\n loaderRegistered: true,\n aliasResolverRegistered: true,\n });\n\n const port = flags.port ?? cfg.server?.port ?? 3000;\n const hostname = flags.hostname ?? cfg.server?.hostname;\n\n if (flags.watch) {\n // Watch the whole `src/`, not just `src/routes`: a route's imports (auth.ts, db.ts, …)\n // and `main.ts` live here, and editing them must rebuild too.\n const srcDir = resolve(current.paths.routesDir, '..');\n if (existsSync(srcDir)) {\n let timer: NodeJS.Timeout | undefined;\n let syncing = false;\n const changed = new Set<string>();\n const updater = createWatchUpdater(cfg, initial);\n const hmrCount = new Map<string, number>();\n const bump = (key: string): number => {\n const next = (hmrCount.get(key) ?? 0) + 1;\n hmrCount.set(key, next);\n return next;\n };\n\n // Drain queued changes, applying each through the incremental updater (it falls back\n // to a full sync for structural changes). Serialized so two drains never overlap;\n // changes arriving mid-drain are picked up by the loop or the trailing re-check.\n const flush = async (): Promise<void> => {\n if (syncing) {\n return;\n }\n syncing = true;\n try {\n while (changed.size > 0) {\n const batch = [...changed];\n changed.clear();\n let rebuild = false;\n let fullSync = false;\n const dirtySet = new Set<string>();\n for (const name of batch) {\n const outcome = await updater.apply(name || null, {\n deferMetadata: true,\n });\n if (outcome === 'skip') {\n continue;\n }\n rebuild = true;\n if (name) {\n dirtySet.add(resolve(srcDir, name));\n }\n const rel = name ? `src/${name.replace(/\\\\/g, '/')}` : 'src';\n log.change(outcome === 'full' ? 'sync' : 'update', rel, bump(rel));\n if (outcome === 'full') {\n fullSync = true;\n break;\n }\n }\n if (rebuild) {\n current = await buildGiriApp(cfg, {\n services,\n dirty: fullSync ? undefined : dirtySet,\n lazy: true,\n loaderRegistered: true,\n aliasResolverRegistered: true,\n });\n }\n }\n } catch (error) {\n log.error(formatError(error), 'watch');\n } finally {\n syncing = false;\n }\n if (changed.size > 0) {\n void flush();\n }\n };\n\n // ignoreInitial: boot() already built the whole project (syncProject + buildGiriApp);\n // replaying an `add` for every existing file here would re-run a full rebuild storm and\n // race with the config-restart below. We only want events for edits made after boot.\n const watcher = watch(srcDir, { persistent: true, ignoreInitial: true });\n // chokidar emits absolute paths; the updater (and its log labels) expect paths relative\n // to the watched `src/`, matching the relative form used everywhere else.\n const onFileChange = (filename: string): void => {\n changed.add(isAbsolute(filename) ? relative(srcDir, filename) : filename);\n clearTimeout(timer);\n timer = setTimeout(() => void flush(), 150);\n };\n watcher.on('change', onFileChange);\n watcher.on('add', onFileChange);\n watcher.on('unlink', onFileChange);\n closers.push(() => {\n clearTimeout(timer);\n watcher.close();\n });\n }\n }\n\n const handler: GiriFetchHandler = (request) => cfg.adapter.fetch(current.app, request);\n\n const server = cfg.adapter.serve(handler, { port, hostname }, (info) => {\n log.ready(`http://${displayHost(info.address)}:${info.port}`);\n });\n\n stop = async () => {\n for (const close of closers) {\n await close();\n }\n try {\n await server.close();\n } catch { }\n if (lifecycle.teardown) {\n await lifecycle.teardown(services);\n }\n };\n };\n\n await boot(config);\n const configPath = flags.watch ? findConfigPath(resolve(process.cwd())) : undefined;\n if (configPath) {\n let timer: NodeJS.Timeout | undefined;\n let restarting = false;\n const configName = basename(configPath);\n\n const restart = async (): Promise<void> => {\n if (restarting) {\n return;\n }\n restarting = true;\n try {\n log.info(`${color.green('restart')} ${configName} changed`, 'config');\n delete require.cache[configPath];\n const next = await load({ throwOnError: true });\n await stop?.();\n await boot(next);\n } catch (error) {\n log.error(error instanceof Error ? error.message : String(error), 'config');\n log.info('kept the previous server running — fix the config and save again', 'config');\n } finally {\n restarting = false;\n }\n };\n // Watch the config FILE directly, never its parent directory: `dirname(configPath)` is the\n // project root, and watching that recursively would scan all of node_modules (tens of seconds\n // on a real project) — which both stalls startup and, on Windows, starves the nested src\n // watcher so edits stop being detected. ignoreInitial avoids a spurious restart from the\n // initial `add` event.\n const configWatcher = watch(configPath, { persistent: true, ignoreInitial: true });\n configWatcher.on('all', () => {\n clearTimeout(timer);\n timer = setTimeout(() => void restart(), 150);\n });\n }\n\n registerShutdown(() => stop?.());\n}\n\nfunction registerShutdown(cleanup: () => void | Promise<void>): void {\n let shuttingDown = false;\n const shutdown = async (): Promise<void> => {\n if (shuttingDown) {\n return;\n }\n shuttingDown = true;\n try {\n await cleanup();\n } catch (error) {\n log.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n } finally {\n process.exit(process.exitCode ?? 0);\n }\n };\n\n process.once('SIGINT', () => void shutdown());\n process.once('SIGTERM', () => void shutdown());\n}\n\nasync function main(): Promise<void> {\n const [command = 'help', ...args] = process.argv.slice(2);\n const cwd = resolve(process.cwd());\n\n if (command === 'help' || command === '--help' || command === '-h') {\n help();\n return;\n }\n\n if (command === 'init') {\n await initProject(cwd, parseInitFlags(args));\n return;\n }\n\n if (command === 'build') {\n log.warn('build is planned, but is currently a no-op', 'build');\n return;\n }\n\n const config = await load();\n\n if (command === 'sync') {\n const result = await syncProject(config);\n log.success(\n `synced ${result.routes.length} route${result.routes.length === 1 ? '' : 's'} ${muted(`at ${result.paths.outDir}`)}`,\n 'sync',\n );\n return;\n }\n\n if (command === 'serve') {\n await serveProject(config, parseFlags(args));\n return;\n }\n\n throw new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error) => {\n log.error(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n});\n","import Module from 'node:module';\nimport { isAbsolute, join, resolve } from 'node:path';\nimport { safeRegister } from './loader/loader';\nimport { assertRouteHandleExport, scanRoutes, type ScannedRoute } from './routes';\nimport type {\n GiriBodySchema,\n GiriConfig,\n GiriInputSchema,\n GiriPaths,\n GiriRouteRegistration,\n Handle,\n Middleware,\n RouteInput,\n Services,\n} from './types';\nimport { isGiriBodySchema, isGiriInputSchema } from './validation';\n\nexport interface BuildGiriAppOptions {\n cwd?: string;\n services?: Services;\n /** Files that changed since last build — only these are purged from require.cache before loading. */\n dirty?: Set<string>;\n /** Defer route-module evaluation until the adapter first reads its runtime fields. */\n lazy?: boolean;\n /** The caller owns a persistent TypeScript loader for lazy route evaluation. */\n loaderRegistered?: boolean;\n /** The caller owns a persistent project-alias resolver for lazy route evaluation. */\n aliasResolverRegistered?: boolean;\n}\n\nexport interface BuiltGiriApp<App> {\n app: App;\n routes: ScannedRoute[];\n paths: GiriPaths;\n}\n\ninterface RouteModule {\n handle?: Handle;\n middleware?: Middleware | Middleware[];\n body?: unknown;\n query?: unknown;\n config?: {\n skipInherited?: boolean;\n };\n}\n\nfunction loadModule(file: string, force = true): unknown {\n const resolved = require.resolve(file);\n if (force) {\n delete require.cache[resolved];\n }\n return require(resolved);\n}\n\nfunction interopDefault(value: unknown): unknown {\n if (value && typeof value === 'object' && 'default' in value) {\n return (value as { default: unknown }).default;\n }\n return value;\n}\n\nfunction normalizeMiddleware(value: unknown, file: string): Middleware[] {\n const exported = interopDefault(value);\n if (exported === undefined) {\n return [];\n }\n if (typeof exported === 'function') {\n return [exported as Middleware];\n }\n if (Array.isArray(exported)) {\n for (const middleware of exported) {\n if (typeof middleware !== 'function') {\n throw new Error(`Middleware export in ${file} must contain only functions.`);\n }\n }\n return exported as Middleware[];\n }\n throw new Error(`Middleware export in ${file} must be a function or an array of functions.`);\n}\n\nfunction assertBodySchema(value: unknown, file: string): asserts value is GiriBodySchema {\n if (!isGiriBodySchema(value)) {\n throw new Error(\n `${file}: \"body\" must be wrapped with a validator, e.g. \\`export const body = zod.body({ json: ... })\\` from @boon4681/giri/validators/zod.`,\n );\n }\n}\n\nfunction assertQuerySchema(value: unknown, file: string): asserts value is GiriInputSchema {\n if (!isGiriInputSchema(value)) {\n throw new Error(\n `${file}: \"query\" must be wrapped with a validator, e.g. \\`export const query = zod.query(...)\\` from @boon4681/giri/validators/zod.`,\n );\n }\n}\n\nfunction routeInput(routeModule: RouteModule, file: string): RouteInput | undefined {\n const input: RouteInput = {};\n if (routeModule.body !== undefined) {\n assertBodySchema(routeModule.body, file);\n input.body = routeModule.body;\n }\n if (routeModule.query !== undefined) {\n assertQuerySchema(routeModule.query, file);\n input.query = routeModule.query;\n }\n return input.body || input.query ? input : undefined;\n}\n\nfunction aliasValues(value: string | string[]): string[] {\n return Array.isArray(value) ? value : [value];\n}\n\nfunction resolveAliasTarget(cwd: string, target: string, capture = ''): string {\n const replaced = target.includes('*') ? target.replaceAll('*', capture) : target;\n return isAbsolute(replaced) ? replaced : resolve(cwd, replaced);\n}\n\nfunction matchAlias(request: string, key: string): string | undefined {\n if (key.includes('*')) {\n const [prefix, suffix = ''] = key.split('*');\n if (request.startsWith(prefix) && request.endsWith(suffix)) {\n return request.slice(prefix.length, request.length - suffix.length);\n }\n return undefined;\n }\n \n return request === key ? '' : undefined;\n}\n\nexport function resolveAliasRequest(\n request: string,\n alias: GiriConfig['alias'],\n cwd: string,\n): string | undefined {\n for (const [key, value] of Object.entries(alias ?? {})) {\n const capture = matchAlias(request, key);\n if (capture === undefined) {\n continue;\n }\n\n const [target] = aliasValues(value);\n if (!target) {\n continue;\n }\n\n return resolveAliasTarget(cwd, target, capture);\n }\n\n return undefined;\n}\n\nexport function registerAliasResolver(alias: GiriConfig['alias'], cwd: string): () => void {\n if (!alias || Object.keys(alias).length === 0) {\n return () => { };\n }\n\n const moduleWithResolver = Module as typeof Module & {\n _resolveFilename: (request: string, parent: unknown, isMain: boolean, options: unknown) => string;\n };\n const originalResolveFilename = moduleWithResolver._resolveFilename;\n\n moduleWithResolver._resolveFilename = function resolveWithGiriAlias(\n request,\n parent,\n isMain,\n options,\n ) {\n return originalResolveFilename.call(\n this,\n resolveAliasRequest(request, alias, cwd) ?? request,\n parent,\n isMain,\n options,\n );\n };\n\n return () => {\n moduleWithResolver._resolveFilename = originalResolveFilename;\n };\n}\n\nconst GIRI_ALIAS_PREFIX = '$giri/';\nlet giriOutDir: string | undefined;\nlet giriResolverInstalled = false;\n\n/**\n * Install a process-lifetime resolver for the internal `$giri/*` alias\n */\nexport function ensureGiriAliasResolver(outDir: string): void {\n giriOutDir = outDir;\n if (giriResolverInstalled) {\n return;\n }\n giriResolverInstalled = true;\n\n const moduleWithResolver = Module as typeof Module & {\n _resolveFilename: (request: string, parent: unknown, isMain: boolean, options: unknown) => string;\n };\n const originalResolveFilename = moduleWithResolver._resolveFilename;\n\n moduleWithResolver._resolveFilename = function resolveWithGiriInternalAlias(\n request,\n parent,\n isMain,\n options,\n ) {\n const mapped =\n typeof request === 'string' && request.startsWith(GIRI_ALIAS_PREFIX) && giriOutDir\n ? join(giriOutDir, request.slice(GIRI_ALIAS_PREFIX.length))\n : request;\n return originalResolveFilename.call(this, mapped, parent, isMain, options);\n };\n}\n\nexport function resolveGiriPaths(config: Pick<GiriConfig, 'outDir'>, cwd = process.cwd()): GiriPaths {\n return {\n cwd: resolve(cwd),\n routesDir: resolve(cwd, 'src/routes'),\n outDir: resolve(cwd, config.outDir ?? '.giri'),\n };\n}\n\nexport async function buildGiriApp<App>(\n config: GiriConfig<App>,\n options: BuildGiriAppOptions = {},\n): Promise<BuiltGiriApp<App>> {\n const paths = resolveGiriPaths(config, options.cwd);\n const routes = await scanRoutes(paths.routesDir);\n if (options.lazy) {\n for (const route of routes) {\n assertRouteHandleExport(route.file);\n }\n }\n const app = config.adapter.createApp();\n // Install the persistent `$giri` resolver BEFORE esbuild-register: it patches\n // `_resolveFilename` too, and its unregister() restores whatever it captured\n ensureGiriAliasResolver(paths.outDir);\n if (options.lazy && (!options.loaderRegistered || !options.aliasResolverRegistered)) {\n throw new Error('Lazy route loading requires persistent loader and alias registrations.');\n }\n const loader = options.loaderRegistered ? undefined : await safeRegister();\n const unregisterAliasResolver = options.aliasResolverRegistered\n ? undefined\n : registerAliasResolver(config.alias, paths.cwd);\n\n try {\n const dirty = options.dirty;\n const forceReload = dirty === undefined;\n const isDirty = (file: string): boolean => forceReload || dirty.has(file);\n const sharedCache = new Map<string, unknown>();\n const loadShared = (file: string): unknown => {\n if (!sharedCache.has(file)) {\n sharedCache.set(file, loadModule(file, isDirty(file)));\n }\n return sharedCache.get(file);\n };\n\n const runtimeFor = (route: ScannedRoute): GiriRouteRegistration => {\n const routeModule = loadModule(route.file, isDirty(route.file)) as RouteModule;\n if (typeof routeModule.handle !== 'function') {\n throw new Error(`${route.file} must export a named handle function.`);\n }\n\n const folderMiddleware = routeModule.config?.skipInherited\n ? []\n : route.sharedFiles.flatMap((file) =>\n normalizeMiddleware((loadShared(file) as { middleware?: unknown }).middleware, file),\n );\n const verbMiddleware = normalizeMiddleware(routeModule.middleware, route.file);\n\n return {\n method: route.method,\n path: route.path,\n handle: routeModule.handle,\n middleware: [...folderMiddleware, ...verbMiddleware],\n input: routeInput(routeModule, route.file),\n services: options.services,\n cookieSecret: config.cookieSecret,\n };\n };\n\n for (const route of routes) {\n if (!options.lazy) {\n config.adapter.register(app, runtimeFor(route));\n continue;\n }\n\n let runtime: GiriRouteRegistration | undefined;\n const getRuntime = (): GiriRouteRegistration => {\n runtime ??= runtimeFor(route);\n return runtime;\n };\n config.adapter.register(app, {\n method: route.method,\n path: route.path,\n get handle() {\n return getRuntime().handle;\n },\n get middleware() {\n return getRuntime().middleware;\n },\n get input() {\n return getRuntime().input;\n },\n services: options.services,\n cookieSecret: config.cookieSecret,\n });\n }\n } finally {\n unregisterAliasResolver?.();\n loader?.unregister();\n }\n\n return { app, routes, paths };\n}\n","import { cancel, log, spinner } from '@clack/prompts';\nimport { existsSync } from 'node:fs';\nimport { join, resolve, sep } from 'node:path';\nimport { exit } from 'node:process';\nimport { configSchema } from '../config/schema';\nimport { Value } from \"@sinclair/typebox/value\"\nimport { Static } from '@sinclair/typebox';\n\nconst assertES5 = async (unregister: () => void) => {\n try {\n require('./_es5.ts');\n } catch (e: any) {\n if ('errors' in e && Array.isArray(e.errors) && e.errors.length > 0) {\n const es5Error = (e.errors as any[]).filter((it) => it.text?.includes(`(\"es5\") is not supported yet`)).length > 0;\n if (es5Error) {\n log.error(\n `Please change compilerOptions.target from 'es5' to 'es6' or above in your tsconfig.json`\n );\n exit(1);\n }\n }\n log.error(e);\n exit(1);\n }\n};\n\nexport const safeRegister = async () => {\n const { register } = await import('esbuild-register/dist/node');\n let res: { unregister: () => void };\n try {\n res = register({\n format: 'cjs',\n loader: 'ts',\n });\n } catch {\n // tsx fallback\n res = {\n unregister: () => { },\n };\n }\n\n // has to be outside try catch to be able to run with tsx\n await assertES5(res.unregister);\n return res;\n}\n\nexport const findConfigPath = (cwd: string = resolve()): string | undefined => {\n for (const name of ['giri.config.ts', 'giri.config.js']) {\n const path = resolve(cwd, name);\n if (existsSync(path)) {\n return path;\n }\n }\n return undefined;\n};\n\nexport const load = async (opts: { throwOnError?: boolean } = {}) => {\n const fail = (message: string): never => {\n if (opts.throwOnError) {\n throw new Error(message);\n }\n log.error(message);\n exit(1);\n };\n\n const path = findConfigPath();\n if (!path) {\n fail(\"Config file not found.\")\n }\n\n const { unregister } = await safeRegister();\n let content: unknown;\n try {\n const required = require(`${path}`);\n content = required.default ?? required;\n } finally { }\n unregister();\n // get response and then check by each dialect independently\n const res = Value.Check(configSchema, content);\n if (!res) {\n const messages = [...Value.Errors(configSchema, content)].map((error) => error.message);\n if (!opts.throwOnError) {\n for (const message of messages) {\n log.error(message);\n }\n }\n fail(messages.join('\\n'));\n }\n return content as Static<typeof configSchema>\n}\n","import { Static, Type } from \"@sinclair/typebox\";\n\nexport const configSchema = Type.Object({\n adapter: Type.Any(),\n alias: Type.Optional(Type.Record(\n Type.String(),\n Type.Union([Type.String(), Type.Array(Type.String())]),\n )),\n outDir: Type.Optional(Type.String()),\n server: Type.Optional(Type.Object({\n port: Type.Optional(Type.Number()),\n hostname: Type.Optional(Type.String()),\n }, { additionalProperties: false })),\n errorSchema: Type.Optional(Type.Any()),\n cookieSecret: Type.Optional(Type.String()),\n}, { additionalProperties: false })","import { existsSync, readFileSync } from 'node:fs';\nimport { readdir } from 'node:fs/promises';\nimport { basename, dirname, join, relative, sep } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport ts from 'typescript';\nimport type { HttpMethod } from './types';\n\nconst METHOD_ORDER: HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS', 'HEAD'];\nconst METHOD_FROM_FILE = new Map<string, HttpMethod>(\n METHOD_ORDER.map((method) => [`+${method.toLowerCase()}`, method]),\n);\n\nexport interface RouteParam {\n name: string;\n catchAll: boolean;\n}\n\nexport interface ScannedRoute {\n method: HttpMethod;\n path: string;\n file: string;\n routeDir: string;\n routeSegments: string[];\n params: RouteParam[];\n /** The `+shared.ts` chain folder-cascading config. */\n sharedFiles: string[];\n}\n\nfunction normalizeSlashes(path: string): string {\n return path.split(sep).join('/');\n}\n\nfunction isRouteSourceFile(fileName: string): boolean {\n return /\\.(?:[cm]?[jt]s|[jt]sx)$/.test(fileName) && !fileName.endsWith('.d.ts');\n}\n\nfunction methodFromFile(fileName: string): HttpMethod | undefined {\n if (!isRouteSourceFile(fileName)) {\n return undefined;\n }\n const stem = fileName.replace(/\\.(?:[cm]?[jt]s|[jt]sx)$/, '').toLowerCase();\n return METHOD_FROM_FILE.get(stem);\n}\n\nfunction hasExportModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n}\n\nfunction hasDeclareModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.DeclareKeyword) ?? false);\n}\n\nfunction propertyName(node: ts.Node): string | undefined {\n if (ts.isIdentifier(node) || ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {\n return node.text;\n }\n if (ts.isPropertyAccessExpression(node)) {\n return node.name.text;\n }\n if (ts.isElementAccessExpression(node) && node.argumentExpression) {\n const argument = node.argumentExpression;\n if (ts.isStringLiteralLike(argument)) {\n return argument.text;\n }\n }\n return undefined;\n}\n\nfunction isExportsObject(node: ts.Expression): boolean {\n return ts.isIdentifier(node) && node.text === 'exports';\n}\n\nfunction isModuleExports(node: ts.Expression): boolean {\n return ts.isPropertyAccessExpression(node) &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === 'module' &&\n node.name.text === 'exports';\n}\n\nfunction isCommonJsHandleTarget(node: ts.Expression): boolean {\n if (!ts.isPropertyAccessExpression(node) && !ts.isElementAccessExpression(node)) {\n return false;\n }\n return propertyName(node) === 'handle' &&\n (isExportsObject(node.expression) || isModuleExports(node.expression));\n}\n\nfunction objectExportsHandle(node: ts.Expression): boolean {\n if (!ts.isObjectLiteralExpression(node)) {\n return false;\n }\n return node.properties.some((property) => {\n if (ts.isShorthandPropertyAssignment(property)) {\n return property.name.text === 'handle';\n }\n return (\n (ts.isPropertyAssignment(property) || ts.isMethodDeclaration(property)) &&\n propertyName(property.name) === 'handle'\n );\n });\n}\n\nfunction hasNamedHandleExport(source: ts.SourceFile): boolean {\n for (const statement of source.statements) {\n if (\n hasExportModifier(statement) &&\n !hasDeclareModifier(statement) &&\n ts.isFunctionDeclaration(statement) &&\n statement.name?.text === 'handle'\n ) {\n return true;\n }\n\n if (\n hasExportModifier(statement) &&\n !hasDeclareModifier(statement) &&\n ts.isVariableStatement(statement)\n ) {\n if (statement.declarationList.declarations.some(\n (declaration) => ts.isIdentifier(declaration.name) && declaration.name.text === 'handle',\n )) {\n return true;\n }\n }\n\n if (\n ts.isExportDeclaration(statement) &&\n !statement.isTypeOnly &&\n statement.exportClause &&\n ts.isNamedExports(statement.exportClause)\n ) {\n if (statement.exportClause.elements.some(\n (element) => !element.isTypeOnly && element.name.text === 'handle',\n )) {\n return true;\n }\n }\n\n if (!ts.isExpressionStatement(statement) || !ts.isBinaryExpression(statement.expression)) {\n continue;\n }\n const assignment = statement.expression;\n if (assignment.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {\n continue;\n }\n if (\n isCommonJsHandleTarget(assignment.left) ||\n (isModuleExports(assignment.left) && objectExportsHandle(assignment.right))\n ) {\n return true;\n }\n }\n return false;\n}\n\nfunction parseSource(file: string): ts.SourceFile {\n return ts.createSourceFile(\n file,\n readFileSync(file, 'utf8'),\n ts.ScriptTarget.Latest,\n true,\n );\n}\n\nfunction parseDiagnostics(source: ts.SourceFile): readonly ts.DiagnosticWithLocation[] {\n return (\n source as ts.SourceFile & {\n parseDiagnostics?: readonly ts.DiagnosticWithLocation[];\n }\n ).parseDiagnostics ?? [];\n}\n\nfunction formatSyntaxDiagnostic(diagnostic: ts.DiagnosticWithLocation): string {\n const position = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);\n const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\\n');\n return `${diagnostic.file.fileName}:${position.line + 1}:${position.character + 1} - error TS${diagnostic.code}: ${message}`;\n}\n\n/** Verify a TypeScript/JavaScript source file parses before accepting a watch update. */\nexport function assertSourceSyntax(file: string): void {\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/i.test(file)) {\n return;\n }\n const diagnostics = parseDiagnostics(parseSource(file));\n if (diagnostics.length > 0) {\n throw new SyntaxError(diagnostics.map(formatSyntaxDiagnostic).join('\\n'));\n }\n}\n\n/** Verify the route declares a named handle export without evaluating the module. */\nexport function assertRouteHandleExport(file: string): void {\n const source = parseSource(file);\n const diagnostics = parseDiagnostics(source);\n if (diagnostics.length > 0) {\n throw new SyntaxError(diagnostics.map(formatSyntaxDiagnostic).join('\\n'));\n }\n if (!hasNamedHandleExport(source)) {\n throw new Error(`${file} must export a named handle function.`);\n }\n}\n\nfunction sharedFileIn(dir: string, cache?: Map<string, string | undefined>): string | undefined {\n if (cache?.has(dir)) {\n return cache.get(dir);\n }\n for (const ext of ['ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts']) {\n const file = join(dir, `+shared.${ext}`);\n if (existsSync(file)) {\n cache?.set(dir, file);\n return file;\n }\n }\n cache?.set(dir, undefined);\n return undefined;\n}\n\nfunction physicalRouteSegments(routesDir: string, routeDir: string): string[] {\n const rel = relative(routesDir, routeDir);\n if (!rel) {\n return [];\n }\n return normalizeSlashes(rel).split('/').filter(Boolean);\n}\n\nfunction urlSegment(segment: string): { value?: string; param?: RouteParam } {\n if (/^\\(.+\\)$/.test(segment)) {\n return {};\n }\n\n const catchAll = /^\\[\\.\\.\\.(.+)\\]$/.exec(segment);\n if (catchAll) {\n const name = catchAll[1];\n return {\n value: `:${name}{.*}`,\n param: { name, catchAll: true },\n };\n }\n\n const param = /^\\[(.+)\\]$/.exec(segment);\n if (param) {\n const name = param[1];\n return {\n value: `:${name}`,\n param: { name, catchAll: false },\n };\n }\n\n return { value: segment };\n}\n\nexport function pathFromSegments(segments: string[]): { path: string; params: RouteParam[] } {\n const pathSegments: string[] = [];\n const params: RouteParam[] = [];\n\n for (const segment of segments) {\n const converted = urlSegment(segment);\n if (converted.value) {\n pathSegments.push(converted.value);\n }\n if (converted.param) {\n params.push(converted.param);\n }\n }\n\n return {\n path: pathSegments.length > 0 ? `/${pathSegments.join('/')}` : '/',\n params,\n };\n}\n\n/**\n * Every directory under `routesDir` (including itself), so `$types` can be generated for a\n * folder the moment it's created\n */\nexport async function scanRouteFolders(routesDir: string): Promise<string[]> {\n if (!existsSync(routesDir)) {\n return [];\n }\n const folders = [routesDir];\n const walk = async (dir: string): Promise<void> => {\n for (const entry of await readdir(dir, { withFileTypes: true })) {\n if (entry.isDirectory() && entry.name !== 'node_modules') {\n const full = join(dir, entry.name);\n folders.push(full);\n await walk(full);\n }\n }\n };\n await walk(routesDir);\n return folders;\n}\n\n/** Folder-derived params for any directory under `routesDir` (used for middleware `$types`). */\nexport function routeParamsForDir(routesDir: string, dir: string): RouteParam[] {\n return pathFromSegments(physicalRouteSegments(routesDir, dir)).params;\n}\n\n/** The ordered `+shared.ts` chain that applies to a directory. */\nexport function sharedFilesForDir(\n routesDir: string,\n dir: string,\n cache?: Map<string, string | undefined>,\n): string[] {\n const segments = physicalRouteSegments(routesDir, dir);\n const dirs = [routesDir];\n\n let current = routesDir;\n for (const segment of segments) {\n current = join(current, segment);\n dirs.push(current);\n }\n\n return dirs.map((currentDir) => sharedFileIn(currentDir, cache)).filter((file): file is string => Boolean(file));\n}\n\nexport async function scanRoutes(routesDir: string): Promise<ScannedRoute[]> {\n if (!existsSync(routesDir)) {\n return [];\n }\n\n const files = await glob('**/+*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}', {\n cwd: routesDir,\n absolute: true,\n onlyFiles: true,\n });\n\n const routes: ScannedRoute[] = [];\n const sharedCache = new Map<string, string | undefined>();\n\n for (const file of files) {\n const method = methodFromFile(basename(file));\n if (!method) {\n continue;\n }\n \n const routeDir = dirname(file);\n const routeSegments = physicalRouteSegments(routesDir, routeDir);\n const { path, params } = pathFromSegments(routeSegments);\n\n routes.push({\n method,\n path,\n file,\n routeDir,\n routeSegments,\n params,\n sharedFiles: sharedFilesForDir(routesDir, routeDir, sharedCache),\n });\n }\n\n return routes.sort((left, right) => {\n const pathOrder = left.path.localeCompare(right.path);\n if (pathOrder !== 0) {\n return pathOrder;\n }\n return METHOD_ORDER.indexOf(left.method) - METHOD_ORDER.indexOf(right.method);\n });\n}\n","export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';\n\nexport type StatusCode = number;\n\nexport type ResponseFormat = 'json' | 'text' | 'html';\n\nexport const typedResponseBrand: unique symbol = Symbol.for('giri.typed-response') as never;\nexport const nativeContextBrand: unique symbol = Symbol.for('giri.native-context') as never;\n\nexport interface TypedResponse<\n T,\n S extends StatusCode = StatusCode,\n F extends ResponseFormat = ResponseFormat,\n> {\n readonly [typedResponseBrand]: {\n data: T;\n status: S;\n format: F;\n };\n readonly data: T;\n readonly status: S;\n readonly format: F;\n readonly headers?: HeadersInit;\n}\n\nexport type HandlerResponse = Response | TypedResponse<unknown, StatusCode, ResponseFormat>;\n\nexport interface ValidatedInput {\n /**\n * The validated request body. For a single declared content-type it's that schema's\n * output; for several it's a discriminated union `{ type; data }` (see `ValidBody`).\n */\n body?: unknown;\n query?: unknown;\n}\n\n/** Attributes for a `Set-Cookie` header. `path` defaults to `/`. */\nexport interface CookieOptions {\n domain?: string;\n path?: string;\n /** Lifetime in seconds. */\n maxAge?: number;\n expires?: Date;\n httpOnly?: boolean;\n secure?: boolean;\n sameSite?: 'Strict' | 'Lax' | 'None' | 'strict' | 'lax' | 'none';\n partitioned?: boolean;\n priority?: 'Low' | 'Medium' | 'High' | 'low' | 'medium' | 'high';\n}\n\n/**\n * Cookie read/write, implemented per adapter with its runtime's native helpers. giri core\n * supplies the {@link CookieSink} (where to read from / write to); the adapter owns encoding.\n */\nexport interface CookieJar {\n get(name: string): string | undefined;\n all(): Record<string, string>;\n set(name: string, value: string, options?: CookieOptions): void;\n delete(name: string, options?: CookieOptions): void;\n getSigned(name: string): Promise<string | false | undefined>;\n setSigned(name: string, value: string, options?: CookieOptions): Promise<void>;\n}\n\n/** What core hands an adapter's cookie jar: the request to read from, the response sink to write to. */\nexport interface CookieSink {\n /** The incoming request, for reading the `Cookie` header. */\n request: Request;\n /** Append one already-serialized `Set-Cookie` header value to the response. */\n append(setCookieHeader: string): void;\n /** The configured `cookieSecret`, if any (for signed cookies). */\n secret?: string;\n}\n\n/** Builds a {@link CookieJar} bound to one request's {@link CookieSink}. Each adapter provides one. */\nexport type CookieJarFactory = (sink: CookieSink) => CookieJar;\n\nexport interface GiriRequest<Input extends ValidatedInput = ValidatedInput> {\n raw: Request;\n url: URL;\n method: string;\n header(name: string): string | null;\n json<T = unknown>(): Promise<T>;\n text(): Promise<string>;\n arrayBuffer(): Promise<ArrayBuffer>;\n formData(): Promise<FormData>;\n valid<K extends keyof Input & ('body' | 'query')>(key: K): Input[K];\n /** Read a request cookie by name, or `undefined` if absent. */\n cookie(name: string): string | undefined;\n /** All request cookies as a name: value map. */\n cookies(): Record<string, string>;\n /**\n * Read and verify a signed cookie. Resolves to the original value, `false` if the\n * signature was tampered with, or `undefined` if the cookie is absent. Requires\n * `cookieSecret` in `giri.config`.\n */\n signedCookie(name: string): Promise<string | false | undefined>;\n}\n\ndeclare global {\n /**\n * Global registration surface for app-wide types. `giri sync` augments\n * `Giri.Register[\"app\"]` from `src/main.ts` `init()` return type so `c.app` is\n * typed without per-route generics (the registration pattern).\n */\n namespace Giri {\n interface Register {}\n }\n}\n\n/**\n * The app-wide services container, the type of `c.app`. `giri sync` infers it from\n * `src/main.ts`'s `init()` return type (via the global `Giri.Register` augmentation);\n * until then it falls back to an open record. Leave `init` unannotated (its return is\n * the source of truth) and annotate `teardown`'s parameter with this:\n *\n * ```ts\n * export const init = () => ({ db }); // inferred\n * export const teardown = (services: Services) => services.db.close();\n * ```\n */\nexport type Services = Giri.Register extends { app: infer A }\n ? A\n : Record<string, unknown>;\n\nexport interface Context<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> {\n params: Params;\n /** App-wide services from `src/main.ts`'s `init()`, seeded into every request. */\n app: Services;\n req: GiriRequest<Input>;\n // Context vars (`c.set`/`c.get`). Keys declared by middleware (`Vars`) are typed;\n // any other key stays open (`unknown`) so untracked keys still work.\n set<K extends keyof Vars & string>(key: K, value: Vars[K]): void;\n set<K extends string>(key: K, value: unknown): void;\n get<K extends keyof Vars & string>(key: K): Vars[K];\n get<V = unknown>(key: string): V;\n json<T, S extends StatusCode = 200>(\n data: T,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<T, S, 'json'>;\n text<S extends StatusCode = 200>(\n text: string,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<string, S, 'text'>;\n /** An HTML response (`text/html`). Like `text`, the body is a string. */\n html<S extends StatusCode = 200>(\n html: string,\n status?: S,\n headers?: HeadersInit,\n ): TypedResponse<string, S, 'html'>;\n /** A raw-body response - string, stream, buffer, FormData, … (not documented in OpenAPI). */\n body(data: BodyInit | null, status?: StatusCode, headers?: HeadersInit): Response;\n /** Alias of `body`, mirroring Hono's `c.newResponse`. */\n newResponse(data: BodyInit | null, status?: StatusCode, headers?: HeadersInit): Response;\n /** A redirect (defaults to 302) with the `Location` header set. */\n redirect(location: string, status?: StatusCode): Response;\n /** A 404 Not Found response. */\n notFound(): Response;\n /**\n * Set a response header applied to whatever this handler returns. Pass `{ append: true }` to add\n * another value (e.g. `Set-Cookie`); omit `value` to delete. Mirrors Hono's `c.header`.\n */\n header(name: string, value?: string, options?: { append?: boolean }): void;\n /** Default status for `body`/`redirect`, and for `json`/`text`/`html` when no status arg is given. */\n status(code: StatusCode): void;\n /**\n * Set a response cookie via `Set-Cookie`. Pass `value: null` to delete it (send the\n * same `path`/`domain` you set it with). Stacks with other cookies set this request.\n */\n cookie(name: string, value: string | null, options?: CookieOptions): void;\n /** Set an HMAC-signed cookie. Requires `cookieSecret` in `giri.config`. */\n signedCookie(name: string, value: string, options?: CookieOptions): Promise<void>;\n}\n\nexport type Handle<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> = (c: Context<Params, Input, Vars>) => HandlerResponse | Promise<HandlerResponse>;\n\nexport type Next = () => Promise<HandlerResponse | void>;\n\n/** An OpenAPI security requirement, e.g. `{ bearerAuth: [] }`. */\nexport type SecurityRequirement = Record<string, string[]>;\n\nexport interface MiddlewareOpenApi {\n /** Security requirements this middleware enforces */\n security?: SecurityRequirement[];\n /** Optional scheme definitions, merged into `components.securitySchemes` so the doc is self-contained. */\n securitySchemes?: Record<string, unknown>;\n [key: string]: unknown;\n}\n\nexport interface MiddlewareOptions {\n openapi?: MiddlewareOpenApi;\n}\n\nexport interface Middleware<\n Params extends Record<string, string> = Record<string, string>,\n Input extends ValidatedInput = ValidatedInput,\n Vars extends Record<string, unknown> = {},\n> {\n (c: Context<Params, Input, Vars>, next: Next): HandlerResponse | void | Promise<HandlerResponse | void>;\n openapi?: MiddlewareOpenApi;\n}\n\n/** The context vars a middleware injects (its `Vars` type parameter). */\nexport type VarsOf<M> = M extends Middleware<Record<string, string>, ValidatedInput, infer V>\n ? V\n : {};\n\n/** Intersect the injected vars of a tuple of middleware (built with `stack(...)`). */\nexport type MergeStack<T> = T extends readonly [infer Head, ...infer Rest]\n ? VarsOf<Head> & MergeStack<Rest>\n : {};\n\n/**\n * Merge the injected vars of a `middleware` export. A `stack(...)` tuple is merged element-wise;\n * a single bare middleware (`export const middleware = fromHono(...)`) contributes its own vars; a\n * plain `Middleware[]` (not a `stack(...)` tuple) contributes nothing - its element types are lost.\n */\nexport type InferStackVars<T> = T extends readonly [unknown, ...unknown[]]\n ? MergeStack<T>\n : T extends Middleware<Record<string, string>, ValidatedInput, any>\n ? VarsOf<T>\n : {};\n\n/**\n * The vars injected by a module own `middleware` export (a `stack(...)`). Used by the\n * generated per-method handle so a verb file's own `export const middleware` types\n * `c.get`/`c.set`, on top of the folder's `+shared.ts` chain.\n */\nexport type MiddlewareVarsOf<M> = M extends { middleware: infer Stack }\n ? InferStackVars<Stack>\n : {};\n\n/** A JSON Schema object (JSON Schema 2020-12 / OpenAPI 3.1 dialect). */\nexport type JsonSchema = Record<string, unknown>;\n\nexport const inputSchemaBrand: unique symbol = Symbol.for('giri.input-schema') as never;\n\nexport type InputValidationResult<Output = unknown> =\n | { ok: true; value: Output }\n | { ok: false; issues: unknown };\n\n/**\n * A input schema every wrapper form (`body`/`query`) export takes. A vendor\n * adapter (`@boon4681/giri/validators/zod`, `@boon4681/giri/validators/valibot`, …) returns one; build a\n * custom one with `defineInputSchema`. giri core depends only on this interface, never\n * on a validator library. `validate` is the runtime check; `toJsonSchema` feeds OpenAPI.\n */\nexport interface GiriInputSchema<Output = unknown> {\n readonly [inputSchemaBrand]: true;\n validate(value: unknown): InputValidationResult<Output> | Promise<InputValidationResult<Output>>;\n toJsonSchema(): JsonSchema;\n}\n\n/** Extract the validated output type of a giri input schema: `Infer<typeof body>`. */\nexport type Infer<T> = T extends GiriInputSchema<infer Output> ? Output : never;\n\nexport type BodyContentType = 'json' | 'form' | 'urlencoded' | 'text';\n\nexport const bodySchemaBrand: unique symbol = Symbol.for('giri.body-schema') as never;\n\n/**\n * A request body declared as a set of accepted content-types wrapped form `body`\n * takes (`zod.body({ json, form })`). One key means that encoding only; several mean the\n * endpoint accepts any of them, dispatched at runtime on the request `Content-Type`.\n * Each entry is a plain `GiriInputSchema`, so `validate`/`toJsonSchema` work per content-type.\n */\nexport interface GiriBodySchema<\n Outputs extends Partial<Record<BodyContentType, unknown>> = Partial<Record<BodyContentType, unknown>>,\n> {\n readonly [bodySchemaBrand]: true;\n readonly contents: { [K in keyof Outputs & BodyContentType]: GiriInputSchema<Outputs[K]> };\n}\n\n/** True when `T` is a union of more than one member. */\ntype IsUnion<T, U = T> = T extends unknown ? ([U] extends [T] ? false : true) : never;\n\n/**\n * The validated body a handler receives. A single declared content-type yields that\n * schema's output directly; several yield a discriminated union keyed by content-type.\n */\nexport type ValidBody<B> = B extends GiriBodySchema<infer Outputs>\n ? IsUnion<keyof Outputs> extends true\n ? { [K in keyof Outputs]: { type: K; data: Outputs[K] } }[keyof Outputs]\n : Outputs[keyof Outputs]\n : never;\n\n/** The validated query a handler receives. */\nexport type ValidQuery<Q> = Q extends GiriInputSchema<infer Output> ? Output : never;\n\n/** Drop keys whose value resolved to `never` (an input the route didn't declare). */\ntype PruneNever<T> = { [K in keyof T as [T[K]] extends [never] ? never : K]: T[K] };\n\n/**\n * Derive a route's `ValidatedInput` from a module's `body`/`query` exports. The generated\n * per-method `$types` handle (`POST`, `GET`, …) uses this so handlers infer `c.req.valid`\n * with no manual generic.\n */\nexport type RouteInputOf<M> = PruneNever<{\n body: M extends { body: infer B } ? ValidBody<B> : never;\n query: M extends { query: infer Q } ? ValidQuery<Q> : never;\n}>;\n\nexport interface RouteInput {\n body?: GiriBodySchema;\n query?: GiriInputSchema;\n}\n\nexport interface RouteOpenApi {\n /** Omit this route from the generated `openapi.json` (it still serves normally). */\n hidden?: boolean;\n /**\n * OpenAPI tags - the grouping in doc viewers. On a `+shared.ts` they apply to every route in the\n * folder; the chain is merged and de-duplicated, so a route's tags add to\n * its folders'.\n */\n tags?: string[];\n /** Short operation summary. Cascades down the chain (a verb file overrides its folders). */\n summary?: string;\n /** Longer operation description. Cascades down the chain (a verb file overrides its folders). */\n description?: string;\n /** Marks the operation(s) deprecated. On a `+shared.ts` it deprecates the whole folder. */\n deprecated?: boolean;\n /** Unique operationId. Verb-file only - it is never inherited from a `+shared.ts`. */\n operationId?: string;\n}\n\nexport type RouteOpenApiConfig = RouteOpenApi | boolean;\n\nexport interface GiriRouteRegistration {\n method: HttpMethod;\n path: string;\n handle: Handle;\n middleware: Middleware[];\n input?: RouteInput;\n /** App-wide services to seed onto `c.app` (same instance for every route). */\n services?: Services;\n /** Secret for signing/verifying cookies (`c.signedCookie`), from `config.cookieSecret`. */\n cookieSecret?: string;\n}\n\nexport type GiriFetchHandler = (req: Request) => Response | Promise<Response>;\n\nexport interface GiriServeOptions {\n port: number;\n hostname?: string;\n}\n\nexport interface GiriServerInfo {\n address: string;\n port: number;\n}\n\nexport interface GiriServer {\n close(): void | Promise<void>;\n}\n\nexport interface GiriAdapter<App> {\n name?: string;\n createApp(): App;\n register(app: App, route: GiriRouteRegistration): void;\n fetch(app: App, req: Request): Promise<Response>;\n /**\n * Bind the configured backend's runtime to a port and start serving.\n * giri core stays runtime-agnostic: it hands the adapter a request handler\n * (so hot-reload keeps working) and the adapter owns the actual server.\n */\n serve(\n handler: GiriFetchHandler,\n options: GiriServeOptions,\n onListen?: (info: GiriServerInfo) => void,\n ): GiriServer;\n}\n\nexport interface GiriConfig<App = unknown> {\n adapter: GiriAdapter<App>;\n alias?: Record<string, string | string[]>;\n outDir?: string;\n server?: {\n port?: number;\n hostname?: string;\n };\n errorSchema?: unknown;\n /** Secret used to sign/verify cookies via `c.signedCookie` / `c.req.signedCookie`. */\n cookieSecret?: string;\n}\n\nexport interface GiriPaths {\n cwd: string;\n routesDir: string;\n outDir: string;\n}\n","import {\n type BodyContentType,\n type GiriBodySchema,\n type GiriInputSchema,\n type InputValidationResult,\n type RouteInput,\n type TypedResponse,\n type ValidatedInput,\n bodySchemaBrand,\n inputSchemaBrand,\n} from './types';\nimport { createTypedResponse } from './context';\n\ninterface PreparedInput {\n ok: true;\n validated: ValidatedInput;\n}\n\ninterface FailedInput {\n ok: false;\n response: TypedResponse<{ message: string; issues: unknown }, 400 | 415, 'json'>;\n}\n\nexport type PreparedRequestInput = PreparedInput | FailedInput;\n\n/**\n * Build a giri input schema from a `validate` + `toJsonSchema` pair. Vendor adapters use\n * this; you can call it directly to make a custom validator. The brand is a global symbol,\n * so a hand-rolled `{ [Symbol.for(\"giri.input-schema\")]: true, validate, toJsonSchema }` works too.\n */\nexport function defineInputSchema<Output>(\n schema: Omit<GiriInputSchema<Output>, typeof inputSchemaBrand>,\n): GiriInputSchema<Output> {\n return { [inputSchemaBrand]: true, ...schema };\n}\n\nexport function isGiriInputSchema(value: unknown): value is GiriInputSchema {\n return Boolean(\n value &&\n typeof value === 'object' &&\n (value as Record<symbol, unknown>)[inputSchemaBrand] === true,\n );\n}\n\n/**\n * Build a giri body schema from per-content-type input schemas. Validator adapters use this `zod.body({ json, form })`\n */\nexport function defineBodySchema<Outputs extends Partial<Record<BodyContentType, unknown>>>(\n contents: GiriBodySchema<Outputs>['contents'],\n): GiriBodySchema<Outputs> {\n return { [bodySchemaBrand]: true, contents };\n}\n\nexport function isGiriBodySchema(value: unknown): value is GiriBodySchema {\n return Boolean(\n value &&\n typeof value === 'object' &&\n (value as Record<symbol, unknown>)[bodySchemaBrand] === true,\n );\n}\n\nconst MIME_TO_CONTENT_TYPE: Record<string, BodyContentType> = {\n 'application/json': 'json',\n 'multipart/form-data': 'form',\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'text/plain': 'text',\n};\n\nfunction contentTypeFromHeader(header: string | null): BodyContentType | undefined {\n if (!header) {\n return undefined;\n }\n const mime = header.split(';', 1)[0].trim().toLowerCase();\n return MIME_TO_CONTENT_TYPE[mime];\n}\n\n/** Flatten a `FormData` into a plain object, collapsing repeated fields into arrays. */\nfunction formDataObject(form: FormData): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n form.forEach((value, key) => {\n const current = result[key];\n if (current === undefined) {\n result[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n result[key] = [current, value];\n }\n });\n return result;\n}\n\nasync function readRawBody(request: Request, contentType: BodyContentType): Promise<unknown> {\n const cloned = request.clone();\n if (contentType === 'json') {\n return cloned.json();\n }\n if (contentType === 'text') {\n return cloned.text();\n }\n return formDataObject(await cloned.formData());\n}\n\nfunction queryObject(url: URL): Record<string, string | string[]> {\n const result: Record<string, string | string[]> = {};\n for (const [key, value] of url.searchParams) {\n const current = result[key];\n if (current === undefined) {\n result[key] = value;\n } else if (Array.isArray(current)) {\n current.push(value);\n } else {\n result[key] = [current, value];\n }\n }\n return result;\n}\n\nasync function runValidation(\n schema: GiriInputSchema,\n value: unknown,\n label: string,\n): Promise<InputValidationResult> {\n if (!isGiriInputSchema(schema)) {\n throw new Error(\n `giri: ${label} schema must be wrapped with a validator, e.g. \\`export const ${label} = zod(...)\\` from @boon4681/giri/validators/zod.`,\n );\n }\n return schema.validate(value);\n}\n\nexport async function prepareRequestInput(request: Request, input?: RouteInput): Promise<PreparedRequestInput> {\n const validated: ValidatedInput = {};\n\n if (input?.query) {\n const query = queryObject(new URL(request.url));\n const result = await runValidation(input.query, query, 'query');\n if (!result.ok) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid query parameters.', issues: result.issues },\n 400,\n 'json',\n ),\n };\n }\n validated.query = result.value;\n }\n\n if (input?.body) {\n const contents = input.body.contents as Record<BodyContentType, GiriInputSchema>;\n const declared = Object.keys(contents) as BodyContentType[];\n const requested = contentTypeFromHeader(request.headers.get('content-type'));\n // Pick the schema matching the request's content-type; fall back to JSON when the\n // header is missing/unrecognized but JSON is on offer (so header-less posts still work).\n const chosen: BodyContentType | undefined =\n requested && contents[requested] ? requested : contents.json ? 'json' : undefined;\n\n if (!chosen) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Unsupported media type.', issues: { accepted: declared } },\n 415,\n 'json',\n ),\n };\n }\n\n let rawBody: unknown;\n try {\n rawBody = await readRawBody(request, chosen);\n } catch (error) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid request body.', issues: error },\n 400,\n 'json',\n ),\n };\n }\n\n const result = await runValidation(contents[chosen], rawBody, 'body');\n if (!result.ok) {\n return {\n ok: false,\n response: createTypedResponse(\n { message: 'Invalid request body.', issues: result.issues },\n 400,\n 'json',\n ),\n };\n }\n\n validated.body = declared.length > 1 ? { type: chosen, data: result.value } : result.value;\n }\n\n return { ok: true, validated };\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { resolveGiriPaths } from '../app';\nimport {\n routeParamsForDir,\n scanRouteFolders,\n scanRoutes,\n sharedFilesForDir,\n type ScannedRoute,\n} from '../routes';\nimport type { GiriConfig, GiriPaths, HttpMethod } from '../types';\nimport { writeAppTypes } from './app-types';\nimport type { RouteInputSchemas } from './inputs';\nimport { writeManifest } from './manifest';\nimport { writeOpenApi } from './openapi';\nimport { writeParamTypes, type TypeFolder } from './param-types';\nimport { extractRouteMeta, type RouteOpenApiMeta, type RouteSecurity } from './route-meta';\nimport { writeRouteTypes } from './route-types';\nimport type { RouteResponses } from './schema';\nimport { writeTsConfig } from './tsconfig';\nimport { assertSafeOutDir, pruneDir, slash, typeFilePath } from './util';\nimport {\n readSyncCache,\n SYNC_CACHE_NAME,\n syncFingerprint,\n writeSyncCache,\n} from './cache';\n\n/** A `$types.d.ts` for every folder under `routes/` even empty/new ones. */\nasync function typeFolders(paths: GiriPaths, routes: ScannedRoute[]): Promise<TypeFolder[]> {\n // `scanRoutes` (tinyglobby) yields forward-slash paths while `scanRouteFolders` yields\n // native-separator paths, so key the map on a slash-normalized dir to match either form.\n const verbsByDir = new Map<string, { method: HttpMethod; file: string }[]>();\n for (const route of routes) {\n const key = slash(route.routeDir);\n const list = verbsByDir.get(key) ?? [];\n list.push({ method: route.method, file: route.file });\n verbsByDir.set(key, list);\n }\n\n const dirs = await scanRouteFolders(paths.routesDir);\n const sharedCache = new Map<string, string | undefined>();\n return dirs.map((dir) => ({\n dir,\n params: routeParamsForDir(paths.routesDir, dir),\n sharedFiles: sharedFilesForDir(paths.routesDir, dir, sharedCache),\n verbs: verbsByDir.get(slash(dir)) ?? [],\n }));\n}\n\n/** The per-route metadata maps feeding `manifest.json` / `openapi.json`. */\nexport interface SyncData {\n responsesByFile: Map<string, RouteResponses>;\n inputsByFile: Map<string, RouteInputSchemas>;\n securityByFile: Map<string, RouteSecurity>;\n hiddenFiles: Set<string>;\n openapiByFile: Map<string, RouteOpenApiMeta>;\n}\n\nexport interface SyncResult {\n paths: GiriPaths;\n routes: ScannedRoute[];\n folders: TypeFolder[];\n /** Aggregated route metadata, so a watcher can update one route and re-serialize. */\n data: SyncData;\n}\n\n/**\n * Walk each route's `handle` return type into per-status JSON Schema. Best-effort: a\n * broken project (or missing TypeScript) must not break `sync`, so failures yield an\n * empty map and the manifest simply omits `responses`.\n */\nasync function extractResponses(paths: GiriPaths, routes: ScannedRoute[]): Promise<Map<string, RouteResponses>> {\n const byFile = new Map<string, RouteResponses>();\n if (routes.length === 0) {\n return byFile;\n }\n\n try {\n const { createSchemaProgram, extractRouteResponses } = await import('./schema/index.js');\n const files = [...new Set(routes.map((route) => route.file))];\n // Include the generated global app.d.ts so `c.app` resolves to its real type.\n const appTypes = join(paths.outDir, 'types', 'app.d.ts');\n const roots = existsSync(appTypes) ? [...files, appTypes] : files;\n const program = createSchemaProgram(paths, roots);\n for (const file of files) {\n byFile.set(file, extractRouteResponses(program, file));\n }\n } catch (error) {\n console.warn(`giri: skipped response schema generation (${(error as Error).message}).`);\n }\n\n return byFile;\n}\n\ninterface RuntimeMeta {\n inputsByFile: Map<string, RouteInputSchemas>;\n securityByFile: Map<string, RouteSecurity>;\n hiddenFiles: Set<string>;\n openapiByFile: Map<string, RouteOpenApiMeta>;\n}\n\n/** Load route modules once to derive input schemas, middleware security, and openapi metadata. */\nasync function extractMeta(\n config: Pick<GiriConfig, 'alias'>,\n paths: GiriPaths,\n routes: ScannedRoute[],\n): Promise<RuntimeMeta> {\n const inputsByFile = new Map<string, RouteInputSchemas>();\n const securityByFile = new Map<string, RouteSecurity>();\n const hiddenFiles = new Set<string>();\n const openapiByFile = new Map<string, RouteOpenApiMeta>();\n if (routes.length === 0) {\n return { inputsByFile, securityByFile, hiddenFiles, openapiByFile };\n }\n\n try {\n const meta = await extractRouteMeta(config, paths, routes);\n for (const [file, entry] of meta) {\n if (entry.input) {\n inputsByFile.set(file, entry.input);\n }\n if (entry.security) {\n securityByFile.set(file, entry.security);\n }\n if (entry.hidden) {\n hiddenFiles.add(file);\n }\n if (entry.openapi) {\n openapiByFile.set(file, entry.openapi);\n }\n }\n } catch (error) {\n console.warn(`giri: skipped input/security generation (${(error as Error).message}).`);\n }\n\n return { inputsByFile, securityByFile, hiddenFiles, openapiByFile };\n}\n\n/**\n * Scan `routes/` and (re)generate the whole `.giri/` payload. Each artifact has its own\n * module under `src/generator/`. Files are overwritten **in place** (no upfront wipe), so\n * the editor never sees `tsconfig`/`$types` vanish during a slow regeneration; orphaned\n * files from removed routes are pruned at the end.\n */\nexport async function syncProject<App>(\n config: Pick<GiriConfig<App>, 'alias' | 'outDir'>,\n options: { cwd?: string } = {},\n): Promise<SyncResult> {\n const paths = resolveGiriPaths(config, options.cwd);\n assertSafeOutDir(paths);\n const hadOutDir = existsSync(paths.outDir);\n const routes = await scanRoutes(paths.routesDir);\n const folders = await typeFolders(paths, routes);\n const fingerprint = await syncFingerprint(config, paths);\n const cached = await readSyncCache(paths, fingerprint);\n\n const generatedFiles = [\n join(paths.outDir, 'tsconfig.json'),\n join(paths.outDir, 'manifest.json'),\n join(paths.outDir, 'openapi.json'),\n join(paths.outDir, 'routes.d.ts'),\n join(paths.outDir, 'types', 'app.d.ts'),\n ...folders.map((folder) => typeFilePath(paths, folder.dir)),\n ];\n if (cached && generatedFiles.every(existsSync)) {\n return { paths, routes, folders, data: cached };\n }\n\n await mkdir(paths.outDir, { recursive: true });\n await writeParamTypes(paths, folders);\n await writeRouteTypes(paths, routes);\n await writeAppTypes(paths);\n await writeTsConfig(paths, config);\n\n // Response schemas need the generated tsconfig + $types to resolve, so extract last.\n const data: SyncData = cached ?? {\n responsesByFile: await extractResponses(paths, routes),\n ...await extractMeta(config, paths, routes),\n };\n await writeManifest(paths, routes, data);\n await writeOpenApi(paths, routes, data);\n await writeSyncCache(paths, fingerprint, data);\n\n if (hadOutDir) {\n await pruneDir(\n paths.outDir,\n new Set([\n join(paths.outDir, 'tsconfig.json'),\n join(paths.outDir, 'manifest.json'),\n join(paths.outDir, 'openapi.json'),\n join(paths.outDir, 'routes.d.ts'),\n join(paths.outDir, SYNC_CACHE_NAME),\n join(paths.outDir, 'types', 'app.d.ts'),\n ...folders.map((folder) => typeFilePath(paths, folder.dir)),\n ]),\n );\n }\n\n return { paths, routes, folders, data };\n}\n","import { existsSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport type { GiriPaths } from '../types';\nimport { GENERATED_HEADER, slash, writeGenerated } from './util';\n\nconst MAIN_EXTENSIONS = ['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'];\n\nfunction findMainFile(cwd: string): string | undefined {\n for (const ext of MAIN_EXTENSIONS) {\n const file = join(cwd, 'src', `main.${ext}`);\n if (existsSync(file)) {\n return file;\n }\n }\n return undefined;\n}\n\nfunction moduleSpecifier(fromDir: string, target: string): string {\n let path = slash(relative(fromDir, target)).replace(/\\.(?:[cm]?[jt]sx?)$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport async function writeAppTypes(paths: GiriPaths): Promise<void> {\n const file = join(paths.outDir, 'types', 'app.d.ts');\n const mainFile = findMainFile(paths.cwd);\n\n if (!mainFile) {\n await writeGenerated(file, [GENERATED_HEADER, 'export {};', ''].join('\\n'));\n return;\n }\n\n const spec = moduleSpecifier(join(paths.outDir, 'types'), mainFile);\n await writeGenerated(\n file,\n [\n GENERATED_HEADER,\n 'declare global {',\n ' namespace Giri {',\n ' interface Register {',\n ` app: typeof import(${JSON.stringify(spec)}) extends {`,\n ' init: (...args: any[]) => infer R;',\n ' }',\n ' ? Awaited<R>',\n ' : Record<string, unknown>;',\n ' }',\n ' }',\n '}',\n 'export {};',\n '',\n ].join('\\n'),\n );\n}\n","import { existsSync } from 'node:fs';\nimport { mkdir, readdir, rm, rmdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative, sep } from 'node:path';\nimport type { GiriPaths } from '../types';\n\nexport const GENERATED_HEADER = '// Generated by giri sync. Do not edit.';\n\nexport function slash(path: string): string {\n return path.split(sep).join('/');\n}\n\nexport function importPath(fromFile: string, toFile: string): string {\n let path = slash(relative(dirname(fromFile), toFile)).replace(/\\.d\\.ts$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport function relativeConfigPath(fromDir: string, toPath: string): string {\n let path = slash(relative(fromDir, toPath));\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\n/** A relative ESM module specifier from `fromDir` to a source file (extension stripped). */\nexport function moduleSpecifier(fromDir: string, target: string): string {\n let path = slash(relative(fromDir, target)).replace(/\\.(?:[cm]?[jt]sx?)$/, '');\n if (!path.startsWith('.')) {\n path = `./${path}`;\n }\n return path;\n}\n\nexport function typeFilePath(paths: GiriPaths, routeDir: string): string {\n // Mirror the folder's source directory (relative to the project root) under\n // `<outDir>/types/`. Combined with `rootDirs: [\"..\", \"./types\"]`, this lets a file's\n const sourceDir = relative(paths.cwd, routeDir);\n return join(paths.outDir, 'types', sourceDir, '$types.d.ts');\n}\n\nexport function assertSafeOutDir(paths: GiriPaths): void {\n const rel = relative(paths.cwd, paths.outDir);\n if (!rel || rel.startsWith('..') || rel.includes(`..${sep}`)) {\n throw new Error(`Refusing to sync outside the project root: ${paths.outDir}`);\n }\n}\n\nconst writeCache = new Map<string, string>();\n\n/** Write a generated file, skipping the write when its content is unchanged and still on disk. */\nexport async function writeGenerated(path: string, content: string): Promise<void> {\n if (writeCache.get(path) === content && existsSync(path)) {\n return;\n }\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content);\n writeCache.set(path, content);\n}\n\nexport async function writeJson(path: string, value: unknown): Promise<void> {\n await writeGenerated(path, `${JSON.stringify(value, null, 2)}\\n`);\n}\n\n/**\n * Remove generated files no longer in `keep`, plus any directories left empty. Lets sync\n * overwrite in place (no upfront wipe), so the editor never sees `tsconfig`/`$types`\n * disappear during a slow regeneration.\n */\nexport async function pruneDir(dir: string, keep: Set<string>): Promise<void> {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const entry of entries) {\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n await pruneDir(full, keep);\n await rmdir(full).catch(() => {}); // succeeds only if now empty\n } else if (!keep.has(full)) {\n await rm(full, { force: true });\n writeCache.delete(full); // a recreated file with identical content must write again\n }\n }\n}\n","import { join, relative } from 'node:path';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport type { RouteInputSchemas } from './inputs';\nimport type { RouteSecurity } from './route-meta';\nimport type { RouteResponses } from './schema';\nimport { slash, typeFilePath, writeJson } from './util';\n\nexport interface ManifestData {\n responsesByFile?: Map<string, RouteResponses>;\n inputsByFile?: Map<string, RouteInputSchemas>;\n securityByFile?: Map<string, RouteSecurity>;\n hiddenFiles?: Set<string>;\n}\n\n/** Emits `manifest.json`: the machine-readable route table consumed by tooling. */\nexport async function writeManifest(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: ManifestData = {},\n): Promise<void> {\n const manifest = {\n version: 1,\n routes: routes.map((route) => {\n const responses = data.responsesByFile?.get(route.file);\n const input = data.inputsByFile?.get(route.file);\n const security = data.securityByFile?.get(route.file);\n return {\n method: route.method,\n path: route.path,\n file: slash(relative(paths.cwd, route.file)),\n params: route.params,\n shared: route.sharedFiles.map((file) => slash(relative(paths.cwd, file))),\n types: slash(relative(paths.cwd, typeFilePath(paths, route.routeDir))),\n ...(data.hiddenFiles?.has(route.file) ? { hidden: true } : {}),\n ...(input ? { input } : {}),\n ...(security && security.security.length > 0 ? { security: security.security } : {}),\n responses: responses?.responses ?? [],\n ...(responses && Object.keys(responses.$defs).length > 0\n ? { $defs: responses.$defs }\n : {}),\n };\n }),\n };\n\n await writeJson(join(paths.outDir, 'manifest.json'), manifest);\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { OpenAPIV3_1 } from 'openapi-types';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport type { RouteInputSchemas } from './inputs';\nimport type { RouteOpenApiMeta, RouteSecurity } from './route-meta';\nimport type { JSONSchema, ResponseSchema, RouteResponses } from './schema';\nimport { writeJson } from './util';\n\nexport interface OpenApiData {\n responsesByFile?: Map<string, RouteResponses>;\n inputsByFile?: Map<string, RouteInputSchemas>;\n securityByFile?: Map<string, RouteSecurity>;\n hiddenFiles?: Set<string>;\n openapiByFile?: Map<string, RouteOpenApiMeta>;\n}\n\ntype JsonObject = Record<string, unknown>;\n\nconst REASON: Record<number, string> = {\n 200: 'OK',\n 201: 'Created',\n 202: 'Accepted',\n 204: 'No Content',\n 400: 'Bad Request',\n 401: 'Unauthorized',\n 403: 'Forbidden',\n 404: 'Not Found',\n 409: 'Conflict',\n 422: 'Unprocessable Entity',\n 500: 'Internal Server Error',\n};\n\nfunction toOpenApiPath(path: string): string {\n return path.replace(/:([A-Za-z0-9_]+)(?:\\{[^}]*\\})?/g, '{$1}');\n}\n\n/** Rewrite walker-local `#/$defs/X` refs to the document-level `#/components/schemas/X`. */\nfunction rewriteRefs(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(rewriteRefs);\n }\n if (value && typeof value === 'object') {\n const out: JsonObject = {};\n for (const [key, child] of Object.entries(value)) {\n if (key === '$ref' && typeof child === 'string' && child.startsWith('#/$defs/')) {\n out.$ref = child.replace('#/$defs/', '#/components/schemas/');\n } else {\n out[key] = rewriteRefs(child);\n }\n }\n return out;\n }\n return value;\n}\n\nfunction mediaTypeFor(format: 'json' | 'text'): string {\n return format === 'text' ? 'text/plain' : 'application/json';\n}\n\nconst BODY_MEDIA_TYPE: Record<string, string> = {\n json: 'application/json',\n form: 'multipart/form-data',\n urlencoded: 'application/x-www-form-urlencoded',\n text: 'text/plain',\n};\n\nfunction buildResponses(responses: ResponseSchema[]): JsonObject {\n if (responses.length === 0) {\n return { default: { description: 'Response' } };\n }\n\n const out: JsonObject = {};\n for (const response of responses) {\n const key = response.status === 'default' ? 'default' : String(response.status);\n const description =\n (typeof response.status === 'number' && REASON[response.status]) || 'Response';\n out[key] = {\n description,\n content: { [mediaTypeFor(response.format)]: { schema: rewriteRefs(response.schema) } },\n };\n }\n return out;\n}\n\nfunction pathParameters(route: ScannedRoute): JsonObject[] {\n const seen = new Set<string>();\n const params: JsonObject[] = [];\n for (const param of route.params) {\n if (seen.has(param.name)) {\n continue;\n }\n seen.add(param.name);\n params.push({ name: param.name, in: 'path', required: true, schema: { type: 'string' } });\n }\n return params;\n}\n\nfunction queryParameters(query: JSONSchema | undefined): JsonObject[] {\n if (!query || query.type !== 'object' || typeof query.properties !== 'object') {\n return [];\n }\n const properties = query.properties as Record<string, JSONSchema>;\n const required = Array.isArray(query.required) ? (query.required as string[]) : [];\n return Object.entries(properties).map(([name, schema]) => ({\n name,\n in: 'query',\n required: required.includes(name),\n schema: rewriteRefs(schema),\n }));\n}\n\nfunction readProjectInfo(cwd: string): { title: string; version: string } {\n const file = join(cwd, 'package.json');\n if (existsSync(file)) {\n try {\n const pkg = JSON.parse(readFileSync(file, 'utf8')) as { name?: string; version?: string };\n return { title: pkg.name ?? 'giri API', version: pkg.version ?? '0.0.0' };\n } catch {\n // fall through to defaults\n }\n }\n return { title: 'giri API', version: '0.0.0' };\n}\n\n/** Assemble an OpenAPI 3.1 document from the scanned routes + generated schemas. */\nexport function buildOpenApiDocument(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: OpenApiData = {},\n): OpenAPIV3_1.Document {\n const documentPaths: JsonObject = {};\n const schemas: JsonObject = {};\n const securitySchemes: JsonObject = {};\n const tagOrder: string[] = [];\n\n for (const route of routes) {\n if (data.hiddenFiles?.has(route.file)) {\n continue; // excluded from the doc via `openapi`/`+shared.ts`\n }\n const responses = data.responsesByFile?.get(route.file);\n const input = data.inputsByFile?.get(route.file);\n const security = data.securityByFile?.get(route.file);\n const meta = data.openapiByFile?.get(route.file);\n\n for (const [name, schema] of Object.entries(responses?.$defs ?? {})) {\n schemas[name] = rewriteRefs(schema);\n }\n\n const operation: JsonObject = {};\n if (meta?.tags && meta.tags.length > 0) {\n operation.tags = meta.tags;\n for (const tag of meta.tags) {\n if (!tagOrder.includes(tag)) {\n tagOrder.push(tag);\n }\n }\n }\n if (meta?.summary) {\n operation.summary = meta.summary;\n }\n if (meta?.description) {\n operation.description = meta.description;\n }\n if (meta?.operationId) {\n operation.operationId = meta.operationId;\n }\n if (meta?.deprecated) {\n operation.deprecated = true;\n }\n operation.responses = buildResponses(responses?.responses ?? []);\n\n const parameters = [...pathParameters(route), ...queryParameters(input?.query)];\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n if (input?.body) {\n const content: JsonObject = {};\n for (const [contentType, schema] of Object.entries(input.body)) {\n content[BODY_MEDIA_TYPE[contentType] ?? contentType] = {\n schema: rewriteRefs(schema),\n };\n }\n if (Object.keys(content).length > 0) {\n operation.requestBody = { required: true, content };\n }\n }\n if (security && security.security.length > 0) {\n operation.security = security.security;\n }\n if (security) {\n Object.assign(securitySchemes, security.securitySchemes);\n }\n\n const openApiPath = toOpenApiPath(route.path);\n const pathItem = (documentPaths[openApiPath] as JsonObject) ?? {};\n pathItem[route.method.toLowerCase()] = operation;\n documentPaths[openApiPath] = pathItem;\n }\n\n const document: JsonObject = {\n openapi: '3.1.0',\n info: readProjectInfo(paths.cwd),\n paths: documentPaths,\n };\n if (tagOrder.length > 0) {\n document.tags = tagOrder.map((name) => ({ name }));\n }\n const components: JsonObject = {};\n if (Object.keys(schemas).length > 0) {\n components.schemas = schemas;\n }\n if (Object.keys(securitySchemes).length > 0) {\n components.securitySchemes = securitySchemes;\n }\n if (Object.keys(components).length > 0) {\n document.components = components;\n }\n return document as unknown as OpenAPIV3_1.Document;\n}\n\n/** Emit `.giri/openapi.json`. */\nexport async function writeOpenApi(\n paths: GiriPaths,\n routes: ScannedRoute[],\n data: OpenApiData = {},\n): Promise<void> {\n await writeJson(join(paths.outDir, 'openapi.json'), buildOpenApiDocument(paths, routes, data));\n}\n","import { dirname } from 'node:path';\nimport type { RouteParam } from '../routes';\nimport type { GiriPaths, HttpMethod } from '../types';\nimport { GENERATED_HEADER, importPath, moduleSpecifier, typeFilePath, writeGenerated } from './util';\n\nexport interface TypeFolder {\n dir: string;\n params: RouteParam[];\n /** The `+shared.ts` chain whose injected vars apply here. */\n sharedFiles: string[];\n /** The verb files (`+get.ts`, `+post.ts`, …) in this folder, one method-named handle each. */\n verbs: { method: HttpMethod; file: string }[];\n}\n\nfunction paramsType(params: RouteParam[]): string {\n if (params.length === 0) {\n return '{}';\n }\n\n const unique = new Map<string, RouteParam>();\n for (const param of params) {\n unique.set(param.name, param);\n }\n\n const fields = [...unique.values()]\n .map((param) => ` ${JSON.stringify(param.name)}: string;`)\n .join('\\n');\n return `{\\n${fields}\\n}`;\n}\n\n/** Merge the injected vars of the folder's `+shared.ts` middleware chain */\nfunction middlewareVarsType(typesDir: string, sharedFile: string): string {\n const spec = JSON.stringify(moduleSpecifier(typesDir, sharedFile));\n return `(typeof import(${spec}) extends { middleware: infer M } ? import(\"@boon4681/giri\").InferStackVars<M> : {})`;\n}\n\nfunction ownSharedFile(dir: string, sharedFiles: string[]): string | undefined {\n for (let index = sharedFiles.length - 1; index >= 0; index -= 1) {\n if (dirname(sharedFiles[index]) === dir) {\n return sharedFiles[index];\n }\n }\n return undefined;\n}\n\nfunction varsType(paths: GiriPaths, file: string, dir: string, sharedFiles: string[]): string {\n const typesDir = dirname(file);\n const parts: string[] = [];\n if (dir !== paths.routesDir) {\n parts.push(`import(${JSON.stringify(importPath(file, typeFilePath(paths, dirname(dir))))}).Vars`);\n }\n\n const ownShared = ownSharedFile(dir, sharedFiles);\n if (ownShared) {\n parts.push(middlewareVarsType(typesDir, ownShared));\n }\n\n return parts.length > 0 ? parts.join('\\n & ') : '{}';\n}\n\nfunction methodExports(typesDir: string, verbs: TypeFolder['verbs']): string[] {\n return verbs.map(({ method, file }) => {\n const spec = JSON.stringify(moduleSpecifier(typesDir, file));\n const input = `import(\"@boon4681/giri\").RouteInputOf<typeof import(${spec})>`;\n const vars = `Vars & import(\"@boon4681/giri\").MiddlewareVarsOf<typeof import(${spec})>`;\n return `export type ${method} = import(\"@boon4681/giri\").Handle<Params, ${input}, ${vars}>;`;\n });\n}\n\nexport async function writeParamTypes(paths: GiriPaths, folders: TypeFolder[]): Promise<void> {\n await Promise.all(folders.map(({ dir, params, sharedFiles, verbs }) => {\n const file = typeFilePath(paths, dir);\n const typesDir = dirname(file);\n const lines = [\n GENERATED_HEADER,\n `export type Params = ${paramsType(params)};`,\n 'export type RouteParams = Params;',\n `export type Vars = ${varsType(paths, file, dir, sharedFiles)};`,\n 'export type Middleware<Injects extends Record<string, unknown> = {}> =',\n ' import(\"@boon4681/giri\").Middleware<Params, import(\"@boon4681/giri\").ValidatedInput, Injects>;',\n 'export type Handle<Input extends import(\"@boon4681/giri\").ValidatedInput = import(\"@boon4681/giri\").ValidatedInput> =',\n ' import(\"@boon4681/giri\").Handle<Params, Input, Vars>;',\n ];\n if (verbs.length > 0) {\n lines.push(...methodExports(typesDir, verbs));\n }\n lines.push('');\n return writeGenerated(file, lines.join('\\n'));\n }));\n}\n","import { readFileSync } from 'node:fs';\nimport ts from 'typescript';\nimport { registerAliasResolver } from '../app';\nimport { safeRegister } from '../loader/loader';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriConfig, GiriPaths, Middleware, SecurityRequirement } from '../types';\nimport { bodyToJsonSchemas, inputToJsonSchema, type RouteInputSchemas } from './inputs';\nimport { parseRouteOpenApi } from './schema/route-openapi';\n\nexport interface RouteSecurity {\n /** Operation-level `security` requirements, e.g. `[{ bearerAuth: [] }]`. */\n security: SecurityRequirement[];\n /** Scheme definitions to merge into `components.securitySchemes`. */\n securitySchemes: Record<string, unknown>;\n}\n\n/** Resolved OpenAPI operation metadata (everything on `openapi` except `hidden`). */\nexport interface RouteOpenApiMeta {\n tags?: string[];\n summary?: string;\n description?: string;\n deprecated?: boolean;\n operationId?: string;\n}\n\nexport interface RouteMeta {\n input?: RouteInputSchemas;\n security?: RouteSecurity;\n /** Excluded from `openapi.json` (via `openapi`/`+shared.ts` resolution). */\n hidden?: boolean;\n /** Operation metadata (tags/summary/…) resolved down the `+shared.ts` chain. */\n openapi?: RouteOpenApiMeta;\n}\n\ntype StaticOpenApi =\n | boolean\n | {\n hidden?: boolean;\n tags?: string[];\n summary?: string;\n description?: string;\n deprecated?: boolean;\n operationId?: string;\n };\n\ninterface StaticModuleMeta {\n openapi?: StaticOpenApi;\n middlewareSecurity: boolean;\n}\n\nfunction loadModule(file: string): Record<string, unknown> {\n const resolved = require.resolve(file);\n delete require.cache[resolved];\n return require(resolved) as Record<string, unknown>;\n}\n\nfunction interopDefault(value: unknown): unknown {\n if (value && typeof value === 'object' && 'default' in value) {\n return (value as { default: unknown }).default;\n }\n return value;\n}\n\nfunction middlewareFunctions(value: unknown): Middleware[] {\n const exported = interopDefault(value);\n if (typeof exported === 'function') {\n return [exported as Middleware];\n }\n if (Array.isArray(exported)) {\n return exported.filter((fn): fn is Middleware => typeof fn === 'function');\n }\n return [];\n}\n\nfunction readInput(routeModule: Record<string, unknown>): RouteInputSchemas | undefined {\n const input: RouteInputSchemas = {};\n const body = bodyToJsonSchemas(routeModule.body);\n const query = inputToJsonSchema(routeModule.query);\n if (body) {\n input.body = body;\n }\n if (query) {\n input.query = query;\n }\n return input.body || input.query ? input : undefined;\n}\n\nfunction hasExportModifier(node: ts.Node): boolean {\n return ts.canHaveModifiers(node) &&\n (ts.getModifiers(node)?.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword) ?? false);\n}\n\nfunction unwrapExpression(expression: ts.Expression): ts.Expression {\n let current = expression;\n while (\n ts.isParenthesizedExpression(current) ||\n ts.isAsExpression(current) ||\n ts.isSatisfiesExpression(current)\n ) {\n current = current.expression;\n }\n return current;\n}\n\nfunction staticBoolean(expression: ts.Expression): boolean | undefined {\n const value = unwrapExpression(expression);\n if (value.kind === ts.SyntaxKind.TrueKeyword) {\n return true;\n }\n if (value.kind === ts.SyntaxKind.FalseKeyword) {\n return false;\n }\n return undefined;\n}\n\nfunction staticString(expression: ts.Expression): string | undefined {\n const value = unwrapExpression(expression);\n return ts.isStringLiteralLike(value) ? value.text : undefined;\n}\n\nfunction staticStringArray(expression: ts.Expression): string[] | undefined {\n const value = unwrapExpression(expression);\n if (!ts.isArrayLiteralExpression(value)) {\n return undefined;\n }\n\n const strings: string[] = [];\n for (const element of value.elements) {\n const string = staticString(element);\n if (string === undefined) {\n return undefined;\n }\n strings.push(string);\n }\n return strings;\n}\n\nfunction propertyName(name: ts.PropertyName): string | undefined {\n if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) {\n return name.text;\n }\n return undefined;\n}\n\nfunction collectImportedNames(source: ts.SourceFile): Set<string> {\n const names = new Set<string>();\n for (const statement of source.statements) {\n if (!ts.isImportDeclaration(statement)) {\n continue;\n }\n const clause = statement.importClause;\n if (!clause) {\n continue;\n }\n if (clause.name) {\n names.add(clause.name.text);\n }\n const bindings = clause.namedBindings;\n if (bindings && ts.isNamespaceImport(bindings)) {\n names.add(bindings.name.text);\n }\n if (bindings && ts.isNamedImports(bindings)) {\n for (const element of bindings.elements) {\n names.add(element.name.text);\n }\n }\n }\n return names;\n}\n\nfunction expressionReferencesImportedMiddleware(expression: ts.Expression, importedNames: Set<string>): boolean {\n let found = false;\n const allowedImportedHelpers = new Set(['stack', 'fromHono']);\n const visit = (node: ts.Node): void => {\n if (found) {\n return;\n }\n if (ts.isIdentifier(node) && importedNames.has(node.text) && !allowedImportedHelpers.has(node.text)) {\n found = true;\n return;\n }\n ts.forEachChild(node, visit);\n };\n visit(expression);\n return found;\n}\n\nfunction parseStaticOpenApi(expression: ts.Expression): StaticOpenApi | undefined {\n const value = unwrapExpression(expression);\n const boolean = staticBoolean(value);\n if (boolean !== undefined) {\n return boolean;\n }\n if (!ts.isObjectLiteralExpression(value)) {\n return undefined;\n }\n\n const openapi: Exclude<StaticOpenApi, boolean> = {};\n for (const property of value.properties) {\n if (!ts.isPropertyAssignment(property)) {\n return undefined;\n }\n const name = propertyName(property.name);\n if (!name) {\n return undefined;\n }\n if (name === 'hidden') {\n const hidden = staticBoolean(property.initializer);\n if (hidden === undefined) {\n return undefined;\n }\n openapi.hidden = hidden;\n } else if (name === 'tags') {\n const tags = staticStringArray(property.initializer);\n if (!tags) {\n return undefined;\n }\n openapi.tags = tags;\n } else if (name === 'summary' || name === 'description' || name === 'operationId') {\n const string = staticString(property.initializer);\n if (string === undefined) {\n return undefined;\n }\n openapi[name] = string;\n } else if (name === 'deprecated') {\n const deprecated = staticBoolean(property.initializer);\n if (deprecated === undefined) {\n return undefined;\n }\n openapi.deprecated = deprecated;\n } else {\n return undefined;\n }\n }\n\n return openapi;\n}\n\nfunction readStaticModuleMeta(file: string): StaticModuleMeta | undefined {\n let source: ts.SourceFile;\n try {\n source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true);\n } catch {\n return undefined;\n }\n\n const importedNames = collectImportedNames(source);\n const sourceText = source.getFullText();\n const canSkipMiddlewareRuntime =\n !sourceText.includes('defineMiddleware') &&\n !sourceText.includes('.openapi');\n const meta: StaticModuleMeta = { middlewareSecurity: false };\n for (const statement of source.statements) {\n if (\n ts.isImportDeclaration(statement) ||\n ts.isInterfaceDeclaration(statement) ||\n ts.isTypeAliasDeclaration(statement) ||\n ts.isEmptyStatement(statement) ||\n !hasExportModifier(statement)\n ) {\n continue;\n }\n\n if (ts.isFunctionDeclaration(statement) && statement.name?.text === 'handle') {\n continue;\n }\n\n if (ts.isVariableStatement(statement)) {\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) {\n return undefined;\n }\n const name = declaration.name.text;\n if (name === 'openapi') {\n if (!declaration.initializer) {\n return undefined;\n }\n const openapi = parseStaticOpenApi(declaration.initializer);\n if (openapi === undefined) {\n return undefined;\n }\n meta.openapi = openapi;\n } else if (name === 'handle') {\n if (\n !declaration.initializer ||\n (!ts.isArrowFunction(declaration.initializer) &&\n !ts.isFunctionExpression(declaration.initializer))\n ) {\n return undefined;\n }\n continue;\n } else if (name === 'middleware') {\n if (\n !declaration.initializer ||\n !canSkipMiddlewareRuntime ||\n expressionReferencesImportedMiddleware(declaration.initializer, importedNames)\n ) {\n return undefined;\n }\n meta.middlewareSecurity = false;\n continue;\n } else {\n return undefined;\n }\n }\n continue;\n }\n\n return undefined;\n }\n\n return meta;\n}\n\nfunction resolveStaticOpenApi(route: ScannedRoute, routeModule: StaticModuleMeta, loadShared: (file: string) => StaticModuleMeta | undefined): { hidden: boolean; meta: RouteOpenApiMeta } | undefined {\n let hidden = false;\n const tags: string[] = [];\n const meta: RouteOpenApiMeta = {};\n\n const apply = (value: StaticOpenApi | undefined, isVerb: boolean): void => {\n if (value === false) {\n hidden = true;\n return;\n }\n if (value === true) {\n hidden = false;\n return;\n }\n if (!value) {\n return;\n }\n if (typeof value.hidden === 'boolean') {\n hidden = value.hidden;\n }\n if (value.tags) {\n tags.push(...value.tags);\n }\n if (typeof value.summary === 'string') {\n meta.summary = value.summary;\n }\n if (typeof value.description === 'string') {\n meta.description = value.description;\n }\n if (typeof value.deprecated === 'boolean') {\n meta.deprecated = value.deprecated;\n }\n if (isVerb && typeof value.operationId === 'string') {\n meta.operationId = value.operationId;\n }\n };\n\n for (const file of route.sharedFiles) {\n const shared = loadShared(file);\n if (!shared) {\n return undefined;\n }\n apply(shared.openapi, false);\n }\n apply(routeModule.openapi, true);\n\n if (tags.length > 0) {\n meta.tags = [...new Set(tags)];\n }\n return { hidden, meta };\n}\n\nfunction extractStaticMeta(\n route: ScannedRoute,\n routeModule: StaticModuleMeta,\n loadShared: (file: string) => StaticModuleMeta | undefined,\n): RouteMeta | undefined {\n const openapi = resolveStaticOpenApi(route, routeModule, loadShared);\n if (!openapi) {\n return undefined;\n }\n\n const meta: RouteMeta = {};\n if (openapi.hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi.meta).length > 0) {\n meta.openapi = openapi.meta;\n }\n return meta;\n}\n\nfunction extractRuntimeSharedMeta(\n route: ScannedRoute,\n routeModule: StaticModuleMeta,\n loadShared: (file: string) => Record<string, unknown>,\n): RouteMeta {\n const meta: RouteMeta = {};\n const security = collectSecurity(route, {}, loadShared);\n const { hidden, meta: openapi } = resolveOpenApi(route, { openapi: routeModule.openapi }, loadShared);\n if (security) {\n meta.security = security;\n }\n if (hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi).length > 0) {\n meta.openapi = openapi;\n }\n return meta;\n}\n\n/**\n * Resolve the `openapi` export down a route's `+shared.ts` chain. `tags` are\n * merged and de-duplicated so a folder groups its routes; scalar fields (summary/description/\n * deprecated) override (verb wins); `operationId` is taken only from the verb file.\n */\nfunction resolveOpenApi(\n route: ScannedRoute,\n routeModule: Record<string, unknown>,\n loadShared: (file: string) => Record<string, unknown>,\n): { hidden: boolean; meta: RouteOpenApiMeta } {\n let hidden = false;\n const tags: string[] = [];\n const meta: RouteOpenApiMeta = {};\n\n const apply = (value: unknown, isVerb: boolean): void => {\n if (value === false) {\n hidden = true;\n return;\n }\n if (value === true) {\n hidden = false;\n return;\n }\n const parsed = parseRouteOpenApi(value);\n if (!parsed) {\n return;\n }\n if (parsed.hidden !== undefined) {\n hidden = parsed.hidden;\n }\n if (parsed.tags) {\n tags.push(...parsed.tags);\n }\n if (parsed.summary !== undefined) {\n meta.summary = parsed.summary;\n }\n if (parsed.description !== undefined) {\n meta.description = parsed.description;\n }\n if (parsed.deprecated !== undefined) {\n meta.deprecated = parsed.deprecated;\n }\n if (isVerb && parsed.operationId !== undefined) {\n meta.operationId = parsed.operationId;\n }\n };\n\n for (const file of route.sharedFiles) {\n apply(loadShared(file).openapi, false);\n }\n apply(routeModule.openapi, true);\n\n if (tags.length > 0) {\n meta.tags = [...new Set(tags)];\n }\n return { hidden, meta };\n}\n\nfunction collectSecurity(\n route: ScannedRoute,\n routeModule: Record<string, unknown>,\n loadShared: (file: string) => Record<string, unknown>,\n): RouteSecurity | undefined {\n const skipInherited = Boolean(\n (routeModule.config as { skipInherited?: boolean } | undefined)?.skipInherited,\n );\n\n const middleware: Middleware[] = [];\n if (!skipInherited) {\n for (const file of route.sharedFiles) {\n middleware.push(...middlewareFunctions(loadShared(file).middleware));\n }\n }\n middleware.push(...middlewareFunctions(routeModule.middleware));\n\n const security: SecurityRequirement[] = [];\n const securitySchemes: Record<string, unknown> = {};\n for (const fn of middleware) {\n const openapi = fn.openapi;\n if (openapi?.security) {\n for (const requirement of openapi.security) {\n if (!security.some((seen) => JSON.stringify(seen) === JSON.stringify(requirement))) {\n security.push(requirement);\n }\n }\n }\n if (openapi?.securitySchemes) {\n Object.assign(securitySchemes, openapi.securitySchemes);\n }\n }\n\n return security.length > 0 || Object.keys(securitySchemes).length > 0\n ? { security, securitySchemes }\n : undefined;\n}\n\n/**\n * Load each route module once (with import aliases active) to derive runtime metadata:\n * input JSON Schemas from `body`/`query`, and OpenAPI `security` from the middleware\n * actually applied to the route (folder chain + verb, honoring `skipInherited`).\n */\nexport async function extractRouteMeta(\n config: Pick<GiriConfig, 'alias'>,\n paths: GiriPaths,\n routes: ScannedRoute[],\n): Promise<Map<string, RouteMeta>> {\n const byFile = new Map<string, RouteMeta>();\n const remainingRoutes: ScannedRoute[] = [];\n const runtimeSharedRoutes: { route: ScannedRoute; routeModule: StaticModuleMeta }[] = [];\n const staticCache = new Map<string, StaticModuleMeta | undefined>();\n const loadStatic = (file: string): StaticModuleMeta | undefined => {\n if (!staticCache.has(file)) {\n staticCache.set(file, readStaticModuleMeta(file));\n }\n return staticCache.get(file);\n };\n\n for (const route of routes) {\n const routeModule = loadStatic(route.file);\n if (!routeModule) {\n remainingRoutes.push(route);\n continue;\n }\n const meta = extractStaticMeta(route, routeModule, loadStatic);\n if (meta) {\n if (meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n continue;\n }\n runtimeSharedRoutes.push({ route, routeModule });\n }\n\n if (remainingRoutes.length === 0 && runtimeSharedRoutes.length === 0) {\n return byFile;\n }\n\n const { unregister } = await safeRegister();\n const unregisterAlias = registerAliasResolver(config.alias, paths.cwd);\n const sharedCache = new Map<string, Record<string, unknown>>();\n const loadShared = (file: string): Record<string, unknown> => {\n if (!sharedCache.has(file)) {\n try {\n sharedCache.set(file, loadModule(file));\n } catch {\n sharedCache.set(file, {});\n }\n }\n return sharedCache.get(file)!;\n };\n\n try {\n for (const { route, routeModule } of runtimeSharedRoutes) {\n const meta = extractRuntimeSharedMeta(route, routeModule, loadShared);\n if (meta.input || meta.security || meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n }\n for (const route of remainingRoutes) {\n try {\n const routeModule = loadModule(route.file);\n const meta: RouteMeta = {};\n const input = readInput(routeModule);\n const security = collectSecurity(route, routeModule, loadShared);\n const { hidden, meta: openapi } = resolveOpenApi(route, routeModule, loadShared);\n if (input) {\n meta.input = input;\n }\n if (security) {\n meta.security = security;\n }\n if (hidden) {\n meta.hidden = true;\n }\n if (Object.keys(openapi).length > 0) {\n meta.openapi = openapi;\n }\n if (meta.input || meta.security || meta.hidden || meta.openapi) {\n byFile.set(route.file, meta);\n }\n } catch {\n // A route that fails to load just contributes no metadata.\n }\n }\n } finally {\n unregisterAlias();\n unregister();\n }\n\n return byFile;\n}\n","import { isGiriBodySchema, isGiriInputSchema } from '../validation';\nimport type { BodyContentType } from '../types';\nimport type { JSONSchema } from './schema';\n\nexport interface RouteInputSchemas {\n /** JSON Schema per declared body content-type (`json`, `form`, …). */\n body?: Partial<Record<BodyContentType, JSONSchema>>;\n query?: JSONSchema;\n}\n\nfunction sanitize(schema: JSONSchema): JSONSchema {\n // `$schema` is meaningful standalone but noise once embedded in OpenAPI.\n const { $schema, ...rest } = schema;\n void $schema;\n return rest;\n}\n\n/**\n * Convert a declared input to JSON Schema by asking the wrapper.\n */\nexport function inputToJsonSchema(schema: unknown): JSONSchema | undefined {\n if (!isGiriInputSchema(schema)) {\n return undefined;\n }\n try {\n return sanitize(schema.toJsonSchema());\n } catch (error) {\n // A schema that can't be rendered to JSON Schema only costs its own request\n // documentation - it must not discard the route's other metadata (tags/security).\n console.warn(`giri: skipped a request schema that can't be represented as JSON Schema (${(error as Error).message}).`);\n return undefined;\n }\n}\n\n/**\n * Convert a declared body (`zod.body({ json, form })`) to a JSON Schema per content-type.\n * Returns `undefined` when the value isn't a giri body schema or carries no schemas.\n */\nexport function bodyToJsonSchemas(\n value: unknown,\n): Partial<Record<BodyContentType, JSONSchema>> | undefined {\n if (!isGiriBodySchema(value)) {\n return undefined;\n }\n const out: Partial<Record<BodyContentType, JSONSchema>> = {};\n for (const [contentType, schema] of Object.entries(value.contents)) {\n const json = inputToJsonSchema(schema);\n if (json) {\n out[contentType as BodyContentType] = json;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n}\n","import { Type, type Static, type TSchema } from '@sinclair/typebox';\nimport { Value } from '@sinclair/typebox/value';\n\nconst StringSchema = Type.String();\nconst BooleanSchema = Type.Boolean();\nconst StringArraySchema = Type.Array(StringSchema);\n\n/** Runtime shape of a route/`+shared.ts` `openapi` object (booleans are handled by the caller). */\nexport const routeOpenApiSchema = Type.Object(\n {\n hidden: Type.Optional(BooleanSchema),\n tags: Type.Optional(StringArraySchema),\n summary: Type.Optional(StringSchema),\n description: Type.Optional(StringSchema),\n deprecated: Type.Optional(BooleanSchema),\n operationId: Type.Optional(StringSchema),\n },\n { additionalProperties: true },\n);\n\nexport type RouteOpenApiInput = Static<typeof routeOpenApiSchema>;\n\nfunction pick<T extends TSchema>(schema: T, value: unknown): Static<T> | undefined {\n return Value.Check(schema, value) ? (value as Static<T>) : undefined;\n}\n\n/**\n * Parse an arbitrary `openapi` value into its known fields, dropping anything mistyped\n * field-by-field rather than rejecting the whole object — a malformed `summary` must not\n * discard a valid `tags`.\n */\nexport function parseRouteOpenApi(value: unknown): RouteOpenApiInput | undefined {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return undefined;\n }\n const o = value as Record<string, unknown>;\n const parsed: RouteOpenApiInput = {};\n if ('hidden' in o) {\n parsed.hidden = Boolean(o.hidden);\n }\n const tags = pick(StringArraySchema, o.tags);\n if (tags) {\n parsed.tags = tags;\n }\n parsed.summary = pick(StringSchema, o.summary);\n parsed.description = pick(StringSchema, o.description);\n parsed.operationId = pick(StringSchema, o.operationId);\n parsed.deprecated = pick(BooleanSchema, o.deprecated);\n return parsed;\n}\n","import { join } from 'node:path';\nimport type { ScannedRoute } from '../routes';\nimport type { GiriPaths } from '../types';\nimport { GENERATED_HEADER, importPath, typeFilePath, writeGenerated } from './util';\n\n/** Emits `routes.d.ts`: a `RouteParams` map keyed by `\"METHOD path\"` for the whole app. */\nexport async function writeRouteTypes(paths: GiriPaths, routes: ScannedRoute[]): Promise<void> {\n const file = join(paths.outDir, 'routes.d.ts');\n const lines = [\n GENERATED_HEADER,\n 'export interface RouteParams {',\n ];\n\n for (const route of routes) {\n const typeFile = typeFilePath(paths, route.routeDir);\n lines.push(\n ` ${JSON.stringify(`${route.method} ${route.path}`)}: import(${JSON.stringify(\n importPath(file, typeFile),\n )}).Params;`,\n );\n }\n\n lines.push('}', '');\n await writeGenerated(file, lines.join('\\n'));\n}\n","import { join, resolve } from 'node:path';\nimport type { GiriConfig, GiriPaths } from '../types';\nimport { relativeConfigPath, writeJson } from './util';\n\nfunction normalizeAlias(alias: GiriConfig['alias'], paths: GiriPaths): Record<string, string[]> {\n const result: Record<string, string[]> = {};\n for (const [key, value] of Object.entries(alias ?? {})) {\n const targets = Array.isArray(value) ? value : [value];\n // Alias values are written relative to the project root (the same base the\n // runtime resolver in app.ts uses), but the generated tsconfig lives in\n // outDir, so re-base each target onto outDir to keep them relative.\n result[key] = targets.map((target) =>\n relativeConfigPath(paths.outDir, resolve(paths.cwd, target)),\n );\n }\n return result;\n}\n\n/** Emits the `.giri/tsconfig.json` the project extends: rootDirs merge, aliases, plugin. */\nexport async function writeTsConfig(paths: GiriPaths, config: Pick<GiriConfig, 'alias'>): Promise<void> {\n const file = join(paths.outDir, 'tsconfig.json');\n await writeJson(file, {\n compilerOptions: {\n rootDirs: [\n '..',\n './types',\n ],\n paths: {\n // The tsconfig lives in outDir, so `$giri/*` maps to its own folder.\n '$giri/*': ['./*'],\n ...normalizeAlias(config.alias, paths),\n },\n plugins: [\n {\n name: '@boon4681/giri/tsc',\n },\n ],\n },\n include: [\n relativeConfigPath(paths.outDir, join(paths.cwd, 'src')),\n relativeConfigPath(paths.outDir, join(paths.cwd, 'giri.config.ts')),\n './types/**/*.d.ts',\n ],\n });\n}\n","import { createHash } from 'node:crypto';\nimport { existsSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { join, relative, resolve, sep } from 'node:path';\nimport { glob } from 'tinyglobby';\nimport type { GiriConfig, GiriPaths } from '../types';\nimport type { SyncData } from './sync';\nimport { slash, writeJson } from './util';\n\nconst CACHE_VERSION = 1;\nexport const SYNC_CACHE_NAME = '.sync-cache.json';\n\ninterface SyncCache {\n version: number;\n fingerprint: string;\n data: {\n responsesByFile: [string, unknown][];\n inputsByFile: [string, unknown][];\n securityByFile: [string, unknown][];\n hiddenFiles: string[];\n openapiByFile: [string, unknown][];\n };\n}\n\nfunction stableConfig(config: Pick<GiriConfig, 'alias' | 'outDir'>): unknown {\n const alias = Object.entries(config.alias ?? {})\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]);\n return { alias, outDir: config.outDir ?? '.giri' };\n}\n\n/** Hash inputs that can affect generated route types, schemas, or OpenAPI metadata. */\nexport async function syncFingerprint(\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\n paths: GiriPaths,\n): Promise<string> {\n const outRelative = slash(relative(paths.cwd, paths.outDir));\n const ignore = ['**/node_modules/**', '**/.git/**'];\n if (outRelative && !outRelative.startsWith('..')) {\n ignore.push(`${outRelative}/**`);\n }\n\n const files = await glob([\n 'src/**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json}',\n 'giri.config.{ts,js,mts,cts,mjs,cjs}',\n 'tsconfig*.json',\n 'package.json',\n 'package-lock.json',\n 'npm-shrinkwrap.json',\n 'yarn.lock',\n 'pnpm-lock.yaml',\n 'bun.lock',\n 'bun.lockb',\n ], {\n cwd: paths.cwd,\n absolute: false,\n onlyFiles: true,\n dot: true,\n ignore,\n });\n\n const hash = createHash('sha256');\n hash.update(JSON.stringify(stableConfig(config)));\n for (const file of files.sort()) {\n hash.update('\\0');\n hash.update(slash(file));\n hash.update('\\0');\n hash.update(await readFile(resolve(paths.cwd, file)));\n }\n return hash.digest('hex');\n}\n\nfunction cachePath(paths: GiriPaths): string {\n return join(paths.outDir, SYNC_CACHE_NAME);\n}\n\nfunction serializePath(paths: GiriPaths, file: string): string {\n return slash(relative(paths.cwd, file));\n}\n\nfunction deserializePath(paths: GiriPaths, file: string): string {\n return slash(resolve(paths.cwd, file.split('/').join(sep)));\n}\n\nfunction serializeMap<T>(paths: GiriPaths, values: Map<string, T>): [string, T][] {\n return [...values].map(([file, value]) => [serializePath(paths, file), value]);\n}\n\nfunction deserializeMap<T>(paths: GiriPaths, values: [string, T][]): Map<string, T> {\n return new Map(values.map(([file, value]) => [deserializePath(paths, file), value]));\n}\n\nexport async function readSyncCache(\n paths: GiriPaths,\n fingerprint: string,\n): Promise<SyncData | undefined> {\n const file = cachePath(paths);\n if (!existsSync(file)) {\n return undefined;\n }\n\n try {\n const cache = JSON.parse(await readFile(file, 'utf8')) as SyncCache;\n if (cache.version !== CACHE_VERSION || cache.fingerprint !== fingerprint) {\n return undefined;\n }\n return {\n responsesByFile: deserializeMap(paths, cache.data.responsesByFile),\n inputsByFile: deserializeMap(paths, cache.data.inputsByFile),\n securityByFile: deserializeMap(paths, cache.data.securityByFile),\n hiddenFiles: new Set(cache.data.hiddenFiles.map((entry) => deserializePath(paths, entry))),\n openapiByFile: deserializeMap(paths, cache.data.openapiByFile),\n } as SyncData;\n } catch {\n return undefined;\n }\n}\n\nexport async function writeSyncCache(\n paths: GiriPaths,\n fingerprint: string,\n data: SyncData,\n): Promise<void> {\n const cache: SyncCache = {\n version: CACHE_VERSION,\n fingerprint,\n data: {\n responsesByFile: serializeMap(paths, data.responsesByFile),\n inputsByFile: serializeMap(paths, data.inputsByFile),\n securityByFile: serializeMap(paths, data.securityByFile),\n hiddenFiles: [...data.hiddenFiles].map((file) => serializePath(paths, file)),\n openapiByFile: serializeMap(paths, data.openapiByFile),\n },\n };\n await writeJson(cachePath(paths), cache);\n}\n","import { existsSync, statSync } from 'node:fs';\r\nimport { basename, dirname, join, resolve } from 'node:path';\nimport { buildImportGraph } from '../loader/import-graph';\r\nimport {\r\n collectDependents,\r\n purgeGeneratedModules,\r\n purgeModules,\r\n purgeProjectModules,\r\n} from '../loader/module-loader';\r\nimport {\n assertRouteHandleExport,\n assertSourceSyntax,\n type ScannedRoute,\n} from '../routes';\nimport type { GiriConfig } from '../types';\r\nimport { writeManifest } from './manifest';\nimport { writeOpenApi } from './openapi';\nimport { extractRouteMeta } from './route-meta';\nimport { syncFingerprint, writeSyncCache } from './cache';\nimport { syncProject, type SyncResult } from './sync';\nimport { slash } from './util';\n\r\nexport type ChangeOutcome = 'incremental' | 'full' | 'skip';\n\nexport interface WatchApplyOptions {\n /** Let runtime HMR continue while OpenAPI/response metadata refreshes in the background. */\n deferMetadata?: boolean;\n}\n\nexport interface WatchUpdater {\n /**\r\n * Apply one watch event. Returns 'incremental'/'full' for real changes, or 'skip' for\r\n * directory notifications (the real edit always arrives as a separate file event).\r\n */\r\n apply(filename: string | null, options?: WatchApplyOptions): Promise<ChangeOutcome>;\n /** Wait for deferred metadata work, primarily for tests and controlled shutdowns. */\n settled(): Promise<void>;\n}\n\r\nexport function createWatchUpdater(\r\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\r\n initial: SyncResult,\r\n): WatchUpdater {\r\n const paths = initial.paths;\r\n let routes = initial.routes;\n const data = initial.data;\n let metadataQueue = Promise.resolve();\n\n const fullResync = async (): Promise<ChangeOutcome> => {\n await metadataQueue;\n purgeProjectModules(paths.cwd);\n const result = await syncProject(config, { cwd: paths.cwd });\r\n routes = result.routes;\r\n data.responsesByFile = result.data.responsesByFile;\r\n data.inputsByFile = result.data.inputsByFile;\r\n data.securityByFile = result.data.securityByFile;\r\n data.hiddenFiles = result.data.hiddenFiles;\r\n data.openapiByFile = result.data.openapiByFile;\r\n purgeGeneratedModules(paths.outDir);\r\n return 'full';\r\n };\r\n\r\n /** Recompute affected routes in one TypeScript program and one metadata-loading pass. */\n const reextractRoutes = async (affected: ScannedRoute[]): Promise<void> => {\n if (affected.length === 0) {\n return;\n }\n\n try {\n const { createSchemaProgram, extractRouteResponses } = await import('./schema/index.js');\n const appTypes = join(paths.outDir, 'types', 'app.d.ts');\n const files = affected.map((route) => route.file);\n const program = createSchemaProgram(\n paths,\n existsSync(appTypes) ? [...files, appTypes] : files,\n );\n for (const route of affected) {\n data.responsesByFile.set(\n route.file,\n extractRouteResponses(program, route.file),\n );\n }\n } catch {\n // keep the previous response schema on failure (e.g. mid-save / type error)\n }\n\n try {\n const meta = await extractRouteMeta(config, paths, affected);\n for (const route of affected) {\n const key = route.file;\n const entry = meta.get(key);\n data.inputsByFile.delete(key);\n data.securityByFile.delete(key);\n data.hiddenFiles.delete(key);\n data.openapiByFile.delete(key);\n if (entry?.input) {\n data.inputsByFile.set(key, entry.input);\n }\n if (entry?.security) {\n data.securityByFile.set(key, entry.security);\n }\n if (entry?.hidden) {\n data.hiddenFiles.add(key);\n }\n if (entry?.openapi) {\n data.openapiByFile.set(key, entry.openapi);\n }\n }\n } catch {\n // keep previous metadata on failure\n }\r\n };\r\n\r\n return {\n settled: () => metadataQueue,\n async apply(filename, options = {}) {\n if (!filename) {\r\n return fullResync();\r\n }\r\n // Filenames arrive relative to the watched `src/` (the parent of routes).\r\n const abs = resolve(dirname(paths.routesDir), filename);\r\n const file = slash(abs);\r\n if (!existsSync(abs)) {\r\n return fullResync();\r\n }\r\n\r\n // Ignore directory notifications. Windows' recursive fs.watch emits a `change` for a\r\n // folder whenever a file inside it is touched - including the access-time bumps from\r\n // the schema TypeScript program reading every route - which would otherwise trigger a\r\n // full resync per folder (a rebuild storm). The real edit always arrives as a file event.\r\n if (statSync(abs).isDirectory()) {\n return 'skip';\n }\n\n // TypeScript can still produce a partial AST for malformed source. Reject its parse\n // diagnostics before logging an update or replacing the last working app.\n assertSourceSyntax(abs);\n\n const isRoute = routes.some((candidate) => slash(candidate.file) === file);\n const isShared = routes.some((route) =>\n route.sharedFiles.some((shared) => slash(shared) === file),\n );\n const isMethodFile =\n /^\\+(?:get|post|put|patch|delete|options|head)\\.(?:[cm]?[jt]s|[jt]sx)$/i\n .test(basename(file));\n const isNewRouteStructure =\n file.startsWith(`${slash(paths.routesDir)}/`) &&\n /^\\+(?:get|post|put|patch|delete|options|head|shared)\\.(?:[cm]?[jt]s|[jt]sx)$/i\n .test(basename(file)) &&\n !isRoute &&\n !isShared;\n\n if (isRoute || (isNewRouteStructure && isMethodFile)) {\n assertRouteHandleExport(abs);\n }\n\n if (isNewRouteStructure) {\n return fullResync();\n }\n\n const graph = await buildImportGraph(config, paths.cwd);\n if (!graph.nodes.has(file) && !isRoute && !isShared) {\n return fullResync();\n }\n\n const dependents = collectDependents(graph, file);\r\n const affected = routes.filter((route) =>\n dependents.has(slash(route.file)) ||\n route.sharedFiles.some((shared) => dependents.has(slash(shared))),\n );\n purgeModules(dependents);\n const refreshMetadata = async (): Promise<void> => {\n await reextractRoutes(affected);\n await writeManifest(paths, routes, data);\n await writeOpenApi(paths, routes, data);\n await writeSyncCache(paths, await syncFingerprint(config, paths), data);\n purgeGeneratedModules(paths.outDir);\n };\n const task = metadataQueue.then(refreshMetadata);\n metadataQueue = task.catch((error) => {\n console.error('giri: deferred metadata update failed', error);\n });\n if (!options.deferMetadata) {\n await task;\n }\n return 'incremental';\n },\n };\r\n}\r\n","/**\n * Build the project's import graph from **source**, not from Node's `require.cache`.\n *\n * The watcher needs to know which routes (transitively) import a changed file so it can\n * rebuild just those. The require.cache only records edges for modules that were actually\n * evaluated at runtime, but `syncProject` resolves most routes statically and never `require`s\n * them - so those import edges are missing and a helper edit would fall back to a full resync.\n * Parsing the imports ourselves makes the graph independent of runtime evaluation.\n */\nimport { existsSync, readFileSync, statSync } from 'node:fs';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport ts from 'typescript';\nimport { glob } from 'tinyglobby';\nimport { resolveAliasRequest } from '../app';\nimport type { GiriConfig } from '../types';\nimport type { ModuleGraph } from './module-loader';\n\nconst RESOLVE_EXTS = ['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs'];\nconst JS_EXT = /\\.(?:c|m)?jsx?$/;\n\nconst toSlash = (path: string): string => path.split(sep).join('/');\n\n/** Resolve a module base (no/with extension) to a real file, trying extensions then `index.*`. */\nfunction probeFile(base: string): string | undefined {\n if (existsSync(base) && statSync(base).isFile()) {\n return base;\n }\n for (const ext of RESOLVE_EXTS) {\n const candidate = base + ext;\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n for (const ext of RESOLVE_EXTS) {\n const candidate = join(base, `index${ext}`);\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return undefined;\n}\n\n/** Resolve one import specifier to an absolute project file, or `undefined` for bare/external. */\nfunction resolveSpecifier(\n specifier: string,\n fromFile: string,\n alias: GiriConfig['alias'],\n cwd: string,\n): string | undefined {\n let target: string;\n if (specifier.startsWith('.')) {\n target = resolve(dirname(fromFile), specifier);\n } else {\n const aliased = resolveAliasRequest(specifier, alias, cwd);\n if (aliased === undefined) {\n return undefined; // bare import (node_modules) - not part of the project graph\n }\n target = aliased;\n }\n\n const resolved = probeFile(target);\n if (resolved) {\n return resolved;\n }\n // A `.js`/`.mjs` specifier in TS source usually points at its `.ts` sibling.\n if (JS_EXT.test(target)) {\n return probeFile(target.replace(JS_EXT, ''));\n }\n return undefined;\n}\n\n/** Collect every static/dynamic import + `require()`/`export … from` specifier in a source file. */\nfunction importSpecifiers(file: string): string[] {\n let source: ts.SourceFile;\n try {\n source = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, false);\n } catch {\n return [];\n }\n\n const specifiers: string[] = [];\n const visit = (node: ts.Node): void => {\n if (\n (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&\n node.moduleSpecifier &&\n ts.isStringLiteral(node.moduleSpecifier)\n ) {\n specifiers.push(node.moduleSpecifier.text);\n } else if (\n ts.isImportEqualsDeclaration(node) &&\n ts.isExternalModuleReference(node.moduleReference) &&\n ts.isStringLiteralLike(node.moduleReference.expression)\n ) {\n specifiers.push(node.moduleReference.expression.text);\n } else if (ts.isCallExpression(node)) {\n const isRequire = ts.isIdentifier(node.expression) && node.expression.text === 'require';\n const isDynamicImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;\n const [first] = node.arguments;\n if ((isRequire || isDynamicImport) && first && ts.isStringLiteralLike(first)) {\n specifiers.push(first.text);\n }\n }\n ts.forEachChild(node, visit);\n };\n visit(source);\n return specifiers;\n}\n\n/**\n * Statically scan every project source file under `cwd` (skipping `node_modules` and the\n * generated `outDir`) and resolve its imports into a `dep -> importers` graph keyed on\n * forward-slash paths, matching what `collectDependents` consumes. Type-only imports are\n * included on purpose: a route's response schema can depend on an imported type.\n */\nexport async function buildImportGraph(\n config: Pick<GiriConfig, 'alias' | 'outDir'>,\n cwd: string,\n): Promise<ModuleGraph> {\n const root = resolve(cwd);\n const outDir = resolve(root, config.outDir ?? '.giri') + sep;\n const outRel = relative(root, outDir).split(sep).join('/').replace(/\\/$/, '');\n const files = await glob('**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}', {\n cwd: root,\n absolute: true,\n onlyFiles: true,\n ignore: ['**/node_modules/**', '**/.git/**', outRel ? `${outRel}/**` : '.giri/**'],\n });\n\n const importers = new Map<string, Set<string>>();\n const nodes = new Set<string>();\n for (const file of files) {\n if (file.startsWith(outDir)) {\n continue;\n }\n // Standalone files are still graph nodes. Without this, a +shared.ts that only imports\n // external packages is mistaken for an unknown structural change and forces a full sync.\n nodes.add(toSlash(file));\n for (const specifier of importSpecifiers(file)) {\n const dep = resolveSpecifier(specifier, file, config.alias, root);\n if (!dep || dep.startsWith(outDir)) {\n continue;\n }\n const from = toSlash(file);\n const to = toSlash(dep);\n nodes.add(to);\n let set = importers.get(to);\n if (!set) {\n set = new Set();\n importers.set(to, set);\n }\n set.add(from);\n }\n }\n return { importers, nodes };\n}\n","/**\r\n * `require.cache` helpers for the dev watcher: purge stale modules so the next build re-evaluates\r\n * them. The import graph itself is built statically in `import-graph.ts` (require.cache only\r\n * records edges for modules that were actually evaluated, which misses statically-synced routes).\r\n */\r\nimport { resolve, sep } from 'node:path';\r\n\r\nexport interface ModuleGraph {\r\n importers: Map<string, Set<string>>;\r\n nodes: Set<string>;\r\n}\r\n\r\nconst toSlash = (path: string): string => path.split(sep).join('/');\r\n\r\nconst isProjectModule = (id: string, root: string): boolean => {\r\n return id.startsWith(root) && !id.includes(`${sep}node_modules${sep}`) && !id.includes(`${sep}.giri${sep}`);\r\n}\r\n\r\nexport const collectDependents = (graph: ModuleGraph, start: string): Set<string> => {\r\n const out = new Set<string>([start]);\r\n const stack = [start];\r\n while (stack.length > 0) {\r\n const current = stack.pop()!;\r\n for (const importer of graph.importers.get(current) ?? []) {\r\n if (!out.has(importer)) {\r\n out.add(importer);\r\n stack.push(importer);\r\n }\r\n }\r\n }\r\n return out;\r\n};\r\n\r\nexport const purgeModules = (files: Set<string>): void => {\r\n for (const id of Object.keys(require.cache)) {\r\n if (files.has(toSlash(id))) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};\r\n\r\n/**\r\n * Drop every cached module under the project root (skipping `node_modules` and `.giri`).\r\n */\r\nexport const purgeProjectModules = (cwd: string): void => {\r\n const root = resolve(cwd) + sep;\r\n for (const id of Object.keys(require.cache)) {\r\n if (isProjectModule(id, root)) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};\r\n\r\nexport const purgeGeneratedModules = (outDir: string): void => {\r\n const root = resolve(outDir) + sep;\r\n for (const id of Object.keys(require.cache)) {\r\n if (resolve(id).startsWith(root)) {\r\n delete require.cache[id];\r\n }\r\n }\r\n};","import { existsSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { safeRegister } from './loader/loader';\nimport type { Services } from './types';\n\nconst MAIN_EXTENSIONS = ['ts', 'tsx', 'mts', 'cts', 'js', 'jsx', 'mjs', 'cjs'];\n\nexport interface GiriLifecycle {\n /** Absolute path to the resolved `src/main.ts`, if one exists. */\n file?: string;\n /** Runtime startup: build the app's service container, awaited before serving. */\n init?: () => Services | Promise<Services>;\n /** Graceful shutdown: receives the container from `init`, run on process exit. */\n teardown?: (services: Services) => void | Promise<void>;\n}\n\nfunction resolveMainFile(cwd: string): string | undefined {\n for (const ext of MAIN_EXTENSIONS) {\n const file = join(cwd, 'src', `main.${ext}`);\n if (existsSync(file)) {\n return file;\n }\n }\n return undefined;\n}\n\n/**\n * Load the optional `src/main.ts` lifecycle module. Absent file ⇒ empty lifecycle\n * (serve immediately). `init`/`teardown` are validated to be functions if present.\n */\nexport async function loadLifecycle(cwd = process.cwd()): Promise<GiriLifecycle> {\n const file = resolveMainFile(resolve(cwd));\n if (!file) {\n return {};\n }\n\n const { unregister } = await safeRegister();\n try {\n const resolved = require.resolve(file);\n delete require.cache[resolved];\n const loaded = require(resolved) as Partial<GiriLifecycle>;\n\n const lifecycle: GiriLifecycle = { file };\n if (loaded.init !== undefined) {\n if (typeof loaded.init !== 'function') {\n throw new Error(`${file}: \"init\" must be a function.`);\n }\n lifecycle.init = loaded.init;\n }\n if (loaded.teardown !== undefined) {\n if (typeof loaded.teardown !== 'function') {\n throw new Error(`${file}: \"teardown\" must be a function.`);\n }\n lifecycle.teardown = loaded.teardown;\n }\n return lifecycle;\n } finally {\n unregister();\n }\n}\n\n/** Run `init()` once and normalize its result into a service container. */\nexport async function runInit(lifecycle: GiriLifecycle): Promise<Services> {\n if (!lifecycle.init) {\n return {} as Services;\n }\n const services = await lifecycle.init();\n return (services ?? {}) as Services;\n}\n","/**\n * A tiny, dependency-free logger styled after Vite's dev output:\n * `HH:MM:SS [giri] (scope) message`. Colors auto-disable for non-TTY output, `NO_COLOR`,\n * or `TERM=dumb`, so piped/CI logs stay clean.\n */\n\nconst noColor =\n !process.stdout.isTTY ||\n process.env.NO_COLOR !== undefined ||\n process.env.TERM === 'dumb' ||\n process.env.FORCE_COLOR === '0';\n\nfunction paint(open: number, close: number): (text: string) => string {\n return (text) => (noColor ? text : `\\x1b[${open}m${text}\\x1b[${close}m`);\n}\n\nexport const color = {\n dim: paint(2, 22),\n bold: paint(1, 22),\n red: paint(31, 39),\n green: paint(32, 39),\n yellow: paint(33, 39),\n blue: paint(34, 39),\n magenta: paint(35, 39),\n cyan: paint(36, 39),\n gray: paint(90, 39),\n};\n\n/** Green for paths/values, like Vite highlights updated files. */\nexport const highlight = (text: string): string => color.green(text);\n/** Dim for secondary details (counts, durations). */\nexport const muted = (text: string): string => color.dim(text);\n\nfunction timestamp(): string {\n const now = new Date();\n const pad = (n: number): string => String(n).padStart(2, '0');\n return `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;\n}\n\nconst TAG = 'giri';\n\nfunction line(tag: string, message: string, scope?: string): string {\n const parts = [color.gray(timestamp()), tag];\n if (scope) {\n parts.push(color.dim(`(${scope})`));\n }\n parts.push(message);\n return parts.join(' ');\n}\n\nconst tag = {\n info: color.bold(color.cyan(`[${TAG}]`)),\n warn: color.bold(color.yellow(`[${TAG}]`)),\n error: color.bold(color.red(`[${TAG}]`)),\n};\n\n/** Preserve stack frames for real errors while still accepting arbitrary thrown values. */\nexport function formatError(error: unknown): string {\n if (error instanceof Error) {\n return error.stack ?? `${error.name}: ${error.message}`;\n }\n return String(error);\n}\n\nexport const log = {\n info(message: string, scope?: string): void {\n console.log(line(tag.info, message, scope));\n },\n success(message: string, scope?: string): void {\n console.log(line(tag.info, color.green(message), scope));\n },\n warn(message: string, scope?: string): void {\n console.warn(line(tag.warn, color.yellow(message), scope));\n },\n error(message: string, scope?: string): void {\n console.error(line(tag.error, color.red(message), scope));\n },\n ready(url: string): void {\n console.log(line(tag.info, `${color.green('ready')} on ${color.cyan(url)}`));\n },\n change(verb: string, path: string, count?: number): void {\n const suffix = count && count > 1 ? ` ${color.dim(`(x${count})`)}` : '';\n console.log(line(tag.info, `${color.green(verb)} ${highlight(path)}${suffix}`, 'watch'));\n },\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA,IAAM,GACC;AADP;AAAA;AAAA;AAAA,IAAM,IAAI;AACV,IAAO,cAAQ;AAAA;AAAA;;;ACgBR,SAAS,oBACZ,OACA,YACU;AACV,MAAI,UAA8B,EAAE,GAAG,gBAAgB;AAEvD,QAAM,aAAa,mBAAAA,QAAG,eAAe,MAAM,KAAK,mBAAAA,QAAG,IAAI,YAAY,eAAe;AAClF,MAAI,YAAY;AACZ,UAAM,SAAS,mBAAAA,QAAG,iCAAiC,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AK;AAE1B,MAAI,YAAY,QAAQ;AACpB,UAAM,SAAS,MAAM,YAAY,MAAM;AACvC,IAAAA,KAAI;AAAA,MACA,UAAU,OAAO,OAAO,MAAM,SAAS,OAAO,OAAO,WAAW,IAAI,KAAK,GAAG,IAAI,MAAM,MAAM,OAAO,MAAM,MAAM,EAAE,CAAC;AAAA,MAClH;AAAA,IACJ;AACA;AAAA,EACJ;AAEA,MAAI,YAAY,SAAS;AACrB,UAAM,aAAa,QAAQ,WAAW,IAAI,CAAC;AAC3C;AAAA,EACJ;AAEA,QAAM,IAAI,MAAM,oBAAoB,OAAO,EAAE;AACjD;AAEA,KAAK,EAAE,MAAM,CAAC,UAAU;AACpB,EAAAA,KAAI,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAChE,UAAQ,WAAW;AACvB,CAAC;","names":["ts","import_typescript","ts","import_typescript","ts","import_typescript","import_node_fs","import_promises","import_node_path","import_node_path","import_node_fs","import_node_path","ts","Module","import_node_fs","import_promises","import_node_path","import_node_fs","import_node_path","import_node_fs","import_promises","import_node_path","moduleSpecifier","import_node_path","import_node_fs","import_node_path","tag","import_node_path","import_node_fs","import_typescript","import_typebox","import_value","loadModule","interopDefault","hasExportModifier","ts","propertyName","import_node_path","import_node_path","import_node_fs","import_promises","import_node_path","import_tinyglobby","createSchemaProgram","extractRouteResponses","import_node_fs","import_node_path","import_node_fs","import_node_path","import_typescript","import_tinyglobby","ts","import_node_path","toSlash","createSchemaProgram","extractRouteResponses","import_node_fs","import_node_path","MAIN_EXTENSIONS","tag","log","initial","log"]}