@emulators/vercel 0.3.0 → 0.4.1

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 ADDED
@@ -0,0 +1,90 @@
1
+ # @emulators/vercel
2
+
3
+ Fully stateful Vercel API emulation with Vercel-style JSON responses and cursor-based pagination.
4
+
5
+ Part of [emulate](https://github.com/vercel-labs/emulate) — local drop-in replacement services for CI and no-network sandboxes.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @emulators/vercel
11
+ ```
12
+
13
+ ## Endpoints
14
+
15
+ ### User & Teams
16
+ - `GET /v2/user` — authenticated user
17
+ - `PATCH /v2/user` — update user
18
+ - `GET /v2/teams` — list teams (cursor paginated)
19
+ - `GET /v2/teams/:teamId` — get team (by ID or slug)
20
+ - `POST /v2/teams` — create team
21
+ - `PATCH /v2/teams/:teamId` — update team
22
+ - `GET /v2/teams/:teamId/members` — list members
23
+ - `POST /v2/teams/:teamId/members` — add member
24
+
25
+ ### Projects
26
+ - `POST /v11/projects` — create project (with optional env vars and git integration)
27
+ - `GET /v10/projects` — list projects (search, cursor pagination)
28
+ - `GET /v9/projects/:idOrName` — get project (includes env vars)
29
+ - `PATCH /v9/projects/:idOrName` — update project
30
+ - `DELETE /v9/projects/:idOrName` — delete project (cascades)
31
+ - `GET /v1/projects/:projectId/promote/aliases` — promote aliases status
32
+ - `PATCH /v1/projects/:idOrName/protection-bypass` — manage bypass secrets
33
+
34
+ ### Deployments
35
+ - `POST /v13/deployments` — create deployment (auto-transitions to READY)
36
+ - `GET /v13/deployments/:idOrUrl` — get deployment (by ID or URL)
37
+ - `GET /v6/deployments` — list deployments (filter by project, target, state)
38
+ - `DELETE /v13/deployments/:id` — delete deployment (cascades)
39
+ - `PATCH /v12/deployments/:id/cancel` — cancel building deployment
40
+ - `GET /v2/deployments/:id/aliases` — list deployment aliases
41
+ - `GET /v3/deployments/:idOrUrl/events` — get build events/logs
42
+ - `GET /v6/deployments/:id/files` — list deployment files
43
+ - `POST /v2/files` — upload file (by SHA digest)
44
+
45
+ ### Domains
46
+ - `POST /v10/projects/:idOrName/domains` — add domain (with verification challenge)
47
+ - `GET /v9/projects/:idOrName/domains` — list domains
48
+ - `GET /v9/projects/:idOrName/domains/:domain` — get domain
49
+ - `PATCH /v9/projects/:idOrName/domains/:domain` — update domain
50
+ - `DELETE /v9/projects/:idOrName/domains/:domain` — remove domain
51
+ - `POST /v9/projects/:idOrName/domains/:domain/verify` — verify domain
52
+
53
+ ### Environment Variables
54
+ - `GET /v10/projects/:idOrName/env` — list env vars (with decrypt option)
55
+ - `POST /v10/projects/:idOrName/env` — create env vars (single, batch, upsert)
56
+ - `GET /v10/projects/:idOrName/env/:id` — get env var
57
+ - `PATCH /v9/projects/:idOrName/env/:id` — update env var
58
+ - `DELETE /v9/projects/:idOrName/env/:id` — delete env var
59
+
60
+ ## Auth
61
+
62
+ All endpoints accept `teamId` or `slug` query params for team scoping. Pagination uses cursor-based `limit`/`since`/`until` with `pagination` response objects.
63
+
64
+ ## Seed Configuration
65
+
66
+ ```yaml
67
+ vercel:
68
+ users:
69
+ - username: developer
70
+ name: Developer
71
+ email: dev@example.com
72
+ teams:
73
+ - slug: my-team
74
+ name: My Team
75
+ projects:
76
+ - name: my-app
77
+ team: my-team
78
+ framework: nextjs
79
+ integrations:
80
+ - client_id: "oac_abc123"
81
+ client_secret: "secret_abc123"
82
+ name: "My Vercel App"
83
+ redirect_uris:
84
+ - "http://localhost:3000/api/auth/callback/vercel"
85
+ ```
86
+
87
+ ## Links
88
+
89
+ - [Full documentation](https://emulate.dev/vercel)
90
+ - [GitHub](https://github.com/vercel-labs/emulate)
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/store.ts","../src/helpers.ts","../../core/src/store.ts","../../core/src/server.ts","../../core/src/webhooks.ts","../../core/src/middleware/error-handler.ts","../../core/src/middleware/auth.ts","../../core/src/debug.ts","../../core/src/fonts.ts","../../core/src/middleware/pagination.ts","../../core/src/ui.ts","../../core/src/oauth-helpers.ts","../src/routes/user.ts","../src/routes/projects.ts","../src/routes/deployments.ts","../src/routes/domains.ts","../src/routes/env.ts","../src/routes/oauth.ts","../src/routes/api-keys.ts","../src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type {\n VercelUser, VercelTeam, VercelTeamMember, VercelProject, VercelDeployment,\n VercelDeploymentAlias, VercelBuild, VercelDeploymentEvent, VercelFile,\n VercelDeploymentFile, VercelDomain, VercelEnvVar, VercelProtectionBypass, VercelIntegration, 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\", [\"deploymentId\", \"projectId\"]),\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 \"hono\";\nimport type { VercelUser, VercelTeam, VercelProject, VercelDeployment, VercelDomain, VercelEnvVar, VercelDeploymentAlias, VercelBuild } 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 let 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 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).map((id) => this.items.get(id)!).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\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","import { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport { authMiddleware, type AuthFallback, type TokenMap, type AppKeyResolver, type AppEnv } from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.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}\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\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://emulate.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 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, port, baseUrl, tokenMap };\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(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): 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 (\n event === \"ping\" ||\n s.events.includes(\"*\") ||\n s.events.includes(event)\n );\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, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\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 \"hono\";\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 type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\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(\n Buffer.from(payloadB64, \"base64url\").toString()\n );\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 = typeof process !== \"undefined\" && (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 \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[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","import type { Context } from \"hono\";\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(\n c: Context,\n totalCount: number,\n page: number,\n perPage: number\n): 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","export function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\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.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\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<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(\n title: string,\n subtitle: string,\n body: string,\n service?: string\n): 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(\n title: string,\n sidebarHtml: string,\n bodyHtml: string,\n service?: string\n): 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 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\n ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>`\n : \"\";\n const emailLine = opts.email\n ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>`\n : \"\";\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 { 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 type { Context } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n row: VercelProtectionBypass\n): { 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.findBy(\"name\", name as VercelProject[\"name\"]).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((t) => t === \"production\" || t === \"preview\" || t === \"development\") 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 = body.buildCommand === null ? null : typeof body.buildCommand === \"string\" ? body.buildCommand : project.buildCommand;\n }\n if (\"devCommand\" in body) {\n patch.devCommand = 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 ? null : typeof body.installCommand === \"string\" ? body.installCommand : project.installCommand;\n }\n if (\"outputDirectory\" in body) {\n patch.outputDirectory =\n body.outputDirectory === null ? null : typeof body.outputDirectory === \"string\" ? body.outputDirectory : project.outputDirectory;\n }\n if (\"framework\" in body) {\n patch.framework = 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 ? null : typeof body.rootDirectory === \"string\" ? body.rootDirectory : 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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n vs: VercelStore,\n dep: VercelDeployment,\n accountId: string\n): boolean {\n const project = vs.projects.findOneBy(\"uid\", dep.projectId as VercelProject[\"uid\"]);\n return !!project && project.accountId === accountId;\n}\n\nfunction defaultProjectPayload(name: string, accountId: string): 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\n .findBy(\"name\", name as VercelProject[\"name\"])\n .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:\n 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\"\n ? targetRaw\n : \"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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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.toLowerCase().split(\".\").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(\n vs: VercelStore,\n projectUid: string,\n domainName: string\n): 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 =\n 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 ? null : typeof body.redirect === \"string\" ? body.redirect.trim() || null : 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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n a: VercelEnvVar[\"target\"],\n b: VercelEnvVar[\"target\"]\n): 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) =>\n e.key === key &&\n (excludeId === undefined || e.id !== excludeId) &&\n 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(\n body: Record<string, unknown>\n): { row: Omit<VercelEnvVar, \"id\" | \"uid\" | \"projectId\" | \"created_at\" | \"updated_at\">; error: string | null } {\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 { row: {} as never, error: \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\" };\n }\n\n const target = parseTarget(body.target);\n if (target === \"invalid\") {\n return { row: {} as never, error: \"Invalid value: target must be a non-empty array of production, preview, development\" };\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(\n vs: VercelStore,\n projectUid: string,\n uid: string\n): 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(\n (e) => e.key === row.key && targetsOverlap(e.target, row.target)\n );\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(c, 400, \"bad_request\", \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\");\n }\n patch.type = t;\n }\n if (\"target\" in body) {\n const t = parseTarget(body.target);\n if (t === \"invalid\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: target must be a non-empty array of production, preview, development\");\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 } 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, 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(renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL), 400);\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, integration.redirect_uris)) {\n console.warn(`[OAuth] redirect_uri mismatch: got \"${redirect_uri}\", registered: ${JSON.stringify(integration.redirect_uris)}`);\n return c.html(renderErrorPage(\"Redirect URI mismatch\", \"The redirect_uri is not registered for this application.\", SERVICE_LABEL), 400);\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: \"/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\n ? '<p class=\"empty\">No users in the emulator store.</p>'\n : 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(\"vercel.oauth\", `[Vercel callback] generated code: ${code.slice(0, 8)}... for username=${username}, challenge=${code_challenge ? \"present\" : \"none\"}, pendingCodes size: ${pendingCodes.size}`);\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(\"vercel.oauth\", `[Vercel token] pendingCodes keys: ${[...pendingCodes.keys()].map(k => k.slice(0, 8) + \"...\").join(\", \")}`);\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 { body = JSON.parse(rawText); } catch { body = {}; }\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(\"vercel.oauth\", `[Vercel token] code_verifier: ${code_verifier ? code_verifier.slice(0, 8) + \"...\" : \"undefined\"}`);\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({ error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" }, 401);\n }\n if (!constantTimeSecretEqual(bodyClientSecret, integration.client_secret)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: client_secret mismatch`);\n return c.json({ error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" }, 401);\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(\n { error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" },\n 400\n );\n }\n if (isPendingCodeExpired(pending)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: code expired`);\n pendingCodes.delete(code);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" },\n 400\n );\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(\"vercel.oauth\", `[Vercel token] REJECTED: redirect_uri mismatch (got \"${redirect_uri}\", expected \"${pending.redirectUri}\")`);\n pendingCodes.delete(code);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The redirect_uri does not match the one used during authorization.\" },\n 400\n );\n }\n\n if (pending.codeChallenge != null) {\n if (code_verifier === undefined) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\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(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\n }\n } else if (method === \"plain\") {\n if (code_verifier !== pending.codeChallenge) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\n }\n } else {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\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(\"vercel.oauth\", `[Vercel token] SUCCESS: issued token for ${user.username} (scopes: ${scopes.join(\",\") || \"none\"})`);\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 \"hono\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { parseJsonBody } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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 { Hono } from \"hono\";\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\";\n\nexport { getVercelStore, type VercelStore } from \"./store.js\";\nexport * from \"./entities.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 },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default vercelPlugin;\n"],"mappings":";AAyBO,SAAS,eAAe,OAA2B;AACxD,SAAO;AAAA,IACL,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,UAAU,CAAC;AAAA,IACvE,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,MAAM,CAAC;AAAA,IACnE,aAAa,MAAM,WAA6B,uBAAuB,CAAC,UAAU,QAAQ,CAAC;AAAA,IAC3F,UAAU,MAAM,WAA0B,mBAAmB,CAAC,OAAO,QAAQ,WAAW,CAAC;AAAA,IACzF,aAAa,MAAM,WAA6B,sBAAsB,CAAC,OAAO,aAAa,KAAK,CAAC;AAAA,IACjG,mBAAmB,MAAM,WAAkC,6BAA6B,CAAC,gBAAgB,WAAW,CAAC;AAAA,IACrH,QAAQ,MAAM,WAAwB,iBAAiB,CAAC,cAAc,CAAC;AAAA,IACvE,kBAAkB,MAAM,WAAkC,4BAA4B,CAAC,cAAc,CAAC;AAAA,IACtG,OAAO,MAAM,WAAuB,gBAAgB,CAAC,QAAQ,CAAC;AAAA,IAC9D,iBAAiB,MAAM,WAAiC,2BAA2B,CAAC,cAAc,CAAC;AAAA,IACnG,SAAS,MAAM,WAAyB,kBAAkB,CAAC,aAAa,MAAM,CAAC;AAAA,IAC/E,SAAS,MAAM,WAAyB,mBAAmB,CAAC,aAAa,KAAK,CAAC;AAAA,IAC/E,oBAAoB,MAAM,WAAmC,8BAA8B,CAAC,WAAW,CAAC;AAAA,IACxG,SAAS,MAAM,WAAyB,mBAAmB,CAAC,OAAO,UAAU,QAAQ,CAAC;AAAA,IACtF,cAAc,M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,aAAG,QAAQ,OAAO;AAAA,YAChB,KAAK,YAAY,KAAK;AAAA,YACtB,WAAW,QAAQ;AAAA,YACnB,KAAK,GAAG;AAAA,YACR,OAAO,GAAG;AAAA,YACV,MAAO,GAAG,QAAQ;AAAA,YAClB,QAAS,GAAG,UAAU,CAAC,cAAc,WAAW,aAAa;AAAA,YAC7D,WAAW;AAAA,YACX,sBAAsB,CAAC;AAAA,YACvB,SAAS;AAAA,YACT,WAAW;AAAA,UACb,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,cAAc;AACvB,eAAW,SAAS,OAAO,cAAc;AACvC,YAAM,WAAW,GAAG,aAAa,UAAU,aAAa,MAAM,SAAS;AACvE,UAAI,SAAU;AACd,SAAG,aAAa,OAAO;AAAA,QACrB,WAAW,MAAM;AAAA,QACjB,eAAe,MAAM;AAAA,QACrB,MAAM,MAAM;AAAA,QACZ,eAAe,MAAM;AAAA,MACvB,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEO,IAAM,eAA8B;AAAA,EACzC,MAAM;AAAA,EACN,SAAS,KAAmB,OAAc,UAA6B,SAAiB,UAA2B;AACjH,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,gBAAY,GAAG;AACf,eAAW,GAAG;AACd,mBAAe,GAAG;AAClB,sBAAkB,GAAG;AACrB,kBAAc,GAAG;AACjB,cAAU,GAAG;AACb,kBAAc,GAAG;AAAA,EACnB;AAAA,EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;AAAA,EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":["vercelErr","vercelErr","vercelErr","vercelErr","randomBytes","randomBytes","randomBytes","vercelErr","randomBytes"]}
1
+ {"version":3,"sources":["../src/store.ts","../src/helpers.ts","../../core/src/store.ts","../../core/src/server.ts","../../core/src/webhooks.ts","../../core/src/middleware/error-handler.ts","../../core/src/middleware/auth.ts","../../core/src/debug.ts","../../core/src/fonts.ts","../../core/src/middleware/pagination.ts","../../core/src/ui.ts","../../core/src/oauth-helpers.ts","../../core/src/persistence.ts","../src/routes/user.ts","../src/routes/projects.ts","../src/routes/deployments.ts","../src/routes/domains.ts","../src/routes/env.ts","../src/routes/oauth.ts","../src/routes/api-keys.ts","../src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type {\n VercelUser, VercelTeam, VercelTeamMember, VercelProject, VercelDeployment,\n VercelDeploymentAlias, VercelBuild, VercelDeploymentEvent, VercelFile,\n VercelDeploymentFile, VercelDomain, VercelEnvVar, VercelProtectionBypass, VercelIntegration, 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\", [\"deploymentId\", \"projectId\"]),\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 \"hono\";\nimport type { VercelUser, VercelTeam, VercelProject, VercelDeployment, VercelDomain, VercelEnvVar, VercelDeploymentAlias, VercelBuild } 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 let 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).map((id) => this.items.get(id)!).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 { Hono } from \"hono\";\nimport { cors } from \"hono/cors\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport { authMiddleware, type AuthFallback, type TokenMap, type AppKeyResolver, type AppEnv } from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.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}\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\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://emulate.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 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, port, baseUrl, tokenMap };\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(event: string, action: string | undefined, payload: unknown, owner: string, repo?: string): 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 (\n event === \"ping\" ||\n s.events.includes(\"*\") ||\n s.events.includes(event)\n );\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, ErrorHandler, MiddlewareHandler } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(...)`. Hono routes handler throws to the app error handler, not to outer middleware try/catch.\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 \"hono\";\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 };\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(\n Buffer.from(payloadB64, \"base64url\").toString()\n );\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 = typeof process !== \"undefined\" && (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 \"hono\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nconst FONTS: Record<string, Buffer> = {\n \"geist-sans.woff2\": readFileSync(join(__dirname, \"fonts\", \"geist-sans.woff2\")),\n \"GeistPixel-Square.woff2\": readFileSync(join(__dirname, \"fonts\", \"GeistPixel-Square.woff2\")),\n};\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n const buf = FONTS[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","import type { Context } from \"hono\";\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(\n c: Context,\n totalCount: number,\n page: number,\n perPage: number\n): 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","export function escapeHtml(s: string): string {\n return s\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n\nexport function escapeAttr(s: string): string {\n return escapeHtml(s).replace(/'/g, \"&#39;\");\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.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\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<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(\n title: string,\n subtitle: string,\n body: string,\n service?: string\n): 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(\n title: string,\n sidebarHtml: string,\n bodyHtml: string,\n service?: string\n): 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 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\n ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>`\n : \"\";\n const emailLine = opts.email\n ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>`\n : \"\";\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 { 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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n row: VercelProtectionBypass\n): { 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.findBy(\"name\", name as VercelProject[\"name\"]).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((t) => t === \"production\" || t === \"preview\" || t === \"development\") 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 = body.buildCommand === null ? null : typeof body.buildCommand === \"string\" ? body.buildCommand : project.buildCommand;\n }\n if (\"devCommand\" in body) {\n patch.devCommand = 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 ? null : typeof body.installCommand === \"string\" ? body.installCommand : project.installCommand;\n }\n if (\"outputDirectory\" in body) {\n patch.outputDirectory =\n body.outputDirectory === null ? null : typeof body.outputDirectory === \"string\" ? body.outputDirectory : project.outputDirectory;\n }\n if (\"framework\" in body) {\n patch.framework = 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 ? null : typeof body.rootDirectory === \"string\" ? body.rootDirectory : 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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n vs: VercelStore,\n dep: VercelDeployment,\n accountId: string\n): boolean {\n const project = vs.projects.findOneBy(\"uid\", dep.projectId as VercelProject[\"uid\"]);\n return !!project && project.accountId === accountId;\n}\n\nfunction defaultProjectPayload(name: string, accountId: string): 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\n .findBy(\"name\", name as VercelProject[\"name\"])\n .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:\n 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\"\n ? targetRaw\n : \"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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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.toLowerCase().split(\".\").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(\n vs: VercelStore,\n projectUid: string,\n domainName: string\n): 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 =\n 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 ? null : typeof body.redirect === \"string\" ? body.redirect.trim() || null : 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 \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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(\n a: VercelEnvVar[\"target\"],\n b: VercelEnvVar[\"target\"]\n): 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) =>\n e.key === key &&\n (excludeId === undefined || e.id !== excludeId) &&\n 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(\n body: Record<string, unknown>\n): { row: Omit<VercelEnvVar, \"id\" | \"uid\" | \"projectId\" | \"created_at\" | \"updated_at\">; error: string | null } {\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 { row: {} as never, error: \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\" };\n }\n\n const target = parseTarget(body.target);\n if (target === \"invalid\") {\n return { row: {} as never, error: \"Invalid value: target must be a non-empty array of production, preview, development\" };\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(\n vs: VercelStore,\n projectUid: string,\n uid: string\n): 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(\n (e) => e.key === row.key && targetsOverlap(e.target, row.target)\n );\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(c, 400, \"bad_request\", \"Invalid value: type must be one of system, encrypted, plain, secret, sensitive\");\n }\n patch.type = t;\n }\n if (\"target\" in body) {\n const t = parseTarget(body.target);\n if (t === \"invalid\") {\n return vercelErr(c, 400, \"bad_request\", \"Invalid value: target must be a non-empty array of production, preview, development\");\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 } 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, 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(renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL), 400);\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, integration.redirect_uris)) {\n console.warn(`[OAuth] redirect_uri mismatch: got \"${redirect_uri}\", registered: ${JSON.stringify(integration.redirect_uris)}`);\n return c.html(renderErrorPage(\"Redirect URI mismatch\", \"The redirect_uri is not registered for this application.\", SERVICE_LABEL), 400);\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: \"/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\n ? '<p class=\"empty\">No users in the emulator store.</p>'\n : 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(\"vercel.oauth\", `[Vercel callback] generated code: ${code.slice(0, 8)}... for username=${username}, challenge=${code_challenge ? \"present\" : \"none\"}, pendingCodes size: ${pendingCodes.size}`);\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(\"vercel.oauth\", `[Vercel token] pendingCodes keys: ${[...pendingCodes.keys()].map(k => k.slice(0, 8) + \"...\").join(\", \")}`);\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 { body = JSON.parse(rawText); } catch { body = {}; }\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(\"vercel.oauth\", `[Vercel token] code_verifier: ${code_verifier ? code_verifier.slice(0, 8) + \"...\" : \"undefined\"}`);\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({ error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" }, 401);\n }\n if (!constantTimeSecretEqual(bodyClientSecret, integration.client_secret)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: client_secret mismatch`);\n return c.json({ error: \"invalid_client\", error_description: \"The client_id and/or client_secret passed are incorrect.\" }, 401);\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(\n { error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" },\n 400\n );\n }\n if (isPendingCodeExpired(pending)) {\n debug(\"vercel.oauth\", `[Vercel token] REJECTED: code expired`);\n pendingCodes.delete(code);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The code passed is incorrect or expired.\" },\n 400\n );\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(\"vercel.oauth\", `[Vercel token] REJECTED: redirect_uri mismatch (got \"${redirect_uri}\", expected \"${pending.redirectUri}\")`);\n pendingCodes.delete(code);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The redirect_uri does not match the one used during authorization.\" },\n 400\n );\n }\n\n if (pending.codeChallenge != null) {\n if (code_verifier === undefined) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\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(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\n }\n } else if (method === \"plain\") {\n if (code_verifier !== pending.codeChallenge) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\n }\n } else {\n return c.json(\n { error: \"invalid_grant\", error_description: \"PKCE verification failed.\" },\n 400\n );\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(\"vercel.oauth\", `[Vercel token] SUCCESS: issued token for ${user.username} (scopes: ${scopes.join(\",\") || \"none\"})`);\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 \"hono\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { parseJsonBody } from \"@emulators/core\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\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 { Hono } from \"hono\";\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\";\n\nexport { getVercelStore, type VercelStore } from \"./store.js\";\nexport * from \"./entities.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 },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default vercelPlugin;\n"],"mappings":";AAyBO,SAAS,eAAe,OAA2B;AACxD,SAAO;AAAA,IACL,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,UAAU,CAAC;AAAA,IACvE,OAAO,MAAM,WAAuB,gBAAgB,CAAC,OAAO,MAAM,CAAC;AAAA,IACnE,aAAa,MAAM,WAA6B,uBAAuB,CAAC,UAAU,QAAQ,CAAC;AAAA,IAC3F,UAAU,MAAM,WAA0B,mBAAmB,CAAC,OAAO,QAAQ,WAAW,CAAC;AAAA,IACzF,aAAa,MAAM,WAA6B,sBAAsB,CAA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ACH;AAAA,EACF;AACF;AAEO,IAAM,eAA8B;AAAA,EACzC,MAAM;AAAA,EACN,SAAS,KAAmB,OAAc,UAA6B,SAAiB,UAA2B;AACjH,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,gBAAY,GAAG;AACf,eAAW,GAAG;AACd,mBAAe,GAAG;AAClB,sBAAkB,GAAG;AACrB,kBAAc,GAAG;AACjB,cAAU,GAAG;AACb,kBAAc,GAAG;AAAA,EACnB;AAAA,EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;AAAA,EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":["vercelErr","vercelErr","vercelErr","vercelErr","randomBytes","randomBytes","randomBytes","vercelErr","randomBytes"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emulators/vercel",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "license": "Apache-2.0",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -28,7 +28,7 @@
28
28
  ],
29
29
  "dependencies": {
30
30
  "hono": "^4",
31
- "@emulators/core": "0.3.0"
31
+ "@emulators/core": "0.4.1"
32
32
  },
33
33
  "devDependencies": {
34
34
  "tsup": "^8",