@executor-js/emulate 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +1044 -0
  2. package/dist/api.d.ts +24 -0
  3. package/dist/api.js +2665 -0
  4. package/dist/api.js.map +1 -0
  5. package/dist/chunk-D6EKRYGP.js +1615 -0
  6. package/dist/chunk-D6EKRYGP.js.map +1 -0
  7. package/dist/chunk-WVQMFHQM.js +83 -0
  8. package/dist/chunk-WVQMFHQM.js.map +1 -0
  9. package/dist/dist-7FDUSG5I.js +24368 -0
  10. package/dist/dist-7FDUSG5I.js.map +1 -0
  11. package/dist/dist-7N4COJHK.js +1814 -0
  12. package/dist/dist-7N4COJHK.js.map +1 -0
  13. package/dist/dist-BTEY33DJ.js +2334 -0
  14. package/dist/dist-BTEY33DJ.js.map +1 -0
  15. package/dist/dist-DK26ESP2.js +595 -0
  16. package/dist/dist-DK26ESP2.js.map +1 -0
  17. package/dist/dist-IYZPDKJW.js +1284 -0
  18. package/dist/dist-IYZPDKJW.js.map +1 -0
  19. package/dist/dist-JJ2ZRCAX.js +189 -0
  20. package/dist/dist-JJ2ZRCAX.js.map +1 -0
  21. package/dist/dist-K4CVTD6K.js +1570 -0
  22. package/dist/dist-K4CVTD6K.js.map +1 -0
  23. package/dist/dist-M3GVASMR.js +1254 -0
  24. package/dist/dist-M3GVASMR.js.map +1 -0
  25. package/dist/dist-OYYGWKZQ.js +1533 -0
  26. package/dist/dist-OYYGWKZQ.js.map +1 -0
  27. package/dist/dist-P3SBBRFR.js +3169 -0
  28. package/dist/dist-P3SBBRFR.js.map +1 -0
  29. package/dist/dist-RMPDKZUA.js +1183 -0
  30. package/dist/dist-RMPDKZUA.js.map +1 -0
  31. package/dist/dist-WBKONLOE.js +2154 -0
  32. package/dist/dist-WBKONLOE.js.map +1 -0
  33. package/dist/dist-XM5HSBDC.js +1090 -0
  34. package/dist/dist-XM5HSBDC.js.map +1 -0
  35. package/dist/dist-XVVIYXQG.js +4241 -0
  36. package/dist/dist-XVVIYXQG.js.map +1 -0
  37. package/dist/dist-YPRJYQHW.js +5109 -0
  38. package/dist/dist-YPRJYQHW.js.map +1 -0
  39. package/dist/dist-ZEC77OKZ.js +913 -0
  40. package/dist/dist-ZEC77OKZ.js.map +1 -0
  41. package/dist/fonts/GeistPixel-Square.woff2 +0 -0
  42. package/dist/fonts/favicon.ico +0 -0
  43. package/dist/fonts/geist-sans.woff2 +0 -0
  44. package/dist/helpers-LXLP3DFE-LBOTATT5.js +17 -0
  45. package/dist/helpers-LXLP3DFE-LBOTATT5.js.map +1 -0
  46. package/dist/index.js +3005 -0
  47. package/dist/index.js.map +1 -0
  48. package/package.json +83 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../@emulators/x/src/store.ts","../../@emulators/x/src/routes/oauth.ts","../../@emulators/core/src/store.ts","../../@emulators/core/src/http.ts","../../@emulators/core/src/webhooks.ts","../../@emulators/core/src/middleware/error-handler.ts","../../@emulators/core/src/middleware/auth.ts","../../@emulators/core/src/debug.ts","../../@emulators/core/src/fonts.ts","../../@emulators/core/src/ledger.ts","../../@emulators/core/src/manifest.ts","../../@emulators/core/src/ui.ts","../../@emulators/core/src/control-plane.ts","../../@emulators/core/src/server.ts","../../@emulators/core/src/service-host.ts","../../@emulators/core/src/middleware/pagination.ts","../../@emulators/core/src/oauth-helpers.ts","../../@emulators/core/src/persistence.ts","../../@emulators/x/src/routes/auth.ts","../../@emulators/x/src/routes/users.ts","../../@emulators/x/src/routes/tweets.ts","../../@emulators/x/src/routes/openapi.ts","../../@emulators/x/src/manifest.ts","../../@emulators/x/src/index.ts"],"sourcesContent":["import { Store, type Collection } from \"@emulators/core\";\nimport type { XUser, XTweet, XOAuthClient, XAuthCode, XAccessToken, XRefreshToken } from \"./entities.js\";\n\nexport interface XStore {\n users: Collection<XUser>;\n tweets: Collection<XTweet>;\n oauthClients: Collection<XOAuthClient>;\n authCodes: Collection<XAuthCode>;\n accessTokens: Collection<XAccessToken>;\n refreshTokens: Collection<XRefreshToken>;\n}\n\nexport function getXStore(store: Store): XStore {\n return {\n users: store.collection<XUser>(\"x.users\", [\"user_id\", \"username\"]),\n tweets: store.collection<XTweet>(\"x.tweets\", [\"tweet_id\", \"author_id\"]),\n oauthClients: store.collection<XOAuthClient>(\"x.oauth_clients\", [\"client_id\"]),\n authCodes: store.collection<XAuthCode>(\"x.auth_codes\", [\"code\", \"client_id\"]),\n accessTokens: store.collection<XAccessToken>(\"x.access_tokens\", [\"token\", \"client_id\"]),\n refreshTokens: store.collection<XRefreshToken>(\"x.refresh_tokens\", [\"token\", \"client_id\"]),\n };\n}\n\n/**\n * Resolve an access token from the store. Returns the token row if it exists and\n * has not expired (expired rows are dropped on read). This is how both the\n * app-only BearerToken and the user-context OAuth2UserToken are validated, since\n * X tokens are opaque (not the core tokenMap, which isn't persisted across DO\n * eviction) and we need to distinguish app-only from user context per request.\n */\nexport function lookupAccessToken(store: Store, token: string): XAccessToken | undefined {\n const xs = getXStore(store);\n const row = xs.accessTokens.findOneBy(\"token\", token);\n if (!row) return undefined;\n if (row.expires > 0 && Date.now() > row.expires) {\n xs.accessTokens.delete(row.id);\n return undefined;\n }\n return row;\n}\n\n/** X v2 numeric snowflake-style id (a long decimal string). */\nexport function xNumericId(): string {\n let s = \"\";\n for (let i = 0; i < 19; i++) {\n s += Math.floor(Math.random() * 10).toString();\n }\n // Avoid a leading zero so the id reads like a real snowflake.\n return s[0] === \"0\" ? \"1\" + s.slice(1) : s;\n}\n","import { createHash, randomBytes } from \"crypto\";\nimport type { Context } from \"@emulators/core\";\nimport {\n escapeHtml,\n renderCardPage,\n renderErrorPage,\n renderUserButton,\n matchesRedirectUri,\n constantTimeSecretEqual,\n bodyStr,\n debug,\n type RouteContext,\n} from \"@emulators/core\";\nimport { getXStore } from \"../store.js\";\nimport type { XOAuthClient } from \"../entities.js\";\n\nconst SERVICE_LABEL = \"X\";\nconst AUTH_CODE_TTL_MS = 10 * 60 * 1000;\nconst ACCESS_TOKEN_TTL_SECONDS = 7200;\n\n/**\n * The full set of OAuth 2.0 scopes the X v2 platform declares for the\n * authorization-code flow (OAuth2UserToken). Used to validate requested scopes\n * and to populate the authorize consent.\n */\nexport const X_SCOPES = [\n \"tweet.read\",\n \"tweet.write\",\n \"tweet.moderate.write\",\n \"users.read\",\n \"follows.read\",\n \"follows.write\",\n \"offline.access\",\n \"space.read\",\n \"mute.read\",\n \"mute.write\",\n \"like.read\",\n \"like.write\",\n \"list.read\",\n \"list.write\",\n \"block.read\",\n \"block.write\",\n \"bookmark.read\",\n \"bookmark.write\",\n] as const;\n\ninterface ClientCredentials {\n clientId: string;\n clientSecret: string | null;\n /** True when the credentials came from an HTTP Basic Authorization header. */\n fromBasic: boolean;\n}\n\n/**\n * Parse client credentials from a token request. X supports a single client-auth\n * method per client type:\n * - Confidential clients: HTTP Basic header `Authorization: Basic base64(id:secret)`\n * (client_secret_basic). X does NOT support client_secret_post.\n * - Public clients: `client_id` in the request body, no secret (PKCE only).\n * The HTTP Basic header takes precedence when present. `fromBasic` records whether\n * the credentials arrived via the Basic header so the authenticator can enforce\n * that confidential clients used it (and did not post their secret in the body).\n */\nfunction parseClientCredentials(c: Context, body: Record<string, unknown>): ClientCredentials {\n const basic = /^Basic\\s+(.+)$/i.exec(c.req.header(\"Authorization\") ?? \"\");\n if (basic) {\n try {\n const decoded = Buffer.from(basic[1].trim(), \"base64\").toString(\"utf-8\");\n const sep = decoded.indexOf(\":\");\n if (sep >= 0) {\n return {\n clientId: decodeURIComponent(decoded.slice(0, sep)),\n clientSecret: decodeURIComponent(decoded.slice(sep + 1)),\n fromBasic: true,\n };\n }\n } catch {\n // Malformed Basic header — fall through to body credentials.\n }\n }\n const clientId = typeof body.client_id === \"string\" ? body.client_id : \"\";\n const clientSecret = typeof body.client_secret === \"string\" ? body.client_secret : null;\n return { clientId, clientSecret, fromBasic: false };\n}\n\nfunction s256(verifier: string): string {\n return createHash(\"sha256\").update(verifier).digest(\"base64url\");\n}\n\nasync function parseTokenBody(c: Context): Promise<Record<string, unknown>> {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const rawText = await c.req.text();\n if (contentType.includes(\"application/json\")) {\n try {\n return JSON.parse(rawText) as Record<string, unknown>;\n } catch {\n return {};\n }\n }\n return Object.fromEntries(new URLSearchParams(rawText));\n}\n\nfunction opaqueToken(): string {\n // X access tokens are opaque, long, URL-safe strings.\n return randomBytes(32).toString(\"base64url\");\n}\n\nexport function oauthRoutes({ app, store, baseUrl }: RouteContext): void {\n const xs = getXStore(store);\n\n /**\n * Validate a client and its authentication for the token endpoint. X supports a\n * single client-auth method per client type, and is strict about it:\n * - Confidential clients authenticate with the HTTP Basic Authorization header\n * (client_secret_basic). X does NOT support client_secret_post, so a secret\n * sent in the request body is rejected even when it is correct.\n * - Public clients send client_id in the body, carry no secret, and rely on\n * PKCE (enforced at code redemption).\n * Returns the client on success, or a faithful error tuple on failure.\n */\n function authenticateClient(\n creds: ClientCredentials,\n _body: Record<string, unknown>,\n ): { client: XOAuthClient } | { error: string; description: string; status: 400 | 401 } {\n // A request with neither a Basic header nor a body client_id cannot identify\n // the client at all.\n if (!creds.clientId) {\n return {\n error: \"invalid_request\",\n description: \"A client_id is required. Public clients must include client_id in the request body.\",\n status: 400,\n };\n }\n\n const client = xs.oauthClients.findOneBy(\"client_id\", creds.clientId);\n if (!client) {\n return { error: \"invalid_client\", description: \"Unknown client_id.\", status: 401 };\n }\n\n if (client.client_type === \"confidential\") {\n // Confidential clients MUST authenticate with the HTTP Basic header\n // (client_secret_basic). A secret in the body (client_secret_post) is not a\n // supported method on X and is rejected even when the secret value is\n // correct — this is what lets the emulator reproduce the real-world failure\n // of an app that incorrectly posts its secret in the body.\n if (!creds.fromBasic) {\n return {\n error: \"invalid_client\",\n description: \"Confidential clients must authenticate with HTTP Basic.\",\n status: 401,\n };\n }\n if (!constantTimeSecretEqual(creds.clientSecret ?? \"\", client.client_secret ?? \"\")) {\n return { error: \"invalid_client\", description: \"Invalid client credentials.\", status: 401 };\n }\n } else {\n // Public clients have no secret. Presenting one (in the Basic header or the\n // body) is not a valid public-client request on X.\n if (creds.fromBasic || creds.clientSecret != null) {\n return {\n error: \"invalid_client\",\n description: \"Public clients have no client_secret and must authenticate with PKCE only.\",\n status: 401,\n };\n }\n }\n\n return { client };\n }\n\n // ---------- Authorization page (GET /2/oauth2/authorize) ----------\n\n app.get(\"/2/oauth2/authorize\", (c) => {\n const client_id = c.req.query(\"client_id\") ?? \"\";\n const redirect_uri = c.req.query(\"redirect_uri\") ?? \"\";\n const scope = c.req.query(\"scope\") ?? \"\";\n const state = c.req.query(\"state\") ?? \"\";\n const response_type = c.req.query(\"response_type\") ?? \"\";\n const code_challenge = c.req.query(\"code_challenge\") ?? \"\";\n const code_challenge_method = c.req.query(\"code_challenge_method\") ?? \"\";\n\n const client = xs.oauthClients.findOneBy(\"client_id\", client_id);\n if (!client) {\n return c.html(\n renderErrorPage(\n \"Application not found\",\n `The client_id '${escapeHtml(client_id)}' is not registered.`,\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, client.redirect_uris)) {\n return c.html(\n renderErrorPage(\n \"Redirect URI mismatch\",\n \"The redirect_uri is not registered for this application.\",\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n if (response_type && response_type !== \"code\") {\n return c.html(\n renderErrorPage(\"Unsupported response_type\", \"Only response_type=code is supported.\", SERVICE_LABEL),\n 400,\n );\n }\n // X requires PKCE for the authorization-code flow.\n if (!code_challenge) {\n return c.html(\n renderErrorPage(\n \"PKCE required\",\n \"A code_challenge is required for the authorization code flow.\",\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n if (code_challenge_method.toUpperCase() !== \"S256\") {\n return c.html(\n renderErrorPage(\n \"Unsupported PKCE method\",\n \"code_challenge_method must be S256 for the X authorization code flow.\",\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n\n const requestedScopes = scope.split(/[\\s+]+/).filter(Boolean);\n const unknownScope = requestedScopes.find((s) => !X_SCOPES.includes(s as (typeof X_SCOPES)[number]));\n if (unknownScope) {\n return c.html(\n renderErrorPage(\"Invalid scope\", `The scope '${escapeHtml(unknownScope)}' is not supported.`, SERVICE_LABEL),\n 400,\n );\n }\n\n const users = [...xs.users.all()].sort((a, b) => a.username.localeCompare(b.username));\n const subtitleText = `Authorize <strong>${escapeHtml(client.name)}</strong> to access your X account.`;\n\n const userButtons = users\n .map((u) =>\n renderUserButton({\n letter: (u.name[0] ?? u.username[0] ?? \"?\").toUpperCase(),\n login: `@${u.username}`,\n name: u.name,\n formAction: `${baseUrl}/2/oauth2/authorize/consent`,\n hiddenFields: {\n user_id: u.user_id,\n redirect_uri,\n scope,\n state,\n client_id,\n code_challenge,\n code_challenge_method,\n },\n }),\n )\n .join(\"\\n\");\n\n const body = users.length === 0 ? '<p class=\"empty\">No users in the emulator store.</p>' : userButtons;\n return c.html(renderCardPage(\"Sign in to X\", subtitleText, body, SERVICE_LABEL));\n });\n\n // ---------- Authorize consent (auto-approve, mints the code) ----------\n\n app.post(\"/2/oauth2/authorize/consent\", async (c) => {\n const form = (await c.req.parseBody()) as Record<string, string>;\n const user_id = bodyStr(form.user_id);\n const redirect_uri = bodyStr(form.redirect_uri);\n const scope = bodyStr(form.scope);\n const state = bodyStr(form.state);\n const client_id = bodyStr(form.client_id);\n const code_challenge = bodyStr(form.code_challenge);\n const code_challenge_method = bodyStr(form.code_challenge_method);\n\n const user = xs.users.findOneBy(\"user_id\", user_id);\n if (!user) {\n return c.html(renderErrorPage(\"User not found\", \"The selected user no longer exists.\", SERVICE_LABEL), 400);\n }\n\n const code = randomBytes(24).toString(\"base64url\");\n xs.authCodes.insert({\n code,\n client_id,\n redirect_uri,\n code_challenge,\n code_challenge_method: code_challenge_method || \"S256\",\n scopes: scope.split(/[\\s+]+/).filter(Boolean),\n user_id,\n expires: Date.now() + AUTH_CODE_TTL_MS,\n });\n\n debug(\"x.oauth\", `[authorize] minted code for user ${user_id} client ${client_id}`);\n\n const url = new URL(redirect_uri);\n url.searchParams.set(\"code\", code);\n if (state) url.searchParams.set(\"state\", state);\n return c.redirect(url.toString(), 302);\n });\n\n // ---------- Token endpoint (POST /2/oauth2/token) ----------\n\n app.post(\"/2/oauth2/token\", async (c) => {\n const body = await parseTokenBody(c);\n const grant_type = typeof body.grant_type === \"string\" ? body.grant_type : \"\";\n const creds = parseClientCredentials(c, body);\n\n // client_credentials → app-only BearerToken. Confidential clients only.\n if (grant_type === \"client_credentials\") {\n const auth = authenticateClient(creds, body);\n if (\"error\" in auth) {\n return c.json({ error: auth.error, error_description: auth.description }, auth.status);\n }\n if (auth.client.client_type !== \"confidential\") {\n return c.json(\n {\n error: \"unauthorized_client\",\n error_description: \"Only confidential clients may use the client_credentials grant.\",\n },\n 400,\n );\n }\n const token = opaqueToken();\n const expires = Date.now() + ACCESS_TOKEN_TTL_SECONDS * 1000;\n xs.accessTokens.insert({\n token,\n client_id: auth.client.client_id,\n user_id: null,\n scopes: [],\n app_only: true,\n expires,\n });\n return c.json({\n token_type: \"bearer\",\n access_token: token,\n expires_in: ACCESS_TOKEN_TTL_SECONDS,\n });\n }\n\n if (grant_type === \"authorization_code\") {\n const auth = authenticateClient(creds, body);\n if (\"error\" in auth) {\n return c.json({ error: auth.error, error_description: auth.description }, auth.status);\n }\n const client = auth.client;\n\n const code = typeof body.code === \"string\" ? body.code : \"\";\n const redirect_uri = typeof body.redirect_uri === \"string\" ? body.redirect_uri : \"\";\n const code_verifier = typeof body.code_verifier === \"string\" ? body.code_verifier : \"\";\n\n const codeRow = xs.authCodes.findOneBy(\"code\", code);\n if (!codeRow || codeRow.expires < Date.now()) {\n if (codeRow) xs.authCodes.delete(codeRow.id);\n return c.json(\n { error: \"invalid_grant\", error_description: \"The authorization code is invalid or expired.\" },\n 400,\n );\n }\n if (codeRow.client_id !== client.client_id) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"The authorization code was issued to another client.\" },\n 400,\n );\n }\n if (codeRow.redirect_uri !== redirect_uri) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"The redirect_uri does not match the authorization request.\" },\n 400,\n );\n }\n // PKCE: base64url(sha256(code_verifier)) must equal the stored S256 challenge.\n if (!code_verifier) {\n return c.json({ error: \"invalid_request\", error_description: \"A code_verifier is required (PKCE).\" }, 400);\n }\n if (s256(code_verifier) !== codeRow.code_challenge) {\n return c.json({ error: \"invalid_grant\", error_description: \"PKCE verification failed.\" }, 400);\n }\n\n // Single-use code.\n xs.authCodes.delete(codeRow.id);\n\n const scopes = codeRow.scopes;\n const token = opaqueToken();\n const expires = Date.now() + ACCESS_TOKEN_TTL_SECONDS * 1000;\n xs.accessTokens.insert({\n token,\n client_id: client.client_id,\n user_id: codeRow.user_id,\n scopes,\n app_only: false,\n expires,\n });\n\n const response: Record<string, unknown> = {\n token_type: \"bearer\",\n access_token: token,\n scope: scopes.join(\" \"),\n expires_in: ACCESS_TOKEN_TTL_SECONDS,\n };\n\n // A refresh token is only issued when offline.access was granted.\n if (scopes.includes(\"offline.access\")) {\n const refreshToken = opaqueToken();\n xs.refreshTokens.insert({\n token: refreshToken,\n client_id: client.client_id,\n user_id: codeRow.user_id,\n scopes,\n });\n response.refresh_token = refreshToken;\n }\n\n debug(\"x.oauth\", `[token] authorization_code → user ${codeRow.user_id} scopes ${scopes.join(\",\")}`);\n return c.json(response);\n }\n\n if (grant_type === \"refresh_token\") {\n const auth = authenticateClient(creds, body);\n if (\"error\" in auth) {\n return c.json({ error: auth.error, error_description: auth.description }, auth.status);\n }\n const client = auth.client;\n\n const refresh_token = typeof body.refresh_token === \"string\" ? body.refresh_token : \"\";\n const row = xs.refreshTokens.findOneBy(\"token\", refresh_token);\n if (!row || row.client_id !== client.client_id) {\n return c.json({ error: \"invalid_grant\", error_description: \"The refresh token is invalid.\" }, 400);\n }\n // Refresh requires that offline.access was granted on the original token.\n if (!row.scopes.includes(\"offline.access\")) {\n return c.json(\n { error: \"invalid_grant\", error_description: \"The refresh token does not have offline.access.\" },\n 400,\n );\n }\n\n const token = opaqueToken();\n const expires = Date.now() + ACCESS_TOKEN_TTL_SECONDS * 1000;\n xs.accessTokens.insert({\n token,\n client_id: client.client_id,\n user_id: row.user_id,\n scopes: row.scopes,\n app_only: false,\n expires,\n });\n\n // Rotate the refresh token, as X does.\n const newRefresh = opaqueToken();\n xs.refreshTokens.update(row.id, { token: newRefresh });\n\n return c.json({\n token_type: \"bearer\",\n access_token: token,\n scope: row.scopes.join(\" \"),\n expires_in: ACCESS_TOKEN_TTL_SECONDS,\n refresh_token: newRefresh,\n });\n }\n\n return c.json(\n {\n error: \"unsupported_grant_type\",\n error_description: \"grant_type must be authorization_code, refresh_token, or client_credentials.\",\n },\n 400,\n );\n });\n\n // ---------- Token revocation (POST /2/oauth2/revoke) ----------\n\n app.post(\"/2/oauth2/revoke\", async (c) => {\n const body = await parseTokenBody(c);\n const creds = parseClientCredentials(c, body);\n const auth = authenticateClient(creds, body);\n if (\"error\" in auth) {\n return c.json({ error: auth.error, error_description: auth.description }, auth.status);\n }\n\n const token = typeof body.token === \"string\" ? body.token : \"\";\n if (token) {\n const access = xs.accessTokens.findOneBy(\"token\", token);\n if (access && access.client_id === auth.client.client_id) {\n xs.accessTokens.delete(access.id);\n }\n const refresh = xs.refreshTokens.findOneBy(\"token\", token);\n if (refresh && refresh.client_id === auth.client.client_id) {\n xs.refreshTokens.delete(refresh.id);\n }\n }\n // X returns { revoked: true } on success.\n return c.json({ revoked: true });\n });\n}\n","export interface Entity {\n id: number;\n created_at: string;\n updated_at: string;\n}\n\nexport type InsertInput<T extends Entity> = Omit<T, \"id\" | \"created_at\" | \"updated_at\"> & { id?: number };\n\nexport type FilterFn<T> = (item: T) => boolean;\nexport type SortFn<T> = (a: T, b: T) => number;\n\nexport interface QueryOptions<T> {\n filter?: FilterFn<T>;\n sort?: SortFn<T>;\n page?: number;\n per_page?: number;\n}\n\nexport interface PaginatedResult<T> {\n items: T[];\n total_count: number;\n page: number;\n per_page: number;\n has_next: boolean;\n has_prev: boolean;\n}\n\nexport interface CollectionSnapshot<T extends Entity = Entity> {\n items: T[];\n autoId: number;\n indexFields: string[];\n}\n\nexport interface StoreSnapshot {\n collections: Record<string, CollectionSnapshot>;\n data: Record<string, unknown>;\n}\n\nexport function serializeValue(value: unknown): unknown {\n if (value instanceof Map) {\n return { __type: \"Map\" as const, entries: [...value.entries()].map(([k, v]) => [k, serializeValue(v)]) };\n }\n if (value instanceof Set) {\n return { __type: \"Set\" as const, values: [...value.values()] };\n }\n return value;\n}\n\nexport function deserializeValue(value: unknown): unknown {\n if (value !== null && typeof value === \"object\" && \"__type\" in value) {\n const tagged = value as Record<string, unknown>;\n if (tagged.__type === \"Map\") {\n const entries = tagged.entries as [unknown, unknown][];\n return new Map(entries.map(([k, v]) => [k, deserializeValue(v)]));\n }\n if (tagged.__type === \"Set\") {\n return new Set(tagged.values as unknown[]);\n }\n }\n return value;\n}\n\nexport class Collection<T extends Entity> {\n private items = new Map<number, T>();\n private indexes = new Map<string, Map<string | number, Set<number>>>();\n private autoId = 1;\n readonly fieldNames: string[];\n\n constructor(private indexFields: (keyof T)[] = []) {\n this.fieldNames = indexFields.map(String).sort();\n for (const field of indexFields) {\n this.indexes.set(String(field), new Map());\n }\n }\n\n private addToIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n if (!indexMap.has(key)) {\n indexMap.set(key, new Set());\n }\n indexMap.get(key)!.add(item.id);\n }\n }\n\n private removeFromIndex(item: T): void {\n for (const field of this.indexFields) {\n const value = item[field];\n if (value === undefined || value === null) continue;\n const indexMap = this.indexes.get(String(field))!;\n const key = String(value);\n indexMap.get(key)?.delete(item.id);\n }\n }\n\n insert(data: InsertInput<T>): T {\n const now = new Date().toISOString();\n const explicitId = data.id != null && data.id > 0 ? data.id : undefined;\n const id = explicitId ?? this.autoId++;\n if (id >= this.autoId) {\n this.autoId = id + 1;\n }\n const item = {\n ...data,\n id,\n created_at: now,\n updated_at: now,\n } as unknown as T;\n this.items.set(id, item);\n this.addToIndex(item);\n return item;\n }\n\n get(id: number): T | undefined {\n return this.items.get(id);\n }\n\n findBy(field: keyof T, value: T[keyof T] | string | number): T[] {\n if (this.indexes.has(String(field))) {\n const ids = this.indexes.get(String(field))!.get(String(value));\n if (!ids) return [];\n return Array.from(ids)\n .map((id) => this.items.get(id)!)\n .filter(Boolean);\n }\n return this.all().filter((item) => item[field] === value);\n }\n\n findOneBy(field: keyof T, value: T[keyof T] | string | number): T | undefined {\n return this.findBy(field, value)[0];\n }\n\n update(id: number, data: Partial<T>): T | undefined {\n const existing = this.items.get(id);\n if (!existing) return undefined;\n this.removeFromIndex(existing);\n const updated = {\n ...existing,\n ...data,\n id,\n updated_at: new Date().toISOString(),\n } as T;\n this.items.set(id, updated);\n this.addToIndex(updated);\n return updated;\n }\n\n delete(id: number): boolean {\n const existing = this.items.get(id);\n if (!existing) return false;\n this.removeFromIndex(existing);\n return this.items.delete(id);\n }\n\n all(): T[] {\n return Array.from(this.items.values());\n }\n\n query(options: QueryOptions<T> = {}): PaginatedResult<T> {\n let results = this.all();\n\n if (options.filter) {\n results = results.filter(options.filter);\n }\n\n const total_count = results.length;\n\n if (options.sort) {\n results.sort(options.sort);\n }\n\n const page = options.page ?? 1;\n const per_page = Math.min(options.per_page ?? 30, 100);\n const start = (page - 1) * per_page;\n const paged = results.slice(start, start + per_page);\n\n return {\n items: paged,\n total_count,\n page,\n per_page,\n has_next: start + per_page < total_count,\n has_prev: page > 1,\n };\n }\n\n count(filter?: FilterFn<T>): number {\n if (!filter) return this.items.size;\n return this.all().filter(filter).length;\n }\n\n clear(): void {\n this.items.clear();\n for (const indexMap of this.indexes.values()) {\n indexMap.clear();\n }\n this.autoId = 1;\n }\n\n snapshot(): CollectionSnapshot<T> {\n return {\n items: this.all(),\n autoId: this.autoId,\n indexFields: this.fieldNames,\n };\n }\n\n restore(snap: CollectionSnapshot<T>): void {\n this.clear();\n this.autoId = snap.autoId;\n for (const item of snap.items) {\n this.items.set(item.id, item);\n this.addToIndex(item);\n }\n }\n}\n\nexport class Store {\n private collections = new Map<string, Collection<any>>();\n private _data = new Map<string, unknown>();\n\n collection<T extends Entity>(name: string, indexFields: (keyof T)[] = []): Collection<T> {\n const existing = this.collections.get(name);\n if (existing) {\n if (indexFields.length > 0) {\n const requested = indexFields.map(String).sort();\n if (existing.fieldNames.length !== requested.length || existing.fieldNames.some((f, i) => f !== requested[i])) {\n throw new Error(\n `Collection \"${name}\" already exists with indexes [${existing.fieldNames}] but was requested with [${requested}]`,\n );\n }\n }\n return existing as Collection<T>;\n }\n const col = new Collection<T>(indexFields);\n this.collections.set(name, col);\n return col;\n }\n\n getData<V>(key: string): V | undefined {\n return this._data.get(key) as V | undefined;\n }\n\n setData<V>(key: string, value: V): void {\n this._data.set(key, value);\n }\n\n reset(): void {\n for (const collection of this.collections.values()) {\n collection.clear();\n }\n this._data.clear();\n }\n\n snapshot(): StoreSnapshot {\n const collections: Record<string, CollectionSnapshot> = {};\n for (const [name, col] of this.collections) {\n collections[name] = col.snapshot();\n }\n const data: Record<string, unknown> = {};\n for (const [key, value] of this._data) {\n data[key] = serializeValue(value);\n }\n return { collections, data };\n }\n\n restore(snap: StoreSnapshot): void {\n const snapshotNames = new Set(Object.keys(snap.collections));\n for (const name of this.collections.keys()) {\n if (!snapshotNames.has(name)) {\n this.collections.delete(name);\n }\n }\n for (const [name, colSnap] of Object.entries(snap.collections)) {\n const indexFields = colSnap.indexFields as (keyof Entity)[];\n const col = this.collection(name, indexFields);\n col.restore(colSnap as CollectionSnapshot<any>);\n }\n this._data.clear();\n for (const [key, value] of Object.entries(snap.data)) {\n this._data.set(key, deserializeValue(value));\n }\n }\n}\n","import { createServer as createNodeServer, type IncomingMessage, type Server, type ServerResponse } from \"node:http\";\n\ntype BodyInit = ConstructorParameters<typeof Response>[0];\ntype HeadersInit = ConstructorParameters<typeof Headers>[0];\ntype FormDataEntryValue = string | File;\n\nexport type ContentfulStatusCode = number;\nexport type Next = () => Promise<Response | void>;\n\ntype VariablesOf<E> = unknown extends E\n ? Record<string, any>\n : E extends { Variables: infer V }\n ? V\n : Record<string, any>;\ntype HandlerResult = Response | void | Promise<Response | void>;\n\nexport type Handler<E = unknown, P extends string = string> = (c: Context<E, P>, next: Next) => HandlerResult;\nexport type MiddlewareHandler<E = unknown> = Handler<E>;\nexport type ErrorHandler<E = unknown> = (err: unknown, c: Context<E>) => Response | Promise<Response>;\nexport type FetchHandler = (request: Request) => Response | Promise<Response>;\n\ninterface CompiledPath {\n pattern: string;\n regex: RegExp;\n paramNames: string[];\n}\n\ninterface Route<E> {\n method: string;\n compiled: CompiledPath;\n handlers: Handler<E>[];\n}\n\ninterface MatchedHandler<E> {\n handler: Handler<E>;\n params: Record<string, string>;\n}\n\nexport interface ServeOptions {\n fetch: FetchHandler;\n port?: number;\n hostname?: string;\n}\n\nexport interface CorsOptions {\n origin?: string;\n allowMethods?: string[];\n allowHeaders?: string[];\n credentials?: boolean;\n maxAge?: number;\n}\n\nexport class HonoRequest {\n readonly raw: Request;\n readonly url: string;\n readonly method: string;\n readonly path: string;\n /** The matched route pattern (e.g. /repos/:owner/:repo), when a route matched. */\n readonly routePath?: string;\n\n constructor(\n request: Request,\n private readonly params: Record<string, string>,\n routePath?: string,\n ) {\n this.raw = request;\n this.url = request.url;\n this.method = request.method;\n this.path = new URL(request.url).pathname;\n this.routePath = routePath;\n }\n\n header(): Record<string, string>;\n header(name: string): string | undefined;\n header(name?: string): Record<string, string> | string | undefined {\n if (name) return this.raw.headers.get(name) ?? undefined;\n const headers: Record<string, string> = {};\n this.raw.headers.forEach((value, key) => {\n headers[key] = value;\n });\n return headers;\n }\n\n query(name: string): string | undefined {\n return new URL(this.url).searchParams.get(name) ?? undefined;\n }\n\n queries(name: string): string[] | undefined {\n const values = new URL(this.url).searchParams.getAll(name);\n return values.length > 0 ? values : undefined;\n }\n\n param(): Record<string, string>;\n param(name: string): string;\n param(name?: string): Record<string, string> | string {\n if (!name) return { ...this.params };\n return this.params[name] ?? \"\";\n }\n\n json<T = any>(): Promise<T> {\n return this.raw.json() as Promise<T>;\n }\n\n text(): Promise<string> {\n return this.raw.text();\n }\n\n arrayBuffer(): Promise<ArrayBuffer> {\n return this.raw.arrayBuffer();\n }\n\n async parseBody(): Promise<Record<string, FormDataEntryValue | FormDataEntryValue[]>> {\n const contentType = this.header(\"Content-Type\") ?? \"\";\n if (contentType.includes(\"multipart/form-data\")) {\n return formDataToObject(await this.raw.formData());\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params = new URLSearchParams(await this.raw.text());\n const out: Record<string, string | string[]> = {};\n for (const [key, value] of params) {\n appendBodyValue(out, key, value);\n }\n return out;\n }\n if (contentType.includes(\"application/json\")) {\n const body = await this.raw.json().catch(() => ({}));\n return body && typeof body === \"object\" && !Array.isArray(body)\n ? (body as Record<string, FormDataEntryValue | FormDataEntryValue[]>)\n : {};\n }\n return {};\n }\n}\n\nexport class Context<E = unknown, _P extends string = string> {\n readonly req: HonoRequest;\n private readonly vars = new Map<string, unknown>();\n private readonly responseHeaders = new Headers();\n private responseStatus = 200;\n\n constructor(\n request: Request,\n params: Record<string, string>,\n private readonly notFoundHandler: (c: Context<E>) => Response | Promise<Response>,\n routePath?: string,\n ) {\n this.req = new HonoRequest(request, params, routePath);\n }\n\n get<K extends keyof VariablesOf<E> & string>(key: K): VariablesOf<E>[K] | undefined {\n return this.vars.get(key) as VariablesOf<E>[K] | undefined;\n }\n\n set<K extends keyof VariablesOf<E> & string>(key: K, value: VariablesOf<E>[K]): void {\n this.vars.set(key, value);\n }\n\n header(name: string, value: string): void {\n this.responseHeaders.set(name, value);\n }\n\n status(status: number): void {\n this.responseStatus = status;\n }\n\n json(data: unknown, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(JSON.stringify(data), status, defaultContentType(headers, \"application/json; charset=UTF-8\"));\n }\n\n text(text: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(text, status, defaultContentType(headers, \"text/plain; charset=UTF-8\"));\n }\n\n html(html: string, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(html, status, defaultContentType(headers, \"text/html; charset=UTF-8\"));\n }\n\n body(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n return this.response(body, status, headers);\n }\n\n redirect(location: string, status: ContentfulStatusCode = 302): Response {\n return this.response(null, status, { Location: location });\n }\n\n notFound(): Response | Promise<Response> {\n return this.notFoundHandler(this);\n }\n\n finalize(response: Response): Response {\n if (!hasHeaders(this.responseHeaders)) return response;\n const headers = new Headers(response.headers);\n this.responseHeaders.forEach((value, key) => {\n headers.set(key, value);\n });\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n });\n }\n\n private response(body: BodyInit | null, status?: ContentfulStatusCode, headers?: HeadersInit): Response {\n const merged = new Headers(headers);\n this.responseHeaders.forEach((value, key) => {\n merged.set(key, value);\n });\n return new Response(body, {\n status: status ?? this.responseStatus,\n headers: merged,\n });\n }\n}\n\nexport class Hono<E = unknown> {\n private readonly middleware: Route<E>[] = [];\n private readonly routes: Route<E>[] = [];\n private errorHandler: ErrorHandler<E> = (err) => {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return new Response(message, { status: 500 });\n };\n private notFoundHandler: (c: Context<E>) => Response | Promise<Response> = () =>\n new Response(\"404 Not Found\", { status: 404 });\n\n use<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this;\n use(...handlers: Handler<E>[]): this;\n use<P extends string = string>(pathOrHandler: string | Handler<E>, ...handlers: Handler<E, P>[]): this {\n if (typeof pathOrHandler === \"string\") {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(pathOrHandler), handlers: handlers as Handler<E>[] });\n } else {\n this.middleware.push({ method: \"ALL\", compiled: compilePath(\"*\"), handlers: [pathOrHandler, ...handlers] });\n }\n return this;\n }\n\n on<P extends string = string>(method: string, path: string, ...handlers: Handler<E, P>[]): this {\n this.routes.push({ method: method.toUpperCase(), compiled: compilePath(path), handlers: handlers as Handler<E>[] });\n return this;\n }\n\n get<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"GET\", path, ...handlers);\n }\n\n post<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"POST\", path, ...handlers);\n }\n\n put<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PUT\", path, ...handlers);\n }\n\n patch<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"PATCH\", path, ...handlers);\n }\n\n delete<P extends string = string>(path: string, ...handlers: Handler<E, P>[]): this {\n return this.on(\"DELETE\", path, ...handlers);\n }\n\n onError(handler: ErrorHandler<E>): this {\n this.errorHandler = handler;\n return this;\n }\n\n notFound(handler: (c: Context<E>) => Response | Promise<Response>): this {\n this.notFoundHandler = handler;\n return this;\n }\n\n async request(input: string | Request, init?: RequestInit): Promise<Response> {\n if (input instanceof Request) return this.fetch(input);\n const url = input.startsWith(\"/\") ? `http://localhost${input}` : input;\n return this.fetch(new Request(url, init));\n }\n\n fetch = async (request: Request): Promise<Response> => {\n const url = new URL(request.url);\n const path = url.pathname;\n const method = request.method.toUpperCase();\n const matched = this.match(method, path);\n const context = new Context<E>(request, matched.params, this.notFoundHandler, matched.routePattern);\n\n try {\n const response = await this.dispatch(context, matched.handlers);\n return context.finalize(response ?? (await this.notFoundHandler(context)));\n } catch (err) {\n return context.finalize(await this.errorHandler(err, context));\n }\n };\n\n private match(\n method: string,\n path: string,\n ): { handlers: MatchedHandler<E>[]; params: Record<string, string>; routePattern?: string } {\n const handlers: MatchedHandler<E>[] = [];\n const params: Record<string, string> = {};\n\n for (const route of this.middleware) {\n const match = matchPath(route.compiled, path);\n if (!match) continue;\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n const route =\n this.routes.find((candidate) => candidate.method === method && matchPath(candidate.compiled, path) != null) ??\n (method === \"HEAD\"\n ? this.routes.find((candidate) => candidate.method === \"GET\" && matchPath(candidate.compiled, path) != null)\n : undefined);\n\n if (route) {\n const match = matchPath(route.compiled, path) ?? {};\n Object.assign(params, match);\n for (const handler of route.handlers) {\n handlers.push({ handler, params: match });\n }\n }\n\n return { handlers, params, routePattern: route?.compiled.pattern };\n }\n\n private async dispatch(context: Context<E>, handlers: MatchedHandler<E>[]): Promise<Response | void> {\n let index = -1;\n const run = async (nextIndex: number): Promise<Response | void> => {\n if (nextIndex <= index) throw new Error(\"next() called multiple times\");\n index = nextIndex;\n const matched = handlers[nextIndex];\n if (!matched) return undefined;\n\n const originalParams = context.req.param();\n Object.assign(originalParams, matched.params);\n\n let nextResponse: Response | void = undefined;\n let nextCalled = false;\n const next: Next = async () => {\n nextCalled = true;\n nextResponse = await run(nextIndex + 1);\n return nextResponse;\n };\n\n const response = await matched.handler(context, next);\n if (response instanceof Response) return response;\n if (nextCalled) return nextResponse;\n return response;\n };\n\n return run(0);\n }\n}\n\nexport function cors(options: CorsOptions = {}): MiddlewareHandler {\n const origin = options.origin ?? \"*\";\n const allowMethods = options.allowMethods ?? [\"GET\", \"HEAD\", \"PUT\", \"POST\", \"DELETE\", \"PATCH\", \"OPTIONS\"];\n\n return async (c, next) => {\n c.header(\"Access-Control-Allow-Origin\", origin);\n if (options.credentials) c.header(\"Access-Control-Allow-Credentials\", \"true\");\n\n if (c.req.method.toUpperCase() === \"OPTIONS\") {\n c.header(\"Access-Control-Allow-Methods\", allowMethods.join(\",\"));\n const allowHeaders = options.allowHeaders?.join(\",\") ?? c.req.header(\"Access-Control-Request-Headers\");\n if (allowHeaders) c.header(\"Access-Control-Allow-Headers\", allowHeaders);\n if (options.maxAge != null) c.header(\"Access-Control-Max-Age\", String(options.maxAge));\n return c.body(null, 204);\n }\n\n await next();\n };\n}\n\nexport function serve(options: ServeOptions): Server {\n const port = options.port ?? 3000;\n const server = createNodeServer(async (req, res) => {\n try {\n const request = nodeRequestToFetchRequest(req);\n const response = await options.fetch(request);\n await writeFetchResponse(res, response, req.method?.toUpperCase() === \"HEAD\");\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n res.statusCode = 500;\n res.setHeader(\"Content-Type\", \"text/plain; charset=UTF-8\");\n res.end(message);\n }\n });\n server.listen(port, options.hostname);\n return server;\n}\n\nfunction compilePath(pattern: string): CompiledPath {\n if (pattern === \"*\" || pattern === \"/*\") {\n return { pattern, regex: /^.*$/, paramNames: [] };\n }\n\n const paramNames: string[] = [];\n let source = \"^\";\n for (let i = 0; i < pattern.length; i++) {\n const char = pattern[i];\n if (char !== \":\") {\n source += escapeRegex(char);\n continue;\n }\n\n let name = \"\";\n i++;\n while (i < pattern.length && /[A-Za-z0-9_]/.test(pattern[i])) {\n name += pattern[i];\n i++;\n }\n i--;\n paramNames.push(name);\n\n if (pattern[i + 1] === \"{\") {\n const close = pattern.indexOf(\"}\", i + 2);\n if (close < 0) throw new Error(`Invalid route pattern: ${pattern}`);\n const expr = pattern.slice(i + 2, close);\n source += `(${expr})`;\n i = close;\n } else {\n source += \"([^/]+)\";\n }\n }\n source += \"$\";\n return { pattern, regex: new RegExp(source), paramNames };\n}\n\nfunction matchPath(compiled: CompiledPath, path: string): Record<string, string> | null {\n const match = compiled.regex.exec(path);\n if (!match) return null;\n const params: Record<string, string> = {};\n for (let i = 0; i < compiled.paramNames.length; i++) {\n params[compiled.paramNames[i]] = decodePathParam(match[i + 1] ?? \"\");\n }\n return params;\n}\n\nfunction decodePathParam(value: string): string {\n try {\n return decodeURIComponent(value);\n } catch {\n return value;\n }\n}\n\nfunction escapeRegex(value: string): string {\n return value.replace(/[|\\\\{}()[\\]^$+*?.]/g, \"\\\\$&\");\n}\n\nfunction hasHeaders(headers: Headers): boolean {\n for (const _ of headers) return true;\n return false;\n}\n\nfunction defaultContentType(headers: HeadersInit | undefined, contentType: string): Headers {\n const out = new Headers(headers);\n if (!out.has(\"Content-Type\")) {\n out.set(\"Content-Type\", contentType);\n }\n return out;\n}\n\nfunction formDataToObject(formData: FormData): Record<string, FormDataEntryValue | FormDataEntryValue[]> {\n const out: Record<string, FormDataEntryValue | FormDataEntryValue[]> = {};\n for (const [key, value] of formData) {\n appendBodyValue(out, key, value);\n }\n return out;\n}\n\nfunction appendBodyValue<T>(target: Record<string, T | T[]>, key: string, value: T): void {\n const existing = target[key];\n if (existing === undefined) {\n target[key] = value;\n } else if (Array.isArray(existing)) {\n existing.push(value);\n } else {\n target[key] = [existing, value];\n }\n}\n\nfunction nodeRequestToFetchRequest(req: IncomingMessage): Request {\n const host = req.headers.host ?? \"localhost\";\n const url = new URL(req.url ?? \"/\", `http://${host}`);\n const headers = new Headers();\n for (const [key, value] of Object.entries(req.headers)) {\n if (value == null) continue;\n if (Array.isArray(value)) {\n for (const item of value) headers.append(key, item);\n } else {\n headers.set(key, value);\n }\n }\n\n const method = req.method ?? \"GET\";\n const hasBody = method !== \"GET\" && method !== \"HEAD\";\n return new Request(url.toString(), {\n method,\n headers,\n body: hasBody ? (req as unknown as BodyInit) : undefined,\n duplex: \"half\",\n } as RequestInit & { duplex: string });\n}\n\nasync function writeFetchResponse(res: ServerResponse, response: Response, headOnly: boolean): Promise<void> {\n res.statusCode = response.status;\n res.statusMessage = response.statusText;\n\n const headersWithCookies = response.headers as Headers & { getSetCookie?: () => string[] };\n const cookies = headersWithCookies.getSetCookie?.();\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() === \"set-cookie\" && cookies && cookies.length > 0) return;\n res.setHeader(key, value);\n });\n if (cookies && cookies.length > 0) {\n res.setHeader(\"Set-Cookie\", cookies);\n }\n\n if (headOnly || !response.body) {\n res.end();\n return;\n }\n\n const reader = response.body.getReader();\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!res.write(value)) {\n await new Promise<void>((resolve) => res.once(\"drain\", resolve));\n }\n }\n res.end();\n } catch (err) {\n res.destroy(err instanceof Error ? err : undefined);\n }\n}\n","import { createHmac } from \"crypto\";\n\nexport interface WebhookSubscription {\n id: number;\n url: string;\n events: string[];\n active: boolean;\n secret?: string;\n owner: string;\n repo?: string;\n}\n\nexport interface WebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n payload: unknown;\n status_code: number | null;\n delivered_at: string;\n duration: number | null;\n success: boolean;\n}\n\nconst MAX_DELIVERIES = 1000;\n\nexport class WebhookDispatcher {\n private subscriptions: WebhookSubscription[] = [];\n private deliveries: WebhookDelivery[] = [];\n private subscriptionIdCounter = 1;\n private deliveryIdCounter = 1;\n\n register(sub: Omit<WebhookSubscription, \"id\"> & { id?: number }): WebhookSubscription {\n const { id: explicitId, ...rest } = sub;\n const id = explicitId !== undefined ? explicitId : this.subscriptionIdCounter++;\n if (id >= this.subscriptionIdCounter) {\n this.subscriptionIdCounter = id + 1;\n }\n const subscription: WebhookSubscription = { ...rest, id };\n this.subscriptions.push(subscription);\n return subscription;\n }\n\n unregister(id: number): boolean {\n const idx = this.subscriptions.findIndex((s) => s.id === id);\n if (idx === -1) return false;\n this.subscriptions.splice(idx, 1);\n return true;\n }\n\n getSubscription(id: number): WebhookSubscription | undefined {\n return this.subscriptions.find((s) => s.id === id);\n }\n\n getSubscriptions(owner?: string, repo?: string): WebhookSubscription[] {\n return this.subscriptions.filter((s) => {\n if (owner && s.owner !== owner) return false;\n if (repo !== undefined && s.repo !== repo) return false;\n return true;\n });\n }\n\n updateSubscription(\n id: number,\n data: Partial<Pick<WebhookSubscription, \"url\" | \"events\" | \"active\" | \"secret\">>,\n ): WebhookSubscription | undefined {\n const sub = this.subscriptions.find((s) => s.id === id);\n if (!sub) return undefined;\n Object.assign(sub, data);\n return sub;\n }\n\n async dispatch(\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> {\n const matchingSubs = this.subscriptions.filter((s) => {\n if (!s.active) return false;\n if (s.owner !== owner) return false;\n if (repo !== undefined) {\n if (s.repo !== repo) return false;\n } else if (s.repo !== undefined) {\n return false;\n }\n return event === \"ping\" || s.events.includes(\"*\") || s.events.includes(event);\n });\n\n for (const sub of matchingSubs) {\n const delivery: WebhookDelivery = {\n id: this.deliveryIdCounter++,\n hook_id: sub.id,\n event,\n action,\n payload,\n status_code: null,\n delivered_at: new Date().toISOString(),\n duration: null,\n success: false,\n };\n\n const body = JSON.stringify(payload);\n\n const signatureHeaders: Record<string, string> = {};\n if (sub.secret) {\n const hmac = createHmac(\"sha256\", sub.secret).update(body).digest(\"hex\");\n signatureHeaders[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n const start = Date.now();\n const response = await fetch(sub.url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(delivery.id),\n ...signatureHeaders,\n },\n body,\n signal: AbortSignal.timeout(10000),\n });\n delivery.duration = Date.now() - start;\n delivery.status_code = response.status;\n delivery.success = response.ok;\n } catch {\n delivery.duration = 0;\n delivery.success = false;\n }\n\n this.deliveries.push(delivery);\n if (this.deliveries.length > MAX_DELIVERIES) {\n this.deliveries.splice(0, this.deliveries.length - MAX_DELIVERIES);\n }\n }\n }\n\n getDeliveries(hookId?: number): WebhookDelivery[] {\n if (hookId !== undefined) {\n return this.deliveries.filter((d) => d.hook_id === hookId);\n }\n return [...this.deliveries];\n }\n\n clear(): void {\n this.subscriptions.length = 0;\n this.deliveries.length = 0;\n this.subscriptionIdCounter = 1;\n this.deliveryIdCounter = 1;\n }\n}\n","import type { Context, ContentfulStatusCode, ErrorHandler, MiddlewareHandler } from \"../http.js\";\n\nconst DEFAULT_DOCS_URL = \"https://emulate.dev\";\n\nfunction getDocsUrl(c: Context): string {\n return (c.get(\"docsUrl\") as string | undefined) ?? DEFAULT_DOCS_URL;\n}\n\nfunction errorStatus(err: unknown): number {\n if (err && typeof err === \"object\" && \"status\" in err) {\n const s = (err as { status: unknown }).status;\n if (typeof s === \"number\" && Number.isFinite(s)) return s;\n }\n return 500;\n}\n\n/**\n * Use with `app.onError(...)`. Route handlers throw to the app error handler.\n */\nexport function createApiErrorHandler(documentationUrl?: string): ErrorHandler {\n return (err, c) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n const status = errorStatus(err);\n const message = err instanceof Error ? err.message : \"Internal Server Error\";\n return c.json(\n {\n message,\n documentation_url: getDocsUrl(c),\n },\n status as ContentfulStatusCode,\n );\n };\n}\n\n/** Sets `docsUrl` on the context for successful responses; register `createApiErrorHandler` for thrown `ApiError`s. */\nexport function createErrorHandler(documentationUrl?: string): MiddlewareHandler {\n return async (c, next) => {\n if (documentationUrl) {\n c.set(\"docsUrl\", documentationUrl);\n }\n await next();\n };\n}\n\nexport const errorHandler: MiddlewareHandler = createErrorHandler();\n\nexport class ApiError extends Error {\n constructor(\n public status: number,\n message: string,\n public errors?: Array<{ resource: string; field: string; code: string }>,\n ) {\n super(message);\n this.name = \"ApiError\";\n }\n}\n\nexport function notFound(resource?: string): ApiError {\n return new ApiError(404, resource ? `${resource} not found` : \"Not Found\");\n}\n\nexport function validationError(message: string, errors?: ApiError[\"errors\"]): ApiError {\n return new ApiError(422, message, errors);\n}\n\nexport function unauthorized(): ApiError {\n return new ApiError(401, \"Requires authentication\");\n}\n\nexport function forbidden(): ApiError {\n return new ApiError(403, \"Forbidden\");\n}\n\nexport async function parseJsonBody(c: Context): Promise<Record<string, unknown>> {\n try {\n const body = await c.req.json();\n if (body && typeof body === \"object\" && !Array.isArray(body)) {\n return body as Record<string, unknown>;\n }\n return {};\n } catch {\n throw new ApiError(400, \"Problems parsing JSON\");\n }\n}\n","import type { Context, Next } from \"../http.js\";\nimport { jwtVerify, importPKCS8 } from \"jose\";\nimport { debug } from \"../debug.js\";\n\nexport interface AuthUser {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport interface AuthApp {\n appId: number;\n slug: string;\n name: string;\n}\n\nexport interface AuthInstallation {\n installationId: number;\n appId: number;\n permissions: Record<string, string>;\n repositoryIds: number[];\n repositorySelection: \"all\" | \"selected\";\n}\n\nexport type TokenMap = Map<string, AuthUser>;\n\nexport interface TokenEntry {\n token: string;\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function serializeTokenMap(tokenMap: TokenMap): TokenEntry[] {\n return [...tokenMap.entries()].map(([token, user]) => ({\n token,\n login: user.login,\n id: user.id,\n scopes: user.scopes,\n }));\n}\n\nexport function restoreTokenMap(tokenMap: TokenMap, tokens: TokenEntry[]): void {\n tokenMap.clear();\n for (const t of tokens) {\n tokenMap.set(t.token, { login: t.login, id: t.id, scopes: t.scopes });\n }\n}\n\nexport type AppEnv = {\n Variables: {\n authUser?: AuthUser;\n authApp?: AuthApp;\n authToken?: string;\n authScopes?: string[];\n docsUrl?: string;\n /** Correlation id for the active request, set by the ledger middleware. */\n correlationId?: string;\n /** Provider operation id a handler can advertise for the ledger. */\n operationId?: string;\n /** Side effects a handler records onto the active request's ledger entry. */\n ledgerEffects?: import(\"../ledger.js\").LedgerSideEffect[];\n };\n};\n\nexport interface AppKeyResolver {\n (appId: number): { privateKey: string; slug: string; name: string } | null;\n}\n\nexport interface AuthFallback {\n login: string;\n id: number;\n scopes: string[];\n}\n\nexport function authMiddleware(tokens: TokenMap, appKeyResolver?: AppKeyResolver, fallbackUser?: AuthFallback) {\n return async (c: Context, next: Next) => {\n const authHeader = c.req.header(\"Authorization\");\n if (authHeader) {\n const token = authHeader.replace(/^(Bearer|token)\\s+/i, \"\").trim();\n\n if (token.startsWith(\"eyJ\") && appKeyResolver) {\n try {\n const [, payloadB64] = token.split(\".\");\n const payload = JSON.parse(Buffer.from(payloadB64, \"base64url\").toString());\n const appId = typeof payload.iss === \"string\" ? parseInt(payload.iss, 10) : payload.iss;\n\n if (typeof appId === \"number\" && !isNaN(appId)) {\n const appInfo = appKeyResolver(appId);\n if (appInfo) {\n const key = await importPKCS8(appInfo.privateKey, \"RS256\");\n await jwtVerify(token, key, { algorithms: [\"RS256\"] });\n c.set(\"authApp\", {\n appId,\n slug: appInfo.slug,\n name: appInfo.name,\n } satisfies AuthApp);\n }\n }\n } catch {\n // JWT verification failed\n }\n } else {\n let user = tokens.get(token);\n if (!user && fallbackUser && token.length > 0) {\n debug(\"auth\", \"fallback user for unknown token\", { login: fallbackUser.login, id: fallbackUser.id });\n user = { login: fallbackUser.login, id: fallbackUser.id, scopes: fallbackUser.scopes };\n }\n if (user) {\n c.set(\"authUser\", user);\n c.set(\"authToken\", token);\n c.set(\"authScopes\", user.scopes);\n }\n }\n }\n await next();\n };\n}\n\nexport function requireAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authUser\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"Requires authentication\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n\nexport function requireAppAuth() {\n return async (c: Context, next: Next) => {\n if (!c.get(\"authApp\")) {\n const docsUrl = (c.get(\"docsUrl\") as string | undefined) ?? \"https://emulate.dev\";\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: docsUrl,\n },\n 401,\n );\n }\n await next();\n };\n}\n","const isDebug =\n typeof process !== \"undefined\" &&\n (process.env.DEBUG === \"1\" || process.env.DEBUG === \"true\" || process.env.EMULATE_DEBUG === \"1\");\n\nexport function debug(label: string, ...args: unknown[]): void {\n if (isDebug) {\n console.log(`[${label}]`, ...args);\n }\n}\n","import { readFileSync } from \"node:fs\";\nimport { fileURLToPath } from \"node:url\";\nimport { dirname, join } from \"node:path\";\nimport type { Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\n\n// Read the cosmetic font/favicon assets lazily and defensively: on a real\n// filesystem (Node/Bun hosts) this serves them; on filesystem-less runtimes\n// (e.g. Cloudflare Workers) the read fails and the route 404s, but — crucially —\n// importing this module touches neither fs NOR import.meta.url at load time\n// (workerd leaves import.meta.url undefined, which would crash `fileURLToPath`),\n// so `createServer` boots everywhere. API emulation never needs these assets.\nconst assetCache = new Map<string, Buffer | null>();\nfunction loadAsset(name: string): Buffer | null {\n if (assetCache.has(name)) return assetCache.get(name)!;\n let buf: Buffer | null = null;\n try {\n const dir = dirname(fileURLToPath(import.meta.url));\n buf = readFileSync(join(dir, \"fonts\", name));\n } catch {\n buf = null;\n }\n assetCache.set(name, buf);\n return buf;\n}\n\nconst FONT_NAMES = new Set([\"geist-sans.woff2\", \"GeistPixel-Square.woff2\"]);\n\nexport function registerFontRoutes(app: Hono<AppEnv>): void {\n app.get(\"/_emulate/fonts/:name\", (c) => {\n const name = c.req.param(\"name\");\n if (!FONT_NAMES.has(name)) return c.notFound();\n const buf = loadAsset(name);\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"font/woff2\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n });\n });\n\n app.get(\"/_emulate/favicon.ico\", (c) => {\n const buf = loadAsset(\"favicon.ico\");\n if (!buf) return c.notFound();\n return new Response(buf, {\n headers: {\n \"Content-Type\": \"image/x-icon\",\n \"Cache-Control\": \"public, max-age=31536000, immutable\",\n },\n });\n });\n}\n","import type { MiddlewareHandler } from \"./http.js\";\nimport type { AppEnv, AuthUser, AuthApp } from \"./middleware/auth.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\n\nexport interface LedgerIdentity {\n user?: Pick<AuthUser, \"login\" | \"id\" | \"scopes\">;\n app?: Pick<AuthApp, \"appId\" | \"slug\" | \"name\">;\n}\n\nexport interface LedgerSideEffect {\n type: \"create\" | \"update\" | \"delete\" | \"custom\";\n collection?: string;\n id?: string | number;\n summary?: string;\n}\n\nexport interface LedgerWebhookDelivery {\n id: number;\n hook_id: number;\n event: string;\n action?: string;\n status_code: number | null;\n success: boolean;\n}\n\nexport interface LedgerEntry {\n id: string;\n /** Correlation id: honored from X-Correlation-Id / X-Request-Id or generated. */\n correlationId: string;\n timestamp: string;\n method: string;\n host: string;\n path: string;\n query: string;\n /** Matched route pattern, e.g. /repos/:owner/:repo/issues. */\n route?: string;\n /** Provider operation id, when the handler advertises one. */\n operationId?: string;\n request: {\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n identity: LedgerIdentity;\n response: {\n status: number;\n headers: Record<string, string>;\n body?: unknown;\n bodyTruncated?: boolean;\n };\n /** Human/agent-readable one-liner, e.g. \"POST /repos/:owner/:repo -> 201\". */\n summary: string;\n sideEffects: LedgerSideEffect[];\n webhookDeliveries: LedgerWebhookDelivery[];\n durationMs: number;\n}\n\nexport interface LedgerOptions {\n maxEntries?: number;\n maxBodyChars?: number;\n /** When provided, webhook deliveries fired during a request are correlated onto its entry. */\n webhooks?: WebhookDispatcher;\n}\n\nexport interface LedgerSnapshot {\n entries: LedgerEntry[];\n counter: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 1000;\nconst DEFAULT_MAX_BODY_CHARS = 20000;\nconst REDACTED = \"[redacted]\";\nconst SENSITIVE_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-api-key\",\n \"x-github-token\",\n \"stripe-signature\",\n]);\nconst SENSITIVE_KEYS = /token|secret|password|authorization|api[_-]?key|client[_-]?secret|private[_-]?key/i;\n\nexport class RequestLedger {\n private entries: LedgerEntry[] = [];\n private counter = 1;\n\n constructor(private readonly options: LedgerOptions = {}) {}\n\n add(entry: Omit<LedgerEntry, \"id\">): LedgerEntry {\n const saved = { ...entry, id: `req_${this.counter++}` };\n this.entries.push(saved);\n const max = this.options.maxEntries ?? DEFAULT_MAX_ENTRIES;\n if (this.entries.length > max) {\n this.entries.splice(0, this.entries.length - max);\n }\n return saved;\n }\n\n list(limit?: number): LedgerEntry[] {\n const all = [...this.entries].reverse();\n return limit != null ? all.slice(0, limit) : all;\n }\n\n clear(): void {\n this.entries.length = 0;\n this.counter = 1;\n }\n\n /** Serialize for durable persistence (e.g. a Cloudflare Durable Object). */\n serialize(): LedgerSnapshot {\n return { entries: [...this.entries], counter: this.counter };\n }\n\n restore(snapshot: LedgerSnapshot | undefined): void {\n if (!snapshot) return;\n this.entries = Array.isArray(snapshot.entries) ? [...snapshot.entries] : [];\n this.counter = typeof snapshot.counter === \"number\" ? snapshot.counter : this.entries.length + 1;\n }\n}\n\nfunction correlationIdFor(headers: Record<string, string>): string {\n const provided = headers[\"x-correlation-id\"] ?? headers[\"x-request-id\"];\n if (provided && provided.length <= 200) return provided;\n return `cor_${crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n\nexport function createLedgerMiddleware(ledger: RequestLedger, options: LedgerOptions = {}): MiddlewareHandler<AppEnv> {\n const maxBodyChars = options.maxBodyChars ?? DEFAULT_MAX_BODY_CHARS;\n const webhooks = options.webhooks;\n\n return async (c, next) => {\n if (c.req.path.startsWith(\"/_emulate\")) {\n await next();\n return;\n }\n\n const started = Date.now();\n const url = new URL(c.req.url);\n const rawHeaders = c.req.header();\n const correlationId = correlationIdFor(rawHeaders);\n c.set(\"correlationId\", correlationId);\n c.set(\"ledgerEffects\", []);\n c.header(\"X-Correlation-Id\", correlationId);\n\n const requestBody = await readBody(c.req.raw.clone(), maxBodyChars);\n const requestHeaders = redactHeaders(rawHeaders);\n\n // Snapshot existing webhook delivery ids so we can correlate the ones this\n // request fires. Exact under the serialized execution of a Durable Object;\n // best-effort on the concurrent local dev server.\n const beforeDeliveryIds = webhooks ? new Set(webhooks.getDeliveries().map((d) => d.id)) : undefined;\n\n const response = await next();\n if (!response) return;\n\n const responseBody = await readBody(response.clone(), maxBodyChars);\n const route = c.req.routePath;\n const operationId = c.get(\"operationId\");\n const sideEffects = (c.get(\"ledgerEffects\") as LedgerSideEffect[] | undefined) ?? [];\n const webhookDeliveries: LedgerWebhookDelivery[] =\n webhooks && beforeDeliveryIds\n ? webhooks\n .getDeliveries()\n .filter((d) => !beforeDeliveryIds.has(d.id))\n .map((d) => ({\n id: d.id,\n hook_id: d.hook_id,\n event: d.event,\n action: d.action,\n status_code: d.status_code,\n success: d.success,\n }))\n : [];\n\n ledger.add({\n correlationId,\n timestamp: new Date().toISOString(),\n method: c.req.method.toUpperCase(),\n host: url.host,\n path: url.pathname,\n query: url.search,\n route,\n operationId,\n request: {\n headers: requestHeaders,\n ...requestBody,\n },\n identity: {\n user: c.get(\"authUser\"),\n app: c.get(\"authApp\"),\n },\n response: {\n status: response.status,\n headers: redactHeaders(headersToRecord(response.headers)),\n ...responseBody,\n },\n summary: `${c.req.method.toUpperCase()} ${route ?? url.pathname} -> ${response.status}`,\n sideEffects,\n webhookDeliveries,\n durationMs: Date.now() - started,\n });\n\n return response;\n };\n}\n\n/** Record a side effect onto the active request's ledger entry. */\nexport function recordSideEffect(\n c: { get: (key: \"ledgerEffects\") => LedgerSideEffect[] | undefined },\n effect: LedgerSideEffect,\n): void {\n const effects = c.get(\"ledgerEffects\");\n if (effects) effects.push(effect);\n}\n\nasync function readBody(\n responseOrRequest: Request | Response,\n maxChars: number,\n): Promise<{ body?: unknown; bodyTruncated?: boolean }> {\n const method = responseOrRequest instanceof Request ? responseOrRequest.method.toUpperCase() : undefined;\n if (method === \"GET\" || method === \"HEAD\") return {};\n\n const contentType = responseOrRequest.headers.get(\"content-type\") ?? \"\";\n if (responseOrRequest instanceof Response && responseOrRequest.status === 204) return {};\n\n let text: string;\n try {\n text = await responseOrRequest.text();\n } catch {\n return {};\n }\n if (!text) return {};\n\n const truncated = text.length > maxChars;\n const clipped = truncated ? text.slice(0, maxChars) : text;\n if (contentType.includes(\"application/json\")) {\n try {\n return { body: redactValue(JSON.parse(clipped)), bodyTruncated: truncated || undefined };\n } catch {\n return { body: clipped, bodyTruncated: truncated || undefined };\n }\n }\n if (contentType.includes(\"application/x-www-form-urlencoded\")) {\n const params: Record<string, string> = {};\n for (const [key, value] of new URLSearchParams(clipped)) {\n params[key] = SENSITIVE_KEYS.test(key) ? REDACTED : value;\n }\n return { body: params, bodyTruncated: truncated || undefined };\n }\n return { body: clipped, bodyTruncated: truncated || undefined };\n}\n\nfunction headersToRecord(headers: Headers): Record<string, string> {\n const out: Record<string, string> = {};\n headers.forEach((value, key) => {\n out[key] = value;\n });\n return out;\n}\n\nfunction redactHeaders(headers: Record<string, string>): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n out[key] = SENSITIVE_HEADERS.has(key.toLowerCase()) ? REDACTED : value;\n }\n return out;\n}\n\nfunction redactValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(redactValue);\n if (!value || typeof value !== \"object\") return value;\n const out: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(value)) {\n out[key] = SENSITIVE_KEYS.test(key) ? REDACTED : redactValue(child);\n }\n return out;\n}\n","export type SpecKind = \"openapi\" | \"graphql\" | \"mcp\" | \"google-discovery\" | \"oauth-metadata\" | \"manual\";\nexport type SpecCoverage = \"generated\" | \"hand-authored\" | \"partial\" | \"unsupported\";\n\n/**\n * Per-operation coverage. The vision asks for honest, operation-level coverage\n * boundaries (generated / hand-authored / partial / unsupported) instead of a\n * single label stamped across an entire spec. A plugin declares the operations\n * it actually implements; `GET /_emulate/coverage` reports them with a summary.\n */\nexport interface OperationCoverage {\n operationId: string;\n method?: string;\n path?: string;\n status: SpecCoverage;\n summary?: string;\n}\n\nexport interface SpecManifest {\n kind: SpecKind;\n title: string;\n url?: string;\n coverage: SpecCoverage;\n operations?: OperationCoverage[];\n notes?: string;\n}\n\nexport interface SurfaceManifest {\n id: string;\n kind: \"rest\" | \"oauth\" | \"oidc\" | \"graphql\" | \"mcp\" | \"webhooks\" | \"ui\" | \"provider-specific\";\n title: string;\n basePath?: string;\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface AuthCapabilityManifest {\n id: string;\n title: string;\n type:\n | \"api-key\"\n | \"bearer-token\"\n | \"oauth-client-credentials\"\n | \"oauth-authorization-code\"\n | \"oidc\"\n | \"jwt-app\"\n | \"dynamic-client-registration\"\n | \"webhook-secret\"\n | \"provider-specific\";\n status: \"supported\" | \"partial\" | \"unsupported\";\n notes?: string;\n}\n\nexport interface ScenarioManifest {\n id: string;\n title: string;\n description?: string;\n}\n\n/** A seedable area of the instance, surfaced so agents can discover the seed shape. */\nexport interface SeedFieldManifest {\n key: string;\n title: string;\n description?: string;\n example?: unknown;\n}\n\nexport interface SeedSchemaManifest {\n description?: string;\n fields: SeedFieldManifest[];\n /** A full example seed body that can be POSTed to /_emulate/seed. */\n example?: unknown;\n}\n\nexport interface StateCollectionManifest {\n name: string;\n title?: string;\n description?: string;\n}\n\nexport interface StateModelManifest {\n description?: string;\n collections: StateCollectionManifest[];\n}\n\nexport interface ResetBehaviorManifest {\n description: string;\n reseeds: boolean;\n clearsLedger: boolean;\n clearsWebhooks: boolean;\n}\n\nexport type InspectorTabKind = \"landing\" | \"ledger\" | \"state\" | \"logs\" | \"credentials\" | \"seed\" | \"spec\" | \"custom\";\n\nexport interface InspectorTabManifest {\n id: string;\n title: string;\n kind: InspectorTabKind;\n description?: string;\n}\n\n/** Describes what the request ledger records and how durable it is. */\nexport interface LedgerCapabilitiesManifest {\n description?: string;\n recordsFields: string[];\n redactsSensitive: boolean;\n correlationId: boolean;\n webhookDeliveries: boolean;\n sideEffects: boolean;\n persistent: boolean;\n maxEntries?: number;\n}\n\nexport type ConnectionKind = \"sdk\" | \"cli\" | \"env\" | \"curl\" | \"config\" | \"mcp\";\n\n/**\n * A copyable connection snippet. The `template` uses {{placeholders}} that the\n * control plane resolves against the live instance ({{baseUrl}}, {{controlBaseUrl}},\n * {{service}}, {{instance}}, {{token}}, {{clientId}}, {{clientSecret}}). This is\n * how a human or agent copies ready-to-run SDK / CLI / app config without repo\n * context.\n */\nexport interface ConnectionSnippet {\n id: string;\n title: string;\n kind: ConnectionKind;\n language?: string;\n description?: string;\n template: string;\n}\n\nexport interface ServiceManifest {\n id: string;\n name: string;\n description: string;\n surfaces: SurfaceManifest[];\n auth: AuthCapabilityManifest[];\n specs: SpecManifest[];\n scenarios?: ScenarioManifest[];\n seedSchema?: SeedSchemaManifest;\n stateModel?: StateModelManifest;\n resetBehavior?: ResetBehaviorManifest;\n inspectorTabs?: InspectorTabManifest[];\n ledger?: LedgerCapabilitiesManifest;\n connections?: ConnectionSnippet[];\n docsUrl?: string;\n}\n\nexport interface EmulatorInstanceInfo {\n service: string;\n instance?: string;\n baseUrl: string;\n controlBaseUrl: string;\n providerBaseUrl: string;\n}\n\n/**\n * Reset, ledger capabilities, inspector tabs and base connection snippets are the\n * same for every emulator because they all run on the shared core control plane.\n * Defining them once here keeps per-plugin manifests focused on service-specific\n * surface, auth, seed, and SDK details, and guarantees the control plane never\n * lies about a capability it actually provides.\n */\nexport const CORE_RESET_BEHAVIOR: ResetBehaviorManifest = {\n description: \"Resets the instance to its seeded baseline.\",\n reseeds: true,\n clearsLedger: true,\n clearsWebhooks: true,\n};\n\nexport function coreLedgerCapabilities(persistent: boolean): LedgerCapabilitiesManifest {\n return {\n description: \"Recent provider requests with sensitive headers and fields redacted.\",\n recordsFields: [\n \"timestamp\",\n \"method\",\n \"host\",\n \"path\",\n \"route\",\n \"operationId\",\n \"correlationId\",\n \"identity\",\n \"request\",\n \"response\",\n \"summary\",\n \"sideEffects\",\n \"webhookDeliveries\",\n \"durationMs\",\n ],\n redactsSensitive: true,\n correlationId: true,\n webhookDeliveries: true,\n sideEffects: true,\n persistent,\n maxEntries: 1000,\n };\n}\n\nexport function coreInspectorTabs(manifest: ServiceManifest): InspectorTabManifest[] {\n const tabs: InspectorTabManifest[] = [\n {\n id: \"overview\",\n title: \"Overview\",\n kind: \"landing\",\n description: \"Service surfaces, base URLs, and connection snippets.\",\n },\n {\n id: \"ledger\",\n title: \"Ledger\",\n kind: \"ledger\",\n description: \"Recent provider requests recorded by the emulator.\",\n },\n { id: \"state\", title: \"State\", kind: \"state\", description: \"Current seeded and mutated instance state.\" },\n {\n id: \"credentials\",\n title: \"Credentials\",\n kind: \"credentials\",\n description: \"Mint tokens, API keys, or OAuth clients.\",\n },\n ];\n if (manifest.seedSchema || (manifest.scenarios && manifest.scenarios.length > 0)) {\n tabs.push({ id: \"seed\", title: \"Seed\", kind: \"seed\", description: \"Seed state or load a scenario.\" });\n }\n if (manifest.specs.some((s) => s.kind === \"openapi\" || s.kind === \"graphql\")) {\n tabs.push({ id: \"spec\", title: \"Spec\", kind: \"spec\", description: \"OpenAPI / GraphQL spec sources and coverage.\" });\n }\n if (manifest.surfaces.some((s) => s.kind === \"webhooks\")) {\n tabs.push({\n id: \"logs\",\n title: \"Webhooks\",\n kind: \"logs\",\n description: \"Webhook deliveries dispatched by the emulator.\",\n });\n }\n return tabs;\n}\n\n/** Connection snippets every emulator can offer (env + curl against the control plane). */\nexport function coreConnections(): ConnectionSnippet[] {\n return [\n {\n id: \"base-url\",\n title: \"Base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point your SDK or app at the emulator instead of the real provider.\",\n template: \"{{SERVICE_UPPER}}_BASE_URL={{baseUrl}}\",\n },\n {\n id: \"create-credential\",\n title: \"Create a credential\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Mint a working credential for this instance.\",\n template:\n 'curl -s -X POST {{controlBaseUrl}}/credentials \\\\\\n -H \"content-type: application/json\" \\\\\\n -d \\'{\"type\":\"{{defaultAuthType}}\"}\\'',\n },\n {\n id: \"inspect-ledger\",\n title: \"Inspect requests\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Read the request ledger to validate how your app called the service.\",\n template: \"curl -s {{controlBaseUrl}}/ledger\",\n },\n ];\n}\n\n/**\n * Merge the shared core capabilities into a plugin manifest so every served\n * manifest fully describes reset behavior, ledger capabilities, inspector tabs,\n * and at least the base connection snippets, without each plugin repeating them.\n */\nexport function enrichManifest(manifest: ServiceManifest, opts: { ledgerPersistent?: boolean } = {}): ServiceManifest {\n return {\n ...manifest,\n resetBehavior: manifest.resetBehavior ?? CORE_RESET_BEHAVIOR,\n ledger: manifest.ledger ?? coreLedgerCapabilities(opts.ledgerPersistent ?? false),\n inspectorTabs: manifest.inspectorTabs ?? coreInspectorTabs(manifest),\n connections: [...(manifest.connections ?? []), ...coreConnections()],\n };\n}\n\nexport interface ConnectionVars {\n baseUrl: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n service: string;\n instance?: string;\n token?: string;\n clientId?: string;\n clientSecret?: string;\n defaultAuthType?: string;\n}\n\nexport interface ResolvedConnection extends ConnectionSnippet {\n body: string;\n}\n\n/** Interpolate a connection snippet template against live instance values. */\nexport function resolveConnections(connections: ConnectionSnippet[], vars: ConnectionVars): ResolvedConnection[] {\n const map: Record<string, string> = {\n baseUrl: vars.baseUrl,\n providerBaseUrl: vars.providerBaseUrl,\n controlBaseUrl: vars.controlBaseUrl,\n service: vars.service,\n SERVICE_UPPER: vars.service.toUpperCase().replace(/[^A-Z0-9]+/g, \"_\"),\n instance: vars.instance ?? \"default\",\n token: vars.token ?? \"<token>\",\n clientId: vars.clientId ?? \"<client_id>\",\n clientSecret: vars.clientSecret ?? \"<client_secret>\",\n defaultAuthType: vars.defaultAuthType ?? \"bearer-token\",\n };\n return connections.map((snippet) => ({\n ...snippet,\n body: snippet.template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key: string) => map[key] ?? `{{${key}}}`),\n }));\n}\n\n/** A summary of declared per-operation coverage across a manifest's specs. */\nexport function coverageReport(manifest: ServiceManifest): {\n operations: OperationCoverage[];\n summary: Record<SpecCoverage, number>;\n specs: Array<{ kind: SpecKind; title: string; coverage: SpecCoverage; operationCount: number }>;\n} {\n const operations: OperationCoverage[] = [];\n const summary: Record<SpecCoverage, number> = {\n generated: 0,\n \"hand-authored\": 0,\n partial: 0,\n unsupported: 0,\n };\n const specs = manifest.specs.map((spec) => {\n const ops = spec.operations ?? [];\n for (const op of ops) {\n operations.push(op);\n summary[op.status] += 1;\n }\n return { kind: spec.kind, title: spec.title, coverage: spec.coverage, operationCount: ops.length };\n });\n return { operations, summary, specs };\n}\n\nexport function createDefaultManifest(service: string): ServiceManifest {\n return {\n id: service,\n name: service,\n description: `Stateful ${service} API emulator.`,\n surfaces: [{ id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\" }],\n auth: [{ id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" }],\n specs: [{ kind: \"manual\", title: \"Hand-authored emulator behavior\", coverage: \"partial\" }],\n };\n}\n","export function escapeHtml(s: string): string {\n return s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\").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.info-text a,.section-heading a{color:#1a8c00;text-decoration:none;transition:color .15s;}\n.info-text a:hover,.section-heading a:hover{color:#33ff00;}\ncode{font-family:'Geist Mono','SF Mono',ui-monospace,monospace;font-size:.8125rem;color:#33ff00;word-break:break-all;}\n.code-block{\n background:#020;border:1px solid #0a3300;border-radius:6px;padding:10px 12px;\n margin:8px 0 12px;overflow-x:auto;\n}\n.code-block code{white-space:pre;word-break:normal;display:block;line-height:1.5;}\n.app-link{\n display:flex;align-items:center;gap:12px;padding:12px;\n border:1px solid #0a3300;border-radius:8px;background:#000;\n text-decoration:none;color:inherit;margin-bottom:8px;transition:border-color .15s;\n}\n.app-link:hover{border-color:#33ff00;}\n.app-link-name{font-weight:600;font-size:.875rem;color:#33ff00;}\n.app-link-scopes{font-size:.6875rem;color:#1a8c00;margin-top:1px;}\n.empty{color:#1a8c00;text-align:center;padding:28px 0;font-size:.875rem;}\n\n.inspector-layout{max-width:960px;margin:0 auto;padding:28px 20px;}\n.inspector-tabs{display:flex;gap:4px;margin-bottom:20px;}\n.inspector-tabs a{\n padding:7px 16px;border-radius:6px;text-decoration:none;\n font-size:.8125rem;color:#1a8c00;border:1px solid transparent;\n transition:color .15s,border-color .15s;\n}\n.inspector-tabs a:hover{color:#33ff00;}\n.inspector-tabs a.active{color:#33ff00;font-weight:600;border-color:#0a3300;background:#0a3300;}\n.inspector-section{margin-bottom:24px;}\n.inspector-section h2{\n font-family:'Geist Pixel',monospace;\n font-size:1rem;font-weight:600;color:#33ff00;margin-bottom:10px;\n}\n.inspector-section h3{\n font-family:'Geist Pixel',monospace;\n font-size:.875rem;font-weight:600;color:#1a8c00;margin:16px 0 8px;\n}\n.inspector-table{width:100%;border-collapse:collapse;margin-bottom:12px;}\n.inspector-table th,.inspector-table td{\n text-align:left;padding:8px 12px;border-bottom:1px solid #0a3300;\n font-size:.8125rem;\n}\n.inspector-table th{color:#1a8c00;font-weight:600;font-size:.75rem;text-transform:uppercase;letter-spacing:.04em;}\n.inspector-table td{color:#33ff00;}\n.inspector-table tbody tr{transition:background .1s;}\n.inspector-table tbody tr:hover{background:#0a3300;}\n.inspector-empty{color:#1a8c00;text-align:center;padding:20px 0;font-size:.8125rem;}\n\n.checkout-layout{\n display:flex;min-height:calc(100vh - 42px);\n}\n.checkout-summary{\n flex:1;background:#020;padding:48px 40px 48px 10%;\n display:flex;flex-direction:column;justify-content:center;\n border-right:1px solid #0a3300;\n}\n.checkout-form-side{\n flex:1;background:#000;padding:48px 10% 48px 40px;\n display:flex;flex-direction:column;justify-content:center;\n}\n.checkout-merchant{\n display:flex;align-items:center;gap:10px;margin-bottom:6px;\n}\n.checkout-merchant-name{\n font-family:'Geist Pixel',monospace;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-test-badge{\n font-size:.625rem;font-weight:700;letter-spacing:.04em;text-transform:uppercase;\n background:#0a3300;color:#1a8c00;padding:2px 8px;border-radius:4px;\n}\n.checkout-total{\n font-family:'Geist Pixel',monospace;\n font-size:2rem;font-weight:700;color:#33ff00;margin:8px 0 28px;\n}\n.checkout-line-item{\n display:flex;align-items:center;gap:14px;padding:14px 0;\n border-bottom:1px solid #0a3300;\n}\n.checkout-line-item:first-child{border-top:1px solid #0a3300;}\n.checkout-item-icon{\n width:42px;height:42px;border-radius:6px;background:#0a3300;\n display:flex;align-items:center;justify-content:center;flex-shrink:0;\n font-family:'Geist Pixel',monospace;font-size:.875rem;font-weight:700;color:#116600;\n}\n.checkout-item-details{flex:1;min-width:0;}\n.checkout-item-name{font-size:.875rem;font-weight:600;color:#33ff00;}\n.checkout-item-qty{font-size:.75rem;color:#1a8c00;margin-top:2px;}\n.checkout-item-price{\n font-size:.875rem;font-weight:600;color:#33ff00;text-align:right;white-space:nowrap;\n}\n.checkout-item-unit{font-size:.6875rem;color:#1a8c00;text-align:right;margin-top:2px;}\n.checkout-totals{margin-top:20px;}\n.checkout-totals-row{\n display:flex;justify-content:space-between;padding:6px 0;\n font-size:.8125rem;color:#1a8c00;\n}\n.checkout-totals-row.total{\n border-top:1px solid #0a3300;margin-top:8px;padding-top:14px;\n font-size:.9375rem;font-weight:600;color:#33ff00;\n}\n.checkout-form-section{margin-bottom:24px;}\n.checkout-form-label{\n font-size:.8125rem;font-weight:600;color:#33ff00;margin-bottom:8px;display:block;\n}\n.checkout-input{\n width:100%;padding:10px 12px;border:1px solid #0a3300;border-radius:6px;\n background:#020;color:#33ff00;font:inherit;font-size:.875rem;\n transition:border-color .15s;outline:none;\n}\n.checkout-input:focus{border-color:#33ff00;}\n.checkout-input::placeholder{color:#116600;}\n.checkout-card-box{\n border:1px solid #0a3300;border-radius:6px;padding:14px;\n background:#020;\n}\n.checkout-card-row{\n display:flex;gap:12px;margin-top:10px;\n}\n.checkout-card-row .checkout-input{flex:1;}\n.checkout-sim-note{\n font-size:.6875rem;color:#1a8c00;margin-top:10px;text-align:center;\n font-style:italic;\n}\n.checkout-pay-btn{\n width:100%;padding:14px;border:none;border-radius:8px;\n background:#33ff00;color:#000;font:inherit;font-size:.9375rem;font-weight:700;\n cursor:pointer;transition:background .15s;\n font-family:'Geist Pixel',monospace;\n}\n.checkout-pay-btn:hover{background:#44ff22;}\n.checkout-cancel{\n text-align:center;margin-top:14px;\n}\n.checkout-cancel a{\n color:#1a8c00;text-decoration:none;font-size:.8125rem;\n transition:color .15s;\n}\n.checkout-cancel a:hover{color:#33ff00;}\n@media(max-width:768px){\n .checkout-layout{flex-direction:column;}\n .checkout-summary{padding:32px 20px;border-right:none;border-bottom:1px solid #0a3300;}\n .checkout-form-side{padding:32px 20px;}\n}\n`;\n\nconst POWERED_BY = `<div class=\"powered-by\">Powered by <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\">emulate</a></div>`;\n\nfunction emuBar(service?: string): string {\n const title = service ? `${escapeHtml(service)} Emulator` : \"Emulator\";\n return `<div class=\"emu-bar\">\n <span class=\"emu-bar-title\">${title}</span>\n <nav class=\"emu-bar-links\">\n <a href=\"https://github.com/vercel-labs/emulate/issues\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Report Issue</span><span class=\"short\">Report</span></a>\n <a href=\"https://github.com/vercel-labs/emulate\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Source Code</span><span class=\"short\">Source</span></a>\n <a href=\"https://emulate.dev\" target=\"_blank\" rel=\"noopener\"><span class=\"full\">Learn More</span><span class=\"short\">Learn</span></a>\n </nav>\n</div>`;\n}\n\nfunction head(title: string): string {\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\"/>\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"/>\n<link rel=\"icon\" href=\"/_emulate/favicon.ico\"/>\n<title>${escapeHtml(title)} | emulate</title>\n<style>${CSS}</style>\n</head>`;\n}\n\nexport function renderCardPage(title: string, subtitle: string, body: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\">\n <div class=\"card-title\">${escapeHtml(title)}</div>\n <div class=\"card-subtitle\">${subtitle}</div>\n ${body}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderErrorPage(title: string, message: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner error-card\">\n <div class=\"error-title\">${escapeHtml(title)}</div>\n <div class=\"error-msg\">${escapeHtml(message)}</div>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderSettingsPage(title: string, sidebarHtml: string, bodyHtml: string, service?: string): string {\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"settings-layout\">\n <nav class=\"settings-sidebar\">${sidebarHtml}</nav>\n <div class=\"settings-main\">${bodyHtml}</div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface InspectorTab {\n id: string;\n label: string;\n href: string;\n}\n\nexport function renderInspectorPage(\n title: string,\n tabs: InspectorTab[],\n activeTab: string,\n body: string,\n service?: string,\n): string {\n const tabLinks = tabs\n .map(\n (t) => `<a href=\"${escapeAttr(t.href)}\" class=\"${t.id === activeTab ? \"active\" : \"\"}\">${escapeHtml(t.label)}</a>`,\n )\n .join(\"\");\n\n return `${head(title)}\n<body>\n${emuBar(service)}\n<div class=\"inspector-layout\">\n <nav class=\"inspector-tabs\">${tabLinks}</nav>\n ${body}\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport function renderFormPostPage(action: string, fields: Record<string, string>, service?: string): string {\n const hiddens = Object.entries(fields)\n .filter(([, v]) => v != null)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\\n\");\n\n return `${head(\"Redirecting\")}\n<body onload=\"document.forms[0].submit()\">\n${emuBar(service)}\n<div class=\"content\">\n <div class=\"content-inner\" style=\"text-align:center\">\n <div class=\"card-subtitle\">Redirecting&hellip;</div>\n <form method=\"POST\" action=\"${escapeAttr(action)}\">\n${hiddens}\n <noscript><button type=\"submit\" class=\"user-btn\" style=\"margin-top:12px;justify-content:center\">\n <span class=\"user-login\">Continue</span>\n </button></noscript>\n </form>\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface CheckoutLineItem {\n name: string;\n quantity: number;\n unitPrice: number;\n totalPrice: number;\n currency: string;\n}\n\nexport interface CheckoutPageOptions {\n merchantName?: string;\n lineItems: CheckoutLineItem[];\n subtotal: number;\n total: number;\n currency: string;\n sessionId: string;\n cancelUrl?: string | null;\n}\n\nexport function renderCheckoutPage(opts: CheckoutPageOptions, service?: string): string {\n const fmt = (cents: number, cur: string) => `$${(cents / 100).toFixed(2)} ${cur.toUpperCase()}`;\n const fmtShort = (cents: number) => `$${(cents / 100).toFixed(2)}`;\n\n const itemsHtml =\n opts.lineItems.length > 0\n ? opts.lineItems\n .map((li) => {\n const initial = li.name.charAt(0).toUpperCase();\n const unitNote =\n li.quantity > 1 ? `<div class=\"checkout-item-unit\">${fmtShort(li.unitPrice)} each</div>` : \"\";\n return `<div class=\"checkout-line-item\">\n <div class=\"checkout-item-icon\">${escapeHtml(initial)}</div>\n <div class=\"checkout-item-details\">\n <div class=\"checkout-item-name\">${escapeHtml(li.name)}</div>\n <div class=\"checkout-item-qty\">Qty ${li.quantity}</div>\n </div>\n <div>\n <div class=\"checkout-item-price\">${fmtShort(li.totalPrice)}</div>\n ${unitNote}\n </div>\n</div>`;\n })\n .join(\"\")\n : '<p class=\"empty\">No line items</p>';\n\n const totalsHtml = `<div class=\"checkout-totals\">\n <div class=\"checkout-totals-row\">\n <span>Subtotal</span><span>${fmtShort(opts.subtotal)}</span>\n </div>\n <div class=\"checkout-totals-row total\">\n <span>Total due</span><span>${fmt(opts.total, opts.currency)}</span>\n </div>\n</div>`;\n\n const cancelHtml = opts.cancelUrl\n ? `<div class=\"checkout-cancel\"><a href=\"${escapeAttr(opts.cancelUrl)}\">Cancel</a></div>`\n : \"\";\n\n const merchant = opts.merchantName ? escapeHtml(opts.merchantName) : \"Checkout\";\n\n return `${head(\"Checkout\")}\n<body>\n${emuBar(service)}\n<div class=\"checkout-layout\">\n <div class=\"checkout-summary\">\n <div class=\"checkout-merchant\">\n <span class=\"checkout-merchant-name\">${merchant}</span>\n <span class=\"checkout-test-badge\">Test Mode</span>\n </div>\n <div class=\"checkout-total\">${fmtShort(opts.total)}</div>\n ${itemsHtml}\n ${totalsHtml}\n </div>\n <div class=\"checkout-form-side\">\n <form method=\"post\" action=\"/checkout/${escapeAttr(opts.sessionId)}/complete\">\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Email</label>\n <input type=\"email\" name=\"email\" class=\"checkout-input\" placeholder=\"you@example.com\"/>\n </div>\n <div class=\"checkout-form-section\">\n <label class=\"checkout-form-label\">Card information</label>\n <div class=\"checkout-card-box\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"1234 1234 1234 1234\" disabled/>\n <div class=\"checkout-card-row\">\n <input type=\"text\" class=\"checkout-input\" placeholder=\"MM / YY\" disabled/>\n <input type=\"text\" class=\"checkout-input\" placeholder=\"CVC\" disabled/>\n </div>\n </div>\n <div class=\"checkout-sim-note\">Card fields are simulated. Payment will be auto-approved.</div>\n </div>\n <button type=\"submit\" class=\"checkout-pay-btn\">Pay ${fmtShort(opts.total)}</button>\n </form>\n ${cancelHtml}\n </div>\n</div>\n${POWERED_BY}\n</body></html>`;\n}\n\nexport interface UserButtonOptions {\n letter: string;\n login: string;\n name?: string;\n email?: string;\n formAction: string;\n hiddenFields: Record<string, string>;\n}\n\nexport function renderUserButton(opts: UserButtonOptions): string {\n const hiddens = Object.entries(opts.hiddenFields)\n .map(([k, v]) => `<input type=\"hidden\" name=\"${escapeAttr(k)}\" value=\"${escapeAttr(v)}\"/>`)\n .join(\"\");\n\n const nameLine = opts.name ? `<div class=\"user-meta\">${escapeHtml(opts.name)}</div>` : \"\";\n const emailLine = opts.email ? `<div class=\"user-email\">${escapeHtml(opts.email)}</div>` : \"\";\n\n return `<form class=\"user-form\" method=\"post\" action=\"${escapeAttr(opts.formAction)}\">\n${hiddens}\n<button type=\"submit\" class=\"user-btn\">\n <span class=\"avatar\">${escapeHtml(opts.letter)}</span>\n <span class=\"user-text\">\n <span class=\"user-login\">${escapeHtml(opts.login)}</span>\n ${nameLine}${emailLine}\n </span>\n</button>\n</form>`;\n}\n","import type { Context, Hono } from \"./http.js\";\nimport type { AppEnv } from \"./middleware/auth.js\";\nimport type { Store } from \"./store.js\";\nimport type { WebhookDispatcher } from \"./webhooks.js\";\nimport type { RequestLedger } from \"./ledger.js\";\nimport type { ConnectionVars, EmulatorInstanceInfo, ResolvedConnection, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport type { TokenMap } from \"./middleware/auth.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\n\nexport interface CredentialRequest {\n type?: string;\n login?: string;\n name?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n [key: string]: unknown;\n}\n\nexport interface IssuedCredential {\n type: string;\n token?: string;\n login?: string;\n scopes?: string[];\n client_id?: string;\n client_secret?: string;\n redirect_uris?: string[];\n token_url?: string;\n authorization_url?: string;\n notes?: string;\n [key: string]: unknown;\n}\n\nexport interface ControlPlaneOptions {\n manifest: ServiceManifest;\n instance: EmulatorInstanceInfo;\n store: Store;\n webhooks: WebhookDispatcher;\n ledger: RequestLedger;\n tokenMap?: TokenMap;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport const INSTANCE_NOTES = \"Hosted deployments create instances lazily when the returned URL is first used.\";\n\nexport interface InstanceCreation {\n service: string;\n instance: string;\n providerBaseUrl: string;\n controlBaseUrl: string;\n pathUrl: string;\n hostHint: string;\n notes: string;\n}\n\n/** The single, canonical shape for POST /_emulate/instances, shared by every host. */\nexport function buildInstanceCreation(args: {\n service: string;\n instance: string;\n providerBaseUrl: string;\n pathOrigin: string;\n hostSuffix: string;\n}): InstanceCreation {\n return {\n service: args.service,\n instance: args.instance,\n providerBaseUrl: args.providerBaseUrl,\n controlBaseUrl: `${args.providerBaseUrl}/_emulate`,\n pathUrl: `${args.pathOrigin}/${args.service}/${args.instance}`,\n hostHint: `${args.service}.${args.instance}.${args.hostSuffix}`,\n notes: INSTANCE_NOTES,\n };\n}\n\nfunction connectionVars(\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n overrides?: Partial<ConnectionVars>,\n): ConnectionVars {\n return {\n baseUrl: instance.providerBaseUrl,\n providerBaseUrl: instance.providerBaseUrl,\n controlBaseUrl: instance.controlBaseUrl,\n service: manifest.id,\n instance: instance.instance,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n ...overrides,\n };\n}\n\nexport function registerControlPlane(app: Hono<AppEnv>, options: ControlPlaneOptions): void {\n const { instance, store, webhooks, ledger } = options;\n const manifest = enrichManifest(options.manifest, { ledgerPersistent: options.ledgerPersistent });\n const hostSuffix = options.hostSuffix ?? \"emulators.dev\";\n\n app.get(\"/_emulate\", (c) => c.html(renderLandingPage(manifest, instance)));\n app.get(\"/_emulate/manifest\", (c) =>\n c.json({\n manifest,\n instance,\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance)),\n }),\n );\n app.get(\"/_emulate/quickstart\", (c) => c.text(renderQuickstart(manifest, instance)));\n app.get(\"/_emulate/specs\", (c) => c.json({ specs: manifest.specs, surfaces: manifest.surfaces }));\n app.get(\"/_emulate/coverage\", (c) => c.json(coverageReport(manifest)));\n app.get(\"/_emulate/connections\", (c) => {\n const overrides: Partial<ConnectionVars> = {};\n const token = c.req.query(\"token\");\n const clientId = c.req.query(\"client_id\");\n const clientSecret = c.req.query(\"client_secret\");\n if (token) overrides.token = token;\n if (clientId) overrides.clientId = clientId;\n if (clientSecret) overrides.clientSecret = clientSecret;\n return c.json({\n connections: resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance, overrides)),\n });\n });\n app.get(\"/_emulate/openapi\", (c) => redirectToSpec(c, manifest, instance, \"openapi\"));\n app.get(\"/_emulate/graphql\", (c) => endpointForSurface(c, manifest, instance, \"graphql\"));\n app.get(\"/_emulate/mcp\", (c) => endpointForSurface(c, manifest, instance, \"mcp\"));\n app.get(\"/_emulate/state\", (c) => c.json(store.snapshot()));\n app.get(\"/_emulate/ledger\", (c) => {\n const limitParam = c.req.query(\"limit\");\n const limit = limitParam ? Number.parseInt(limitParam, 10) : undefined;\n return c.json({ entries: ledger.list(Number.isFinite(limit) ? limit : undefined) });\n });\n app.delete(\"/_emulate/ledger\", (c) => {\n ledger.clear();\n return c.json({ ok: true });\n });\n app.get(\"/_emulate/logs\", (c) => c.json({ webhooks: webhooks.getDeliveries(), requests: ledger.list(100) }));\n app.post(\"/_emulate/reset\", async (c) => {\n if (options.reset) {\n await options.reset();\n } else {\n store.reset();\n webhooks.clear();\n ledger.clear();\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/seed\", async (c) => {\n if (!options.seed) {\n return c.json({ error: \"unsupported\", message: \"This emulator does not support runtime seeding.\" }, 501);\n }\n const body = await c.req.json().catch(() => undefined);\n try {\n await options.seed(body);\n } catch (err) {\n return c.json({ error: \"invalid_seed\", message: err instanceof Error ? err.message : \"Seed failed.\" }, 400);\n }\n return c.json({ ok: true });\n });\n app.post(\"/_emulate/credentials\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as CredentialRequest;\n try {\n if (options.issueCredential) {\n const credential = await options.issueCredential(body);\n return c.json({ credential });\n }\n const credential = issueDefaultCredential(body, manifest, options.tokenMap);\n if (!credential) {\n return c.json({ error: \"unsupported\", message: \"This emulator cannot create that credential type.\" }, 501);\n }\n return c.json({ credential });\n } catch (err) {\n return c.json(\n { error: \"unsupported\", message: err instanceof Error ? err.message : \"Credential creation failed.\" },\n 400,\n );\n }\n });\n app.post(\"/_emulate/instances\", async (c) => {\n const body = (await c.req.json().catch(() => ({}))) as { instance?: string; service?: string };\n const nextInstance = slug(body.instance ?? `${manifest.id}-${randomId().slice(0, 8)}`);\n const service = slug(body.service ?? manifest.id);\n const origin = new URL(instance.providerBaseUrl).origin;\n return c.json(\n buildInstanceCreation({\n service,\n instance: nextInstance,\n providerBaseUrl: `${origin}/${service}/${nextInstance}`,\n pathOrigin: origin,\n hostSuffix,\n }),\n );\n });\n}\n\nexport function renderLandingPage(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const surfaces = manifest.surfaces\n .map(\n (surface) =>\n `<tr><td>${escapeHtml(surface.title)}</td><td><span class=\"badge\">${escapeHtml(surface.status)}</span></td><td><code>${escapeHtml(surface.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const auth = manifest.auth\n .map((cap) => `<li><span class=\"badge\">${escapeHtml(cap.status)}</span> ${escapeHtml(cap.title)}</li>`)\n .join(\"\");\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const instanceLabel = instance.instance ? ` · instance <code>${escapeHtml(instance.instance)}</code>` : \"\";\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Base URLs${instanceLabel}</div>\n <p class=\"info-text\">Provider: <code>${escapeHtml(instance.providerBaseUrl)}</code></p>\n <p class=\"info-text\">Control: <code>${escapeHtml(instance.controlBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Credentials</div>\n <ul class=\"perm-list\">${auth}</ul>\n </div>\n ${renderConnectionsHtml(connections)}\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">${controlLinks()}</p>\n </div>\n `,\n manifest.id,\n );\n}\n\nfunction renderConnectionsHtml(connections: ResolvedConnection[]): string {\n if (connections.length === 0) return \"\";\n const blocks = connections\n .map(\n (c) =>\n `<div class=\"section-heading\">${escapeHtml(c.title)}</div><pre class=\"code-block\"><code>${escapeHtml(c.body)}</code></pre>`,\n )\n .join(\"\");\n return `<div class=\"s-card\"><div class=\"section-heading\">Connect</div>${blocks}</div>`;\n}\n\nfunction controlLinks(): string {\n const routes = [\"manifest\", \"quickstart\", \"specs\", \"coverage\", \"connections\", \"state\", \"ledger\", \"logs\"];\n return routes.map((r) => `<a href=\"/_emulate/${r}\">${r}</a>`).join(\" | \");\n}\n\nexport function renderQuickstart(manifest: ServiceManifest, instance: EmulatorInstanceInfo): string {\n const connections = resolveConnections(manifest.connections ?? [], connectionVars(manifest, instance));\n const lines = [\n `# ${manifest.name} Emulator`,\n \"\",\n manifest.description,\n \"\",\n `Provider base URL: ${instance.providerBaseUrl}`,\n `Control base URL: ${instance.controlBaseUrl}`,\n \"\",\n \"Supported surfaces:\",\n ...manifest.surfaces.map((s) => `- ${s.title}: ${s.status}${s.basePath ? ` at ${s.basePath}` : \"\"}`),\n \"\",\n \"Control endpoints:\",\n `- ${instance.controlBaseUrl}/manifest`,\n `- ${instance.controlBaseUrl}/coverage`,\n `- ${instance.controlBaseUrl}/connections`,\n `- ${instance.controlBaseUrl}/state`,\n `- ${instance.controlBaseUrl}/ledger`,\n `- POST ${instance.controlBaseUrl}/credentials`,\n `- POST ${instance.controlBaseUrl}/seed`,\n `- POST ${instance.controlBaseUrl}/reset`,\n \"\",\n \"Connect:\",\n ...connections.flatMap((c) => [\"\", `## ${c.title}`, c.body]),\n ];\n return lines.join(\"\\n\");\n}\n\nfunction issueDefaultCredential(\n request: CredentialRequest,\n manifest: ServiceManifest,\n tokenMap: TokenMap | undefined,\n): IssuedCredential | null {\n const type = request.type ?? manifest.auth[0]?.type ?? \"bearer-token\";\n if (type !== \"bearer-token\" && type !== \"api-key\") return null;\n if (!tokenMap) return null;\n const token = typeof request.token === \"string\" && request.token ? request.token : `emu_${manifest.id}_${randomId()}`;\n const login = request.login ?? \"admin\";\n const scopes = Array.isArray(request.scopes) ? request.scopes.filter((s): s is string => typeof s === \"string\") : [];\n tokenMap.set(token, { login, id: Date.now(), scopes });\n return { type, token, login, scopes };\n}\n\nfunction redirectToSpec(c: Context<AppEnv>, manifest: ServiceManifest, instance: EmulatorInstanceInfo, kind: string) {\n const spec = manifest.specs.find((s) => s.kind === kind && s.url);\n if (spec?.url) return c.redirect(resolveUrl(instance.providerBaseUrl, spec.url));\n const advertised = manifest.specs.some((s) => s.kind === kind);\n if (kind === \"openapi\" && advertised) return c.redirect(`${instance.providerBaseUrl}/openapi.json`);\n return c.json({ error: \"not_found\", message: `No ${kind} spec is advertised for this emulator.` }, 404);\n}\n\nfunction endpointForSurface(\n c: Context<AppEnv>,\n manifest: ServiceManifest,\n instance: EmulatorInstanceInfo,\n kind: \"graphql\" | \"mcp\",\n) {\n const surface = manifest.surfaces.find((s) => s.kind === kind && s.basePath);\n if (!surface?.basePath) {\n return c.json({ error: \"not_found\", message: `No ${kind} surface is advertised for this emulator.` }, 404);\n }\n return c.json({ endpoint: resolveUrl(instance.providerBaseUrl, surface.basePath), surface });\n}\n\nfunction resolveUrl(baseUrl: string, pathOrUrl: string): string {\n if (/^https?:\\/\\//i.test(pathOrUrl)) return pathOrUrl;\n return `${baseUrl}${pathOrUrl.startsWith(\"/\") ? \"\" : \"/\"}${pathOrUrl}`;\n}\n\nfunction randomId(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction slug(value: string): string {\n return value\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, \"-\")\n .replace(/-+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n","import { Hono, cors } from \"./http.js\";\nimport { Store } from \"./store.js\";\nimport { WebhookDispatcher } from \"./webhooks.js\";\nimport { createApiErrorHandler, createErrorHandler } from \"./middleware/error-handler.js\";\nimport {\n authMiddleware,\n type AuthFallback,\n type TokenMap,\n type AppKeyResolver,\n type AppEnv,\n} from \"./middleware/auth.js\";\nimport type { ServicePlugin } from \"./plugin.js\";\nimport { registerFontRoutes } from \"./fonts.js\";\nimport { RequestLedger, createLedgerMiddleware } from \"./ledger.js\";\nimport { registerControlPlane, type CredentialRequest, type IssuedCredential } from \"./control-plane.js\";\nimport { createDefaultManifest, type ServiceManifest } from \"./manifest.js\";\n\nexport interface ServerOptions {\n port?: number;\n baseUrl?: string;\n docsUrl?: string;\n tokens?: Record<string, { login: string; id: number; scopes?: string[] }>;\n appKeyResolver?: AppKeyResolver;\n fallbackUser?: AuthFallback;\n manifest?: ServiceManifest;\n instance?: string;\n enableControlPlane?: boolean;\n /** True when the host persists the ledger across eviction (e.g. a Durable Object). */\n ledgerPersistent?: boolean;\n /** Host suffix for the deployed form surfaced in control-plane responses. */\n hostSuffix?: string;\n reset?: () => void | Promise<void>;\n seed?: (seed: unknown) => void | Promise<void>;\n issueCredential?: (request: CredentialRequest) => IssuedCredential | Promise<IssuedCredential>;\n}\n\nexport function createServer(plugin: ServicePlugin, options: ServerOptions = {}) {\n const port = options.port ?? 4000;\n const baseUrl = options.baseUrl ?? `http://localhost:${port}`;\n\n const app = new Hono<AppEnv>();\n const store = new Store();\n const webhooks = new WebhookDispatcher();\n const ledger = new RequestLedger();\n\n const tokenMap: TokenMap = new Map();\n if (options.tokens) {\n for (const [token, user] of Object.entries(options.tokens)) {\n tokenMap.set(token, {\n login: user.login,\n id: user.id,\n scopes: user.scopes ?? [\"repo\", \"user\", \"admin:org\", \"admin:repo_hook\"],\n });\n }\n }\n\n const docsUrl = options.docsUrl ?? `https://docs.emulators.dev/${plugin.name}`;\n\n registerFontRoutes(app);\n\n app.onError(createApiErrorHandler(docsUrl));\n app.use(\"*\", cors());\n app.use(\"*\", createErrorHandler(docsUrl));\n app.use(\"*\", authMiddleware(tokenMap, options.appKeyResolver, options.fallbackUser));\n\n if (options.enableControlPlane !== false) {\n const manifest = options.manifest ?? createDefaultManifest(plugin.name);\n registerControlPlane(app, {\n manifest,\n instance: {\n service: manifest.id,\n instance: options.instance,\n baseUrl,\n providerBaseUrl: baseUrl,\n controlBaseUrl: `${baseUrl}/_emulate`,\n },\n store,\n webhooks,\n ledger,\n tokenMap,\n ledgerPersistent: options.ledgerPersistent,\n hostSuffix: options.hostSuffix,\n reset: options.reset,\n seed: options.seed,\n issueCredential: options.issueCredential,\n });\n }\n\n app.use(\"*\", createLedgerMiddleware(ledger, { webhooks }));\n\n const rateLimitCounters = new Map<string, { remaining: number; resetAt: number }>();\n let lastPruneAt = Math.floor(Date.now() / 1000);\n\n app.use(\"*\", async (c, next) => {\n const token = c.get(\"authToken\") ?? \"__anonymous__\";\n const now = Math.floor(Date.now() / 1000);\n\n if (now - lastPruneAt > 3600) {\n for (const [key, val] of rateLimitCounters) {\n if (val.resetAt <= now) rateLimitCounters.delete(key);\n }\n lastPruneAt = now;\n }\n\n let counter = rateLimitCounters.get(token);\n if (!counter || counter.resetAt <= now) {\n counter = { remaining: 5000, resetAt: now + 3600 };\n rateLimitCounters.set(token, counter);\n }\n\n counter.remaining = Math.max(0, counter.remaining - 1);\n\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", String(counter.remaining));\n c.header(\"X-RateLimit-Reset\", String(counter.resetAt));\n c.header(\"X-RateLimit-Resource\", \"core\");\n\n if (counter.remaining === 0) {\n return c.json(\n {\n message: \"API rate limit exceeded\",\n documentation_url: docsUrl,\n },\n 403,\n );\n }\n\n await next();\n });\n\n plugin.register(app, store, webhooks, baseUrl, tokenMap);\n\n app.notFound((c) =>\n c.json(\n {\n message: \"Not Found\",\n documentation_url: docsUrl,\n },\n 404,\n ),\n );\n\n return { app, store, webhooks, ledger, port, baseUrl, tokenMap };\n}\n","import type { EmulatorInstanceInfo, ServiceManifest } from \"./manifest.js\";\nimport { coverageReport, enrichManifest, resolveConnections } from \"./manifest.js\";\nimport { escapeHtml, renderCardPage } from \"./ui.js\";\nimport { renderQuickstart, INSTANCE_NOTES } from \"./control-plane.js\";\n\nexport interface ServiceHostContext {\n manifest: ServiceManifest;\n service: string;\n /** Apex origin for the path form, e.g. https://emulators.dev. */\n origin: string;\n /** Request protocol including the colon, e.g. \"https:\". */\n protocol: string;\n /** Host suffix for the deployed form, e.g. \"emulators.dev\". */\n hostSuffix: string;\n /** Whether the deployed host persists the ledger across eviction. */\n ledgerPersistent?: boolean;\n}\n\nconst SAMPLE_INSTANCE = \"your-instance\";\n\nfunction sampleInstanceInfo(ctx: ServiceHostContext): EmulatorInstanceInfo {\n const providerBaseUrl = `${ctx.protocol}//${ctx.service}.${SAMPLE_INSTANCE}.${ctx.hostSuffix}`;\n return {\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n baseUrl: providerBaseUrl,\n providerBaseUrl,\n controlBaseUrl: `${providerBaseUrl}/_emulate`,\n };\n}\n\nfunction json(data: unknown, status = 200): Response {\n return new Response(JSON.stringify(data), {\n status,\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n\n/**\n * Serve the service-level control plane on a bare service host (e.g.\n * github.emulators.dev) so a human or agent can read the manifest, quickstart,\n * specs, coverage, and connection snippets WITHOUT first creating an instance.\n * Returns null for paths this should not handle (so the caller can fall through\n * to the interactive console SPA).\n */\nexport function serviceHostControlPlane(path: string, method: string, ctx: ServiceHostContext): Response | null {\n if (!path.startsWith(\"/_emulate\")) return null;\n if (method !== \"GET\" && method !== \"HEAD\") return null;\n\n const manifest = enrichManifest(ctx.manifest, { ledgerPersistent: ctx.ledgerPersistent });\n const sample = sampleInstanceInfo(ctx);\n const connections = resolveConnections(manifest.connections ?? [], {\n baseUrl: sample.providerBaseUrl,\n providerBaseUrl: sample.providerBaseUrl,\n controlBaseUrl: sample.controlBaseUrl,\n service: ctx.service,\n instance: SAMPLE_INSTANCE,\n defaultAuthType: manifest.auth[0]?.type ?? \"bearer-token\",\n });\n\n switch (path) {\n case \"/_emulate\":\n return new Response(renderServiceLanding(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/html; charset=utf-8\" },\n });\n case \"/_emulate/manifest\":\n return json({ manifest, instance: null, sampleInstance: sample, connections });\n case \"/_emulate/quickstart\":\n return new Response(renderServiceQuickstart(manifest, ctx, sample), {\n headers: { \"content-type\": \"text/plain; charset=utf-8\" },\n });\n case \"/_emulate/specs\":\n return json({ specs: manifest.specs, surfaces: manifest.surfaces });\n case \"/_emulate/coverage\":\n return json(coverageReport(manifest));\n case \"/_emulate/connections\":\n return json({ connections });\n case \"/_emulate/openapi\": {\n const spec = manifest.specs.find((s) => s.kind === \"openapi\");\n if (!spec) return json({ error: \"not_found\", message: \"No OpenAPI spec is advertised for this emulator.\" }, 404);\n return json({\n openapi: `${sample.providerBaseUrl}${spec.url ?? \"/openapi.json\"}`,\n note: \"Create an instance, then fetch this URL for the live spec.\",\n });\n }\n default:\n return null;\n }\n}\n\nfunction renderServiceQuickstart(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const base = renderQuickstart(manifest, sample);\n const header = [\n `# ${manifest.name} Emulator (service host)`,\n \"\",\n \"Create an instance:\",\n `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances -H 'content-type: application/json' -d '{\"instance\":\"my-run\"}'`,\n `# ${INSTANCE_NOTES}`,\n \"\",\n \"Then use the returned providerBaseUrl / controlBaseUrl. Example below uses a sample instance.\",\n \"\",\n ];\n return header.join(\"\\n\") + base;\n}\n\nfunction renderServiceLanding(\n manifest: ServiceManifest,\n ctx: ServiceHostContext,\n sample: EmulatorInstanceInfo,\n): string {\n const surfaces = manifest.surfaces\n .map(\n (s) =>\n `<tr><td>${escapeHtml(s.title)}</td><td><span class=\"badge\">${escapeHtml(s.status)}</span></td><td><code>${escapeHtml(s.basePath ?? \"\")}</code></td></tr>`,\n )\n .join(\"\");\n const createCurl = `curl -s -X POST ${ctx.protocol}//${ctx.service}.${ctx.hostSuffix}/_emulate/instances \\\\\n -H \"content-type: application/json\" \\\\\n -d '{\"instance\":\"my-run\"}'`;\n\n return renderCardPage(\n `${manifest.name} Emulator`,\n escapeHtml(manifest.description),\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Create an instance</div>\n <p class=\"info-text\">Each instance is isolated, stateful, and addressable at its own host.</p>\n <pre class=\"code-block\"><code>${escapeHtml(createCurl)}</code></pre>\n <p class=\"info-text\">${escapeHtml(INSTANCE_NOTES)}</p>\n <p class=\"info-text\">Sample instance host: <code>${escapeHtml(sample.providerBaseUrl)}</code></p>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Surfaces</div>\n <table class=\"inspector-table\">\n <thead><tr><th>Surface</th><th>Status</th><th>Path</th></tr></thead>\n <tbody>${surfaces}</tbody>\n </table>\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">Control API</div>\n <p class=\"info-text\">\n <a href=\"/_emulate/manifest\">manifest</a> | <a href=\"/_emulate/quickstart\">quickstart</a> |\n <a href=\"/_emulate/specs\">specs</a> | <a href=\"/_emulate/coverage\">coverage</a> |\n <a href=\"/_emulate/connections\">connections</a>\n </p>\n </div>\n `,\n manifest.id,\n );\n}\n\nexport interface ServiceCatalogEntry {\n id: string;\n name: string;\n description: string;\n}\n\n/**\n * Server-rendered catalog landing for the apex host. Readable by an agent over a\n * raw fetch (no JS): it lists every emulator with its host and manifest URL. The\n * interactive console SPA is served instead only for browser navigations.\n */\nexport function renderCatalogPage(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): string {\n const rows = entries\n .map((e) => {\n const host = `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`;\n return `<a class=\"app-link\" href=\"${escapeHtml(host)}\">\n <img src=\"/_emulate/icons/${escapeHtml(e.id)}\" alt=\"\" width=\"24\" height=\"24\" style=\"object-fit:contain\" />\n <span><span class=\"app-link-name\">${escapeHtml(e.name)}</span><span class=\"app-link-scopes\">${escapeHtml(host)}</span></span>\n </a>`;\n })\n .join(\"\");\n return renderCardPage(\n \"Emulate\",\n \"Stateful integration emulators for real developer APIs. Each emulator has its own host; open one or fetch its manifest.\",\n `\n <div class=\"s-card\">\n <div class=\"section-heading\">Emulators</div>\n ${rows}\n </div>\n <div class=\"s-card\">\n <div class=\"section-heading\">For agents</div>\n <p class=\"info-text\">Machine-readable catalog: <a href=\"/_emulate/services\">/_emulate/services</a></p>\n <p class=\"info-text\">Each service host serves <code>/_emulate/manifest</code>, <code>/_emulate/quickstart</code>, and <code>/_emulate/connections</code>, and the provider API directly against a default instance.</p>\n </div>\n `,\n );\n}\n\n/** A machine-readable index of the services a host serves, with both URL forms. */\nexport function servicesCatalog(\n entries: ServiceCatalogEntry[],\n ctx: { origin: string; protocol: string; hostSuffix: string },\n): Response {\n const services = entries.map((e) => ({\n id: e.id,\n name: e.name,\n description: e.description,\n icon: `${ctx.origin}/_emulate/icons/${e.id}`,\n serviceHost: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}`,\n instanceHostPattern: `${ctx.protocol}//${e.id}.<instance>.${ctx.hostSuffix}`,\n pathForm: `${ctx.origin}/${e.id}/<instance>`,\n manifest: `${ctx.protocol}//${e.id}.${ctx.hostSuffix}/_emulate/manifest`,\n }));\n return new Response(JSON.stringify({ services }), {\n headers: { \"content-type\": \"application/json; charset=utf-8\" },\n });\n}\n","import type { Context } from \"../http.js\";\n\nexport interface PaginationParams {\n page: number;\n per_page: number;\n}\n\nexport function parsePagination(c: Context): PaginationParams {\n const page = Math.max(1, parseInt(c.req.query(\"page\") ?? \"1\", 10) || 1);\n const per_page = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n return { page, per_page };\n}\n\nexport function setLinkHeader(c: Context, totalCount: number, page: number, perPage: number): void {\n const lastPage = Math.max(1, Math.ceil(totalCount / perPage));\n const baseUrl = new URL(c.req.url);\n const links: string[] = [];\n\n const makeLink = (p: number, rel: string) => {\n baseUrl.searchParams.set(\"page\", String(p));\n baseUrl.searchParams.set(\"per_page\", String(perPage));\n return `<${baseUrl.toString()}>; rel=\"${rel}\"`;\n };\n\n if (page < lastPage) {\n links.push(makeLink(page + 1, \"next\"));\n links.push(makeLink(lastPage, \"last\"));\n }\n if (page > 1) {\n links.push(makeLink(1, \"first\"));\n links.push(makeLink(page - 1, \"prev\"));\n }\n\n if (links.length > 0) {\n c.header(\"Link\", links.join(\", \"));\n }\n}\n","import { timingSafeEqual } from \"crypto\";\n\nexport function normalizeUri(uri: string): string {\n try {\n const u = new URL(uri);\n return `${u.origin}${u.pathname.replace(/\\/+$/, \"\")}`;\n } catch {\n return uri.replace(/\\/+$/, \"\").split(\"?\")[0];\n }\n}\n\nexport function matchesRedirectUri(incoming: string, registered: string[]): boolean {\n const normalized = normalizeUri(incoming);\n return registered.some((r) => normalizeUri(r) === normalized);\n}\n\nexport function constantTimeSecretEqual(a: string, b: string): boolean {\n const bufA = Buffer.from(a, \"utf-8\");\n const bufB = Buffer.from(b, \"utf-8\");\n if (bufA.length !== bufB.length) return false;\n return timingSafeEqual(bufA, bufB);\n}\n\nexport function bodyStr(v: unknown): string {\n if (typeof v === \"string\") return v;\n if (Array.isArray(v) && typeof v[0] === \"string\") return v[0];\n return \"\";\n}\n\nexport function parseCookies(header: string): Record<string, string> {\n const cookies: Record<string, string> = {};\n for (const part of header.split(\";\")) {\n const [k, ...v] = part.split(\"=\");\n if (k) cookies[k.trim()] = v.join(\"=\").trim();\n }\n return cookies;\n}\n","import { readFile, writeFile, mkdir } from \"node:fs/promises\";\nimport { dirname } from \"node:path\";\n\nexport interface PersistenceAdapter {\n load(): Promise<string | null>;\n save(data: string): Promise<void>;\n}\n\nexport function filePersistence(path: string): PersistenceAdapter {\n return {\n async load() {\n try {\n return await readFile(path, \"utf-8\");\n } catch {\n return null;\n }\n },\n async save(data: string) {\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, data, \"utf-8\");\n },\n };\n}\n","import type { Context, Store } from \"@emulators/core\";\nimport { lookupAccessToken } from \"../store.js\";\nimport type { XAccessToken } from \"../entities.js\";\n\n/**\n * Extract and resolve the bearer token presented on a v2 API request. Returns the\n * matching access-token row (app-only or user-context) or `null`.\n */\nexport function resolveToken(store: Store, c: Context): XAccessToken | null {\n const m = /^Bearer\\s+(.+)$/i.exec(c.req.header(\"Authorization\") ?? \"\");\n if (!m) return null;\n return lookupAccessToken(store, m[1].trim()) ?? null;\n}\n\n/** X v2 error envelope for a missing or invalid bearer token (HTTP 401). */\nexport function unauthorized(c: Context) {\n return c.json(\n {\n title: \"Unauthorized\",\n type: \"about:blank\",\n status: 401,\n detail: \"Unauthorized\",\n },\n 401,\n );\n}\n\n/**\n * X v2 error envelope for an authenticated request that lacks the required scope\n * or token type (HTTP 403). Used when an app-only token hits a user-context\n * endpoint, or when a user token is missing a required scope.\n */\nexport function forbidden(c: Context, detail: string) {\n return c.json(\n {\n title: \"Forbidden\",\n type: \"https://api.twitter.com/2/problems/oauth2-insufficient-scope\",\n status: 403,\n detail,\n },\n 403,\n );\n}\n\n/** True when the token is a user-context token that holds every required scope. */\nexport function hasUserScope(token: XAccessToken, ...required: string[]): boolean {\n if (token.app_only) return false;\n return required.every((s) => token.scopes.includes(s));\n}\n","import type { Context, RouteContext } from \"@emulators/core\";\nimport { getXStore } from \"../store.js\";\nimport type { XUser } from \"../entities.js\";\nimport { resolveToken, unauthorized, forbidden, hasUserScope } from \"./auth.js\";\n\n/**\n * Format an X user into the v2 user object. The default fields match what the v2\n * API returns without an explicit `user.fields` request, plus the common\n * expansions tools rely on (public_metrics, verified, etc.).\n */\nfunction formatUser(u: XUser): Record<string, unknown> {\n return {\n id: u.user_id,\n name: u.name,\n username: u.username,\n created_at: u.created_at_x,\n description: u.description,\n location: u.location,\n url: u.url,\n protected: u.protected,\n verified: u.verified,\n profile_image_url: u.profile_image_url,\n public_metrics: {\n followers_count: u.followers_count,\n following_count: u.following_count,\n tweet_count: u.tweet_count,\n listed_count: u.listed_count,\n },\n };\n}\n\nfunction notFound(c: Context, detail: string) {\n return c.json(\n {\n errors: [\n {\n title: \"Not Found Error\",\n type: \"https://api.twitter.com/2/problems/resource-not-found\",\n detail,\n },\n ],\n },\n 404,\n );\n}\n\nexport function usersRoutes({ app, store }: RouteContext): void {\n const xs = getXStore(store);\n\n // GET /2/users/me — the authenticated user. Requires a user-context token with\n // the users.read scope (app-only tokens have no user → 403).\n app.get(\"/2/users/me\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (token.app_only) {\n return forbidden(c, \"This endpoint requires a user-context OAuth 2.0 token; an app-only token has no user.\");\n }\n if (!hasUserScope(token, \"users.read\")) {\n return forbidden(c, \"Your token is missing the users.read scope required by this endpoint.\");\n }\n const user = token.user_id ? xs.users.findOneBy(\"user_id\", token.user_id) : undefined;\n if (!user) return unauthorized(c);\n return c.json({ data: formatUser(user) });\n });\n\n // GET /2/users/:id — app-only bearer OR user token with users.read.\n app.get(\"/2/users/:id\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (!token.app_only && !hasUserScope(token, \"users.read\")) {\n return forbidden(c, \"Your token is missing the users.read scope required by this endpoint.\");\n }\n const user = xs.users.findOneBy(\"user_id\", c.req.param(\"id\"));\n if (!user) return notFound(c, `Could not find user with id: [${c.req.param(\"id\")}].`);\n return c.json({ data: formatUser(user) });\n });\n\n // GET /2/users/by/username/:username — app-only bearer OR user token.\n app.get(\"/2/users/by/username/:username\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (!token.app_only && !hasUserScope(token, \"users.read\")) {\n return forbidden(c, \"Your token is missing the users.read scope required by this endpoint.\");\n }\n const username = c.req.param(\"username\").toLowerCase();\n const user = xs.users.findOneBy(\"username\", username);\n if (!user) return notFound(c, `Could not find user with username: [${c.req.param(\"username\")}].`);\n return c.json({ data: formatUser(user) });\n });\n}\n","import type { Context, RouteContext } from \"@emulators/core\";\nimport { getXStore, xNumericId } from \"../store.js\";\nimport type { XTweet } from \"../entities.js\";\nimport { resolveToken, unauthorized, forbidden, hasUserScope } from \"./auth.js\";\n\n/** Format a tweet into the v2 tweet object (default fields plus public_metrics). */\nfunction formatTweet(t: XTweet): Record<string, unknown> {\n return {\n id: t.tweet_id,\n text: t.text,\n author_id: t.author_id,\n created_at: t.created_at_x,\n conversation_id: t.conversation_id,\n lang: t.lang,\n possibly_sensitive: t.possibly_sensitive,\n in_reply_to_user_id: t.in_reply_to_user_id,\n edit_history_tweet_ids: [t.tweet_id],\n public_metrics: {\n retweet_count: t.retweet_count,\n reply_count: t.reply_count,\n like_count: t.like_count,\n quote_count: t.quote_count,\n impression_count: t.impression_count,\n },\n };\n}\n\nfunction notFound(c: Context, detail: string) {\n return c.json(\n {\n errors: [\n {\n title: \"Not Found Error\",\n type: \"https://api.twitter.com/2/problems/resource-not-found\",\n detail,\n },\n ],\n },\n 404,\n );\n}\n\nexport function tweetsRoutes({ app, store }: RouteContext): void {\n const xs = getXStore(store);\n\n // GET /2/tweets/:id — app-only bearer OR user token, both need tweet.read for a\n // user-context token (app-only is implicitly read).\n app.get(\"/2/tweets/:id\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (!token.app_only && !hasUserScope(token, \"tweet.read\")) {\n return forbidden(c, \"Your token is missing the tweet.read scope required by this endpoint.\");\n }\n const tweet = xs.tweets.findOneBy(\"tweet_id\", c.req.param(\"id\"));\n if (!tweet) return notFound(c, `Could not find tweet with id: [${c.req.param(\"id\")}].`);\n return c.json({ data: formatTweet(tweet) });\n });\n\n // GET /2/tweets?ids=1,2,3 — batch lookup by id.\n app.get(\"/2/tweets\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (!token.app_only && !hasUserScope(token, \"tweet.read\")) {\n return forbidden(c, \"Your token is missing the tweet.read scope required by this endpoint.\");\n }\n const idsParam = c.req.query(\"ids\") ?? \"\";\n const ids = idsParam\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n if (ids.length === 0) {\n return c.json(\n {\n errors: [\n {\n parameters: { ids: [] },\n message: \"The `ids` query parameter is required and must be a comma-separated list of Tweet IDs.\",\n },\n ],\n title: \"Invalid Request\",\n detail: \"One or more parameters to your request was invalid.\",\n type: \"https://api.twitter.com/2/problems/invalid-request\",\n },\n 400,\n );\n }\n const data: Array<Record<string, unknown>> = [];\n const errors: Array<Record<string, unknown>> = [];\n for (const id of ids) {\n const tweet = xs.tweets.findOneBy(\"tweet_id\", id);\n if (tweet) {\n data.push(formatTweet(tweet));\n } else {\n errors.push({\n value: id,\n detail: `Could not find tweet with ids: [${id}].`,\n title: \"Not Found Error\",\n resource_type: \"tweet\",\n parameter: \"ids\",\n resource_id: id,\n type: \"https://api.twitter.com/2/problems/resource-not-found\",\n });\n }\n }\n const out: Record<string, unknown> = { data };\n if (errors.length > 0) out.errors = errors;\n return c.json(out);\n });\n\n // GET /2/users/:id/tweets — a user's timeline. App-only bearer OR user token.\n app.get(\"/2/users/:id/tweets\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (!token.app_only && !hasUserScope(token, \"tweet.read\")) {\n return forbidden(c, \"Your token is missing the tweet.read scope required by this endpoint.\");\n }\n const authorId = c.req.param(\"id\");\n const author = xs.users.findOneBy(\"user_id\", authorId);\n if (!author) return notFound(c, `Could not find user with id: [${authorId}].`);\n const tweets = xs.tweets.findBy(\"author_id\", authorId).sort((a, b) => b.created_at_x.localeCompare(a.created_at_x));\n return c.json({\n data: tweets.map(formatTweet),\n meta: {\n result_count: tweets.length,\n newest_id: tweets[0]?.tweet_id,\n oldest_id: tweets[tweets.length - 1]?.tweet_id,\n },\n });\n });\n\n // POST /2/tweets — create a tweet. Requires a user token with tweet.write.\n app.post(\"/2/tweets\", async (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (token.app_only) {\n return forbidden(c, \"Creating a Tweet requires a user-context OAuth 2.0 token; an app-only token cannot post.\");\n }\n if (!hasUserScope(token, \"tweet.write\")) {\n return forbidden(c, \"Your token is missing the tweet.write scope required to create a Tweet.\");\n }\n const author = token.user_id ? xs.users.findOneBy(\"user_id\", token.user_id) : undefined;\n if (!author) return unauthorized(c);\n\n const body = (await c.req.json().catch(() => ({}))) as Record<string, unknown>;\n const text = typeof body.text === \"string\" ? body.text : \"\";\n if (!text.trim()) {\n return c.json(\n {\n errors: [{ message: \"text or media is required\", parameters: {} }],\n title: \"Invalid Request\",\n detail: \"One or more parameters to your request was invalid.\",\n type: \"https://api.twitter.com/2/problems/invalid-request\",\n },\n 400,\n );\n }\n\n const reply = body.reply as { in_reply_to_tweet_id?: unknown } | undefined;\n const inReplyToTweetId =\n reply && typeof reply.in_reply_to_tweet_id === \"string\" ? reply.in_reply_to_tweet_id : null;\n const parent = inReplyToTweetId ? xs.tweets.findOneBy(\"tweet_id\", inReplyToTweetId) : undefined;\n\n const tweetId = xNumericId();\n const tweet = xs.tweets.insert({\n tweet_id: tweetId,\n author_id: author.user_id,\n text,\n reply_count: 0,\n retweet_count: 0,\n like_count: 0,\n quote_count: 0,\n impression_count: 0,\n in_reply_to_user_id: parent ? parent.author_id : null,\n conversation_id: parent ? parent.conversation_id : tweetId,\n lang: \"en\",\n possibly_sensitive: false,\n created_at_x: new Date().toISOString(),\n });\n xs.users.update(author.id, { tweet_count: author.tweet_count + 1 });\n if (parent) xs.tweets.update(parent.id, { reply_count: parent.reply_count + 1 });\n\n // X returns a minimal create payload: { data: { id, text } }.\n return c.json({ data: { id: tweet.tweet_id, text: tweet.text } }, 201);\n });\n\n // DELETE /2/tweets/:id — delete a tweet. Requires a user token with tweet.write.\n app.delete(\"/2/tweets/:id\", (c) => {\n const token = resolveToken(store, c);\n if (!token) return unauthorized(c);\n if (token.app_only) {\n return forbidden(c, \"Deleting a Tweet requires a user-context OAuth 2.0 token; an app-only token cannot delete.\");\n }\n if (!hasUserScope(token, \"tweet.write\")) {\n return forbidden(c, \"Your token is missing the tweet.write scope required to delete a Tweet.\");\n }\n const tweet = xs.tweets.findOneBy(\"tweet_id\", c.req.param(\"id\"));\n if (!tweet) return notFound(c, `Could not find tweet with id: [${c.req.param(\"id\")}].`);\n // X only lets you delete your own tweet.\n if (token.user_id && tweet.author_id !== token.user_id) {\n return forbidden(c, \"You may only delete your own Tweets.\");\n }\n xs.tweets.delete(tweet.id);\n return c.json({ data: { deleted: true } });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { X_SCOPES } from \"./oauth.js\";\n\n/**\n * Serves a curated OpenAPI 3.0 subset of the X (Twitter) v2 API, pointed at this\n * emulator instance. It declares the three real X security schemes (app-only\n * BearerToken, OAuth 2.0 user-context with PKCE, and the legacy OAuth 1.0a\n * UserToken modelled as a partial/unsupported surface) and the operations this\n * emulator actually implements. Served at both /2/openapi.json (X's real path)\n * and /openapi.json (the emulate convention).\n */\nexport function openapiRoutes({ app, baseUrl }: RouteContext): void {\n const handler = (c: { json: (v: unknown) => Response }) => c.json(buildSpec(baseUrl));\n app.get(\"/2/openapi.json\", handler);\n app.get(\"/openapi.json\", handler);\n}\n\nconst ok = (description: string) => ({\n description,\n content: { \"application/json\": { schema: { type: \"object\" } } },\n});\n\nfunction buildSpec(baseUrl: string): Record<string, unknown> {\n const userScopes = Object.fromEntries(X_SCOPES.map((s) => [s, `Scope: ${s}`]));\n return {\n openapi: \"3.0.3\",\n info: {\n title: \"X API v2 (Emulated)\",\n version: \"2.0.0\",\n description:\n \"Emulated subset of the X (formerly Twitter) API v2. Supports app-only Bearer tokens (client_credentials), the OAuth 2.0 Authorization Code flow with PKCE (user context), and a documented-partial legacy OAuth 1.0a user context.\",\n },\n servers: [{ url: baseUrl }],\n components: {\n securitySchemes: {\n // App-only Bearer token, minted via POST /2/oauth2/token grant_type=client_credentials.\n BearerToken: {\n type: \"http\",\n scheme: \"bearer\",\n description:\n \"App-only Bearer token (OAuth 2.0 client_credentials). Minted with client_secret_basic (HTTP Basic) only; client_secret_post is not supported. Read-only public endpoints.\",\n },\n // OAuth 2.0 Authorization Code with PKCE (S256). User context.\n OAuth2UserToken: {\n type: \"oauth2\",\n description:\n \"OAuth 2.0 Authorization Code with PKCE (S256). User-context access and writes. Confidential clients authenticate with client_secret_basic (HTTP Basic) only; client_secret_post is not supported.\",\n flows: {\n authorizationCode: {\n authorizationUrl: `${baseUrl}/2/oauth2/authorize`,\n tokenUrl: `${baseUrl}/2/oauth2/token`,\n scopes: userScopes,\n },\n },\n },\n // Legacy OAuth 1.0a user context — declared faithfully but NOT implemented.\n UserToken: {\n type: \"http\",\n scheme: \"OAuth\",\n description:\n \"Legacy OAuth 1.0a user context. Declared for fidelity but emulated as a partial/unsupported surface; the emulator does not validate OAuth 1.0a signatures.\",\n },\n },\n },\n security: [{ BearerToken: [] }, { OAuth2UserToken: [...X_SCOPES] }],\n paths: {\n \"/2/oauth2/token\": {\n post: {\n operationId: \"oauth2Token\",\n summary: \"Token endpoint (authorization_code, refresh_token, client_credentials)\",\n responses: { \"200\": ok(\"Token response.\"), \"400\": ok(\"OAuth error.\"), \"401\": ok(\"invalid_client.\") },\n },\n },\n \"/2/oauth2/revoke\": {\n post: { operationId: \"oauth2Revoke\", summary: \"Revoke a token\", responses: { \"200\": ok(\"Revoked.\") } },\n },\n \"/2/users/me\": {\n get: {\n operationId: \"findMyUser\",\n summary: \"Get the authenticated user\",\n security: [{ OAuth2UserToken: [\"users.read\"] }],\n responses: { \"200\": ok(\"User object.\"), \"401\": ok(\"Unauthorized.\"), \"403\": ok(\"Insufficient scope.\") },\n },\n },\n \"/2/users/{id}\": {\n get: {\n operationId: \"findUserById\",\n summary: \"Get a user by id\",\n parameters: [{ name: \"id\", in: \"path\", required: true, schema: { type: \"string\" } }],\n security: [{ BearerToken: [] }, { OAuth2UserToken: [\"users.read\"] }],\n responses: { \"200\": ok(\"User object.\"), \"404\": ok(\"Not found.\") },\n },\n },\n \"/2/users/by/username/{username}\": {\n get: {\n operationId: \"findUserByUsername\",\n summary: \"Get a user by username\",\n parameters: [{ name: \"username\", in: \"path\", required: true, schema: { type: \"string\" } }],\n security: [{ BearerToken: [] }, { OAuth2UserToken: [\"users.read\"] }],\n responses: { \"200\": ok(\"User object.\"), \"404\": ok(\"Not found.\") },\n },\n },\n \"/2/users/{id}/tweets\": {\n get: {\n operationId: \"usersIdTweets\",\n summary: \"Get a user's Tweets timeline\",\n parameters: [{ name: \"id\", in: \"path\", required: true, schema: { type: \"string\" } }],\n security: [{ BearerToken: [] }, { OAuth2UserToken: [\"tweet.read\", \"users.read\"] }],\n responses: { \"200\": ok(\"Tweet list.\"), \"404\": ok(\"Not found.\") },\n },\n },\n \"/2/tweets/{id}\": {\n get: {\n operationId: \"findTweetById\",\n summary: \"Get a Tweet by id\",\n parameters: [{ name: \"id\", in: \"path\", required: true, schema: { type: \"string\" } }],\n security: [{ BearerToken: [] }, { OAuth2UserToken: [\"tweet.read\"] }],\n responses: { \"200\": ok(\"Tweet object.\"), \"404\": ok(\"Not found.\") },\n },\n delete: {\n operationId: \"deleteTweetById\",\n summary: \"Delete a Tweet\",\n parameters: [{ name: \"id\", in: \"path\", required: true, schema: { type: \"string\" } }],\n security: [{ OAuth2UserToken: [\"tweet.write\"] }],\n responses: { \"200\": ok(\"Deletion result.\"), \"403\": ok(\"Insufficient scope.\") },\n },\n },\n \"/2/tweets\": {\n get: {\n operationId: \"findTweetsById\",\n summary: \"Get Tweets by ids\",\n parameters: [{ name: \"ids\", in: \"query\", required: true, schema: { type: \"string\" } }],\n security: [{ BearerToken: [] }, { OAuth2UserToken: [\"tweet.read\"] }],\n responses: { \"200\": ok(\"Tweet list.\"), \"400\": ok(\"Invalid request.\") },\n },\n post: {\n operationId: \"createTweet\",\n summary: \"Create a Tweet\",\n security: [{ OAuth2UserToken: [\"tweet.write\"] }],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: { type: \"object\", required: [\"text\"], properties: { text: { type: \"string\" } } },\n },\n },\n },\n responses: { \"201\": ok(\"Created Tweet.\"), \"403\": ok(\"Insufficient scope.\") },\n },\n },\n },\n };\n}\n","import type { ServiceManifest } from \"@emulators/core\";\n\n/**\n * X's machine-readable service manifest. The single source of truth for X's\n * surfaces, auth, specs, seed shape, and copyable connection snippets, consumed\n * by the CLI registry, the Cloudflare host, and the console.\n *\n * X is modelled around its real authentication strategies: an app-only Bearer\n * token (OAuth 2.0 client_credentials), the OAuth 2.0 Authorization Code flow\n * with PKCE for user context, and the legacy OAuth 1.0a user context declared as\n * a documented-partial surface. There is intentionally no GraphQL or MCP surface\n * because the public X API v2 does not expose them.\n */\nexport const manifest: ServiceManifest = {\n id: \"x\",\n name: \"X\",\n description:\n \"Stateful X (formerly Twitter) API v2 emulator focused on faithful auth: app-only Bearer tokens, OAuth 2.0 Authorization Code with PKCE, and a documented-partial legacy OAuth 1.0a surface.\",\n docsUrl: \"https://docs.emulators.dev/x\",\n surfaces: [\n { id: \"rest\", kind: \"rest\", title: \"X API v2 (REST)\", status: \"partial\", basePath: \"/2\" },\n {\n id: \"oauth2\",\n kind: \"oauth\",\n title: \"OAuth 2.0 Authorization Code (PKCE)\",\n status: \"supported\",\n basePath: \"/2/oauth2\",\n },\n {\n id: \"app-only\",\n kind: \"oauth\",\n title: \"App-only Bearer token (client credentials)\",\n status: \"supported\",\n basePath: \"/2/oauth2/token\",\n },\n {\n id: \"oauth1\",\n kind: \"provider-specific\",\n title: \"Legacy OAuth 1.0a user context\",\n status: \"unsupported\",\n notes: \"Declared for fidelity. Signature validation is not implemented.\",\n },\n ],\n auth: [\n {\n id: \"bearer-token\",\n title: \"App-only Bearer token\",\n type: \"bearer-token\",\n status: \"supported\",\n notes: \"Minted via POST /2/oauth2/token grant_type=client_credentials with HTTP Basic client auth.\",\n },\n {\n id: \"oauth2-user\",\n title: \"OAuth 2.0 Authorization Code with PKCE\",\n type: \"oauth-authorization-code\",\n status: \"supported\",\n notes:\n \"Confidential clients authenticate with client_secret_basic (HTTP Basic header) only; X does not support client_secret_post, so a secret in the request body is rejected. Public clients send client_id in the body and rely on PKCE (S256). offline.access yields a refresh token.\",\n },\n {\n id: \"oauth1-user\",\n title: \"Legacy OAuth 1.0a user context\",\n type: \"provider-specific\",\n status: \"unsupported\",\n notes: \"Accepted honestly as a partial surface; OAuth 1.0a request signing is not emulated.\",\n },\n ],\n specs: [\n {\n kind: \"openapi\",\n title: \"X API v2 subset\",\n coverage: \"hand-authored\",\n url: \"/2/openapi.json\",\n operations: [\n {\n operationId: \"oauth2Token\",\n method: \"POST\",\n path: \"/2/oauth2/token\",\n status: \"hand-authored\",\n summary: \"authorization_code (PKCE), refresh_token, and client_credentials grants.\",\n },\n { operationId: \"oauth2Revoke\", method: \"POST\", path: \"/2/oauth2/revoke\", status: \"hand-authored\" },\n {\n operationId: \"findMyUser\",\n method: \"GET\",\n path: \"/2/users/me\",\n status: \"hand-authored\",\n summary: \"User-context token with users.read.\",\n },\n { operationId: \"findUserById\", method: \"GET\", path: \"/2/users/:id\", status: \"hand-authored\" },\n {\n operationId: \"findUserByUsername\",\n method: \"GET\",\n path: \"/2/users/by/username/:username\",\n status: \"hand-authored\",\n },\n { operationId: \"usersIdTweets\", method: \"GET\", path: \"/2/users/:id/tweets\", status: \"hand-authored\" },\n { operationId: \"findTweetById\", method: \"GET\", path: \"/2/tweets/:id\", status: \"hand-authored\" },\n { operationId: \"findTweetsById\", method: \"GET\", path: \"/2/tweets\", status: \"hand-authored\" },\n {\n operationId: \"createTweet\",\n method: \"POST\",\n path: \"/2/tweets\",\n status: \"hand-authored\",\n summary: \"User-context token with tweet.write.\",\n },\n { operationId: \"deleteTweetById\", method: \"DELETE\", path: \"/2/tweets/:id\", status: \"hand-authored\" },\n {\n operationId: \"tweetsRecentSearch\",\n method: \"GET\",\n path: \"/2/tweets/search/recent\",\n status: \"unsupported\",\n },\n { operationId: \"usersIdFollow\", method: \"POST\", path: \"/2/users/:id/following\", status: \"unsupported\" },\n { operationId: \"usersIdLike\", method: \"POST\", path: \"/2/users/:id/likes\", status: \"unsupported\" },\n ],\n },\n {\n kind: \"oauth-metadata\",\n title: \"OAuth 2.0 client-auth behavior (confidential clients use client_secret_basic only)\",\n coverage: \"hand-authored\",\n },\n ],\n scenarios: [\n {\n id: \"default\",\n title: \"Single developer account\",\n description: \"One verified user with a seeded confidential and public OAuth client.\",\n },\n ],\n seedSchema: {\n description: \"Seed users, OAuth 2.0 clients (confidential or public), and Tweets.\",\n fields: [\n {\n key: \"users\",\n title: \"Users\",\n description: \"X accounts addressable by username (@handle) and numeric id.\",\n example: [{ username: \"developer\", name: \"Developer\", verified: true }],\n },\n {\n key: \"oauth_clients\",\n title: \"OAuth 2.0 clients\",\n description:\n \"Confidential clients have a client_secret and use HTTP Basic auth; public clients omit it and use PKCE only.\",\n example: [\n {\n client_id: \"x-confidential-client\",\n client_secret: \"x-confidential-secret\",\n client_type: \"confidential\",\n name: \"My X App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n { client_id: \"x-public-client\", client_type: \"public\", name: \"My X SPA\" },\n ],\n },\n {\n key: \"tweets\",\n title: \"Tweets\",\n description: \"Tweets authored by a seeded user (referenced by username or id).\",\n example: [{ text: \"Hello from X.\", author: \"developer\", like_count: 42 }],\n },\n ],\n example: {\n users: [{ username: \"developer\", name: \"Developer\", verified: true, followers_count: 1200 }],\n oauth_clients: [\n {\n client_id: \"x-confidential-client\",\n client_secret: \"x-confidential-secret\",\n client_type: \"confidential\",\n name: \"My X App\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n { client_id: \"x-public-client\", client_type: \"public\", name: \"My X SPA\" },\n ],\n tweets: [{ text: \"Hello from the X API v2 emulator.\", author: \"developer\", like_count: 42, retweet_count: 7 }],\n },\n },\n stateModel: {\n description: \"Entities seeded and mutated by X provider calls.\",\n collections: [\n { name: \"x.users\", title: \"Users\" },\n { name: \"x.tweets\", title: \"Tweets\" },\n { name: \"x.oauth_clients\", title: \"OAuth 2.0 clients\" },\n { name: \"x.auth_codes\", title: \"Authorization codes\" },\n { name: \"x.access_tokens\", title: \"Access tokens\" },\n { name: \"x.refresh_tokens\", title: \"Refresh tokens\" },\n ],\n },\n connections: [\n {\n id: \"twitter-api-v2\",\n title: \"twitter-api-v2 (TypeScript)\",\n kind: \"sdk\",\n language: \"typescript\",\n description: \"Point the twitter-api-v2 SDK at the emulator for both app-only and user-context auth.\",\n template:\n 'import { TwitterApi } from \"twitter-api-v2\";\\n\\nconst base = \"{{baseUrl}}\";\\n\\n// App-only Bearer token (client_credentials).\\nconst appClient = new TwitterApi(\"{{token}}\", { baseUrl: base });\\nconst user = await appClient.v2.userByUsername(\"developer\");\\n\\n// OAuth 2.0 user-context client (Authorization Code with PKCE).\\nconst oauthClient = new TwitterApi({ clientId: \"{{clientId}}\", clientSecret: \"{{clientSecret}}\" });\\nconst { url, codeVerifier, state } = oauthClient.generateOAuth2AuthLink(\\n \"http://localhost:3000/api/auth/callback/twitter\",\\n { scope: [\"tweet.read\", \"tweet.write\", \"users.read\", \"offline.access\"] },\\n);\\n// Send the user to `url` (against `${base}/2/oauth2/authorize`), then exchange the code at `${base}/2/oauth2/token`.',\n },\n {\n id: \"x-env\",\n title: \"X base URL and credentials (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Point your app at the emulator instead of api.x.com.\",\n template:\n \"X_API_BASE_URL={{baseUrl}}\\nX_CLIENT_ID={{clientId}}\\nX_CLIENT_SECRET={{clientSecret}}\\nX_BEARER_TOKEN={{token}}\",\n },\n {\n id: \"curl-app-only\",\n title: \"curl (app-only Bearer)\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Mint an app-only Bearer token (confidential client, HTTP Basic auth) and read a user.\",\n template:\n 'curl -s -X POST {{baseUrl}}/2/oauth2/token \\\\\\n -u \"{{clientId}}:{{clientSecret}}\" \\\\\\n -d grant_type=client_credentials\\n\\ncurl -s {{baseUrl}}/2/users/by/username/developer \\\\\\n -H \"authorization: Bearer {{token}}\"',\n },\n {\n id: \"curl-token-exchange\",\n title: \"curl (authorization code + PKCE)\",\n kind: \"curl\",\n language: \"bash\",\n description:\n \"Exchange an authorization code for a user-context token. Confidential clients use -u (Basic); public clients send client_id in the body with no secret.\",\n template:\n 'curl -s -X POST {{baseUrl}}/2/oauth2/token \\\\\\n -u \"{{clientId}}:{{clientSecret}}\" \\\\\\n -d grant_type=authorization_code \\\\\\n -d code=$CODE \\\\\\n -d redirect_uri=http://localhost:3000/api/auth/callback/twitter \\\\\\n -d code_verifier=$CODE_VERIFIER',\n },\n ],\n};\n","import type { RouteContext, ServicePlugin, Store } from \"@emulators/core\";\nimport { getXStore, xNumericId } from \"./store.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\nimport { usersRoutes } from \"./routes/users.js\";\nimport { tweetsRoutes } from \"./routes/tweets.js\";\nimport { openapiRoutes } from \"./routes/openapi.js\";\n\nexport { getXStore, lookupAccessToken, type XStore } from \"./store.js\";\nexport { manifest } from \"./manifest.js\";\nexport * from \"./entities.js\";\n\nexport interface XSeedConfig {\n users?: Array<{\n username: string;\n name?: string;\n user_id?: string;\n description?: string;\n verified?: boolean;\n protected?: boolean;\n location?: string;\n url?: string;\n profile_image_url?: string;\n followers_count?: number;\n following_count?: number;\n listed_count?: number;\n created_at?: string;\n }>;\n oauth_clients?: Array<{\n client_id: string;\n client_secret?: string | null;\n client_type?: \"confidential\" | \"public\";\n name?: string;\n redirect_uris?: string[];\n }>;\n tweets?: Array<{\n text: string;\n author: string; // username or user_id of the author\n tweet_id?: string;\n like_count?: number;\n retweet_count?: number;\n reply_count?: number;\n quote_count?: number;\n impression_count?: number;\n lang?: string;\n created_at?: string;\n }>;\n}\n\nfunction resolveAuthor(store: Store, ref: string): string | null {\n const xs = getXStore(store);\n const byId = xs.users.findOneBy(\"user_id\", ref);\n if (byId) return byId.user_id;\n const byUsername = xs.users.findOneBy(\"username\", ref.toLowerCase().replace(/^@/, \"\"));\n return byUsername ? byUsername.user_id : null;\n}\n\nexport function seedFromConfig(store: Store, baseUrl: string, config: XSeedConfig): void {\n const xs = getXStore(store);\n\n for (const u of config.users ?? []) {\n const username = u.username.toLowerCase().replace(/^@/, \"\");\n if (xs.users.findOneBy(\"username\", username)) continue;\n const userId = u.user_id ?? xNumericId();\n xs.users.insert({\n user_id: userId,\n username,\n name: u.name ?? u.username,\n description: u.description ?? \"\",\n verified: u.verified ?? false,\n protected: u.protected ?? false,\n location: u.location ?? null,\n url: u.url ?? null,\n profile_image_url: u.profile_image_url ?? `${baseUrl}/profile_images/${username}.png`,\n followers_count: u.followers_count ?? 0,\n following_count: u.following_count ?? 0,\n tweet_count: 0,\n listed_count: u.listed_count ?? 0,\n created_at_x: u.created_at ?? new Date().toISOString(),\n });\n }\n\n for (const cl of config.oauth_clients ?? []) {\n if (xs.oauthClients.findOneBy(\"client_id\", cl.client_id)) continue;\n const clientType: \"confidential\" | \"public\" = cl.client_type ?? (cl.client_secret ? \"confidential\" : \"public\");\n xs.oauthClients.insert({\n client_id: cl.client_id,\n client_secret: clientType === \"confidential\" ? (cl.client_secret ?? null) : null,\n client_type: clientType,\n name: cl.name ?? cl.client_id,\n redirect_uris: cl.redirect_uris ?? [\"http://localhost:3000/callback\"],\n });\n }\n\n for (const t of config.tweets ?? []) {\n const authorId = resolveAuthor(store, t.author);\n if (!authorId) continue;\n const tweetId = t.tweet_id ?? xNumericId();\n if (xs.tweets.findOneBy(\"tweet_id\", tweetId)) continue;\n xs.tweets.insert({\n tweet_id: tweetId,\n author_id: authorId,\n text: t.text,\n reply_count: t.reply_count ?? 0,\n retweet_count: t.retweet_count ?? 0,\n like_count: t.like_count ?? 0,\n quote_count: t.quote_count ?? 0,\n impression_count: t.impression_count ?? 0,\n in_reply_to_user_id: null,\n conversation_id: tweetId,\n lang: t.lang ?? \"en\",\n possibly_sensitive: false,\n created_at_x: t.created_at ?? new Date().toISOString(),\n });\n const author = xs.users.findOneBy(\"user_id\", authorId);\n if (author) xs.users.update(author.id, { tweet_count: author.tweet_count + 1 });\n }\n}\n\nexport const xPlugin: ServicePlugin = {\n name: \"x\",\n register(app, store, webhooks, baseUrl, tokenMap): void {\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n oauthRoutes(ctx);\n usersRoutes(ctx);\n tweetsRoutes(ctx);\n openapiRoutes(ctx);\n },\n seed(store, baseUrl): void {\n seedFromConfig(store, baseUrl, {\n users: [\n {\n username: \"developer\",\n name: \"Developer\",\n description: \"Building with the X API v2 emulator.\",\n verified: true,\n followers_count: 1200,\n following_count: 320,\n },\n ],\n oauth_clients: [\n {\n client_id: \"x-confidential-client\",\n client_secret: \"x-confidential-secret\",\n client_type: \"confidential\",\n name: \"My X App (confidential)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n {\n client_id: \"x-public-client\",\n client_type: \"public\",\n name: \"My X App (public)\",\n redirect_uris: [\"http://localhost:3000/api/auth/callback/twitter\"],\n },\n ],\n tweets: [{ text: \"Hello from the X API v2 emulator.\", author: \"developer\", like_count: 42, retweet_count: 7 }],\n });\n },\n};\n\nexport default xPlugin;\n"],"mappings":";ACAA,SAAS,YAAY,mBAAmB;AeAxC,SAAS,uBAAuB;AhBY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