emulate 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/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/oauth-helpers.ts","../src/registry.ts","../src/commands/start.ts","../src/commands/init.ts","../src/commands/list.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { startCommand } from \"./commands/start.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { listCommand } from \"./commands/list.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nconst defaultPort = process.env.EMULATE_PORT ?? process.env.PORT ?? \"4000\";\n\nconst program = new Command();\n\nprogram\n .name(\"emulate\")\n .description(\"Local drop-in replacement services for CI and no-network sandboxes\")\n .version(pkg.version);\n\nprogram\n .command(\"start\", { isDefault: true })\n .description(\"Start the emulator server\")\n .option(\"-p, --port <port>\", \"Base port\", defaultPort)\n .option(\"-s, --service <services>\", \"Comma-separated services to enable\")\n .option(\"--seed <file>\", \"Path to seed config file\")\n .action(async (opts) => {\n const port = parseInt(opts.port, 10);\n if (Number.isNaN(port) || port < 1 || port > 65535) {\n console.error(`Invalid port: ${opts.port}`);\n process.exit(1);\n }\n await startCommand({\n port,\n service: opts.service,\n seed: opts.seed,\n });\n });\n\nprogram\n .command(\"init\")\n .description(\"Generate a starter config file\")\n .option(\"-s, --service <service>\", \"Service to generate config for\", \"all\")\n .action((opts) => {\n initCommand({ service: opts.service });\n });\n\nprogram\n .command(\"list\")\n .alias(\"list-services\")\n .description(\"List available services\")\n .action(() => {\n listCommand();\n });\n\nprogram.parse();\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 { ServicePlugin, Store, AppKeyResolver, AuthFallback } from \"@emulators/core\";\n\nexport interface LoadedService {\n plugin: ServicePlugin;\n seedFromConfig?(store: Store, baseUrl: string, config: unknown): void;\n createAppKeyResolver?(store: Store): AppKeyResolver;\n}\n\nexport interface ServiceEntry {\n label: string;\n endpoints: string;\n load(): Promise<LoadedService>;\n defaultFallback(svcSeedConfig?: Record<string, unknown>): AuthFallback;\n initConfig: Record<string, unknown>;\n}\n\nconst SERVICE_NAME_LIST = [\"vercel\", \"github\", \"google\", \"slack\", \"apple\", \"microsoft\", \"aws\"] as const;\nexport type ServiceName = (typeof SERVICE_NAME_LIST)[number];\nexport const SERVICE_NAMES: readonly ServiceName[] = SERVICE_NAME_LIST;\n\nexport const SERVICE_REGISTRY: Record<ServiceName, ServiceEntry> = {\n vercel: {\n label: \"Vercel REST API emulator\",\n endpoints: \"projects, deployments, domains, env vars, users, teams, file uploads, protection bypass\",\n async load() {\n const mod = await import(\"@emulators/vercel\");\n return { plugin: mod.vercelPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [] };\n },\n initConfig: {\n vercel: {\n users: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n teams: [{ slug: \"my-team\", name: \"My Team\" }],\n projects: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n integrations: [{\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n }],\n },\n },\n },\n\n github: {\n label: \"GitHub REST API emulator\",\n endpoints: \"users, repos, issues, PRs, comments, reviews, labels, milestones, branches, git data, orgs, teams, releases, webhooks, search, actions, checks, rate limit\",\n async load() {\n const mod = await import(\"@emulators/github\");\n return {\n plugin: mod.githubPlugin,\n seedFromConfig: mod.seedFromConfig,\n createAppKeyResolver(store: Store): AppKeyResolver {\n return (appId: number) => {\n try {\n const gh = mod.getGitHubStore(store);\n const ghApp = gh.apps.all().find((a) => a.app_id === appId);\n if (!ghApp) return null;\n return { privateKey: ghApp.private_key, slug: ghApp.slug, name: ghApp.name };\n } catch {\n return null;\n }\n };\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ login?: string }> | undefined)?.[0]?.login ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n },\n initConfig: {\n github: {\n users: [{\n login: \"octocat\", name: \"The Octocat\", email: \"octocat@github.com\",\n bio: \"I am the Octocat\", company: \"GitHub\", location: \"San Francisco\",\n }],\n orgs: [{ login: \"my-org\", name: \"My Organization\", description: \"A test organization\" }],\n repos: [\n { owner: \"octocat\", name: \"hello-world\", description: \"My first repository\", language: \"JavaScript\", topics: [\"hello\", \"world\"], auto_init: true },\n { owner: \"my-org\", name: \"org-repo\", description: \"An organization repository\", language: \"TypeScript\", auto_init: true },\n ],\n oauth_apps: [{\n client_id: \"Iv1.example_client_id\", client_secret: \"example_client_secret\",\n name: \"My App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/github\"],\n }],\n },\n },\n },\n\n google: {\n label: \"Google OAuth 2.0 / OpenID Connect + Gmail, Calendar, and Drive emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, token revocation, Gmail messages/drafts/threads/labels/history/settings, Calendar lists/events/freebusy, Drive files/uploads\",\n async load() {\n const mod = await import(\"@emulators/google\");\n return { plugin: mod.googlePlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@gmail.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\"] };\n },\n initConfig: {\n google: {\n users: [{ email: \"testuser@example.com\", name: \"Test User\", picture: \"https://lh3.googleusercontent.com/a/default-user\", email_verified: true }],\n oauth_clients: [{\n client_id: \"example-client-id.apps.googleusercontent.com\", client_secret: \"GOCSPX-example_secret\",\n name: \"Code App (Google)\", redirect_uris: [\"http://localhost:3000/api/auth/callback/google\"],\n }],\n labels: [{ id: \"Label_ops\", user_email: \"testuser@example.com\", name: \"Ops/Review\", color_background: \"#DDEEFF\", color_text: \"#111111\" }],\n messages: [{\n id: \"msg_welcome\", user_email: \"testuser@example.com\", from: \"welcome@example.com\", to: \"testuser@example.com\",\n subject: \"Welcome to the Gmail emulator\", body_text: \"You can now test Gmail, Calendar, and Drive flows locally.\",\n label_ids: [\"INBOX\", \"UNREAD\", \"CATEGORY_UPDATES\"], date: \"2025-01-04T10:00:00.000Z\",\n }],\n calendars: [{ id: \"primary\", user_email: \"testuser@example.com\", summary: \"testuser@example.com\", primary: true, selected: true, time_zone: \"UTC\" }],\n calendar_events: [{\n id: \"evt_kickoff\", user_email: \"testuser@example.com\", calendar_id: \"primary\",\n summary: \"Project Kickoff\", start_date_time: \"2025-01-10T09:00:00.000Z\", end_date_time: \"2025-01-10T09:30:00.000Z\",\n }],\n drive_items: [{ id: \"drv_docs\", user_email: \"testuser@example.com\", name: \"Docs\", mime_type: \"application/vnd.google-apps.folder\", parent_ids: [\"root\"] }],\n },\n },\n },\n\n slack: {\n label: \"Slack API emulator\",\n endpoints: \"auth, chat, conversations, users, reactions, team, OAuth, incoming webhooks\",\n async load() {\n const mod = await import(\"@emulators/slack\");\n return { plugin: mod.slackPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"U000000001\", id: 1, scopes: [\"chat:write\", \"channels:read\", \"users:read\", \"reactions:write\"] };\n },\n initConfig: {\n slack: {\n team: { name: \"My Workspace\", domain: \"my-workspace\" },\n users: [{ name: \"developer\", real_name: \"Developer\", email: \"dev@example.com\" }],\n channels: [{ name: \"general\", topic: \"General discussion\" }, { name: \"random\", topic: \"Random stuff\" }],\n bots: [{ name: \"my-bot\" }],\n oauth_apps: [{\n client_id: \"12345.67890\", client_secret: \"example_client_secret\",\n name: \"My Slack App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/slack\"],\n }],\n },\n },\n },\n\n apple: {\n label: \"Apple Sign In / OAuth emulator\",\n endpoints: \"OAuth authorize, token exchange, JWKS\",\n async load() {\n const mod = await import(\"@emulators/apple\");\n return { plugin: mod.applePlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@icloud.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"name\"] };\n },\n initConfig: {\n apple: {\n users: [{ email: \"testuser@icloud.com\", name: \"Test User\" }],\n oauth_clients: [{\n client_id: \"com.example.app\", team_id: \"TEAM001\",\n name: \"My Apple App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/apple\"],\n }],\n },\n },\n },\n\n microsoft: {\n label: \"Microsoft Entra ID OAuth 2.0 / OpenID Connect emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, Graph /me, logout, token revocation\",\n async load() {\n const mod = await import(\"@emulators/microsoft\");\n return { plugin: mod.microsoftPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@outlook.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\", \"User.Read\"] };\n },\n initConfig: {\n microsoft: {\n users: [{ email: \"testuser@outlook.com\", name: \"Test User\" }],\n oauth_clients: [{\n client_id: \"example-client-id\", client_secret: \"example-client-secret\",\n name: \"My Microsoft App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/microsoft-entra-id\"],\n }],\n },\n },\n },\n\n aws: {\n label: \"AWS cloud service emulator\",\n endpoints: \"S3 (buckets, objects), SQS (queues, messages), IAM (users, roles, access keys), STS (assume role, caller identity)\",\n async load() {\n const mod = await import(\"@emulators/aws\");\n return { plugin: mod.awsPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [\"s3:*\", \"sqs:*\", \"iam:*\", \"sts:*\"] };\n },\n initConfig: {\n aws: {\n region: \"us-east-1\",\n s3: { buckets: [{ name: \"my-app-bucket\" }, { name: \"my-app-uploads\" }] },\n sqs: { queues: [{ name: \"my-app-events\" }, { name: \"my-app-dlq\" }] },\n iam: {\n users: [{ user_name: \"developer\", create_access_key: true }],\n roles: [{ role_name: \"lambda-execution-role\", description: \"Role for Lambda function execution\" }],\n },\n },\n },\n },\n};\n\nexport const DEFAULT_TOKENS = {\n tokens: {\n \"test_token_admin\": {\n login: \"admin\",\n scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n },\n \"test_token_user1\": {\n login: \"octocat\",\n scopes: [\"repo\", \"user\"],\n },\n },\n};\n","import { createServer, type AppKeyResolver, type Store } from \"@emulators/core\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES } from \"../registry.js\";\nimport { serve } from \"@hono/node-server\";\nimport { readFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { parse as parseYaml } from \"yaml\";\nimport pc from \"picocolors\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nexport interface StartOptions {\n port: number;\n service?: string;\n seed?: string;\n}\n\ninterface SeedConfig {\n tokens?: Record<string, { login: string; scopes?: string[] }>;\n [service: string]: unknown;\n}\n\ninterface LoadResult {\n config: SeedConfig;\n source: string;\n}\n\nfunction loadSeedConfig(seedPath?: string): LoadResult | null {\n if (seedPath) {\n const fullPath = resolve(seedPath);\n if (!existsSync(fullPath)) {\n console.error(`Seed file not found: ${fullPath}`);\n process.exit(1);\n }\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: seedPath };\n } catch (err) {\n console.error(`Failed to parse ${seedPath}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n\n const autoFiles = [\n \"emulate.config.yaml\",\n \"emulate.config.yml\",\n \"emulate.config.json\",\n \"service-emulator.config.yaml\",\n \"service-emulator.config.yml\",\n \"service-emulator.config.json\",\n ];\n\n for (const file of autoFiles) {\n const fullPath = resolve(file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: file };\n } catch (err) {\n console.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n }\n\n return null;\n}\n\nfunction inferServicesFromConfig(config: SeedConfig): string[] | null {\n const found = SERVICE_NAMES.filter((k) => k in config);\n return found.length > 0 ? found : null;\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const { port: basePort } = options;\n\n const loaded = loadSeedConfig(options.seed);\n const seedConfig = loaded?.config ?? null;\n const configSource = loaded?.source ?? null;\n\n let services: string[];\n if (options.service) {\n services = options.service.split(\",\").map((s) => s.trim());\n } else if (seedConfig) {\n services = inferServicesFromConfig(seedConfig) ?? SERVICE_NAMES;\n } else {\n services = SERVICE_NAMES;\n }\n\n for (const svc of services) {\n if (!SERVICE_REGISTRY[svc]) {\n console.error(`Unknown service: ${svc}`);\n process.exit(1);\n }\n }\n\n const tokens: Record<string, { login: string; id: number; scopes?: string[] }> = {};\n if (seedConfig?.tokens) {\n let tokenId = 100;\n for (const [token, user] of Object.entries(seedConfig.tokens)) {\n tokens[token] = { login: user.login, id: tokenId++, scopes: user.scopes };\n }\n } else {\n tokens[\"test_token_admin\"] = { login: \"admin\", id: 2, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n }\n\n const serviceUrls: Array<{ name: string; url: string }> = [];\n const stores: Store[] = [];\n const httpServers: ReturnType<typeof serve>[] = [];\n\n for (let i = 0; i < services.length; i++) {\n const svc = services[i];\n const entry = SERVICE_REGISTRY[svc];\n const loadedSvc = await entry.load();\n\n const svcSeedConfig = seedConfig?.[svc] as Record<string, unknown> | undefined;\n const port = (svcSeedConfig?.port as number | undefined) ?? basePort + i;\n const baseUrl = `http://localhost:${port}`;\n serviceUrls.push({ name: svc, url: baseUrl });\n\n let cachedResolver: AppKeyResolver | undefined;\n const appKeyResolver: AppKeyResolver | undefined = loadedSvc.createAppKeyResolver\n ? (appId) => cachedResolver!(appId)\n : undefined;\n\n const fallbackUser = entry.defaultFallback(svcSeedConfig);\n\n const { app, store } = createServer(loadedSvc.plugin, { port, baseUrl, tokens, appKeyResolver, fallbackUser });\n cachedResolver = loadedSvc.createAppKeyResolver?.(store);\n stores.push(store);\n\n loadedSvc.plugin.seed?.(store, baseUrl);\n\n if (svcSeedConfig && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, svcSeedConfig);\n }\n\n const httpServer = serve({ fetch: app.fetch, port });\n httpServers.push(httpServer);\n }\n\n printBanner(serviceUrls, tokens, configSource);\n\n const shutdown = () => {\n console.log(`\\n${pc.dim(\"Shutting down...\")}`);\n for (const store of stores) {\n store.reset();\n }\n for (const srv of httpServers) {\n srv.close();\n }\n process.exit(0);\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction printBanner(\n services: Array<{ name: string; url: string }>,\n tokens: Record<string, { login: string; id: number; scopes?: string[] }>,\n configSource: string | null,\n): void {\n const lines: string[] = [];\n lines.push(\"\");\n lines.push(` ${pc.bold(\"emulate\")} ${pc.dim(`v${pkg.version}`)}`);\n lines.push(\"\");\n\n const maxNameLen = Math.max(...services.map((s) => s.name.length));\n for (const { name, url } of services) {\n lines.push(` ${pc.cyan(name.padEnd(maxNameLen + 2))}${pc.bold(url)}`);\n }\n lines.push(\"\");\n\n const tokenEntries = Object.entries(tokens);\n if (tokenEntries.length > 0) {\n lines.push(` ${pc.dim(\"Tokens\")}`);\n for (const [token, user] of tokenEntries) {\n lines.push(` ${pc.dim(token)} ${pc.dim(\"->\")} ${user.login}`);\n }\n lines.push(\"\");\n }\n\n if (configSource) {\n lines.push(` ${pc.dim(\"Config:\")} ${configSource}`);\n } else {\n lines.push(` ${pc.dim(\"Config:\")} defaults ${pc.dim(\"(run\")} emulate init ${pc.dim(\"to customize)\")}`);\n }\n lines.push(\"\");\n\n console.log(lines.join(\"\\n\"));\n}\n","import { writeFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { stringify as yamlStringify } from \"yaml\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, DEFAULT_TOKENS } from \"../registry.js\";\n\ninterface InitOptions {\n service: string;\n}\n\nexport function initCommand(options: InitOptions): void {\n const filename = \"emulate.config.yaml\";\n const fullPath = resolve(filename);\n\n if (existsSync(fullPath)) {\n console.error(`Config file already exists: ${filename}`);\n process.exit(1);\n }\n\n let config: Record<string, unknown>;\n if (options.service === \"all\") {\n config = { ...DEFAULT_TOKENS };\n for (const name of SERVICE_NAMES) {\n Object.assign(config, SERVICE_REGISTRY[name].initConfig);\n }\n } else {\n const entry = SERVICE_REGISTRY[options.service];\n if (!entry) {\n console.error(`Unknown service: ${options.service}. Available: ${SERVICE_NAMES.join(\", \")}, all`);\n process.exit(1);\n }\n config = { ...DEFAULT_TOKENS, ...entry.initConfig };\n }\n\n const content = yamlStringify(config);\n writeFileSync(fullPath, content, \"utf-8\");\n\n console.log(`Created ${filename}`);\n console.log(`\\nRun 'emulate' to start the emulator.`);\n}\n","import { SERVICE_REGISTRY } from \"../registry.js\";\n\nexport function listCommand(): void {\n console.log(\"\\nAvailable services:\\n\");\n for (const [name, entry] of Object.entries(SERVICE_REGISTRY)) {\n console.log(` ${name.padEnd(10)}${entry.label}`);\n console.log(` Endpoints: ${entry.endpoints}`);\n console.log();\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,eAAe;;;AGAxB,SAAS,kBAAkB;AIA3B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,QACG,QAAQ,SAAS,EAAE,WAAW,KAAK,CAAC,EACpC,YAAY,2BAA2B,EACvC,OAAO,qBAAqB,aAAa,WAAW,EACpD,OAAO,4BAA4B,oCAAoC,EACvE,OAAO,iBAAiB,0BAA0B,EAClD,OAAO,OAAO,SAAS;AACtB,QAAM,OAAO,SAAS,KAAK,MAAM,EAAE;AACnC,MAAI,OAAO,MAAM,IAAI,KAAK,OAAO,KAAK,OAAO,OAAO;AAClD,YAAQ,MAAM,iBAAiB,KAAK,IAAI,EAAE;AAC1C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,SAAS,KAAK;AAAA,IACd,MAAM,KAAK;AAAA,EACb,CAAC;AACH,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,YAAY,gCAAgC,EAC5C,OAAO,2BAA2B,kCAAkC,KAAK,EACzE,OAAO,CAAC,SAAS;AAChB,cAAY,EAAE,SAAS,KAAK,QAAQ,CAAC;AACvC,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,MAAM,eAAe,EACrB,YAAY,yBAAyB,EACrC,OAAO,MAAM;AACZ,cAAY;AACd,CAAC;AAEH,QAAQ,MAAM;","names":["readFileSync","existsSync","resolve","resolve","existsSync","pkg"]}
1
+ {"version":3,"sources":["../src/index.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../src/registry.ts","../src/commands/start.ts","../src/commands/init.ts","../src/commands/list.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport { startCommand } from \"./commands/start.js\";\nimport { initCommand } from \"./commands/init.js\";\nimport { listCommand } from \"./commands/list.js\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nconst defaultPort = process.env.EMULATE_PORT ?? process.env.PORT ?? \"4000\";\n\nconst program = new Command();\n\nprogram\n .name(\"emulate\")\n .description(\"Local drop-in replacement services for CI and no-network sandboxes\")\n .version(pkg.version);\n\nprogram\n .command(\"start\", { isDefault: true })\n .description(\"Start the emulator server\")\n .option(\"-p, --port <port>\", \"Base port\", defaultPort)\n .option(\"-s, --service <services>\", \"Comma-separated services to enable\")\n .option(\"--seed <file>\", \"Path to seed config file\")\n .action(async (opts) => {\n const port = parseInt(opts.port, 10);\n if (Number.isNaN(port) || port < 1 || port > 65535) {\n console.error(`Invalid port: ${opts.port}`);\n process.exit(1);\n }\n await startCommand({\n port,\n service: opts.service,\n seed: opts.seed,\n });\n });\n\nprogram\n .command(\"init\")\n .description(\"Generate a starter config file\")\n .option(\"-s, --service <service>\", \"Service to generate config for\", \"all\")\n .action((opts) => {\n initCommand({ service: opts.service });\n });\n\nprogram\n .command(\"list\")\n .alias(\"list-services\")\n .description(\"List available services\")\n .action(() => {\n listCommand();\n });\n\nprogram.parse();\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 { ServicePlugin, Store, AppKeyResolver, AuthFallback } from \"@emulators/core\";\n\nexport interface LoadedService {\n plugin: ServicePlugin;\n seedFromConfig?(store: Store, baseUrl: string, config: unknown): void;\n createAppKeyResolver?(store: Store): AppKeyResolver;\n}\n\nexport interface ServiceEntry {\n label: string;\n endpoints: string;\n load(): Promise<LoadedService>;\n defaultFallback(svcSeedConfig?: Record<string, unknown>): AuthFallback;\n initConfig: Record<string, unknown>;\n}\n\nconst SERVICE_NAME_LIST = [\"vercel\", \"github\", \"google\", \"slack\", \"apple\", \"microsoft\", \"okta\", \"aws\", \"resend\", \"stripe\", \"mongoatlas\"] as const;\nexport type ServiceName = (typeof SERVICE_NAME_LIST)[number];\nexport const SERVICE_NAMES: readonly ServiceName[] = SERVICE_NAME_LIST;\n\nexport const SERVICE_REGISTRY: Record<ServiceName, ServiceEntry> = {\n vercel: {\n label: \"Vercel REST API emulator\",\n endpoints: \"projects, deployments, domains, env vars, users, teams, file uploads, protection bypass\",\n async load() {\n const mod = await import(\"@emulators/vercel\");\n return { plugin: mod.vercelPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ username?: string }> | undefined)?.[0]?.username ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [] };\n },\n initConfig: {\n vercel: {\n users: [{ username: \"developer\", name: \"Developer\", email: \"dev@example.com\" }],\n teams: [{ slug: \"my-team\", name: \"My Team\" }],\n projects: [{ name: \"my-app\", team: \"my-team\", framework: \"nextjs\" }],\n integrations: [{\n client_id: \"oac_example_client_id\",\n client_secret: \"example_client_secret\",\n name: \"My Vercel App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/vercel\"],\n }],\n },\n },\n },\n\n github: {\n label: \"GitHub REST API emulator\",\n endpoints: \"users, repos, issues, PRs, comments, reviews, labels, milestones, branches, git data, orgs, teams, releases, webhooks, search, actions, checks, rate limit\",\n async load() {\n const mod = await import(\"@emulators/github\");\n return {\n plugin: mod.githubPlugin,\n seedFromConfig: mod.seedFromConfig,\n createAppKeyResolver(store: Store): AppKeyResolver {\n return (appId: number) => {\n try {\n const gh = mod.getGitHubStore(store);\n const ghApp = gh.apps.all().find((a) => a.app_id === appId);\n if (!ghApp) return null;\n return { privateKey: ghApp.private_key, slug: ghApp.slug, name: ghApp.name };\n } catch {\n return null;\n }\n };\n },\n };\n },\n defaultFallback(cfg) {\n const firstLogin = (cfg?.users as Array<{ login?: string }> | undefined)?.[0]?.login ?? \"admin\";\n return { login: firstLogin, id: 1, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n },\n initConfig: {\n github: {\n users: [{\n login: \"octocat\", name: \"The Octocat\", email: \"octocat@github.com\",\n bio: \"I am the Octocat\", company: \"GitHub\", location: \"San Francisco\",\n }],\n orgs: [{ login: \"my-org\", name: \"My Organization\", description: \"A test organization\" }],\n repos: [\n { owner: \"octocat\", name: \"hello-world\", description: \"My first repository\", language: \"JavaScript\", topics: [\"hello\", \"world\"], auto_init: true },\n { owner: \"my-org\", name: \"org-repo\", description: \"An organization repository\", language: \"TypeScript\", auto_init: true },\n ],\n oauth_apps: [{\n client_id: \"Iv1.example_client_id\", client_secret: \"example_client_secret\",\n name: \"My App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/github\"],\n }],\n },\n },\n },\n\n google: {\n label: \"Google OAuth 2.0 / OpenID Connect + Gmail, Calendar, and Drive emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, token revocation, Gmail messages/drafts/threads/labels/history/settings, Calendar lists/events/freebusy, Drive files/uploads\",\n async load() {\n const mod = await import(\"@emulators/google\");\n return { plugin: mod.googlePlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@gmail.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\"] };\n },\n initConfig: {\n google: {\n users: [{ email: \"testuser@example.com\", name: \"Test User\", picture: \"https://lh3.googleusercontent.com/a/default-user\", email_verified: true }],\n oauth_clients: [{\n client_id: \"example-client-id.apps.googleusercontent.com\", client_secret: \"GOCSPX-example_secret\",\n name: \"Code App (Google)\", redirect_uris: [\"http://localhost:3000/api/auth/callback/google\"],\n }],\n labels: [{ id: \"Label_ops\", user_email: \"testuser@example.com\", name: \"Ops/Review\", color_background: \"#DDEEFF\", color_text: \"#111111\" }],\n messages: [{\n id: \"msg_welcome\", user_email: \"testuser@example.com\", from: \"welcome@example.com\", to: \"testuser@example.com\",\n subject: \"Welcome to the Gmail emulator\", body_text: \"You can now test Gmail, Calendar, and Drive flows locally.\",\n label_ids: [\"INBOX\", \"UNREAD\", \"CATEGORY_UPDATES\"], date: \"2025-01-04T10:00:00.000Z\",\n }],\n calendars: [{ id: \"primary\", user_email: \"testuser@example.com\", summary: \"testuser@example.com\", primary: true, selected: true, time_zone: \"UTC\" }],\n calendar_events: [{\n id: \"evt_kickoff\", user_email: \"testuser@example.com\", calendar_id: \"primary\",\n summary: \"Project Kickoff\", start_date_time: \"2025-01-10T09:00:00.000Z\", end_date_time: \"2025-01-10T09:30:00.000Z\",\n }],\n drive_items: [{ id: \"drv_docs\", user_email: \"testuser@example.com\", name: \"Docs\", mime_type: \"application/vnd.google-apps.folder\", parent_ids: [\"root\"] }],\n },\n },\n },\n\n slack: {\n label: \"Slack API emulator\",\n endpoints: \"auth, chat, conversations, users, reactions, team, OAuth, incoming webhooks\",\n async load() {\n const mod = await import(\"@emulators/slack\");\n return { plugin: mod.slackPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"U000000001\", id: 1, scopes: [\"chat:write\", \"channels:read\", \"users:read\", \"reactions:write\"] };\n },\n initConfig: {\n slack: {\n team: { name: \"My Workspace\", domain: \"my-workspace\" },\n users: [{ name: \"developer\", real_name: \"Developer\", email: \"dev@example.com\" }],\n channels: [{ name: \"general\", topic: \"General discussion\" }, { name: \"random\", topic: \"Random stuff\" }],\n bots: [{ name: \"my-bot\" }],\n oauth_apps: [{\n client_id: \"12345.67890\", client_secret: \"example_client_secret\",\n name: \"My Slack App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/slack\"],\n }],\n },\n },\n },\n\n apple: {\n label: \"Apple Sign In / OAuth emulator\",\n endpoints: \"OAuth authorize, token exchange, JWKS\",\n async load() {\n const mod = await import(\"@emulators/apple\");\n return { plugin: mod.applePlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@icloud.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"name\"] };\n },\n initConfig: {\n apple: {\n users: [{ email: \"testuser@icloud.com\", name: \"Test User\" }],\n oauth_clients: [{\n client_id: \"com.example.app\", team_id: \"TEAM001\",\n name: \"My Apple App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/apple\"],\n }],\n },\n },\n },\n\n microsoft: {\n label: \"Microsoft Entra ID OAuth 2.0 / OpenID Connect emulator\",\n endpoints: \"OAuth authorize, token exchange, userinfo, OIDC discovery, Graph /me, logout, token revocation\",\n async load() {\n const mod = await import(\"@emulators/microsoft\");\n return { plugin: mod.microsoftPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstEmail = (cfg?.users as Array<{ email?: string }> | undefined)?.[0]?.email ?? \"testuser@outlook.com\";\n return { login: firstEmail, id: 1, scopes: [\"openid\", \"email\", \"profile\", \"User.Read\"] };\n },\n initConfig: {\n microsoft: {\n users: [{ email: \"testuser@outlook.com\", name: \"Test User\" }],\n oauth_clients: [{\n client_id: \"example-client-id\", client_secret: \"example-client-secret\",\n name: \"My Microsoft App\", redirect_uris: [\"http://localhost:3000/api/auth/callback/microsoft-entra-id\"],\n }],\n },\n },\n },\n\n okta: {\n label: \"Okta OAuth 2.0 / OpenID Connect + management API emulator\",\n endpoints: \"OIDC discovery, JWKS, OAuth authorize/token/userinfo/introspect/revoke/logout, users, groups, apps, authorization servers\",\n async load() {\n const mod = await import(\"@emulators/okta\");\n return { plugin: mod.oktaPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback(cfg) {\n const firstLogin =\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.login ??\n (cfg?.users as Array<{ login?: string; email?: string }> | undefined)?.[0]?.email ??\n \"testuser@okta.local\";\n return { login: firstLogin, id: 1, scopes: [\"openid\", \"profile\", \"email\", \"groups\"] };\n },\n initConfig: {\n okta: {\n users: [{ login: \"testuser@okta.local\", email: \"testuser@okta.local\", first_name: \"Test\", last_name: \"User\" }],\n groups: [{ name: \"Everyone\", description: \"All users\", type: \"BUILT_IN\", okta_id: \"00g_everyone\" }],\n authorization_servers: [{ id: \"default\", name: \"default\", audiences: [\"api://default\"] }],\n oauth_clients: [{\n client_id: \"okta-test-client\",\n client_secret: \"okta-test-secret\",\n name: \"Sample OIDC Client\",\n redirect_uris: [\"http://localhost:3000/callback\"],\n auth_server_id: \"default\",\n }],\n },\n },\n },\n\n aws: {\n label: \"AWS cloud service emulator\",\n endpoints: \"S3 (buckets, objects), SQS (queues, messages), IAM (users, roles, access keys), STS (assume role, caller identity)\",\n async load() {\n const mod = await import(\"@emulators/aws\");\n return { plugin: mod.awsPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [\"s3:*\", \"sqs:*\", \"iam:*\", \"sts:*\"] };\n },\n initConfig: {\n aws: {\n region: \"us-east-1\",\n s3: { buckets: [{ name: \"my-app-bucket\" }, { name: \"my-app-uploads\" }] },\n sqs: { queues: [{ name: \"my-app-events\" }, { name: \"my-app-dlq\" }] },\n iam: {\n users: [{ user_name: \"developer\", create_access_key: true }],\n roles: [{ role_name: \"lambda-execution-role\", description: \"Role for Lambda function execution\" }],\n },\n },\n },\n },\n resend: {\n label: \"Resend email API emulator\",\n endpoints: \"emails, domains, contacts, API keys, inbox UI\",\n async load() {\n const mod = await import(\"@emulators/resend\");\n return { plugin: mod.resendPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"re_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n resend: {\n domains: [{ name: \"example.com\", region: \"us-east-1\" }],\n contacts: [{ email: \"test@example.com\", first_name: \"Test\", last_name: \"User\" }],\n },\n },\n },\n stripe: {\n label: \"Stripe payments emulator\",\n endpoints: \"customers, payment intents, charges, products, prices, checkout sessions, webhooks\",\n async load() {\n const mod = await import(\"@emulators/stripe\");\n return { plugin: mod.stripePlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"sk_test_admin\", id: 1, scopes: [] };\n },\n initConfig: {\n stripe: {\n customers: [{ email: \"test@example.com\", name: \"Test Customer\" }],\n products: [{ name: \"Pro Plan\", description: \"Monthly pro subscription\" }],\n prices: [{ product_name: \"Pro Plan\", currency: \"usd\", unit_amount: 2000 }],\n },\n },\n },\n mongoatlas: {\n label: \"MongoDB Atlas service emulator\",\n endpoints: \"Atlas Admin API v2 (projects, clusters, database users, databases, collections), Atlas Data API v1 (findOne, find, insertOne, insertMany, updateOne, updateMany, deleteOne, deleteMany, aggregate)\",\n async load() {\n const mod = await import(\"@emulators/mongoatlas\");\n return { plugin: mod.mongoatlasPlugin, seedFromConfig: mod.seedFromConfig };\n },\n defaultFallback() {\n return { login: \"admin\", id: 1, scopes: [] };\n },\n initConfig: {\n mongoatlas: {\n projects: [{ name: \"Project0\" }],\n clusters: [{ name: \"Cluster0\", project: \"Project0\" }],\n database_users: [{ username: \"admin\", project: \"Project0\" }],\n databases: [{ cluster: \"Cluster0\", name: \"test\", collections: [\"items\"] }],\n },\n },\n },\n};\n\nexport const DEFAULT_TOKENS = {\n tokens: {\n \"test_token_admin\": {\n login: \"admin\",\n scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n },\n \"test_token_user1\": {\n login: \"octocat\",\n scopes: [\"repo\", \"user\"],\n },\n },\n};\n","import { createServer, type AppKeyResolver, type Store } from \"@emulators/core\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES } from \"../registry.js\";\nimport { serve } from \"@hono/node-server\";\nimport { readFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { parse as parseYaml } from \"yaml\";\nimport pc from \"picocolors\";\n\ndeclare const PKG_VERSION: string;\nconst pkg = { version: PKG_VERSION };\n\nexport interface StartOptions {\n port: number;\n service?: string;\n seed?: string;\n}\n\ninterface SeedConfig {\n tokens?: Record<string, { login: string; scopes?: string[] }>;\n [service: string]: unknown;\n}\n\ninterface LoadResult {\n config: SeedConfig;\n source: string;\n}\n\nfunction loadSeedConfig(seedPath?: string): LoadResult | null {\n if (seedPath) {\n const fullPath = resolve(seedPath);\n if (!existsSync(fullPath)) {\n console.error(`Seed file not found: ${fullPath}`);\n process.exit(1);\n }\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: seedPath };\n } catch (err) {\n console.error(`Failed to parse ${seedPath}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n\n const autoFiles = [\n \"emulate.config.yaml\",\n \"emulate.config.yml\",\n \"emulate.config.json\",\n \"service-emulator.config.yaml\",\n \"service-emulator.config.yml\",\n \"service-emulator.config.json\",\n ];\n\n for (const file of autoFiles) {\n const fullPath = resolve(file);\n if (existsSync(fullPath)) {\n const content = readFileSync(fullPath, \"utf-8\");\n try {\n const config = fullPath.endsWith(\".json\") ? JSON.parse(content) : parseYaml(content);\n return { config, source: file };\n } catch (err) {\n console.error(`Failed to parse ${file}: ${err instanceof Error ? err.message : err}`);\n process.exit(1);\n }\n }\n }\n\n return null;\n}\n\nfunction inferServicesFromConfig(config: SeedConfig): string[] | null {\n const found = SERVICE_NAMES.filter((k) => k in config);\n return found.length > 0 ? found : null;\n}\n\nexport async function startCommand(options: StartOptions): Promise<void> {\n const { port: basePort } = options;\n\n const loaded = loadSeedConfig(options.seed);\n const seedConfig = loaded?.config ?? null;\n const configSource = loaded?.source ?? null;\n\n let services: string[];\n if (options.service) {\n services = options.service.split(\",\").map((s) => s.trim());\n } else if (seedConfig) {\n services = inferServicesFromConfig(seedConfig) ?? SERVICE_NAMES;\n } else {\n services = SERVICE_NAMES;\n }\n\n for (const svc of services) {\n if (!SERVICE_REGISTRY[svc]) {\n console.error(`Unknown service: ${svc}`);\n process.exit(1);\n }\n }\n\n const tokens: Record<string, { login: string; id: number; scopes?: string[] }> = {};\n if (seedConfig?.tokens) {\n let tokenId = 100;\n for (const [token, user] of Object.entries(seedConfig.tokens)) {\n tokens[token] = { login: user.login, id: tokenId++, scopes: user.scopes };\n }\n } else {\n tokens[\"test_token_admin\"] = { login: \"admin\", id: 2, scopes: [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"] };\n }\n\n const serviceUrls: Array<{ name: string; url: string }> = [];\n const stores: Store[] = [];\n const httpServers: ReturnType<typeof serve>[] = [];\n\n for (let i = 0; i < services.length; i++) {\n const svc = services[i];\n const entry = SERVICE_REGISTRY[svc];\n const loadedSvc = await entry.load();\n\n const svcSeedConfig = seedConfig?.[svc] as Record<string, unknown> | undefined;\n const port = (svcSeedConfig?.port as number | undefined) ?? basePort + i;\n const baseUrl = `http://localhost:${port}`;\n serviceUrls.push({ name: svc, url: baseUrl });\n\n let cachedResolver: AppKeyResolver | undefined;\n const appKeyResolver: AppKeyResolver | undefined = loadedSvc.createAppKeyResolver\n ? (appId) => cachedResolver!(appId)\n : undefined;\n\n const fallbackUser = entry.defaultFallback(svcSeedConfig);\n\n const { app, store } = createServer(loadedSvc.plugin, { port, baseUrl, tokens, appKeyResolver, fallbackUser });\n cachedResolver = loadedSvc.createAppKeyResolver?.(store);\n stores.push(store);\n\n loadedSvc.plugin.seed?.(store, baseUrl);\n\n if (svcSeedConfig && loadedSvc.seedFromConfig) {\n loadedSvc.seedFromConfig(store, baseUrl, svcSeedConfig);\n }\n\n const httpServer = serve({ fetch: app.fetch, port });\n httpServers.push(httpServer);\n }\n\n printBanner(serviceUrls, tokens, configSource);\n\n const shutdown = () => {\n console.log(`\\n${pc.dim(\"Shutting down...\")}`);\n for (const store of stores) {\n store.reset();\n }\n for (const srv of httpServers) {\n srv.close();\n }\n process.exit(0);\n };\n process.once(\"SIGINT\", shutdown);\n process.once(\"SIGTERM\", shutdown);\n}\n\nfunction printBanner(\n services: Array<{ name: string; url: string }>,\n tokens: Record<string, { login: string; id: number; scopes?: string[] }>,\n configSource: string | null,\n): void {\n const lines: string[] = [];\n lines.push(\"\");\n lines.push(` ${pc.bold(\"emulate\")} ${pc.dim(`v${pkg.version}`)}`);\n lines.push(\"\");\n\n const maxNameLen = Math.max(...services.map((s) => s.name.length));\n for (const { name, url } of services) {\n lines.push(` ${pc.cyan(name.padEnd(maxNameLen + 2))}${pc.bold(url)}`);\n }\n lines.push(\"\");\n\n const tokenEntries = Object.entries(tokens);\n if (tokenEntries.length > 0) {\n lines.push(` ${pc.dim(\"Tokens\")}`);\n for (const [token, user] of tokenEntries) {\n lines.push(` ${pc.dim(token)} ${pc.dim(\"->\")} ${user.login}`);\n }\n lines.push(\"\");\n }\n\n if (configSource) {\n lines.push(` ${pc.dim(\"Config:\")} ${configSource}`);\n } else {\n lines.push(` ${pc.dim(\"Config:\")} defaults ${pc.dim(\"(run\")} emulate init ${pc.dim(\"to customize)\")}`);\n }\n lines.push(\"\");\n\n console.log(lines.join(\"\\n\"));\n}\n","import { writeFileSync, existsSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { stringify as yamlStringify } from \"yaml\";\nimport { SERVICE_REGISTRY, SERVICE_NAMES, DEFAULT_TOKENS } from \"../registry.js\";\n\ninterface InitOptions {\n service: string;\n}\n\nexport function initCommand(options: InitOptions): void {\n const filename = \"emulate.config.yaml\";\n const fullPath = resolve(filename);\n\n if (existsSync(fullPath)) {\n console.error(`Config file already exists: ${filename}`);\n process.exit(1);\n }\n\n let config: Record<string, unknown>;\n if (options.service === \"all\") {\n config = { ...DEFAULT_TOKENS };\n for (const name of SERVICE_NAMES) {\n Object.assign(config, SERVICE_REGISTRY[name].initConfig);\n }\n } else {\n const entry = SERVICE_REGISTRY[options.service];\n if (!entry) {\n console.error(`Unknown service: ${options.service}. Available: ${SERVICE_NAMES.join(\", \")}, all`);\n process.exit(1);\n }\n config = { ...DEFAULT_TOKENS, ...entry.initConfig };\n }\n\n const content = yamlStringify(config);\n writeFileSync(fullPath, content, \"utf-8\");\n\n console.log(`Created ${filename}`);\n console.log(`\\nRun 'emulate' to start the emulator.`);\n}\n","import { SERVICE_REGISTRY } from \"../registry.js\";\n\nexport function listCommand(): void {\n console.log(\"\\nAvailable services:\\n\");\n for (const [name, entry] of Object.entries(SERVICE_REGISTRY)) {\n console.log(` ${name.padEnd(10)}${entry.label}`);\n console.log(` Endpoints: ${entry.endpoints}`);\n console.log();\n }\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,eAAe;;;AGAxB,SAAS,kBAAkB;AIA3B,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,YAAY;ANoCvB,SAAS,eAAe,OAAyB;AACtD,MAAI,iBAAiB,KAAK;AACxB,WAAO,EAAE,QAAQ,OAAgB,SAAS,CAAC,GAAG,MAAM,QAAQ,CAAC,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,eAAe,CAAC,CAAC,CAAC,EAAE;EACzG;AACA,MAAI,iBAAiB,KAAK;AACxB,WAAO,EAAE,QAAQ,OAAgB,QAAQ,CAAC,GAAG,MAAM,OAAO,CAAC,EAAE;EAC/D;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,OAAyB;AACxD,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,YAAY,OAAO;AACpE,UAAM,SAAS;AACf,QAAI,OAAO,WAAW,OAAO;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AI,QAAQ;AAE5B,QACG,KAAK,SAAS,EACd,YAAY,oEAAoE,EAChF,QAAQA,KAAI,OAAO;AAEtB,QACG,QAAQ,SAAS,EAAE,WAAW,KAAK,CAAC,EACpC,YAAY,2BAA2B,EACvC,OAAO,qBAAqB,aAAa,WAAW,EACpD,OAAO,4BAA4B,oCAAoC,EACvE,OAAO,iBAAiB,0BAA0B,EAClD,OAAO,OAAO,SAAS;AACtB,QAAM,OAAO,SAAS,KAAK,MAAM,EAAE;AACnC,MAAI,OAAO,MAAM,IAAI,KAAK,OAAO,KAAK,OAAO,OAAO;AAClD,YAAQ,MAAM,iBAAiB,KAAK,IAAI,EAAE;AAC1C,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,QAAM,aAAa;AAAA,IACjB;AAAA,IACA,SAAS,KAAK;AAAA,IACd,MAAM,KAAK;AAAA,EACb,CAAC;AACH,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,YAAY,gCAAgC,EAC5C,OAAO,2BAA2B,kCAAkC,KAAK,EACzE,OAAO,CAAC,SAAS;AAChB,cAAY,EAAE,SAAS,KAAK,QAAQ,CAAC;AACvC,CAAC;AAEH,QACG,QAAQ,MAAM,EACd,MAAM,eAAe,EACrB,YAAY,yBAAyB,EACrC,OAAO,MAAM;AACZ,cAAY;AACd,CAAC;AAEH,QAAQ,MAAM;","names":["readFileSync","existsSync","resolve","resolve","existsSync","pkg"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "emulate",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Local drop-in replacement services for CI and no-network sandboxes",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -51,14 +51,18 @@
51
51
  "devDependencies": {
52
52
  "tsup": "^8",
53
53
  "typescript": "^5.7",
54
- "@emulators/core": "0.3.0",
55
- "@emulators/github": "0.3.0",
56
- "@emulators/microsoft": "0.3.0",
57
- "@emulators/aws": "0.3.0",
58
- "@emulators/apple": "0.3.0",
59
- "@emulators/google": "0.3.0",
60
- "@emulators/vercel": "0.3.0",
61
- "@emulators/slack": "0.3.0"
54
+ "@emulators/github": "0.4.1",
55
+ "@emulators/apple": "0.4.1",
56
+ "@emulators/core": "0.4.1",
57
+ "@emulators/microsoft": "0.4.1",
58
+ "@emulators/okta": "0.4.1",
59
+ "@emulators/vercel": "0.4.1",
60
+ "@emulators/mongoatlas": "0.4.1",
61
+ "@emulators/aws": "0.4.1",
62
+ "@emulators/google": "0.4.1",
63
+ "@emulators/slack": "0.4.1",
64
+ "@emulators/resend": "0.4.1",
65
+ "@emulators/stripe": "0.4.1"
62
66
  },
63
67
  "scripts": {
64
68
  "build": "tsup",