@executor-js/emulate 0.6.0
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/README.md +1044 -0
- package/dist/api.d.ts +24 -0
- package/dist/api.js +2665 -0
- package/dist/api.js.map +1 -0
- package/dist/chunk-D6EKRYGP.js +1615 -0
- package/dist/chunk-D6EKRYGP.js.map +1 -0
- package/dist/chunk-WVQMFHQM.js +83 -0
- package/dist/chunk-WVQMFHQM.js.map +1 -0
- package/dist/dist-7FDUSG5I.js +24368 -0
- package/dist/dist-7FDUSG5I.js.map +1 -0
- package/dist/dist-7N4COJHK.js +1814 -0
- package/dist/dist-7N4COJHK.js.map +1 -0
- package/dist/dist-BTEY33DJ.js +2334 -0
- package/dist/dist-BTEY33DJ.js.map +1 -0
- package/dist/dist-DK26ESP2.js +595 -0
- package/dist/dist-DK26ESP2.js.map +1 -0
- package/dist/dist-IYZPDKJW.js +1284 -0
- package/dist/dist-IYZPDKJW.js.map +1 -0
- package/dist/dist-JJ2ZRCAX.js +189 -0
- package/dist/dist-JJ2ZRCAX.js.map +1 -0
- package/dist/dist-K4CVTD6K.js +1570 -0
- package/dist/dist-K4CVTD6K.js.map +1 -0
- package/dist/dist-M3GVASMR.js +1254 -0
- package/dist/dist-M3GVASMR.js.map +1 -0
- package/dist/dist-OYYGWKZQ.js +1533 -0
- package/dist/dist-OYYGWKZQ.js.map +1 -0
- package/dist/dist-P3SBBRFR.js +3169 -0
- package/dist/dist-P3SBBRFR.js.map +1 -0
- package/dist/dist-RMPDKZUA.js +1183 -0
- package/dist/dist-RMPDKZUA.js.map +1 -0
- package/dist/dist-WBKONLOE.js +2154 -0
- package/dist/dist-WBKONLOE.js.map +1 -0
- package/dist/dist-XM5HSBDC.js +1090 -0
- package/dist/dist-XM5HSBDC.js.map +1 -0
- package/dist/dist-XVVIYXQG.js +4241 -0
- package/dist/dist-XVVIYXQG.js.map +1 -0
- package/dist/dist-YPRJYQHW.js +5109 -0
- package/dist/dist-YPRJYQHW.js.map +1 -0
- package/dist/dist-ZEC77OKZ.js +913 -0
- package/dist/dist-ZEC77OKZ.js.map +1 -0
- package/dist/fonts/GeistPixel-Square.woff2 +0 -0
- package/dist/fonts/favicon.ico +0 -0
- package/dist/fonts/geist-sans.woff2 +0 -0
- package/dist/helpers-LXLP3DFE-LBOTATT5.js +17 -0
- package/dist/helpers-LXLP3DFE-LBOTATT5.js.map +1 -0
- package/dist/index.js +3005 -0
- package/dist/index.js.map +1 -0
- package/package.json +83 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../@emulators/vercel/src/store.ts","../../@emulators/vercel/src/helpers.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/http.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/ledger.ts","../../@emulators/core/src/manifest.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/control-plane.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/service-host.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../../@emulators/vercel/src/routes/user.ts","../../@emulators/vercel/src/routes/projects.ts","../../@emulators/vercel/src/routes/deployments.ts","../../@emulators/vercel/src/routes/domains.ts","../../@emulators/vercel/src/routes/env.ts","../../@emulators/vercel/src/routes/oauth.ts","../../@emulators/vercel/src/routes/api-keys.ts","../../@emulators/vercel/src/routes/openapi.ts","../../@emulators/vercel/src/manifest.ts","../../@emulators/vercel/src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type {\n VercelUser,\n VercelTeam,\n VercelTeamMember,\n VercelProject,\n VercelDeployment,\n VercelDeploymentAlias,\n VercelBuild,\n VercelDeploymentEvent,\n VercelFile,\n VercelDeploymentFile,\n VercelDomain,\n VercelEnvVar,\n VercelProtectionBypass,\n VercelIntegration,\n VercelApiKey,\n} from \"./entities.js\";\n\nexport interface VercelStore {\n users: Collection<VercelUser>;\n teams: Collection<VercelTeam>;\n teamMembers: Collection<VercelTeamMember>;\n projects: Collection<VercelProject>;\n deployments: Collection<VercelDeployment>;\n deploymentAliases: Collection<VercelDeploymentAlias>;\n builds: Collection<VercelBuild>;\n deploymentEvents: Collection<VercelDeploymentEvent>;\n files: Collection<VercelFile>;\n deploymentFiles: Collection<VercelDeploymentFile>;\n domains: Collection<VercelDomain>;\n envVars: Collection<VercelEnvVar>;\n protectionBypasses: Collection<VercelProtectionBypass>;\n apiKeys: Collection<VercelApiKey>;\n integrations: Collection<VercelIntegration>;\n}\n\nexport function getVercelStore(store: Store): VercelStore {\n return {\n users: store.collection<VercelUser>(\"vercel.users\", [\"uid\", \"username\"]),\n teams: store.collection<VercelTeam>(\"vercel.teams\", [\"uid\", \"slug\"]),\n teamMembers: store.collection<VercelTeamMember>(\"vercel.team_members\", [\"teamId\", \"userId\"]),\n projects: store.collection<VercelProject>(\"vercel.projects\", [\"uid\", \"name\", \"accountId\"]),\n deployments: store.collection<VercelDeployment>(\"vercel.deployments\", [\"uid\", \"projectId\", \"url\"]),\n deploymentAliases: store.collection<VercelDeploymentAlias>(\"vercel.deployment_aliases\", [\n \"deploymentId\",\n \"projectId\",\n ]),\n builds: store.collection<VercelBuild>(\"vercel.builds\", [\"deploymentId\"]),\n deploymentEvents: store.collection<VercelDeploymentEvent>(\"vercel.deployment_events\", [\"deploymentId\"]),\n files: store.collection<VercelFile>(\"vercel.files\", [\"digest\"]),\n deploymentFiles: store.collection<VercelDeploymentFile>(\"vercel.deployment_files\", [\"deploymentId\"]),\n domains: store.collection<VercelDomain>(\"vercel.domains\", [\"projectId\", \"name\"]),\n envVars: store.collection<VercelEnvVar>(\"vercel.env_vars\", [\"projectId\", \"uid\"]),\n protectionBypasses: store.collection<VercelProtectionBypass>(\"vercel.protection_bypasses\", [\"projectId\"]),\n apiKeys: store.collection<VercelApiKey>(\"vercel.api_keys\", [\"uid\", \"teamId\", \"userId\"]),\n integrations: store.collection<VercelIntegration>(\"vercel.integrations\", [\"client_id\"]),\n };\n}\n","import { randomBytes } from \"crypto\";\nimport type { Context } from \"@emulators/core\";\nimport type {\n VercelUser,\n VercelTeam,\n VercelProject,\n VercelDeployment,\n VercelDomain,\n VercelEnvVar,\n VercelDeploymentAlias,\n VercelBuild,\n} from \"./entities.js\";\nimport type { VercelStore } from \"./store.js\";\n\nexport function generateUid(prefix = \"\"): string {\n const id = randomBytes(12).toString(\"base64url\").slice(0, 20);\n return prefix ? `${prefix}_${id}` : id;\n}\n\nexport function generateSecret(): string {\n return randomBytes(32).toString(\"base64url\");\n}\n\nexport function nowMs(): number {\n return Date.now();\n}\n\nexport function resolveTeamScope(c: Context, vs: VercelStore): { accountId: string; team: VercelTeam | null } | null {\n const teamId = c.req.query(\"teamId\");\n const slug = c.req.query(\"slug\");\n\n if (teamId) {\n const team = vs.teams.findOneBy(\"uid\", teamId);\n if (!team) return null;\n return { accountId: team.uid, team };\n }\n\n if (slug) {\n const team = vs.teams.findOneBy(\"slug\", slug);\n if (!team) return null;\n return { accountId: team.uid, team };\n }\n\n const authUser = c.get(\"authUser\") as { login: string; id: number } | undefined;\n if (!authUser) return null;\n\n const user = vs.users.findOneBy(\"username\", authUser.login);\n if (!user) return null;\n\n return { accountId: user.uid, team: null };\n}\n\nexport function lookupProject(vs: VercelStore, idOrName: string, accountId: string): VercelProject | undefined {\n const project = vs.projects.findOneBy(\"uid\", idOrName);\n if (project && project.accountId === accountId) return project;\n\n const byName = vs.projects.findBy(\"name\", idOrName);\n return byName.find((p) => p.accountId === accountId);\n}\n\nexport interface CursorPagination {\n limit: number;\n since?: number;\n until?: number;\n from?: number;\n}\n\nexport function parseCursorPagination(c: Context): CursorPagination {\n return {\n limit: Math.min(100, Math.max(1, parseInt(c.req.query(\"limit\") ?? \"20\", 10) || 20)),\n since: c.req.query(\"since\") ? parseInt(c.req.query(\"since\")!, 10) : undefined,\n until: c.req.query(\"until\") ? parseInt(c.req.query(\"until\")!, 10) : undefined,\n from: c.req.query(\"from\") ? parseInt(c.req.query(\"from\")!, 10) : undefined,\n };\n}\n\nexport function applyCursorPagination<T extends { created_at: string }>(\n items: T[],\n pagination: CursorPagination,\n): { items: T[]; pagination: { count: number; next: number | null; prev: number | null } } {\n let filtered = [...items].sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime());\n\n if (pagination.since !== undefined) {\n filtered = filtered.filter((i) => new Date(i.created_at).getTime() > pagination.since!);\n }\n if (pagination.until !== undefined) {\n filtered = filtered.filter((i) => new Date(i.created_at).getTime() <= pagination.until!);\n }\n\n const total = filtered.length;\n const limited = filtered.slice(0, pagination.limit);\n const hasNext = total > pagination.limit;\n\n return {\n items: limited,\n pagination: {\n count: limited.length,\n next: hasNext && limited.length > 0 ? new Date(limited[limited.length - 1].created_at).getTime() : null,\n prev: limited.length > 0 ? new Date(limited[0].created_at).getTime() : null,\n },\n };\n}\n\nexport function formatUser(user: VercelUser) {\n return {\n id: user.uid,\n email: user.email,\n name: user.name,\n username: user.username,\n avatar: user.avatar,\n defaultTeamId: user.defaultTeamId,\n version: user.version,\n createdAt: new Date(user.created_at).getTime(),\n softBlock: user.softBlock,\n billing: user.billing,\n resourceConfig: user.resourceConfig,\n stagingPrefix: user.stagingPrefix,\n };\n}\n\nexport function formatTeam(team: VercelTeam) {\n return {\n id: team.uid,\n slug: team.slug,\n name: team.name,\n avatar: team.avatar,\n description: team.description,\n creatorId: team.creatorId,\n createdAt: new Date(team.created_at).getTime(),\n updatedAt: new Date(team.updated_at).getTime(),\n membership: team.membership,\n billing: team.billing,\n resourceConfig: team.resourceConfig,\n stagingPrefix: team.stagingPrefix,\n };\n}\n\nexport function formatProject(project: VercelProject, baseUrl: string) {\n return {\n accountId: project.accountId,\n autoAssignCustomDomains: project.autoAssignCustomDomains,\n autoAssignCustomDomainsUpdatedBy: project.autoAssignCustomDomainsUpdatedBy,\n buildCommand: project.buildCommand,\n createdAt: new Date(project.created_at).getTime(),\n devCommand: project.devCommand,\n directoryListing: false,\n framework: project.framework,\n gitForkProtection: project.gitForkProtection,\n gitComments: project.gitComments,\n id: project.uid,\n installCommand: project.installCommand,\n name: project.name,\n nodeVersion: project.nodeVersion,\n outputDirectory: project.outputDirectory,\n publicSource: project.publicSource,\n rootDirectory: project.rootDirectory,\n commandForIgnoringBuildStep: project.commandForIgnoringBuildStep,\n serverlessFunctionRegion: project.serverlessFunctionRegion,\n sourceFilesOutsideRootDirectory: project.sourceFilesOutsideRootDirectory,\n updatedAt: new Date(project.updated_at).getTime(),\n live: project.live,\n link: project.link,\n latestDeployments: project.latestDeployments,\n targets: project.targets,\n protectionBypass: project.protectionBypass,\n passwordProtection: project.passwordProtection,\n ssoProtection: project.ssoProtection,\n trustedIps: project.trustedIps,\n connectConfigurationId: project.connectConfigurationId,\n webAnalytics: project.webAnalytics,\n speedInsights: project.speedInsights,\n oidcTokenConfig: project.oidcTokenConfig,\n tier: project.tier,\n };\n}\n\nexport function formatDeployment(dep: VercelDeployment, vs: VercelStore, baseUrl: string) {\n const project = vs.projects.findOneBy(\"uid\", dep.projectId);\n const creator = vs.users.findOneBy(\"uid\", dep.creatorId);\n const aliases = vs.deploymentAliases.findBy(\"deploymentId\", dep.uid);\n\n return {\n uid: dep.uid,\n id: dep.uid,\n name: dep.name,\n url: dep.url,\n created: new Date(dep.created_at).getTime(),\n createdAt: new Date(dep.created_at).getTime(),\n source: dep.source,\n state: dep.state,\n readyState: dep.readyState,\n readySubstate: dep.readySubstate,\n type: \"LAMBDAS\",\n creator: creator ? { uid: creator.uid, email: creator.email, username: creator.username } : null,\n inspectorUrl: dep.inspectorUrl,\n meta: dep.meta,\n target: dep.target,\n aliasAssigned: dep.aliasAssigned,\n aliasError: dep.aliasError,\n buildingAt: dep.buildingAt,\n readyAt: dep.readyAt,\n bootedAt: dep.bootedAt,\n canceledAt: dep.canceledAt,\n errorCode: dep.errorCode,\n errorMessage: dep.errorMessage,\n regions: dep.regions,\n functions: dep.functions,\n routes: dep.routes,\n plan: dep.plan,\n projectId: dep.projectId,\n gitSource: dep.gitSource,\n alias: aliases.map((a) => a.alias),\n };\n}\n\nexport function formatDeploymentBrief(dep: VercelDeployment, vs: VercelStore) {\n const creator = vs.users.findOneBy(\"uid\", dep.creatorId);\n return {\n uid: dep.uid,\n name: dep.name,\n url: dep.url,\n created: new Date(dep.created_at).getTime(),\n state: dep.state,\n readyState: dep.readyState,\n type: \"LAMBDAS\",\n creator: creator ? { uid: creator.uid, email: creator.email, username: creator.username } : null,\n meta: dep.meta,\n target: dep.target,\n aliasAssigned: dep.aliasAssigned,\n projectId: dep.projectId,\n };\n}\n\nexport function formatDomain(domain: VercelDomain) {\n return {\n name: domain.name,\n apexName: domain.apexName,\n projectId: domain.projectId,\n redirect: domain.redirect,\n redirectStatusCode: domain.redirectStatusCode,\n gitBranch: domain.gitBranch,\n customEnvironmentId: domain.customEnvironmentId,\n updatedAt: new Date(domain.updated_at).getTime(),\n createdAt: new Date(domain.created_at).getTime(),\n verified: domain.verified,\n verification: domain.verified ? [] : domain.verification,\n };\n}\n\nexport function formatEnvVar(env: VercelEnvVar, decrypt = false) {\n return {\n type: env.type,\n id: env.uid,\n key: env.key,\n value: decrypt || env.type === \"plain\" ? env.value : \"\",\n target: env.target,\n gitBranch: env.gitBranch,\n customEnvironmentIds: env.customEnvironmentIds,\n configurationId: null,\n createdAt: new Date(env.created_at).getTime(),\n updatedAt: new Date(env.updated_at).getTime(),\n createdBy: null,\n updatedBy: null,\n comment: env.comment ?? \"\",\n };\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids)\n .map((id) => this.items.get(id)!)\n .filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`,\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { createServer as createNodeServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\n\ntype BodyInit = ConstructorParameters<typeof Response>[0];\ntype HeadersInit = ConstructorParameters<typeof Headers>[0];\ntype FormDataEntryValue = string | File;\n\nexport type ContentfulStatusCode = number;\nexport type Next = () => Promise<Response | void>;\n\ntype VariablesOf<E> = unknown extends E\n ? Record<string, any>\n : E extends { Variables: infer V }\n ? V\n : Record<string, any>;\ntype HandlerResult = Response | void | Promise<Response | void>;\n\nexport type Handler<E = unknown, P extends string = string> = (c: Context<E, P>, next: Next) => HandlerResult;\nexport type MiddlewareHandler<E = unknown> = Handler<E>;\nexport type ErrorHandler<E = unknown> = (err: unknown, c: Context<E>) => Response | Promise<Response>;\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\ninterface CompiledPath {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\ninterface Route<E> {\n method: string;\n compiled: CompiledPath;\n handlers: Handler<E>[];\n}\n\ninterface MatchedHandler<E> {\n handler: Handler<E>;\n params: Record<string, string>;\n}\n\nexport interface ServeOptions {\n fetch: FetchHandler;\n port?: number;\n hostname?: string;\n}\n\nexport interface CorsOptions {\n origin?: string;\n allowMethods?: string[];\n allowHeaders?: string[];\n credentials?: boolean;\n maxAge?: number;\n}\n\nexport class HonoRequest {\n readonly raw: Request;\n readonly url: string;\n readonly method: string;\n readonly path: string;\n /** The matched route pattern (e.g. /repos/:owner/:repo), when a route matched. */\n readonly routePath?: string;\n\n constructor(\n request: Request,\n private readonly params: Record<string, string>,\n routePath?: string,\n ) {\n this.raw = request;\n this.url = request.url;\n this.method = request.method;\n this.path = new URL(request.url).pathname;\n this.routePath = routePath;\n }\n\n header(): Record<string, string>;\n header(name: string): string | undefined;\n header(name?: string): Record<string, string> | string | undefined {\n if (name) return this.raw.headers.get(name) ?? undefined;\n const headers: Record<string, string> = {};\n this.raw.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return headers;\n }\n\n query(name: string): string | undefined {\n return new URL(this.url).searchParams.get(name) ?? undefined;\n }\n\n queries(name: string): string[] | undefined {\n const values = new URL(this.url).searchParams.getAll(name);\n return values.length > 0 ? values : undefined;\n }\n\n param(): Record<string, string>;\n param(name: string): string;\n param(name?: string): Record<string, string> | string {\n if (!name) return { ...this.params };\n return this.params[name] ?? \"\";\n }\n\n json<T = any>(): Promise<T> {\n return this.raw.json() as Promise<T>;\n }\n\n text(): Promise<string> {\n return this.raw.text();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.raw.arrayBuffer();\n }\n\n async parseBody(): Promise<Record<string, FormDataEntryValue | FormDataEntryValue[]>> {\n const contentType = this.header(\"Content-Type\") ?? \"\";\n if (contentType.includes(\"multipart/form-data\")) {\n return formDataToObject(await this.raw.formData());\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params = new URLSearchParams(await this.raw.text());\n const out: Record<string, string | string[]> = {};\n for (const [key, value] of params) {\n appendBodyValue(out, key, value);\n }\n return out;\n }\n if (contentType.includes(\"application/json\")) {\n const body = await this.raw.json().catch(() => ({}));\n return body && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, FormDataEntryValue | FormDataEntryValue[]>)\n : {};\n }\n return {};\n }\n}\n\nexport class Context<E = unknown, _P extends string = string> {\n readonly req: HonoRequest;\n private readonly vars = new Map<string, unknown>();\n private readonly responseHeaders = new Headers();\n private responseStatus = 200;\n\n constructor(\n request: Request,\n params: Record<string, string>,\n private readonly notFoundHandler: (c: Context<E>) => Response | Promise<Response>,\n routePath?: string,\n ) {\n this.req = new HonoRequest(request, params, routePath);\n }\n\n get<K extends keyof VariablesOf<E> & string>(key: K): VariablesOf<E>[K] | undefined {\n return this.vars.get(key) as VariablesOf<E>[K] | undefined;\n }\n\n set<K extends keyof VariablesOf<E> & string>(key: K, value: VariablesOf<E>[K]): void {\n this.vars.set(key, value);\n }\n\n header(name: string, value: string): void {\n this.responseHeaders.set(name, value);\n }\n\n status(status: number): void {\n this.responseStatus = status;\n }\n\n json(data: unknown, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(JSON.stringify(data), status, defaultContentType(headers, \"application/json; charset=UTF-8\"));\n }\n\n text(text: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(text, status, defaultContentType(headers, \"text/plain; charset=UTF-8\"));\n }\n\n html(html: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(html, status, defaultContentType(headers, \"text/html; charset=UTF-8\"));\n }\n\n body(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(body, status, headers);\n }\n\n redirect(location: string, status: ContentfulStatusCode = 302): Response {\n return this.response(null, status, { Location: location });\n }\n\n notFound(): Response | Promise<Response> {\n return this.notFoundHandler(this);\n }\n\n finalize(response: Response): Response {\n if (!hasHeaders(this.responseHeaders)) return response;\n const headers = new Headers(response.headers);\n this.responseHeaders.forEach((value, key) => {\n headers.set(key, value);\n });\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n private response(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n const merged = new Headers(headers);\n this.responseHeaders.forEach((value, key) => {\n merged.set(key, value);\n });\n return new Response(body, {\n status: status ?? this.responseStatus,\n headers: merged,\n });\n }\n}\n\nexport class Hono<E = unknown> {\n private readonly middleware: Route<E>[] = [];\n private readonly routes: Route<E>[] = [];\n private errorHandler: ErrorHandler<E> = (err) => {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return new Response(message, { status: 500 });\n };\n private notFoundHandler: (c: Context<E>) => Response | Promise<Response> = () =>\n new Response(\"404 Not Found\", { status: 404 });\n\n use<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;\n use(...handlers: Handler<E>[]): this;\n use<P extends string = string>(pathOrHandler: string | Handler<E>, ...handlers: Handler<E, P>[]): this {\n if (typeof pathOrHandler === \"string\") {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(pathOrHandler), handlers: handlers as Handler<E>[] });\n } else {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(\"*\"), handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n on<P extends string = string>(method: string, path: string, ...handlers: Handler<E, P>[]): this {\n this.routes.push({ method: method.toUpperCase(), compiled: compilePath(path), handlers: handlers as Handler<E>[] });\n return this;\n }\n\n get<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"GET\", path, ...handlers);\n }\n\n post<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"POST\", path, ...handlers);\n }\n\n put<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PUT\", path, ...handlers);\n }\n\n patch<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PATCH\", path, ...handlers);\n }\n\n delete<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"DELETE\", path, ...handlers);\n }\n\n onError(handler: ErrorHandler<E>): this {\n this.errorHandler = handler;\n return this;\n }\n\n notFound(handler: (c: Context<E>) => Response | Promise<Response>): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n async request(input: string | Request, init?: RequestInit): Promise<Response> {\n if (input instanceof Request) return this.fetch(input);\n const url = input.startsWith(\"/\") ? `http://localhost${input}` : input;\n return this.fetch(new Request(url, init));\n }\n\n fetch = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n const method = request.method.toUpperCase();\n const matched = this.match(method, path);\n const context = new Context<E>(request, matched.params, this.notFoundHandler, matched.routePattern);\n\n try {\n const response = await this.dispatch(context, matched.handlers);\n return context.finalize(response ?? (await this.notFoundHandler(context)));\n } catch (err) {\n return context.finalize(await this.errorHandler(err, context));\n }\n };\n\n private match(\n method: string,\n path: string,\n ): { handlers: MatchedHandler<E>[]; params: Record<string, string>; routePattern?: string } {\n const handlers: MatchedHandler<E>[] = [];\n const params: Record<string, string> = {};\n\n for (const route of this.middleware) {\n const match = matchPath(route.compiled, path);\n if (!match) continue;\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n const route =\n this.routes.find((candidate) => candidate.method === method && matchPath(candidate.compiled, path) != null) ??\n (method === \"HEAD\"\n ? this.routes.find((candidate) => candidate.method === \"GET\" && matchPath(candidate.compiled, path) != null)\n : undefined);\n\n if (route) {\n const match = matchPath(route.compiled, path) ?? {};\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n return { handlers, params, routePattern: route?.compiled.pattern };\n }\n\n private async dispatch(context: Context<E>, handlers: MatchedHandler<E>[]): Promise<Response | void> {\n let index = -1;\n const run = async (nextIndex: number): Promise<Response | void> => {\n if (nextIndex <= index) throw new Error(\"next() called multiple times\");\n index = nextIndex;\n const matched = handlers[nextIndex];\n if (!matched) return undefined;\n\n const originalParams = context.req.param();\n Object.assign(originalParams, matched.params);\n\n let nextResponse: Response | void = undefined;\n let nextCalled = false;\n const next: Next = async () => {\n nextCalled = true;\n nextResponse = await run(nextIndex + 1);\n return nextResponse;\n };\n\n const response = await matched.handler(context, next);\n if (response instanceof Response) return response;\n if (nextCalled) return nextResponse;\n return response;\n };\n\n return run(0);\n }\n}\n\nexport function cors(options: CorsOptions = {}): MiddlewareHandler {\n const origin = options.origin ?? \"*\";\n const allowMethods = options.allowMethods ?? [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n\n return async (c, next) => {\n c.header(\"Access-Control-Allow-Origin\", origin);\n if (options.credentials) c.header(\"Access-Control-Allow-Credentials\", \"true\");\n\n if (c.req.method.toUpperCase() === \"OPTIONS\") {\n c.header(\"Access-Control-Allow-Methods\", allowMethods.join(\",\"));\n const allowHeaders = options.allowHeaders?.join(\",\") ?? c.req.header(\"Access-Control-Request-Headers\");\n if (allowHeaders) c.header(\"Access-Control-Allow-Headers\", allowHeaders);\n if (options.maxAge != null) c.header(\"Access-Control-Max-Age\", String(options.maxAge));\n return c.body(null, 204);\n }\n\n await next();\n };\n}\n\nexport function serve(options: ServeOptions): Server {\n const port = options.port ?? 3000;\n const server = createNodeServer(async (req, res) => {\n try {\n const request = nodeRequestToFetchRequest(req);\n const response = await options.fetch(request);\n await writeFetchResponse(res, response, req.method?.toUpperCase() === \"HEAD\");\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=UTF-8\");\n res.end(message);\n }\n });\n server.listen(port, options.hostname);\n return server;\n}\n\nfunction compilePath(pattern: string): CompiledPath {\n if (pattern === \"*\" || pattern === \"/*\") {\n return { pattern, regex: /^.*$/, paramNames: [] };\n }\n\n const paramNames: string[] = [];\n let source = \"^\";\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char !== \":\") {\n source += escapeRegex(char);\n continue;\n }\n\n let name = \"\";\n i++;\n while (i < pattern.length && /[A-Za-z0-9_]/.test(pattern[i])) {\n name += pattern[i];\n i++;\n }\n i--;\n paramNames.push(name);\n\n if (pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 2);\n if (close < 0) throw new Error(`Invalid route pattern: ${pattern}`);\n const expr = pattern.slice(i + 2, close);\n source += `(${expr})`;\n i = close;\n } else {\n source += \"([^/]+)\";\n }\n }\n source += \"$\";\n return { pattern, regex: new RegExp(source), paramNames };\n}\n\nfunction matchPath(compiled: CompiledPath, path: string): Record<string, string> | null {\n const match = compiled.regex.exec(path);\n if (!match) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = decodePathParam(match[i + 1] ?? \"\");\n }\n return params;\n}\n\nfunction decodePathParam(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\nfunction hasHeaders(headers: Headers): boolean {\n for (const _ of headers) return true;\n return false;\n}\n\nfunction defaultContentType(headers: HeadersInit | undefined, contentType: string): Headers {\n const out = new Headers(headers);\n if (!out.has(\"Content-Type\")) {\n out.set(\"Content-Type\", contentType);\n }\n return out;\n}\n\nfunction formDataToObject(formData: FormData): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const out: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n for (const [key, value] of formData) {\n appendBodyValue(out, key, value);\n }\n return out;\n}\n\nfunction appendBodyValue<T>(target: Record<string, T | T[]>, key: string, value: T): void {\n const existing = target[key];\n if (existing === undefined) {\n target[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n target[key] = [existing, value];\n }\n}\n\nfunction nodeRequestToFetchRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? \"localhost\";\n const url = new URL(req.url ?? \"/\", `http://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n return new Request(url.toString(), {\n method,\n headers,\n body: hasBody ? (req as unknown as BodyInit) : undefined,\n duplex: \"half\",\n } as RequestInit & { duplex: string });\n}\n\nasync function writeFetchResponse(res: ServerResponse, response: Response, headOnly: boolean): Promise<void> {\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n\n const headersWithCookies = response.headers as Headers & { getSetCookie?: () => string[] };\n const cookies = headersWithCookies.getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\" && cookies && cookies.length > 0) return;\n res.setHeader(key, value);\n });\n if (cookies && cookies.length > 0) {\n res.setHeader(\"Set-Cookie\", cookies);\n }\n\n if (headOnly || !response.body) {\n res.end();\n return;\n }\n\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) {\n await new Promise<void>((resolve) => res.once(\"drain\", resolve));\n }\n }\n res.end();\n } catch (err) {\n res.destroy(err instanceof Error ? err : undefined);\n }\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>,\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return event === \"ping\" || s.events.includes(\"*\") || s.events.includes(event);\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ContentfulStatusCode, ErrorHandler, MiddlewareHandler } from \"../http.js\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Route handlers throw to the app error handler.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode,\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"../http.js\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n /** Correlation id for the active request, set by the ledger middleware. */\n correlationId?: string;\n /** Provider operation id a handler can advertise for the ledger. */\n operationId?: string;\n /** Side effects a handler records onto the active request's ledger entry. */\n ledgerEffects?: import(\"../ledger.js\").LedgerSideEffect[];\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString());\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n","const isDebug =\n typeof process !== \"undefined\" &&\n (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\n// Read the cosmetic font/favicon assets lazily and defensively: on a real\n// filesystem (Node/Bun hosts) this serves them; on filesystem-less runtimes\n// (e.g. Cloudflare Workers) the read fails and the route 404s, but — crucially —\n// importing this module touches neither fs NOR import.meta.url at load time\n// (workerd leaves import.meta.url undefined, which would crash `fileURLToPath`),\n// so `createServer` boots everywhere. API emulation never needs these assets.\nconst assetCache = new Map<string, Buffer | null>();\nfunction loadAsset(name: string): Buffer | null {\n if (assetCache.has(name)) return assetCache.get(name)!;\n let buf: Buffer | null = null;\n try {\n const dir = dirname(fileURLToPath(import.meta.url));\n buf = readFileSync(join(dir, \"fonts\", name));\n } catch {\n buf = null;\n }\n assetCache.set(name, buf);\n return buf;\n}\n\nconst FONT_NAMES = new Set([\"geist-sans.woff2\", \"GeistPixel-Square.woff2\"]);\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n if (!FONT_NAMES.has(name)) return c.notFound();\n const buf = loadAsset(name);\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n\n app.get(\"/_emulate/favicon.ico\", (c) => {\n const buf = loadAsset(\"favicon.ico\");\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"image/x-icon\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n });\n });\n}\n","import type { MiddlewareHandler } from \"./http.js\";\nimport type { AppEnv, AuthUser, AuthApp } from \"./middleware/auth.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\n\nexport interface LedgerIdentity {\n user?: Pick<AuthUser, \"login\" | \"id\" | \"scopes\">;\n app?: Pick<AuthApp, \"appId\" | \"slug\" | \"name\">;\n}\n\nexport interface LedgerSideEffect {\n type: \"create\" | \"update\" | \"delete\" | \"custom\";\n collection?: string;\n id?: string | number;\n summary?: string;\n}\n\nexport interface LedgerWebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n status_code: number | null;\n success: boolean;\n}\n\nexport interface LedgerEntry {\n id: string;\n /** Correlation id: honored from X-Correlation-Id / X-Request-Id or generated. */\n correlationId: string;\n timestamp: string;\n method: string;\n host: string;\n path: string;\n query: string;\n /** Matched route pattern, e.g. /repos/:owner/:repo/issues. */\n route?: string;\n /** Provider operation id, when the handler advertises one. */\n operationId?: string;\n request: {\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n identity: LedgerIdentity;\n response: {\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n /** Human/agent-readable one-liner, e.g. \"POST /repos/:owner/:repo -> 201\". */\n summary: string;\n sideEffects: LedgerSideEffect[];\n webhookDeliveries: LedgerWebhookDelivery[];\n durationMs: number;\n}\n\nexport interface LedgerOptions {\n maxEntries?: number;\n maxBodyChars?: number;\n /** When provided, webhook deliveries fired during a request are correlated onto its entry. */\n webhooks?: WebhookDispatcher;\n}\n\nexport interface LedgerSnapshot {\n entries: LedgerEntry[];\n counter: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 1000;\nconst DEFAULT_MAX_BODY_CHARS = 20000;\nconst REDACTED = \"[redacted]\";\nconst SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-github-token\",\n \"stripe-signature\",\n]);\nconst SENSITIVE_KEYS = /token|secret|password|authorization|api[_-]?key|client[_-]?secret|private[_-]?key/i;\n\nexport class RequestLedger {\n private entries: LedgerEntry[] = [];\n private counter = 1;\n\n constructor(private readonly options: LedgerOptions = {}) {}\n\n add(entry: Omit<LedgerEntry, \"id\">): LedgerEntry {\n const saved = { ...entry, id: `req_${this.counter++}` };\n this.entries.push(saved);\n const max = this.options.maxEntries ?? DEFAULT_MAX_ENTRIES;\n if (this.entries.length > max) {\n this.entries.splice(0, this.entries.length - max);\n }\n return saved;\n }\n\n list(limit?: number): LedgerEntry[] {\n const all = [...this.entries].reverse();\n return limit != null ? all.slice(0, limit) : all;\n }\n\n clear(): void {\n this.entries.length = 0;\n this.counter = 1;\n }\n\n /** Serialize for durable persistence (e.g. a Cloudflare Durable Object). */\n serialize(): LedgerSnapshot {\n return { entries: [...this.entries], counter: this.counter };\n }\n\n restore(snapshot: LedgerSnapshot | undefined): void {\n if (!snapshot) return;\n this.entries = Array.isArray(snapshot.entries) ? [...snapshot.entries] : [];\n this.counter = typeof snapshot.counter === \"number\" ? snapshot.counter : this.entries.length + 1;\n }\n}\n\nfunction correlationIdFor(headers: Record<string, string>): string {\n const provided = headers[\"x-correlation-id\"] ?? headers[\"x-request-id\"];\n if (provided && provided.length <= 200) return provided;\n return `cor_${crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n\nexport function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOptions = {}): MiddlewareHandler<AppEnv> {\n const maxBodyChars = options.maxBodyChars ?? DEFAULT_MAX_BODY_CHARS;\n const webhooks = options.webhooks;\n\n return async (c, next) => {\n if (c.req.path.startsWith(\"/_emulate\")) {\n await next();\n return;\n }\n\n const started = Date.now();\n const url = new URL(c.req.url);\n const rawHeaders = c.req.header();\n const correlationId = correlationIdFor(rawHeaders);\n c.set(\"correlationId\", correlationId);\n c.set(\"ledgerEffects\", []);\n c.header(\"X-Correlation-Id\", correlationId);\n\n const requestBody = await readBody(c.req.raw.clone(), maxBodyChars);\n const requestHeaders = redactHeaders(rawHeaders);\n\n // Snapshot existing webhook delivery ids so we can correlate the ones this\n // request fires. Exact under the serialized execution of a Durable Object;\n // best-effort on the concurrent local dev server.\n const beforeDeliveryIds = webhooks ? new Set(webhooks.getDeliveries().map((d) => d.id)) : undefined;\n\n const response = await next();\n if (!response) return;\n\n const responseBody = await readBody(response.clone(), maxBodyChars);\n const route = c.req.routePath;\n const operationId = c.get(\"operationId\");\n const sideEffects = (c.get(\"ledgerEffects\") as LedgerSideEffect[] | undefined) ?? [];\n const webhookDeliveries: LedgerWebhookDelivery[] =\n webhooks && beforeDeliveryIds\n ? webhooks\n .getDeliveries()\n .filter((d) => !beforeDeliveryIds.has(d.id))\n .map((d) => ({\n id: d.id,\n hook_id: d.hook_id,\n event: d.event,\n action: d.action,\n status_code: d.status_code,\n success: d.success,\n }))\n : [];\n\n ledger.add({\n correlationId,\n timestamp: new Date().toISOString(),\n method: c.req.method.toUpperCase(),\n host: url.host,\n path: url.pathname,\n query: url.search,\n route,\n operationId,\n request: {\n headers: requestHeaders,\n ...requestBody,\n },\n identity: {\n user: c.get(\"authUser\"),\n app: c.get(\"authApp\"),\n },\n response: {\n status: response.status,\n headers: redactHeaders(headersToRecord(response.headers)),\n ...responseBody,\n },\n summary: `${c.req.method.toUpperCase()} ${route ?? url.pathname} -> ${response.status}`,\n sideEffects,\n webhookDeliveries,\n durationMs: Date.now() - started,\n });\n\n return response;\n };\n}\n\n/** Record a side effect onto the active request's ledger entry. */\nexport function recordSideEffect(\n c: { get: (key: \"ledgerEffects\") => LedgerSideEffect[] | undefined },\n effect: LedgerSideEffect,\n): void {\n const effects = c.get(\"ledgerEffects\");\n if (effects) effects.push(effect);\n}\n\nasync function readBody(\n responseOrRequest: Request | Response,\n maxChars: number,\n): Promise<{ body?: unknown; bodyTruncated?: boolean }> {\n const method = responseOrRequest instanceof Request ? responseOrRequest.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") return {};\n\n const contentType = responseOrRequest.headers.get(\"content-type\") ?? \"\";\n if (responseOrRequest instanceof Response && responseOrRequest.status === 204) return {};\n\n let text: string;\n try {\n text = await responseOrRequest.text();\n } catch {\n return {};\n }\n if (!text) return {};\n\n const truncated = text.length > maxChars;\n const clipped = truncated ? text.slice(0, maxChars) : text;\n if (contentType.includes(\"application/json\")) {\n try {\n return { body: redactValue(JSON.parse(clipped)), bodyTruncated: truncated || undefined };\n } catch {\n return { body: clipped, bodyTruncated: truncated || undefined };\n }\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params: Record<string, string> = {};\n for (const [key, value] of new URLSearchParams(clipped)) {\n params[key] = SENSITIVE_KEYS.test(key) ? REDACTED : value;\n }\n return { body: params, bodyTruncated: truncated || undefined };\n }\n return { body: clipped, bodyTruncated: truncated || undefined };\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction redactHeaders(headers: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n out[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? REDACTED : value;\n }\n return out;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactValue);\n if (!value || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n out[key] = SENSITIVE_KEYS.test(key) ? REDACTED : redactValue(child);\n }\n return out;\n}\n","export type SpecKind = \"openapi\" | \"graphql\" | \"mcp\" | \"google-discovery\" | \"oauth-metadata\" | \"manual\";\nexport type SpecCoverage = \"generated\" | \"hand-authored\" | \"partial\" | \"unsupported\";\n\n/**\n * Per-operation coverage. The vision asks for honest, operation-level coverage\n * boundaries (generated / hand-authored / partial / unsupported) instead of a\n * single label stamped across an entire spec. A plugin declares the operations\n * it actually implements; `GET /_emulate/coverage` reports them with a summary.\n */\nexport interface OperationCoverage {\n operationId: string;\n method?: string;\n path?: string;\n status: SpecCoverage;\n summary?: string;\n}\n\nexport interface SpecManifest {\n kind: SpecKind;\n title: string;\n url?: string;\n coverage: SpecCoverage;\n operations?: OperationCoverage[];\n notes?: string;\n}\n\nexport interface SurfaceManifest {\n id: string;\n kind: \"rest\" | \"oauth\" | \"oidc\" | \"graphql\" | \"mcp\" | \"webhooks\" | \"ui\" | \"provider-specific\";\n title: string;\n basePath?: string;\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface AuthCapabilityManifest {\n id: string;\n title: string;\n type:\n | \"api-key\"\n | \"bearer-token\"\n | \"oauth-client-credentials\"\n | \"oauth-authorization-code\"\n | \"oidc\"\n | \"jwt-app\"\n | \"dynamic-client-registration\"\n | \"webhook-secret\"\n | \"provider-specific\";\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface ScenarioManifest {\n id: string;\n title: string;\n description?: string;\n}\n\n/** A seedable area of the instance, surfaced so agents can discover the seed shape. */\nexport interface SeedFieldManifest {\n key: string;\n title: string;\n description?: string;\n example?: unknown;\n}\n\nexport interface SeedSchemaManifest {\n description?: string;\n fields: SeedFieldManifest[];\n /** A full example seed body that can be POSTed to /_emulate/seed. */\n example?: unknown;\n}\n\nexport interface StateCollectionManifest {\n name: string;\n title?: string;\n description?: string;\n}\n\nexport interface StateModelManifest {\n description?: string;\n collections: StateCollectionManifest[];\n}\n\nexport interface ResetBehaviorManifest {\n description: string;\n reseeds: boolean;\n clearsLedger: boolean;\n clearsWebhooks: boolean;\n}\n\nexport type InspectorTabKind = \"landing\" | \"ledger\" | \"state\" | \"logs\" | \"credentials\" | \"seed\" | \"spec\" | \"custom\";\n\nexport interface InspectorTabManifest {\n id: string;\n title: string;\n kind: InspectorTabKind;\n description?: string;\n}\n\n/** Describes what the request ledger records and how durable it is. */\nexport interface LedgerCapabilitiesManifest {\n description?: string;\n recordsFields: string[];\n redactsSensitive: boolean;\n correlationId: boolean;\n webhookDeliveries: boolean;\n sideEffects: boolean;\n persistent: boolean;\n maxEntries?: number;\n}\n\nexport type ConnectionKind = \"sdk\" | \"cli\" | \"env\" | \"curl\" | \"config\" | \"mcp\";\n\n/**\n * A copyable connection snippet. The `template` uses {{placeholders}} that the\n * control plane resolves against the live instance ({{baseUrl}}, {{controlBaseUrl}},\n * {{service}}, {{instance}}, {{token}}, {{clientId}}, {{clientSecret}}). This is\n * how a human or agent copies ready-to-run SDK / CLI / app config without repo\n * context.\n */\nexport interface ConnectionSnippet {\n id: string;\n title: string;\n kind: ConnectionKind;\n language?: string;\n description?: string;\n template: string;\n}\n\nexport interface ServiceManifest {\n id: string;\n name: string;\n description: string;\n surfaces: SurfaceManifest[];\n auth: AuthCapabilityManifest[];\n specs: SpecManifest[];\n scenarios?: ScenarioManifest[];\n seedSchema?: SeedSchemaManifest;\n stateModel?: StateModelManifest;\n resetBehavior?: ResetBehaviorManifest;\n inspectorTabs?: InspectorTabManifest[];\n ledger?: LedgerCapabilitiesManifest;\n connections?: ConnectionSnippet[];\n docsUrl?: string;\n}\n\nexport interface EmulatorInstanceInfo {\n service: string;\n instance?: string;\n baseUrl: string;\n controlBaseUrl: string;\n providerBaseUrl: string;\n}\n\n/**\n * Reset, ledger capabilities, inspector tabs and base connection snippets are the\n * same for every emulator because they all run on the shared core control plane.\n * Defining them once here keeps per-plugin manifests focused on service-specific\n * surface, auth, seed, and SDK details, and guarantees the control plane never\n * lies about a capability it actually provides.\n */\nexport const CORE_RESET_BEHAVIOR: ResetBehaviorManifest = {\n description: \"Resets the instance to its seeded baseline.\",\n reseeds: true,\n clearsLedger: true,\n clearsWebhooks: true,\n};\n\nexport function coreLedgerCapabilities(persistent: boolean): LedgerCapabilitiesManifest {\n return {\n description: \"Recent provider requests with sensitive headers and fields redacted.\",\n recordsFields: [\n \"timestamp\",\n \"method\",\n \"host\",\n \"path\",\n \"route\",\n \"operationId\",\n \"correlationId\",\n \"identity\",\n \"request\",\n \"response\",\n \"summary\",\n \"sideEffects\",\n \"webhookDeliveries\",\n \"durationMs\",\n ],\n redactsSensitive: true,\n correlationId: true,\n webhookDeliveries: true,\n sideEffects: true,\n persistent,\n maxEntries: 1000,\n };\n}\n\nexport function coreInspectorTabs(manifest: ServiceManifest): InspectorTabManifest[] {\n const tabs: InspectorTabManifest[] = [\n {\n id: \"overview\",\n title: \"Overview\",\n kind: \"landing\",\n description: \"Service surfaces, base URLs, and connection snippets.\",\n },\n {\n id: \"ledger\",\n title: \"Ledger\",\n kind: \"ledger\",\n description: \"Recent provider requests recorded by the emulator.\",\n },\n { id: \"state\", title: \"State\", kind: \"state\", description: \"Current seeded and mutated instance state.\" },\n {\n id: \"credentials\",\n title: \"Credentials\",\n kind: \"credentials\",\n description: \"Mint tokens, API keys, or OAuth clients.\",\n },\n ];\n if (manifest.seedSchema || (manifest.scenarios && manifest.scenarios.length > 0)) {\n tabs.push({ id: \"seed\", title: \"Seed\", kind: \"seed\", description: \"Seed state or load a scenario.\" });\n }\n if (manifest.specs.some((s) => s.kind === \"openapi\" || s.kind === \"graphql\")) {\n tabs.push({ id: \"spec\", title: \"Spec\", kind: \"spec\", description: \"OpenAPI / GraphQL spec sources and coverage.\" });\n }\n if (manifest.surfaces.some((s) => s.kind === \"webhooks\")) {\n tabs.push({\n id: \"logs\",\n title: \"Webhooks\",\n kind: \"logs\",\n description: \"Webhook deliveries dispatched by the emulator.\",\n });\n }\n return tabs;\n}\n\n/** Connection snippets every emulator can offer (env + curl against the control plane). */\nexport function coreConnections(): ConnectionSnippet[] {\n return [\n {\n id: \"base-url\",\n title: \"Base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point your SDK or app at the emulator instead of the real provider.\",\n template: \"{{SERVICE_UPPER}}_BASE_URL={{baseUrl}}\",\n },\n {\n id: \"create-credential\",\n title: \"Create a credential\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Mint a working credential for this instance.\",\n template:\n 'curl -s -X POST {{controlBaseUrl}}/credentials \\\\\\n -H \"content-type: application/json\" \\\\\\n -d \\'{\"type\":\"{{defaultAuthType}}\"}\\'',\n },\n {\n id: \"inspect-ledger\",\n title: \"Inspect requests\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Read the request ledger to validate how your app called the service.\",\n template: \"curl -s {{controlBaseUrl}}/ledger\",\n },\n ];\n}\n\n/**\n * Merge the shared core capabilities into a plugin manifest so every served\n * manifest fully describes reset behavior, ledger capabilities, inspector tabs,\n * and at least the base connection snippets, without each plugin repeating them.\n */\nexport function enrichManifest(manifest: ServiceManifest, opts: { ledgerPersistent?: boolean } = {}): ServiceManifest {\n return {\n ...manifest,\n resetBehavior: manifest.resetBehavior ?? CORE_RESET_BEHAVIOR,\n ledger: manifest.ledger ?? coreLedgerCapabilities(opts.ledgerPersistent ?? false),\n inspectorTabs: manifest.inspectorTabs ?? coreInspectorTabs(manifest),\n connections: [...(manifest.connections ?? []), ...coreConnections()],\n };\n}\n\nexport interface ConnectionVars {\n baseUrl: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n service: string;\n instance?: string;\n token?: string;\n clientId?: string;\n clientSecret?: string;\n defaultAuthType?: string;\n}\n\nexport interface ResolvedConnection extends ConnectionSnippet {\n body: string;\n}\n\n/** Interpolate a connection snippet template against live instance values. */\nexport function resolveConnections(connections: ConnectionSnippet[], vars: ConnectionVars): ResolvedConnection[] {\n const map: Record<string, string> = {\n baseUrl: vars.baseUrl,\n providerBaseUrl: vars.providerBaseUrl,\n controlBaseUrl: vars.controlBaseUrl,\n service: vars.service,\n SERVICE_UPPER: vars.service.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\"),\n instance: vars.instance ?? \"default\",\n token: vars.token ?? \"<token>\",\n clientId: vars.clientId ?? \"<client_id>\",\n clientSecret: vars.clientSecret ?? \"<client_secret>\",\n defaultAuthType: vars.defaultAuthType ?? \"bearer-token\",\n };\n return connections.map((snippet) => ({\n ...snippet,\n body: snippet.template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => map[key] ?? `{{${key}}}`),\n }));\n}\n\n/** A summary of declared per-operation coverage across a manifest's specs. */\nexport function coverageReport(manifest: ServiceManifest): {\n operations: OperationCoverage[];\n summary: Record<SpecCoverage, number>;\n specs: Array<{ kind: SpecKind; title: string; coverage: SpecCoverage; operationCount: number }>;\n} {\n const operations: OperationCoverage[] = [];\n const summary: Record<SpecCoverage, number> = {\n generated: 0,\n \"hand-authored\": 0,\n partial: 0,\n unsupported: 0,\n };\n const specs = manifest.specs.map((spec) => {\n const ops = spec.operations ?? [];\n for (const op of ops) {\n operations.push(op);\n summary[op.status] += 1;\n }\n return { kind: spec.kind, title: spec.title, coverage: spec.coverage, operationCount: ops.length };\n });\n return { operations, summary, specs };\n}\n\nexport function createDefaultManifest(service: string): ServiceManifest {\n return {\n id: service,\n name: service,\n description: `Stateful ${service} API emulator.`,\n surfaces: [{ id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\" }],\n auth: [{ id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" }],\n specs: [{ kind: \"manual\", title: \"Hand-authored emulator behavior\", coverage: \"partial\" }],\n };\n}\n","export function escapeHtml(s: string): string {\n return s.replace(/&/g, \"&\").replace(/</g, \"<\").replace(/>/g, \">\").replace(/\"/g, \""\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"'\");\n}\n\nconst CSS = `\n@font-face{\n font-family:'Geist';font-style:normal;font-weight:100 900;font-display:swap;\n src:url('/_emulate/fonts/geist-sans.woff2') format('woff2');\n}\n@font-face{\n font-family:'Geist Pixel';font-style:normal;font-weight:400;font-display:swap;\n src:url('/_emulate/fonts/GeistPixel-Square.woff2') format('woff2');\n}\n*{box-sizing:border-box;margin:0;padding:0}\nbody{\n font-family:'Geist',-apple-system,BlinkMacSystemFont,sans-serif;\n background:#000;color:#33ff00;min-height:100vh;\n -webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;\n}\n.emu-bar{\n border-bottom:1px solid #0a3300;padding:10px 20px;\n display:flex;align-items:center;gap:10px;font-size:.8125rem;color:#1a8c00;\n}\n.emu-bar-title{font-weight:600;color:#33ff00;font-family:'Geist Pixel',monospace;}\n.emu-bar-links{margin-left:auto;display:flex;gap:16px;}\n.emu-bar-links a{\n color:#1a8c00;font-size:.75rem;text-decoration:none;transition:color .15s;\n}\n.emu-bar-links a:hover{color:#33ff00;}\n.emu-bar-links a .full{display:inline;}\n.emu-bar-links a .short{display:none;}\n@media(max-width:600px){\n .emu-bar-links a .full{display:none;}\n .emu-bar-links a .short{display:inline;}\n}\n\n.content{\n display:flex;align-items:center;justify-content:center;\n min-height:calc(100vh - 42px);padding:24px 16px;\n}\n.content-inner{width:100%;max-width:420px;}\n.card-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.125rem;font-weight:600;margin-bottom:4px;color:#33ff00;\n}\n.card-subtitle{color:#1a8c00;font-size:.8125rem;margin-bottom:18px;line-height:1.45;}\n.powered-by{\n position:fixed;bottom:0;left:0;right:0;\n text-align:center;padding:12px;font-size:.6875rem;color:#0a3300;\n font-family:'Geist Pixel',monospace;\n}\n.powered-by a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.powered-by a:hover{color:#33ff00;}\n\n.error-title{\n font-family:'Geist Pixel',monospace;\n color:#ff4444;font-size:1.125rem;font-weight:600;margin-bottom:8px;\n}\n.error-msg{color:#1a8c00;font-size:.875rem;line-height:1.5;}\n.error-card{text-align:center;}\n\n.user-form{margin-bottom:8px;}\n.user-form:last-of-type{margin-bottom:0;}\n.user-btn{\n width:100%;display:flex;align-items:center;gap:12px;\n padding:10px 12px;border:1px solid #0a3300;border-radius:8px;\n background:#000;color:inherit;cursor:pointer;text-align:left;\n font:inherit;transition:border-color .15s;\n}\n.user-btn:hover{border-color:#33ff00;}\n.avatar{\n width:36px;height:36px;border-radius:50%;\n background:#0a3300;color:#33ff00;font-weight:600;font-size:.875rem;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.user-text{min-width:0;}\n.user-login{font-weight:600;font-size:.875rem;display:block;color:#33ff00;}\n.user-meta{color:#1a8c00;font-size:.75rem;margin-top:1px;}\n.user-email{font-size:.6875rem;color:#116600;word-break:break-all;margin-top:1px;}\n\n.settings-layout{\n max-width:920px;margin:0 auto;padding:28px 20px;\n display:flex;gap:28px;\n}\n.settings-sidebar{width:200px;flex-shrink:0;}\n.settings-sidebar a{\n display:block;padding:6px 10px;border-radius:6px;color:#1a8c00;\n text-decoration:none;font-size:.8125rem;transition:color .15s;\n}\n.settings-sidebar a:hover{color:#33ff00;}\n.settings-sidebar a.active{color:#33ff00;font-weight:600;}\n.settings-main{flex:1;min-width:0;}\n\n.s-card{\n padding:18px 0;margin-bottom:14px;border-bottom:1px solid #0a3300;\n}\n.s-card:last-child{border-bottom:none;}\n.s-card-header{display:flex;align-items:center;gap:14px;margin-bottom:14px;}\n.s-icon{\n width:42px;height:42px;border-radius:8px;\n background:#0a3300;display:flex;align-items:center;justify-content:center;\n font-size:1.125rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.s-title{\n font-family:'Geist Pixel',monospace;\n font-size:1.25rem;font-weight:600;color:#33ff00;\n}\n.s-subtitle{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.section-heading{\n font-size:.9375rem;font-weight:600;margin-bottom:10px;color:#33ff00;\n display:flex;align-items:center;justify-content:space-between;\n}\n.perm-list{list-style:none;}\n.perm-list li{padding:5px 0;font-size:.8125rem;display:flex;align-items:center;gap:6px;color:#1a8c00;}\n.check{color:#33ff00;}\n.org-row{\n display:flex;align-items:center;gap:8px;padding:7px 0;\n border-bottom:1px solid #0a3300;font-size:.8125rem;\n}\n.org-row:last-child{border-bottom:none;}\n.org-icon{\n width:22px;height:22px;border-radius:4px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;\n font-size:.625rem;font-weight:700;color:#116600;flex-shrink:0;\n font-family:'Geist Pixel',monospace;\n}\n.org-name{font-weight:600;color:#33ff00;}\n.badge{font-size:.6875rem;padding:1px 7px;border-radius:999px;font-weight:500;}\n.badge-granted{background:#0a3300;color:#33ff00;}\n.badge-denied{background:#1a0a0a;color:#ff4444;}\n.badge-requested{background:#0a3300;color:#1a8c00;}\n.btn-revoke{\n display:inline-block;padding:5px 14px;border-radius:6px;\n border:1px solid #0a3300;background:transparent;color:#ff4444;\n font-size:.75rem;font-weight:600;cursor:pointer;transition:border-color .15s;\n}\n.btn-revoke:hover{border-color:#ff4444;}\n.info-text{color:#1a8c00;font-size:.75rem;line-height:1.5;margin-top:10px;}\n.info-text a,.section-heading a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.info-text a:hover,.section-heading a:hover{color:#33ff00;}\ncode{font-family:'Geist Mono','SF Mono',ui-monospace,monospace;font-size:.8125rem;color:#33ff00;word-break:break-all;}\n.code-block{\n background:#020;border:1px solid #0a3300;border-radius:6px;padding:10px 12px;\n margin:8px 0 12px;overflow-x:auto;\n}\n.code-block code{white-space:pre;word-break:normal;display:block;line-height:1.5;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n\n.inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}\n.inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}\n.inspector-tabs a{\n padding:7px 16px;border-radius:6px;text-decoration:none;\n font-size:.8125rem;color:#1a8c00;border:1px solid transparent;\n transition:color .15s,border-color .15s;\n}\n.inspector-tabs a:hover{color:#33ff00;}\n.inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}\n.inspector-section{margin-bottom:24px;}\n.inspector-section h2{\n font-family:'Geist Pixel',monospace;\n font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;\n}\n.inspector-section h3{\n font-family:'Geist Pixel',monospace;\n font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;\n}\n.inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}\n.inspector-table th,.inspector-table td{\n text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;\n font-size:.8125rem;\n}\n.inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}\n.inspector-table td{color:#33ff00;}\n.inspector-table tbody tr{transition:background .1s;}\n.inspector-table tbody tr:hover{background:#0a3300;}\n.inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}\n\n.checkout-layout{\n display:flex;min-height:calc(100vh - 42px);\n}\n.checkout-summary{\n flex:1;background:#020;padding:48px 40px 48px 10%;\n display:flex;flex-direction:column;justify-content:center;\n border-right:1px solid #0a3300;\n}\n.checkout-form-side{\n flex:1;background:#000;padding:48px 10% 48px 40px;\n display:flex;flex-direction:column;justify-content:center;\n}\n.checkout-merchant{\n display:flex;align-items:center;gap:10px;margin-bottom:6px;\n}\n.checkout-merchant-name{\n font-family:'Geist Pixel',monospace;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-test-badge{\n font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;\n}\n.checkout-total{\n font-family:'Geist Pixel',monospace;\n font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;\n}\n.checkout-line-item{\n display:flex;align-items:center;gap:14px;padding:14px 0;\n border-bottom:1px solid #0a3300;\n}\n.checkout-line-item:first-child{border-top:1px solid #0a3300;}\n.checkout-item-icon{\n width:42px;height:42px;border-radius:6px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;\n}\n.checkout-item-details{flex:1;min-width:0;}\n.checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}\n.checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.checkout-item-price{\n font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;\n}\n.checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}\n.checkout-totals{margin-top:20px;}\n.checkout-totals-row{\n display:flex;justify-content:space-between;padding:6px 0;\n font-size:.8125rem;color:#1a8c00;\n}\n.checkout-totals-row.total{\n border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-form-section{margin-bottom:24px;}\n.checkout-form-label{\n font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;\n}\n.checkout-input{\n width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;\n background:#020;color:#33ff00;font:inherit;font-size:.875rem;\n transition:border-color .15s;outline:none;\n}\n.checkout-input:focus{border-color:#33ff00;}\n.checkout-input::placeholder{color:#116600;}\n.checkout-card-box{\n border:1px solid #0a3300;border-radius:6px;padding:14px;\n background:#020;\n}\n.checkout-card-row{\n display:flex;gap:12px;margin-top:10px;\n}\n.checkout-card-row .checkout-input{flex:1;}\n.checkout-sim-note{\n font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;\n font-style:italic;\n}\n.checkout-pay-btn{\n width:100%;padding:14px;border:none;border-radius:8px;\n background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;\n cursor:pointer;transition:background .15s;\n font-family:'Geist Pixel',monospace;\n}\n.checkout-pay-btn:hover{background:#44ff22;}\n.checkout-cancel{\n text-align:center;margin-top:14px;\n}\n.checkout-cancel a{\n color:#1a8c00;text-decoration:none;font-size:.8125rem;\n transition:color .15s;\n}\n.checkout-cancel a:hover{color:#33ff00;}\n@media(max-width:768px){\n .checkout-layout{flex-direction:column;}\n .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}\n .checkout-form-side{padding:32px 20px;}\n}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<link rel=\"icon\" href=\"/_emulate/favicon.ico\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(title: string, subtitle: string, body: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(title: string, sidebarHtml: string, bodyHtml: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface InspectorTab {\n id: string;\n label: string;\n href: string;\n}\n\nexport function renderInspectorPage(\n title: string,\n tabs: InspectorTab[],\n activeTab: string,\n body: string,\n service?: string,\n): string {\n const tabLinks = tabs\n .map(\n (t) => `<a href=\"${escapeAttr(t.href)}\" class=\"${t.id === activeTab ? \"active\" : \"\"}\">${escapeHtml(t.label)}</a>`,\n )\n .join(\"\");\n\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"inspector-layout\">\n <nav class=\"inspector-tabs\">${tabLinks}</nav>\n ${body}\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderFormPostPage(action: string, fields: Record<string, string>, service?: string): string {\n const hiddens = Object.entries(fields)\n .filter(([, v]) => v != null)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\\n\");\n\n return `${head(\"Redirecting\")}\n<body onload=\"document.forms[0].submit()\">\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\" style=\"text-align:center\">\n <div class=\"card-subtitle\">Redirecting…</div>\n <form method=\"POST\" action=\"${escapeAttr(action)}\">\n${hiddens}\n <noscript><button type=\"submit\" class=\"user-btn\" style=\"margin-top:12px;justify-content:center\">\n <span class=\"user-login\">Continue</span>\n </button></noscript>\n </form>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface CheckoutLineItem {\n name: string;\n quantity: number;\n unitPrice: number;\n totalPrice: number;\n currency: string;\n}\n\nexport interface CheckoutPageOptions {\n merchantName?: string;\n lineItems: CheckoutLineItem[];\n subtotal: number;\n total: number;\n currency: string;\n sessionId: string;\n cancelUrl?: string | null;\n}\n\nexport function renderCheckoutPage(opts: CheckoutPageOptions, service?: string): string {\n const fmt = (cents: number, cur: string) => `$${(cents / 100).toFixed(2)} ${cur.toUpperCase()}`;\n const fmtShort = (cents: number) => `$${(cents / 100).toFixed(2)}`;\n\n const itemsHtml =\n opts.lineItems.length > 0\n ? opts.lineItems\n .map((li) => {\n const initial = li.name.charAt(0).toUpperCase();\n const unitNote =\n li.quantity > 1 ? `<div class=\"checkout-item-unit\">${fmtShort(li.unitPrice)} each</div>` : \"\";\n return `<div class=\"checkout-line-item\">\n <div class=\"checkout-item-icon\">${escapeHtml(initial)}</div>\n <div class=\"checkout-item-details\">\n <div class=\"checkout-item-name\">${escapeHtml(li.name)}</div>\n <div class=\"checkout-item-qty\">Qty ${li.quantity}</div>\n </div>\n <div>\n <div class=\"checkout-item-price\">${fmtShort(li.totalPrice)}</div>\n ${unitNote}\n </div>\n</div>`;\n })\n .join(\"\")\n : '<p class=\"empty\">No line items</p>';\n\n const totalsHtml = `<div class=\"checkout-totals\">\n <div class=\"checkout-totals-row\">\n <span>Subtotal</span><span>${fmtShort(opts.subtotal)}</span>\n </div>\n <div class=\"checkout-totals-row total\">\n <span>Total due</span><span>${fmt(opts.total, opts.currency)}</span>\n </div>\n</div>`;\n\n const cancelHtml = opts.cancelUrl\n ? `<div class=\"checkout-cancel\"><a href=\"${escapeAttr(opts.cancelUrl)}\">Cancel</a></div>`\n : \"\";\n\n const merchant = opts.merchantName ? escapeHtml(opts.merchantName) : \"Checkout\";\n\n return `${head(\"Checkout\")}\n<body>\n${emuBar(service)}\n<div class=\"checkout-layout\">\n <div class=\"checkout-summary\">\n <div class=\"checkout-merchant\">\n <span class=\"checkout-merchant-name\">${merchant}</span>\n <span class=\"checkout-test-badge\">Test Mode</span>\n </div>\n <div class=\"checkout-total\">${fmtShort(opts.total)}</div>\n ${itemsHtml}\n ${totalsHtml}\n </div>\n <div class=\"checkout-form-side\">\n <form method=\"post\" action=\"/checkout/${escapeAttr(opts.sessionId)}/complete\">\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Email</label>\n <input type=\"email\" name=\"email\" class=\"checkout-input\" placeholder=\"you@example.com\"/>\n </div>\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Card information</label>\n <div class=\"checkout-card-box\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"1234 1234 1234 1234\" disabled/>\n <div class=\"checkout-card-row\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"MM / YY\" disabled/>\n <input type=\"text\" class=\"checkout-input\" placeholder=\"CVC\" disabled/>\n </div>\n </div>\n <div class=\"checkout-sim-note\">Card fields are simulated. Payment will be auto-approved.</div>\n </div>\n <button type=\"submit\" class=\"checkout-pay-btn\">Pay ${fmtShort(opts.total)}</button>\n </form>\n ${cancelHtml}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>` : \"\";\n const emailLine = opts.email ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>` : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import type { Context, Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\nimport type { Store } from \"./store.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\nimport type { RequestLedger } from \"./ledger.js\";\nimport type { ConnectionVars, EmulatorInstanceInfo, ResolvedConnection, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport type { TokenMap } from \"./middleware/auth.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\n\nexport interface CredentialRequest {\n type?: string;\n login?: string;\n name?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n [key: string]: unknown;\n}\n\nexport interface IssuedCredential {\n type: string;\n token?: string;\n login?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n token_url?: string;\n authorization_url?: string;\n notes?: string;\n [key: string]: unknown;\n}\n\nexport interface ControlPlaneOptions {\n manifest: ServiceManifest;\n instance: EmulatorInstanceInfo;\n store: Store;\n webhooks: WebhookDispatcher;\n ledger: RequestLedger;\n tokenMap?: TokenMap;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport const INSTANCE_NOTES = \"Hosted deployments create instances lazily when the returned URL is first used.\";\n\nexport interface InstanceCreation {\n service: string;\n instance: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n pathUrl: string;\n hostHint: string;\n notes: string;\n}\n\n/** The single, canonical shape for POST /_emulate/instances, shared by every host. */\nexport function buildInstanceCreation(args: {\n service: string;\n instance: string;\n providerBaseUrl: string;\n pathOrigin: string;\n hostSuffix: string;\n}): InstanceCreation {\n return {\n service: args.service,\n instance: args.instance,\n providerBaseUrl: args.providerBaseUrl,\n controlBaseUrl: `${args.providerBaseUrl}/_emulate`,\n pathUrl: `${args.pathOrigin}/${args.service}/${args.instance}`,\n hostHint: `${args.service}.${args.instance}.${args.hostSuffix}`,\n notes: INSTANCE_NOTES,\n };\n}\n\nfunction connectionVars(\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n overrides?: Partial<ConnectionVars>,\n): ConnectionVars {\n return {\n baseUrl: instance.providerBaseUrl,\n providerBaseUrl: instance.providerBaseUrl,\n controlBaseUrl: instance.controlBaseUrl,\n service: manifest.id,\n instance: instance.instance,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n ...overrides,\n };\n}\n\nexport function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOptions): void {\n const { instance, store, webhooks, ledger } = options;\n const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent });\n const hostSuffix = options.hostSuffix ?? \"emulators.dev\";\n\n app.get(\"/_emulate\", (c) => c.html(renderLandingPage(manifest, instance)));\n app.get(\"/_emulate/manifest\", (c) =>\n c.json({\n manifest,\n instance,\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance)),\n }),\n );\n app.get(\"/_emulate/quickstart\", (c) => c.text(renderQuickstart(manifest, instance)));\n app.get(\"/_emulate/specs\", (c) => c.json({ specs: manifest.specs, surfaces: manifest.surfaces }));\n app.get(\"/_emulate/coverage\", (c) => c.json(coverageReport(manifest)));\n app.get(\"/_emulate/connections\", (c) => {\n const overrides: Partial<ConnectionVars> = {};\n const token = c.req.query(\"token\");\n const clientId = c.req.query(\"client_id\");\n const clientSecret = c.req.query(\"client_secret\");\n if (token) overrides.token = token;\n if (clientId) overrides.clientId = clientId;\n if (clientSecret) overrides.clientSecret = clientSecret;\n return c.json({\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance, overrides)),\n });\n });\n app.get(\"/_emulate/openapi\", (c) => redirectToSpec(c, manifest, instance, \"openapi\"));\n app.get(\"/_emulate/graphql\", (c) => endpointForSurface(c, manifest, instance, \"graphql\"));\n app.get(\"/_emulate/mcp\", (c) => endpointForSurface(c, manifest, instance, \"mcp\"));\n app.get(\"/_emulate/state\", (c) => c.json(store.snapshot()));\n app.get(\"/_emulate/ledger\", (c) => {\n const limitParam = c.req.query(\"limit\");\n const limit = limitParam ? Number.parseInt(limitParam, 10) : undefined;\n return c.json({ entries: ledger.list(Number.isFinite(limit) ? limit : undefined) });\n });\n app.delete(\"/_emulate/ledger\", (c) => {\n ledger.clear();\n return c.json({ ok: true });\n });\n app.get(\"/_emulate/logs\", (c) => c.json({ webhooks: webhooks.getDeliveries(), requests: ledger.list(100) }));\n app.post(\"/_emulate/reset\", async (c) => {\n if (options.reset) {\n await options.reset();\n } else {\n store.reset();\n webhooks.clear();\n ledger.clear();\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/seed\", async (c) => {\n if (!options.seed) {\n return c.json({ error: \"unsupported\", message: \"This emulator does not support runtime seeding.\" }, 501);\n }\n const body = await c.req.json().catch(() => undefined);\n try {\n await options.seed(body);\n } catch (err) {\n return c.json({ error: \"invalid_seed\", message: err instanceof Error ? err.message : \"Seed failed.\" }, 400);\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/credentials\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as CredentialRequest;\n try {\n if (options.issueCredential) {\n const credential = await options.issueCredential(body);\n return c.json({ credential });\n }\n const credential = issueDefaultCredential(body, manifest, options.tokenMap);\n if (!credential) {\n return c.json({ error: \"unsupported\", message: \"This emulator cannot create that credential type.\" }, 501);\n }\n return c.json({ credential });\n } catch (err) {\n return c.json(\n { error: \"unsupported\", message: err instanceof Error ? err.message : \"Credential creation failed.\" },\n 400,\n );\n }\n });\n app.post(\"/_emulate/instances\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as { instance?: string; service?: string };\n const nextInstance = slug(body.instance ?? `${manifest.id}-${randomId().slice(0, 8)}`);\n const service = slug(body.service ?? manifest.id);\n const origin = new URL(instance.providerBaseUrl).origin;\n return c.json(\n buildInstanceCreation({\n service,\n instance: nextInstance,\n providerBaseUrl: `${origin}/${service}/${nextInstance}`,\n pathOrigin: origin,\n hostSuffix,\n }),\n );\n });\n}\n\nexport function renderLandingPage(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const surfaces = manifest.surfaces\n .map(\n (surface) =>\n `<tr><td>${escapeHtml(surface.title)}</td><td><span class=\"badge\">${escapeHtml(surface.status)}</span></td><td><code>${escapeHtml(surface.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const auth = manifest.auth\n .map((cap) => `<li><span class=\"badge\">${escapeHtml(cap.status)}</span> ${escapeHtml(cap.title)}</li>`)\n .join(\"\");\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const instanceLabel = instance.instance ? ` · instance <code>${escapeHtml(instance.instance)}</code>` : \"\";\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Base URLs${instanceLabel}</div>\n <p class=\"info-text\">Provider: <code>${escapeHtml(instance.providerBaseUrl)}</code></p>\n <p class=\"info-text\">Control: <code>${escapeHtml(instance.controlBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Credentials</div>\n <ul class=\"perm-list\">${auth}</ul>\n </div>\n ${renderConnectionsHtml(connections)}\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">${controlLinks()}</p>\n </div>\n `,\n manifest.id,\n );\n}\n\nfunction renderConnectionsHtml(connections: ResolvedConnection[]): string {\n if (connections.length === 0) return \"\";\n const blocks = connections\n .map(\n (c) =>\n `<div class=\"section-heading\">${escapeHtml(c.title)}</div><pre class=\"code-block\"><code>${escapeHtml(c.body)}</code></pre>`,\n )\n .join(\"\");\n return `<div class=\"s-card\"><div class=\"section-heading\">Connect</div>${blocks}</div>`;\n}\n\nfunction controlLinks(): string {\n const routes = [\"manifest\", \"quickstart\", \"specs\", \"coverage\", \"connections\", \"state\", \"ledger\", \"logs\"];\n return routes.map((r) => `<a href=\"/_emulate/${r}\">${r}</a>`).join(\" | \");\n}\n\nexport function renderQuickstart(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const lines = [\n `# ${manifest.name} Emulator`,\n \"\",\n manifest.description,\n \"\",\n `Provider base URL: ${instance.providerBaseUrl}`,\n `Control base URL: ${instance.controlBaseUrl}`,\n \"\",\n \"Supported surfaces:\",\n ...manifest.surfaces.map((s) => `- ${s.title}: ${s.status}${s.basePath ? ` at ${s.basePath}` : \"\"}`),\n \"\",\n \"Control endpoints:\",\n `- ${instance.controlBaseUrl}/manifest`,\n `- ${instance.controlBaseUrl}/coverage`,\n `- ${instance.controlBaseUrl}/connections`,\n `- ${instance.controlBaseUrl}/state`,\n `- ${instance.controlBaseUrl}/ledger`,\n `- POST ${instance.controlBaseUrl}/credentials`,\n `- POST ${instance.controlBaseUrl}/seed`,\n `- POST ${instance.controlBaseUrl}/reset`,\n \"\",\n \"Connect:\",\n ...connections.flatMap((c) => [\"\", `## ${c.title}`, c.body]),\n ];\n return lines.join(\"\\n\");\n}\n\nfunction issueDefaultCredential(\n request: CredentialRequest,\n manifest: ServiceManifest,\n tokenMap: TokenMap | undefined,\n): IssuedCredential | null {\n const type = request.type ?? manifest.auth[0]?.type ?? \"bearer-token\";\n if (type !== \"bearer-token\" && type !== \"api-key\") return null;\n if (!tokenMap) return null;\n const token = typeof request.token === \"string\" && request.token ? request.token : `emu_${manifest.id}_${randomId()}`;\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes) ? request.scopes.filter((s): s is string => typeof s === \"string\") : [];\n tokenMap.set(token, { login, id: Date.now(), scopes });\n return { type, token, login, scopes };\n}\n\nfunction redirectToSpec(c: Context<AppEnv>, manifest: ServiceManifest, instance: EmulatorInstanceInfo, kind: string) {\n const spec = manifest.specs.find((s) => s.kind === kind && s.url);\n if (spec?.url) return c.redirect(resolveUrl(instance.providerBaseUrl, spec.url));\n const advertised = manifest.specs.some((s) => s.kind === kind);\n if (kind === \"openapi\" && advertised) return c.redirect(`${instance.providerBaseUrl}/openapi.json`);\n return c.json({ error: \"not_found\", message: `No ${kind} spec is advertised for this emulator.` }, 404);\n}\n\nfunction endpointForSurface(\n c: Context<AppEnv>,\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n kind: \"graphql\" | \"mcp\",\n) {\n const surface = manifest.surfaces.find((s) => s.kind === kind && s.basePath);\n if (!surface?.basePath) {\n return c.json({ error: \"not_found\", message: `No ${kind} surface is advertised for this emulator.` }, 404);\n }\n return c.json({ endpoint: resolveUrl(instance.providerBaseUrl, surface.basePath), surface });\n}\n\nfunction resolveUrl(baseUrl: string, pathOrUrl: string): string {\n if (/^https?:\\/\\//i.test(pathOrUrl)) return pathOrUrl;\n return `${baseUrl}${pathOrUrl.startsWith(\"/\") ? \"\" : \"/\"}${pathOrUrl}`;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n","import { Hono, cors } from \"./http.js\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport {\n authMiddleware,\n type AuthFallback,\n type TokenMap,\n type AppKeyResolver,\n type AppEnv,\n} from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\nimport { RequestLedger, createLedgerMiddleware } from \"./ledger.js\";\nimport { registerControlPlane, type CredentialRequest, type IssuedCredential } from \"./control-plane.js\";\nimport { createDefaultManifest, type ServiceManifest } from \"./manifest.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n manifest?: ServiceManifest;\n instance?: string;\n enableControlPlane?: boolean;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form surfaced in control-plane responses. */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n const ledger = new RequestLedger();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://docs.emulators.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n if (options.enableControlPlane !== false) {\n const manifest = options.manifest ?? createDefaultManifest(plugin.name);\n registerControlPlane(app, {\n manifest,\n instance: {\n service: manifest.id,\n instance: options.instance,\n baseUrl,\n providerBaseUrl: baseUrl,\n controlBaseUrl: `${baseUrl}/_emulate`,\n },\n store,\n webhooks,\n ledger,\n tokenMap,\n ledgerPersistent: options.ledgerPersistent,\n hostSuffix: options.hostSuffix,\n reset: options.reset,\n seed: options.seed,\n issueCredential: options.issueCredential,\n });\n }\n\n app.use(\"*\", createLedgerMiddleware(ledger, { webhooks }));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403,\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404,\n ),\n );\n\n return { app, store, webhooks, ledger, port, baseUrl, tokenMap };\n}\n","import type { EmulatorInstanceInfo, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\nimport { renderQuickstart, INSTANCE_NOTES } from \"./control-plane.js\";\n\nexport interface ServiceHostContext {\n manifest: ServiceManifest;\n service: string;\n /** Apex origin for the path form, e.g. https://emulators.dev. */\n origin: string;\n /** Request protocol including the colon, e.g. \"https:\". */\n protocol: string;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix: string;\n /** Whether the deployed host persists the ledger across eviction. */\n ledgerPersistent?: boolean;\n}\n\nconst SAMPLE_INSTANCE = \"your-instance\";\n\nfunction sampleInstanceInfo(ctx: ServiceHostContext): EmulatorInstanceInfo {\n const providerBaseUrl = `${ctx.protocol}//${ctx.service}.${SAMPLE_INSTANCE}.${ctx.hostSuffix}`;\n return {\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n baseUrl: providerBaseUrl,\n providerBaseUrl,\n controlBaseUrl: `${providerBaseUrl}/_emulate`,\n };\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/**\n * Serve the service-level control plane on a bare service host (e.g.\n * github.emulators.dev) so a human or agent can read the manifest, quickstart,\n * specs, coverage, and connection snippets WITHOUT first creating an instance.\n * Returns null for paths this should not handle (so the caller can fall through\n * to the interactive console SPA).\n */\nexport function serviceHostControlPlane(path: string, method: string, ctx: ServiceHostContext): Response | null {\n if (!path.startsWith(\"/_emulate\")) return null;\n if (method !== \"GET\" && method !== \"HEAD\") return null;\n\n const manifest = enrichManifest(ctx.manifest, { ledgerPersistent: ctx.ledgerPersistent });\n const sample = sampleInstanceInfo(ctx);\n const connections = resolveConnections(manifest.connections ?? [], {\n baseUrl: sample.providerBaseUrl,\n providerBaseUrl: sample.providerBaseUrl,\n controlBaseUrl: sample.controlBaseUrl,\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n });\n\n switch (path) {\n case \"/_emulate\":\n return new Response(renderServiceLanding(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n case \"/_emulate/manifest\":\n return json({ manifest, instance: null, sampleInstance: sample, connections });\n case \"/_emulate/quickstart\":\n return new Response(renderServiceQuickstart(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n });\n case \"/_emulate/specs\":\n return json({ specs: manifest.specs, surfaces: manifest.surfaces });\n case \"/_emulate/coverage\":\n return json(coverageReport(manifest));\n case \"/_emulate/connections\":\n return json({ connections });\n case \"/_emulate/openapi\": {\n const spec = manifest.specs.find((s) => s.kind === \"openapi\");\n if (!spec) return json({ error: \"not_found\", message: \"No OpenAPI spec is advertised for this emulator.\" }, 404);\n return json({\n openapi: `${sample.providerBaseUrl}${spec.url ?? \"/openapi.json\"}`,\n note: \"Create an instance, then fetch this URL for the live spec.\",\n });\n }\n default:\n return null;\n }\n}\n\nfunction renderServiceQuickstart(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const base = renderQuickstart(manifest, sample);\n const header = [\n `# ${manifest.name} Emulator (service host)`,\n \"\",\n \"Create an instance:\",\n `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances -H 'content-type: application/json' -d '{\"instance\":\"my-run\"}'`,\n `# ${INSTANCE_NOTES}`,\n \"\",\n \"Then use the returned providerBaseUrl / controlBaseUrl. Example below uses a sample instance.\",\n \"\",\n ];\n return header.join(\"\\n\") + base;\n}\n\nfunction renderServiceLanding(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const surfaces = manifest.surfaces\n .map(\n (s) =>\n `<tr><td>${escapeHtml(s.title)}</td><td><span class=\"badge\">${escapeHtml(s.status)}</span></td><td><code>${escapeHtml(s.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const createCurl = `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances \\\\\n -H \"content-type: application/json\" \\\\\n -d '{\"instance\":\"my-run\"}'`;\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Create an instance</div>\n <p class=\"info-text\">Each instance is isolated, stateful, and addressable at its own host.</p>\n <pre class=\"code-block\"><code>${escapeHtml(createCurl)}</code></pre>\n <p class=\"info-text\">${escapeHtml(INSTANCE_NOTES)}</p>\n <p class=\"info-text\">Sample instance host: <code>${escapeHtml(sample.providerBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">\n <a href=\"/_emulate/manifest\">manifest</a> | <a href=\"/_emulate/quickstart\">quickstart</a> |\n <a href=\"/_emulate/specs\">specs</a> | <a href=\"/_emulate/coverage\">coverage</a> |\n <a href=\"/_emulate/connections\">connections</a>\n </p>\n </div>\n `,\n manifest.id,\n );\n}\n\nexport interface ServiceCatalogEntry {\n id: string;\n name: string;\n description: string;\n}\n\n/**\n * Server-rendered catalog landing for the apex host. Readable by an agent over a\n * raw fetch (no JS): it lists every emulator with its host and manifest URL. The\n * interactive console SPA is served instead only for browser navigations.\n */\nexport function renderCatalogPage(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): string {\n const rows = entries\n .map((e) => {\n const host = `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`;\n return `<a class=\"app-link\" href=\"${escapeHtml(host)}\">\n <img src=\"/_emulate/icons/${escapeHtml(e.id)}\" alt=\"\" width=\"24\" height=\"24\" style=\"object-fit:contain\" />\n <span><span class=\"app-link-name\">${escapeHtml(e.name)}</span><span class=\"app-link-scopes\">${escapeHtml(host)}</span></span>\n </a>`;\n })\n .join(\"\");\n return renderCardPage(\n \"Emulate\",\n \"Stateful integration emulators for real developer APIs. Each emulator has its own host; open one or fetch its manifest.\",\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Emulators</div>\n ${rows}\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">For agents</div>\n <p class=\"info-text\">Machine-readable catalog: <a href=\"/_emulate/services\">/_emulate/services</a></p>\n <p class=\"info-text\">Each service host serves <code>/_emulate/manifest</code>, <code>/_emulate/quickstart</code>, and <code>/_emulate/connections</code>, and the provider API directly against a default instance.</p>\n </div>\n `,\n );\n}\n\n/** A machine-readable index of the services a host serves, with both URL forms. */\nexport function servicesCatalog(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): Response {\n const services = entries.map((e) => ({\n id: e.id,\n name: e.name,\n description: e.description,\n icon: `${ctx.origin}/_emulate/icons/${e.id}`,\n serviceHost: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`,\n instanceHostPattern: `${ctx.protocol}//${e.id}.<instance>.${ctx.hostSuffix}`,\n pathForm: `${ctx.origin}/${e.id}/<instance>`,\n manifest: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}/_emulate/manifest`,\n }));\n return new Response(JSON.stringify({ services }), {\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n","import type { Context } from \"../http.js\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(c: Context, totalCount: number, page: number, perPage: number): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","import type { Context } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody } from \"@emulators/core\";\nexport { ApiError };\nimport { getVercelStore } from \"../store.js\";\nimport type { VercelStore } from \"../store.js\";\nimport type { VercelTeam, VercelTeamMember, VercelUser } from \"../entities.js\";\nimport {\n applyCursorPagination,\n formatTeam,\n formatUser,\n generateUid,\n parseCursorPagination,\n resolveTeamScope,\n} from \"../helpers.js\";\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nfunction resolveTeamByIdOrSlug(vs: VercelStore, teamIdOrSlug: string): VercelTeam | undefined {\n return (\n vs.teams.findOneBy(\"uid\", teamIdOrSlug as VercelTeam[\"uid\"]) ??\n vs.teams.findOneBy(\"slug\", teamIdOrSlug as VercelTeam[\"slug\"])\n );\n}\n\nfunction getTeamMember(vs: VercelStore, teamUid: string, userUid: string): VercelTeamMember | undefined {\n return vs.teamMembers.findBy(\"teamId\", teamUid as VercelTeamMember[\"teamId\"]).find((m) => m.userId === userUid);\n}\n\nfunction formatTeamForViewer(team: VercelTeam, member: VercelTeamMember | undefined) {\n return {\n ...formatTeam(team),\n membership: member\n ? { confirmed: member.confirmed, role: member.role }\n : { confirmed: false, role: \"VIEWER\" as const },\n };\n}\n\nfunction formatMemberRow(vs: VercelStore, m: VercelTeamMember) {\n const user = vs.users.findOneBy(\"uid\", m.userId as VercelUser[\"uid\"]);\n return {\n id: String(m.id),\n role: m.role,\n confirmed: m.confirmed,\n joinedFrom: m.joinedFrom,\n user: user ? formatUser(user) : null,\n };\n}\n\nconst TEAM_ROLES: VercelTeamMember[\"role\"][] = [\"OWNER\", \"MEMBER\", \"DEVELOPER\", \"VIEWER\"];\n\nfunction parseRole(value: unknown, fallback: VercelTeamMember[\"role\"]): VercelTeamMember[\"role\"] | null {\n if (value === undefined || value === null) return fallback;\n if (typeof value !== \"string\") return null;\n return TEAM_ROLES.includes(value as VercelTeamMember[\"role\"]) ? (value as VercelTeamMember[\"role\"]) : null;\n}\n\nfunction defaultTeamBilling(): VercelTeam[\"billing\"] {\n return { plan: \"hobby\", period: null, trial: null, cancelation: null, addons: null };\n}\n\nfunction defaultTeamResourceConfig(): VercelTeam[\"resourceConfig\"] {\n return { nodeType: \"standard\", concurrentBuilds: 1 };\n}\n\nexport function userRoutes({ app, store }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.get(\"/registration\", (c) => c.json({ registration: false }));\n\n app.get(\"/v2/user\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n return c.json({ user: formatUser(user) });\n });\n\n app.patch(\"/v2/user\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const existing = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!existing) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<Pick<VercelUser, \"name\" | \"email\">> = {};\n if (\"name\" in body) {\n if (body.name === null) patch.name = null;\n else if (typeof body.name === \"string\") patch.name = body.name;\n }\n if (\"email\" in body && typeof body.email === \"string\") {\n patch.email = body.email;\n }\n\n const updated = vs.users.update(existing.id, patch);\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update user\");\n }\n return c.json({ user: formatUser(updated) });\n });\n\n app.get(\"/v2/teams\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const pagination = parseCursorPagination(c);\n const memberships = vs.teamMembers.findBy(\"userId\", user.uid as VercelTeamMember[\"userId\"]);\n let teams = memberships\n .map((m) => vs.teams.findOneBy(\"uid\", m.teamId as VercelTeam[\"uid\"]))\n .filter((t): t is VercelTeam => Boolean(t));\n\n if (c.req.query(\"teamId\") || c.req.query(\"slug\")) {\n const scope = resolveTeamScope(c, vs);\n const scopedTeam = scope?.team;\n if (!scopedTeam) {\n return vercelErr(c, 404, \"not_found\", \"Team not found\");\n }\n teams = teams.filter((t) => t.uid === scopedTeam.uid);\n }\n\n const { items, pagination: pageMeta } = applyCursorPagination(teams, pagination);\n const formatted = items.map((team) => {\n const member = getTeamMember(vs, team.uid, user.uid);\n return formatTeamForViewer(team, member);\n });\n\n return c.json({\n teams: formatted,\n pagination: pageMeta,\n });\n });\n\n app.get(\"/v2/teams/:teamId\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const team = resolveTeamByIdOrSlug(vs, c.req.param(\"teamId\"));\n if (!team) {\n return vercelErr(c, 404, \"not_found\", \"Team not found\");\n }\n const member = getTeamMember(vs, team.uid, user.uid);\n return c.json({ team: formatTeamForViewer(team, member) });\n });\n\n app.post(\"/v2/teams\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const creator = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!creator) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const body = await parseJsonBody(c);\n const slug = typeof body.slug === \"string\" ? body.slug.trim() : \"\";\n if (!slug) {\n return vercelErr(c, 400, \"bad_request\", \"Missing required field: slug\");\n }\n\n if (vs.teams.findOneBy(\"slug\", slug as VercelTeam[\"slug\"])) {\n return vercelErr(c, 409, \"team_slug_already_exists\", \"A team with this slug already exists\");\n }\n\n const name = typeof body.name === \"string\" && body.name.trim() ? body.name.trim() : slug;\n\n const team = vs.teams.insert({\n uid: generateUid(\"team\"),\n slug,\n name,\n avatar: null,\n description: null,\n creatorId: creator.uid,\n membership: { confirmed: true, role: \"OWNER\" },\n billing: defaultTeamBilling(),\n resourceConfig: defaultTeamResourceConfig(),\n stagingPrefix: \"\",\n });\n\n vs.teamMembers.insert({\n teamId: team.uid,\n userId: creator.uid,\n role: \"OWNER\",\n confirmed: true,\n joinedFrom: \"cli\",\n });\n\n const member = getTeamMember(vs, team.uid, creator.uid);\n return c.json({ team: formatTeamForViewer(team, member) });\n });\n\n app.patch(\"/v2/teams/:teamId\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const team = resolveTeamByIdOrSlug(vs, c.req.param(\"teamId\"));\n if (!team) {\n return vercelErr(c, 404, \"not_found\", \"Team not found\");\n }\n\n const member = getTeamMember(vs, team.uid, user.uid);\n if (!member || member.role !== \"OWNER\") {\n return vercelErr(c, 403, \"forbidden\", \"Insufficient permissions to update this team\");\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<Pick<VercelTeam, \"name\" | \"description\" | \"slug\">> = {};\n\n if (\"name\" in body && typeof body.name === \"string\") patch.name = body.name;\n if (\"description\" in body) {\n if (body.description === null) patch.description = null;\n else if (typeof body.description === \"string\") patch.description = body.description;\n }\n if (\"slug\" in body && typeof body.slug === \"string\") {\n const nextSlug = body.slug.trim();\n if (nextSlug && nextSlug !== team.slug) {\n const taken = vs.teams.findOneBy(\"slug\", nextSlug as VercelTeam[\"slug\"]);\n if (taken && taken.id !== team.id) {\n return vercelErr(c, 409, \"team_slug_already_exists\", \"A team with this slug already exists\");\n }\n patch.slug = nextSlug;\n }\n }\n\n const updated = vs.teams.update(team.id, patch);\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update team\");\n }\n const viewer = getTeamMember(vs, updated.uid, user.uid);\n return c.json({ team: formatTeamForViewer(updated, viewer) });\n });\n\n app.get(\"/v2/teams/:teamId/members\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const team = resolveTeamByIdOrSlug(vs, c.req.param(\"teamId\"));\n if (!team) {\n return vercelErr(c, 404, \"not_found\", \"Team not found\");\n }\n\n if (!getTeamMember(vs, team.uid, user.uid)) {\n return vercelErr(c, 403, \"forbidden\", \"Not a member of this team\");\n }\n\n const pagination = parseCursorPagination(c);\n const members = vs.teamMembers.findBy(\"teamId\", team.uid as VercelTeamMember[\"teamId\"]);\n const { items, pagination: pageMeta } = applyCursorPagination(members, pagination);\n return c.json({\n members: items.map((m) => formatMemberRow(vs, m)),\n pagination: pageMeta,\n });\n });\n\n app.post(\"/v2/teams/:teamId/members\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const actor = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!actor) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const team = resolveTeamByIdOrSlug(vs, c.req.param(\"teamId\"));\n if (!team) {\n return vercelErr(c, 404, \"not_found\", \"Team not found\");\n }\n\n const actorMember = getTeamMember(vs, team.uid, actor.uid);\n if (!actorMember || actorMember.role !== \"OWNER\") {\n return vercelErr(c, 403, \"forbidden\", \"Insufficient permissions to add members\");\n }\n\n const body = await parseJsonBody(c);\n const email = typeof body.email === \"string\" ? body.email.trim() : undefined;\n const uid = typeof body.uid === \"string\" ? body.uid.trim() : undefined;\n\n let target: VercelUser | undefined;\n if (uid) {\n target = vs.users.findOneBy(\"uid\", uid as VercelUser[\"uid\"]);\n } else if (email) {\n target = vs.users.findOneBy(\"email\", email as VercelUser[\"email\"]);\n } else {\n return vercelErr(c, 400, \"bad_request\", \"Provide uid or email\");\n }\n\n if (!target) {\n return vercelErr(c, 404, \"not_found\", \"User not found\");\n }\n\n const role = parseRole(body.role, \"MEMBER\");\n if (role === null) {\n return vercelErr(c, 400, \"bad_request\", \"Invalid role\");\n }\n\n if (getTeamMember(vs, team.uid, target.uid)) {\n return vercelErr(c, 409, \"member_already_exists\", \"User is already a member of this team\");\n }\n\n const row = vs.teamMembers.insert({\n teamId: team.uid,\n userId: target.uid,\n role,\n confirmed: true,\n joinedFrom: email ? \"email\" : \"invite\",\n });\n\n return c.json({ member: formatMemberRow(vs, row) });\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody } from \"@emulators/core\";\nexport { ApiError };\nimport { getVercelStore } from \"../store.js\";\nimport type { VercelStore } from \"../store.js\";\nimport type {\n VercelDeployment,\n VercelDeploymentAlias,\n VercelDeploymentEvent,\n VercelDeploymentFile,\n VercelDomain,\n VercelEnvVar,\n VercelProject,\n VercelProtectionBypass,\n VercelBuild,\n VercelUser,\n} from \"../entities.js\";\nimport {\n applyCursorPagination,\n formatEnvVar,\n formatProject,\n generateSecret,\n generateUid,\n lookupProject,\n nowMs,\n parseCursorPagination,\n resolveTeamScope,\n} from \"../helpers.js\";\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nfunction parseGitLink(body: Record<string, unknown>): VercelProject[\"link\"] {\n const gr = body.gitRepository;\n if (!gr || typeof gr !== \"object\") return null;\n const g = gr as Record<string, unknown>;\n const repo = typeof g.repo === \"string\" ? g.repo : \"\";\n if (!repo) return null;\n const t = nowMs();\n return {\n type: typeof g.type === \"string\" ? g.type : \"github\",\n repo,\n repoId: typeof g.repoId === \"number\" ? g.repoId : 0,\n org: typeof g.org === \"string\" ? g.org : \"\",\n gitCredentialId: typeof g.gitCredentialId === \"string\" ? g.gitCredentialId : \"\",\n productionBranch: typeof g.productionBranch === \"string\" ? g.productionBranch : \"main\",\n createdAt: t,\n updatedAt: t,\n deployHooks: [],\n };\n}\n\nfunction deleteProjectCascade(vs: VercelStore, project: VercelProject): void {\n const projectUid = project.uid;\n\n const deps = vs.deployments.findBy(\"projectId\", projectUid as VercelDeployment[\"projectId\"]);\n for (const dep of deps) {\n for (const b of vs.builds.findBy(\"deploymentId\", dep.uid as VercelBuild[\"deploymentId\"])) {\n vs.builds.delete(b.id);\n }\n for (const e of vs.deploymentEvents.findBy(\"deploymentId\", dep.uid as VercelDeploymentEvent[\"deploymentId\"])) {\n vs.deploymentEvents.delete(e.id);\n }\n for (const f of vs.deploymentFiles.findBy(\"deploymentId\", dep.uid as VercelDeploymentFile[\"deploymentId\"])) {\n vs.deploymentFiles.delete(f.id);\n }\n for (const a of vs.deploymentAliases.findBy(\"deploymentId\", dep.uid as VercelDeploymentAlias[\"deploymentId\"])) {\n vs.deploymentAliases.delete(a.id);\n }\n vs.deployments.delete(dep.id);\n }\n\n for (const d of vs.domains.findBy(\"projectId\", projectUid as VercelDomain[\"projectId\"])) {\n vs.domains.delete(d.id);\n }\n for (const ev of vs.envVars.findBy(\"projectId\", projectUid as VercelEnvVar[\"projectId\"])) {\n vs.envVars.delete(ev.id);\n }\n for (const pb of vs.protectionBypasses.findBy(\"projectId\", projectUid as VercelProtectionBypass[\"projectId\"])) {\n vs.protectionBypasses.delete(pb.id);\n }\n vs.projects.delete(project.id);\n}\n\nfunction protectionMetaForRow(row: VercelProtectionBypass): { createdAt: number; createdBy: string; scope: string } {\n return {\n createdAt: new Date(row.created_at).getTime(),\n createdBy: row.createdBy,\n scope: row.scope,\n };\n}\n\nfunction syncProtectionRecordFromCollection(vs: VercelStore, project: VercelProject): VercelProject {\n const rows = vs.protectionBypasses.findBy(\"projectId\", project.uid as VercelProtectionBypass[\"projectId\"]);\n const record: VercelProject[\"protectionBypass\"] = {};\n for (const row of rows) {\n record[row.secret] = protectionMetaForRow(row);\n }\n const updated = vs.projects.update(project.id, { protectionBypass: record });\n return updated ?? { ...project, protectionBypass: record };\n}\n\nexport function projectsRoutes({ app, store, baseUrl }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.post(\"/v11/projects\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name.trim() : \"\";\n if (!name) {\n return vercelErr(c, 400, \"bad_request\", \"Missing required field: name\");\n }\n\n const existing = vs.projects\n .findBy(\"name\", name as VercelProject[\"name\"])\n .filter((p) => p.accountId === scope.accountId);\n if (existing.length > 0) {\n return vercelErr(c, 409, \"project_already_exists\", \"A project with this name already exists\");\n }\n\n const link = parseGitLink(body);\n\n const project = vs.projects.insert({\n uid: generateUid(\"prj\"),\n name,\n accountId: scope.accountId,\n framework: typeof body.framework === \"string\" ? body.framework : null,\n buildCommand: typeof body.buildCommand === \"string\" ? body.buildCommand : null,\n devCommand: typeof body.devCommand === \"string\" ? body.devCommand : null,\n installCommand: typeof body.installCommand === \"string\" ? body.installCommand : null,\n outputDirectory: typeof body.outputDirectory === \"string\" ? body.outputDirectory : null,\n rootDirectory: typeof body.rootDirectory === \"string\" ? body.rootDirectory : null,\n commandForIgnoringBuildStep: null,\n nodeVersion: typeof body.nodeVersion === \"string\" ? body.nodeVersion : \"20.x\",\n serverlessFunctionRegion:\n typeof body.serverlessFunctionRegion === \"string\" ? body.serverlessFunctionRegion : null,\n publicSource: typeof body.publicSource === \"boolean\" ? body.publicSource : false,\n autoAssignCustomDomains: true,\n autoAssignCustomDomainsUpdatedBy: null,\n gitForkProtection: true,\n sourceFilesOutsideRootDirectory: false,\n live: true,\n link,\n latestDeployments: [],\n targets: {},\n protectionBypass: {},\n passwordProtection: null,\n ssoProtection: null,\n trustedIps: null,\n connectConfigurationId: null,\n gitComments: { onPullRequest: true, onCommit: false },\n webAnalytics: null,\n speedInsights: null,\n oidcTokenConfig: null,\n tier: \"hobby\",\n });\n\n const envIn = body.environmentVariables;\n if (Array.isArray(envIn)) {\n for (const raw of envIn) {\n if (!raw || typeof raw !== \"object\") continue;\n const ev = raw as Record<string, unknown>;\n const key = typeof ev.key === \"string\" ? ev.key : \"\";\n if (!key) continue;\n vs.envVars.insert({\n uid: generateUid(\"env\"),\n projectId: project.uid,\n key,\n value: typeof ev.value === \"string\" ? ev.value : String(ev.value ?? \"\"),\n type:\n ev.type === \"system\" ||\n ev.type === \"encrypted\" ||\n ev.type === \"plain\" ||\n ev.type === \"secret\" ||\n ev.type === \"sensitive\"\n ? ev.type\n : \"encrypted\",\n target: Array.isArray(ev.target)\n ? (ev.target.filter(\n (t) => t === \"production\" || t === \"preview\" || t === \"development\",\n ) as VercelEnvVar[\"target\"])\n : [\"production\", \"preview\", \"development\"],\n gitBranch: typeof ev.gitBranch === \"string\" ? ev.gitBranch : null,\n customEnvironmentIds: Array.isArray(ev.customEnvironmentIds) ? (ev.customEnvironmentIds as string[]) : [],\n comment: typeof ev.comment === \"string\" ? ev.comment : null,\n decrypted: false,\n });\n }\n }\n\n return c.json(formatProject(project, baseUrl));\n });\n\n app.get(\"/v10/projects\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const pagination = parseCursorPagination(c);\n const search = (c.req.query(\"search\") ?? \"\").trim().toLowerCase();\n\n let list = vs.projects.all().filter((p) => p.accountId === scope.accountId);\n if (search) {\n list = list.filter((p) => p.name.toLowerCase().includes(search));\n }\n\n const { items, pagination: pageMeta } = applyCursorPagination(list, pagination);\n return c.json({\n projects: items.map((p) => formatProject(p, baseUrl)),\n pagination: pageMeta,\n });\n });\n\n app.get(\"/v9/projects/:idOrName\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const envs = vs.envVars.findBy(\"projectId\", project.uid as VercelEnvVar[\"projectId\"]);\n return c.json({\n ...formatProject(project, baseUrl),\n env: envs.map((e) => formatEnvVar(e)),\n });\n });\n\n app.patch(\"/v9/projects/:idOrName\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<VercelProject> = {};\n\n if (\"name\" in body && typeof body.name === \"string\") patch.name = body.name.trim();\n if (\"buildCommand\" in body) {\n patch.buildCommand =\n body.buildCommand === null\n ? null\n : typeof body.buildCommand === \"string\"\n ? body.buildCommand\n : project.buildCommand;\n }\n if (\"devCommand\" in body) {\n patch.devCommand =\n body.devCommand === null ? null : typeof body.devCommand === \"string\" ? body.devCommand : project.devCommand;\n }\n if (\"installCommand\" in body) {\n patch.installCommand =\n body.installCommand === null\n ? null\n : typeof body.installCommand === \"string\"\n ? body.installCommand\n : project.installCommand;\n }\n if (\"outputDirectory\" in body) {\n patch.outputDirectory =\n body.outputDirectory === null\n ? null\n : typeof body.outputDirectory === \"string\"\n ? body.outputDirectory\n : project.outputDirectory;\n }\n if (\"framework\" in body) {\n patch.framework =\n body.framework === null ? null : typeof body.framework === \"string\" ? body.framework : project.framework;\n }\n if (\"rootDirectory\" in body) {\n patch.rootDirectory =\n body.rootDirectory === null\n ? null\n : typeof body.rootDirectory === \"string\"\n ? body.rootDirectory\n : project.rootDirectory;\n }\n if (\"gitForkProtection\" in body && typeof body.gitForkProtection === \"boolean\") {\n patch.gitForkProtection = body.gitForkProtection;\n }\n if (\"publicSource\" in body && typeof body.publicSource === \"boolean\") {\n patch.publicSource = body.publicSource;\n }\n if (\"nodeVersion\" in body && typeof body.nodeVersion === \"string\") {\n patch.nodeVersion = body.nodeVersion;\n }\n if (\"serverlessFunctionRegion\" in body) {\n patch.serverlessFunctionRegion =\n body.serverlessFunctionRegion === null\n ? null\n : typeof body.serverlessFunctionRegion === \"string\"\n ? body.serverlessFunctionRegion\n : project.serverlessFunctionRegion;\n }\n if (\"autoAssignCustomDomains\" in body && typeof body.autoAssignCustomDomains === \"boolean\") {\n patch.autoAssignCustomDomains = body.autoAssignCustomDomains;\n }\n if (\"commandForIgnoringBuildStep\" in body) {\n patch.commandForIgnoringBuildStep =\n body.commandForIgnoringBuildStep === null\n ? null\n : typeof body.commandForIgnoringBuildStep === \"string\"\n ? body.commandForIgnoringBuildStep\n : project.commandForIgnoringBuildStep;\n }\n\n const updated = vs.projects.update(project.id, patch);\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update project\");\n }\n return c.json(formatProject(updated, baseUrl));\n });\n\n app.delete(\"/v9/projects/:idOrName\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n deleteProjectCascade(vs, project);\n return c.body(null, 204);\n });\n\n app.get(\"/v1/projects/:projectId/promote/aliases\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"projectId\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const deployments = vs.deployments.findBy(\"projectId\", project.uid as VercelDeployment[\"projectId\"]);\n const production = deployments\n .filter((d) => d.target === \"production\")\n .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];\n\n if (!production) {\n return c.json({\n status: \"PENDING\",\n alias: [] as string[],\n });\n }\n\n const aliases = vs.deploymentAliases\n .findBy(\"deploymentId\", production.uid as VercelDeploymentAlias[\"deploymentId\"])\n .map((a) => a.alias);\n\n const status =\n production.readySubstate === \"PROMOTED\" || production.readyState === \"READY\" ? \"PROMOTED\" : \"PENDING\";\n\n return c.json({\n status,\n alias: aliases,\n });\n });\n\n app.patch(\"/v1/projects/:idOrName/protection-bypass\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n let project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n const createdBy = user?.uid ?? auth.login;\n\n const body = await parseJsonBody(c);\n\n if (body.generate && typeof body.generate === \"object\" && body.generate !== null) {\n const g = body.generate as Record<string, unknown>;\n const secret = generateSecret();\n vs.protectionBypasses.insert({\n projectId: project.uid,\n secret,\n note: typeof g.note === \"string\" ? g.note : null,\n scope: typeof g.scope === \"string\" ? g.scope : \"deployment\",\n createdBy,\n });\n project = syncProtectionRecordFromCollection(vs, project);\n }\n\n if (Array.isArray(body.revoke)) {\n for (const secret of body.revoke) {\n if (typeof secret !== \"string\") continue;\n const row = vs.protectionBypasses\n .findBy(\"projectId\", project.uid as VercelProtectionBypass[\"projectId\"])\n .find((r) => r.secret === secret);\n if (row) {\n vs.protectionBypasses.delete(row.id);\n }\n }\n project = syncProtectionRecordFromCollection(vs, project);\n }\n\n if (Array.isArray(body.regenerate)) {\n for (const oldSecret of body.regenerate) {\n if (typeof oldSecret !== \"string\") continue;\n const row = vs.protectionBypasses\n .findBy(\"projectId\", project.uid as VercelProtectionBypass[\"projectId\"])\n .find((r) => r.secret === oldSecret);\n if (!row) continue;\n const note = row.note;\n const scopeVal = row.scope;\n vs.protectionBypasses.delete(row.id);\n vs.protectionBypasses.insert({\n projectId: project.uid,\n secret: generateSecret(),\n note,\n scope: scopeVal,\n createdBy,\n });\n }\n project = syncProtectionRecordFromCollection(vs, project);\n }\n\n const fresh = vs.projects.get(project.id) ?? project;\n return c.json({ protectionBypass: fresh.protectionBypass });\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody } from \"@emulators/core\";\nexport { ApiError };\nimport { getVercelStore } from \"../store.js\";\nimport type { VercelStore } from \"../store.js\";\nimport type {\n VercelBuild,\n VercelDeployment,\n VercelDeploymentAlias,\n VercelDeploymentEvent,\n VercelDeploymentFile,\n VercelFile,\n VercelProject,\n VercelUser,\n} from \"../entities.js\";\nimport {\n applyCursorPagination,\n formatDeployment,\n formatDeploymentBrief,\n generateUid,\n lookupProject,\n nowMs,\n parseCursorPagination,\n resolveTeamScope,\n} from \"../helpers.js\";\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nfunction normalizeUrlParam(raw: string): string {\n const s = raw.trim();\n if (s.startsWith(\"http://\") || s.startsWith(\"https://\")) {\n try {\n return new URL(s).hostname;\n } catch {\n return s;\n }\n }\n return s;\n}\n\nfunction primaryHostFromBaseUrl(baseUrl: string): string {\n try {\n const u = new URL(baseUrl);\n if (u.hostname && u.hostname !== \"localhost\" && u.hostname !== \"127.0.0.1\") {\n return u.hostname;\n }\n } catch {\n /* ignore */\n }\n return \"vercel.app\";\n}\n\nfunction deploymentHostname(name: string, uid: string, baseUrl: string): string {\n const slug = `${name}-${uid.slice(4, 12)}`;\n return `${slug}.${primaryHostFromBaseUrl(baseUrl)}`;\n}\n\nfunction productionProjectAlias(projectName: string, baseUrl: string): string {\n return `${projectName}.${primaryHostFromBaseUrl(baseUrl)}`;\n}\n\nfunction findDeploymentByIdOrUrl(vs: VercelStore, idOrUrl: string): VercelDeployment | undefined {\n const raw = idOrUrl.trim();\n const byUid = vs.deployments.findOneBy(\"uid\", raw as VercelDeployment[\"uid\"]);\n if (byUid) return byUid;\n const host = normalizeUrlParam(raw);\n return (\n vs.deployments.findOneBy(\"url\", host as VercelDeployment[\"url\"]) ??\n vs.deployments.findOneBy(\"url\", raw as VercelDeployment[\"url\"])\n );\n}\n\nfunction assertDeploymentAccess(vs: VercelStore, dep: VercelDeployment, accountId: string): boolean {\n const project = vs.projects.findOneBy(\"uid\", dep.projectId as VercelProject[\"uid\"]);\n return !!project && project.accountId === accountId;\n}\n\nfunction defaultProjectPayload(\n name: string,\n accountId: string,\n): Omit<VercelProject, \"id\" | \"created_at\" | \"updated_at\"> {\n return {\n uid: generateUid(\"prj\"),\n name,\n accountId,\n framework: null,\n buildCommand: null,\n devCommand: null,\n installCommand: null,\n outputDirectory: null,\n rootDirectory: null,\n commandForIgnoringBuildStep: null,\n nodeVersion: \"20.x\",\n serverlessFunctionRegion: null,\n publicSource: false,\n autoAssignCustomDomains: true,\n autoAssignCustomDomainsUpdatedBy: null,\n gitForkProtection: true,\n sourceFilesOutsideRootDirectory: false,\n live: true,\n link: null,\n latestDeployments: [],\n targets: {},\n protectionBypass: {},\n passwordProtection: null,\n ssoProtection: null,\n trustedIps: null,\n connectConfigurationId: null,\n gitComments: { onPullRequest: true, onCommit: false },\n webAnalytics: null,\n speedInsights: null,\n oidcTokenConfig: null,\n tier: \"hobby\",\n };\n}\n\nfunction resolveOrCreateProject(\n vs: VercelStore,\n accountId: string,\n name: string,\n projectField: unknown,\n): VercelProject {\n if (typeof projectField === \"string\" && projectField.trim()) {\n const byId = lookupProject(vs, projectField.trim(), accountId);\n if (byId) return byId;\n }\n const existing = vs.projects.findBy(\"name\", name as VercelProject[\"name\"]).find((p) => p.accountId === accountId);\n if (existing) return existing;\n return vs.projects.insert(defaultProjectPayload(name, accountId));\n}\n\nfunction targetKey(target: VercelDeployment[\"target\"]): \"production\" | \"preview\" | \"staging\" {\n if (target === \"production\") return \"production\";\n if (target === \"staging\") return \"staging\";\n return \"preview\";\n}\n\nfunction upsertProjectDeploymentRefs(vs: VercelStore, projectId: number, dep: VercelDeployment): void {\n const project = vs.projects.get(projectId);\n if (!project) return;\n const createdAt = new Date(dep.created_at).getTime();\n const entry = { id: dep.uid, url: dep.url, state: dep.state, createdAt };\n const latest = [{ ...entry }, ...project.latestDeployments.filter((d) => d.id !== dep.uid)];\n const targets = { ...project.targets };\n targets[targetKey(dep.target)] = { ...entry };\n vs.projects.update(project.id, { latestDeployments: latest, targets });\n}\n\nfunction parseGitSource(raw: unknown): VercelDeployment[\"gitSource\"] {\n if (!raw || typeof raw !== \"object\") return null;\n const g = raw as Record<string, unknown>;\n return {\n type: typeof g.type === \"string\" ? g.type : \"github\",\n ref: typeof g.ref === \"string\" ? g.ref : \"\",\n sha: typeof g.sha === \"string\" ? g.sha : \"\",\n repoId: typeof g.repoId === \"string\" ? g.repoId : typeof g.repoId === \"number\" ? String(g.repoId) : \"\",\n org: typeof g.org === \"string\" ? g.org : \"\",\n repo: typeof g.repo === \"string\" ? g.repo : \"\",\n message: typeof g.message === \"string\" ? g.message : \"\",\n authorName: typeof g.authorName === \"string\" ? g.authorName : \"\",\n commitAuthorName: typeof g.commitAuthorName === \"string\" ? g.commitAuthorName : \"\",\n };\n}\n\ntype FileTreeNode = {\n uid: string;\n name: string;\n type: \"file\" | \"directory\";\n mode: number;\n size: number;\n contentType: string | null;\n children: FileTreeNode[];\n};\n\nfunction buildFileTreeFromRows(rows: VercelDeploymentFile[], genUid: () => string): FileTreeNode[] {\n if (rows.length === 0) {\n return [\n {\n uid: genUid(),\n name: \"/\",\n type: \"directory\",\n mode: 0o40755,\n size: 0,\n contentType: null,\n children: [],\n },\n ];\n }\n\n const root: FileTreeNode = {\n uid: genUid(),\n name: \"/\",\n type: \"directory\",\n mode: 0o40755,\n size: 0,\n contentType: null,\n children: [],\n };\n\n for (const row of rows) {\n if (row.type !== \"file\") continue;\n const parts = row.name.split(\"/\").filter(Boolean);\n if (parts.length === 0) continue;\n const fileName = parts.pop()!;\n let current = root;\n for (const part of parts) {\n let dir = current.children.find((c) => c.name === part && c.type === \"directory\");\n if (!dir) {\n dir = {\n uid: genUid(),\n name: part,\n type: \"directory\",\n mode: 0o40755,\n size: 0,\n contentType: null,\n children: [],\n };\n current.children.push(dir);\n }\n current = dir;\n }\n current.children.push({\n uid: row.uid,\n name: fileName,\n type: \"file\",\n mode: row.mode,\n size: row.size,\n contentType: row.contentType,\n children: [],\n });\n }\n\n return [root];\n}\n\nfunction deleteDeploymentCascade(vs: VercelStore, dep: VercelDeployment): void {\n const uid = dep.uid;\n for (const b of vs.builds.findBy(\"deploymentId\", uid as VercelBuild[\"deploymentId\"])) {\n vs.builds.delete(b.id);\n }\n for (const e of vs.deploymentEvents.findBy(\"deploymentId\", uid as VercelDeploymentEvent[\"deploymentId\"])) {\n vs.deploymentEvents.delete(e.id);\n }\n for (const f of vs.deploymentFiles.findBy(\"deploymentId\", uid as VercelDeploymentFile[\"deploymentId\"])) {\n vs.deploymentFiles.delete(f.id);\n }\n for (const a of vs.deploymentAliases.findBy(\"deploymentId\", uid as VercelDeploymentAlias[\"deploymentId\"])) {\n vs.deploymentAliases.delete(a.id);\n }\n vs.deployments.delete(dep.id);\n\n const project = vs.projects.findOneBy(\"uid\", dep.projectId as VercelProject[\"uid\"]);\n if (project) {\n const latestDeployments = project.latestDeployments.filter((d) => d.id !== uid);\n const targets = { ...project.targets };\n for (const k of Object.keys(targets) as (keyof typeof targets)[]) {\n if (targets[k]?.id === uid) {\n delete targets[k];\n }\n }\n vs.projects.update(project.id, { latestDeployments, targets });\n }\n}\n\nexport function deploymentsRoutes({ app, store, baseUrl }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.patch(\"/v12/deployments/:id/cancel\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const dep = vs.deployments.findOneBy(\"uid\", c.req.param(\"id\") as VercelDeployment[\"uid\"]);\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n if (dep.readyState !== \"QUEUED\" && dep.readyState !== \"BUILDING\") {\n return vercelErr(c, 400, \"bad_request\", \"Deployment cannot be canceled in its current state\");\n }\n\n const t = nowMs();\n const updated =\n vs.deployments.update(dep.id, {\n readyState: \"CANCELED\",\n state: \"CANCELED\",\n canceledAt: t,\n }) ?? dep;\n\n vs.deploymentEvents.insert({\n deploymentId: updated.uid,\n type: \"canceled\",\n payload: { text: \"Deployment canceled\" },\n date: t,\n serial: String(t),\n });\n\n return c.json(formatDeployment(updated, vs, baseUrl));\n });\n\n app.get(\"/v2/deployments/:id/aliases\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const dep = vs.deployments.findOneBy(\"uid\", c.req.param(\"id\") as VercelDeployment[\"uid\"]);\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n const aliases = vs.deploymentAliases.findBy(\"deploymentId\", dep.uid as VercelDeploymentAlias[\"deploymentId\"]);\n return c.json({\n aliases: aliases.map((a) => ({\n uid: a.uid,\n alias: a.alias,\n deploymentId: a.deploymentId,\n projectId: a.projectId,\n })),\n });\n });\n\n app.get(\"/v3/deployments/:idOrUrl/events\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const dep = findDeploymentByIdOrUrl(vs, c.req.param(\"idOrUrl\"));\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n void c.req.query(\"follow\");\n\n const direction = (c.req.query(\"direction\") ?? \"backward\").toLowerCase();\n const limit = Math.min(100, Math.max(1, parseInt(c.req.query(\"limit\") ?? \"20\", 10) || 20));\n\n let list = [...vs.deploymentEvents.findBy(\"deploymentId\", dep.uid as VercelDeploymentEvent[\"deploymentId\"])];\n list.sort((a, b) => a.date - b.date);\n if (direction === \"backward\") {\n list.reverse();\n }\n list = list.slice(0, limit);\n\n return c.json(\n list.map((e) => ({\n type: e.type,\n payload: e.payload,\n date: e.date,\n serial: e.serial,\n })),\n );\n });\n\n app.get(\"/v6/deployments/:id/files\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const dep = vs.deployments.findOneBy(\"uid\", c.req.param(\"id\") as VercelDeployment[\"uid\"]);\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n const rows = vs.deploymentFiles.findBy(\"deploymentId\", dep.uid as VercelDeploymentFile[\"deploymentId\"]);\n const tree = buildFileTreeFromRows(rows, () => generateUid(\"file\"));\n return c.json({ files: tree });\n });\n\n app.post(\"/v13/deployments\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name.trim() : \"\";\n if (!name) {\n return vercelErr(c, 400, \"bad_request\", \"Missing required field: name\");\n }\n\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 400, \"bad_request\", \"User not found in Vercel store\");\n }\n\n const project = resolveOrCreateProject(vs, scope.accountId, name, body.project);\n\n const uid = generateUid(\"dpl\");\n const url = deploymentHostname(name, uid, baseUrl);\n const inspectorUrl = `${baseUrl.replace(/\\/$/, \"\")}/deployments/${uid}`;\n\n const targetRaw = body.target;\n const target: VercelDeployment[\"target\"] =\n targetRaw === \"production\" || targetRaw === \"preview\" || targetRaw === \"staging\" ? targetRaw : \"preview\";\n\n const meta: Record<string, string> = {};\n if (body.meta && typeof body.meta === \"object\" && body.meta !== null) {\n for (const [k, v] of Object.entries(body.meta as Record<string, unknown>)) {\n if (typeof v === \"string\") meta[k] = v;\n }\n }\n\n const regions =\n Array.isArray(body.regions) && body.regions.every((r) => typeof r === \"string\")\n ? (body.regions as string[])\n : [\"iad1\"];\n\n const t = nowMs();\n const gitSource = parseGitSource(body.gitSource);\n const source = gitSource ? \"git\" : \"cli\";\n\n const dep = vs.deployments.insert({\n uid,\n name,\n url,\n projectId: project.uid,\n source,\n target,\n readyState: \"READY\",\n readySubstate: null,\n state: \"READY\",\n creatorId: user.uid,\n inspectorUrl,\n meta,\n gitSource,\n buildingAt: t,\n readyAt: t,\n canceledAt: null,\n errorCode: null,\n errorMessage: null,\n regions,\n functions: null,\n routes: null,\n plan: \"hobby\",\n aliasAssigned: true,\n aliasError: null,\n bootedAt: t,\n });\n\n vs.deploymentAliases.insert({\n uid: generateUid(\"als\"),\n alias: url,\n deploymentId: dep.uid,\n projectId: project.uid,\n });\n\n if (target === \"production\") {\n vs.deploymentAliases.insert({\n uid: generateUid(\"als\"),\n alias: productionProjectAlias(project.name, baseUrl),\n deploymentId: dep.uid,\n projectId: project.uid,\n });\n }\n\n upsertProjectDeploymentRefs(vs, project.id, dep);\n\n vs.builds.insert({\n uid: generateUid(\"bld\"),\n deploymentId: dep.uid,\n entrypoint: \"api/index.ts\",\n readyState: \"READY\",\n output: [],\n readyStateAt: t,\n fingerprint: generateUid(\"fgp\"),\n });\n\n let serial = 0;\n const pushEvent = (type: string, text: string) => {\n serial += 1;\n vs.deploymentEvents.insert({\n deploymentId: dep.uid,\n type,\n payload: { text },\n date: t,\n serial: String(serial),\n });\n };\n pushEvent(\"created\", \"Deployment created\");\n pushEvent(\"building\", \"Building\");\n pushEvent(\"ready\", \"Deployment ready\");\n\n const filesIn = body.files;\n if (Array.isArray(filesIn)) {\n for (const raw of filesIn) {\n if (!raw || typeof raw !== \"object\") continue;\n const f = raw as Record<string, unknown>;\n const filePath = typeof f.file === \"string\" ? f.file : \"\";\n const sha = typeof f.sha === \"string\" ? f.sha : \"\";\n const size = typeof f.size === \"number\" ? f.size : 0;\n if (!filePath || !sha) continue;\n\n if (!vs.files.findOneBy(\"digest\", sha as VercelFile[\"digest\"])) {\n vs.files.insert({\n digest: sha,\n size,\n contentType: \"application/octet-stream\",\n });\n }\n\n vs.deploymentFiles.insert({\n deploymentId: dep.uid,\n name: filePath,\n type: \"file\",\n uid: generateUid(\"f\"),\n children: [],\n contentType: \"application/octet-stream\",\n mode: 0o644,\n size,\n });\n }\n }\n\n return c.json(formatDeployment(dep, vs, baseUrl));\n });\n\n app.get(\"/v6/deployments\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const appName = (c.req.query(\"app\") ?? \"\").trim();\n const projectIdFilter = (c.req.query(\"projectId\") ?? \"\").trim();\n const targetFilter = c.req.query(\"target\");\n const stateFilter = c.req.query(\"state\");\n\n let list = vs.deployments.all().filter((d) => {\n const proj = vs.projects.findOneBy(\"uid\", d.projectId as VercelProject[\"uid\"]);\n return proj && proj.accountId === scope.accountId;\n });\n\n if (appName) {\n list = list.filter((d) => {\n const proj = vs.projects.findOneBy(\"uid\", d.projectId as VercelProject[\"uid\"]);\n return proj?.name === appName;\n });\n }\n\n if (projectIdFilter) {\n list = list.filter((d) => d.projectId === projectIdFilter);\n }\n\n if (targetFilter === \"production\" || targetFilter === \"preview\" || targetFilter === \"staging\") {\n list = list.filter((d) => d.target === targetFilter);\n }\n\n if (stateFilter) {\n list = list.filter((d) => d.state === stateFilter || d.readyState === stateFilter);\n }\n\n const pagination = parseCursorPagination(c);\n const { items, pagination: pageMeta } = applyCursorPagination(list, pagination);\n\n return c.json({\n deployments: items.map((d) => formatDeploymentBrief(d, vs)),\n pagination: pageMeta,\n });\n });\n\n app.delete(\"/v13/deployments/:id\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const dep = vs.deployments.findOneBy(\"uid\", c.req.param(\"id\") as VercelDeployment[\"uid\"]);\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n const uid = dep.uid;\n deleteDeploymentCascade(vs, dep);\n\n return c.json({ uid, state: \"DELETED\" });\n });\n\n app.get(\"/v13/deployments/:idOrUrl\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const dep = findDeploymentByIdOrUrl(vs, c.req.param(\"idOrUrl\"));\n if (!dep || !assertDeploymentAccess(vs, dep, scope.accountId)) {\n return vercelErr(c, 404, \"not_found\", \"Deployment not found\");\n }\n\n return c.json(formatDeployment(dep, vs, baseUrl));\n });\n\n app.post(\"/v2/files\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const digest = c.req.header(\"x-vercel-digest\") ?? \"\";\n if (!digest) {\n return vercelErr(c, 400, \"bad_request\", \"Missing x-vercel-digest header\");\n }\n\n const lenRaw = c.req.header(\"Content-Length\");\n const size = lenRaw ? parseInt(lenRaw, 10) : 0;\n if (!Number.isFinite(size) || size < 0) {\n return vercelErr(c, 400, \"bad_request\", \"Invalid Content-Length\");\n }\n\n await c.req.arrayBuffer();\n\n const contentType = c.req.header(\"Content-Type\") ?? \"application/octet-stream\";\n\n if (!vs.files.findOneBy(\"digest\", digest as VercelFile[\"digest\"])) {\n vs.files.insert({\n digest,\n size,\n contentType,\n });\n }\n\n return c.json([]);\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody } from \"@emulators/core\";\nexport { ApiError };\nimport { getVercelStore } from \"../store.js\";\nimport type { VercelStore } from \"../store.js\";\nimport type { VercelDomain } from \"../entities.js\";\nimport {\n applyCursorPagination,\n formatDomain,\n generateUid,\n lookupProject,\n parseCursorPagination,\n resolveTeamScope,\n} from \"../helpers.js\";\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nfunction extractApexName(domain: string): string {\n const parts = domain\n .toLowerCase()\n .split(\".\")\n .filter((p) => p.length > 0);\n if (parts.length === 0) return domain;\n if (parts.length === 1) return parts[0];\n return parts.slice(-2).join(\".\");\n}\n\nfunction isVercelAppDomain(domain: string): boolean {\n const d = domain.toLowerCase();\n return d === \"vercel.app\" || d.endsWith(\".vercel.app\");\n}\n\nfunction normalizeDomainName(raw: string): string {\n return raw.trim().toLowerCase();\n}\n\nfunction parseRedirectStatusCode(raw: unknown): 301 | 302 | 307 | 308 | null | \"invalid\" {\n if (raw === undefined || raw === null) return null;\n if (typeof raw !== \"number\" || !Number.isInteger(raw)) return \"invalid\";\n if (raw === 301 || raw === 302 || raw === 307 || raw === 308) return raw;\n return \"invalid\";\n}\n\nfunction findDomainInProject(vs: VercelStore, projectUid: string, domainName: string): VercelDomain | undefined {\n const normalized = normalizeDomainName(domainName);\n return vs.domains\n .findBy(\"projectId\", projectUid as VercelDomain[\"projectId\"])\n .find((d) => d.name.toLowerCase() === normalized);\n}\n\nfunction decodeDomainParam(raw: string): string {\n try {\n return decodeURIComponent(raw);\n } catch {\n return raw;\n }\n}\n\nexport function domainsRoutes({ app, store }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.post(\"/v10/projects/:idOrName/domains\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const body = await parseJsonBody(c);\n const nameRaw = typeof body.name === \"string\" ? body.name.trim() : \"\";\n if (!nameRaw) {\n return vercelErr(c, 400, \"bad_request\", \"Missing required field: name\");\n }\n\n const name = normalizeDomainName(nameRaw);\n const apexName = extractApexName(name);\n\n if (findDomainInProject(vs, project.uid, name)) {\n return vercelErr(c, 409, \"domain_already_exists\", \"A domain with this name already exists on the project\");\n }\n\n const redirect =\n body.redirect === null ? null : typeof body.redirect === \"string\" ? body.redirect.trim() || null : null;\n const redirectStatusCode = parseRedirectStatusCode(body.redirectStatusCode);\n if (redirectStatusCode === \"invalid\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid redirectStatusCode\");\n }\n\n const gitBranch = body.gitBranch === null ? null : typeof body.gitBranch === \"string\" ? body.gitBranch : null;\n const customEnvironmentId =\n body.customEnvironmentId === null\n ? null\n : typeof body.customEnvironmentId === \"string\"\n ? body.customEnvironmentId\n : null;\n\n const uid = generateUid();\n const autoVerified = isVercelAppDomain(name);\n const verified = autoVerified;\n const verification: VercelDomain[\"verification\"] = autoVerified\n ? []\n : [\n {\n type: \"TXT\",\n domain: `_vercel.${apexName}`,\n value: `vc-domain-verify=${name},${uid}`,\n reason: \"Add the TXT record above to verify domain ownership\",\n },\n ];\n\n const row = vs.domains.insert({\n uid,\n projectId: project.uid,\n name,\n apexName,\n redirect,\n redirectStatusCode,\n gitBranch,\n customEnvironmentId,\n verified,\n verification,\n });\n\n return c.json(formatDomain(row));\n });\n\n app.get(\"/v9/projects/:idOrName/domains\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const pagination = parseCursorPagination(c);\n const list = vs.domains.findBy(\"projectId\", project.uid as VercelDomain[\"projectId\"]);\n const { items, pagination: pageMeta } = applyCursorPagination(list, pagination);\n return c.json({\n domains: items.map((d) => formatDomain(d)),\n pagination: pageMeta,\n });\n });\n\n app.post(\"/v9/projects/:idOrName/domains/:domain/verify\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const domainName = decodeDomainParam(c.req.param(\"domain\"));\n const existing = findDomainInProject(vs, project.uid, domainName);\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Domain not found\");\n }\n\n const updated = vs.domains.update(existing.id, {\n verified: true,\n verification: [],\n });\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update domain\");\n }\n return c.json(formatDomain(updated));\n });\n\n app.get(\"/v9/projects/:idOrName/domains/:domain\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const domainName = decodeDomainParam(c.req.param(\"domain\"));\n const existing = findDomainInProject(vs, project.uid, domainName);\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Domain not found\");\n }\n\n return c.json(formatDomain(existing));\n });\n\n app.patch(\"/v9/projects/:idOrName/domains/:domain\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const domainName = decodeDomainParam(c.req.param(\"domain\"));\n const existing = findDomainInProject(vs, project.uid, domainName);\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Domain not found\");\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<Omit<VercelDomain, \"id\" | \"created_at\" | \"updated_at\">> = {};\n\n if (\"gitBranch\" in body) {\n patch.gitBranch =\n body.gitBranch === null ? null : typeof body.gitBranch === \"string\" ? body.gitBranch : existing.gitBranch;\n }\n if (\"redirect\" in body) {\n patch.redirect =\n body.redirect === null\n ? null\n : typeof body.redirect === \"string\"\n ? body.redirect.trim() || null\n : existing.redirect;\n }\n if (\"redirectStatusCode\" in body) {\n const code = parseRedirectStatusCode(body.redirectStatusCode);\n if (code === \"invalid\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid redirectStatusCode\");\n }\n patch.redirectStatusCode = code;\n }\n if (\"customEnvironmentId\" in body) {\n patch.customEnvironmentId =\n body.customEnvironmentId === null\n ? null\n : typeof body.customEnvironmentId === \"string\"\n ? body.customEnvironmentId\n : existing.customEnvironmentId;\n }\n\n const updated = vs.domains.update(existing.id, patch);\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update domain\");\n }\n return c.json(formatDomain(updated));\n });\n\n app.delete(\"/v9/projects/:idOrName/domains/:domain\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const domainName = decodeDomainParam(c.req.param(\"domain\"));\n const existing = findDomainInProject(vs, project.uid, domainName);\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Domain not found\");\n }\n\n vs.domains.delete(existing.id);\n return c.json({}, 200);\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody } from \"@emulators/core\";\nexport { ApiError };\nimport { getVercelStore } from \"../store.js\";\nimport type { VercelStore } from \"../store.js\";\nimport type { VercelEnvVar } from \"../entities.js\";\nimport {\n applyCursorPagination,\n formatEnvVar,\n generateUid,\n lookupProject,\n parseCursorPagination,\n resolveTeamScope,\n} from \"../helpers.js\";\n\nconst ENV_TYPES = new Set<VercelEnvVar[\"type\"]>([\"system\", \"encrypted\", \"plain\", \"secret\", \"sensitive\"]);\n\nconst TARGET_ENVS: readonly VercelEnvVar[\"target\"][number][] = [\"production\", \"preview\", \"development\"];\n\nfunction isTargetEnv(t: string): t is VercelEnvVar[\"target\"][number] {\n return (TARGET_ENVS as readonly string[]).includes(t);\n}\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nfunction parseQueryBoolean(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const v = raw.toLowerCase();\n return v === \"true\" || v === \"1\" || v === \"yes\";\n}\n\nfunction targetsOverlap(a: VercelEnvVar[\"target\"], b: VercelEnvVar[\"target\"]): boolean {\n const set = new Set(a);\n return b.some((t) => set.has(t));\n}\n\nfunction findEnvByKeyAndTargetsOverlap(\n vs: VercelStore,\n projectUid: string,\n key: string,\n targets: VercelEnvVar[\"target\"],\n excludeId?: number,\n): VercelEnvVar | undefined {\n const list = vs.envVars.findBy(\"projectId\", projectUid as VercelEnvVar[\"projectId\"]);\n return list.find(\n (e) => e.key === key && (excludeId === undefined || e.id !== excludeId) && targetsOverlap(e.target, targets),\n );\n}\n\nfunction parseTarget(raw: unknown): VercelEnvVar[\"target\"] | \"invalid\" {\n if (!Array.isArray(raw) || raw.length === 0) return \"invalid\";\n const out: VercelEnvVar[\"target\"] = [];\n for (const t of raw) {\n if (typeof t !== \"string\" || !isTargetEnv(t)) return \"invalid\";\n out.push(t);\n }\n return out;\n}\n\nfunction parseType(raw: unknown): VercelEnvVar[\"type\"] | \"invalid\" {\n if (typeof raw !== \"string\" || !ENV_TYPES.has(raw as VercelEnvVar[\"type\"])) return \"invalid\";\n return raw as VercelEnvVar[\"type\"];\n}\n\nfunction parseCustomEnvironmentIds(raw: unknown): string[] | \"invalid\" {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) return \"invalid\";\n const ids: string[] = [];\n for (const x of raw) {\n if (typeof x !== \"string\") return \"invalid\";\n ids.push(x);\n }\n return ids;\n}\n\nfunction parseEnvRow(body: Record<string, unknown>): {\n row: Omit<VercelEnvVar, \"id\" | \"uid\" | \"projectId\" | \"created_at\" | \"updated_at\">;\n error: string | null;\n} {\n const key = typeof body.key === \"string\" ? body.key : \"\";\n if (!key.trim()) {\n return { row: {} as never, error: \"Missing required field: key\" };\n }\n\n if (body.value === undefined) {\n return { row: {} as never, error: \"Missing required field: value\" };\n }\n if (typeof body.value !== \"string\") {\n return { row: {} as never, error: \"Invalid value: value must be a string\" };\n }\n\n const type = parseType(body.type);\n if (type === \"invalid\") {\n return {\n row: {} as never,\n error: \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\",\n };\n }\n\n const target = parseTarget(body.target);\n if (target === \"invalid\") {\n return {\n row: {} as never,\n error: \"Invalid value: target must be a non-empty array of production, preview, development\",\n };\n }\n\n const customEnvironmentIds = parseCustomEnvironmentIds(body.customEnvironmentIds);\n if (customEnvironmentIds === \"invalid\") {\n return { row: {} as never, error: \"Invalid value: customEnvironmentIds must be an array of strings\" };\n }\n\n let gitBranch: string | null;\n if (!(\"gitBranch\" in body)) {\n gitBranch = null;\n } else if (body.gitBranch === null) {\n gitBranch = null;\n } else if (typeof body.gitBranch === \"string\") {\n gitBranch = body.gitBranch;\n } else {\n return { row: {} as never, error: \"Invalid value: gitBranch must be a string or null\" };\n }\n\n let comment: string | null;\n if (!(\"comment\" in body)) {\n comment = null;\n } else if (body.comment === null) {\n comment = null;\n } else if (typeof body.comment === \"string\") {\n comment = body.comment;\n } else {\n return { row: {} as never, error: \"Invalid value: comment must be a string or null\" };\n }\n\n return {\n row: {\n key,\n value: body.value,\n type,\n target,\n gitBranch,\n customEnvironmentIds,\n comment,\n decrypted: false,\n },\n error: null,\n };\n}\n\nfunction findEnvByUidInProject(vs: VercelStore, projectUid: string, uid: string): VercelEnvVar | undefined {\n const list = vs.envVars.findBy(\"projectId\", projectUid as VercelEnvVar[\"projectId\"]);\n return list.find((e) => e.uid === uid);\n}\n\nexport function envRoutes({ app, store }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.get(\"/v10/projects/:idOrName/env\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const decrypt = parseQueryBoolean(c.req.query(\"decrypt\"));\n const gitBranchQ = c.req.query(\"gitBranch\");\n const customEnvironmentId = c.req.query(\"customEnvironmentId\");\n const customEnvironmentSlug = c.req.query(\"customEnvironmentSlug\");\n\n let list = vs.envVars.findBy(\"projectId\", project.uid as VercelEnvVar[\"projectId\"]);\n\n if (gitBranchQ !== undefined) {\n list = list.filter((e) => e.gitBranch === gitBranchQ);\n }\n if (customEnvironmentId !== undefined && customEnvironmentId !== \"\") {\n list = list.filter((e) => e.customEnvironmentIds.includes(customEnvironmentId));\n }\n if (customEnvironmentSlug !== undefined && customEnvironmentSlug !== \"\") {\n list = list.filter((e) => e.customEnvironmentIds.includes(customEnvironmentSlug));\n }\n\n const pagination = parseCursorPagination(c);\n const { items, pagination: pageMeta } = applyCursorPagination(list, pagination);\n return c.json({\n envs: items.map((i) => formatEnvVar(i, decrypt)),\n pagination: pageMeta,\n });\n });\n\n app.post(\"/v10/projects/:idOrName/env\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const upsert = parseQueryBoolean(c.req.query(\"upsert\"));\n const rawBody = await c.req.json().catch(() => null);\n\n let items: Record<string, unknown>[] = [];\n if (Array.isArray(rawBody)) {\n items = rawBody as Record<string, unknown>[];\n } else if (rawBody && typeof rawBody === \"object\" && !Array.isArray(rawBody)) {\n items = [rawBody as Record<string, unknown>];\n } else {\n return vercelErr(c, 400, \"bad_request\", \"Invalid JSON body\");\n }\n\n const created: VercelEnvVar[] = [];\n const pending: VercelEnvVar[] = [];\n\n for (const body of items) {\n const parsed = parseEnvRow(body);\n if (parsed.error) {\n return vercelErr(c, 400, \"bad_request\", parsed.error);\n }\n const { row } = parsed;\n\n const existingDb = findEnvByKeyAndTargetsOverlap(vs, project.uid, row.key, row.target);\n const existingPending = pending.find((e) => e.key === row.key && targetsOverlap(e.target, row.target));\n\n if (upsert) {\n const toUpdate = existingDb ?? existingPending;\n if (toUpdate) {\n const updated = vs.envVars.update(toUpdate.id, {\n key: row.key,\n value: row.value,\n type: row.type,\n target: row.target,\n gitBranch: row.gitBranch,\n customEnvironmentIds: row.customEnvironmentIds,\n comment: row.comment,\n });\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update environment variable\");\n }\n const idx = pending.findIndex((p) => p.id === updated.id);\n if (idx >= 0) pending[idx] = updated;\n else pending.push(updated);\n created.push(updated);\n continue;\n }\n } else {\n if (existingDb || existingPending) {\n return vercelErr(\n c,\n 409,\n \"env_already_exists\",\n `An environment variable with key \"${row.key}\" and overlapping targets already exists`,\n );\n }\n }\n\n const inserted = vs.envVars.insert({\n uid: generateUid(\"env\"),\n projectId: project.uid,\n key: row.key,\n value: row.value,\n type: row.type,\n target: row.target,\n gitBranch: row.gitBranch,\n customEnvironmentIds: row.customEnvironmentIds,\n comment: row.comment,\n decrypted: row.decrypted,\n });\n pending.push(inserted);\n created.push(inserted);\n }\n\n return c.json({ envs: created.map((e) => formatEnvVar(e, true)) });\n });\n\n app.get(\"/v10/projects/:idOrName/env/:id\", (c) => {\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const env = findEnvByUidInProject(vs, project.uid, c.req.param(\"id\"));\n if (!env) {\n return vercelErr(c, 404, \"not_found\", \"Environment variable not found\");\n }\n\n const decrypt = parseQueryBoolean(c.req.query(\"decrypt\"));\n return c.json(formatEnvVar(env, decrypt));\n });\n\n app.patch(\"/v9/projects/:idOrName/env/:id\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const existing = findEnvByUidInProject(vs, project.uid, c.req.param(\"id\"));\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Environment variable not found\");\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<\n Pick<VercelEnvVar, \"key\" | \"value\" | \"type\" | \"target\" | \"gitBranch\" | \"customEnvironmentIds\" | \"comment\">\n > = {};\n\n if (\"key\" in body) {\n if (typeof body.key !== \"string\" || !body.key.trim()) {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: key must be a non-empty string\");\n }\n patch.key = body.key;\n }\n if (\"value\" in body) {\n if (typeof body.value !== \"string\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: value must be a string\");\n }\n patch.value = body.value;\n }\n if (\"type\" in body) {\n const t = parseType(body.type);\n if (t === \"invalid\") {\n return vercelErr(\n c,\n 400,\n \"bad_request\",\n \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\",\n );\n }\n patch.type = t;\n }\n if (\"target\" in body) {\n const t = parseTarget(body.target);\n if (t === \"invalid\") {\n return vercelErr(\n c,\n 400,\n \"bad_request\",\n \"Invalid value: target must be a non-empty array of production, preview, development\",\n );\n }\n patch.target = t;\n }\n if (\"gitBranch\" in body) {\n if (body.gitBranch === null) {\n patch.gitBranch = null;\n } else if (typeof body.gitBranch === \"string\") {\n patch.gitBranch = body.gitBranch;\n } else {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: gitBranch must be a string or null\");\n }\n }\n if (\"customEnvironmentIds\" in body) {\n const ids = parseCustomEnvironmentIds(body.customEnvironmentIds);\n if (ids === \"invalid\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: customEnvironmentIds must be an array of strings\");\n }\n patch.customEnvironmentIds = ids;\n }\n if (\"comment\" in body) {\n if (body.comment === null) {\n patch.comment = null;\n } else if (typeof body.comment === \"string\") {\n patch.comment = body.comment;\n } else {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: comment must be a string or null\");\n }\n }\n\n const nextKey = patch.key ?? existing.key;\n const nextTarget = patch.target ?? existing.target;\n\n const conflict = findEnvByKeyAndTargetsOverlap(vs, project.uid, nextKey, nextTarget, existing.id);\n if (conflict) {\n return vercelErr(\n c,\n 409,\n \"env_already_exists\",\n `An environment variable with key \"${nextKey}\" and overlapping targets already exists`,\n );\n }\n\n const updated = vs.envVars.update(existing.id, patch);\n if (!updated) {\n return vercelErr(c, 500, \"internal_error\", \"Failed to update environment variable\");\n }\n return c.json(formatEnvVar(updated, true));\n });\n\n app.delete(\"/v9/projects/:idOrName/env/:id\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n\n const scope = resolveTeamScope(c, vs);\n if (!scope) {\n return vercelErr(c, 400, \"bad_request\", \"Could not resolve team or account scope\");\n }\n\n const project = lookupProject(vs, c.req.param(\"idOrName\"), scope.accountId);\n if (!project) {\n return vercelErr(c, 404, \"not_found\", \"Project not found\");\n }\n\n const existing = findEnvByUidInProject(vs, project.uid, c.req.param(\"id\"));\n if (!existing) {\n return vercelErr(c, 404, \"not_found\", \"Environment variable not found\");\n }\n\n const snapshot = formatEnvVar(existing, true);\n vs.envVars.delete(existing.id);\n return c.json(snapshot, 200);\n });\n}\n","import { createHash, randomBytes } from \"crypto\";\nimport type { RouteContext, Store } from \"@emulators/core\";\nimport {\n escapeHtml,\n escapeAttr,\n renderCardPage,\n renderErrorPage,\n renderUserButton,\n matchesRedirectUri,\n constantTimeSecretEqual,\n bodyStr,\n debug,\n} from \"@emulators/core\";\nimport { getVercelStore } from \"../store.js\";\nimport { formatUser } from \"../helpers.js\";\nimport type { VercelUser } from \"../entities.js\";\n\ntype PendingCode = {\n username: string;\n scope: string;\n redirectUri: string;\n clientId: string;\n codeChallenge: string | null;\n codeChallengeMethod: string | null;\n created_at: number;\n};\n\nconst PENDING_CODE_TTL_MS = 10 * 60 * 1000;\n\nfunction getPendingCodes(store: Store): Map<string, PendingCode> {\n let map = store.getData<Map<string, PendingCode>>(\"vercel.oauth.pendingCodes\");\n if (!map) {\n map = new Map();\n store.setData(\"vercel.oauth.pendingCodes\", map);\n }\n return map;\n}\n\nfunction isPendingCodeExpired(p: PendingCode): boolean {\n return Date.now() - p.created_at > PENDING_CODE_TTL_MS;\n}\n\nconst SERVICE_LABEL = \"Vercel\";\n\nexport function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {\n const vs = getVercelStore(store);\n\n // ---------- OAuth authorize page ----------\n\n app.get(\"/oauth/authorize\", (c) => {\n const client_id = c.req.query(\"client_id\") ?? \"\";\n const redirect_uri = c.req.query(\"redirect_uri\") ?? \"\";\n const scope = c.req.query(\"scope\") ?? \"\";\n const state = c.req.query(\"state\") ?? \"\";\n const code_challenge = c.req.query(\"code_challenge\") ?? \"\";\n const code_challenge_method = c.req.query(\"code_challenge_method\") ?? \"\";\n\n const integrationsConfigured = vs.integrations.all().length > 0;\n let integrationName = \"\";\n if (integrationsConfigured) {\n const integration = vs.integrations.findOneBy(\"client_id\", client_id);\n if (!integration) {\n return c.html(\n renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),\n 400,\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, integration.redirect_uris)) {\n console.warn(\n `[OAuth] redirect_uri mismatch: got \"${redirect_uri}\", registered: ${JSON.stringify(integration.redirect_uris)}`,\n );\n return c.html(\n renderErrorPage(\n \"Redirect URI mismatch\",\n \"The redirect_uri is not registered for this application.\",\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n integrationName = integration.name;\n }\n\n const subtitleText = integrationName\n ? `Authorize <strong>${escapeHtml(integrationName)}</strong> to access your account.`\n : \"Choose a seeded user to continue.\";\n\n const users = vs.users.all();\n const userButtons = users\n .map((user) => {\n const u = formatUser(user);\n return renderUserButton({\n letter: (u.username[0] ?? \"?\").toUpperCase(),\n login: u.username,\n name: u.name ?? undefined,\n email: u.email,\n formAction: `${baseUrl}/oauth/authorize/callback`,\n hiddenFields: {\n username: u.username,\n redirect_uri,\n scope,\n state,\n client_id,\n code_challenge,\n code_challenge_method,\n },\n });\n })\n .join(\"\\n\");\n\n const body = users.length === 0 ? '<p class=\"empty\">No users in the emulator store.</p>' : userButtons;\n\n return c.html(renderCardPage(\"Sign in to Vercel\", subtitleText, body, SERVICE_LABEL));\n });\n\n // ---------- OAuth callback ----------\n\n app.post(\"/oauth/authorize/callback\", async (c) => {\n const body = await c.req.parseBody();\n const username = bodyStr(body.username);\n const redirect_uri = bodyStr(body.redirect_uri);\n const scope = bodyStr(body.scope);\n const state = bodyStr(body.state);\n const client_id = bodyStr(body.client_id);\n\n const code = randomBytes(20).toString(\"hex\");\n const code_challenge = bodyStr(body.code_challenge);\n const code_challenge_method = bodyStr(body.code_challenge_method);\n\n const pendingCodes = getPendingCodes(store);\n pendingCodes.set(code, {\n username,\n scope,\n redirectUri: redirect_uri,\n clientId: client_id,\n codeChallenge: code_challenge || null,\n codeChallengeMethod: code_challenge_method || null,\n created_at: Date.now(),\n });\n\n debug(\n \"vercel.oauth\",\n `[Vercel callback] generated code: ${code.slice(0, 8)}... for username=${username}, challenge=${code_challenge ? \"present\" : \"none\"}, pendingCodes size: ${pendingCodes.size}`,\n );\n\n const url = new URL(redirect_uri);\n url.searchParams.set(\"code\", code);\n if (state !== \"\") url.searchParams.set(\"state\", state);\n\n debug(\"vercel.oauth\", `[Vercel callback] redirecting to: ${url.toString().slice(0, 120)}...`);\n return c.redirect(url.toString(), 302);\n });\n\n // ---------- Token exchange ----------\n\n app.post(\"/login/oauth/token\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const pendingCodes = getPendingCodes(store);\n debug(\"vercel.oauth\", `[Vercel token] Content-Type: ${contentType}`);\n debug(\"vercel.oauth\", `[Vercel token] pendingCodes size: ${pendingCodes.size}`);\n debug(\n \"vercel.oauth\",\n `[Vercel token] pendingCodes keys: ${[...pendingCodes.keys()].map((k) => k.slice(0, 8) + \"...\").join(\", \")}`,\n );\n\n const rawText = await c.req.text();\n debug(\"vercel.oauth\", `[Vercel token] raw body: ${rawText.slice(0, 500)}`);\n\n let body: Record<string, unknown>;\n if (contentType.includes(\"application/json\")) {\n try {\n body = JSON.parse(rawText);\n } catch {\n body = {};\n }\n } else {\n body = Object.fromEntries(new URLSearchParams(rawText));\n }\n\n debug(\"vercel.oauth\", `[Vercel token] parsed keys: ${Object.keys(body).join(\", \")}`);\n\n const code = typeof body.code === \"string\" ? body.code : \"\";\n const redirect_uri = typeof body.redirect_uri === \"string\" ? body.redirect_uri : \"\";\n const code_verifier = typeof body.code_verifier === \"string\" ? body.code_verifier : undefined;\n const bodyClientId = typeof body.client_id === \"string\" ? body.client_id : \"\";\n const bodyClientSecret = typeof body.client_secret === \"string\" ? body.client_secret : \"\";\n\n debug(\"vercel.oauth\", `[Vercel token] code: ${code.slice(0, 8)}... (len=${code.length})`);\n debug(\"vercel.oauth\", `[Vercel token] client_id: ${bodyClientId}`);\n debug(\"vercel.oauth\", `[Vercel token] client_secret: ${bodyClientSecret.slice(0, 4)}****`);\n debug(\n \"vercel.oauth\",\n `[Vercel token] code_verifier: ${code_verifier ? code_verifier.slice(0, 8) + \"...\" : \"undefined\"}`,\n );\n\n const integrationsConfigured = vs.integrations.all().length > 0;\n if (integrationsConfigured) {\n const integration = vs.integrations.findOneBy(\"client_id\", bodyClientId);\n if (!integration) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: client_id not found`);\n return c.json(\n { error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" },\n 401,\n );\n }\n if (!constantTimeSecretEqual(bodyClientSecret, integration.client_secret)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: client_secret mismatch`);\n return c.json(\n { error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" },\n 401,\n );\n }\n debug(\"vercel.oauth\", `[Vercel token] client credentials OK (${integration.name})`);\n }\n\n const pending = pendingCodes.get(code);\n if (!pending) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: code not found in pendingCodes`);\n return c.json({ error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" }, 400);\n }\n if (isPendingCodeExpired(pending)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: code expired`);\n pendingCodes.delete(code);\n return c.json({ error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" }, 400);\n }\n debug(\"vercel.oauth\", `[Vercel token] code valid, username=${pending.username}, scope=${pending.scope}`);\n\n if (redirect_uri && pending.redirectUri && redirect_uri !== pending.redirectUri) {\n debug(\n \"vercel.oauth\",\n `[Vercel token] REJECTED: redirect_uri mismatch (got \"${redirect_uri}\", expected \"${pending.redirectUri}\")`,\n );\n pendingCodes.delete(code);\n return c.json(\n {\n error: \"invalid_grant\",\n error_description: \"The redirect_uri does not match the one used during authorization.\",\n },\n 400,\n );\n }\n\n if (pending.codeChallenge != null) {\n if (code_verifier === undefined) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n const method = (pending.codeChallengeMethod ?? \"plain\").toLowerCase();\n if (method === \"s256\") {\n const expected = createHash(\"sha256\").update(code_verifier).digest(\"base64url\");\n if (expected !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n } else if (method === \"plain\") {\n if (code_verifier !== pending.codeChallenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n } else {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n }\n\n debug(\"vercel.oauth\", `[Vercel token] PKCE OK (challenge=${pending.codeChallenge ? \"present\" : \"none\"})`);\n pendingCodes.delete(code);\n\n const user = vs.users.findOneBy(\"username\", pending.username as VercelUser[\"username\"]);\n if (!user) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: user \"${pending.username}\" not found`);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The user associated with this code was not found.\" },\n 400,\n );\n }\n\n const token = \"vercel_\" + randomBytes(20).toString(\"base64url\");\n const scopes = pending.scope ? pending.scope.split(/[,\\s]+/).filter(Boolean) : [];\n\n if (tokenMap) {\n tokenMap.set(token, { login: user.username, id: user.id, scopes });\n }\n\n debug(\n \"vercel.oauth\",\n `[Vercel token] SUCCESS: issued token for ${user.username} (scopes: ${scopes.join(\",\") || \"none\"})`,\n );\n\n return c.json({\n access_token: token,\n token_type: \"Bearer\",\n scope: pending.scope || \"\",\n });\n });\n\n // ---------- User info ----------\n\n app.get(\"/login/oauth/userinfo\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n return c.json({ error: { code: \"unauthorized\", message: \"Authentication required\" } }, 401);\n }\n\n const user = vs.users.findOneBy(\"username\", authUser.login as VercelUser[\"username\"]);\n if (!user) {\n return c.json({ error: { code: \"unauthorized\", message: \"Authentication required\" } }, 401);\n }\n\n return c.json({\n sub: user.uid,\n email: user.email,\n name: user.name,\n preferred_username: user.username,\n email_verified: true,\n picture: user.avatar,\n });\n });\n}\n","import { randomBytes } from \"crypto\";\nimport type { Context } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { parseJsonBody } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"@emulators/core\";\nimport { getVercelStore } from \"../store.js\";\nimport { generateUid } from \"../helpers.js\";\nimport type { VercelUser } from \"../entities.js\";\n\nfunction vercelErr(c: Context, status: ContentfulStatusCode, code: string, message: string) {\n return c.json({ error: { code, message } }, status);\n}\n\nexport function apiKeysRoutes({ app, store, tokenMap }: RouteContext): void {\n const vs = getVercelStore(store);\n\n app.post(\"/v1/api-keys\", async (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const teamId = c.req.query(\"teamId\") ?? null;\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name : \"API Key\";\n\n const tokenString = `vercel_api_${randomBytes(24).toString(\"base64url\")}`;\n const uid = generateUid(\"ak\");\n\n vs.apiKeys.insert({\n uid,\n name,\n teamId,\n userId: user.uid,\n tokenString,\n });\n\n if (tokenMap) {\n tokenMap.set(tokenString, { login: user.username, id: user.id, scopes: [] });\n }\n\n return c.json({\n apiKeyString: tokenString,\n apiKey: {\n id: uid,\n name,\n teamId,\n createdAt: Date.now(),\n },\n });\n });\n\n app.get(\"/v1/api-keys\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const teamId = c.req.query(\"teamId\") ?? null;\n const keys = vs.apiKeys.all().filter((k) => {\n if (k.userId !== user.uid) return false;\n if (teamId && k.teamId !== teamId) return false;\n return true;\n });\n\n return c.json({\n keys: keys.map((k) => ({\n id: k.uid,\n name: k.name,\n teamId: k.teamId,\n createdAt: k.created_at,\n })),\n });\n });\n\n app.delete(\"/v1/api-keys/:keyId\", (c) => {\n const auth = c.get(\"authUser\");\n if (!auth) {\n return vercelErr(c, 401, \"not_authenticated\", \"Authentication required\");\n }\n const user = vs.users.findOneBy(\"username\", auth.login as VercelUser[\"username\"]);\n if (!user) {\n return vercelErr(c, 403, \"forbidden\", \"User not found\");\n }\n\n const keyId = c.req.param(\"keyId\");\n const key = vs.apiKeys.findOneBy(\"uid\", keyId);\n if (!key) {\n return vercelErr(c, 404, \"not_found\", \"API key not found\");\n }\n\n if (key.userId !== user.uid) {\n return vercelErr(c, 403, \"forbidden\", \"Not authorized to delete this API key\");\n }\n\n if (tokenMap) {\n tokenMap.delete(key.tokenString);\n }\n\n vs.apiKeys.delete(key.id);\n return c.json({});\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\n\n// OpenAPI 3.1 document for this Vercel emulator instance, pointed at itself, with\n// an OAuth2 authorization-code security scheme bound to the emulator's own\n// authorize and token endpoints for OpenAPI-aware clients and test tools.\nexport function openapiRoutes({ app, baseUrl }: RouteContext): void {\n app.get(\"/openapi.json\", (c) => c.json(buildSpec(baseUrl)));\n}\n\nconst ok = (description: string) => ({\n description,\n content: { \"application/json\": { schema: { type: \"object\" } } },\n});\nconst idOrName = { name: \"idOrName\", in: \"path\", required: true, schema: { type: \"string\" } };\n\nfunction buildSpec(baseUrl: string): Record<string, unknown> {\n return {\n openapi: \"3.1.0\",\n info: {\n title: \"Vercel API (Emulated)\",\n version: \"1.0.0\",\n description:\n \"Emulated subset of the Vercel REST API. OAuth 2.0 Authorization Code (user-scoped). Authorize via the consent page, exchange the code at the token endpoint.\",\n },\n servers: [{ url: baseUrl }],\n components: {\n securitySchemes: {\n vercelOAuth: {\n type: \"oauth2\",\n description: \"Authorization Code — user-scoped bearer token.\",\n flows: {\n authorizationCode: {\n authorizationUrl: `${baseUrl}/oauth/authorize`,\n tokenUrl: `${baseUrl}/login/oauth/token`,\n scopes: {\n \"user:read\": \"Read the authenticated user\",\n \"projects:read\": \"Read projects and domains\",\n \"projects:write\": \"Create projects and domains\",\n },\n },\n },\n },\n },\n },\n security: [{ vercelOAuth: [\"user:read\", \"projects:read\", \"projects:write\"] }],\n paths: {\n \"/v2/user\": {\n get: {\n operationId: \"getCurrentUser\",\n summary: \"Get the authenticated user\",\n responses: { \"200\": ok(\"User object.\") },\n },\n },\n \"/v10/projects\": {\n get: {\n operationId: \"listProjects\",\n summary: \"List projects\",\n parameters: [{ name: \"limit\", in: \"query\", required: false, schema: { type: \"integer\" } }],\n responses: { \"200\": ok(\"Project list.\") },\n },\n },\n \"/v11/projects\": {\n post: {\n operationId: \"createProject\",\n summary: \"Create a project\",\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { type: \"object\", required: [\"name\"], properties: { name: { type: \"string\" } } },\n },\n },\n },\n responses: { \"200\": ok(\"Created project.\") },\n },\n },\n \"/v9/projects/{idOrName}\": {\n get: {\n operationId: \"getProject\",\n summary: \"Get a project\",\n parameters: [idOrName],\n responses: { \"200\": ok(\"Project object.\") },\n },\n },\n \"/v9/projects/{idOrName}/domains\": {\n get: {\n operationId: \"listDomains\",\n summary: \"List a project's domains\",\n parameters: [idOrName],\n responses: { \"200\": ok(\"Domain list.\") },\n },\n },\n \"/v10/projects/{idOrName}/domains\": {\n post: {\n operationId: \"addDomain\",\n summary: \"Add a domain to a project\",\n parameters: [idOrName],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { type: \"object\", required: [\"name\"], properties: { name: { type: \"string\" } } },\n },\n },\n },\n responses: { \"200\": ok(\"Added domain.\") },\n },\n },\n \"/v6/deployments\": {\n get: {\n operationId: \"listDeployments\",\n summary: \"List deployments\",\n parameters: [{ name: \"limit\", in: \"query\", required: false, schema: { type: \"integer\" } }],\n responses: { \"200\": ok(\"Deployment list.\") },\n },\n },\n },\n };\n}\n","import type { ServiceManifest } from \"@emulators/core\";\n\n/**\n * Vercel's machine-readable service manifest. This is the single source of truth\n * for Vercel's surfaces, auth, specs, seed shape, and copyable connection\n * snippets, consumed by the CLI registry, the Cloudflare host, and the console.\n */\nexport const manifest: ServiceManifest = {\n id: \"vercel\",\n name: \"Vercel\",\n description:\n \"Stateful Vercel API emulator for projects, deployments, domains, teams, users, env vars, and integration OAuth flows.\",\n docsUrl: \"https://docs.emulators.dev/vercel\",\n surfaces: [\n { id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\", basePath: \"/\" },\n { id: \"oauth\", kind: \"oauth\", title: \"Integration OAuth\", status: \"supported\", basePath: \"/oauth\" },\n ],\n auth: [\n { id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" },\n { id: \"oauth-code\", title: \"OAuth authorization code\", type: \"oauth-authorization-code\", status: \"supported\" },\n ],\n specs: [\n {\n kind: \"openapi\",\n title: \"Vercel REST API subset\",\n coverage: \"hand-authored\",\n url: \"/openapi.json\",\n operations: [\n { operationId: \"getCurrentUser\", method: \"GET\", path: \"/v2/user\", status: \"hand-authored\" },\n { operationId: \"updateCurrentUser\", method: \"PATCH\", path: \"/v2/user\", status: \"hand-authored\" },\n { operationId: \"listTeams\", method: \"GET\", path: \"/v2/teams\", status: \"hand-authored\" },\n { operationId: \"getTeam\", method: \"GET\", path: \"/v2/teams/:teamId\", status: \"hand-authored\" },\n { operationId: \"createTeam\", method: \"POST\", path: \"/v2/teams\", status: \"hand-authored\" },\n { operationId: \"patchTeam\", method: \"PATCH\", path: \"/v2/teams/:teamId\", status: \"hand-authored\" },\n { operationId: \"listTeamMembers\", method: \"GET\", path: \"/v2/teams/:teamId/members\", status: \"hand-authored\" },\n { operationId: \"inviteTeamMember\", method: \"POST\", path: \"/v2/teams/:teamId/members\", status: \"hand-authored\" },\n { operationId: \"listProjects\", method: \"GET\", path: \"/v10/projects\", status: \"hand-authored\" },\n { operationId: \"createProject\", method: \"POST\", path: \"/v11/projects\", status: \"hand-authored\" },\n { operationId: \"getProject\", method: \"GET\", path: \"/v9/projects/:idOrName\", status: \"hand-authored\" },\n { operationId: \"updateProject\", method: \"PATCH\", path: \"/v9/projects/:idOrName\", status: \"hand-authored\" },\n { operationId: \"deleteProject\", method: \"DELETE\", path: \"/v9/projects/:idOrName\", status: \"hand-authored\" },\n {\n operationId: \"updateProtectionBypass\",\n method: \"PATCH\",\n path: \"/v1/projects/:idOrName/protection-bypass\",\n status: \"hand-authored\",\n },\n { operationId: \"createDeployment\", method: \"POST\", path: \"/v13/deployments\", status: \"hand-authored\" },\n { operationId: \"listDeployments\", method: \"GET\", path: \"/v6/deployments\", status: \"hand-authored\" },\n { operationId: \"getDeployment\", method: \"GET\", path: \"/v13/deployments/:idOrUrl\", status: \"hand-authored\" },\n { operationId: \"deleteDeployment\", method: \"DELETE\", path: \"/v13/deployments/:id\", status: \"hand-authored\" },\n {\n operationId: \"cancelDeployment\",\n method: \"PATCH\",\n path: \"/v12/deployments/:id/cancel\",\n status: \"hand-authored\",\n },\n {\n operationId: \"getDeploymentEvents\",\n method: \"GET\",\n path: \"/v3/deployments/:idOrUrl/events\",\n status: \"hand-authored\",\n },\n { operationId: \"uploadFile\", method: \"POST\", path: \"/v2/files\", status: \"hand-authored\" },\n {\n operationId: \"listProjectDomains\",\n method: \"GET\",\n path: \"/v9/projects/:idOrName/domains\",\n status: \"hand-authored\",\n },\n {\n operationId: \"addProjectDomain\",\n method: \"POST\",\n path: \"/v10/projects/:idOrName/domains\",\n status: \"hand-authored\",\n },\n {\n operationId: \"verifyProjectDomain\",\n method: \"POST\",\n path: \"/v9/projects/:idOrName/domains/:domain/verify\",\n status: \"hand-authored\",\n },\n {\n operationId: \"deleteProjectDomain\",\n method: \"DELETE\",\n path: \"/v9/projects/:idOrName/domains/:domain\",\n status: \"hand-authored\",\n },\n { operationId: \"listProjectEnv\", method: \"GET\", path: \"/v10/projects/:idOrName/env\", status: \"hand-authored\" },\n {\n operationId: \"createProjectEnv\",\n method: \"POST\",\n path: \"/v10/projects/:idOrName/env\",\n status: \"hand-authored\",\n },\n {\n operationId: \"editProjectEnv\",\n method: \"PATCH\",\n path: \"/v9/projects/:idOrName/env/:id\",\n status: \"hand-authored\",\n },\n {\n operationId: \"deleteProjectEnv\",\n method: \"DELETE\",\n path: \"/v9/projects/:idOrName/env/:id\",\n status: \"hand-authored\",\n },\n { operationId: \"createAuthToken\", method: \"POST\", path: \"/v1/api-keys\", status: \"hand-authored\" },\n { operationId: \"listAuthTokens\", method: \"GET\", path: \"/v1/api-keys\", status: \"hand-authored\" },\n { operationId: \"deleteAuthToken\", method: \"DELETE\", path: \"/v1/api-keys/:keyId\", status: \"hand-authored\" },\n ],\n },\n { kind: \"oauth-metadata\", title: \"Integration OAuth authorize and token flow\", coverage: \"hand-authored\" },\n ],\n seedSchema: {\n description: \"Seed users, teams, projects (with env vars), and integration OAuth apps.\",\n fields: [\n {\n key: \"users\",\n title: \"Users\",\n description: \"Accounts addressable by username.\",\n example: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n },\n {\n key: \"teams\",\n title: \"Teams\",\n description: \"Teams addressable by slug.\",\n example: [{ slug: \"my-team\", name: \"My Team\" }],\n },\n {\n key: \"projects\",\n title: \"Projects\",\n description: \"Projects owned by a user or team, optionally with env vars.\",\n example: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n },\n {\n key: \"integrations\",\n title: \"Integration OAuth apps\",\n description: \"OAuth clients for the integration authorization-code flow.\",\n example: [\n {\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n },\n ],\n },\n ],\n example: {\n users: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n teams: [{ slug: \"my-team\", name: \"My Team\" }],\n projects: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n integrations: [\n {\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n },\n ],\n },\n },\n stateModel: {\n description: \"Entities mutated by Vercel provider calls.\",\n collections: [\n { name: \"users\" },\n { name: \"teams\" },\n { name: \"team_members\" },\n { name: \"projects\" },\n { name: \"deployments\" },\n { name: \"deployment_aliases\" },\n { name: \"builds\" },\n { name: \"deployment_events\" },\n { name: \"files\" },\n { name: \"deployment_files\" },\n { name: \"domains\" },\n { name: \"env_vars\" },\n { name: \"protection_bypasses\" },\n { name: \"api_keys\" },\n { name: \"integrations\" },\n ],\n },\n connections: [\n {\n id: \"vercel-sdk\",\n title: \"Vercel SDK (TypeScript)\",\n kind: \"sdk\",\n language: \"typescript\",\n description: \"Point the Vercel SDK at the emulator instance via serverURL.\",\n template:\n 'import { Vercel } from \"@vercel/sdk\";\\n\\nconst vercel = new Vercel({\\n serverURL: \"{{baseUrl}}\",\\n bearerToken: \"{{token}}\",\\n});\\n\\nconst { projects } = await vercel.projects.getProjects({});',\n },\n {\n id: \"vercel-fetch\",\n title: \"fetch (TypeScript)\",\n kind: \"sdk\",\n language: \"typescript\",\n description: \"Call the REST API directly with the emulator base URL.\",\n template:\n 'const res = await fetch(\"{{baseUrl}}/v2/user\", {\\n headers: { authorization: \"Bearer {{token}}\" },\\n});\\nconst { user } = await res.json();',\n },\n {\n id: \"vercel-env\",\n title: \"Vercel API base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point the Vercel CLI or your app at the emulator instead of api.vercel.com.\",\n template: \"VERCEL_API_URL={{baseUrl}}\\nVERCEL_TOKEN={{token}}\",\n },\n {\n id: \"curl\",\n title: \"curl\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Call the REST API directly.\",\n template: 'curl -s {{baseUrl}}/v2/user -H \"authorization: Bearer {{token}}\"',\n },\n ],\n};\n","import type { Hono } from \"@emulators/core\";\nimport type { AppEnv, RouteContext, ServicePlugin, Store, WebhookDispatcher, TokenMap } from \"@emulators/core\";\nimport type { VercelEnvVar } from \"./entities.js\";\nimport { getVercelStore } from \"./store.js\";\nimport { generateUid, nowMs } from \"./helpers.js\";\nimport { userRoutes } from \"./routes/user.js\";\nimport { projectsRoutes } from \"./routes/projects.js\";\nimport { deploymentsRoutes } from \"./routes/deployments.js\";\nimport { domainsRoutes } from \"./routes/domains.js\";\nimport { envRoutes } from \"./routes/env.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\nimport { apiKeysRoutes } from \"./routes/api-keys.js\";\nimport { openapiRoutes } from \"./routes/openapi.js\";\n\nexport { getVercelStore, type VercelStore } from \"./store.js\";\nexport * from \"./entities.js\";\nexport { manifest } from \"./manifest.js\";\n\nexport interface VercelSeedConfig {\n port?: number;\n users?: Array<{\n username: string;\n email?: string;\n name?: string;\n }>;\n teams?: Array<{\n slug: string;\n name?: string;\n description?: string;\n }>;\n projects?: Array<{\n name: string;\n team?: string;\n framework?: string;\n buildCommand?: string;\n outputDirectory?: string;\n rootDirectory?: string;\n nodeVersion?: string;\n envVars?: Array<{\n key: string;\n value: string;\n type?: string;\n target?: string[];\n }>;\n }>;\n integrations?: Array<{\n client_id: string;\n client_secret: string;\n name: string;\n redirect_uris: string[];\n }>;\n}\n\nfunction seedDefaults(store: Store, _baseUrl: string): void {\n const vs = getVercelStore(store);\n\n vs.users.insert({\n uid: generateUid(\"user\"),\n email: \"admin@localhost\",\n username: \"admin\",\n name: \"Admin\",\n avatar: null,\n defaultTeamId: null,\n softBlock: null,\n billing: { plan: \"hobby\", period: null, trial: null, cancelation: null, addons: null },\n resourceConfig: { nodeType: \"Edge Functions\", concurrentBuilds: 1 },\n stagingPrefix: \"staging\",\n version: null,\n });\n}\n\nexport function seedFromConfig(store: Store, baseUrl: string, config: VercelSeedConfig): void {\n const vs = getVercelStore(store);\n\n if (config.users) {\n for (const u of config.users) {\n const existing = vs.users.findOneBy(\"username\", u.username);\n if (existing) continue;\n vs.users.insert({\n uid: generateUid(\"user\"),\n email: u.email ?? `${u.username}@localhost`,\n username: u.username,\n name: u.name ?? null,\n avatar: null,\n defaultTeamId: null,\n softBlock: null,\n billing: { plan: \"hobby\", period: null, trial: null, cancelation: null, addons: null },\n resourceConfig: { nodeType: \"Edge Functions\", concurrentBuilds: 1 },\n stagingPrefix: \"staging\",\n version: null,\n });\n }\n }\n\n if (config.teams) {\n for (const t of config.teams) {\n const existing = vs.teams.findOneBy(\"slug\", t.slug);\n if (existing) continue;\n\n const firstUser = vs.users.all()[0];\n const creatorId = firstUser?.uid ?? \"unknown\";\n\n const team = vs.teams.insert({\n uid: generateUid(\"team\"),\n slug: t.slug,\n name: t.name ?? t.slug,\n avatar: null,\n description: t.description ?? null,\n creatorId,\n membership: { confirmed: true, role: \"OWNER\" },\n billing: { plan: \"pro\", period: null, trial: null, cancelation: null, addons: null },\n resourceConfig: { nodeType: \"Edge Functions\", concurrentBuilds: 1 },\n stagingPrefix: \"staging\",\n });\n\n for (const u of vs.users.all()) {\n const role = u.uid === creatorId ? \"OWNER\" : \"MEMBER\";\n vs.teamMembers.insert({\n teamId: team.uid,\n userId: u.uid,\n role,\n confirmed: true,\n joinedFrom: \"seed\",\n });\n }\n }\n }\n\n if (config.projects) {\n for (const p of config.projects) {\n let accountId: string;\n if (p.team) {\n const team = vs.teams.findOneBy(\"slug\", p.team);\n if (!team) continue;\n accountId = team.uid;\n } else {\n const user = vs.users.all()[0];\n if (!user) continue;\n accountId = user.uid;\n }\n\n const existingByName = vs.projects.findBy(\"name\", p.name);\n if (existingByName.some((proj) => proj.accountId === accountId)) continue;\n\n const project = vs.projects.insert({\n uid: generateUid(\"prj\"),\n name: p.name,\n accountId,\n framework: p.framework ?? null,\n buildCommand: p.buildCommand ?? null,\n devCommand: null,\n installCommand: null,\n outputDirectory: p.outputDirectory ?? null,\n rootDirectory: p.rootDirectory ?? null,\n commandForIgnoringBuildStep: null,\n nodeVersion: p.nodeVersion ?? \"20.x\",\n serverlessFunctionRegion: null,\n publicSource: false,\n autoAssignCustomDomains: true,\n autoAssignCustomDomainsUpdatedBy: null,\n gitForkProtection: true,\n sourceFilesOutsideRootDirectory: false,\n live: true,\n link: null,\n latestDeployments: [],\n targets: {},\n protectionBypass: {},\n passwordProtection: null,\n ssoProtection: null,\n trustedIps: null,\n connectConfigurationId: null,\n gitComments: { onPullRequest: true, onCommit: false },\n webAnalytics: null,\n speedInsights: null,\n oidcTokenConfig: null,\n tier: \"hobby\",\n });\n\n if (p.envVars) {\n for (const ev of p.envVars) {\n vs.envVars.insert({\n uid: generateUid(\"env\"),\n projectId: project.uid,\n key: ev.key,\n value: ev.value,\n type: (ev.type ?? \"encrypted\") as VercelEnvVar[\"type\"],\n target: (ev.target ?? [\"production\", \"preview\", \"development\"]) as VercelEnvVar[\"target\"],\n gitBranch: null,\n customEnvironmentIds: [],\n comment: null,\n decrypted: false,\n });\n }\n }\n }\n }\n\n if (config.integrations) {\n for (const integ of config.integrations) {\n const existing = vs.integrations.findOneBy(\"client_id\", integ.client_id);\n if (existing) continue;\n vs.integrations.insert({\n client_id: integ.client_id,\n client_secret: integ.client_secret,\n name: integ.name,\n redirect_uris: integ.redirect_uris,\n });\n }\n }\n}\n\nexport const vercelPlugin: ServicePlugin = {\n name: \"vercel\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n oauthRoutes(ctx);\n userRoutes(ctx);\n projectsRoutes(ctx);\n deploymentsRoutes(ctx);\n domainsRoutes(ctx);\n envRoutes(ctx);\n apiKeysRoutes(ctx);\n openapiRoutes(ctx);\n },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default vercelPlugin;\n"],"mappings":";ACAA,SAAS,mBAAmB;AeA5B,SAAS,uBAAuB;AOAhC,SAAS,YAAY,eAAAA,oBAAmB;ACAxC,SAAS,eAAAA,oBAAmB;AxBqCrB,SAAS,eAAe,OAA2B;AACxD,SAAO;IACL,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,UAAU,CAAC;IACvE,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,MAAM,CAAC;IACnE,aAAa,MAAM,WAA6B,uBAAuB,CAAC,UAAU,QAAQ,CAAC;IAC3F,UAAU,MAAM,WAA0B,mBAAmB,CAAC,OAAO,QAAQ,WAAW,CAAC;IACzF,aAAa,MAAM,WAA6B,sBAAsB,CAAC,OAAO,aAAa,KAAK,CAAC;IACjG,mBAAmB,MAAM,WAAkC,6BAA6B;MACtF;MACA;IACF,CAAC;IACD,QAAQ,MAAM,WAAwB,iBAAiB,CAAC,cAAc,CAAC;IACvE,kBAAkB,MAAM,WAAkC,4BAA4B,CAAC,cAAc,CAAC;IACtG,OAAO,MAAM,WAAuB,gBAAgB,CAAC,QAAQ,CAAC;IAC9D,iBAAiB,MAAM,WAAiC,2BAA2B,CAAC,cAAc,CAAC;IACnG,SAAS,MAAM,WAAyB,kBAAkB,CAAC,aAAa,MAAM,CAAC;IAC/E,SAAS,MAAM,WAAyB,mBAAmB,CAAC,aAAa,KAAK,CAAC;IAC/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