@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/github/src/index.ts","../../@emulators/github/src/store.ts","../../@emulators/github/src/helpers.ts","../../@emulators/github/src/routes/graphql.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/github/src/route-helpers.ts","../../@emulators/github/src/routes/users.ts","../../@emulators/github/src/routes/repos.ts","../../@emulators/github/src/routes/issues.ts","../../@emulators/github/src/routes/pulls.ts","../../@emulators/github/src/routes/comments.ts","../../@emulators/github/src/routes/reviews.ts","../../@emulators/github/src/routes/labels.ts","../../@emulators/github/src/routes/branches.ts","../../@emulators/github/src/routes/orgs.ts","../../@emulators/github/src/routes/releases.ts","../../@emulators/github/src/routes/webhooks.ts","../../@emulators/github/src/routes/search.ts","../../@emulators/github/src/routes/actions.ts","../../@emulators/github/src/routes/checks.ts","../../@emulators/github/src/routes/rate-limit.ts","../../@emulators/github/src/routes/meta.ts","../../@emulators/github/src/routes/oauth.ts","../../@emulators/github/src/routes/apps.ts","../../@emulators/github/src/routes/openapi.ts","../../@emulators/github/src/manifest.ts","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/devAssert.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/isPromise.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/isObjectLike.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/invariant.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/location.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/printLocation.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/error/GraphQLError.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/error/syntaxError.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/ast.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/directiveLocation.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/kinds.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/characterClasses.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/blockString.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/tokenKind.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/lexer.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/inspect.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/instanceOf.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/source.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/parser.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/didYouMean.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/identityFunc.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/keyMap.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/keyValMap.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/mapValue.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/naturalCompare.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/suggestionList.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/toObjMap.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/printString.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/visitor.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/printer.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/valueFromASTUntyped.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/assertName.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/definition.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/typeComparators.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/scalars.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/directives.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/isIterableObject.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/astFromValue.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/introspection.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/schema.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/type/validate.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/typeFromAST.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/TypeInfo.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/language/predicates.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/sortValueNode.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/printPathArray.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/Path.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/coerceInputValue.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/valueFromAST.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/execution/values.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/execution/collectFields.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/groupBy.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/specifiedRules.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/ValidationContext.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/validation/validate.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/memoize3.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/promiseForObject.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/promiseReduce.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/jsutils/toError.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/error/locatedError.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/execution/execute.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/graphql.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/extendSchema.mjs","../../../node_modules/.pnpm/graphql@16.14.1/node_modules/graphql/utilities/buildASTSchema.mjs"],"sourcesContent":["import { createHmac } from \"crypto\";\nimport type { Hono } from \"@emulators/core\";\nimport type { ServicePlugin, Store, WebhookDispatcher, TokenMap, AppEnv, RouteContext } from \"@emulators/core\";\nimport { getGitHubStore } from \"./store.js\";\nimport type { GitHubStore } from \"./store.js\";\nimport type { GitHubAppInstallation } from \"./entities.js\";\nimport { generateNodeId, generateSha } from \"./helpers.js\";\nimport { graphqlRoutes } from \"./routes/graphql.js\";\nimport { usersRoutes } from \"./routes/users.js\";\nimport { reposRoutes } from \"./routes/repos.js\";\nimport { issuesRoutes } from \"./routes/issues.js\";\nimport { pullsRoutes } from \"./routes/pulls.js\";\nimport { commentsRoutes } from \"./routes/comments.js\";\nimport { reviewsRoutes } from \"./routes/reviews.js\";\nimport { labelsAndMilestonesRoutes } from \"./routes/labels.js\";\nimport { branchesAndGitRoutes } from \"./routes/branches.js\";\nimport { orgsAndTeamsRoutes } from \"./routes/orgs.js\";\nimport { releasesRoutes } from \"./routes/releases.js\";\nimport { webhooksRoutes } from \"./routes/webhooks.js\";\nimport { searchRoutes } from \"./routes/search.js\";\nimport { actionsRoutes } from \"./routes/actions.js\";\nimport { checksRoutes } from \"./routes/checks.js\";\nimport { rateLimitRoutes } from \"./routes/rate-limit.js\";\nimport { metaRoutes } from \"./routes/meta.js\";\nimport { oauthRoutes } from \"./routes/oauth.js\";\nimport { appsRoutes } from \"./routes/apps.js\";\nimport { openapiRoutes } from \"./routes/openapi.js\";\n\nexport { getGitHubStore, type GitHubStore } from \"./store.js\";\nexport { manifest } from \"./manifest.js\";\nexport * from \"./entities.js\";\n\nexport interface GitHubSeedConfig {\n port?: number;\n users?: Array<{\n login: string;\n name?: string;\n email?: string;\n bio?: string;\n company?: string;\n location?: string;\n blog?: string;\n twitter_username?: string;\n site_admin?: boolean;\n }>;\n orgs?: Array<{\n login: string;\n name?: string;\n description?: string;\n email?: string;\n }>;\n tokens?: Record<string, { login: string; scopes?: string[] }>;\n repos?: Array<{\n owner: string;\n name: string;\n description?: string;\n private?: boolean;\n language?: string;\n topics?: string[];\n default_branch?: string;\n auto_init?: boolean;\n }>;\n oauth_apps?: Array<{\n client_id: string;\n client_secret: string;\n name: string;\n redirect_uris: string[];\n }>;\n apps?: Array<{\n app_id: number;\n slug: string;\n name: string;\n private_key: string;\n permissions?: Record<string, string>;\n events?: string[];\n webhook_url?: string;\n webhook_secret?: string;\n description?: string;\n installations?: Array<{\n installation_id: number;\n account: string;\n repository_selection?: \"all\" | \"selected\";\n repositories?: string[];\n permissions?: Record<string, string>;\n events?: string[];\n }>;\n }>;\n}\n\nfunction seedDefaults(store: Store, baseUrl: string): void {\n const gh = getGitHubStore(store);\n\n const ghost = gh.users.insert({\n login: \"ghost\",\n node_id: \"\",\n avatar_url: `${baseUrl}/avatars/u/ghost`,\n gravatar_id: \"\",\n type: \"User\",\n site_admin: false,\n name: \"Ghost\",\n company: null,\n blog: \"\",\n location: null,\n email: null,\n hireable: null,\n bio: null,\n twitter_username: null,\n public_repos: 0,\n public_gists: 0,\n followers: 0,\n following: 0,\n });\n gh.users.update(ghost.id, { node_id: generateNodeId(\"User\", ghost.id) });\n\n const admin = gh.users.insert({\n login: \"admin\",\n node_id: \"\",\n avatar_url: `${baseUrl}/avatars/u/admin`,\n gravatar_id: \"\",\n type: \"User\",\n site_admin: true,\n name: \"Admin\",\n company: null,\n blog: \"\",\n location: null,\n email: \"admin@localhost\",\n hireable: null,\n bio: \"Default admin user\",\n twitter_username: null,\n public_repos: 0,\n public_gists: 0,\n followers: 0,\n following: 0,\n });\n gh.users.update(admin.id, { node_id: generateNodeId(\"User\", admin.id) });\n}\n\nexport function seedFromConfig(store: Store, baseUrl: string, config: GitHubSeedConfig): void {\n const gh = getGitHubStore(store);\n\n if (config.users) {\n for (const u of config.users) {\n const existing = gh.users.findOneBy(\"login\", u.login);\n if (existing) continue;\n const user = gh.users.insert({\n login: u.login,\n node_id: \"\",\n avatar_url: `${baseUrl}/avatars/u/${u.login}`,\n gravatar_id: \"\",\n type: \"User\",\n site_admin: u.site_admin ?? false,\n name: u.name ?? null,\n company: u.company ?? null,\n blog: u.blog ?? \"\",\n location: u.location ?? null,\n email: u.email ?? null,\n hireable: null,\n bio: u.bio ?? null,\n twitter_username: u.twitter_username ?? null,\n public_repos: 0,\n public_gists: 0,\n followers: 0,\n following: 0,\n });\n gh.users.update(user.id, { node_id: generateNodeId(\"User\", user.id) });\n }\n }\n\n if (config.orgs) {\n for (const o of config.orgs) {\n const existing = gh.orgs.findOneBy(\"login\", o.login);\n if (existing) continue;\n const org = gh.orgs.insert({\n login: o.login,\n node_id: \"\",\n description: o.description ?? null,\n name: o.name ?? null,\n company: null,\n blog: \"\",\n location: null,\n email: o.email ?? null,\n twitter_username: null,\n is_verified: false,\n has_organization_projects: true,\n has_repository_projects: true,\n public_repos: 0,\n public_gists: 0,\n followers: 0,\n following: 0,\n members_can_create_repositories: true,\n default_repository_permission: \"read\",\n billing_email: null,\n });\n gh.orgs.update(org.id, { node_id: generateNodeId(\"Org\", org.id) });\n }\n }\n\n if (config.repos) {\n for (const r of config.repos) {\n const ownerUser = gh.users.findOneBy(\"login\", r.owner);\n const owner = ownerUser ?? gh.orgs.findOneBy(\"login\", r.owner);\n if (!owner) continue;\n\n const fullName = `${r.owner}/${r.name}`;\n const existing = gh.repos.findOneBy(\"full_name\", fullName);\n if (existing) continue;\n\n const ownerType = ownerUser ? \"User\" : \"Organization\";\n const defaultBranch = r.default_branch ?? \"main\";\n\n const repo = gh.repos.insert({\n node_id: \"\",\n name: r.name,\n full_name: fullName,\n owner_id: owner.id,\n owner_type: ownerType,\n private: r.private ?? false,\n description: r.description ?? null,\n fork: false,\n forked_from_id: null,\n homepage: null,\n language: r.language ?? null,\n languages: r.language ? { [r.language]: 10000 } : {},\n forks_count: 0,\n stargazers_count: 0,\n watchers_count: 0,\n size: 0,\n default_branch: defaultBranch,\n open_issues_count: 0,\n topics: r.topics ?? [],\n has_issues: true,\n has_projects: true,\n has_wiki: true,\n has_pages: false,\n has_downloads: true,\n has_discussions: false,\n archived: false,\n disabled: false,\n visibility: r.private ? \"private\" : \"public\",\n pushed_at: null,\n allow_rebase_merge: true,\n allow_squash_merge: true,\n allow_merge_commit: true,\n allow_auto_merge: false,\n delete_branch_on_merge: false,\n allow_forking: true,\n is_template: false,\n license: null,\n });\n gh.repos.update(repo.id, { node_id: generateNodeId(\"Repository\", repo.id) });\n\n if (r.auto_init !== false) {\n const sha = generateSha();\n const treeSha = generateSha();\n\n const commit = gh.commits.insert({\n repo_id: repo.id,\n sha,\n node_id: \"\",\n message: \"Initial commit\",\n author_name: r.owner,\n author_email: `${r.owner}@localhost`,\n author_date: repo.created_at,\n committer_name: r.owner,\n committer_email: `${r.owner}@localhost`,\n committer_date: repo.created_at,\n tree_sha: treeSha,\n parent_shas: [],\n user_id: owner.id,\n });\n gh.commits.update(commit.id, { node_id: generateNodeId(\"Commit\", commit.id) });\n\n const tree = gh.trees.insert({\n repo_id: repo.id,\n sha: treeSha,\n node_id: \"\",\n tree: [{ path: \"README.md\", mode: \"100644\", type: \"blob\", sha: generateSha(), size: 20 }],\n truncated: false,\n });\n gh.trees.update(tree.id, { node_id: generateNodeId(\"Tree\", tree.id) });\n\n gh.branches.insert({\n repo_id: repo.id,\n name: defaultBranch,\n sha,\n protected: false,\n });\n\n const refRow = gh.refs.insert({\n repo_id: repo.id,\n ref: `refs/heads/${defaultBranch}`,\n sha,\n node_id: \"\",\n });\n gh.refs.update(refRow.id, { node_id: generateNodeId(\"Ref\", refRow.id) });\n\n gh.repos.update(repo.id, { pushed_at: repo.created_at, size: 1 });\n }\n\n if (ownerType === \"User\") {\n const user = gh.users.findOneBy(\"login\", r.owner);\n if (user && !r.private) {\n gh.users.update(user.id, { public_repos: user.public_repos + 1 });\n }\n } else {\n const org = gh.orgs.findOneBy(\"login\", r.owner);\n if (org && !r.private) {\n gh.orgs.update(org.id, { public_repos: org.public_repos + 1 });\n }\n }\n }\n }\n\n if (config.oauth_apps) {\n for (const oa of config.oauth_apps) {\n const existing = gh.oauthApps.findOneBy(\"client_id\", oa.client_id);\n if (existing) continue;\n gh.oauthApps.insert({\n client_id: oa.client_id,\n client_secret: oa.client_secret,\n name: oa.name,\n redirect_uris: oa.redirect_uris,\n });\n }\n }\n\n if (config.apps) {\n for (const a of config.apps) {\n const existingApp = gh.apps.findOneBy(\"slug\", a.slug);\n if (existingApp) continue;\n\n gh.apps.insert({\n app_id: a.app_id,\n slug: a.slug,\n name: a.name,\n private_key: a.private_key,\n permissions: a.permissions ?? {},\n events: a.events ?? [],\n webhook_url: a.webhook_url ?? null,\n webhook_secret: a.webhook_secret ?? null,\n description: a.description ?? null,\n });\n\n if (a.installations) {\n for (const inst of a.installations) {\n const account = gh.users.findOneBy(\"login\", inst.account) ?? gh.orgs.findOneBy(\"login\", inst.account);\n if (!account) continue;\n\n const accountType = gh.users.findOneBy(\"login\", inst.account) ? (\"User\" as const) : (\"Organization\" as const);\n\n const repoIds: number[] = [];\n if (inst.repositories) {\n for (const repoFullName of inst.repositories) {\n const fullName = repoFullName.includes(\"/\") ? repoFullName : `${inst.account}/${repoFullName}`;\n const repo = gh.repos.findOneBy(\"full_name\", fullName);\n if (repo) repoIds.push(repo.id);\n }\n }\n\n gh.appInstallations.insert({\n installation_id: inst.installation_id,\n app_id: a.app_id,\n account_type: accountType,\n account_id: account.id,\n account_login: inst.account,\n repository_selection: inst.repository_selection ?? \"all\",\n repository_ids: repoIds,\n permissions: inst.permissions ?? a.permissions ?? {},\n events: inst.events ?? a.events ?? [],\n suspended_at: null,\n });\n }\n }\n }\n }\n}\n\nfunction findInstallationsForRepo(\n gh: GitHubStore,\n ownerLogin: string,\n repoName: string | undefined,\n event: string,\n): GitHubAppInstallation[] {\n const ownerEntity = gh.users.findOneBy(\"login\", ownerLogin) ?? gh.orgs.findOneBy(\"login\", ownerLogin);\n if (!ownerEntity) return [];\n\n const repoEntity = repoName ? gh.repos.findOneBy(\"full_name\", `${ownerLogin}/${repoName}`) : null;\n\n const results: GitHubAppInstallation[] = [];\n for (const inst of gh.appInstallations.all()) {\n if (inst.account_id !== ownerEntity.id) continue;\n if (inst.suspended_at) continue;\n\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n if (!ghApp) continue;\n if (!ghApp.events.includes(event) && !ghApp.events.includes(\"*\")) continue;\n\n if (repoEntity && inst.repository_selection === \"selected\") {\n if (!inst.repository_ids.includes(repoEntity.id)) continue;\n }\n\n results.push(inst);\n }\n return results;\n}\n\nfunction enrichPayloadWithInstallation(payload: unknown, installation: GitHubAppInstallation): unknown {\n if (!payload || typeof payload !== \"object\") return payload;\n return {\n ...(payload as Record<string, unknown>),\n installation: {\n id: installation.installation_id,\n node_id: generateNodeId(\"Installation\", installation.installation_id),\n },\n };\n}\n\nasync function deliverToAppWebhookUrls(\n gh: GitHubStore,\n event: string,\n action: string | undefined,\n payload: unknown,\n ownerLogin: string,\n repoName: string | undefined,\n): Promise<void> {\n const installations = findInstallationsForRepo(gh, ownerLogin, repoName, event);\n\n for (const inst of installations) {\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n if (!ghApp?.webhook_url) continue;\n\n const enriched = enrichPayloadWithInstallation(payload, inst);\n const body = JSON.stringify(enriched);\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"X-GitHub-Event\": event,\n \"X-GitHub-Delivery\": String(Date.now()),\n };\n if (ghApp.webhook_secret) {\n const hmac = createHmac(\"sha256\", ghApp.webhook_secret).update(body).digest(\"hex\");\n headers[\"X-Hub-Signature-256\"] = `sha256=${hmac}`;\n }\n\n try {\n await fetch(ghApp.webhook_url, {\n method: \"POST\",\n headers,\n body,\n signal: AbortSignal.timeout(10000),\n });\n } catch {\n // Best-effort delivery\n }\n }\n}\n\nexport const githubPlugin: ServicePlugin = {\n name: \"github\",\n register(app: Hono<AppEnv>, store: Store, webhooks: WebhookDispatcher, baseUrl: string, tokenMap?: TokenMap): void {\n const gh = getGitHubStore(store);\n\n const originalDispatch = webhooks.dispatch.bind(webhooks);\n webhooks.dispatch = async (\n event: string,\n action: string | undefined,\n payload: unknown,\n owner: string,\n repo?: string,\n ): Promise<void> => {\n const installations = findInstallationsForRepo(gh, owner, repo, event);\n\n const enrichedPayload =\n installations.length > 0 ? enrichPayloadWithInstallation(payload, installations[0]) : payload;\n\n await originalDispatch(event, action, enrichedPayload, owner, repo);\n await deliverToAppWebhookUrls(gh, event, action, payload, owner, repo);\n };\n\n const ctx: RouteContext = { app, store, webhooks, baseUrl, tokenMap };\n graphqlRoutes(ctx);\n usersRoutes(ctx);\n reposRoutes(ctx);\n issuesRoutes(ctx);\n pullsRoutes(ctx);\n commentsRoutes(ctx);\n reviewsRoutes(ctx);\n labelsAndMilestonesRoutes(ctx);\n branchesAndGitRoutes(ctx);\n orgsAndTeamsRoutes(ctx);\n releasesRoutes(ctx);\n webhooksRoutes(ctx);\n searchRoutes(ctx);\n actionsRoutes(ctx);\n checksRoutes(ctx);\n rateLimitRoutes(ctx);\n metaRoutes(ctx);\n oauthRoutes(ctx);\n appsRoutes(ctx);\n openapiRoutes(ctx);\n },\n seed(store: Store, baseUrl: string): void {\n seedDefaults(store, baseUrl);\n },\n};\n\nexport default githubPlugin;\n","import { Store, type Collection } from \"@emulators/core\";\nimport type {\n GitHubUser,\n GitHubOrg,\n GitHubTeam,\n GitHubTeamMember,\n GitHubTeamRepo,\n GitHubRepo,\n GitHubCollaborator,\n GitHubIssue,\n GitHubPullRequest,\n GitHubLabel,\n GitHubMilestone,\n GitHubComment,\n GitHubReview,\n GitHubIssueEvent,\n GitHubBranch,\n GitHubBranchProtection,\n GitHubRef,\n GitHubCommit,\n GitHubTree,\n GitHubBlob,\n GitHubTag,\n GitHubRelease,\n GitHubReleaseAsset,\n GitHubWebhook,\n GitHubWorkflow,\n GitHubWorkflowRun,\n GitHubJob,\n GitHubArtifact,\n GitHubSecret,\n GitHubCheckRun,\n GitHubCheckSuite,\n GitHubOAuthApp,\n GitHubApp,\n GitHubAppInstallation,\n GitHubOAuthGrant,\n} from \"./entities.js\";\n\nexport interface GitHubStore {\n users: Collection<GitHubUser>;\n orgs: Collection<GitHubOrg>;\n teams: Collection<GitHubTeam>;\n teamMembers: Collection<GitHubTeamMember>;\n teamRepos: Collection<GitHubTeamRepo>;\n repos: Collection<GitHubRepo>;\n collaborators: Collection<GitHubCollaborator>;\n issues: Collection<GitHubIssue>;\n pullRequests: Collection<GitHubPullRequest>;\n labels: Collection<GitHubLabel>;\n milestones: Collection<GitHubMilestone>;\n comments: Collection<GitHubComment>;\n reviews: Collection<GitHubReview>;\n issueEvents: Collection<GitHubIssueEvent>;\n branches: Collection<GitHubBranch>;\n branchProtections: Collection<GitHubBranchProtection>;\n refs: Collection<GitHubRef>;\n commits: Collection<GitHubCommit>;\n trees: Collection<GitHubTree>;\n blobs: Collection<GitHubBlob>;\n tags: Collection<GitHubTag>;\n releases: Collection<GitHubRelease>;\n releaseAssets: Collection<GitHubReleaseAsset>;\n webhooks: Collection<GitHubWebhook>;\n workflows: Collection<GitHubWorkflow>;\n workflowRuns: Collection<GitHubWorkflowRun>;\n jobs: Collection<GitHubJob>;\n artifacts: Collection<GitHubArtifact>;\n secrets: Collection<GitHubSecret>;\n checkRuns: Collection<GitHubCheckRun>;\n checkSuites: Collection<GitHubCheckSuite>;\n oauthApps: Collection<GitHubOAuthApp>;\n apps: Collection<GitHubApp>;\n appInstallations: Collection<GitHubAppInstallation>;\n oauthGrants: Collection<GitHubOAuthGrant>;\n}\n\nexport function getGitHubStore(store: Store): GitHubStore {\n return {\n users: store.collection<GitHubUser>(\"github.users\", [\"login\"]),\n orgs: store.collection<GitHubOrg>(\"github.orgs\", [\"login\"]),\n teams: store.collection<GitHubTeam>(\"github.teams\", [\"org_id\", \"slug\"]),\n teamMembers: store.collection<GitHubTeamMember>(\"github.team_members\", [\"team_id\", \"user_id\"]),\n teamRepos: store.collection<GitHubTeamRepo>(\"github.team_repos\", [\"team_id\", \"repo_id\"]),\n repos: store.collection<GitHubRepo>(\"github.repos\", [\"owner_id\", \"full_name\"]),\n collaborators: store.collection<GitHubCollaborator>(\"github.collaborators\", [\"repo_id\", \"user_id\"]),\n issues: store.collection<GitHubIssue>(\"github.issues\", [\"repo_id\", \"number\"]),\n pullRequests: store.collection<GitHubPullRequest>(\"github.pull_requests\", [\"repo_id\", \"number\"]),\n labels: store.collection<GitHubLabel>(\"github.labels\", [\"repo_id\"]),\n milestones: store.collection<GitHubMilestone>(\"github.milestones\", [\"repo_id\", \"number\"]),\n comments: store.collection<GitHubComment>(\"github.comments\", [\"repo_id\"]),\n reviews: store.collection<GitHubReview>(\"github.reviews\", [\"repo_id\", \"pull_number\"]),\n issueEvents: store.collection<GitHubIssueEvent>(\"github.issue_events\", [\"repo_id\", \"issue_number\"]),\n branches: store.collection<GitHubBranch>(\"github.branches\", [\"repo_id\"]),\n branchProtections: store.collection<GitHubBranchProtection>(\"github.branch_protections\", [\"repo_id\"]),\n refs: store.collection<GitHubRef>(\"github.refs\", [\"repo_id\"]),\n commits: store.collection<GitHubCommit>(\"github.commits\", [\"repo_id\", \"sha\"]),\n trees: store.collection<GitHubTree>(\"github.trees\", [\"repo_id\", \"sha\"]),\n blobs: store.collection<GitHubBlob>(\"github.blobs\", [\"repo_id\", \"sha\"]),\n tags: store.collection<GitHubTag>(\"github.tags\", [\"repo_id\"]),\n releases: store.collection<GitHubRelease>(\"github.releases\", [\"repo_id\"]),\n releaseAssets: store.collection<GitHubReleaseAsset>(\"github.release_assets\", [\"release_id\", \"repo_id\"]),\n webhooks: store.collection<GitHubWebhook>(\"github.webhooks\", [\"repo_id\", \"org_id\"]),\n workflows: store.collection<GitHubWorkflow>(\"github.workflows\", [\"repo_id\"]),\n workflowRuns: store.collection<GitHubWorkflowRun>(\"github.workflow_runs\", [\"repo_id\", \"workflow_id\"]),\n jobs: store.collection<GitHubJob>(\"github.jobs\", [\"run_id\"]),\n artifacts: store.collection<GitHubArtifact>(\"github.artifacts\", [\"run_id\", \"repo_id\"]),\n secrets: store.collection<GitHubSecret>(\"github.secrets\", [\"repo_id\", \"org_id\"]),\n checkRuns: store.collection<GitHubCheckRun>(\"github.check_runs\", [\"repo_id\", \"head_sha\"]),\n checkSuites: store.collection<GitHubCheckSuite>(\"github.check_suites\", [\"repo_id\", \"head_sha\"]),\n oauthApps: store.collection<GitHubOAuthApp>(\"github.oauth_apps\", [\"client_id\"]),\n apps: store.collection<GitHubApp>(\"github.apps\", [\"slug\"]),\n appInstallations: store.collection<GitHubAppInstallation>(\"github.app_installations\", [\n \"app_id\",\n \"installation_id\",\n ]),\n oauthGrants: store.collection<GitHubOAuthGrant>(\"github.oauth_grants\", [\"user_id\", \"client_id\"]),\n };\n}\n","import { randomBytes } from \"crypto\";\nimport type {\n GitHubUser,\n GitHubOrg,\n GitHubRepo,\n GitHubIssue,\n GitHubPullRequest,\n GitHubLabel,\n GitHubMilestone,\n GitHubComment,\n GitHubRelease,\n GitHubTeam,\n GitHubBranch,\n GitHubCommit,\n GitHubCheckRun,\n GitHubCheckSuite,\n GitHubReview,\n GitHubWorkflow,\n GitHubWorkflowRun,\n GitHubJob,\n GitHubArtifact,\n GitHubReleaseAsset,\n GitHubWebhook,\n GitHubRef,\n GitHubTag,\n GitHubBlob,\n GitHubTree,\n} from \"./entities.js\";\nimport type { GitHubStore } from \"./store.js\";\n\nexport function generateNodeId(type: string, id: number): string {\n return Buffer.from(`0:${type}${id}`).toString(\"base64\").replace(/=+$/, \"\");\n}\n\nexport function generateSha(): string {\n return randomBytes(20).toString(\"hex\");\n}\n\nexport function timestamp(): string {\n return new Date().toISOString();\n}\n\nexport function userUrl(baseUrl: string, login: string) {\n return {\n url: `${baseUrl}/users/${login}`,\n html_url: `${baseUrl}/${login}`,\n repos_url: `${baseUrl}/users/${login}/repos`,\n followers_url: `${baseUrl}/users/${login}/followers`,\n following_url: `${baseUrl}/users/${login}/following{/other_user}`,\n gists_url: `${baseUrl}/users/${login}/gists{/gist_id}`,\n starred_url: `${baseUrl}/users/${login}/starred{/owner}{/repo}`,\n subscriptions_url: `${baseUrl}/users/${login}/subscriptions`,\n organizations_url: `${baseUrl}/users/${login}/orgs`,\n events_url: `${baseUrl}/users/${login}/events{/privacy}`,\n received_events_url: `${baseUrl}/users/${login}/received_events`,\n avatar_url: `${baseUrl}/avatars/u/${login}`,\n };\n}\n\nexport function formatUser(user: GitHubUser, baseUrl: string) {\n const urls = userUrl(baseUrl, user.login);\n return {\n login: user.login,\n id: user.id,\n node_id: user.node_id,\n avatar_url: urls.avatar_url,\n gravatar_id: user.gravatar_id,\n url: urls.url,\n html_url: urls.html_url,\n followers_url: urls.followers_url,\n following_url: urls.following_url,\n gists_url: urls.gists_url,\n starred_url: urls.starred_url,\n subscriptions_url: urls.subscriptions_url,\n organizations_url: urls.organizations_url,\n repos_url: urls.repos_url,\n events_url: urls.events_url,\n received_events_url: urls.received_events_url,\n type: user.type,\n site_admin: user.site_admin,\n user_view_type: \"public\",\n };\n}\n\nexport function formatUserFull(user: GitHubUser, baseUrl: string) {\n return {\n ...formatUser(user, baseUrl),\n name: user.name,\n company: user.company,\n blog: user.blog,\n location: user.location,\n email: user.email,\n hireable: user.hireable,\n bio: user.bio,\n twitter_username: user.twitter_username,\n public_repos: user.public_repos,\n public_gists: user.public_gists,\n followers: user.followers,\n following: user.following,\n created_at: user.created_at,\n updated_at: user.updated_at,\n };\n}\n\nexport function formatOwner(store: GitHubStore, ownerId: number, ownerType: string, baseUrl: string) {\n if (ownerType === \"Organization\") {\n const org = store.orgs.get(ownerId);\n if (!org) return null;\n return formatOrgBrief(org, baseUrl);\n }\n const user = store.users.get(ownerId);\n if (!user) return null;\n return formatUser(user, baseUrl);\n}\n\nexport function formatOrgBrief(org: GitHubOrg, baseUrl: string) {\n return {\n login: org.login,\n id: org.id,\n node_id: org.node_id,\n url: `${baseUrl}/orgs/${org.login}`,\n html_url: `${baseUrl}/${org.login}`,\n repos_url: `${baseUrl}/orgs/${org.login}/repos`,\n events_url: `${baseUrl}/orgs/${org.login}/events`,\n hooks_url: `${baseUrl}/orgs/${org.login}/hooks`,\n issues_url: `${baseUrl}/orgs/${org.login}/issues`,\n members_url: `${baseUrl}/orgs/${org.login}/members{/member}`,\n public_members_url: `${baseUrl}/orgs/${org.login}/public_members{/member}`,\n avatar_url: `${baseUrl}/avatars/o/${org.login}`,\n description: org.description,\n type: \"Organization\",\n site_admin: false,\n user_view_type: \"public\",\n };\n}\n\nfunction permissionsFromLevel(level: string) {\n const levels = [\"pull\", \"triage\", \"push\", \"maintain\", \"admin\"];\n const idx = levels.indexOf(level);\n return {\n admin: idx >= 4,\n maintain: idx >= 3,\n push: idx >= 2,\n triage: idx >= 1,\n pull: idx >= 0,\n };\n}\n\nfunction computeRepoPermissions(store: GitHubStore, repo: GitHubRepo, authUserId: number) {\n if (repo.owner_type === \"User\" && repo.owner_id === authUserId) {\n return { admin: true, maintain: true, push: true, triage: true, pull: true };\n }\n if (repo.owner_type === \"Organization\") {\n for (const team of store.teams.all()) {\n if (team.org_id !== repo.owner_id) continue;\n const member = store.teamMembers.findBy(\"team_id\", team.id).find((m) => m.user_id === authUserId);\n if (member) {\n return { admin: true, maintain: true, push: true, triage: true, pull: true };\n }\n }\n }\n const collab = store.collaborators.findBy(\"repo_id\", repo.id).find((c) => c.user_id === authUserId);\n if (collab) {\n return permissionsFromLevel(collab.permission);\n }\n if (!repo.private) {\n return { admin: false, maintain: false, push: false, triage: false, pull: true };\n }\n return { admin: false, maintain: false, push: false, triage: false, pull: false };\n}\n\nexport function computeAuthorAssociation(store: GitHubStore, userId: number, repoId: number): string {\n const repo = store.repos.get(repoId);\n if (!repo) return \"NONE\";\n\n if (repo.owner_type === \"User\" && repo.owner_id === userId) return \"OWNER\";\n\n if (repo.owner_type === \"Organization\") {\n for (const team of store.teams.all()) {\n if (team.org_id !== repo.owner_id) continue;\n const member = store.teamMembers.findBy(\"team_id\", team.id).find((m) => m.user_id === userId);\n if (member) return \"MEMBER\";\n }\n }\n\n const collab = store.collaborators.findBy(\"repo_id\", repoId).find((c) => c.user_id === userId);\n if (collab) return \"COLLABORATOR\";\n\n return \"NONE\";\n}\n\nexport function formatOrgFull(org: GitHubOrg, baseUrl: string) {\n return {\n ...formatOrgBrief(org, baseUrl),\n name: org.name,\n company: org.company,\n blog: org.blog,\n location: org.location,\n email: org.email,\n twitter_username: org.twitter_username,\n is_verified: org.is_verified,\n has_organization_projects: org.has_organization_projects,\n has_repository_projects: org.has_repository_projects,\n public_repos: org.public_repos,\n public_gists: org.public_gists,\n followers: org.followers,\n following: org.following,\n created_at: org.created_at,\n updated_at: org.updated_at,\n members_can_create_repositories: org.members_can_create_repositories,\n default_repository_permission: org.default_repository_permission,\n billing_email: org.billing_email ?? null,\n };\n}\n\nexport function formatRepo(repo: GitHubRepo, store: GitHubStore, baseUrl: string, authUserId?: number) {\n const owner = formatOwner(store, repo.owner_id, repo.owner_type, baseUrl);\n const ownerLogin = owner?.login ?? \"unknown\";\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const htmlUrl = `${baseUrl}/${repo.full_name}`;\n\n return {\n id: repo.id,\n node_id: repo.node_id,\n name: repo.name,\n full_name: repo.full_name,\n private: repo.private,\n owner,\n html_url: htmlUrl,\n description: repo.description,\n fork: repo.fork,\n url: repoUrl,\n forks_url: `${repoUrl}/forks`,\n keys_url: `${repoUrl}/keys{/key_id}`,\n collaborators_url: `${repoUrl}/collaborators{/collaborator}`,\n teams_url: `${repoUrl}/teams`,\n hooks_url: `${repoUrl}/hooks`,\n issue_events_url: `${repoUrl}/issues/events{/number}`,\n events_url: `${repoUrl}/events`,\n assignees_url: `${repoUrl}/assignees{/user}`,\n branches_url: `${repoUrl}/branches{/branch}`,\n tags_url: `${repoUrl}/tags`,\n blobs_url: `${repoUrl}/git/blobs{/sha}`,\n git_tags_url: `${repoUrl}/git/tags{/sha}`,\n git_refs_url: `${repoUrl}/git/ref{/sha}`,\n trees_url: `${repoUrl}/git/trees{/sha}`,\n statuses_url: `${repoUrl}/statuses/{sha}`,\n languages_url: `${repoUrl}/languages`,\n stargazers_url: `${repoUrl}/stargazers`,\n contributors_url: `${repoUrl}/contributors`,\n subscribers_url: `${repoUrl}/subscribers`,\n subscription_url: `${repoUrl}/subscription`,\n commits_url: `${repoUrl}/commits{/sha}`,\n git_commits_url: `${repoUrl}/git/commits{/sha}`,\n comments_url: `${repoUrl}/comments{/number}`,\n issue_comment_url: `${repoUrl}/issues/comments{/number}`,\n contents_url: `${repoUrl}/contents/{+path}`,\n compare_url: `${repoUrl}/compare/{base}...{head}`,\n merges_url: `${repoUrl}/merges`,\n archive_url: `${repoUrl}/{archive_format}{/ref}`,\n downloads_url: `${repoUrl}/downloads`,\n issues_url: `${repoUrl}/issues{/number}`,\n pulls_url: `${repoUrl}/pulls{/number}`,\n milestones_url: `${repoUrl}/milestones{/number}`,\n notifications_url: `${repoUrl}/notifications{?since,all,participating}`,\n labels_url: `${repoUrl}/labels{/name}`,\n releases_url: `${repoUrl}/releases{/id}`,\n deployments_url: `${repoUrl}/deployments`,\n created_at: repo.created_at,\n updated_at: repo.updated_at,\n pushed_at: repo.pushed_at,\n git_url: `git://${baseUrl.replace(/^https?:\\/\\//, \"\")}/${repo.full_name}.git`,\n ssh_url: `git@${baseUrl.replace(/^https?:\\/\\//, \"\")}:${repo.full_name}.git`,\n clone_url: `${htmlUrl}.git`,\n svn_url: htmlUrl,\n homepage: repo.homepage,\n size: repo.size,\n stargazers_count: repo.stargazers_count,\n watchers_count: repo.watchers_count,\n language: repo.language,\n has_issues: repo.has_issues,\n has_projects: repo.has_projects,\n has_downloads: repo.has_downloads,\n has_wiki: repo.has_wiki,\n has_pages: repo.has_pages,\n has_discussions: repo.has_discussions,\n forks_count: repo.forks_count,\n mirror_url: null,\n archived: repo.archived,\n disabled: repo.disabled,\n open_issues_count: repo.open_issues_count,\n license: repo.license,\n allow_forking: repo.allow_forking,\n is_template: repo.is_template,\n topics: repo.topics,\n visibility: repo.visibility,\n forks: repo.forks_count,\n open_issues: repo.open_issues_count,\n watchers: repo.watchers_count,\n default_branch: repo.default_branch,\n permissions:\n authUserId !== undefined\n ? computeRepoPermissions(store, repo, authUserId)\n : {\n admin: true,\n maintain: true,\n push: true,\n triage: true,\n pull: true,\n },\n allow_rebase_merge: repo.allow_rebase_merge,\n allow_squash_merge: repo.allow_squash_merge,\n allow_merge_commit: repo.allow_merge_commit,\n allow_auto_merge: repo.allow_auto_merge,\n delete_branch_on_merge: repo.delete_branch_on_merge,\n };\n}\n\nexport function formatIssue(issue: GitHubIssue, store: GitHubStore, baseUrl: string) {\n const repo = store.repos.get(issue.repo_id);\n if (!repo) return null;\n const user = store.users.get(issue.user_id);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n\n const labels = issue.label_ids\n .map((id) => store.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n\n const assignees = issue.assignee_ids\n .map((id) => store.users.get(id))\n .filter(Boolean)\n .map((u) => formatUser(u!, baseUrl));\n\n const milestone = issue.milestone_id ? store.milestones.get(issue.milestone_id) : null;\n const closedBy = issue.closed_by_id ? store.users.get(issue.closed_by_id) : null;\n\n return {\n url: `${repoUrl}/issues/${issue.number}`,\n repository_url: repoUrl,\n labels_url: `${repoUrl}/issues/${issue.number}/labels{/name}`,\n comments_url: `${repoUrl}/issues/${issue.number}/comments`,\n events_url: `${repoUrl}/issues/${issue.number}/events`,\n html_url: `${baseUrl}/${repo.full_name}/issues/${issue.number}`,\n id: issue.id,\n node_id: issue.node_id,\n number: issue.number,\n title: issue.title,\n user: user ? formatUser(user, baseUrl) : null,\n labels,\n state: issue.state,\n state_reason: issue.state_reason,\n locked: issue.locked,\n active_lock_reason: issue.active_lock_reason,\n assignee: assignees[0] ?? null,\n assignees,\n milestone: milestone ? formatMilestone(milestone, repo, store, baseUrl) : null,\n comments: issue.comments,\n created_at: issue.created_at,\n updated_at: issue.updated_at,\n closed_at: issue.closed_at,\n closed_by: closedBy ? formatUser(closedBy, baseUrl) : null,\n body: issue.body,\n reactions: defaultReactions(`${repoUrl}/issues/${issue.number}`),\n timeline_url: `${repoUrl}/issues/${issue.number}/timeline`,\n performed_via_github_app: null,\n author_association: computeAuthorAssociation(store, issue.user_id, issue.repo_id),\n };\n}\n\nexport function formatPullRequest(pr: GitHubPullRequest, store: GitHubStore, baseUrl: string) {\n const repo = store.repos.get(pr.repo_id);\n if (!repo) return null;\n const user = store.users.get(pr.user_id);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const headRepo = store.repos.get(pr.head_repo_id);\n const baseRepo = store.repos.get(pr.base_repo_id);\n\n const labels = pr.label_ids\n .map((id) => store.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n\n const assignees = pr.assignee_ids\n .map((id) => store.users.get(id))\n .filter(Boolean)\n .map((u) => formatUser(u!, baseUrl));\n\n const requestedReviewers = pr.requested_reviewer_ids\n .map((id) => store.users.get(id))\n .filter(Boolean)\n .map((u) => formatUser(u!, baseUrl));\n\n const requestedTeams = pr.requested_team_ids\n .map((id) => store.teams.get(id))\n .filter(Boolean)\n .map((t) => formatTeamBrief(t!, store, baseUrl));\n\n const milestone = pr.milestone_id ? store.milestones.get(pr.milestone_id) : null;\n const mergedBy = pr.merged_by_id ? store.users.get(pr.merged_by_id) : null;\n\n return {\n url: `${repoUrl}/pulls/${pr.number}`,\n id: pr.id,\n node_id: pr.node_id,\n html_url: `${baseUrl}/${repo.full_name}/pull/${pr.number}`,\n diff_url: `${baseUrl}/${repo.full_name}/pull/${pr.number}.diff`,\n patch_url: `${baseUrl}/${repo.full_name}/pull/${pr.number}.patch`,\n issue_url: `${repoUrl}/issues/${pr.number}`,\n number: pr.number,\n state: pr.state,\n locked: pr.locked,\n title: pr.title,\n user: user ? formatUser(user, baseUrl) : null,\n body: pr.body,\n created_at: pr.created_at,\n updated_at: pr.updated_at,\n closed_at: pr.closed_at,\n merged_at: pr.merged_at,\n merge_commit_sha: pr.merge_commit_sha,\n assignee: assignees[0] ?? null,\n assignees,\n requested_reviewers: requestedReviewers,\n requested_teams: requestedTeams,\n labels,\n milestone: milestone ? formatMilestone(milestone, repo, store, baseUrl) : null,\n draft: pr.draft,\n commits_url: `${repoUrl}/pulls/${pr.number}/commits`,\n review_comments_url: `${repoUrl}/pulls/${pr.number}/comments`,\n review_comment_url: `${repoUrl}/pulls/comments{/number}`,\n comments_url: `${repoUrl}/issues/${pr.number}/comments`,\n statuses_url: `${repoUrl}/statuses/${pr.head_sha}`,\n head: {\n label: `${headRepo?.full_name?.split(\"/\")[0] ?? \"unknown\"}:${pr.head_ref}`,\n ref: pr.head_ref,\n sha: pr.head_sha,\n user: headRepo ? formatOwner(store, headRepo.owner_id, headRepo.owner_type, baseUrl) : null,\n repo: headRepo ? formatRepo(headRepo, store, baseUrl) : null,\n },\n base: {\n label: `${baseRepo?.full_name?.split(\"/\")[0] ?? \"unknown\"}:${pr.base_ref}`,\n ref: pr.base_ref,\n sha: pr.base_sha,\n user: baseRepo ? formatOwner(store, baseRepo.owner_id, baseRepo.owner_type, baseUrl) : null,\n repo: baseRepo ? formatRepo(baseRepo, store, baseUrl) : null,\n },\n _links: {\n self: { href: `${repoUrl}/pulls/${pr.number}` },\n html: { href: `${baseUrl}/${repo.full_name}/pull/${pr.number}` },\n issue: { href: `${repoUrl}/issues/${pr.number}` },\n comments: { href: `${repoUrl}/issues/${pr.number}/comments` },\n review_comments: { href: `${repoUrl}/pulls/${pr.number}/comments` },\n review_comment: { href: `${repoUrl}/pulls/comments{/number}` },\n commits: { href: `${repoUrl}/pulls/${pr.number}/commits` },\n statuses: { href: `${repoUrl}/statuses/${pr.head_sha}` },\n },\n author_association: computeAuthorAssociation(store, pr.user_id, pr.repo_id),\n auto_merge: pr.auto_merge,\n merged: pr.merged,\n mergeable: pr.mergeable,\n rebaseable: true,\n mergeable_state: pr.mergeable_state,\n merged_by: mergedBy ? formatUser(mergedBy, baseUrl) : null,\n comments: pr.comments,\n review_comments: pr.review_comments,\n maintainer_can_modify: true,\n commits: pr.commits,\n additions: pr.additions,\n deletions: pr.deletions,\n changed_files: pr.changed_files,\n };\n}\n\nexport function formatLabel(label: GitHubLabel, repo: GitHubRepo, baseUrl: string) {\n return {\n id: label.id,\n node_id: label.node_id,\n url: `${baseUrl}/repos/${repo.full_name}/labels/${encodeURIComponent(label.name)}`,\n name: label.name,\n description: label.description,\n color: label.color,\n default: label.default,\n };\n}\n\nexport function formatMilestone(m: GitHubMilestone, repo: GitHubRepo, store: GitHubStore, baseUrl: string) {\n const creator = store.users.get(m.creator_id);\n return {\n url: `${baseUrl}/repos/${repo.full_name}/milestones/${m.number}`,\n html_url: `${baseUrl}/${repo.full_name}/milestone/${m.number}`,\n labels_url: `${baseUrl}/repos/${repo.full_name}/milestones/${m.number}/labels`,\n id: m.id,\n node_id: m.node_id,\n number: m.number,\n title: m.title,\n description: m.description,\n creator: creator ? formatUser(creator, baseUrl) : null,\n open_issues: m.open_issues,\n closed_issues: m.closed_issues,\n state: m.state,\n created_at: m.created_at,\n updated_at: m.updated_at,\n due_on: m.due_on,\n closed_at: m.closed_at,\n };\n}\n\nexport function formatComment(comment: GitHubComment, store: GitHubStore, baseUrl: string) {\n const repo = store.repos.get(comment.repo_id);\n if (!repo) return null;\n const user = store.users.get(comment.user_id);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n\n if (comment.comment_type === \"issue\") {\n return {\n url: `${repoUrl}/issues/comments/${comment.id}`,\n html_url: `${baseUrl}/${repo.full_name}/issues/${comment.issue_number}#issuecomment-${comment.id}`,\n issue_url: `${repoUrl}/issues/${comment.issue_number}`,\n id: comment.id,\n node_id: comment.node_id,\n user: user ? formatUser(user, baseUrl) : null,\n created_at: comment.created_at,\n updated_at: comment.updated_at,\n author_association: computeAuthorAssociation(store, comment.user_id, comment.repo_id),\n body: comment.body,\n reactions: defaultReactions(`${repoUrl}/issues/comments/${comment.id}`),\n performed_via_github_app: null,\n };\n }\n\n if (comment.comment_type === \"review\") {\n return {\n url: `${repoUrl}/pulls/comments/${comment.id}`,\n html_url: `${baseUrl}/${repo.full_name}/pull/${comment.pull_number}#discussion_r${comment.id}`,\n pull_request_url: `${repoUrl}/pulls/${comment.pull_number}`,\n id: comment.id,\n node_id: comment.node_id,\n diff_hunk: \"\",\n path: comment.path ?? \"\",\n position: comment.position,\n original_position: comment.position,\n commit_id: comment.commit_sha ?? \"\",\n original_commit_id: comment.commit_sha ?? \"\",\n in_reply_to_id: comment.in_reply_to_id,\n user: user ? formatUser(user, baseUrl) : null,\n body: comment.body,\n created_at: comment.created_at,\n updated_at: comment.updated_at,\n author_association: computeAuthorAssociation(store, comment.user_id, comment.repo_id),\n reactions: defaultReactions(`${repoUrl}/pulls/comments/${comment.id}`),\n line: comment.line,\n side: comment.side ?? \"RIGHT\",\n subject_type: comment.subject_type ?? \"line\",\n pull_request_review_id: comment.review_id,\n };\n }\n\n return {\n url: `${repoUrl}/comments/${comment.id}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${comment.commit_sha}#commitcomment-${comment.id}`,\n id: comment.id,\n node_id: comment.node_id,\n user: user ? formatUser(user, baseUrl) : null,\n body: comment.body,\n path: comment.path,\n position: comment.position,\n line: comment.line,\n commit_id: comment.commit_sha,\n created_at: comment.created_at,\n updated_at: comment.updated_at,\n author_association: computeAuthorAssociation(store, comment.user_id, comment.repo_id),\n reactions: defaultReactions(`${repoUrl}/comments/${comment.id}`),\n };\n}\n\nexport function formatReview(review: GitHubReview, store: GitHubStore, baseUrl: string) {\n const repo = store.repos.get(review.repo_id);\n if (!repo) return null;\n const user = store.users.get(review.user_id);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n\n return {\n id: review.id,\n node_id: review.node_id,\n user: user ? formatUser(user, baseUrl) : null,\n body: review.body ?? \"\",\n state: review.state,\n html_url: `${baseUrl}/${repo.full_name}/pull/${review.pull_number}#pullrequestreview-${review.id}`,\n pull_request_url: `${repoUrl}/pulls/${review.pull_number}`,\n _links: {\n html: { href: `${baseUrl}/${repo.full_name}/pull/${review.pull_number}#pullrequestreview-${review.id}` },\n pull_request: { href: `${repoUrl}/pulls/${review.pull_number}` },\n },\n submitted_at: review.submitted_at,\n commit_id: review.commit_id,\n author_association: computeAuthorAssociation(store, review.user_id, review.repo_id),\n created_at: review.created_at,\n updated_at: review.updated_at,\n };\n}\n\nexport function formatTeamBrief(team: GitHubTeam, store: GitHubStore, baseUrl: string) {\n const org = store.orgs.get(team.org_id);\n return {\n id: team.id,\n node_id: team.node_id,\n url: `${baseUrl}/teams/${team.id}`,\n html_url: `${baseUrl}/orgs/${org?.login}/teams/${team.slug}`,\n name: team.name,\n slug: team.slug,\n description: team.description,\n privacy: team.privacy,\n permission: team.permission,\n members_url: `${baseUrl}/teams/${team.id}/members{/member}`,\n repositories_url: `${baseUrl}/teams/${team.id}/repos`,\n };\n}\n\nexport function formatBranch(branch: GitHubBranch, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n name: branch.name,\n commit: {\n sha: branch.sha,\n url: `${repoUrl}/commits/${branch.sha}`,\n },\n protected: branch.protected,\n protection_url: `${repoUrl}/branches/${branch.name}/protection`,\n };\n}\n\nexport function formatRelease(release: GitHubRelease, store: GitHubStore, baseUrl: string) {\n const repo = store.repos.get(release.repo_id);\n if (!repo) return null;\n const author = store.users.get(release.author_id);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const assets = store.releaseAssets.findBy(\"release_id\", release.id);\n\n return {\n url: `${repoUrl}/releases/${release.id}`,\n html_url: `${baseUrl}/${repo.full_name}/releases/tag/${release.tag_name}`,\n assets_url: `${repoUrl}/releases/${release.id}/assets`,\n upload_url: `${repoUrl}/releases/${release.id}/assets{?name,label}`,\n tarball_url: `${repoUrl}/tarball/${release.tag_name}`,\n zipball_url: `${repoUrl}/zipball/${release.tag_name}`,\n id: release.id,\n node_id: release.node_id,\n tag_name: release.tag_name,\n target_commitish: release.target_commitish,\n name: release.name,\n draft: release.draft,\n prerelease: release.prerelease,\n created_at: release.created_at,\n published_at: release.published_at,\n author: author ? formatUser(author, baseUrl) : null,\n assets: assets.map((a) => formatReleaseAsset(a, repo, baseUrl)),\n body: release.body,\n };\n}\n\nexport function formatReleaseAsset(asset: GitHubReleaseAsset, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const uploader = null;\n return {\n url: `${repoUrl}/releases/assets/${asset.id}`,\n id: asset.id,\n node_id: asset.node_id,\n name: asset.name,\n label: asset.label,\n uploader,\n content_type: asset.content_type,\n state: asset.state,\n size: asset.size,\n download_count: asset.download_count,\n created_at: asset.created_at,\n updated_at: asset.updated_at,\n browser_download_url: `${baseUrl}/${repo.full_name}/releases/download/${asset.name}`,\n };\n}\n\nexport function formatWebhook(wh: GitHubWebhook, baseUrl: string, ownerPath: string) {\n const pathPrefix = wh.repo_id != null ? `repos/${ownerPath}` : `orgs/${ownerPath}`;\n return {\n type: wh.repo_id ? \"Repository\" : \"Organization\",\n id: wh.id,\n name: wh.name,\n active: wh.active,\n events: wh.events,\n config: {\n content_type: wh.config.content_type,\n insecure_ssl: wh.config.insecure_ssl,\n url: wh.config.url,\n },\n updated_at: wh.updated_at,\n created_at: wh.created_at,\n url: `${baseUrl}/${pathPrefix}/hooks/${wh.id}`,\n test_url: `${baseUrl}/${pathPrefix}/hooks/${wh.id}/tests`,\n ping_url: `${baseUrl}/${pathPrefix}/hooks/${wh.id}/pings`,\n deliveries_url: `${baseUrl}/${pathPrefix}/hooks/${wh.id}/deliveries`,\n last_response: wh.last_response,\n };\n}\n\nfunction defaultReactions(url: string) {\n return {\n url: `${url}/reactions`,\n total_count: 0,\n \"+1\": 0,\n \"-1\": 0,\n laugh: 0,\n hooray: 0,\n confused: 0,\n heart: 0,\n rocket: 0,\n eyes: 0,\n };\n}\n\nexport function lookupRepo(store: GitHubStore, owner: string, repoName: string) {\n const fullName = `${owner}/${repoName}`;\n return store.repos.findOneBy(\"full_name\", fullName);\n}\n\nexport function lookupOwner(store: GitHubStore, login: string) {\n const user = store.users.findOneBy(\"login\", login);\n if (user) return { type: \"User\" as const, id: user.id, login: user.login };\n const org = store.orgs.findOneBy(\"login\", login);\n if (org) return { type: \"Organization\" as const, id: org.id, login: org.login };\n return null;\n}\n\nexport function getNextIssueNumber(store: GitHubStore, repoId: number): number {\n const issues = store.issues.findBy(\"repo_id\", repoId);\n const prs = store.pullRequests.findBy(\"repo_id\", repoId);\n const maxIssue = issues.reduce((max, i) => Math.max(max, i.number), 0);\n const maxPr = prs.reduce((max, p) => Math.max(max, p.number), 0);\n return Math.max(maxIssue, maxPr) + 1;\n}\n\nexport function getNextMilestoneNumber(store: GitHubStore, repoId: number): number {\n const milestones = store.milestones.findBy(\"repo_id\", repoId);\n return milestones.reduce((max, m) => Math.max(max, m.number), 0) + 1;\n}\n","import { buildSchema, graphql, GraphQLError, type ExecutionResult } from \"graphql\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\n\n// GitHub's GraphQL API (api.github.com/graphql), emulated on the SAME instance as\n// the REST routes so both read one store. We use graphql-js for real parsing,\n// validation, and introspection, then wrap it with GitHub's HTTP quirks captured\n// from the live API:\n// • no User-Agent → 403 \"Request forbidden by administrative rules…\"\n// • no/anonymous auth → 403 \"API rate limit exceeded…\" (GraphQL needs auth)\n// • invalid token → 401 {\"message\":\"Bad credentials\", …}\n// • empty query → 200 {\"errors\":[{\"message\":\"A query attribute …\"}]}\n// • undefined field → 200 errors[].extensions.code = \"undefinedField\"\n// • success → 200 {\"data\":…} + x-github-media-type / x-ratelimit headers\n\nconst SCHEMA = buildSchema(/* GraphQL */ `\n type Query {\n viewer: User!\n user(login: String!): User\n repository(owner: String!, name: String!): Repository\n rateLimit: RateLimit\n }\n type User {\n login: String!\n name: String\n id: ID!\n databaseId: Int\n company: String\n bio: String\n url: String\n }\n type Repository {\n id: ID!\n name: String!\n nameWithOwner: String!\n description: String\n stargazerCount: Int!\n forkCount: Int!\n isPrivate: Boolean!\n primaryLanguage: Language\n defaultBranchRef: Ref\n owner: RepositoryOwner!\n url: String\n }\n type Language {\n name: String!\n }\n type Ref {\n name: String!\n }\n type RepositoryOwner {\n login: String!\n }\n type RateLimit {\n limit: Int!\n cost: Int!\n remaining: Int!\n used: Int!\n resource: String!\n }\n`);\n\n// graphql-js validation says \"Cannot query field 'x' on type 'T'.\"; GitHub says\n// \"Field 'x' doesn't exist on type 'T'\" with extensions.code \"undefinedField\".\n// Re-shape known validation errors so the envelope matches the real API.\nfunction toGitHubError(err: GraphQLError): Record<string, unknown> {\n const base: Record<string, unknown> = { message: err.message };\n if (err.locations) base.locations = err.locations;\n if (err.path) base.path = err.path;\n const m = /^Cannot query field \"(.+?)\" on type \"(.+?)\"\\.?/.exec(err.message);\n if (m) {\n base.message = `Field '${m[1]}' doesn't exist on type '${m[2]}'`;\n base.extensions = { code: \"undefinedField\", typeName: m[2], fieldName: m[1] };\n } else if (err.extensions && Object.keys(err.extensions).length > 0) {\n base.extensions = err.extensions;\n }\n return base;\n}\n\nexport function graphqlRoutes(ctx: RouteContext): void {\n const { app, store, tokenMap } = ctx;\n const gh = getGitHubStore(store);\n\n const root = {\n viewer: (_args: unknown, c: { login: string }) => shapeUser(c.login),\n user: ({ login }: { login: string }) => shapeUser(login),\n repository: ({ owner, name }: { owner: string; name: string }) => {\n const repo = gh.repos.all().find((r) => r.full_name === `${owner}/${name}`);\n if (!repo) return null;\n const ownerLogin =\n gh.users.all().find((u) => u.id === repo.owner_id)?.login ??\n gh.orgs.all().find((o) => o.id === repo.owner_id)?.login ??\n owner;\n return {\n id: repo.node_id,\n name: repo.name,\n nameWithOwner: repo.full_name,\n description: repo.description,\n stargazerCount: repo.stargazers_count ?? 0,\n forkCount: (repo as { forks_count?: number }).forks_count ?? 0,\n isPrivate: Boolean((repo as { private?: boolean }).private),\n primaryLanguage: repo.language ? { name: repo.language } : null,\n defaultBranchRef: repo.default_branch ? { name: repo.default_branch } : null,\n owner: { login: ownerLogin },\n url: `https://github.com/${repo.full_name}`,\n };\n },\n rateLimit: () => ({ limit: 5000, cost: 1, remaining: 4999, used: 1, resource: \"graphql\" }),\n };\n\n function shapeUser(login: string) {\n const u = gh.users.all().find((x) => x.login === login);\n if (!u) return null;\n return {\n login: u.login,\n name: u.name ?? null,\n id: u.node_id,\n databaseId: u.id,\n company: u.company ?? null,\n bio: u.bio ?? null,\n url: `https://github.com/${u.login}`,\n };\n }\n\n app.post(\"/graphql\", async (c) => {\n // Quirk 1: User-Agent required — checked before auth, like the real API.\n if (!c.req.header(\"user-agent\")) {\n return c.text(\n \"Request forbidden by administrative rules. Please make sure your request has a User-Agent header (https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required). Check https://developer.github.com for other possible causes.\",\n 403,\n );\n }\n\n // Quirk 2/3: auth. Anonymous → 403 rate-limit; bad token → 401 Bad credentials.\n const authz = c.req.header(\"authorization\") ?? \"\";\n const token = /^(?:bearer|token)\\s+(.+)$/i.exec(authz)?.[1]?.trim();\n if (!token) {\n return c.json(\n {\n message:\n \"API rate limit exceeded for your request. (But here's the good news: Authenticated requests get a higher rate limit. Check out the documentation for more details.)\",\n documentation_url:\n \"https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#rate-limiting\",\n },\n 403,\n );\n }\n const authUser = tokenMap?.get(token);\n if (!authUser) {\n return c.json(\n { message: \"Bad credentials\", documentation_url: \"https://docs.github.com/rest\", status: \"401\" },\n 401,\n );\n }\n\n const body = (await c.req.json().catch(() => ({}))) as {\n query?: unknown;\n variables?: Record<string, unknown>;\n operationName?: string;\n };\n if (typeof body.query !== \"string\" || body.query.length === 0) {\n return c.json({ errors: [{ message: \"A query attribute must be specified and must be a string.\" }] }, 200);\n }\n\n let result: ExecutionResult;\n try {\n result = await graphql({\n schema: SCHEMA,\n source: body.query,\n rootValue: root,\n contextValue: { login: authUser.login },\n variableValues: body.variables,\n operationName: body.operationName,\n });\n } catch (e) {\n return c.json({ errors: [{ message: e instanceof Error ? e.message : \"Internal error\" }] }, 200);\n }\n\n // GitHub returns 200 for executed queries (even with errors) + these headers.\n c.header(\"X-GitHub-Media-Type\", \"github.v4; format=json\");\n c.header(\"X-RateLimit-Limit\", \"5000\");\n c.header(\"X-RateLimit-Remaining\", \"4999\");\n c.header(\"X-RateLimit-Used\", \"1\");\n c.header(\"X-RateLimit-Resource\", \"graphql\");\n c.header(\"X-OAuth-Scopes\", (authUser.scopes ?? []).join(\", \"));\n\n const payload: Record<string, unknown> = {};\n if (result.errors) payload.errors = result.errors.map((e) => toGitHubError(e as GraphQLError));\n if (\"data\" in result && result.data !== undefined) payload.data = result.data;\n return c.json(payload, 200);\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 { AuthUser } from \"@emulators/core\";\nimport { notFound, unauthorized, forbidden } from \"@emulators/core\";\nimport type { GitHubStore } from \"./store.js\";\nimport type { GitHubRepo, GitHubUser } from \"./entities.js\";\n\nexport { notFound as notFoundResponse };\n\nexport function ownerLoginOf(gh: GitHubStore, repo: GitHubRepo): string {\n if (repo.owner_type === \"User\") {\n return gh.users.get(repo.owner_id)?.login ?? \"unknown\";\n }\n return gh.orgs.get(repo.owner_id)?.login ?? \"unknown\";\n}\n\nexport function isOrgMember(gh: GitHubStore, userId: number, orgId: number): boolean {\n for (const team of gh.teams.all()) {\n if (team.org_id !== orgId) continue;\n const m = gh.teamMembers.findBy(\"team_id\", team.id).find((x) => x.user_id === userId);\n if (m) return true;\n }\n return false;\n}\n\nexport function getActorUser(gh: GitHubStore, authUser: AuthUser): GitHubUser | undefined {\n return gh.users.findOneBy(\"login\", authUser.login);\n}\n\nexport function canAccessRepo(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): boolean {\n if (!repo.private) return true;\n if (!authUser) return false;\n const user = getActorUser(gh, authUser);\n if (!user) return false;\n if (repo.owner_type === \"User\" && repo.owner_id === user.id) return true;\n if (repo.owner_type === \"Organization\" && isOrgMember(gh, user.id, repo.owner_id)) return true;\n return Boolean(gh.collaborators.findBy(\"repo_id\", repo.id).find((c) => c.user_id === user.id));\n}\n\nexport function assertRepoRead(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): void {\n if (canAccessRepo(gh, authUser, repo)) return;\n if (!authUser) throw unauthorized();\n throw forbidden();\n}\n\nexport function assertAuthenticatedUser(gh: GitHubStore, authUser: AuthUser | undefined): GitHubUser {\n if (!authUser) throw unauthorized();\n const user = getActorUser(gh, authUser);\n if (!user) throw unauthorized();\n return user;\n}\n\nexport function hasRepoAdmin(gh: GitHubStore, user: GitHubUser, repo: GitHubRepo): boolean {\n if (repo.owner_type === \"User\" && repo.owner_id === user.id) return true;\n if (repo.owner_type === \"Organization\" && isOrgMember(gh, user.id, repo.owner_id)) return true;\n const collab = gh.collaborators.findBy(\"repo_id\", repo.id).find((c) => c.user_id === user.id);\n return collab?.permission === \"admin\" || collab?.permission === \"maintain\";\n}\n\nexport function assertRepoAdmin(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): GitHubUser {\n if (!authUser) throw unauthorized();\n const user = getActorUser(gh, authUser);\n if (!user) throw unauthorized();\n if (hasRepoAdmin(gh, user, repo)) return user;\n throw forbidden();\n}\n\nexport function assertRepoWrite(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): GitHubUser {\n const user = assertAuthenticatedUser(gh, authUser);\n if (!repo.private) return user;\n if (!canAccessRepo(gh, authUser, repo)) throw forbidden();\n return user;\n}\n\nexport function assertIssueWrite(gh: GitHubStore, authUser: AuthUser | undefined, repo: GitHubRepo): GitHubUser {\n const user = assertAuthenticatedUser(gh, authUser);\n if (!repo.private) return user;\n if (!canAccessRepo(gh, authUser, repo)) throw forbidden();\n return user;\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader, unauthorized } from \"@emulators/core\";\nimport { assertAuthenticatedUser, canAccessRepo, notFoundResponse } from \"../route-helpers.js\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubRepo, GitHubUser } from \"../entities.js\";\nimport { formatOrgBrief, formatRepo, formatUser, formatUserFull } from \"../helpers.js\";\n\nfunction listReposForUser(gh: GitHubStore, user: GitHubUser, type: \"all\" | \"owner\" | \"member\"): GitHubRepo[] {\n const owned = gh.repos.all().filter((r) => r.owner_id === user.id && r.owner_type === \"User\");\n const member = gh.collaborators\n .findBy(\"user_id\", user.id)\n .map((c) => gh.repos.get(c.repo_id))\n .filter((r): r is GitHubRepo => Boolean(r))\n .filter((r) => !(r.owner_id === user.id && r.owner_type === \"User\"));\n\n if (type === \"owner\") return owned;\n if (type === \"member\") return member;\n\n const map = new Map<number, GitHubRepo>();\n for (const r of owned) map.set(r.id, r);\n for (const r of member) map.set(r.id, r);\n return Array.from(map.values());\n}\n\nfunction sortRepos(\n repos: GitHubRepo[],\n sort: \"created\" | \"updated\" | \"pushed\" | \"full_name\",\n direction: \"asc\" | \"desc\",\n): GitHubRepo[] {\n const mul = direction === \"asc\" ? 1 : -1;\n const sorted = [...repos];\n sorted.sort((a, b) => {\n if (sort === \"full_name\") {\n return a.full_name.localeCompare(b.full_name) * mul;\n }\n const field = sort === \"created\" ? \"created_at\" : sort === \"updated\" ? \"updated_at\" : \"pushed_at\";\n const av = a[field] ?? \"\";\n const bv = b[field] ?? \"\";\n if (av < bv) return -1 * mul;\n if (av > bv) return 1 * mul;\n return 0;\n });\n return sorted;\n}\n\nfunction orgsForUser(gh: GitHubStore, userId: number) {\n const memberships = gh.teamMembers.findBy(\"user_id\", userId);\n const orgIds = new Set<number>();\n for (const m of memberships) {\n const team = gh.teams.get(m.team_id);\n if (team) orgIds.add(team.org_id);\n }\n const orgs = [...orgIds].map((id) => gh.orgs.get(id)).filter((o): o is NonNullable<typeof o> => Boolean(o));\n orgs.sort((a, b) => a.login.localeCompare(b.login));\n return orgs;\n}\n\nexport function usersRoutes({ app, store, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/user\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n throw unauthorized();\n }\n const user = gh.users.findOneBy(\"login\", authUser.login);\n if (!user) {\n throw notFoundResponse();\n }\n return c.json(formatUserFull(user, baseUrl));\n });\n\n app.patch(\"/user\", async (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n throw unauthorized();\n }\n const existing = gh.users.findOneBy(\"login\", authUser.login);\n if (!existing) {\n throw notFoundResponse();\n }\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubUser> = {};\n\n if (\"name\" in body) {\n if (body.name === null) patch.name = null;\n else if (typeof body.name === \"string\") patch.name = body.name;\n }\n if (\"email\" in body) {\n if (body.email === null) patch.email = null;\n else if (typeof body.email === \"string\") patch.email = body.email;\n }\n if (\"blog\" in body && typeof body.blog === \"string\") {\n patch.blog = body.blog;\n }\n if (\"twitter_username\" in body) {\n if (body.twitter_username === null) patch.twitter_username = null;\n else if (typeof body.twitter_username === \"string\") {\n patch.twitter_username = body.twitter_username;\n }\n }\n if (\"company\" in body) {\n if (body.company === null) patch.company = null;\n else if (typeof body.company === \"string\") patch.company = body.company;\n }\n if (\"location\" in body) {\n if (body.location === null) patch.location = null;\n else if (typeof body.location === \"string\") patch.location = body.location;\n }\n if (\"hireable\" in body) {\n if (body.hireable === null) patch.hireable = null;\n else if (typeof body.hireable === \"boolean\") patch.hireable = body.hireable;\n }\n if (\"bio\" in body) {\n if (body.bio === null) patch.bio = null;\n else if (typeof body.bio === \"string\") patch.bio = body.bio;\n }\n\n const updated = gh.users.update(existing.id, patch);\n if (!updated) {\n throw notFoundResponse();\n }\n return c.json(formatUserFull(updated, baseUrl));\n });\n\n app.get(\"/user/repos\", (c) => {\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n\n const typeRaw = (c.req.query(\"type\") ?? \"all\").toLowerCase();\n if (typeRaw !== \"all\" && typeRaw !== \"owner\" && typeRaw !== \"member\") {\n throw new ApiError(422, \"Invalid type parameter\");\n }\n const type = typeRaw as \"all\" | \"owner\" | \"member\";\n\n const sortRaw = (c.req.query(\"sort\") ?? \"full_name\").toLowerCase();\n if (sortRaw !== \"created\" && sortRaw !== \"updated\" && sortRaw !== \"pushed\" && sortRaw !== \"full_name\") {\n throw new ApiError(422, \"Invalid sort parameter\");\n }\n const sort = sortRaw as \"created\" | \"updated\" | \"pushed\" | \"full_name\";\n\n const direction =\n (c.req.query(\"direction\")?.toLowerCase() as \"asc\" | \"desc\" | undefined) ??\n (sort === \"full_name\" ? \"asc\" : \"desc\");\n if (direction !== \"asc\" && direction !== \"desc\") {\n throw new ApiError(422, \"Invalid direction parameter\");\n }\n\n const { page, per_page } = parsePagination(c);\n const allRepos = sortRepos(listReposForUser(gh, user, type), sort, direction).filter((r) =>\n canAccessRepo(gh, authUser, r),\n );\n const total = allRepos.length;\n const start = (page - 1) * per_page;\n const items = allRepos.slice(start, start + per_page).map((r) => formatRepo(r, gh, baseUrl));\n\n setLinkHeader(c, total, page, per_page);\n return c.json(items);\n });\n\n app.get(\"/users\", (c) => {\n const since = Math.max(0, parseInt(c.req.query(\"since\") ?? \"0\", 10) || 0);\n const perPage = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n\n const ordered = gh.users\n .all()\n .filter((u) => u.id > since)\n .sort((a, b) => a.id - b.id);\n const page = ordered.slice(0, perPage);\n\n if (page.length === perPage && ordered.length > perPage) {\n const lastId = page[page.length - 1]!.id;\n const nextUrl = new URL(c.req.url);\n nextUrl.searchParams.set(\"since\", String(lastId));\n nextUrl.searchParams.set(\"per_page\", String(perPage));\n c.header(\"Link\", `<${nextUrl.toString()}>; rel=\"next\"`);\n }\n\n return c.json(page.map((u) => formatUser(u, baseUrl)));\n });\n\n app.get(\"/users/:username/repos\", (c) => {\n const username = c.req.param(\"username\")!;\n const user = gh.users.findOneBy(\"login\", username);\n if (!user) {\n throw notFoundResponse();\n }\n\n const typeRaw = (c.req.query(\"type\") ?? \"owner\").toLowerCase();\n if (typeRaw !== \"all\" && typeRaw !== \"owner\" && typeRaw !== \"member\") {\n throw new ApiError(422, \"Invalid type parameter\");\n }\n const type = typeRaw as \"all\" | \"owner\" | \"member\";\n\n const sortRaw = (c.req.query(\"sort\") ?? \"full_name\").toLowerCase();\n if (sortRaw !== \"created\" && sortRaw !== \"updated\" && sortRaw !== \"pushed\" && sortRaw !== \"full_name\") {\n throw new ApiError(422, \"Invalid sort parameter\");\n }\n const sort = sortRaw as \"created\" | \"updated\" | \"pushed\" | \"full_name\";\n\n const direction =\n (c.req.query(\"direction\")?.toLowerCase() as \"asc\" | \"desc\" | undefined) ??\n (sort === \"full_name\" ? \"asc\" : \"desc\");\n if (direction !== \"asc\" && direction !== \"desc\") {\n throw new ApiError(422, \"Invalid direction parameter\");\n }\n\n const { page, per_page } = parsePagination(c);\n const allRepos = sortRepos(listReposForUser(gh, user, type), sort, direction);\n const total = allRepos.length;\n const start = (page - 1) * per_page;\n const items = allRepos.slice(start, start + per_page).map((r) => formatRepo(r, gh, baseUrl));\n\n setLinkHeader(c, total, page, per_page);\n return c.json(items);\n });\n\n app.get(\"/users/:username/orgs\", (c) => {\n const username = c.req.param(\"username\")!;\n const user = gh.users.findOneBy(\"login\", username);\n if (!user) {\n throw notFoundResponse();\n }\n\n const orgs = orgsForUser(gh, user.id);\n return c.json(orgs.map((o) => formatOrgBrief(o, baseUrl)));\n });\n\n app.get(\"/users/:username/followers\", (c) => {\n const username = c.req.param(\"username\")!;\n if (!gh.users.findOneBy(\"login\", username)) {\n throw notFoundResponse();\n }\n\n const { page, per_page } = parsePagination(c);\n setLinkHeader(c, 0, page, per_page);\n return c.json([]);\n });\n\n app.get(\"/users/:username/following\", (c) => {\n const username = c.req.param(\"username\")!;\n if (!gh.users.findOneBy(\"login\", username)) {\n throw notFoundResponse();\n }\n\n const { page, per_page } = parsePagination(c);\n setLinkHeader(c, 0, page, per_page);\n return c.json([]);\n });\n\n app.get(\"/users/:username/hovercard\", (c) => {\n const username = c.req.param(\"username\")!;\n if (!gh.users.findOneBy(\"login\", username)) {\n throw notFoundResponse();\n }\n\n return c.json({ contexts: [] });\n });\n\n app.get(\"/users/:username\", (c) => {\n const username = c.req.param(\"username\")!;\n const user = gh.users.findOneBy(\"login\", username);\n if (!user) {\n throw notFoundResponse();\n }\n return c.json(formatUserFull(user, baseUrl));\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { ApiError, forbidden, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport {\n assertAuthenticatedUser,\n assertRepoRead,\n hasRepoAdmin,\n isOrgMember,\n notFoundResponse,\n ownerLoginOf,\n} from \"../route-helpers.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubBlob,\n GitHubBranch,\n GitHubCollaborator,\n GitHubCommit,\n GitHubRef,\n GitHubRepo,\n GitHubTag,\n GitHubTree,\n GitHubUser,\n} from \"../entities.js\";\nimport type { Collection, Entity } from \"@emulators/core\";\nimport { formatRepo, formatUser, generateNodeId, generateSha, lookupOwner, lookupRepo, timestamp } from \"../helpers.js\";\n\nconst LICENSE_TEMPLATES: Record<string, { key: string; name: string; spdx_id: string }> = {\n mit: { key: \"mit\", name: \"MIT License\", spdx_id: \"MIT\" },\n \"apache-2.0\": { key: \"apache-2.0\", name: \"Apache License 2.0\", spdx_id: \"Apache-2.0\" },\n \"gpl-3.0\": { key: \"gpl-3.0\", name: \"GNU General Public License v3.0\", spdx_id: \"GPL-3.0\" },\n \"bsd-3-clause\": {\n key: \"bsd-3-clause\",\n name: 'BSD 3-Clause \"New\" or \"Revised\" License',\n spdx_id: \"BSD-3-Clause\",\n },\n unlicense: { key: \"unlicense\", name: \"The Unlicense\", spdx_id: \"Unlicense\" },\n};\n\nfunction resolveLicenseTemplate(template: string) {\n const key = template.trim().toLowerCase();\n return LICENSE_TEMPLATES[key] ?? null;\n}\n\nfunction validateRepoName(name: unknown): string {\n if (typeof name !== \"string\" || !name.trim()) {\n throw new ApiError(422, \"Invalid repository name\");\n }\n const trimmed = name.trim();\n if (trimmed.length > 100 || !/^[a-zA-Z0-9._-]+$/.test(trimmed)) {\n throw new ApiError(422, \"Invalid repository name\");\n }\n return trimmed;\n}\n\nfunction seedInitialGit(gh: GitHubStore, repo: GitHubRepo, actor: GitHubUser | null, readmeTitle?: string) {\n const repoId = repo.id;\n const readme = `# ${readmeTitle ?? repo.name}\\n`;\n const size = Buffer.byteLength(readme, \"utf8\");\n\n const blob = gh.blobs.insert({\n repo_id: repoId,\n sha: generateSha(),\n node_id: \"\",\n content: readme,\n encoding: \"utf-8\",\n size,\n } as Omit<GitHubBlob, \"id\" | \"created_at\" | \"updated_at\">);\n gh.blobs.update(blob.id, { node_id: generateNodeId(\"Blob\", blob.id) });\n\n const tree = gh.trees.insert({\n repo_id: repoId,\n sha: generateSha(),\n node_id: \"\",\n tree: [{ path: \"README.md\", mode: \"100644\", type: \"blob\", sha: blob.sha }],\n truncated: false,\n } as Omit<GitHubTree, \"id\" | \"created_at\" | \"updated_at\">);\n gh.trees.update(tree.id, { node_id: generateNodeId(\"Tree\", tree.id) });\n\n const authorName = actor?.name ?? actor?.login ?? \"User\";\n const login = actor?.login ?? \"user\";\n const email = actor?.email ?? `${login}@users.noreply.github.com`;\n const now = timestamp();\n\n const commit = gh.commits.insert({\n repo_id: repoId,\n sha: generateSha(),\n node_id: \"\",\n message: \"Initial commit\",\n author_name: authorName,\n author_email: email,\n author_date: now,\n committer_name: authorName,\n committer_email: email,\n committer_date: now,\n tree_sha: tree.sha,\n parent_shas: [],\n user_id: actor?.id ?? null,\n } as Omit<GitHubCommit, \"id\" | \"created_at\" | \"updated_at\">);\n gh.commits.update(commit.id, { node_id: generateNodeId(\"Commit\", commit.id) });\n\n gh.branches.insert({\n repo_id: repoId,\n name: repo.default_branch,\n sha: commit.sha,\n protected: false,\n } as Omit<GitHubBranch, \"id\" | \"created_at\" | \"updated_at\">);\n\n const ref = gh.refs.insert({\n repo_id: repoId,\n ref: `refs/heads/${repo.default_branch}`,\n sha: commit.sha,\n node_id: \"\",\n } as Omit<GitHubRef, \"id\" | \"created_at\" | \"updated_at\">);\n gh.refs.update(ref.id, { node_id: generateNodeId(\"Ref\", ref.id) });\n\n gh.repos.update(repo.id, {\n size,\n pushed_at: now,\n language: \"Markdown\",\n languages: { Markdown: size },\n });\n}\n\nfunction bumpPublicRepos(gh: GitHubStore, ownerId: number, ownerType: \"User\" | \"Organization\", delta: number) {\n if (delta === 0) return;\n if (ownerType === \"User\") {\n const u = gh.users.get(ownerId);\n if (u) gh.users.update(ownerId, { public_repos: Math.max(0, u.public_repos + delta) });\n } else {\n const o = gh.orgs.get(ownerId);\n if (o) gh.orgs.update(ownerId, { public_repos: Math.max(0, o.public_repos + delta) });\n }\n}\n\ntype CreateRepoRecordParams = {\n name: unknown;\n description: string | null;\n private: boolean;\n homepage: string | null;\n has_issues: boolean;\n has_wiki: boolean;\n has_projects: boolean;\n auto_init: boolean;\n license_template: string | null | undefined;\n gitignore_template: string | null | undefined;\n owner_id: number;\n owner_type: \"User\" | \"Organization\";\n owner_login: string;\n default_branch: string;\n baseUrl: string;\n allow_rebase_merge?: boolean;\n allow_squash_merge?: boolean;\n allow_merge_commit?: boolean;\n delete_branch_on_merge?: boolean;\n};\n\nfunction createRepoRecord(gh: GitHubStore, params: CreateRepoRecordParams, actor: GitHubUser): GitHubRepo {\n const name = validateRepoName(params.name);\n const fullName = `${params.owner_login}/${name}`;\n if (gh.repos.findOneBy(\"full_name\", fullName)) {\n throw new ApiError(422, \"Repository already exists\");\n }\n\n const isPrivate = params.private;\n const visibility = isPrivate ? \"private\" : (\"public\" as GitHubRepo[\"visibility\"]);\n\n const license = typeof params.license_template === \"string\" ? resolveLicenseTemplate(params.license_template) : null;\n\n const repo = gh.repos.insert({\n node_id: \"\",\n name,\n full_name: fullName,\n owner_id: params.owner_id,\n owner_type: params.owner_type,\n private: isPrivate,\n description: params.description,\n fork: false,\n forked_from_id: null,\n homepage: params.homepage,\n language: null,\n languages: {},\n forks_count: 0,\n stargazers_count: 0,\n watchers_count: 0,\n size: 0,\n default_branch: params.default_branch,\n open_issues_count: 0,\n topics: [],\n has_issues: params.has_issues,\n has_projects: params.has_projects,\n has_wiki: params.has_wiki,\n has_pages: false,\n has_downloads: true,\n has_discussions: false,\n archived: false,\n disabled: false,\n visibility,\n pushed_at: null,\n allow_rebase_merge: params.allow_rebase_merge ?? true,\n allow_squash_merge: params.allow_squash_merge ?? true,\n allow_merge_commit: params.allow_merge_commit ?? true,\n allow_auto_merge: false,\n delete_branch_on_merge: params.delete_branch_on_merge ?? false,\n allow_forking: true,\n is_template: false,\n license,\n } as Omit<GitHubRepo, \"id\" | \"created_at\" | \"updated_at\">);\n\n gh.repos.update(repo.id, { node_id: generateNodeId(\"Repository\", repo.id) });\n\n if (!isPrivate) {\n bumpPublicRepos(gh, params.owner_id, params.owner_type, 1);\n }\n\n const updated = gh.repos.get(repo.id)!;\n if (params.auto_init) {\n seedInitialGit(gh, updated, actor);\n }\n\n return gh.repos.get(repo.id)!;\n}\n\nfunction deleteRepoCascade(gh: GitHubStore, repo: GitHubRepo) {\n const repoId = repo.id;\n const wasPublic = !repo.private;\n\n const delByRepo = <T extends Entity>(col: Collection<T>) => {\n for (const item of col.findBy(\"repo_id\" as keyof T, repoId as T[keyof T])) {\n col.delete(item.id);\n }\n };\n\n delByRepo(gh.collaborators);\n delByRepo(gh.issues);\n delByRepo(gh.pullRequests);\n delByRepo(gh.labels);\n delByRepo(gh.milestones);\n delByRepo(gh.comments);\n delByRepo(gh.reviews);\n delByRepo(gh.issueEvents);\n delByRepo(gh.branches);\n delByRepo(gh.branchProtections);\n delByRepo(gh.refs);\n delByRepo(gh.commits);\n delByRepo(gh.trees);\n delByRepo(gh.blobs);\n delByRepo(gh.tags);\n\n for (const rel of gh.releases.findBy(\"repo_id\", repoId)) {\n for (const a of gh.releaseAssets.findBy(\"release_id\", rel.id)) {\n gh.releaseAssets.delete(a.id);\n }\n gh.releases.delete(rel.id);\n }\n\n delByRepo(gh.webhooks);\n delByRepo(gh.workflows);\n for (const run of gh.workflowRuns.findBy(\"repo_id\", repoId)) {\n for (const j of gh.jobs.findBy(\"run_id\", run.id)) {\n gh.jobs.delete(j.id);\n }\n for (const a of gh.artifacts.findBy(\"run_id\", run.id)) {\n gh.artifacts.delete(a.id);\n }\n gh.workflowRuns.delete(run.id);\n }\n\n delByRepo(gh.secrets);\n delByRepo(gh.checkRuns);\n delByRepo(gh.checkSuites);\n\n gh.repos.delete(repoId);\n\n if (wasPublic) {\n bumpPublicRepos(gh, repo.owner_id, repo.owner_type, -1);\n }\n\n if (repo.forked_from_id) {\n const parent = gh.repos.get(repo.forked_from_id);\n if (parent && parent.forks_count > 0) {\n gh.repos.update(parent.id, { forks_count: parent.forks_count - 1 });\n }\n }\n}\n\nfunction formatTagItem(tag: GitHubTag, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n name: tag.tag,\n zipball_url: `${repoUrl}/zipball/${encodeURIComponent(tag.tag)}`,\n tarball_url: `${repoUrl}/tarball/${encodeURIComponent(tag.tag)}`,\n commit: {\n sha: tag.sha,\n url: `${repoUrl}/commits/${tag.sha}`,\n },\n node_id: tag.node_id,\n };\n}\n\nfunction parsePermission(raw: unknown): \"pull\" | \"triage\" | \"push\" | \"maintain\" | \"admin\" | undefined {\n if (raw === undefined) return undefined;\n if (raw === \"pull\" || raw === \"triage\" || raw === \"push\" || raw === \"maintain\" || raw === \"admin\") {\n return raw;\n }\n return undefined;\n}\n\nexport function reposRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n return c.json(formatRepo(repo, gh, baseUrl));\n });\n\n app.post(\"/user/repos\", async (c) => {\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n const body = await parseJsonBody(c);\n\n const finalRepo = createRepoRecord(\n gh,\n {\n name: body.name,\n description: typeof body.description === \"string\" ? body.description : null,\n private: typeof body.private === \"boolean\" ? body.private : false,\n homepage: typeof body.homepage === \"string\" ? body.homepage : null,\n has_issues: typeof body.has_issues === \"boolean\" ? body.has_issues : true,\n has_projects: typeof body.has_projects === \"boolean\" ? body.has_projects : true,\n has_wiki: typeof body.has_wiki === \"boolean\" ? body.has_wiki : true,\n auto_init: body.auto_init === true,\n license_template: typeof body.license_template === \"string\" ? body.license_template : undefined,\n gitignore_template: typeof body.gitignore_template === \"string\" ? body.gitignore_template : undefined,\n owner_id: user.id,\n owner_type: \"User\",\n owner_login: user.login,\n default_branch: \"main\",\n baseUrl,\n allow_rebase_merge: typeof body.allow_rebase_merge === \"boolean\" ? body.allow_rebase_merge : undefined,\n allow_squash_merge: typeof body.allow_squash_merge === \"boolean\" ? body.allow_squash_merge : undefined,\n allow_merge_commit: typeof body.allow_merge_commit === \"boolean\" ? body.allow_merge_commit : undefined,\n delete_branch_on_merge:\n typeof body.delete_branch_on_merge === \"boolean\" ? body.delete_branch_on_merge : undefined,\n },\n user,\n );\n\n webhooks.dispatch(\n \"repository\",\n \"created\",\n { action: \"created\", repository: formatRepo(finalRepo, gh, baseUrl), sender: formatUser(user, baseUrl) },\n user.login,\n finalRepo.name,\n );\n\n return c.json(formatRepo(finalRepo, gh, baseUrl), 201);\n });\n\n app.post(\"/orgs/:org/repos\", async (c) => {\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n const orgLogin = c.req.param(\"org\")!;\n const org = gh.orgs.findOneBy(\"login\", orgLogin);\n if (!org) throw notFoundResponse();\n\n if (!isOrgMember(gh, user.id, org.id)) {\n throw forbidden();\n }\n\n const body = await parseJsonBody(c);\n\n const finalRepo = createRepoRecord(\n gh,\n {\n name: body.name,\n description: typeof body.description === \"string\" ? body.description : null,\n private: typeof body.private === \"boolean\" ? body.private : false,\n homepage: typeof body.homepage === \"string\" ? body.homepage : null,\n has_issues: typeof body.has_issues === \"boolean\" ? body.has_issues : true,\n has_projects: typeof body.has_projects === \"boolean\" ? body.has_projects : true,\n has_wiki: typeof body.has_wiki === \"boolean\" ? body.has_wiki : true,\n auto_init: body.auto_init === true,\n license_template: typeof body.license_template === \"string\" ? body.license_template : undefined,\n gitignore_template: typeof body.gitignore_template === \"string\" ? body.gitignore_template : undefined,\n owner_id: org.id,\n owner_type: \"Organization\",\n owner_login: org.login,\n default_branch: \"main\",\n baseUrl,\n allow_rebase_merge: typeof body.allow_rebase_merge === \"boolean\" ? body.allow_rebase_merge : undefined,\n allow_squash_merge: typeof body.allow_squash_merge === \"boolean\" ? body.allow_squash_merge : undefined,\n allow_merge_commit: typeof body.allow_merge_commit === \"boolean\" ? body.allow_merge_commit : undefined,\n delete_branch_on_merge:\n typeof body.delete_branch_on_merge === \"boolean\" ? body.delete_branch_on_merge : undefined,\n },\n user,\n );\n\n webhooks.dispatch(\n \"repository\",\n \"created\",\n { action: \"created\", repository: formatRepo(finalRepo, gh, baseUrl), sender: formatUser(user, baseUrl) },\n org.login,\n finalRepo.name,\n );\n\n return c.json(formatRepo(finalRepo, gh, baseUrl), 201);\n });\n\n app.patch(\"/repos/:owner/:repo\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, user, repo)) throw forbidden();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubRepo> = {};\n\n if (typeof body.name === \"string\") {\n const newName = validateRepoName(body.name);\n const login = ownerLoginOf(gh, repo);\n const newFull = `${login}/${newName}`;\n if (newFull !== repo.full_name && gh.repos.findOneBy(\"full_name\", newFull)) {\n throw new ApiError(422, \"Repository already exists\");\n }\n patch.name = newName;\n patch.full_name = newFull;\n }\n\n if (\"description\" in body) {\n patch.description = body.description === null ? null : String(body.description);\n }\n if (\"homepage\" in body && (typeof body.homepage === \"string\" || body.homepage === null)) {\n patch.homepage = body.homepage;\n }\n if (typeof body.private === \"boolean\") {\n patch.private = body.private;\n patch.visibility = body.private ? \"private\" : \"public\";\n }\n if (typeof body.has_issues === \"boolean\") patch.has_issues = body.has_issues;\n if (typeof body.has_projects === \"boolean\") patch.has_projects = body.has_projects;\n if (typeof body.has_wiki === \"boolean\") patch.has_wiki = body.has_wiki;\n if (typeof body.has_pages === \"boolean\") patch.has_pages = body.has_pages;\n if (typeof body.has_downloads === \"boolean\") patch.has_downloads = body.has_downloads;\n if (typeof body.has_discussions === \"boolean\") patch.has_discussions = body.has_discussions;\n if (typeof body.archived === \"boolean\") patch.archived = body.archived;\n if (typeof body.disabled === \"boolean\") patch.disabled = body.disabled;\n if (typeof body.default_branch === \"string\") patch.default_branch = body.default_branch;\n\n if (Array.isArray(body.topics)) {\n patch.topics = body.topics.filter((t): t is string => typeof t === \"string\");\n }\n\n if (typeof body.visibility === \"string\") {\n const v = body.visibility;\n if (v === \"public\" || v === \"private\" || v === \"internal\") {\n patch.visibility = v;\n patch.private = v !== \"public\";\n }\n }\n\n if (\"license\" in body) {\n if (body.license === null) patch.license = null;\n else if (typeof body.license === \"object\" && body.license !== null) {\n const L = body.license as Record<string, unknown>;\n if (typeof L.key === \"string\" && typeof L.name === \"string\" && typeof L.spdx_id === \"string\") {\n patch.license = { key: L.key, name: L.name, spdx_id: L.spdx_id };\n }\n }\n }\n\n if (typeof body.allow_rebase_merge === \"boolean\") patch.allow_rebase_merge = body.allow_rebase_merge;\n if (typeof body.allow_squash_merge === \"boolean\") patch.allow_squash_merge = body.allow_squash_merge;\n if (typeof body.allow_merge_commit === \"boolean\") patch.allow_merge_commit = body.allow_merge_commit;\n if (typeof body.allow_auto_merge === \"boolean\") patch.allow_auto_merge = body.allow_auto_merge;\n if (typeof body.delete_branch_on_merge === \"boolean\") {\n patch.delete_branch_on_merge = body.delete_branch_on_merge;\n }\n if (typeof body.allow_forking === \"boolean\") patch.allow_forking = body.allow_forking;\n if (typeof body.is_template === \"boolean\") patch.is_template = body.is_template;\n\n const oldPrivate = repo.private;\n const updated = gh.repos.update(repo.id, patch);\n if (!updated) throw notFoundResponse();\n\n if (oldPrivate !== updated.private) {\n const delta = updated.private ? -1 : 1;\n bumpPublicRepos(gh, updated.owner_id, updated.owner_type, delta);\n }\n\n webhooks.dispatch(\n \"repository\",\n \"edited\",\n { action: \"edited\", repository: formatRepo(updated, gh, baseUrl), sender: formatUser(user, baseUrl) },\n ownerLoginOf(gh, updated),\n updated.name,\n );\n\n return c.json(formatRepo(updated, gh, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, user, repo)) throw forbidden();\n\n webhooks.dispatch(\n \"repository\",\n \"deleted\",\n { action: \"deleted\", repository: formatRepo(repo, gh, baseUrl), sender: formatUser(user, baseUrl) },\n owner,\n repoName,\n );\n\n deleteRepoCascade(gh, repo);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/topics\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n return c.json({ names: repo.topics });\n });\n\n app.put(\"/repos/:owner/:repo/topics\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, user, repo)) throw forbidden();\n\n const body = (await parseJsonBody(c)) as { names?: unknown };\n const names = Array.isArray(body.names) ? body.names.filter((n): n is string => typeof n === \"string\") : [];\n const updated = gh.repos.update(repo.id, { topics: names });\n if (!updated) throw notFoundResponse();\n return c.json({ names: updated.topics });\n });\n\n app.get(\"/repos/:owner/:repo/languages\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n return c.json(repo.languages);\n });\n\n app.get(\"/repos/:owner/:repo/contributors\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const collabUsers = gh.collaborators\n .findBy(\"repo_id\", repo.id)\n .map((col) => gh.users.get(col.user_id))\n .filter((u): u is GitHubUser => Boolean(u));\n\n const ownerUser = repo.owner_type === \"User\" ? gh.users.get(repo.owner_id) : undefined;\n\n const map = new Map<number, GitHubUser>();\n if (ownerUser) map.set(ownerUser.id, ownerUser);\n for (const u of collabUsers) map.set(u.id, u);\n\n const all = [...map.values()].sort((a, b) => a.login.localeCompare(b.login));\n const { page, per_page } = parsePagination(c);\n const total = all.length;\n const start = (page - 1) * per_page;\n const slice = all.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(\n slice.map((u) => ({\n ...formatUser(u, baseUrl),\n contributions: 1,\n })),\n );\n });\n\n app.get(\"/repos/:owner/:repo/forks\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const forks = gh.repos\n .all()\n .filter((r) => r.forked_from_id === repo.id)\n .sort((a, b) => (a.created_at < b.created_at ? 1 : -1));\n\n const { page, per_page } = parsePagination(c);\n const total = forks.length;\n const start = (page - 1) * per_page;\n const slice = forks.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((r) => formatRepo(r, gh, baseUrl)));\n });\n\n app.post(\"/repos/:owner/:repo/forks\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const parent = lookupRepo(gh, owner, repoName);\n if (!parent) throw notFoundResponse();\n\n const authUser = c.get(\"authUser\");\n const user = assertAuthenticatedUser(gh, authUser);\n assertRepoRead(gh, authUser, parent);\n\n const body = (await parseJsonBody(c)) as {\n organization?: unknown;\n name?: unknown;\n };\n\n let ownerType: \"User\" | \"Organization\" = \"User\";\n let ownerId = user.id;\n let fullName = \"\";\n const forkName = typeof body.name === \"string\" && body.name.trim() ? validateRepoName(body.name) : parent.name;\n\n if (typeof body.organization === \"string\" && body.organization.trim()) {\n const org = gh.orgs.findOneBy(\"login\", body.organization.trim());\n if (!org) throw notFoundResponse();\n if (!isOrgMember(gh, user.id, org.id)) throw forbidden();\n ownerType = \"Organization\";\n ownerId = org.id;\n fullName = `${org.login}/${forkName}`;\n } else {\n fullName = `${user.login}/${forkName}`;\n }\n\n if (gh.repos.findOneBy(\"full_name\", fullName)) {\n throw new ApiError(422, \"Repository already exists\");\n }\n\n const isPrivate = parent.private;\n const visibility = isPrivate ? \"private\" : \"public\";\n\n const repo = gh.repos.insert({\n node_id: \"\",\n name: forkName,\n full_name: fullName,\n owner_id: ownerId,\n owner_type: ownerType,\n private: isPrivate,\n description: parent.description,\n fork: true,\n forked_from_id: parent.id,\n homepage: parent.homepage,\n language: parent.language,\n languages: { ...parent.languages },\n forks_count: 0,\n stargazers_count: 0,\n watchers_count: 0,\n size: parent.size,\n default_branch: parent.default_branch,\n open_issues_count: 0,\n topics: [...parent.topics],\n has_issues: parent.has_issues,\n has_projects: parent.has_projects,\n has_wiki: parent.has_wiki,\n has_pages: parent.has_pages,\n has_downloads: parent.has_downloads,\n has_discussions: parent.has_discussions,\n archived: false,\n disabled: false,\n visibility: visibility as GitHubRepo[\"visibility\"],\n pushed_at: parent.pushed_at,\n allow_rebase_merge: parent.allow_rebase_merge,\n allow_squash_merge: parent.allow_squash_merge,\n allow_merge_commit: parent.allow_merge_commit,\n allow_auto_merge: parent.allow_auto_merge,\n delete_branch_on_merge: parent.delete_branch_on_merge,\n allow_forking: parent.allow_forking,\n is_template: false,\n license: parent.license,\n } as Omit<GitHubRepo, \"id\" | \"created_at\" | \"updated_at\">);\n\n gh.repos.update(repo.id, { node_id: generateNodeId(\"Repository\", repo.id) });\n\n if (!isPrivate) {\n bumpPublicRepos(gh, ownerId, ownerType, 1);\n }\n\n gh.repos.update(parent.id, { forks_count: parent.forks_count + 1 });\n\n seedInitialGit(gh, gh.repos.get(repo.id)!, user, parent.full_name);\n\n const finalRepo = gh.repos.get(repo.id)!;\n const ownerLogin = ownerLoginOf(gh, finalRepo);\n webhooks.dispatch(\n \"fork\",\n \"created\",\n { action: \"created\", repository: formatRepo(finalRepo, gh, baseUrl), sender: formatUser(user, baseUrl) },\n ownerLogin,\n finalRepo.name,\n );\n\n return c.json(formatRepo(finalRepo, gh, baseUrl), 202);\n });\n\n app.get(\"/repos/:owner/:repo/collaborators\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const collabs = gh.collaborators.findBy(\"repo_id\", repo.id);\n const users = collabs\n .map((col) => {\n const u = gh.users.get(col.user_id);\n if (!u) return null;\n return { user: u, permission: col.permission };\n })\n .filter((x): x is { user: GitHubUser; permission: GitHubCollaborator[\"permission\"] } => Boolean(x))\n .sort((a, b) => a.user.login.localeCompare(b.user.login));\n\n const { page, per_page } = parsePagination(c);\n const total = users.length;\n const start = (page - 1) * per_page;\n const slice = users.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((x) => formatUser(x.user, baseUrl)));\n });\n\n app.put(\"/repos/:owner/:repo/collaborators/:username\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const username = c.req.param(\"username\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const authUser = c.get(\"authUser\");\n const actor = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, actor, repo)) throw forbidden();\n\n const target = gh.users.findOneBy(\"login\", username);\n if (!target) throw notFoundResponse();\n\n const body = (await parseJsonBody(c)) as { permission?: unknown };\n const permission = parsePermission(body.permission) ?? \"push\";\n\n const existing = gh.collaborators.findBy(\"repo_id\", repo.id).find((c) => c.user_id === target.id);\n if (existing) {\n gh.collaborators.update(existing.id, { permission });\n } else {\n gh.collaborators.insert({\n repo_id: repo.id,\n user_id: target.id,\n permission,\n } as Omit<GitHubCollaborator, \"id\" | \"created_at\" | \"updated_at\">);\n }\n\n return c.json({ permission }, 201);\n });\n\n app.delete(\"/repos/:owner/:repo/collaborators/:username\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const username = c.req.param(\"username\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const authUser = c.get(\"authUser\");\n const actor = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, actor, repo)) throw forbidden();\n\n const target = gh.users.findOneBy(\"login\", username);\n if (!target) throw notFoundResponse();\n\n const existing = gh.collaborators.findBy(\"repo_id\", repo.id).find((col) => col.user_id === target.id);\n if (existing) {\n gh.collaborators.delete(existing.id);\n }\n\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/collaborators/:username/permission\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const username = c.req.param(\"username\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const target = gh.users.findOneBy(\"login\", username);\n if (!target) throw notFoundResponse();\n\n if (repo.owner_type === \"User\" && repo.owner_id === target.id) {\n return c.json({\n permission: \"admin\",\n role_name: \"admin\",\n user: formatUser(target, baseUrl),\n });\n }\n\n if (repo.owner_type === \"Organization\" && isOrgMember(gh, target.id, repo.owner_id)) {\n return c.json({\n permission: \"admin\",\n role_name: \"admin\",\n user: formatUser(target, baseUrl),\n });\n }\n\n const collab = gh.collaborators.findBy(\"repo_id\", repo.id).find((col) => col.user_id === target.id);\n if (!collab) throw notFoundResponse();\n\n const roleName =\n collab.permission === \"admin\"\n ? \"admin\"\n : collab.permission === \"maintain\"\n ? \"maintain\"\n : collab.permission === \"push\"\n ? \"write\"\n : collab.permission === \"triage\"\n ? \"triage\"\n : \"read\";\n\n return c.json({\n permission: collab.permission,\n role_name: roleName,\n user: formatUser(target, baseUrl),\n });\n });\n\n app.post(\"/repos/:owner/:repo/transfer\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const authUser = c.get(\"authUser\");\n const actor = assertAuthenticatedUser(gh, authUser);\n if (!hasRepoAdmin(gh, actor, repo)) throw forbidden();\n\n const body = (await parseJsonBody(c)) as { new_owner?: unknown };\n if (typeof body.new_owner !== \"string\" || !body.new_owner.trim()) {\n throw new ApiError(422, \"new_owner is required\");\n }\n\n const newOwner = lookupOwner(gh, body.new_owner.trim());\n if (!newOwner) throw notFoundResponse();\n\n const newFull = `${newOwner.login}/${repo.name}`;\n if (newFull !== repo.full_name && gh.repos.findOneBy(\"full_name\", newFull)) {\n throw new ApiError(422, \"Repository already exists\");\n }\n\n const updated = gh.repos.update(repo.id, {\n owner_id: newOwner.id,\n owner_type: newOwner.type === \"User\" ? \"User\" : \"Organization\",\n full_name: newFull,\n });\n if (!updated) throw notFoundResponse();\n\n webhooks.dispatch(\n \"repository\",\n \"transferred\",\n { action: \"transferred\", repository: formatRepo(updated, gh, baseUrl), sender: formatUser(actor, baseUrl) },\n newOwner.login,\n updated.name,\n );\n\n return c.json(formatRepo(updated, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/tags\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const tags = [...gh.tags.findBy(\"repo_id\", repo.id)].sort((a, b) => a.tag.localeCompare(b.tag));\n\n const { page, per_page } = parsePagination(c);\n const total = tags.length;\n const start = (page - 1) * per_page;\n const slice = tags.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((t) => formatTagItem(t, repo, baseUrl)));\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport { assertIssueWrite, assertRepoRead, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubIssue, GitHubIssueEvent, GitHubLabel, GitHubRepo, GitHubUser } from \"../entities.js\";\nimport {\n formatIssue,\n formatRepo,\n formatUser,\n generateNodeId,\n getNextIssueNumber,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\n\nfunction findIssueForRepo(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined {\n return gh.issues.findBy(\"repo_id\", repoId).find((i) => i.number === issueNumber && !i.is_pull_request);\n}\n\nfunction adjustRepoOpenIssues(gh: GitHubStore, repoId: number, delta: number) {\n const repo = gh.repos.get(repoId);\n if (!repo) return;\n gh.repos.update(repoId, { open_issues_count: Math.max(0, repo.open_issues_count + delta) });\n}\n\nfunction getOrCreateLabel(gh: GitHubStore, repo: GitHubRepo, name: string): GitHubLabel {\n const existing = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (existing) return existing;\n const label = gh.labels.insert({\n node_id: \"\",\n repo_id: repo.id,\n name,\n description: null,\n color: \"ededed\",\n default: false,\n } as Omit<GitHubLabel, \"id\" | \"created_at\" | \"updated_at\">);\n gh.labels.update(label.id, { node_id: generateNodeId(\"Label\", label.id) });\n return gh.labels.get(label.id)!;\n}\n\nfunction resolveLabelIds(gh: GitHubStore, repo: GitHubRepo, raw: unknown, createMissing: boolean): number[] {\n if (raw === undefined) return [];\n if (!Array.isArray(raw)) {\n throw new ApiError(422, \"Validation failed\");\n }\n const ids: number[] = [];\n for (const item of raw) {\n if (typeof item === \"number\" && Number.isFinite(item)) {\n const label = gh.labels.get(item);\n if (!label || label.repo_id !== repo.id) {\n throw new ApiError(422, \"Validation failed\");\n }\n ids.push(item);\n } else if (typeof item === \"string\") {\n if (createMissing) {\n ids.push(getOrCreateLabel(gh, repo, item).id);\n } else {\n const label = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === item);\n if (!label) throw new ApiError(422, \"Validation failed\");\n ids.push(label.id);\n }\n } else {\n throw new ApiError(422, \"Validation failed\");\n }\n }\n return [...new Set(ids)];\n}\n\nfunction lookupUserByLogin(gh: GitHubStore, login: string): GitHubUser {\n const u = gh.users.findOneBy(\"login\", login);\n if (!u) throw new ApiError(422, \"Validation failed\");\n return u;\n}\n\nfunction insertIssueEvent(\n gh: GitHubStore,\n repo: GitHubRepo,\n issueNumber: number,\n event: string,\n actorId: number,\n extra?: Partial<\n Pick<GitHubIssueEvent, \"commit_id\" | \"commit_url\" | \"label_name\" | \"assignee_id\" | \"milestone_title\" | \"rename\">\n >,\n): GitHubIssueEvent {\n const row = gh.issueEvents.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: issueNumber,\n event,\n actor_id: actorId,\n commit_id: null,\n commit_url: null,\n label_name: null,\n assignee_id: null,\n milestone_title: null,\n rename: null,\n ...extra,\n } as Omit<GitHubIssueEvent, \"id\" | \"created_at\" | \"updated_at\">);\n gh.issueEvents.update(row.id, { node_id: generateNodeId(\"IssueEvent\", row.id) });\n return gh.issueEvents.get(row.id)!;\n}\n\nfunction formatIssueEventApi(\n ev: GitHubIssueEvent,\n gh: GitHubStore,\n repo: GitHubRepo,\n issue: GitHubIssue,\n baseUrl: string,\n) {\n const actor = gh.users.get(ev.actor_id);\n const issueJson = formatIssue(issue, gh, baseUrl);\n return {\n id: ev.id,\n node_id: ev.node_id,\n url: `${baseUrl}/repos/${repo.full_name}/issues/events/${ev.id}`,\n actor: actor ? formatUser(actor, baseUrl) : null,\n event: ev.event,\n commit_id: ev.commit_id,\n commit_url: ev.commit_url,\n created_at: ev.created_at,\n label:\n ev.label_name !== null\n ? gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === ev.label_name)\n ? {\n name: ev.label_name,\n color: gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === ev.label_name)!.color,\n }\n : { name: ev.label_name, color: \"ededed\" }\n : null,\n assignee:\n ev.assignee_id !== null && gh.users.get(ev.assignee_id)\n ? formatUser(gh.users.get(ev.assignee_id)!, baseUrl)\n : null,\n milestone: null,\n rename: ev.rename,\n issue: issueJson,\n };\n}\n\nfunction sortIssues(\n issues: GitHubIssue[],\n sort: \"created\" | \"updated\" | \"comments\",\n direction: \"asc\" | \"desc\",\n): GitHubIssue[] {\n const mul = direction === \"asc\" ? 1 : -1;\n const field = sort === \"created\" ? \"created_at\" : sort === \"updated\" ? \"updated_at\" : \"comments\";\n const sorted = [...issues];\n sorted.sort((a, b) => {\n const av = a[field];\n const bv = b[field];\n if (typeof av === \"number\" && typeof bv === \"number\") {\n return av < bv ? -1 * mul : av > bv ? 1 * mul : 0;\n }\n const as = String(av);\n const bs = String(bv);\n if (as < bs) return -1 * mul;\n if (as > bs) return 1 * mul;\n return 0;\n });\n return sorted;\n}\n\nfunction parseIssueListFilters(c: Context) {\n const stateQ = c.req.query(\"state\") ?? \"open\";\n const state: \"open\" | \"closed\" | \"all\" =\n stateQ === \"closed\" || stateQ === \"all\" || stateQ === \"open\" ? stateQ : \"open\";\n\n const labelsParam = c.req.query(\"labels\");\n const labelNames = labelsParam\n ? labelsParam\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean)\n : [];\n\n const sortRaw = c.req.query(\"sort\") ?? \"created\";\n const sort: \"created\" | \"updated\" | \"comments\" =\n sortRaw === \"updated\" || sortRaw === \"comments\" ? sortRaw : \"created\";\n\n const dirRaw = c.req.query(\"direction\") ?? \"desc\";\n const direction: \"asc\" | \"desc\" = dirRaw === \"asc\" ? \"asc\" : \"desc\";\n\n const milestoneQ = c.req.query(\"milestone\");\n const assigneeQ = c.req.query(\"assignee\");\n const creatorQ = c.req.query(\"creator\");\n const sinceQ = c.req.query(\"since\");\n\n return {\n state,\n labelNames,\n sort,\n direction,\n milestoneQ,\n assigneeQ,\n creatorQ,\n sinceQ,\n };\n}\n\nexport function issuesRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/issues\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { state, labelNames, sort, direction, milestoneQ, assigneeQ, creatorQ, sinceQ } = parseIssueListFilters(c);\n\n let list = gh.issues.findBy(\"repo_id\", repo.id).filter((i) => !i.is_pull_request);\n\n if (state === \"open\") list = list.filter((i) => i.state === \"open\");\n else if (state === \"closed\") list = list.filter((i) => i.state === \"closed\");\n\n if (labelNames.length > 0) {\n const labelIds = labelNames\n .map((name) => gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name)?.id)\n .filter((x): x is number => x !== undefined);\n if (labelIds.length !== labelNames.length) {\n return c.json([]);\n }\n list = list.filter((i) => labelIds.every((lid) => i.label_ids.includes(lid)));\n }\n\n if (milestoneQ !== undefined && milestoneQ !== \"\") {\n if (milestoneQ === \"none\") {\n list = list.filter((i) => i.milestone_id === null);\n } else if (milestoneQ === \"*\") {\n list = list.filter((i) => i.milestone_id !== null);\n } else {\n const n = parseInt(milestoneQ, 10);\n if (!Number.isFinite(n)) {\n list = [];\n } else {\n const ms = gh.milestones.findBy(\"repo_id\", repo.id).find((m) => m.number === n);\n if (!ms) list = [];\n else list = list.filter((i) => i.milestone_id === ms.id);\n }\n }\n }\n\n if (assigneeQ !== undefined && assigneeQ !== \"\") {\n if (assigneeQ === \"none\") {\n list = list.filter((i) => i.assignee_ids.length === 0);\n } else if (assigneeQ === \"*\") {\n list = list.filter((i) => i.assignee_ids.length > 0);\n } else {\n const u = gh.users.findOneBy(\"login\", assigneeQ);\n if (!u) list = [];\n else list = list.filter((i) => i.assignee_ids.includes(u.id));\n }\n }\n\n if (creatorQ !== undefined && creatorQ !== \"\") {\n const u = gh.users.findOneBy(\"login\", creatorQ);\n if (!u) list = [];\n else list = list.filter((i) => i.user_id === u.id);\n }\n\n if (sinceQ) {\n list = list.filter((i) => i.updated_at >= sinceQ);\n }\n\n list = sortIssues(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((i) => formatIssue(i, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/issues\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n\n const title = body.title;\n if (typeof title !== \"string\" || !title.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const issueBody = typeof body.body === \"string\" || body.body === null ? (body.body as string | null) : null;\n\n const assigneeLogins = Array.isArray(body.assignees)\n ? body.assignees.filter((x): x is string => typeof x === \"string\")\n : [];\n const assigneeIds = assigneeLogins.map((login) => lookupUserByLogin(gh, login).id);\n\n const labelIds = body.labels !== undefined ? resolveLabelIds(gh, repo, body.labels, true) : [];\n\n let milestoneId: number | null = null;\n if (body.milestone !== undefined && body.milestone !== null) {\n const mn = typeof body.milestone === \"number\" ? body.milestone : parseInt(String(body.milestone), 10);\n if (!Number.isFinite(mn)) throw new ApiError(422, \"Validation failed\");\n const ms = gh.milestones.findBy(\"repo_id\", repo.id).find((m) => m.number === mn);\n if (!ms) throw new ApiError(422, \"Validation failed\");\n milestoneId = ms.id;\n }\n\n const num = getNextIssueNumber(gh, repo.id);\n const row = gh.issues.insert({\n node_id: \"\",\n number: num,\n repo_id: repo.id,\n title: title.trim(),\n body: issueBody,\n state: \"open\",\n state_reason: null,\n locked: false,\n active_lock_reason: null,\n user_id: actor.id,\n assignee_ids: assigneeIds,\n label_ids: labelIds,\n milestone_id: milestoneId,\n comments: 0,\n closed_at: null,\n closed_by_id: null,\n is_pull_request: false,\n } as Omit<GitHubIssue, \"id\" | \"created_at\" | \"updated_at\">);\n gh.issues.update(row.id, { node_id: generateNodeId(\"Issue\", row.id) });\n const issue = gh.issues.get(row.id)!;\n\n adjustRepoOpenIssues(gh, repo.id, 1);\n\n insertIssueEvent(gh, repo, issue.number, \"opened\", actor.id);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n const issueFmt = formatIssue(issue, gh, baseUrl)!;\n webhooks.dispatch(\n \"issues\",\n \"opened\",\n {\n action: \"opened\",\n issue: issueFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(issueFmt, 201);\n });\n\n app.get(\"/repos/:owner/:repo/issues/:issue_number\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const json = formatIssue(issue, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.patch(\"/repos/:owner/:repo/issues/:issue_number\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n let issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const beforePatch = issue;\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubIssue> = {};\n\n if (typeof body.title === \"string\") patch.title = body.title;\n if (\"body\" in body) {\n patch.body = body.body === null ? null : String(body.body);\n }\n\n const oldState = issue.state;\n if (body.state === \"open\" || body.state === \"closed\") {\n patch.state = body.state;\n }\n\n if (\"state_reason\" in body) {\n if (body.state_reason === null) {\n patch.state_reason = null;\n } else if (\n body.state_reason === \"completed\" ||\n body.state_reason === \"not_planned\" ||\n body.state_reason === \"reopened\"\n ) {\n patch.state_reason = body.state_reason;\n }\n }\n\n if (Array.isArray(body.labels)) {\n patch.label_ids = resolveLabelIds(gh, repo, body.labels, true);\n }\n\n if (Array.isArray(body.assignees)) {\n const logins = body.assignees.filter((x): x is string => typeof x === \"string\");\n patch.assignee_ids = logins.map((login) => lookupUserByLogin(gh, login).id);\n }\n\n if (\"milestone\" in body) {\n if (body.milestone === null) {\n patch.milestone_id = null;\n } else {\n const mn = typeof body.milestone === \"number\" ? body.milestone : parseInt(String(body.milestone), 10);\n if (!Number.isFinite(mn)) throw new ApiError(422, \"Validation failed\");\n const ms = gh.milestones.findBy(\"repo_id\", repo.id).find((m) => m.number === mn);\n if (!ms) throw new ApiError(422, \"Validation failed\");\n patch.milestone_id = ms.id;\n }\n }\n\n const prevLabelIds = new Set(issue.label_ids);\n const prevAssigneeIds = new Set(issue.assignee_ids);\n const prevMilestoneId = issue.milestone_id;\n\n const updated = gh.issues.update(issue.id, patch);\n if (!updated) throw notFoundResponse();\n issue = updated;\n\n let statePatch: Partial<GitHubIssue> = {};\n if (patch.state === \"closed\" && oldState === \"open\") {\n statePatch = {\n closed_at: timestamp(),\n closed_by_id: actor.id,\n ...(patch.state_reason === undefined ? { state_reason: \"completed\" as const } : {}),\n };\n } else if (patch.state === \"open\" && oldState === \"closed\") {\n statePatch = {\n closed_at: null,\n closed_by_id: null,\n ...(patch.state_reason === undefined ? { state_reason: \"reopened\" as const } : {}),\n };\n } else if (patch.state === \"closed\" && oldState === \"closed\") {\n if (patch.state_reason !== undefined) statePatch.state_reason = patch.state_reason;\n }\n\n if (Object.keys(statePatch).length > 0) {\n const again = gh.issues.update(issue.id, statePatch);\n if (again) issue = again;\n }\n\n const ownerLogin = ownerLoginOf(gh, repo);\n\n if (patch.state === \"closed\" && oldState === \"open\") {\n adjustRepoOpenIssues(gh, repo.id, -1);\n insertIssueEvent(gh, repo, issue.number, \"closed\", actor.id);\n webhooks.dispatch(\n \"issues\",\n \"closed\",\n {\n action: \"closed\",\n issue: formatIssue(issue, gh, baseUrl)!,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n } else if (patch.state === \"open\" && oldState === \"closed\") {\n adjustRepoOpenIssues(gh, repo.id, 1);\n insertIssueEvent(gh, repo, issue.number, \"reopened\", actor.id);\n webhooks.dispatch(\n \"issues\",\n \"reopened\",\n {\n action: \"reopened\",\n issue: formatIssue(issue, gh, baseUrl)!,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n\n if (Array.isArray(body.labels)) {\n const newIds = new Set(issue.label_ids);\n for (const id of prevLabelIds) {\n if (!newIds.has(id)) {\n const label = gh.labels.get(id);\n insertIssueEvent(gh, repo, issue.number, \"unlabeled\", actor.id, {\n label_name: label?.name ?? null,\n });\n webhooks.dispatch(\n \"issues\",\n \"unlabeled\",\n {\n action: \"unlabeled\",\n issue: formatIssue(issue, gh, baseUrl)!,\n label: label ? { name: label.name, color: label.color } : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n for (const id of newIds) {\n if (!prevLabelIds.has(id)) {\n const label = gh.labels.get(id);\n if (label) {\n insertIssueEvent(gh, repo, issue.number, \"labeled\", actor.id, { label_name: label.name });\n webhooks.dispatch(\n \"issues\",\n \"labeled\",\n {\n action: \"labeled\",\n issue: formatIssue(issue, gh, baseUrl)!,\n label: { name: label.name, color: label.color },\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n }\n }\n\n if (Array.isArray(body.assignees)) {\n const newAssignees = new Set(issue.assignee_ids);\n for (const id of prevAssigneeIds) {\n if (!newAssignees.has(id)) {\n insertIssueEvent(gh, repo, issue.number, \"unassigned\", actor.id, { assignee_id: id });\n const u = gh.users.get(id);\n webhooks.dispatch(\n \"issues\",\n \"unassigned\",\n {\n action: \"unassigned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n assignee: u ? formatUser(u, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n for (const id of newAssignees) {\n if (!prevAssigneeIds.has(id)) {\n insertIssueEvent(gh, repo, issue.number, \"assigned\", actor.id, { assignee_id: id });\n const u = gh.users.get(id);\n webhooks.dispatch(\n \"issues\",\n \"assigned\",\n {\n action: \"assigned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n assignee: u ? formatUser(u, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n }\n\n if (\"milestone\" in body) {\n const newMs = issue.milestone_id;\n if (prevMilestoneId !== newMs) {\n const oldTitle = prevMilestoneId ? (gh.milestones.get(prevMilestoneId)?.title ?? null) : null;\n const newTitle = newMs ? (gh.milestones.get(newMs)?.title ?? null) : null;\n if (prevMilestoneId !== null) {\n insertIssueEvent(gh, repo, issue.number, \"demilestoned\", actor.id, {\n milestone_title: oldTitle,\n });\n webhooks.dispatch(\n \"issues\",\n \"demilestoned\",\n {\n action: \"demilestoned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n milestone: oldTitle ? { title: oldTitle } : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n if (newMs !== null) {\n insertIssueEvent(gh, repo, issue.number, \"milestoned\", actor.id, {\n milestone_title: newTitle,\n });\n webhooks.dispatch(\n \"issues\",\n \"milestoned\",\n {\n action: \"milestoned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n milestone: newTitle ? { title: newTitle } : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n }\n\n const titleEdited = typeof body.title === \"string\" && body.title !== beforePatch.title;\n const bodyEdited =\n \"body\" in body &&\n (body.body === null ? beforePatch.body !== null : String(body.body) !== (beforePatch.body ?? \"\"));\n if (titleEdited || bodyEdited) {\n insertIssueEvent(gh, repo, issue.number, \"edited\", actor.id);\n webhooks.dispatch(\n \"issues\",\n \"edited\",\n {\n action: \"edited\",\n issue: formatIssue(issue, gh, baseUrl)!,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n changes: {\n title: titleEdited,\n body: bodyEdited,\n },\n },\n ownerLogin,\n repo.name,\n );\n }\n\n const json = formatIssue(issue, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.put(\"/repos/:owner/:repo/issues/:issue_number/lock\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n let issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const lockReason =\n typeof body.lock_reason === \"string\"\n ? body.lock_reason\n : typeof body.active_lock_reason === \"string\"\n ? body.active_lock_reason\n : \"resolved\";\n\n issue = gh.issues.update(issue.id, {\n locked: true,\n active_lock_reason: lockReason,\n })!;\n\n insertIssueEvent(gh, repo, issue.number, \"locked\", actor.id);\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"issues\",\n \"locked\",\n {\n action: \"locked\",\n issue: formatIssue(issue, gh, baseUrl)!,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n app.delete(\"/repos/:owner/:repo/issues/:issue_number/lock\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n let issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n issue = gh.issues.update(issue.id, { locked: false, active_lock_reason: null })!;\n\n insertIssueEvent(gh, repo, issue.number, \"unlocked\", actor.id);\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"issues\",\n \"unlocked\",\n {\n action: \"unlocked\",\n issue: formatIssue(issue, gh, baseUrl)!,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n function listIssueEventsForIssue(c: Context) {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n let events = gh.issueEvents.findBy(\"repo_id\", repo.id).filter((e) => e.issue_number === issueNumber);\n events.sort((a, b) => a.created_at.localeCompare(b.created_at));\n const total = events.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n events = events.slice(start, start + per_page);\n\n const payload = events.map((ev) => formatIssueEventApi(ev, gh, repo, issue, baseUrl));\n return c.json(payload);\n }\n\n app.get(\"/repos/:owner/:repo/issues/:issue_number/timeline\", (c) => listIssueEventsForIssue(c));\n app.get(\"/repos/:owner/:repo/issues/:issue_number/events\", (c) => listIssueEventsForIssue(c));\n\n app.post(\"/repos/:owner/:repo/issues/:issue_number/assignees\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n let issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const body = (await parseJsonBody(c)) as { assignees?: unknown };\n const logins = Array.isArray(body.assignees)\n ? body.assignees.filter((x): x is string => typeof x === \"string\")\n : [];\n const addIds = logins.map((login) => lookupUserByLogin(gh, login).id);\n const prevAssigneeSet = new Set(issue.assignee_ids);\n const merged = [...new Set([...issue.assignee_ids, ...addIds])];\n issue = gh.issues.update(issue.id, { assignee_ids: merged })!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n for (const id of addIds) {\n if (prevAssigneeSet.has(id)) continue;\n insertIssueEvent(gh, repo, issue.number, \"assigned\", actor.id, { assignee_id: id });\n const u = gh.users.get(id);\n webhooks.dispatch(\n \"issues\",\n \"assigned\",\n {\n action: \"assigned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n assignee: u ? formatUser(u, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n\n const json = formatIssue(issue, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.delete(\"/repos/:owner/:repo/issues/:issue_number/assignees\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n let issue = findIssueForRepo(gh, repo.id, issueNumber);\n if (!issue || issue.is_pull_request) throw notFoundResponse();\n\n const body = (await parseJsonBody(c)) as { assignees?: unknown };\n const logins = Array.isArray(body.assignees)\n ? body.assignees.filter((x): x is string => typeof x === \"string\")\n : [];\n const removeIds = new Set(logins.map((login) => lookupUserByLogin(gh, login).id));\n const prevAssignees = new Set(issue.assignee_ids);\n const merged = issue.assignee_ids.filter((id) => !removeIds.has(id));\n issue = gh.issues.update(issue.id, { assignee_ids: merged })!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n for (const id of removeIds) {\n if (prevAssignees.has(id)) {\n insertIssueEvent(gh, repo, issue.number, \"unassigned\", actor.id, { assignee_id: id });\n const u = gh.users.get(id);\n webhooks.dispatch(\n \"issues\",\n \"unassigned\",\n {\n action: \"unassigned\",\n issue: formatIssue(issue, gh, baseUrl)!,\n assignee: u ? formatUser(u, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n\n const json = formatIssue(issue, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport {\n assertAuthenticatedUser,\n assertRepoRead,\n assertRepoWrite,\n notFoundResponse,\n ownerLoginOf,\n} from \"../route-helpers.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubBranch,\n GitHubCommit,\n GitHubIssue,\n GitHubPullRequest,\n GitHubRef,\n GitHubRepo,\n GitHubUser,\n} from \"../entities.js\";\nimport {\n formatPullRequest,\n formatRepo,\n formatUser,\n generateNodeId,\n generateSha,\n getNextIssueNumber,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\n\nfunction findPull(gh: GitHubStore, repoId: number, pullNumber: number): GitHubPullRequest | undefined {\n return gh.pullRequests.findBy(\"repo_id\", repoId).find((p) => p.number === pullNumber);\n}\n\nfunction findPrIssue(gh: GitHubStore, repoId: number, number: number): GitHubIssue | undefined {\n return gh.issues.findBy(\"repo_id\", repoId).find((i) => i.number === number && i.is_pull_request);\n}\n\nfunction adjustRepoOpenIssues(gh: GitHubStore, repoId: number, delta: number) {\n const repo = gh.repos.get(repoId);\n if (!repo) return;\n gh.repos.update(repoId, { open_issues_count: Math.max(0, repo.open_issues_count + delta) });\n}\n\nfunction getDefaultBranchSha(gh: GitHubStore, repo: GitHubRepo): string {\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === repo.default_branch);\n if (!branch) {\n throw new ApiError(422, \"The repository is empty.\");\n }\n return branch.sha;\n}\n\nfunction createBranchAt(gh: GitHubStore, repo: GitHubRepo, branchName: string, sha: string): GitHubBranch {\n const b = gh.branches.insert({\n repo_id: repo.id,\n name: branchName,\n sha,\n protected: false,\n } as Omit<GitHubBranch, \"id\" | \"created_at\" | \"updated_at\">);\n const ref = gh.refs.insert({\n repo_id: repo.id,\n ref: `refs/heads/${branchName}`,\n sha,\n node_id: \"\",\n } as Omit<GitHubRef, \"id\" | \"created_at\" | \"updated_at\">);\n gh.refs.update(ref.id, { node_id: generateNodeId(\"Ref\", ref.id) });\n return b;\n}\n\nfunction getOrCreateBranch(gh: GitHubStore, repo: GitHubRepo, branchName: string): GitHubBranch {\n const existing = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === branchName);\n if (existing) return existing;\n const tip = getDefaultBranchSha(gh, repo);\n return createBranchAt(gh, repo, branchName, tip);\n}\n\nfunction updateBranchSha(gh: GitHubStore, repo: GitHubRepo, branchName: string, newSha: string) {\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === branchName);\n if (branch) gh.branches.update(branch.id, { sha: newSha });\n const ref = gh.refs.findBy(\"repo_id\", repo.id).find((r) => r.ref === `refs/heads/${branchName}`);\n if (ref) gh.refs.update(ref.id, { sha: newSha });\n}\n\nfunction resolveHeadTarget(\n gh: GitHubStore,\n baseRepo: GitHubRepo,\n head: string,\n): { headRepo: GitHubRepo; headRef: string } {\n const trimmed = head.trim();\n if (!trimmed.includes(\":\")) {\n return { headRepo: baseRepo, headRef: trimmed };\n }\n const idx = trimmed.indexOf(\":\");\n const ownerLogin = trimmed.slice(0, idx).trim();\n const ref = trimmed.slice(idx + 1).trim();\n if (!ref) throw new ApiError(422, \"Validation failed\");\n\n const baseOwner = ownerLoginOf(gh, baseRepo);\n if (ownerLogin === baseOwner) {\n return { headRepo: baseRepo, headRef: ref };\n }\n\n const fork = gh.repos.all().find((r) => {\n if (r.forked_from_id !== baseRepo.id) return false;\n const login = r.owner_type === \"User\" ? gh.users.get(r.owner_id)?.login : gh.orgs.get(r.owner_id)?.login;\n return login === ownerLogin;\n });\n if (!fork) throw new ApiError(422, \"Validation failed\");\n return { headRepo: fork, headRef: ref };\n}\n\nfunction countCommitsBetween(gh: GitHubStore, repo: GitHubRepo, headSha: string, baseSha: string): number {\n const chain = walkCommitsToBase(gh, repo, headSha, baseSha);\n return chain.length;\n}\n\nfunction walkCommitsToBase(gh: GitHubStore, repo: GitHubRepo, headSha: string, baseSha: string): GitHubCommit[] {\n const out: GitHubCommit[] = [];\n const seen = new Set<string>();\n let cur: string | undefined = headSha;\n while (cur && !seen.has(cur)) {\n seen.add(cur);\n const commit = gh.commits.findBy(\"repo_id\", repo.id).find((c) => c.sha === cur);\n if (!commit) break;\n out.push(commit);\n if (cur === baseSha) break;\n cur = commit.parent_shas[0];\n }\n return out.reverse();\n}\n\nfunction insertCommit(\n gh: GitHubStore,\n repo: GitHubRepo,\n opts: {\n treeSha: string;\n parentShas: string[];\n message: string;\n user: GitHubUser | null;\n },\n): GitHubCommit {\n const u = opts.user;\n const authorName = u?.name ?? u?.login ?? \"User\";\n const login = u?.login ?? \"user\";\n const email = u?.email ?? `${login}@users.noreply.github.com`;\n const now = timestamp();\n const row = gh.commits.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n message: opts.message,\n author_name: authorName,\n author_email: email,\n author_date: now,\n committer_name: authorName,\n committer_email: email,\n committer_date: now,\n tree_sha: opts.treeSha,\n parent_shas: opts.parentShas,\n user_id: u?.id ?? null,\n } as Omit<GitHubCommit, \"id\" | \"created_at\" | \"updated_at\">);\n gh.commits.update(row.id, { node_id: generateNodeId(\"Commit\", row.id) });\n return gh.commits.get(row.id)!;\n}\n\nfunction formatCommitApi(commit: GitHubCommit, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n sha: commit.sha,\n node_id: commit.node_id,\n url: `${repoUrl}/commits/${commit.sha}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${commit.sha}`,\n comments_url: `${repoUrl}/comments/${commit.sha}`,\n commit: {\n url: `${repoUrl}/git/commits/${commit.sha}`,\n author: {\n name: commit.author_name,\n email: commit.author_email,\n date: commit.author_date,\n },\n committer: {\n name: commit.committer_name,\n email: commit.committer_email,\n date: commit.committer_date,\n },\n message: commit.message,\n tree: { sha: commit.tree_sha },\n comment_count: 0,\n verification: {\n verified: false,\n reason: \"unsigned\",\n signature: null,\n payload: null,\n verified_at: null,\n },\n },\n author: null,\n committer: null,\n parents: commit.parent_shas.map((sha) => ({\n sha,\n url: `${repoUrl}/commits/${sha}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${sha}`,\n })),\n };\n}\n\nfunction headLabel(gh: GitHubStore, pr: GitHubPullRequest): string {\n const headRepo = gh.repos.get(pr.head_repo_id);\n const owner = headRepo\n ? headRepo.owner_type === \"User\"\n ? gh.users.get(headRepo.owner_id)?.login\n : gh.orgs.get(headRepo.owner_id)?.login\n : undefined;\n return `${owner ?? \"unknown\"}:${pr.head_ref}`;\n}\n\nfunction matchesHeadFilter(gh: GitHubStore, pr: GitHubPullRequest, headParam: string): boolean {\n const trimmed = headParam.trim();\n if (!trimmed) return true;\n if (!trimmed.includes(\":\")) {\n return pr.head_ref === trimmed;\n }\n return headLabel(gh, pr) === trimmed;\n}\n\nfunction sortPulls(\n list: GitHubPullRequest[],\n sort: \"created\" | \"updated\" | \"popularity\" | \"long-running\",\n direction: \"asc\" | \"desc\",\n): GitHubPullRequest[] {\n const sorted = [...list];\n sorted.sort((a, b) => {\n if (sort === \"long-running\") {\n const cmp = a.created_at.localeCompare(b.created_at);\n return direction === \"desc\" ? cmp : -cmp;\n }\n const mul = direction === \"asc\" ? 1 : -1;\n if (sort === \"updated\") {\n return a.updated_at.localeCompare(b.updated_at) * mul;\n }\n if (sort === \"created\") {\n return a.created_at.localeCompare(b.created_at) * mul;\n }\n const av = a.comments + a.review_comments;\n const bv = b.comments + b.review_comments;\n if (av < bv) return -1 * mul;\n if (av > bv) return 1 * mul;\n return 0;\n });\n return sorted;\n}\n\nfunction checkMergeRequirements(gh: GitHubStore, pr: GitHubPullRequest) {\n const baseRepo = gh.repos.get(pr.base_repo_id);\n if (!baseRepo) throw new ApiError(422, \"Base repository not found\");\n\n const rule = gh.branchProtections.findBy(\"repo_id\", baseRepo.id).find((p) => p.branch_name === pr.base_ref);\n\n if (!rule) return;\n\n const checks = rule.required_status_checks;\n if (checks && checks.contexts.length > 0) {\n const runs = gh.checkRuns.findBy(\"repo_id\", baseRepo.id).filter((r) => r.head_sha === pr.head_sha);\n for (const ctx of checks.contexts) {\n const ok = runs.some((r) => r.name === ctx && r.status === \"completed\" && r.conclusion === \"success\");\n if (!ok) {\n throw new ApiError(422, \"Required status checks have not succeeded.\");\n }\n }\n }\n\n const rev = rule.required_pull_request_reviews;\n if (rev) {\n const need = rev.required_approving_review_count;\n const approved = gh.reviews\n .findBy(\"repo_id\", baseRepo.id)\n .filter((r) => r.pull_number === pr.number && r.state === \"APPROVED\");\n const approvers = new Set(approved.map((r) => r.user_id));\n if (approvers.size < need) {\n throw new ApiError(422, \"Required approving review count not met.\");\n }\n }\n}\n\nfunction deleteBranchByName(gh: GitHubStore, repo: GitHubRepo, branchName: string) {\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === branchName);\n if (branch) gh.branches.delete(branch.id);\n const ref = gh.refs.findBy(\"repo_id\", repo.id).find((r) => r.ref === `refs/heads/${branchName}`);\n if (ref) gh.refs.delete(ref.id);\n}\n\nfunction lookupUserByLogin(gh: GitHubStore, login: string): GitHubUser {\n const u = gh.users.findOneBy(\"login\", login);\n if (!u) throw new ApiError(422, \"Validation failed\");\n return u;\n}\n\nfunction lookupTeamSlug(gh: GitHubStore, orgId: number, slug: string) {\n const t = gh.teams.findBy(\"org_id\", orgId).find((x) => x.slug === slug);\n if (!t) throw new ApiError(422, \"Validation failed\");\n return t;\n}\n\nexport function pullsRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/pulls\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const stateQ = c.req.query(\"state\") ?? \"open\";\n const state: \"open\" | \"closed\" | \"all\" =\n stateQ === \"closed\" || stateQ === \"all\" || stateQ === \"open\" ? stateQ : \"open\";\n\n const headQ = c.req.query(\"head\") ?? \"\";\n const baseQ = c.req.query(\"base\") ?? \"\";\n\n const sortRaw = c.req.query(\"sort\") ?? \"created\";\n const sort: \"created\" | \"updated\" | \"popularity\" | \"long-running\" =\n sortRaw === \"updated\" || sortRaw === \"popularity\" || sortRaw === \"long-running\" ? sortRaw : \"created\";\n\n const dirRaw = c.req.query(\"direction\") ?? \"desc\";\n const direction: \"asc\" | \"desc\" = dirRaw === \"asc\" ? \"asc\" : \"desc\";\n\n let list = gh.pullRequests.findBy(\"repo_id\", repo.id);\n if (state === \"open\") list = list.filter((p) => p.state === \"open\");\n else if (state === \"closed\") list = list.filter((p) => p.state === \"closed\");\n\n if (baseQ.trim()) {\n list = list.filter((p) => p.base_ref === baseQ.trim());\n }\n if (headQ.trim()) {\n list = list.filter((p) => matchesHeadFilter(gh, p, headQ));\n }\n\n list = sortPulls(list, sort, direction);\n\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((p) => formatPullRequest(p, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/pulls\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n\n const title = body.title;\n if (typeof title !== \"string\" || !title.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n const headRaw = body.head;\n const baseRaw = body.base;\n if (typeof headRaw !== \"string\" || !headRaw.trim()) throw new ApiError(422, \"Validation failed\");\n if (typeof baseRaw !== \"string\" || !baseRaw.trim()) throw new ApiError(422, \"Validation failed\");\n\n const { headRepo, headRef } = resolveHeadTarget(gh, repo, headRaw);\n const baseRef = baseRaw.trim();\n\n if (headRef === baseRef && headRepo.id === repo.id) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const prBody = typeof body.body === \"string\" || body.body === null ? (body.body as string | null) : null;\n const draft = typeof body.draft === \"boolean\" ? body.draft : false;\n\n const headBranch = getOrCreateBranch(gh, headRepo, headRef);\n const baseBranch = getOrCreateBranch(gh, repo, baseRef);\n\n const num = getNextIssueNumber(gh, repo.id);\n const now = timestamp();\n\n const issueRow = gh.issues.insert({\n node_id: \"\",\n number: num,\n repo_id: repo.id,\n title: title.trim(),\n body: prBody,\n state: \"open\",\n state_reason: null,\n locked: false,\n active_lock_reason: null,\n user_id: actor.id,\n assignee_ids: [],\n label_ids: [],\n milestone_id: null,\n comments: 0,\n closed_at: null,\n closed_by_id: null,\n is_pull_request: true,\n } as Omit<GitHubIssue, \"id\" | \"created_at\" | \"updated_at\">);\n gh.issues.update(issueRow.id, { node_id: generateNodeId(\"Issue\", issueRow.id) });\n\n const commitCount = countCommitsBetween(gh, headRepo, headBranch.sha, baseBranch.sha);\n\n const prRow = gh.pullRequests.insert({\n node_id: \"\",\n number: num,\n repo_id: repo.id,\n title: title.trim(),\n body: prBody,\n state: \"open\",\n locked: false,\n user_id: actor.id,\n assignee_ids: [],\n label_ids: [],\n milestone_id: null,\n head_ref: headRef,\n head_sha: headBranch.sha,\n head_repo_id: headRepo.id,\n base_ref: baseRef,\n base_sha: baseBranch.sha,\n base_repo_id: repo.id,\n merged: false,\n merged_at: null,\n merged_by_id: null,\n merge_commit_sha: null,\n mergeable: true,\n mergeable_state: \"clean\",\n comments: 0,\n review_comments: 0,\n commits: Math.max(1, commitCount),\n additions: 0,\n deletions: 0,\n changed_files: 0,\n draft,\n requested_reviewer_ids: [],\n requested_team_ids: [],\n closed_at: null,\n auto_merge: null,\n } as Omit<GitHubPullRequest, \"id\" | \"created_at\" | \"updated_at\">);\n gh.pullRequests.update(prRow.id, { node_id: generateNodeId(\"PullRequest\", prRow.id) });\n\n adjustRepoOpenIssues(gh, repo.id, 1);\n\n const pr = gh.pullRequests.get(prRow.id)!;\n const prFmt = formatPullRequest(pr, gh, baseUrl)!;\n const ownerLogin = ownerLoginOf(gh, repo);\n\n webhooks.dispatch(\n \"pull_request\",\n \"opened\",\n {\n action: \"opened\",\n pull_request: prFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(prFmt, 201);\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const fmt = formatPullRequest(pr, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt);\n });\n\n app.patch(\"/repos/:owner/:repo/pulls/:pull_number\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubPullRequest> = {};\n const issuePatch: Partial<GitHubIssue> = {};\n\n if (typeof body.title === \"string\") {\n patch.title = body.title;\n issuePatch.title = body.title;\n }\n if (typeof body.body === \"string\" || body.body === null) {\n patch.body = body.body as string | null;\n issuePatch.body = body.body as string | null;\n }\n if (body.state === \"open\" || body.state === \"closed\") {\n const wasClosed = pr.state === \"closed\";\n patch.state = body.state;\n issuePatch.state = body.state;\n if (body.state === \"closed\") {\n patch.closed_at = timestamp();\n issuePatch.closed_at = timestamp();\n issuePatch.closed_by_id = actor.id;\n } else {\n patch.closed_at = null;\n issuePatch.closed_at = null;\n issuePatch.closed_by_id = null;\n }\n if (!wasClosed && body.state === \"closed\") {\n adjustRepoOpenIssues(gh, repo.id, -1);\n } else if (wasClosed && body.state === \"open\") {\n adjustRepoOpenIssues(gh, repo.id, 1);\n }\n }\n if (typeof body.base === \"string\" && body.base.trim()) {\n const newBase = body.base.trim();\n const bb = getOrCreateBranch(gh, repo, newBase);\n patch.base_ref = newBase;\n patch.base_sha = bb.sha;\n patch.base_repo_id = repo.id;\n }\n if (typeof body.draft === \"boolean\") {\n patch.draft = body.draft;\n }\n\n const updated = gh.pullRequests.update(pr.id, patch);\n if (!updated) throw notFoundResponse();\n\n const iss = findPrIssue(gh, repo.id, pullNumber);\n if (iss) {\n gh.issues.update(iss.id, issuePatch);\n }\n\n const fresh = gh.pullRequests.get(pr.id)!;\n const prFmt = formatPullRequest(fresh, gh, baseUrl)!;\n const ownerLogin = ownerLoginOf(gh, repo);\n\n if (body.state === \"closed\" && pr.state === \"open\") {\n webhooks.dispatch(\n \"pull_request\",\n \"closed\",\n {\n action: \"closed\",\n pull_request: prFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n } else if (body.state === \"open\" && pr.state === \"closed\") {\n webhooks.dispatch(\n \"pull_request\",\n \"reopened\",\n {\n action: \"reopened\",\n pull_request: prFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n } else if (typeof body.title === \"string\" || typeof body.body === \"string\" || body.body === null) {\n webhooks.dispatch(\n \"pull_request\",\n \"edited\",\n {\n action: \"edited\",\n pull_request: prFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n\n return c.json(prFmt);\n });\n\n app.put(\"/repos/:owner/:repo/pulls/:pull_number/merge\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n if (pr.merged || pr.state === \"closed\") {\n throw new ApiError(422, \"Pull Request is not mergeable\");\n }\n if (pr.draft) {\n throw new ApiError(422, \"Draft pull requests cannot be merged.\");\n }\n\n const body = await parseJsonBody(c);\n if (typeof body.sha === \"string\" && body.sha !== pr.head_sha) {\n throw new ApiError(422, \"Head sha is out of date\");\n }\n\n const mergeMethod = body.merge_method === \"squash\" || body.merge_method === \"rebase\" ? body.merge_method : \"merge\";\n\n if (mergeMethod === \"merge\" && !repo.allow_merge_commit) {\n throw new ApiError(422, \"Merge commits are not allowed on this repository.\");\n }\n if (mergeMethod === \"squash\" && !repo.allow_squash_merge) {\n throw new ApiError(422, \"Squash merges are not allowed on this repository.\");\n }\n if (mergeMethod === \"rebase\" && !repo.allow_rebase_merge) {\n throw new ApiError(422, \"Rebase merges are not allowed on this repository.\");\n }\n\n checkMergeRequirements(gh, pr);\n\n const baseRepo = gh.repos.get(pr.base_repo_id)!;\n const headRepo = gh.repos.get(pr.head_repo_id)!;\n\n const baseCommit = gh.commits.findBy(\"repo_id\", baseRepo.id).find((x) => x.sha === pr.base_sha);\n const headCommit = gh.commits.findBy(\"repo_id\", headRepo.id).find((x) => x.sha === pr.head_sha);\n\n if (!baseCommit || !headCommit) {\n throw new ApiError(422, \"Could not resolve commits to merge.\");\n }\n\n const commitTitle =\n typeof body.commit_title === \"string\" && body.commit_title.trim()\n ? body.commit_title.trim()\n : `Merge pull request #${pr.number} from ${headLabel(gh, pr)}`;\n const commitMessage =\n typeof body.commit_message === \"string\" && body.commit_message.trim() ? body.commit_message.trim() : \"\";\n\n const fullMessage = commitMessage ? `${commitTitle}\\n\\n${commitMessage}` : commitTitle;\n\n let mergeCommit: GitHubCommit;\n if (mergeMethod === \"merge\") {\n mergeCommit = insertCommit(gh, baseRepo, {\n treeSha: headCommit.tree_sha,\n parentShas: [pr.base_sha, pr.head_sha],\n message: fullMessage,\n user: actor,\n });\n } else {\n mergeCommit = insertCommit(gh, baseRepo, {\n treeSha: headCommit.tree_sha,\n parentShas: [pr.base_sha],\n message: fullMessage,\n user: actor,\n });\n }\n\n updateBranchSha(gh, baseRepo, pr.base_ref, mergeCommit.sha);\n\n const now = timestamp();\n gh.pullRequests.update(pr.id, {\n merged: true,\n merged_at: now,\n merged_by_id: actor.id,\n merge_commit_sha: mergeCommit.sha,\n state: \"closed\",\n closed_at: now,\n mergeable: false,\n mergeable_state: \"unknown\",\n });\n\n const iss = findPrIssue(gh, repo.id, pullNumber);\n if (iss) {\n gh.issues.update(iss.id, {\n state: \"closed\",\n closed_at: now,\n closed_by_id: actor.id,\n });\n }\n\n adjustRepoOpenIssues(gh, repo.id, -1);\n\n if (repo.delete_branch_on_merge && pr.head_ref !== pr.base_ref) {\n deleteBranchByName(gh, headRepo, pr.head_ref);\n }\n\n const mergedPr = gh.pullRequests.get(pr.id)!;\n const prFmt = formatPullRequest(mergedPr, gh, baseUrl)!;\n const ownerLogin = ownerLoginOf(gh, repo);\n\n webhooks.dispatch(\n \"pull_request\",\n \"closed\",\n {\n action: \"closed\",\n pull_request: { ...prFmt, merged: true },\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json({\n sha: mergeCommit.sha,\n merged: true,\n message: \"Pull Request successfully merged\",\n });\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/commits\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const headRepo = gh.repos.get(pr.head_repo_id);\n if (!headRepo) throw notFoundResponse();\n\n const chain = walkCommitsToBase(gh, headRepo, pr.head_sha, pr.base_sha);\n const { page, per_page } = parsePagination(c);\n const total = chain.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const slice = chain.slice(start, start + per_page);\n\n return c.json(slice.map((commit) => formatCommitApi(commit, headRepo, baseUrl)));\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/files\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const n = pr.changed_files;\n const stubNames = Array.from({ length: n }, (_, i) => `file${i + 1}.ts`);\n const total = stubNames.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageNames = stubNames.slice(start, start + per_page);\n\n return c.json(\n pageNames.map((filename, i) => ({\n sha: generateSha(),\n filename,\n status: \"modified\",\n additions: 1,\n deletions: 0,\n changes: 1,\n blob_url: `${baseUrl}/${repo.full_name}/blob/${pr.head_sha}/${filename}`,\n raw_url: `${baseUrl}/${repo.full_name}/raw/${pr.head_sha}/${filename}`,\n contents_url: `${baseUrl}/repos/${repo.full_name}/contents/${encodeURIComponent(filename)}?ref=${pr.head_ref}`,\n patch: \"\",\n })),\n );\n });\n\n app.post(\"/repos/:owner/:repo/pulls/:pull_number/requested_reviewers\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const body = (await parseJsonBody(c)) as {\n reviewers?: unknown;\n team_reviewers?: unknown;\n };\n\n const reviewerLogins = Array.isArray(body.reviewers)\n ? body.reviewers.filter((x): x is string => typeof x === \"string\")\n : [];\n const teamSlugs = Array.isArray(body.team_reviewers)\n ? body.team_reviewers.filter((x): x is string => typeof x === \"string\")\n : [];\n\n const newUserIds = reviewerLogins.map((login) => lookupUserByLogin(gh, login).id);\n let newTeamIds: number[] = [];\n if (teamSlugs.length > 0) {\n if (repo.owner_type !== \"Organization\") {\n throw new ApiError(422, \"Team reviewers are only supported for organization repositories.\");\n }\n newTeamIds = teamSlugs.map((slug) => lookupTeamSlug(gh, repo.owner_id, slug).id);\n }\n\n const requested_reviewer_ids = [...new Set([...pr.requested_reviewer_ids, ...newUserIds])];\n const requested_team_ids = [...new Set([...pr.requested_team_ids, ...newTeamIds])];\n\n gh.pullRequests.update(pr.id, { requested_reviewer_ids, requested_team_ids });\n const fresh = gh.pullRequests.get(pr.id)!;\n const prFmt = formatPullRequest(fresh, gh, baseUrl)!;\n const ownerLogin = ownerLoginOf(gh, repo);\n\n webhooks.dispatch(\n \"pull_request\",\n \"review_requested\",\n {\n action: \"review_requested\",\n pull_request: prFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(prFmt);\n });\n\n app.delete(\"/repos/:owner/:repo/pulls/:pull_number/requested_reviewers\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const body = (await parseJsonBody(c)) as {\n reviewers?: unknown;\n team_reviewers?: unknown;\n };\n\n const reviewerLogins = Array.isArray(body.reviewers)\n ? body.reviewers.filter((x): x is string => typeof x === \"string\")\n : [];\n const teamSlugs = Array.isArray(body.team_reviewers)\n ? body.team_reviewers.filter((x): x is string => typeof x === \"string\")\n : [];\n\n const removeUserIds = new Set(reviewerLogins.map((login) => lookupUserByLogin(gh, login).id));\n let removeTeamIds = new Set<number>();\n if (teamSlugs.length > 0 && repo.owner_type === \"Organization\") {\n removeTeamIds = new Set(teamSlugs.map((slug) => lookupTeamSlug(gh, repo.owner_id, slug).id));\n }\n\n const requested_reviewer_ids = pr.requested_reviewer_ids.filter((id) => !removeUserIds.has(id));\n const requested_team_ids = pr.requested_team_ids.filter((id) => !removeTeamIds.has(id));\n\n gh.pullRequests.update(pr.id, { requested_reviewer_ids, requested_team_ids });\n const fresh = gh.pullRequests.get(pr.id)!;\n return c.json(formatPullRequest(fresh, gh, baseUrl)!);\n });\n\n app.put(\"/repos/:owner/:repo/pulls/:pull_number/update-branch\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n if (pr.state === \"closed\" || pr.merged) {\n throw new ApiError(422, \"Cannot update a closed pull request\");\n }\n\n const body = (await parseJsonBody(c)) as { expected_head_sha?: unknown };\n if (typeof body.expected_head_sha === \"string\" && body.expected_head_sha !== pr.head_sha) {\n throw new ApiError(422, \"Head sha is out of date\");\n }\n\n const headRepo = gh.repos.get(pr.head_repo_id);\n const baseRepo = gh.repos.get(pr.base_repo_id);\n if (!headRepo || !baseRepo) throw notFoundResponse();\n\n const headCommit = gh.commits.findBy(\"repo_id\", headRepo.id).find((x) => x.sha === pr.head_sha);\n const baseCommit = gh.commits.findBy(\"repo_id\", baseRepo.id).find((x) => x.sha === pr.base_sha);\n if (!headCommit || !baseCommit) throw new ApiError(422, \"Could not resolve commits.\");\n\n const actor = assertAuthenticatedUser(gh, c.get(\"authUser\"));\n const mergeMsg = `Merge branch '${pr.base_ref}' into ${pr.head_ref}`;\n const newCommit = insertCommit(gh, headRepo, {\n treeSha: headCommit.tree_sha,\n parentShas: [pr.head_sha, pr.base_sha],\n message: mergeMsg,\n user: actor,\n });\n\n updateBranchSha(gh, headRepo, pr.head_ref, newCommit.sha);\n const next = gh.pullRequests.update(pr.id, {\n head_sha: newCommit.sha,\n commits: pr.commits + 1,\n });\n if (!next) throw notFoundResponse();\n\n const apiUrl = `${baseUrl}/repos/${repo.full_name}/pulls/${pullNumber}`;\n return c.json(\n {\n message: \"Updating pull request branch.\",\n url: apiUrl,\n },\n 202,\n );\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubComment, GitHubCommit, GitHubIssue, GitHubPullRequest, GitHubRepo } from \"../entities.js\";\nimport {\n formatComment,\n formatIssue,\n formatPullRequest,\n formatRepo,\n formatUser,\n generateNodeId,\n lookupRepo,\n} from \"../helpers.js\";\nimport { assertRepoRead, assertRepoWrite, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\nfunction findIssueByNumber(gh: GitHubStore, repoId: number, number: number): GitHubIssue | undefined {\n return gh.issues.findBy(\"repo_id\", repoId).find((i) => i.number === number);\n}\n\nfunction findPull(gh: GitHubStore, repoId: number, pullNumber: number): GitHubPullRequest | undefined {\n return gh.pullRequests.findBy(\"repo_id\", repoId).find((p) => p.number === pullNumber);\n}\n\nfunction findCommitInRepo(gh: GitHubStore, repoId: number, shaParam: string): GitHubCommit | undefined {\n const want = shaParam.toLowerCase();\n const list = gh.commits.findBy(\"repo_id\", repoId);\n return list.find((c) => c.sha === shaParam || c.sha.toLowerCase() === want || c.sha.startsWith(shaParam));\n}\n\nfunction getCommentForRepo(\n gh: GitHubStore,\n repo: GitHubRepo,\n commentId: number,\n kind: GitHubComment[\"comment_type\"],\n): GitHubComment | undefined {\n const c = gh.comments.get(commentId);\n if (!c || c.repo_id !== repo.id || c.comment_type !== kind) return undefined;\n return c;\n}\n\nfunction sortComments(\n comments: GitHubComment[],\n sort: \"created\" | \"updated\",\n direction: \"asc\" | \"desc\",\n): GitHubComment[] {\n const mul = direction === \"asc\" ? 1 : -1;\n const field = sort === \"created\" ? \"created_at\" : \"updated_at\";\n const sorted = [...comments];\n sorted.sort((a, b) => {\n const as = a[field];\n const bs = b[field];\n if (as < bs) return -1 * mul;\n if (as > bs) return 1 * mul;\n return a.id < b.id ? -1 * mul : a.id > b.id ? 1 * mul : 0;\n });\n return sorted;\n}\n\nfunction parseCommentSort(c: Context, defaultDirection: \"asc\" | \"desc\") {\n const sortRaw = c.req.query(\"sort\") ?? \"created\";\n const sort: \"created\" | \"updated\" = sortRaw === \"updated\" ? \"updated\" : \"created\";\n const dirRaw = c.req.query(\"direction\");\n const direction: \"asc\" | \"desc\" = dirRaw === \"desc\" ? \"desc\" : dirRaw === \"asc\" ? \"asc\" : defaultDirection;\n return { sort, direction };\n}\n\nfunction adjustIssueCommentCount(gh: GitHubStore, issue: GitHubIssue, delta: number) {\n gh.issues.update(issue.id, { comments: Math.max(0, issue.comments + delta) });\n}\n\nfunction adjustPrReviewCommentCount(gh: GitHubStore, pr: GitHubPullRequest, delta: number) {\n gh.pullRequests.update(pr.id, { review_comments: Math.max(0, pr.review_comments + delta) });\n}\n\nexport function commentsRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n // --- Issue comments: specific paths before /issues/:issue_number/comments ---\n\n app.get(\"/repos/:owner/:repo/issues/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"issue\");\n if (!comment) throw notFoundResponse();\n\n const json = formatComment(comment, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.patch(\"/repos/:owner/:repo/issues/comments/:comment_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n let comment = getCommentForRepo(gh, repo, commentId, \"issue\");\n if (!comment) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n if (typeof body.body !== \"string\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n comment = gh.comments.update(comment.id, { body: body.body })!;\n const issue = comment.issue_number !== null ? findIssueByNumber(gh, repo.id, comment.issue_number) : undefined;\n const ownerLogin = ownerLoginOf(gh, repo);\n const issueFmt = issue ? formatIssue(issue, gh, baseUrl) : null;\n const commentFmt = formatComment(comment, gh, baseUrl);\n if (!commentFmt) throw notFoundResponse();\n\n webhooks.dispatch(\n \"issue_comment\",\n \"edited\",\n {\n action: \"edited\",\n comment: commentFmt,\n issue: issueFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(commentFmt);\n });\n\n app.delete(\"/repos/:owner/:repo/issues/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"issue\");\n if (!comment) throw notFoundResponse();\n\n const issue = comment.issue_number !== null ? findIssueByNumber(gh, repo.id, comment.issue_number) : undefined;\n const commentFmt = formatComment(comment, gh, baseUrl);\n const issueFmt = issue ? formatIssue(issue, gh, baseUrl) : null;\n const ownerLogin = ownerLoginOf(gh, repo);\n\n gh.comments.delete(comment.id);\n if (issue) adjustIssueCommentCount(gh, issue, -1);\n\n webhooks.dispatch(\n \"issue_comment\",\n \"deleted\",\n {\n action: \"deleted\",\n comment: commentFmt,\n issue: issueFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/issues/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n const since = c.req.query(\"since\");\n\n let list = gh.comments.findBy(\"repo_id\", repo.id).filter((x) => x.comment_type === \"issue\");\n if (since) {\n list = list.filter((x) => x.updated_at >= since);\n }\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n // --- Pull review comments ---\n\n app.get(\"/repos/:owner/:repo/pulls/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"review\");\n if (!comment) throw notFoundResponse();\n\n const json = formatComment(comment, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.patch(\"/repos/:owner/:repo/pulls/comments/:comment_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n let comment = getCommentForRepo(gh, repo, commentId, \"review\");\n if (!comment) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n if (typeof body.body !== \"string\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n comment = gh.comments.update(comment.id, { body: body.body })!;\n const pr = comment.pull_number !== null ? findPull(gh, repo.id, comment.pull_number) : undefined;\n const ownerLogin = ownerLoginOf(gh, repo);\n const commentFmt = formatComment(comment, gh, baseUrl);\n if (!commentFmt) throw notFoundResponse();\n\n webhooks.dispatch(\n \"pull_request_review_comment\",\n \"edited\",\n {\n action: \"edited\",\n comment: commentFmt,\n pull_request: pr ? formatPullRequest(pr, gh, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(commentFmt);\n });\n\n app.delete(\"/repos/:owner/:repo/pulls/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"review\");\n if (!comment) throw notFoundResponse();\n\n const pr = comment.pull_number !== null ? findPull(gh, repo.id, comment.pull_number) : undefined;\n const commentFmt = formatComment(comment, gh, baseUrl);\n const ownerLogin = ownerLoginOf(gh, repo);\n\n gh.comments.delete(comment.id);\n if (pr) adjustPrReviewCommentCount(gh, pr, -1);\n\n webhooks.dispatch(\n \"pull_request_review_comment\",\n \"deleted\",\n {\n action: \"deleted\",\n comment: commentFmt,\n pull_request: pr ? formatPullRequest(pr, gh, baseUrl) : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/pulls/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments.findBy(\"repo_id\", repo.id).filter((x) => x.comment_type === \"review\");\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n // --- Commit comments (repo scope) ---\n\n app.get(\"/repos/:owner/:repo/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"commit\");\n if (!comment) throw notFoundResponse();\n\n const json = formatComment(comment, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.patch(\"/repos/:owner/:repo/comments/:comment_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n let comment = getCommentForRepo(gh, repo, commentId, \"commit\");\n if (!comment) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n if (typeof body.body !== \"string\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n comment = gh.comments.update(comment.id, { body: body.body })!;\n const json = formatComment(comment, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.delete(\"/repos/:owner/:repo/comments/:comment_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commentId = parseInt(c.req.param(\"comment_id\")!, 10);\n if (!Number.isFinite(commentId)) throw notFoundResponse();\n\n const comment = getCommentForRepo(gh, repo, commentId, \"commit\");\n if (!comment) throw notFoundResponse();\n\n gh.comments.delete(comment.id);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments.findBy(\"repo_id\", repo.id).filter((x) => x.comment_type === \"commit\");\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n // --- Per-issue / per-PR / per-commit ---\n\n app.get(\"/repos/:owner/:repo/issues/:issue_number/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments\n .findBy(\"repo_id\", repo.id)\n .filter((x) => x.comment_type === \"issue\" && x.issue_number === issueNumber);\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/issues/:issue_number/comments\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n if (!repo.has_issues) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const raw = await parseJsonBody(c);\n if (typeof raw.body !== \"string\" || !raw.body.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const row = gh.comments.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: issueNumber,\n pull_number: null,\n commit_sha: null,\n body: raw.body,\n user_id: actor.id,\n in_reply_to_id: null,\n path: null,\n position: null,\n line: null,\n side: null,\n subject_type: null,\n comment_type: \"issue\",\n review_id: null,\n } as Omit<GitHubComment, \"id\" | \"created_at\" | \"updated_at\">);\n gh.comments.update(row.id, { node_id: generateNodeId(\"IssueComment\", row.id) });\n const comment = gh.comments.get(row.id)!;\n\n adjustIssueCommentCount(gh, issue, 1);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n const commentFmt = formatComment(comment, gh, baseUrl)!;\n\n webhooks.dispatch(\n \"issue_comment\",\n \"created\",\n {\n action: \"created\",\n comment: commentFmt,\n issue: formatIssue(issue, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(commentFmt, 201);\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments\n .findBy(\"repo_id\", repo.id)\n .filter((x) => x.comment_type === \"review\" && x.pull_number === pullNumber);\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/pulls/:pull_number/comments\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const raw = await parseJsonBody(c);\n if (typeof raw.body !== \"string\" || !raw.body.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const commitSha = typeof raw.commit_id === \"string\" && raw.commit_id.trim() ? raw.commit_id.trim() : pr.head_sha;\n\n let inReplyTo: number | null = null;\n if (raw.in_reply_to_id !== undefined && raw.in_reply_to_id !== null) {\n const rid =\n typeof raw.in_reply_to_id === \"number\" ? raw.in_reply_to_id : parseInt(String(raw.in_reply_to_id), 10);\n if (!Number.isFinite(rid)) throw new ApiError(422, \"Validation failed\");\n const parent = gh.comments.get(rid);\n if (\n !parent ||\n parent.repo_id !== repo.id ||\n parent.comment_type !== \"review\" ||\n parent.pull_number !== pullNumber\n ) {\n throw new ApiError(422, \"Validation failed\");\n }\n inReplyTo = rid;\n }\n\n const pathVal = raw.path === undefined || raw.path === null ? null : typeof raw.path === \"string\" ? raw.path : null;\n const position =\n raw.position === undefined || raw.position === null\n ? null\n : typeof raw.position === \"number\" && Number.isFinite(raw.position)\n ? raw.position\n : parseInt(String(raw.position), 10);\n const line =\n raw.line === undefined || raw.line === null\n ? null\n : typeof raw.line === \"number\" && Number.isFinite(raw.line)\n ? raw.line\n : parseInt(String(raw.line), 10);\n let side: \"LEFT\" | \"RIGHT\" | null = null;\n if (raw.side === \"LEFT\" || raw.side === \"RIGHT\") side = raw.side;\n else if (raw.side === null || raw.side === undefined) side = null;\n else throw new ApiError(422, \"Validation failed\");\n\n let subjectType: \"line\" | \"file\" | null = null;\n if (raw.subject_type === \"line\" || raw.subject_type === \"file\") subjectType = raw.subject_type;\n else if (raw.subject_type === null || raw.subject_type === undefined) subjectType = null;\n else throw new ApiError(422, \"Validation failed\");\n\n if (position !== null && !Number.isFinite(position)) throw new ApiError(422, \"Validation failed\");\n if (line !== null && !Number.isFinite(line)) throw new ApiError(422, \"Validation failed\");\n\n const row = gh.comments.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: null,\n pull_number: pullNumber,\n commit_sha: commitSha,\n body: raw.body,\n user_id: actor.id,\n in_reply_to_id: inReplyTo,\n path: pathVal,\n position: position !== null && Number.isFinite(position) ? position : null,\n line: line !== null && Number.isFinite(line) ? line : null,\n side,\n subject_type: subjectType,\n comment_type: \"review\",\n review_id: null,\n } as Omit<GitHubComment, \"id\" | \"created_at\" | \"updated_at\">);\n gh.comments.update(row.id, { node_id: generateNodeId(\"PullRequestReviewComment\", row.id) });\n const comment = gh.comments.get(row.id)!;\n\n adjustPrReviewCommentCount(gh, pr, 1);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n const commentFmt = formatComment(comment, gh, baseUrl)!;\n\n webhooks.dispatch(\n \"pull_request_review_comment\",\n \"created\",\n {\n action: \"created\",\n comment: commentFmt,\n pull_request: formatPullRequest(pr, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(commentFmt, 201);\n });\n\n app.get(\"/repos/:owner/:repo/commits/:commit_sha/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const commitSha = c.req.param(\"commit_sha\")!;\n const commit = findCommitInRepo(gh, repo.id, commitSha);\n if (!commit) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments\n .findBy(\"repo_id\", repo.id)\n .filter((x) => x.comment_type === \"commit\" && x.commit_sha === commit.sha);\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/commits/:commit_sha/comments\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const commitShaParam = c.req.param(\"commit_sha\")!;\n const commit = findCommitInRepo(gh, repo.id, commitShaParam);\n if (!commit) throw notFoundResponse();\n\n const raw = await parseJsonBody(c);\n if (typeof raw.body !== \"string\" || !raw.body.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const pathVal = raw.path === undefined || raw.path === null ? null : typeof raw.path === \"string\" ? raw.path : null;\n const position =\n raw.position === undefined || raw.position === null\n ? null\n : typeof raw.position === \"number\" && Number.isFinite(raw.position)\n ? raw.position\n : parseInt(String(raw.position), 10);\n const line =\n raw.line === undefined || raw.line === null\n ? null\n : typeof raw.line === \"number\" && Number.isFinite(raw.line)\n ? raw.line\n : parseInt(String(raw.line), 10);\n\n if (position !== null && !Number.isFinite(position)) throw new ApiError(422, \"Validation failed\");\n if (line !== null && !Number.isFinite(line)) throw new ApiError(422, \"Validation failed\");\n\n const row = gh.comments.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: null,\n pull_number: null,\n commit_sha: commit.sha,\n body: raw.body,\n user_id: actor.id,\n in_reply_to_id: null,\n path: pathVal,\n position: position !== null && Number.isFinite(position) ? position : null,\n line: line !== null && Number.isFinite(line) ? line : null,\n side: null,\n subject_type: null,\n comment_type: \"commit\",\n review_id: null,\n } as Omit<GitHubComment, \"id\" | \"created_at\" | \"updated_at\">);\n gh.comments.update(row.id, { node_id: generateNodeId(\"CommitComment\", row.id) });\n const comment = gh.comments.get(row.id)!;\n\n const commentFmt = formatComment(comment, gh, baseUrl)!;\n return c.json(commentFmt, 201);\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { RouteContext, WebhookDispatcher } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubComment, GitHubPullRequest, GitHubRepo, GitHubReview, GitHubUser } from \"../entities.js\";\nimport {\n formatComment,\n formatPullRequest,\n formatRepo,\n formatReview,\n formatUser,\n generateNodeId,\n generateSha,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\nimport { assertRepoRead, assertRepoWrite, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\nfunction findPull(gh: GitHubStore, repoId: number, pullNumber: number): GitHubPullRequest | undefined {\n return gh.pullRequests.findBy(\"repo_id\", repoId).find((p) => p.number === pullNumber);\n}\n\nfunction findReview(gh: GitHubStore, repo: GitHubRepo, pullNumber: number, reviewId: number): GitHubReview | undefined {\n const r = gh.reviews.get(reviewId);\n if (!r || r.repo_id !== repo.id || r.pull_number !== pullNumber) return undefined;\n return r;\n}\n\nfunction adjustPrReviewCommentCount(gh: GitHubStore, pr: GitHubPullRequest, delta: number) {\n gh.pullRequests.update(pr.id, { review_comments: Math.max(0, pr.review_comments + delta) });\n}\n\nfunction sortComments(\n comments: GitHubComment[],\n sort: \"created\" | \"updated\",\n direction: \"asc\" | \"desc\",\n): GitHubComment[] {\n const mul = direction === \"asc\" ? 1 : -1;\n const field = sort === \"created\" ? \"created_at\" : \"updated_at\";\n const sorted = [...comments];\n sorted.sort((a, b) => {\n const as = a[field];\n const bs = b[field];\n if (as < bs) return -1 * mul;\n if (as > bs) return 1 * mul;\n return a.id < b.id ? -1 * mul : a.id > b.id ? 1 * mul : 0;\n });\n return sorted;\n}\n\nfunction parseCommentSort(c: Context, defaultDirection: \"asc\" | \"desc\") {\n const sortRaw = c.req.query(\"sort\") ?? \"created\";\n const sort: \"created\" | \"updated\" = sortRaw === \"updated\" ? \"updated\" : \"created\";\n const dirRaw = c.req.query(\"direction\");\n const direction: \"asc\" | \"desc\" = dirRaw === \"desc\" ? \"desc\" : dirRaw === \"asc\" ? \"asc\" : defaultDirection;\n return { sort, direction };\n}\n\nfunction parseSubmitEvent(raw: unknown): \"APPROVE\" | \"REQUEST_CHANGES\" | \"COMMENT\" {\n if (raw === \"APPROVE\" || raw === \"REQUEST_CHANGES\" || raw === \"COMMENT\") return raw;\n throw new ApiError(422, \"Validation failed\");\n}\n\nfunction eventToState(event: \"APPROVE\" | \"REQUEST_CHANGES\" | \"COMMENT\"): GitHubReview[\"state\"] {\n switch (event) {\n case \"APPROVE\":\n return \"APPROVED\";\n case \"REQUEST_CHANGES\":\n return \"CHANGES_REQUESTED\";\n case \"COMMENT\":\n return \"COMMENTED\";\n default:\n return \"COMMENTED\";\n }\n}\n\nfunction dispatchReviewWebhook(\n webhooks: WebhookDispatcher,\n gh: GitHubStore,\n repo: GitHubRepo,\n review: GitHubReview,\n pr: GitHubPullRequest,\n actor: GitHubUser,\n baseUrl: string,\n action: \"submitted\" | \"dismissed\",\n) {\n const ownerLogin = ownerLoginOf(gh, repo);\n const reviewFmt = formatReview(review, gh, baseUrl);\n if (!reviewFmt) return;\n webhooks.dispatch(\n \"pull_request_review\",\n action,\n {\n action,\n review: reviewFmt,\n pull_request: formatPullRequest(pr, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n}\n\nexport function reviewsRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/reviews\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const list = gh.reviews.findBy(\"repo_id\", repo.id).filter((r) => r.pull_number === pullNumber);\n list.sort((a, b) => a.id - b.id);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((r) => formatReview(r, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n\n app.post(\"/repos/:owner/:repo/pulls/:pull_number/reviews\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n if (!Number.isFinite(pullNumber)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const raw = await parseJsonBody(c);\n\n const eventRaw = raw.event;\n const hasEvent = eventRaw === \"APPROVE\" || eventRaw === \"REQUEST_CHANGES\" || eventRaw === \"COMMENT\";\n if (eventRaw !== undefined && eventRaw !== null && !hasEvent) {\n throw new ApiError(422, \"Validation failed\");\n }\n const event = hasEvent ? parseSubmitEvent(eventRaw) : undefined;\n\n let bodyText: string | null = null;\n if (typeof raw.body === \"string\") bodyText = raw.body;\n else if (raw.body === null || raw.body === undefined) bodyText = null;\n else throw new ApiError(422, \"Validation failed\");\n\n const commitId =\n typeof raw.commit_id === \"string\" && raw.commit_id.trim() ? raw.commit_id.trim() : pr.head_sha || generateSha();\n\n const state: GitHubReview[\"state\"] = event ? eventToState(event) : \"PENDING\";\n const submittedAt = event ? timestamp() : null;\n\n const row = gh.reviews.insert({\n node_id: \"\",\n repo_id: repo.id,\n pull_number: pullNumber,\n user_id: actor.id,\n body: bodyText,\n state,\n commit_id: commitId,\n submitted_at: submittedAt,\n } as Omit<GitHubReview, \"id\" | \"created_at\" | \"updated_at\">);\n gh.reviews.update(row.id, { node_id: generateNodeId(\"PullRequestReview\", row.id) });\n const review = gh.reviews.get(row.id)!;\n\n const commentsArr = Array.isArray(raw.comments) ? raw.comments : [];\n for (const entry of commentsArr) {\n if (!entry || typeof entry !== \"object\") throw new ApiError(422, \"Validation failed\");\n const o = entry as Record<string, unknown>;\n if (typeof o.path !== \"string\" || !o.path.trim()) throw new ApiError(422, \"Validation failed\");\n const pos =\n typeof o.position === \"number\" && Number.isFinite(o.position) ? o.position : parseInt(String(o.position), 10);\n if (!Number.isFinite(pos)) throw new ApiError(422, \"Validation failed\");\n if (typeof o.body !== \"string\") throw new ApiError(422, \"Validation failed\");\n\n const cRow = gh.comments.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: null,\n pull_number: pullNumber,\n commit_sha: commitId,\n body: o.body,\n user_id: actor.id,\n in_reply_to_id: null,\n path: o.path,\n position: pos,\n line: null,\n side: \"RIGHT\",\n subject_type: \"line\",\n comment_type: \"review\",\n review_id: review.id,\n } as Omit<GitHubComment, \"id\" | \"created_at\" | \"updated_at\">);\n gh.comments.update(cRow.id, { node_id: generateNodeId(\"PullRequestReviewComment\", cRow.id) });\n adjustPrReviewCommentCount(gh, pr, 1);\n }\n\n if (event) {\n dispatchReviewWebhook(webhooks, gh, repo, review, pr, actor, baseUrl, \"submitted\");\n }\n\n const json = formatReview(review, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json, 201);\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/reviews/:review_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n const reviewId = parseInt(c.req.param(\"review_id\")!, 10);\n if (!Number.isFinite(pullNumber) || !Number.isFinite(reviewId)) throw notFoundResponse();\n\n const review = findReview(gh, repo, pullNumber, reviewId);\n if (!review) throw notFoundResponse();\n\n const json = formatReview(review, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.put(\"/repos/:owner/:repo/pulls/:pull_number/reviews/:review_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n const reviewId = parseInt(c.req.param(\"review_id\")!, 10);\n if (!Number.isFinite(pullNumber) || !Number.isFinite(reviewId)) throw notFoundResponse();\n\n const existing = findReview(gh, repo, pullNumber, reviewId);\n if (!existing) throw notFoundResponse();\n if (existing.state !== \"PENDING\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const raw = await parseJsonBody(c);\n if (typeof raw.body !== \"string\" && raw.body !== null) {\n throw new ApiError(422, \"Validation failed\");\n }\n const bodyVal = typeof raw.body === \"string\" ? raw.body : null;\n\n const updated = gh.reviews.update(reviewId, { body: bodyVal });\n if (!updated) throw notFoundResponse();\n\n const json = formatReview(updated, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.post(\"/repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/events\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n const reviewId = parseInt(c.req.param(\"review_id\")!, 10);\n if (!Number.isFinite(pullNumber) || !Number.isFinite(reviewId)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const review = findReview(gh, repo, pullNumber, reviewId);\n if (!review) throw notFoundResponse();\n if (review.state !== \"PENDING\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const raw = await parseJsonBody(c);\n const event = parseSubmitEvent(raw.event);\n\n let bodyText: string | null = review.body;\n if (typeof raw.body === \"string\") bodyText = raw.body;\n else if (raw.body === null) bodyText = null;\n else if (raw.body !== undefined) throw new ApiError(422, \"Validation failed\");\n\n const nextState = eventToState(event);\n const updated = gh.reviews.update(reviewId, {\n body: bodyText,\n state: nextState,\n submitted_at: timestamp(),\n });\n if (!updated) throw notFoundResponse();\n\n dispatchReviewWebhook(webhooks, gh, repo, updated, pr, actor, baseUrl, \"submitted\");\n\n const json = formatReview(updated, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.put(\"/repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/dismissals\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n const reviewId = parseInt(c.req.param(\"review_id\")!, 10);\n if (!Number.isFinite(pullNumber) || !Number.isFinite(reviewId)) throw notFoundResponse();\n\n const pr = findPull(gh, repo.id, pullNumber);\n if (!pr) throw notFoundResponse();\n\n const review = findReview(gh, repo, pullNumber, reviewId);\n if (!review) throw notFoundResponse();\n if (review.state === \"PENDING\" || review.state === \"DISMISSED\") {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const raw = await parseJsonBody(c);\n const message = typeof raw.message === \"string\" ? raw.message : null;\n\n const updated = gh.reviews.update(reviewId, {\n state: \"DISMISSED\",\n body: message !== null && message !== undefined ? message : review.body,\n });\n if (!updated) throw notFoundResponse();\n\n dispatchReviewWebhook(webhooks, gh, repo, updated, pr, actor, baseUrl, \"dismissed\");\n\n const json = formatReview(updated, gh, baseUrl);\n if (!json) throw notFoundResponse();\n return c.json(json);\n });\n\n app.get(\"/repos/:owner/:repo/pulls/:pull_number/reviews/:review_id/comments\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const pullNumber = parseInt(c.req.param(\"pull_number\")!, 10);\n const reviewId = parseInt(c.req.param(\"review_id\")!, 10);\n if (!Number.isFinite(pullNumber) || !Number.isFinite(reviewId)) throw notFoundResponse();\n\n const review = findReview(gh, repo, pullNumber, reviewId);\n if (!review) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const { sort, direction } = parseCommentSort(c, \"asc\");\n\n let list = gh.comments\n .findBy(\"repo_id\", repo.id)\n .filter((x) => x.comment_type === \"review\" && x.pull_number === pullNumber && x.review_id === reviewId);\n list = sortComments(list, sort, direction);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n const body = pageItems\n .map((x) => formatComment(x, gh, baseUrl))\n .filter((x): x is NonNullable<typeof x> => x !== null);\n return c.json(body);\n });\n}\n","import type { Context } from \"@emulators/core\";\nimport type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubIssue,\n GitHubIssueEvent,\n GitHubLabel,\n GitHubMilestone,\n GitHubRepo,\n GitHubUser,\n} from \"../entities.js\";\nimport {\n formatIssue,\n formatLabel,\n formatMilestone,\n formatPullRequest,\n formatRepo,\n formatUser,\n generateNodeId,\n getNextMilestoneNumber,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\nimport { assertIssueWrite, assertRepoRead, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\nfunction findIssueByNumber(gh: GitHubStore, repoId: number, issueNumber: number): GitHubIssue | undefined {\n return gh.issues.findBy(\"repo_id\", repoId).find((i) => i.number === issueNumber);\n}\n\nfunction findPullByNumber(gh: GitHubStore, repoId: number, num: number) {\n return gh.pullRequests.findBy(\"repo_id\", repoId).find((p) => p.number === num);\n}\n\nfunction formatIssueOrPullPayload(gh: GitHubStore, issue: GitHubIssue, current: GitHubIssue, baseUrl: string) {\n if (issue.is_pull_request) {\n const pr = findPullByNumber(gh, issue.repo_id, issue.number);\n return pr ? formatPullRequest(pr, gh, baseUrl) : null;\n }\n return formatIssue(current, gh, baseUrl);\n}\n\n/** Keep issue and pull request rows in sync for label_ids. */\nfunction setIssueLabelIds(gh: GitHubStore, issue: GitHubIssue, labelIds: number[]) {\n gh.issues.update(issue.id, { label_ids: labelIds });\n if (issue.is_pull_request) {\n const pr = findPullByNumber(gh, issue.repo_id, issue.number);\n if (pr) gh.pullRequests.update(pr.id, { label_ids: labelIds });\n }\n}\n\nfunction insertIssueEvent(\n gh: GitHubStore,\n repo: GitHubRepo,\n issueNumber: number,\n event: string,\n actorId: number,\n extra?: Partial<\n Pick<GitHubIssueEvent, \"commit_id\" | \"commit_url\" | \"label_name\" | \"assignee_id\" | \"milestone_title\" | \"rename\">\n >,\n): GitHubIssueEvent {\n const row = gh.issueEvents.insert({\n node_id: \"\",\n repo_id: repo.id,\n issue_number: issueNumber,\n event,\n actor_id: actorId,\n commit_id: null,\n commit_url: null,\n label_name: null,\n assignee_id: null,\n milestone_title: null,\n rename: null,\n ...extra,\n } as Omit<GitHubIssueEvent, \"id\" | \"created_at\" | \"updated_at\">);\n gh.issueEvents.update(row.id, { node_id: generateNodeId(\"IssueEvent\", row.id) });\n return gh.issueEvents.get(row.id)!;\n}\n\nfunction randomLabelColor(): string {\n return Math.floor(Math.random() * 0xffffff)\n .toString(16)\n .padStart(6, \"0\");\n}\n\nfunction normalizeColor(raw: unknown): string {\n if (typeof raw !== \"string\" || !raw.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n const s = raw.trim().replace(/^#/, \"\");\n if (!/^[0-9a-fA-F]{6}$/.test(s)) {\n throw new ApiError(422, \"Validation failed\");\n }\n return s.toLowerCase();\n}\n\nfunction getOrCreateLabel(gh: GitHubStore, repo: GitHubRepo, name: string): GitHubLabel {\n const existing = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (existing) return existing;\n const label = gh.labels.insert({\n node_id: \"\",\n repo_id: repo.id,\n name,\n description: null,\n color: randomLabelColor(),\n default: false,\n } as Omit<GitHubLabel, \"id\" | \"created_at\" | \"updated_at\">);\n gh.labels.update(label.id, { node_id: generateNodeId(\"Label\", label.id) });\n return gh.labels.get(label.id)!;\n}\n\nasync function parseLabelNamesFromBody(c: Context): Promise<string[]> {\n const raw = await c.req.json().catch(() => null);\n if (raw === null) throw new ApiError(422, \"Validation failed\");\n let arr: unknown[];\n if (Array.isArray(raw)) {\n arr = raw;\n } else if (typeof raw === \"object\" && raw !== null && Array.isArray((raw as { labels?: unknown }).labels)) {\n arr = (raw as { labels: unknown[] }).labels;\n } else {\n throw new ApiError(422, \"Validation failed\");\n }\n const names = arr.filter((x): x is string => typeof x === \"string\" && x.length > 0);\n if (names.length !== arr.length) throw new ApiError(422, \"Validation failed\");\n return names;\n}\n\nfunction removeLabelFromAllIssuesAndPrs(gh: GitHubStore, repoId: number, labelId: number) {\n for (const i of gh.issues.findBy(\"repo_id\", repoId)) {\n if (i.label_ids.includes(labelId)) {\n const next = i.label_ids.filter((id) => id !== labelId);\n setIssueLabelIds(gh, i, next);\n }\n }\n}\n\nfunction recalcMilestoneIssueCounts(gh: GitHubStore, repoId: number, milestoneId: number): GitHubMilestone | undefined {\n const m = gh.milestones.get(milestoneId);\n if (!m) return undefined;\n const items = gh.issues.findBy(\"repo_id\", repoId).filter((i) => i.milestone_id === milestoneId);\n let open = 0;\n let closed = 0;\n for (const i of items) {\n if (i.state === \"open\") open++;\n else closed++;\n }\n return gh.milestones.update(milestoneId, { open_issues: open, closed_issues: closed }) ?? m;\n}\n\nfunction sortMilestones(\n list: GitHubMilestone[],\n sort: \"due_on\" | \"completeness\",\n direction: \"asc\" | \"desc\",\n): GitHubMilestone[] {\n const mul = direction === \"asc\" ? 1 : -1;\n const sorted = [...list];\n sorted.sort((a, b) => {\n if (sort === \"due_on\") {\n const aNull = a.due_on === null;\n const bNull = b.due_on === null;\n if (aNull && bNull) return 0;\n // Asc: no due date last. Desc: no due date first (GitHub-style).\n if (aNull) return direction === \"asc\" ? 1 : -1;\n if (bNull) return direction === \"asc\" ? -1 : 1;\n const cmp = a.due_on! < b.due_on! ? -1 : a.due_on! > b.due_on! ? 1 : 0;\n return cmp * mul;\n }\n const totalA = a.open_issues + a.closed_issues;\n const totalB = b.open_issues + b.closed_issues;\n const pctA = totalA === 0 ? 0 : a.closed_issues / totalA;\n const pctB = totalB === 0 ? 0 : b.closed_issues / totalB;\n const cmp = pctA < pctB ? -1 : pctA > pctB ? 1 : 0;\n return cmp * mul;\n });\n return sorted;\n}\n\nexport function labelsAndMilestonesRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/labels\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const { page, per_page } = parsePagination(c);\n const list = gh.labels.findBy(\"repo_id\", repo.id).slice();\n list.sort((a, b) => a.name.localeCompare(b.name));\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n return c.json(pageItems.map((l) => formatLabel(l, repo, baseUrl)));\n });\n\n app.post(\"/repos/:owner/:repo/labels\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name.trim() : \"\";\n if (!name) throw new ApiError(422, \"Validation failed\");\n\n const dup = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (dup) throw new ApiError(422, \"Validation failed\");\n\n const color = body.color !== undefined && body.color !== null ? normalizeColor(body.color) : randomLabelColor();\n const description =\n typeof body.description === \"string\" || body.description === null ? (body.description as string | null) : null;\n\n const row = gh.labels.insert({\n node_id: \"\",\n repo_id: repo.id,\n name,\n description,\n color,\n default: false,\n } as Omit<GitHubLabel, \"id\" | \"created_at\" | \"updated_at\">);\n gh.labels.update(row.id, { node_id: generateNodeId(\"Label\", row.id) });\n const label = gh.labels.get(row.id)!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"label\",\n \"created\",\n {\n action: \"created\",\n label: formatLabel(label, repo, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(formatLabel(label, repo, baseUrl), 201);\n });\n\n app.get(\"/repos/:owner/:repo/labels/:name\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const rawName = c.req.param(\"name\")!;\n const name = decodeURIComponent(rawName);\n const label = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (!label) throw notFoundResponse();\n return c.json(formatLabel(label, repo, baseUrl));\n });\n\n app.patch(\"/repos/:owner/:repo/labels/:name\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n\n const rawName = c.req.param(\"name\")!;\n const name = decodeURIComponent(rawName);\n let label = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (!label) throw notFoundResponse();\n const labelId = label.id;\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubLabel> = {};\n if (typeof body.new_name === \"string\" && body.new_name.trim()) {\n const nn = body.new_name.trim();\n const clash = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === nn && l.id !== labelId);\n if (clash) throw new ApiError(422, \"Validation failed\");\n patch.name = nn;\n }\n if (body.color !== undefined) {\n patch.color = normalizeColor(body.color);\n }\n if (\"description\" in body) {\n patch.description =\n typeof body.description === \"string\" || body.description === null ? (body.description as string | null) : null;\n }\n\n const updated = gh.labels.update(labelId, patch);\n if (!updated) throw notFoundResponse();\n label = updated;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"label\",\n \"edited\",\n {\n action: \"edited\",\n label: formatLabel(label, repo, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(formatLabel(label, repo, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/labels/:name\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n\n const rawName = c.req.param(\"name\")!;\n const name = decodeURIComponent(rawName);\n const label = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === name);\n if (!label) throw notFoundResponse();\n\n removeLabelFromAllIssuesAndPrs(gh, repo.id, label.id);\n gh.labels.delete(label.id);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"label\",\n \"deleted\",\n {\n action: \"deleted\",\n label: formatLabel(label, repo, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/issues/:issue_number/labels\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const labels = issue.label_ids\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n return c.json(labels);\n });\n\n app.post(\"/repos/:owner/:repo/issues/:issue_number/labels\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const names = await parseLabelNamesFromBody(c);\n const prev = new Set(issue.label_ids);\n const ids = [...prev];\n for (const n of names) {\n const label = getOrCreateLabel(gh, repo, n);\n if (!ids.includes(label.id)) ids.push(label.id);\n }\n setIssueLabelIds(gh, issue, ids);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n const after = gh.issues.get(issue.id)!;\n for (const id of after.label_ids) {\n if (!prev.has(id)) {\n const lbl = gh.labels.get(id);\n if (lbl) {\n insertIssueEvent(gh, repo, issue.number, \"labeled\", actor.id, { label_name: lbl.name });\n webhooks.dispatch(\n \"issues\",\n \"labeled\",\n {\n action: \"labeled\",\n issue: formatIssueOrPullPayload(gh, issue, after, baseUrl),\n label: lbl ? { name: lbl.name, color: lbl.color } : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n }\n\n const labelsJson = after.label_ids\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n return c.json(labelsJson);\n });\n\n app.put(\"/repos/:owner/:repo/issues/:issue_number/labels\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const names = await parseLabelNamesFromBody(c);\n const newIds = [...new Set(names.map((n) => getOrCreateLabel(gh, repo, n).id))];\n const prev = new Set(issue.label_ids);\n\n setIssueLabelIds(gh, issue, newIds);\n const after = gh.issues.get(issue.id)!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n for (const id of prev) {\n if (!newIds.includes(id)) {\n const lbl = gh.labels.get(id);\n insertIssueEvent(gh, repo, issue.number, \"unlabeled\", actor.id, { label_name: lbl?.name ?? null });\n webhooks.dispatch(\n \"issues\",\n \"unlabeled\",\n {\n action: \"unlabeled\",\n issue: formatIssueOrPullPayload(gh, issue, after, baseUrl),\n label: lbl ? { name: lbl.name, color: lbl.color } : null,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n for (const id of newIds) {\n if (!prev.has(id)) {\n const lbl = gh.labels.get(id);\n if (lbl) {\n insertIssueEvent(gh, repo, issue.number, \"labeled\", actor.id, { label_name: lbl.name });\n webhooks.dispatch(\n \"issues\",\n \"labeled\",\n {\n action: \"labeled\",\n issue: formatIssueOrPullPayload(gh, issue, after, baseUrl),\n label: { name: lbl.name, color: lbl.color },\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n }\n }\n\n const labelsJson = after.label_ids\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n return c.json(labelsJson);\n });\n\n app.delete(\"/repos/:owner/:repo/issues/:issue_number/labels/:name\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n const rawLabelName = c.req.param(\"name\")!;\n const labelName = decodeURIComponent(rawLabelName);\n const label = gh.labels.findBy(\"repo_id\", repo.id).find((l) => l.name === labelName);\n if (!label || !issue.label_ids.includes(label.id)) throw notFoundResponse();\n\n const next = issue.label_ids.filter((id) => id !== label.id);\n setIssueLabelIds(gh, issue, next);\n const after = gh.issues.get(issue.id)!;\n\n insertIssueEvent(gh, repo, issue.number, \"unlabeled\", actor.id, { label_name: label.name });\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"issues\",\n \"unlabeled\",\n {\n action: \"unlabeled\",\n issue: formatIssueOrPullPayload(gh, issue, after, baseUrl),\n label: { name: label.name, color: label.color },\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n const labelsJson = after.label_ids\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => formatLabel(l!, repo, baseUrl));\n return c.json(labelsJson);\n });\n\n app.delete(\"/repos/:owner/:repo/issues/:issue_number/labels\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const issueNumber = parseInt(c.req.param(\"issue_number\")!, 10);\n if (!Number.isFinite(issueNumber)) throw notFoundResponse();\n\n const issue = findIssueByNumber(gh, repo.id, issueNumber);\n if (!issue) throw notFoundResponse();\n\n setIssueLabelIds(gh, issue, []);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/milestones\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const stateQ = c.req.query(\"state\") ?? \"open\";\n const state: \"open\" | \"closed\" | \"all\" =\n stateQ === \"closed\" || stateQ === \"all\" || stateQ === \"open\" ? stateQ : \"open\";\n\n const sortRaw = c.req.query(\"sort\") ?? \"due_on\";\n const sort: \"due_on\" | \"completeness\" = sortRaw === \"completeness\" ? \"completeness\" : \"due_on\";\n\n const dirRaw = c.req.query(\"direction\") ?? \"desc\";\n const direction: \"asc\" | \"desc\" = dirRaw === \"asc\" ? \"asc\" : \"desc\";\n\n let list = gh.milestones.findBy(\"repo_id\", repo.id).map((m) => recalcMilestoneIssueCounts(gh, repo.id, m.id)!);\n\n if (state === \"open\") list = list.filter((m) => m.state === \"open\");\n else if (state === \"closed\") list = list.filter((m) => m.state === \"closed\");\n\n list = sortMilestones(list, sort, direction);\n\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n return c.json(pageItems.map((m) => formatMilestone(m, repo, gh, baseUrl)));\n });\n\n app.post(\"/repos/:owner/:repo/milestones\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const title = typeof body.title === \"string\" ? body.title.trim() : \"\";\n if (!title) throw new ApiError(422, \"Validation failed\");\n\n let state: \"open\" | \"closed\" = \"open\";\n if (body.state === \"open\" || body.state === \"closed\") state = body.state;\n\n const description =\n typeof body.description === \"string\" || body.description === null ? (body.description as string | null) : null;\n\n let due_on: string | null = null;\n if (\"due_on\" in body) {\n if (body.due_on === null) {\n due_on = null;\n } else if (typeof body.due_on === \"string\") {\n due_on = body.due_on;\n } else {\n throw new ApiError(422, \"Validation failed\");\n }\n }\n\n const num = getNextMilestoneNumber(gh, repo.id);\n const closed_at = state === \"closed\" ? timestamp() : null;\n\n const row = gh.milestones.insert({\n node_id: \"\",\n repo_id: repo.id,\n number: num,\n title,\n description,\n state,\n open_issues: 0,\n closed_issues: 0,\n due_on,\n closed_at,\n creator_id: actor.id,\n } as Omit<GitHubMilestone, \"id\" | \"created_at\" | \"updated_at\">);\n gh.milestones.update(row.id, { node_id: generateNodeId(\"Milestone\", row.id) });\n const m = recalcMilestoneIssueCounts(gh, repo.id, row.id)!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"milestone\",\n state === \"closed\" ? \"closed\" : \"created\",\n {\n action: state === \"closed\" ? \"closed\" : \"created\",\n milestone: formatMilestone(m, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.json(formatMilestone(m, repo, gh, baseUrl), 201);\n });\n\n app.get(\"/repos/:owner/:repo/milestones/:milestone_number\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const n = parseInt(c.req.param(\"milestone_number\")!, 10);\n if (!Number.isFinite(n)) throw notFoundResponse();\n\n const raw = gh.milestones.findBy(\"repo_id\", repo.id).find((m) => m.number === n);\n if (!raw) throw notFoundResponse();\n const m = recalcMilestoneIssueCounts(gh, repo.id, raw.id)!;\n return c.json(formatMilestone(m, repo, gh, baseUrl));\n });\n\n app.patch(\"/repos/:owner/:repo/milestones/:milestone_number\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const n = parseInt(c.req.param(\"milestone_number\")!, 10);\n if (!Number.isFinite(n)) throw notFoundResponse();\n\n let m = gh.milestones.findBy(\"repo_id\", repo.id).find((x) => x.number === n);\n if (!m) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubMilestone> = {};\n\n if (typeof body.title === \"string\") patch.title = body.title;\n if (body.state === \"open\" || body.state === \"closed\") {\n patch.state = body.state;\n }\n if (\"description\" in body) {\n patch.description =\n typeof body.description === \"string\" || body.description === null ? (body.description as string | null) : null;\n }\n if (\"due_on\" in body) {\n if (body.due_on === null) patch.due_on = null;\n else if (typeof body.due_on === \"string\") patch.due_on = body.due_on;\n else throw new ApiError(422, \"Validation failed\");\n }\n\n const prevState = m.state;\n if (patch.state === \"closed\" && prevState === \"open\") {\n patch.closed_at = m.closed_at ?? timestamp();\n } else if (patch.state === \"open\" && prevState === \"closed\") {\n patch.closed_at = null;\n }\n\n const updated = gh.milestones.update(m.id, patch);\n if (!updated) throw notFoundResponse();\n m = recalcMilestoneIssueCounts(gh, repo.id, updated.id)!;\n\n const ownerLogin = ownerLoginOf(gh, repo);\n if (patch.state === \"closed\" && prevState === \"open\") {\n webhooks.dispatch(\n \"milestone\",\n \"closed\",\n {\n action: \"closed\",\n milestone: formatMilestone(m, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n } else if (patch.state === \"open\" && prevState === \"closed\") {\n webhooks.dispatch(\n \"milestone\",\n \"opened\",\n {\n action: \"opened\",\n milestone: formatMilestone(m, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n } else {\n webhooks.dispatch(\n \"milestone\",\n \"edited\",\n {\n action: \"edited\",\n milestone: formatMilestone(m, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n }\n\n return c.json(formatMilestone(m, repo, gh, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/milestones/:milestone_number\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertIssueWrite(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const n = parseInt(c.req.param(\"milestone_number\")!, 10);\n if (!Number.isFinite(n)) throw notFoundResponse();\n\n const m = gh.milestones.findBy(\"repo_id\", repo.id).find((x) => x.number === n);\n if (!m) throw notFoundResponse();\n\n for (const i of gh.issues.findBy(\"repo_id\", repo.id)) {\n if (i.milestone_id === m.id) gh.issues.update(i.id, { milestone_id: null });\n }\n for (const p of gh.pullRequests.findBy(\"repo_id\", repo.id)) {\n if (p.milestone_id === m.id) gh.pullRequests.update(p.id, { milestone_id: null });\n }\n\n gh.milestones.delete(m.id);\n\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"milestone\",\n \"deleted\",\n {\n action: \"deleted\",\n milestone: formatMilestone(m, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/milestones/:milestone_number/labels\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n if (!repo.has_issues) throw notFoundResponse();\n\n const n = parseInt(c.req.param(\"milestone_number\")!, 10);\n if (!Number.isFinite(n)) throw notFoundResponse();\n\n const ms = gh.milestones.findBy(\"repo_id\", repo.id).find((m) => m.number === n);\n if (!ms) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n\n const labelIdSet = new Set<number>();\n for (const i of gh.issues.findBy(\"repo_id\", repo.id)) {\n if (i.milestone_id !== ms.id) continue;\n for (const lid of i.label_ids) labelIdSet.add(lid);\n }\n\n const labels = [...labelIdSet].map((id) => gh.labels.get(id)).filter(Boolean) as GitHubLabel[];\n labels.sort((a, b) => a.name.localeCompare(b.name));\n\n const total = labels.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = labels.slice(start, start + per_page);\n return c.json(pageItems.map((l) => formatLabel(l, repo, baseUrl)));\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubBlob,\n GitHubBranch,\n GitHubBranchProtection,\n GitHubCommit,\n GitHubRef,\n GitHubRepo,\n GitHubTag,\n GitHubTree,\n GitHubUser,\n} from \"../entities.js\";\nimport {\n formatBranch,\n formatRepo,\n formatUser,\n generateNodeId,\n generateSha,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\nimport {\n assertAuthenticatedUser,\n assertRepoAdmin,\n assertRepoRead,\n assertRepoWrite,\n getActorUser,\n notFoundResponse,\n ownerLoginOf,\n} from \"../route-helpers.js\";\n\nfunction findBranchByName(gh: GitHubStore, repoId: number, name: string) {\n return gh.branches.findBy(\"repo_id\", repoId).find((b) => b.name === name);\n}\n\nfunction findCommitBySha(gh: GitHubStore, repoId: number, sha: string) {\n return gh.commits.findBy(\"repo_id\", repoId).find((c) => c.sha === sha);\n}\n\nfunction findTreeBySha(gh: GitHubStore, repoId: number, sha: string) {\n return gh.trees.findBy(\"repo_id\", repoId).find((t) => t.sha === sha);\n}\n\nfunction findBlobBySha(gh: GitHubStore, repoId: number, sha: string) {\n return gh.blobs.findBy(\"repo_id\", repoId).find((b) => b.sha === sha);\n}\n\nfunction findTagObjectBySha(gh: GitHubStore, repoId: number, sha: string) {\n return gh.tags.findBy(\"repo_id\", repoId).find((t) => t.sha === sha);\n}\n\nfunction fullRefFromParam(refParam: string): string {\n return refParam.startsWith(\"refs/\") ? refParam : `refs/${refParam}`;\n}\n\nfunction isDescendantOf(gh: GitHubStore, repoId: number, ancestorSha: string, descendantSha: string): boolean {\n const visiting = new Set<string>();\n const stack = [descendantSha];\n while (stack.length) {\n const sha = stack.pop()!;\n if (sha === ancestorSha) return true;\n if (visiting.has(sha)) continue;\n visiting.add(sha);\n const commit = findCommitBySha(gh, repoId, sha);\n if (!commit) continue;\n for (const p of commit.parent_shas) stack.push(p);\n }\n return false;\n}\n\nfunction resolveGitObjectType(gh: GitHubStore, repoId: number, sha: string): \"commit\" | \"tag\" | \"blob\" | \"tree\" {\n if (findCommitBySha(gh, repoId, sha)) return \"commit\";\n if (findTagObjectBySha(gh, repoId, sha)) return \"tag\";\n if (findTreeBySha(gh, repoId, sha)) return \"tree\";\n if (findBlobBySha(gh, repoId, sha)) return \"blob\";\n return \"commit\";\n}\n\nfunction objectApiUrl(\n repo: GitHubRepo,\n baseUrl: string,\n type: \"commit\" | \"tag\" | \"blob\" | \"tree\",\n sha: string,\n): string {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n switch (type) {\n case \"commit\":\n return `${repoUrl}/git/commits/${sha}`;\n case \"tag\":\n return `${repoUrl}/git/tags/${sha}`;\n case \"tree\":\n return `${repoUrl}/git/trees/${sha}`;\n default:\n return `${repoUrl}/git/blobs/${sha}`;\n }\n}\n\nfunction formatRefJson(gh: GitHubStore, repo: GitHubRepo, fullRef: string, sha: string, baseUrl: string) {\n const refRec = gh.refs.findBy(\"repo_id\", repo.id).find((r) => r.ref === fullRef);\n const type = resolveGitObjectType(gh, repo.id, sha);\n const shortRef = fullRef.startsWith(\"refs/\") ? fullRef.slice(5) : fullRef;\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n ref: fullRef,\n node_id: refRec?.node_id ?? \"\",\n url: `${repoUrl}/git/ref/${shortRef}`,\n object: {\n type,\n sha,\n url: objectApiUrl(repo, baseUrl, type, sha),\n },\n };\n}\n\nfunction syncBranchFromRef(gh: GitHubStore, repo: GitHubRepo, fullRef: string, sha: string) {\n if (!fullRef.startsWith(\"refs/heads/\")) return;\n const name = fullRef.slice(\"refs/heads/\".length);\n const existing = findBranchByName(gh, repo.id, name);\n if (existing) {\n gh.branches.update(existing.id, { sha });\n } else {\n gh.branches.insert({\n repo_id: repo.id,\n name,\n sha,\n protected: false,\n } as Omit<GitHubBranch, \"id\" | \"created_at\" | \"updated_at\">);\n }\n}\n\nfunction deleteBranchForHeadRef(gh: GitHubStore, repoId: number, fullRef: string) {\n if (!fullRef.startsWith(\"refs/heads/\")) return;\n const name = fullRef.slice(\"refs/heads/\".length);\n const b = findBranchByName(gh, repoId, name);\n if (b) gh.branches.delete(b.id);\n}\n\nfunction expandTreeEntries(\n gh: GitHubStore,\n repoId: number,\n entries: GitHubTree[\"tree\"],\n recursive: boolean,\n prefix = \"\",\n): GitHubTree[\"tree\"] {\n const out: GitHubTree[\"tree\"] = [];\n for (const e of entries) {\n const path = prefix ? `${prefix}/${e.path}` : e.path;\n if (e.type === \"blob\") {\n out.push({ ...e, path });\n } else if (e.type === \"tree\" && recursive) {\n const sub = findTreeBySha(gh, repoId, e.sha);\n if (sub) {\n out.push(...expandTreeEntries(gh, repoId, sub.tree, true, path));\n } else {\n out.push({ ...e, path });\n }\n } else {\n out.push({ ...e, path });\n }\n }\n return out.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nfunction formatCommitJson(gh: GitHubStore, repo: GitHubRepo, c: GitHubCommit, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const htmlUrl = `${baseUrl}/${repo.full_name}/commit/${c.sha}`;\n const authorUser = c.user_id ? gh.users.get(c.user_id) : null;\n return {\n sha: c.sha,\n node_id: c.node_id,\n url: `${repoUrl}/git/commits/${c.sha}`,\n html_url: htmlUrl,\n author: authorUser ? formatUser(authorUser, baseUrl) : null,\n committer: authorUser ? formatUser(authorUser, baseUrl) : null,\n parents: c.parent_shas.map((sha) => ({\n sha,\n url: `${repoUrl}/git/commits/${sha}`,\n })),\n stats: { total: 0, additions: 0, deletions: 0 },\n files: [],\n commit: {\n author: {\n name: c.author_name,\n email: c.author_email,\n date: c.author_date,\n },\n committer: {\n name: c.committer_name,\n email: c.committer_email,\n date: c.committer_date,\n },\n message: c.message,\n tree: { sha: c.tree_sha, url: `${repoUrl}/git/trees/${c.tree_sha}` },\n url: `${repoUrl}/git/commits/${c.sha}`,\n comment_count: 0,\n verification: { verified: false, reason: \"unsigned\", signature: null, payload: null, verified_at: null },\n },\n };\n}\n\nfunction protectionEntityToGitHub(gh: GitHubStore, repo: GitHubRepo, bp: GitHubBranchProtection, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const encBranch = encodeURIComponent(bp.branch_name);\n const base = `${repoUrl}/branches/${encBranch}/protection`;\n return {\n url: base,\n required_status_checks: bp.required_status_checks\n ? {\n url: `${base}/required_status_checks`,\n strict: bp.required_status_checks.strict,\n contexts: bp.required_status_checks.contexts,\n contexts_url: `${base}/required_status_checks/contexts`,\n checks: bp.required_status_checks.contexts.map((c) => ({\n context: c,\n app_id: null,\n })),\n }\n : null,\n enforce_admins: {\n url: `${base}/enforce_admins`,\n enabled: bp.enforce_admins,\n },\n required_pull_request_reviews: bp.required_pull_request_reviews\n ? {\n url: `${base}/required_pull_request_reviews`,\n dismiss_stale_reviews: bp.required_pull_request_reviews.dismiss_stale_reviews,\n require_code_owner_reviews: bp.required_pull_request_reviews.require_code_owner_reviews,\n required_approving_review_count: bp.required_pull_request_reviews.required_approving_review_count,\n }\n : null,\n restrictions: bp.restrictions\n ? {\n url: `${base}/restrictions`,\n users_url: `${base}/restrictions/users`,\n teams_url: `${base}/restrictions/teams`,\n apps_url: `${base}/restrictions/apps`,\n users: bp.restrictions.users.map((login) => ({\n login,\n id: 0,\n node_id: \"\",\n avatar_url: `${baseUrl}/avatars/u/${login}`,\n gravatar_id: \"\",\n url: `${baseUrl}/users/${login}`,\n html_url: `${baseUrl}/${login}`,\n type: \"User\",\n site_admin: false,\n })),\n teams: bp.restrictions.teams.map((slug) => ({\n id: 0,\n node_id: \"\",\n url: `${baseUrl}/teams/0`,\n name: slug,\n slug,\n })),\n apps: [],\n }\n : null,\n required_linear_history: { enabled: bp.required_linear_history },\n allow_force_pushes: { enabled: bp.allow_force_pushes },\n allow_deletions: { enabled: bp.allow_deletions },\n required_conversation_resolution: { enabled: false },\n required_signatures: { url: `${base}/required_signatures`, enabled: bp.required_signatures },\n lock_branch: { enabled: false },\n allow_fork_syncing: { enabled: false },\n };\n}\n\nfunction parseProtectionPutBody(\n body: Record<string, unknown>,\n): Omit<GitHubBranchProtection, \"id\" | \"repo_id\" | \"branch_name\" | \"created_at\" | \"updated_at\"> {\n const rsc = body.required_status_checks;\n let required_status_checks: GitHubBranchProtection[\"required_status_checks\"] = null;\n if (rsc && typeof rsc === \"object\" && rsc !== null) {\n const o = rsc as Record<string, unknown>;\n required_status_checks = {\n strict: Boolean(o.strict),\n contexts: Array.isArray(o.contexts) ? o.contexts.filter((x): x is string => typeof x === \"string\") : [],\n };\n }\n\n let enforce_admins = false;\n const ea = body.enforce_admins;\n if (typeof ea === \"boolean\") enforce_admins = ea;\n else if (ea && typeof ea === \"object\" && \"enabled\" in ea) {\n enforce_admins = Boolean((ea as { enabled?: unknown }).enabled);\n }\n\n const rprr = body.required_pull_request_reviews;\n let required_pull_request_reviews: GitHubBranchProtection[\"required_pull_request_reviews\"] = null;\n if (rprr && typeof rprr === \"object\" && rprr !== null) {\n const o = rprr as Record<string, unknown>;\n required_pull_request_reviews = {\n required_approving_review_count:\n typeof o.required_approving_review_count === \"number\" ? o.required_approving_review_count : 1,\n dismiss_stale_reviews: Boolean(o.dismiss_stale_reviews),\n require_code_owner_reviews: Boolean(o.require_code_owner_reviews),\n };\n }\n\n const rest = body.restrictions;\n let restrictions: GitHubBranchProtection[\"restrictions\"] = null;\n if (rest && typeof rest === \"object\" && rest !== null) {\n const o = rest as Record<string, unknown>;\n restrictions = {\n users: Array.isArray(o.users)\n ? o.users\n .map((u) => (typeof u === \"string\" ? u : (u as { login?: string })?.login))\n .filter((x): x is string => typeof x === \"string\")\n : [],\n teams: Array.isArray(o.teams)\n ? o.teams\n .map((t) => (typeof t === \"string\" ? t : (t as { slug?: string })?.slug))\n .filter((x): x is string => typeof x === \"string\")\n : [],\n };\n }\n\n const rlh = body.required_linear_history;\n const required_linear_history =\n typeof rlh === \"boolean\"\n ? rlh\n : rlh && typeof rlh === \"object\" && rlh !== null\n ? Boolean((rlh as { enabled?: unknown }).enabled)\n : false;\n const afp = body.allow_force_pushes;\n const allow_force_pushes =\n typeof afp === \"boolean\"\n ? afp\n : afp && typeof afp === \"object\" && afp !== null\n ? Boolean((afp as { enabled?: unknown }).enabled)\n : false;\n const ad = body.allow_deletions;\n const allow_deletions =\n typeof ad === \"boolean\"\n ? ad\n : ad && typeof ad === \"object\" && ad !== null\n ? Boolean((ad as { enabled?: unknown }).enabled)\n : false;\n\n return {\n required_status_checks,\n enforce_admins,\n required_pull_request_reviews,\n restrictions,\n required_linear_history,\n allow_force_pushes,\n allow_deletions,\n required_signatures: Boolean(\n typeof body.required_signatures === \"boolean\"\n ? body.required_signatures\n : (body.required_signatures as { enabled?: boolean } | undefined)?.enabled,\n ),\n };\n}\n\nexport function branchesAndGitRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n // --- Branches: sub-routes before generic protection/branch ---\n\n app.get(\"/repos/:owner/:repo/branches/:branch{.+}/protection/required_status_checks\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp || !bp.required_status_checks) throw notFoundResponse();\n const encBranch = encodeURIComponent(branch);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const base = `${repoUrl}/branches/${encBranch}/protection/required_status_checks`;\n return c.json({\n url: base,\n strict: bp.required_status_checks.strict,\n contexts: bp.required_status_checks.contexts,\n contexts_url: `${base}/contexts`,\n checks: bp.required_status_checks.contexts.map((ctx) => ({\n context: ctx,\n app_id: null,\n })),\n });\n });\n\n app.patch(\"/repos/:owner/:repo/branches/:branch{.+}/protection/required_status_checks\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp) throw notFoundResponse();\n const body = await parseJsonBody(c);\n const strict = typeof body.strict === \"boolean\" ? body.strict : (bp.required_status_checks?.strict ?? false);\n const contexts = Array.isArray(body.contexts)\n ? body.contexts.filter((x): x is string => typeof x === \"string\")\n : (bp.required_status_checks?.contexts ?? []);\n gh.branchProtections.update(bp.id, {\n required_status_checks: { strict, contexts },\n });\n const encBranch = encodeURIComponent(branch);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const url = `${repoUrl}/branches/${encBranch}/protection/required_status_checks`;\n return c.json({\n url,\n strict,\n contexts,\n contexts_url: `${url}/contexts`,\n checks: contexts.map((ctx) => ({ context: ctx, app_id: null })),\n });\n });\n\n app.get(\"/repos/:owner/:repo/branches/:branch{.+}/protection/enforce_admins\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp) throw notFoundResponse();\n const encBranch = encodeURIComponent(branch);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const url = `${repoUrl}/branches/${encBranch}/protection/enforce_admins`;\n return c.json({\n url,\n enabled: bp.enforce_admins,\n });\n });\n\n app.get(\"/repos/:owner/:repo/branches/:branch{.+}/protection/required_pull_request_reviews\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp || !bp.required_pull_request_reviews) throw notFoundResponse();\n const encBranch = encodeURIComponent(branch);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const base = `${repoUrl}/branches/${encBranch}/protection/required_pull_request_reviews`;\n const r = bp.required_pull_request_reviews;\n return c.json({\n url: base,\n dismiss_stale_reviews: r.dismiss_stale_reviews,\n require_code_owner_reviews: r.require_code_owner_reviews,\n required_approving_review_count: r.required_approving_review_count,\n });\n });\n\n app.patch(\"/repos/:owner/:repo/branches/:branch{.+}/protection/required_pull_request_reviews\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp) throw notFoundResponse();\n const body = await parseJsonBody(c);\n const prev = bp.required_pull_request_reviews ?? {\n required_approving_review_count: 1,\n dismiss_stale_reviews: false,\n require_code_owner_reviews: false,\n };\n const next = {\n required_approving_review_count:\n typeof body.required_approving_review_count === \"number\"\n ? body.required_approving_review_count\n : prev.required_approving_review_count,\n dismiss_stale_reviews:\n typeof body.dismiss_stale_reviews === \"boolean\" ? body.dismiss_stale_reviews : prev.dismiss_stale_reviews,\n require_code_owner_reviews:\n typeof body.require_code_owner_reviews === \"boolean\"\n ? body.require_code_owner_reviews\n : prev.require_code_owner_reviews,\n };\n gh.branchProtections.update(bp.id, { required_pull_request_reviews: next });\n const encBranch = encodeURIComponent(branch);\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const url = `${repoUrl}/branches/${encBranch}/protection/required_pull_request_reviews`;\n return c.json({\n url,\n ...next,\n });\n });\n\n app.get(\"/repos/:owner/:repo/branches/:branch{.+}/protection\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (!bp) throw notFoundResponse();\n return c.json(protectionEntityToGitHub(gh, repo, bp, baseUrl));\n });\n\n app.put(\"/repos/:owner/:repo/branches/:branch{.+}/protection\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const b = findBranchByName(gh, repo.id, branch);\n if (!b) throw notFoundResponse();\n const body = await parseJsonBody(c);\n const parsed = parseProtectionPutBody(body);\n const existing = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (existing) {\n gh.branchProtections.update(existing.id, { ...parsed });\n } else {\n gh.branchProtections.insert({\n repo_id: repo.id,\n branch_name: branch,\n ...parsed,\n } as Omit<GitHubBranchProtection, \"id\" | \"created_at\" | \"updated_at\">);\n }\n gh.branches.update(b.id, { protected: true });\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch)!;\n webhooks.dispatch(\n \"branch_protection_rule\",\n \"edited\",\n {\n action: \"edited\",\n rule: protectionEntityToGitHub(gh, repo, bp, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n },\n ownerLoginOf(gh, repo),\n repo.name,\n );\n return c.json(protectionEntityToGitHub(gh, repo, bp, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/branches/:branch{.+}/protection\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branch = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branch);\n if (bp) gh.branchProtections.delete(bp.id);\n const b = findBranchByName(gh, repo.id, branch);\n if (b) gh.branches.update(b.id, { protected: false });\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/branches/:branch{.+}\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const branchName = decodeURIComponent(c.req.param(\"branch\")!);\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const branch = findBranchByName(gh, repo.id, branchName);\n if (!branch) throw notFoundResponse();\n const commit = findCommitBySha(gh, repo.id, branch.sha);\n const base = formatBranch(branch, repo, baseUrl);\n if (!branch.protected) return c.json(base);\n const bp = gh.branchProtections.findBy(\"repo_id\", repo.id).find((p) => p.branch_name === branchName);\n return c.json({\n ...base,\n protection: {\n enabled: true,\n required_status_checks: bp?.required_status_checks\n ? {\n enforcement_level: \"everyone\",\n contexts: bp.required_status_checks.contexts,\n checks: bp.required_status_checks.contexts.map((ctx) => ({ context: ctx, app_id: null })),\n }\n : { enforcement_level: \"off\", contexts: [], checks: [] },\n },\n protection_commit: commit\n ? {\n author: { email: commit.author_email, name: commit.author_name },\n url: `${baseUrl}/repos/${repo.full_name}/commits/${commit.sha}`,\n message: commit.message,\n html_url: `${baseUrl}/${repo.full_name}/commit/${commit.sha}`,\n }\n : null,\n });\n });\n\n app.get(\"/repos/:owner/:repo/branches\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n let list = [...gh.branches.findBy(\"repo_id\", repo.id)].sort((a, b) => a.name.localeCompare(b.name));\n const prot = c.req.query(\"protected\");\n if (prot === \"true\") list = list.filter((b) => b.protected);\n else if (prot === \"false\") list = list.filter((b) => !b.protected);\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n const start = (page - 1) * per_page;\n const slice = list.slice(start, start + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((b) => formatBranch(b, repo, baseUrl)));\n });\n\n // --- Git refs ---\n\n app.get(\"/repos/:owner/:repo/git/ref/:ref{.+}\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const refParam = c.req.param(\"ref\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const fullRef = fullRefFromParam(refParam);\n const r = gh.refs.findBy(\"repo_id\", repo.id).find((x) => x.ref === fullRef);\n if (!r) throw notFoundResponse();\n return c.json(formatRefJson(gh, repo, r.ref, r.sha, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/git/matching-refs/:ref{.+}\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const refParam = c.req.param(\"ref\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const prefix = fullRefFromParam(refParam);\n const matches = gh.refs\n .findBy(\"repo_id\", repo.id)\n .filter((r) => r.ref.startsWith(prefix))\n .sort((a, b) => a.ref.localeCompare(b.ref));\n return c.json(matches.map((r) => formatRefJson(gh, repo, r.ref, r.sha, baseUrl)));\n });\n\n app.post(\"/repos/:owner/:repo/git/refs\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const user = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = (await parseJsonBody(c)) as { ref?: unknown; sha?: unknown };\n if (typeof body.ref !== \"string\" || !body.ref.startsWith(\"refs/\")) {\n throw new ApiError(422, \"Invalid ref\");\n }\n if (typeof body.sha !== \"string\") {\n throw new ApiError(422, \"sha is required\");\n }\n const fullRef = body.ref;\n const sha = body.sha;\n if (findCommitBySha(gh, repo.id, sha) === undefined && findTagObjectBySha(gh, repo.id, sha) === undefined) {\n throw new ApiError(422, \"Invalid sha\");\n }\n if (gh.refs.findBy(\"repo_id\", repo.id).some((r) => r.ref === fullRef)) {\n throw new ApiError(422, \"Reference already exists\");\n }\n const refRow = gh.refs.insert({\n repo_id: repo.id,\n ref: fullRef,\n sha,\n node_id: \"\",\n } as Omit<GitHubRef, \"id\" | \"created_at\" | \"updated_at\">);\n gh.refs.update(refRow.id, { node_id: generateNodeId(\"Ref\", refRow.id) });\n syncBranchFromRef(gh, repo, fullRef, sha);\n webhooks.dispatch(\n \"create\",\n undefined,\n {\n ref: fullRef,\n ref_type: fullRef.startsWith(\"refs/heads/\") ? \"branch\" : \"tag\",\n master_branch: repo.default_branch,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(user, baseUrl),\n },\n ownerLoginOf(gh, repo),\n repo.name,\n );\n const r = gh.refs.get(refRow.id)!;\n return c.json(formatRefJson(gh, repo, r.ref, r.sha, baseUrl), 201);\n });\n\n app.patch(\"/repos/:owner/:repo/git/refs/:ref{.+}\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const refParam = c.req.param(\"ref\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const user = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const fullRef = fullRefFromParam(refParam);\n const r = gh.refs.findBy(\"repo_id\", repo.id).find((x) => x.ref === fullRef);\n if (!r) throw notFoundResponse();\n const body = (await parseJsonBody(c)) as { sha?: unknown; force?: unknown };\n if (typeof body.sha !== \"string\") {\n throw new ApiError(422, \"sha is required\");\n }\n const newSha = body.sha;\n const force = Boolean(body.force);\n const oldSha = r.sha;\n if (findCommitBySha(gh, repo.id, newSha) === undefined && findTagObjectBySha(gh, repo.id, newSha) === undefined) {\n throw new ApiError(422, \"Invalid sha\");\n }\n if (!force) {\n const oldCommit = findCommitBySha(gh, repo.id, oldSha);\n const newCommit = findCommitBySha(gh, repo.id, newSha);\n if (!oldCommit || !newCommit) {\n throw new ApiError(422, \"Fast-forward update requires commit objects\");\n }\n if (!isDescendantOf(gh, repo.id, oldSha, newSha)) {\n throw new ApiError(422, \"Update is not a fast-forward\");\n }\n }\n gh.refs.update(r.id, { sha: newSha });\n syncBranchFromRef(gh, repo, fullRef, newSha);\n webhooks.dispatch(\n \"push\",\n undefined,\n {\n ref: fullRef,\n before: oldSha,\n after: newSha,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(user, baseUrl),\n },\n ownerLoginOf(gh, repo),\n repo.name,\n );\n const updated = gh.refs.get(r.id)!;\n return c.json(formatRefJson(gh, repo, updated.ref, updated.sha, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/git/refs/:ref{.+}\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const refParam = c.req.param(\"ref\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const fullRef = fullRefFromParam(refParam);\n const r = gh.refs.findBy(\"repo_id\", repo.id).find((x) => x.ref === fullRef);\n if (!r) throw notFoundResponse();\n gh.refs.delete(r.id);\n deleteBranchForHeadRef(gh, repo.id, fullRef);\n return c.body(null, 204);\n });\n\n // --- Git commits ---\n\n app.get(\"/repos/:owner/:repo/git/commits/:commit_sha\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const commitSha = c.req.param(\"commit_sha\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const commit = findCommitBySha(gh, repo.id, commitSha);\n if (!commit) throw notFoundResponse();\n return c.json(formatCommitJson(gh, repo, commit, baseUrl));\n });\n\n app.post(\"/repos/:owner/:repo/git/commits\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n if (typeof body.message !== \"string\") throw new ApiError(422, \"message is required\");\n if (typeof body.tree !== \"string\") throw new ApiError(422, \"tree is required\");\n if (!Array.isArray(body.parents)) throw new ApiError(422, \"parents must be an array\");\n const parents = body.parents.filter((p): p is string => typeof p === \"string\");\n const treeSha = body.tree as string;\n if (!findTreeBySha(gh, repo.id, treeSha)) throw new ApiError(422, \"Invalid tree\");\n for (const p of parents) {\n if (!findCommitBySha(gh, repo.id, p)) throw new ApiError(422, `Invalid parent ${p}`);\n }\n let author_name: string;\n let author_email: string;\n let author_date: string;\n let committer_name: string;\n let committer_email: string;\n let committer_date: string;\n const now = timestamp();\n const actor = getActorUser(gh, c.get(\"authUser\")!);\n const defaultName = actor?.name ?? actor?.login ?? \"user\";\n const defaultEmail = actor?.email ?? `${actor?.login ?? \"user\"}@users.noreply.github.com`;\n if (body.author && typeof body.author === \"object\" && body.author !== null) {\n const a = body.author as Record<string, unknown>;\n author_name = typeof a.name === \"string\" ? a.name : defaultName;\n author_email = typeof a.email === \"string\" ? a.email : defaultEmail;\n author_date = typeof a.date === \"string\" ? a.date : now;\n } else {\n author_name = defaultName;\n author_email = defaultEmail;\n author_date = now;\n }\n if (body.committer && typeof body.committer === \"object\" && body.committer !== null) {\n const a = body.committer as Record<string, unknown>;\n committer_name = typeof a.name === \"string\" ? a.name : defaultName;\n committer_email = typeof a.email === \"string\" ? a.email : defaultEmail;\n committer_date = typeof a.date === \"string\" ? a.date : now;\n } else {\n committer_name = author_name;\n committer_email = author_email;\n committer_date = author_date;\n }\n const commit = gh.commits.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n message: body.message as string,\n author_name,\n author_email,\n author_date,\n committer_name,\n committer_email,\n committer_date,\n tree_sha: treeSha,\n parent_shas: parents,\n user_id: actor?.id ?? null,\n } as Omit<GitHubCommit, \"id\" | \"created_at\" | \"updated_at\">);\n gh.commits.update(commit.id, { node_id: generateNodeId(\"Commit\", commit.id) });\n const saved = gh.commits.get(commit.id)!;\n return c.json(formatCommitJson(gh, repo, saved, baseUrl), 201);\n });\n\n // --- Git trees ---\n\n app.get(\"/repos/:owner/:repo/git/trees/:tree_sha\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const treeSha = c.req.param(\"tree_sha\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const tree = findTreeBySha(gh, repo.id, treeSha);\n if (!tree) throw notFoundResponse();\n const recursive = c.req.query(\"recursive\") === \"1\" || c.req.query(\"recursive\") === \"true\";\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const entries = recursive\n ? expandTreeEntries(gh, repo.id, tree.tree, true)\n : tree.tree.filter((e) => !e.path.includes(\"/\"));\n return c.json({\n sha: tree.sha,\n url: `${repoUrl}/git/trees/${tree.sha}`,\n tree: entries,\n truncated: tree.truncated,\n });\n });\n\n app.post(\"/repos/:owner/:repo/git/trees\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n if (!Array.isArray(body.tree)) throw new ApiError(422, \"tree array is required\");\n const items = body.tree as Array<{\n path?: string;\n mode?: string;\n type?: string;\n sha?: string;\n content?: string;\n }>;\n const pathMap = new Map<string, { mode: string; type: \"blob\" | \"tree\"; sha: string; size?: number }>();\n\n const baseTreeSha = typeof body.base_tree === \"string\" ? body.base_tree : undefined;\n if (baseTreeSha) {\n const base = findTreeBySha(gh, repo.id, baseTreeSha);\n if (!base) throw new ApiError(422, \"Invalid base_tree\");\n for (const e of base.tree) {\n pathMap.set(e.path, { mode: e.mode, type: e.type, sha: e.sha, size: e.size });\n }\n }\n\n for (const raw of items) {\n if (\n typeof raw.path !== \"string\" ||\n typeof raw.mode !== \"string\" ||\n (raw.type !== \"blob\" && raw.type !== \"tree\")\n ) {\n throw new ApiError(422, \"Each tree entry needs path, mode, type (blob|tree)\");\n }\n if (raw.sha !== undefined && raw.content !== undefined) {\n throw new ApiError(422, \"Cannot pass both sha and content\");\n }\n let sha = raw.sha;\n if (raw.content !== undefined) {\n const buf = Buffer.from(String(raw.content), \"utf8\");\n const blob = gh.blobs.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n content: String(raw.content),\n encoding: \"utf-8\",\n size: buf.byteLength,\n } as Omit<GitHubBlob, \"id\" | \"created_at\" | \"updated_at\">);\n gh.blobs.update(blob.id, { node_id: generateNodeId(\"Blob\", blob.id) });\n sha = blob.sha;\n }\n if (typeof sha !== \"string\") throw new ApiError(422, \"sha or content required\");\n pathMap.set(raw.path, { mode: raw.mode, type: raw.type, sha });\n }\n\n const treeEntries: GitHubTree[\"tree\"] = [...pathMap.entries()].map(([path, v]) => ({\n path,\n mode: v.mode,\n type: v.type,\n sha: v.sha,\n size: v.size,\n }));\n\n const tree = gh.trees.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n tree: treeEntries,\n truncated: false,\n } as Omit<GitHubTree, \"id\" | \"created_at\" | \"updated_at\">);\n gh.trees.update(tree.id, { node_id: generateNodeId(\"Tree\", tree.id) });\n const saved = gh.trees.get(tree.id)!;\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return c.json(\n {\n sha: saved.sha,\n url: `${repoUrl}/git/trees/${saved.sha}`,\n tree: saved.tree,\n truncated: saved.truncated,\n },\n 201,\n );\n });\n\n // --- Git blobs ---\n\n app.get(\"/repos/:owner/:repo/git/blobs/:file_sha\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const fileSha = c.req.param(\"file_sha\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const blob = findBlobBySha(gh, repo.id, fileSha);\n if (!blob) throw notFoundResponse();\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const content = blob.encoding === \"base64\" ? blob.content : Buffer.from(blob.content, \"utf8\").toString(\"base64\");\n return c.json({\n sha: blob.sha,\n node_id: blob.node_id,\n size: blob.size,\n url: `${repoUrl}/git/blobs/${blob.sha}`,\n content,\n encoding: \"base64\",\n });\n });\n\n app.post(\"/repos/:owner/:repo/git/blobs\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = (await parseJsonBody(c)) as {\n content?: unknown;\n encoding?: unknown;\n };\n if (typeof body.content !== \"string\") throw new ApiError(422, \"content is required\");\n const enc = body.encoding === \"base64\" || body.encoding === \"utf-8\" ? body.encoding : \"utf-8\";\n if (enc === \"base64\") {\n const blob = gh.blobs.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n content: body.content,\n encoding: \"base64\",\n size: Buffer.from(body.content, \"base64\").length,\n } as Omit<GitHubBlob, \"id\" | \"created_at\" | \"updated_at\">);\n gh.blobs.update(blob.id, { node_id: generateNodeId(\"Blob\", blob.id) });\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const saved = gh.blobs.get(blob.id)!;\n return c.json(\n {\n sha: saved.sha,\n node_id: saved.node_id,\n url: `${repoUrl}/git/blobs/${saved.sha}`,\n size: saved.size,\n },\n 201,\n );\n }\n const raw = body.content;\n const size = Buffer.byteLength(raw, \"utf8\");\n const blob = gh.blobs.insert({\n repo_id: repo.id,\n sha: generateSha(),\n node_id: \"\",\n content: raw,\n encoding: \"utf-8\",\n size,\n } as Omit<GitHubBlob, \"id\" | \"created_at\" | \"updated_at\">);\n gh.blobs.update(blob.id, { node_id: generateNodeId(\"Blob\", blob.id) });\n const saved = gh.blobs.get(blob.id)!;\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return c.json(\n {\n sha: saved.sha,\n node_id: saved.node_id,\n url: `${repoUrl}/git/blobs/${saved.sha}`,\n size: saved.size,\n },\n 201,\n );\n });\n\n // --- Git tags ---\n\n app.get(\"/repos/:owner/:repo/git/tags/:tag_sha\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const tagSha = c.req.param(\"tag_sha\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const tag = findTagObjectBySha(gh, repo.id, tagSha);\n if (!tag) throw notFoundResponse();\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return c.json({\n tag: tag.tag,\n sha: tag.sha,\n node_id: tag.node_id,\n url: `${repoUrl}/git/tags/${tag.sha}`,\n message: tag.message,\n tagger: {\n name: tag.tagger_name,\n email: tag.tagger_email,\n date: tag.tagger_date,\n },\n object: {\n type: tag.object_type,\n sha: tag.object_sha,\n url: objectApiUrl(repo, baseUrl, resolveGitObjectType(gh, repo.id, tag.object_sha), tag.object_sha),\n },\n verification: { verified: false, reason: \"unsigned\", signature: null, payload: null, verified_at: null },\n });\n });\n\n app.post(\"/repos/:owner/:repo/git/tags\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n if (typeof body.tag !== \"string\") throw new ApiError(422, \"tag is required\");\n if (typeof body.message !== \"string\") throw new ApiError(422, \"message is required\");\n if (typeof body.object !== \"string\") throw new ApiError(422, \"object is required\");\n if (typeof body.type !== \"string\") throw new ApiError(422, \"type is required\");\n const now = timestamp();\n let tagger_name = \"user\";\n let tagger_email = \"user@users.noreply.github.com\";\n let tagger_date = now;\n if (body.tagger && typeof body.tagger === \"object\" && body.tagger !== null) {\n const t = body.tagger as Record<string, unknown>;\n if (typeof t.name === \"string\") tagger_name = t.name;\n if (typeof t.email === \"string\") tagger_email = t.email;\n if (typeof t.date === \"string\") tagger_date = t.date;\n }\n const tag = gh.tags.insert({\n repo_id: repo.id,\n tag: body.tag as string,\n sha: generateSha(),\n node_id: \"\",\n message: body.message as string,\n tagger_name,\n tagger_email,\n tagger_date,\n object_type: body.type as string,\n object_sha: body.object as string,\n } as Omit<GitHubTag, \"id\" | \"created_at\" | \"updated_at\">);\n gh.tags.update(tag.id, { node_id: generateNodeId(\"Tag\", tag.id) });\n const saved = gh.tags.get(tag.id)!;\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return c.json(\n {\n tag: saved.tag,\n sha: saved.sha,\n node_id: saved.node_id,\n url: `${repoUrl}/git/tags/${saved.sha}`,\n message: saved.message,\n tagger: {\n name: saved.tagger_name,\n email: saved.tagger_email,\n date: saved.tagger_date,\n },\n object: {\n type: saved.object_type,\n sha: saved.object_sha,\n url: objectApiUrl(repo, baseUrl, resolveGitObjectType(gh, repo.id, saved.object_sha), saved.object_sha),\n },\n verification: { verified: false, reason: \"unsigned\", signature: null, payload: null, verified_at: null },\n },\n 201,\n );\n });\n}\n","import type { RouteContext, AuthUser } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader, unauthorized, forbidden } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubOrg, GitHubRepo, GitHubTeam, GitHubUser } from \"../entities.js\";\nimport {\n formatOrgBrief,\n formatOrgFull,\n formatRepo,\n formatTeamBrief,\n formatUser,\n generateNodeId,\n lookupOwner,\n lookupRepo,\n} from \"../helpers.js\";\n\nconst MEMBERS_TEAM_SLUG = \"members\";\n\nfunction notFound() {\n return new ApiError(404, \"Not Found\");\n}\n\nfunction requireAuthUser(c: { get: (k: \"authUser\") => AuthUser | undefined }): AuthUser {\n const u = c.get(\"authUser\");\n if (!u) throw unauthorized();\n return u;\n}\n\nfunction requireOrgAdmin(gh: GitHubStore, org: GitHubOrg, auth: AuthUser): void {\n const user = gh.users.findOneBy(\"login\", auth.login);\n if (!user) throw forbidden();\n const role = orgRoleForUser(gh, org.id, user.id);\n if (role !== \"admin\") throw forbidden();\n}\n\nfunction getOrgByLogin(gh: GitHubStore, login: string): GitHubOrg | undefined {\n return gh.orgs.findOneBy(\"login\", login);\n}\n\nfunction teamsForOrg(gh: GitHubStore, orgId: number): GitHubTeam[] {\n return gh.teams.findBy(\"org_id\", orgId);\n}\n\nfunction getTeamByOrgSlug(gh: GitHubStore, org: GitHubOrg, slug: string): GitHubTeam | undefined {\n return teamsForOrg(gh, org.id).find((t) => t.slug === slug);\n}\n\nfunction slugifyFromName(name: string): string {\n const s = name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return s || \"team\";\n}\n\nfunction uniqueTeamSlug(gh: GitHubStore, orgId: number, base: string): string {\n let slug = base;\n let n = 2;\n const taken = (s: string) => teamsForOrg(gh, orgId).some((t) => t.slug === s);\n while (taken(slug)) {\n slug = `${base}-${n}`;\n n += 1;\n }\n return slug;\n}\n\nfunction orgsForAuthenticatedUser(gh: GitHubStore, userId: number): GitHubOrg[] {\n const memberships = gh.teamMembers.findBy(\"user_id\", userId);\n const orgIds = new Set<number>();\n for (const m of memberships) {\n const team = gh.teams.get(m.team_id);\n if (team) orgIds.add(team.org_id);\n }\n const orgs = [...orgIds].map((id) => gh.orgs.get(id)).filter((o): o is GitHubOrg => Boolean(o));\n orgs.sort((a, b) => a.login.localeCompare(b.login));\n return orgs;\n}\n\ntype OrgMemberRow = { user: GitHubUser; orgRole: \"admin\" | \"member\" };\n\nfunction listOrgMembersDeduped(gh: GitHubStore, orgId: number): OrgMemberRow[] {\n const byUser = new Map<number, { user: GitHubUser; isAdmin: boolean }>();\n for (const team of teamsForOrg(gh, orgId)) {\n for (const m of gh.teamMembers.findBy(\"team_id\", team.id)) {\n const user = gh.users.get(m.user_id);\n if (!user) continue;\n const isAdmin = m.role === \"maintainer\";\n const prev = byUser.get(user.id);\n if (!prev) {\n byUser.set(user.id, { user, isAdmin });\n } else {\n byUser.set(user.id, { user, isAdmin: prev.isAdmin || isAdmin });\n }\n }\n }\n return [...byUser.values()]\n .map(({ user, isAdmin }) => ({\n user,\n orgRole: isAdmin ? (\"admin\" as const) : (\"member\" as const),\n }))\n .sort((a, b) => a.user.id - b.user.id);\n}\n\nfunction orgRoleForUser(gh: GitHubStore, orgId: number, userId: number): \"admin\" | \"member\" | null {\n const row = listOrgMembersDeduped(gh, orgId).find((r) => r.user.id === userId);\n return row?.orgRole ?? null;\n}\n\nfunction syncTeamMemberCount(gh: GitHubStore, teamId: number) {\n const n = gh.teamMembers.findBy(\"team_id\", teamId).length;\n gh.teams.update(teamId, { members_count: n });\n}\n\nfunction syncTeamRepoCount(gh: GitHubStore, teamId: number) {\n const n = gh.teamRepos.findBy(\"team_id\", teamId).length;\n gh.teams.update(teamId, { repos_count: n });\n}\n\nfunction findTeamRepo(gh: GitHubStore, teamId: number, repoId: number) {\n return gh.teamRepos.findBy(\"team_id\", teamId).find((r) => r.repo_id === repoId);\n}\n\nfunction getOrCreateMembersTeam(gh: GitHubStore, org: GitHubOrg): GitHubTeam {\n const existing = teamsForOrg(gh, org.id).find((t) => t.slug === MEMBERS_TEAM_SLUG);\n if (existing) return existing;\n const team = gh.teams.insert({\n node_id: \"pending\",\n name: \"Members\",\n slug: MEMBERS_TEAM_SLUG,\n description: null,\n privacy: \"closed\",\n permission: \"pull\",\n org_id: org.id,\n parent_id: null,\n members_count: 0,\n repos_count: 0,\n });\n const fixed = gh.teams.update(team.id, { node_id: generateNodeId(\"Team\", team.id) });\n return fixed ?? team;\n}\n\nfunction deleteTeamCascade(gh: GitHubStore, team: GitHubTeam) {\n for (const child of teamsForOrg(gh, team.org_id).filter((t) => t.parent_id === team.id)) {\n gh.teams.update(child.id, { parent_id: null });\n }\n for (const m of gh.teamMembers.findBy(\"team_id\", team.id)) {\n gh.teamMembers.delete(m.id);\n }\n for (const tr of gh.teamRepos.findBy(\"team_id\", team.id)) {\n gh.teamRepos.delete(tr.id);\n }\n gh.teams.delete(team.id);\n}\n\nfunction removeUserFromAllOrgTeams(gh: GitHubStore, orgId: number, userId: number) {\n for (const team of teamsForOrg(gh, orgId)) {\n const memberships = gh.teamMembers.findBy(\"team_id\", team.id).filter((m) => m.user_id === userId);\n for (const m of memberships) {\n gh.teamMembers.delete(m.id);\n }\n syncTeamMemberCount(gh, team.id);\n }\n}\n\nfunction membershipUrl(baseUrl: string, orgLogin: string, teamSlug: string, userLogin: string) {\n return `${baseUrl}/orgs/${orgLogin}/teams/${teamSlug}/memberships/${userLogin}`;\n}\n\nfunction orgMembershipUrl(baseUrl: string, orgLogin: string, userLogin: string) {\n return `${baseUrl}/orgs/${orgLogin}/memberships/${userLogin}`;\n}\n\nfunction formatTeamMembership(\n baseUrl: string,\n orgLogin: string,\n teamSlug: string,\n user: GitHubUser,\n role: \"member\" | \"maintainer\",\n) {\n return {\n url: membershipUrl(baseUrl, orgLogin, teamSlug, user.login),\n role,\n state: \"active\" as const,\n user: formatUser(user, baseUrl),\n };\n}\n\nexport function orgsAndTeamsRoutes({ app, store, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/organizations\", (c) => {\n const since = Math.max(0, parseInt(c.req.query(\"since\") ?? \"0\", 10) || 0);\n const perPage = Math.min(100, Math.max(1, parseInt(c.req.query(\"per_page\") ?? \"30\", 10) || 30));\n\n const ordered = gh.orgs\n .all()\n .filter((o) => o.id > since)\n .sort((a, b) => a.id - b.id);\n const page = ordered.slice(0, perPage);\n\n if (page.length === perPage && ordered.length > perPage) {\n const lastId = page[page.length - 1]!.id;\n const nextUrl = new URL(c.req.url);\n nextUrl.searchParams.set(\"since\", String(lastId));\n nextUrl.searchParams.set(\"per_page\", String(perPage));\n c.header(\"Link\", `<${nextUrl.toString()}>; rel=\"next\"`);\n }\n\n return c.json(page.map((o) => formatOrgBrief(o, baseUrl)));\n });\n\n app.get(\"/user/orgs\", (c) => {\n const auth = requireAuthUser(c);\n const user = gh.users.findOneBy(\"login\", auth.login);\n if (!user) throw notFound();\n const orgs = orgsForAuthenticatedUser(gh, user.id);\n return c.json(orgs.map((o) => formatOrgBrief(o, baseUrl)));\n });\n\n app.get(\"/orgs/:org\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n return c.json(formatOrgFull(org, baseUrl));\n });\n\n app.patch(\"/orgs/:org\", async (c) => {\n const auth = requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n requireOrgAdmin(gh, org, auth);\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubOrg> = {};\n\n if (\"billing_email\" in body) {\n if (body.billing_email === null) patch.billing_email = null;\n else if (typeof body.billing_email === \"string\") patch.billing_email = body.billing_email;\n }\n if (\"company\" in body) {\n if (body.company === null) patch.company = null;\n else if (typeof body.company === \"string\") patch.company = body.company;\n }\n if (\"email\" in body) {\n if (body.email === null) patch.email = null;\n else if (typeof body.email === \"string\") patch.email = body.email;\n }\n if (\"twitter_username\" in body) {\n if (body.twitter_username === null) patch.twitter_username = null;\n else if (typeof body.twitter_username === \"string\") {\n patch.twitter_username = body.twitter_username;\n }\n }\n if (\"location\" in body) {\n if (body.location === null) patch.location = null;\n else if (typeof body.location === \"string\") patch.location = body.location;\n }\n if (\"name\" in body) {\n if (body.name === null) patch.name = null;\n else if (typeof body.name === \"string\") patch.name = body.name;\n }\n if (\"description\" in body) {\n if (body.description === null) patch.description = null;\n else if (typeof body.description === \"string\") patch.description = body.description;\n }\n if (\"default_repository_permission\" in body && typeof body.default_repository_permission === \"string\") {\n patch.default_repository_permission = body.default_repository_permission;\n }\n if (\"members_can_create_repositories\" in body && typeof body.members_can_create_repositories === \"boolean\") {\n patch.members_can_create_repositories = body.members_can_create_repositories;\n }\n\n const updated = gh.orgs.update(org.id, patch);\n if (!updated) throw notFound();\n return c.json(formatOrgFull(updated, baseUrl));\n });\n\n app.get(\"/orgs/:org/members\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n\n const roleQ = (c.req.query(\"role\") ?? \"all\").toLowerCase();\n if (roleQ !== \"all\" && roleQ !== \"admin\" && roleQ !== \"member\") {\n throw new ApiError(422, \"Invalid role parameter\");\n }\n\n let rows = listOrgMembersDeduped(gh, org.id);\n if (roleQ === \"admin\") rows = rows.filter((r) => r.orgRole === \"admin\");\n else if (roleQ === \"member\") rows = rows.filter((r) => r.orgRole === \"member\");\n\n const { page, per_page } = parsePagination(c);\n const total = rows.length;\n const start = (page - 1) * per_page;\n const slice = rows.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((r) => formatUser(r.user, baseUrl)));\n });\n\n app.get(\"/orgs/:org/members/:username\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n if (!orgRoleForUser(gh, org.id, user.id)) throw notFound();\n return c.body(null, 204);\n });\n\n app.delete(\"/orgs/:org/members/:username\", (c) => {\n const auth = requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n requireOrgAdmin(gh, org, auth);\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n removeUserFromAllOrgTeams(gh, org.id, user.id);\n return c.body(null, 204);\n });\n\n app.get(\"/orgs/:org/memberships/:username\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n const role = orgRoleForUser(gh, org.id, user.id);\n if (!role) throw notFound();\n return c.json({\n url: orgMembershipUrl(baseUrl, org.login, user.login),\n state: \"active\",\n role,\n organization_url: `${baseUrl}/orgs/${org.login}`,\n user: formatUser(user, baseUrl),\n organization: formatOrgBrief(org, baseUrl),\n });\n });\n\n app.put(\"/orgs/:org/memberships/:username\", async (c) => {\n const auth = requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n requireOrgAdmin(gh, org, auth);\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n\n const body = await parseJsonBody(c);\n const roleRaw = body.role;\n if (roleRaw !== \"admin\" && roleRaw !== \"member\") {\n throw new ApiError(422, \"role must be admin or member\");\n }\n const teamRole: \"member\" | \"maintainer\" = roleRaw === \"admin\" ? \"maintainer\" : \"member\";\n\n const membersTeam = getOrCreateMembersTeam(gh, org);\n const existing = gh.teamMembers.findBy(\"team_id\", membersTeam.id).find((m) => m.user_id === user.id);\n if (existing) {\n gh.teamMembers.update(existing.id, { role: teamRole });\n } else {\n gh.teamMembers.insert({ team_id: membersTeam.id, user_id: user.id, role: teamRole });\n }\n syncTeamMemberCount(gh, membersTeam.id);\n\n const orgRole = orgRoleForUser(gh, org.id, user.id)!;\n return c.json({\n url: orgMembershipUrl(baseUrl, org.login, user.login),\n state: \"active\",\n role: orgRole,\n organization_url: `${baseUrl}/orgs/${org.login}`,\n user: formatUser(user, baseUrl),\n organization: formatOrgBrief(org, baseUrl),\n });\n });\n\n app.get(\"/orgs/:org/teams\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n\n const all = teamsForOrg(gh, org.id).sort((a, b) => a.id - b.id);\n const { page, per_page } = parsePagination(c);\n const total = all.length;\n const start = (page - 1) * per_page;\n const slice = all.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((t) => formatTeamBrief(t, gh, baseUrl)));\n });\n\n app.post(\"/orgs/:org/teams\", async (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n\n const body = await parseJsonBody(c);\n const name = body.name;\n if (typeof name !== \"string\" || !name.trim()) {\n throw new ApiError(422, \"name is required\");\n }\n\n let parentId: number | null = null;\n if (body.parent_team_id != null) {\n const pid = Number(body.parent_team_id);\n const parent = gh.teams.get(pid);\n if (!parent || parent.org_id !== org.id) {\n throw new ApiError(422, \"Invalid parent_team_id\");\n }\n parentId = parent.id;\n }\n\n const baseSlug = uniqueTeamSlug(gh, org.id, slugifyFromName(name));\n const privacy = body.privacy === \"secret\" || body.privacy === \"closed\" ? body.privacy : \"closed\";\n const permission = typeof body.permission === \"string\" ? body.permission : \"pull\";\n const description =\n body.description === null ? null : typeof body.description === \"string\" ? body.description : null;\n\n const team = gh.teams.insert({\n node_id: \"pending\",\n name: name.trim(),\n slug: baseSlug,\n description,\n privacy,\n permission,\n org_id: org.id,\n parent_id: parentId,\n members_count: 0,\n repos_count: 0,\n });\n const fixed = gh.teams.update(team.id, { node_id: generateNodeId(\"Team\", team.id) });\n return c.json(formatTeamBrief(fixed ?? team, gh, baseUrl), 201);\n });\n\n app.get(\"/orgs/:org/teams/:team_slug\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n return c.json(formatTeamBrief(team, gh, baseUrl));\n });\n\n app.patch(\"/orgs/:org/teams/:team_slug\", async (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubTeam> = {};\n\n if (\"name\" in body && typeof body.name === \"string\" && body.name.trim()) {\n patch.name = body.name.trim();\n }\n if (\"description\" in body) {\n if (body.description === null) patch.description = null;\n else if (typeof body.description === \"string\") patch.description = body.description;\n }\n if (body.privacy === \"secret\" || body.privacy === \"closed\") {\n patch.privacy = body.privacy;\n }\n if (\"permission\" in body && typeof body.permission === \"string\") {\n patch.permission = body.permission;\n }\n if (\"parent_team_id\" in body) {\n if (body.parent_team_id === null) {\n patch.parent_id = null;\n } else {\n const pid = Number(body.parent_team_id);\n const parent = gh.teams.get(pid);\n if (!parent || parent.org_id !== org.id) {\n throw new ApiError(422, \"Invalid parent_team_id\");\n }\n if (parent.id === team.id) throw new ApiError(422, \"Invalid parent_team_id\");\n patch.parent_id = parent.id;\n }\n }\n\n const updated = gh.teams.update(team.id, patch);\n if (!updated) throw notFound();\n return c.json(formatTeamBrief(updated, gh, baseUrl));\n });\n\n app.delete(\"/orgs/:org/teams/:team_slug\", (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n deleteTeamCascade(gh, team);\n return c.body(null, 204);\n });\n\n app.get(\"/orgs/:org/teams/:team_slug/members\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n\n const roleQ = (c.req.query(\"role\") ?? \"all\").toLowerCase();\n if (roleQ !== \"all\" && roleQ !== \"member\" && roleQ !== \"maintainer\") {\n throw new ApiError(422, \"Invalid role parameter\");\n }\n\n let members = gh.teamMembers\n .findBy(\"team_id\", team.id)\n .map((m) => {\n const user = gh.users.get(m.user_id);\n return user ? { user, role: m.role } : null;\n })\n .filter((x): x is { user: GitHubUser; role: \"member\" | \"maintainer\" } => Boolean(x));\n\n if (roleQ === \"member\") members = members.filter((m) => m.role === \"member\");\n else if (roleQ === \"maintainer\") members = members.filter((m) => m.role === \"maintainer\");\n\n members.sort((a, b) => a.user.id - b.user.id);\n\n const { page, per_page } = parsePagination(c);\n const total = members.length;\n const start = (page - 1) * per_page;\n const slice = members.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((m) => formatUser(m.user, baseUrl)));\n });\n\n app.put(\"/orgs/:org/teams/:team_slug/memberships/:username\", async (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n\n const body = await parseJsonBody(c);\n const role: \"member\" | \"maintainer\" = body.role === \"maintainer\" ? \"maintainer\" : \"member\";\n\n const existing = gh.teamMembers.findBy(\"team_id\", team.id).find((m) => m.user_id === user.id);\n if (existing) {\n gh.teamMembers.update(existing.id, { role });\n } else {\n gh.teamMembers.insert({ team_id: team.id, user_id: user.id, role });\n }\n syncTeamMemberCount(gh, team.id);\n\n return c.json(formatTeamMembership(baseUrl, org.login, team.slug, user, role));\n });\n\n app.delete(\"/orgs/:org/teams/:team_slug/memberships/:username\", (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n\n const existing = gh.teamMembers.findBy(\"team_id\", team.id).find((m) => m.user_id === user.id);\n if (existing) {\n gh.teamMembers.delete(existing.id);\n syncTeamMemberCount(gh, team.id);\n }\n return c.body(null, 204);\n });\n\n app.get(\"/orgs/:org/teams/:team_slug/memberships/:username\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n const user = gh.users.findOneBy(\"login\", c.req.param(\"username\")!);\n if (!user) throw notFound();\n\n const m = gh.teamMembers.findBy(\"team_id\", team.id).find((x) => x.user_id === user.id);\n if (!m) throw notFound();\n\n return c.json(formatTeamMembership(baseUrl, org.login, team.slug, user, m.role));\n });\n\n app.get(\"/orgs/:org/teams/:team_slug/repos\", (c) => {\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n\n const links = gh.teamRepos.findBy(\"team_id\", team.id);\n const repos = links\n .map((l) => gh.repos.get(l.repo_id))\n .filter((r): r is GitHubRepo => Boolean(r))\n .sort((a, b) => a.id - b.id);\n\n const { page, per_page } = parsePagination(c);\n const total = repos.length;\n const start = (page - 1) * per_page;\n const slice = repos.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((r) => formatRepo(r, gh, baseUrl)));\n });\n\n app.put(\"/orgs/:org/teams/:team_slug/repos/:owner/:repo\", (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n\n const ownerLogin = c.req.param(\"owner\")!;\n const ownerInfo = lookupOwner(gh, ownerLogin);\n if (!ownerInfo || ownerInfo.type !== \"Organization\" || ownerInfo.id !== org.id) {\n throw new ApiError(422, \"Repository must belong to this organization\");\n }\n const repo = lookupRepo(gh, ownerLogin, c.req.param(\"repo\")!);\n if (!repo) throw notFound();\n\n if (!findTeamRepo(gh, team.id, repo.id)) {\n gh.teamRepos.insert({ team_id: team.id, repo_id: repo.id });\n syncTeamRepoCount(gh, team.id);\n }\n return c.body(null, 204);\n });\n\n app.delete(\"/orgs/:org/teams/:team_slug/repos/:owner/:repo\", (c) => {\n requireAuthUser(c);\n const org = getOrgByLogin(gh, c.req.param(\"org\")!);\n if (!org) throw notFound();\n const team = getTeamByOrgSlug(gh, org, c.req.param(\"team_slug\")!);\n if (!team) throw notFound();\n\n const ownerLogin = c.req.param(\"owner\")!;\n const ownerInfo = lookupOwner(gh, ownerLogin);\n if (!ownerInfo || ownerInfo.type !== \"Organization\" || ownerInfo.id !== org.id) {\n throw new ApiError(422, \"Repository must belong to this organization\");\n }\n const repo = lookupRepo(gh, ownerLogin, c.req.param(\"repo\")!);\n if (!repo) throw notFound();\n\n const tr = findTeamRepo(gh, team.id, repo.id);\n if (tr) {\n gh.teamRepos.delete(tr.id);\n syncTeamRepoCount(gh, team.id);\n }\n return c.body(null, 204);\n });\n\n app.get(\"/teams/:team_id\", (c) => {\n const tid = parseInt(c.req.param(\"team_id\") ?? \"\", 10);\n if (Number.isNaN(tid)) throw notFound();\n const team = gh.teams.get(tid);\n if (!team) throw notFound();\n return c.json(formatTeamBrief(team, gh, baseUrl));\n });\n\n app.get(\"/teams/:team_id/members\", (c) => {\n const tid = parseInt(c.req.param(\"team_id\") ?? \"\", 10);\n if (Number.isNaN(tid)) throw notFound();\n const team = gh.teams.get(tid);\n if (!team) throw notFound();\n\n const roleQ = (c.req.query(\"role\") ?? \"all\").toLowerCase();\n if (roleQ !== \"all\" && roleQ !== \"member\" && roleQ !== \"maintainer\") {\n throw new ApiError(422, \"Invalid role parameter\");\n }\n\n let members = gh.teamMembers\n .findBy(\"team_id\", team.id)\n .map((m) => {\n const user = gh.users.get(m.user_id);\n return user ? { user, role: m.role } : null;\n })\n .filter((x): x is { user: GitHubUser; role: \"member\" | \"maintainer\" } => Boolean(x));\n\n if (roleQ === \"member\") members = members.filter((m) => m.role === \"member\");\n else if (roleQ === \"maintainer\") members = members.filter((m) => m.role === \"maintainer\");\n\n members.sort((a, b) => a.user.id - b.user.id);\n\n const { page, per_page } = parsePagination(c);\n const total = members.length;\n const start = (page - 1) * per_page;\n const slice = members.slice(start, start + per_page);\n\n setLinkHeader(c, total, page, per_page);\n return c.json(slice.map((m) => formatUser(m.user, baseUrl)));\n });\n}\n","import type { RouteContext, WebhookDispatcher, AuthUser } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubRelease, GitHubReleaseAsset, GitHubRepo, GitHubUser } from \"../entities.js\";\nimport {\n formatRelease,\n formatReleaseAsset,\n formatRepo,\n formatUser,\n generateNodeId,\n lookupRepo,\n timestamp,\n} from \"../helpers.js\";\nimport { assertRepoRead, assertRepoWrite, getActorUser, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\n/** Draft releases are omitted for anonymous API clients; any authenticated user may see them once repo read is allowed. */\nfunction isAuthenticatedActor(gh: GitHubStore, authUser: AuthUser | undefined): boolean {\n return Boolean(authUser && getActorUser(gh, authUser));\n}\n\nfunction assertReleaseVisible(gh: GitHubStore, authUser: AuthUser | undefined, release: GitHubRelease) {\n if (release.draft && !isAuthenticatedActor(gh, authUser)) {\n throw notFoundResponse();\n }\n}\n\nfunction releasesForRepo(gh: GitHubStore, repoId: number): GitHubRelease[] {\n return gh.releases.findBy(\"repo_id\", repoId);\n}\n\nfunction findReleaseById(gh: GitHubStore, repoId: number, releaseId: number): GitHubRelease | undefined {\n const r = gh.releases.get(releaseId);\n if (!r || r.repo_id !== repoId) return undefined;\n return r;\n}\n\nfunction findReleaseByTag(gh: GitHubStore, repoId: number, tagName: string): GitHubRelease | undefined {\n return releasesForRepo(gh, repoId).find((rel) => rel.tag_name === tagName);\n}\n\nfunction tagTaken(gh: GitHubStore, repoId: number, tagName: string, exceptId?: number): boolean {\n return releasesForRepo(gh, repoId).some((r) => r.tag_name === tagName && r.id !== exceptId);\n}\n\nfunction sortReleasesByCreatedDesc(a: GitHubRelease, b: GitHubRelease): number {\n return b.created_at.localeCompare(a.created_at);\n}\n\nfunction deleteAssetsForRelease(gh: GitHubStore, releaseId: number) {\n for (const a of gh.releaseAssets.findBy(\"release_id\", releaseId)) {\n gh.releaseAssets.delete(a.id);\n }\n}\n\nfunction dispatchReleaseWebhook(\n webhooks: WebhookDispatcher,\n gh: GitHubStore,\n repo: GitHubRepo,\n actor: GitHubUser,\n release: GitHubRelease,\n action: string,\n baseUrl: string,\n) {\n const relFmt = formatRelease(release, gh, baseUrl);\n if (!relFmt) return;\n const ownerLogin = ownerLoginOf(gh, repo);\n webhooks.dispatch(\n \"release\",\n action,\n {\n action,\n release: relFmt,\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n}\n\nexport function releasesRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/releases\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const authUser = c.get(\"authUser\");\n const showDrafts = isAuthenticatedActor(gh, authUser);\n\n let list = releasesForRepo(gh, repo.id);\n if (!showDrafts) {\n list = list.filter((r) => !r.draft);\n }\n list = [...list].sort(sortReleasesByCreatedDesc);\n\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = list.slice(start, start + per_page);\n\n const out = pageItems.map((r) => formatRelease(r, gh, baseUrl)).filter(Boolean);\n return c.json(out);\n });\n\n app.post(\"/repos/:owner/:repo/releases/generate-notes\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const body = await parseJsonBody(c);\n const tagName = typeof body.tag_name === \"string\" ? body.tag_name : \"\";\n const target = typeof body.target_commitish === \"string\" ? body.target_commitish : undefined;\n const prev = typeof body.previous_tag_name === \"string\" ? body.previous_tag_name : undefined;\n return c.json({\n name: tagName ? `Release ${tagName}` : \"Release\",\n body: `## What's changed\\n\\n_Auto-generated release notes (stub)._\\n\\n<!-- target: ${target ?? \"default\"} previous: ${prev ?? \"none\"} -->`,\n });\n });\n\n app.get(\"/repos/:owner/:repo/releases/latest\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const candidates = releasesForRepo(gh, repo.id).filter((r) => !r.draft && !r.prerelease && r.published_at);\n if (candidates.length === 0) throw notFoundResponse();\n\n candidates.sort((a, b) => {\n const pa = a.published_at ?? a.created_at;\n const pb = b.published_at ?? b.created_at;\n return pb.localeCompare(pa);\n });\n const latest = candidates[0]!;\n const fmt = formatRelease(latest, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt);\n });\n\n app.get(\"/repos/:owner/:repo/releases/tags/:tag\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const tag = decodeURIComponent(c.req.param(\"tag\")!);\n const release = findReleaseByTag(gh, repo.id, tag);\n if (!release) throw notFoundResponse();\n assertReleaseVisible(gh, c.get(\"authUser\"), release);\n\n const fmt = formatRelease(release, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt);\n });\n\n app.get(\"/repos/:owner/:repo/releases/assets/:asset_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const assetId = parseInt(c.req.param(\"asset_id\")!, 10);\n if (!Number.isFinite(assetId)) throw notFoundResponse();\n\n const asset = gh.releaseAssets.get(assetId);\n if (!asset || asset.repo_id !== repo.id) throw notFoundResponse();\n\n const release = gh.releases.get(asset.release_id);\n if (release) {\n assertReleaseVisible(gh, c.get(\"authUser\"), release);\n }\n\n return c.json(formatReleaseAsset(asset, repo, baseUrl));\n });\n\n app.patch(\"/repos/:owner/:repo/releases/assets/:asset_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const assetId = parseInt(c.req.param(\"asset_id\")!, 10);\n if (!Number.isFinite(assetId)) throw notFoundResponse();\n\n const asset = gh.releaseAssets.get(assetId);\n if (!asset || asset.repo_id !== repo.id) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubReleaseAsset> = {};\n if (typeof body.name === \"string\") patch.name = body.name;\n if (typeof body.label === \"string\" || body.label === null) patch.label = body.label as string | null;\n\n const updated = gh.releaseAssets.update(asset.id, patch);\n if (!updated) throw notFoundResponse();\n\n return c.json(formatReleaseAsset(updated, repo, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/releases/assets/:asset_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const assetId = parseInt(c.req.param(\"asset_id\")!, 10);\n if (!Number.isFinite(assetId)) throw notFoundResponse();\n\n const asset = gh.releaseAssets.get(assetId);\n if (!asset || asset.repo_id !== repo.id) throw notFoundResponse();\n\n gh.releaseAssets.delete(asset.id);\n return c.body(null, 204);\n });\n\n app.post(\"/repos/:owner/:repo/releases\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const body = await parseJsonBody(c);\n if (typeof body.tag_name !== \"string\" || !body.tag_name.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n const tag_name = body.tag_name.trim();\n if (tagTaken(gh, repo.id, tag_name)) {\n throw new ApiError(422, \"Validation failed\");\n }\n\n const target_commitish =\n typeof body.target_commitish === \"string\" && body.target_commitish.trim()\n ? body.target_commitish.trim()\n : repo.default_branch;\n\n const draft = typeof body.draft === \"boolean\" ? body.draft : false;\n const prerelease = typeof body.prerelease === \"boolean\" ? body.prerelease : false;\n\n let name: string | null = typeof body.name === \"string\" || body.name === null ? (body.name as string | null) : null;\n let releaseBody: string | null =\n typeof body.body === \"string\" || body.body === null ? (body.body as string | null) : null;\n\n if (body.generate_release_notes === true) {\n releaseBody = releaseBody ?? `## What's changed\\n\\n_Auto-generated release notes (stub) for ${tag_name}._`;\n name = name ?? `Release ${tag_name}`;\n }\n\n const published_at = draft ? null : timestamp();\n\n const row = gh.releases.insert({\n node_id: \"\",\n repo_id: repo.id,\n tag_name,\n target_commitish,\n name,\n body: releaseBody,\n draft,\n prerelease,\n author_id: actor.id,\n published_at,\n } as Omit<GitHubRelease, \"id\" | \"created_at\" | \"updated_at\">);\n gh.releases.update(row.id, { node_id: generateNodeId(\"Release\", row.id) });\n\n const release = gh.releases.get(row.id)!;\n\n if (draft) {\n dispatchReleaseWebhook(webhooks, gh, repo, actor, release, \"created\", baseUrl);\n } else {\n dispatchReleaseWebhook(webhooks, gh, repo, actor, release, \"published\", baseUrl);\n }\n\n const fmt = formatRelease(release, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt, 201);\n });\n\n app.get(\"/repos/:owner/:repo/releases/:release_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const releaseId = parseInt(c.req.param(\"release_id\")!, 10);\n if (!Number.isFinite(releaseId)) throw notFoundResponse();\n\n const release = findReleaseById(gh, repo.id, releaseId);\n if (!release) throw notFoundResponse();\n assertReleaseVisible(gh, c.get(\"authUser\"), release);\n\n const fmt = formatRelease(release, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt);\n });\n\n app.patch(\"/repos/:owner/:repo/releases/:release_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const releaseId = parseInt(c.req.param(\"release_id\")!, 10);\n if (!Number.isFinite(releaseId)) throw notFoundResponse();\n\n const release = findReleaseById(gh, repo.id, releaseId);\n if (!release) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const patch: Partial<GitHubRelease> = {};\n\n if (typeof body.tag_name === \"string\" && body.tag_name.trim()) {\n const nextTag = body.tag_name.trim();\n if (tagTaken(gh, repo.id, nextTag, release.id)) {\n throw new ApiError(422, \"Validation failed\");\n }\n patch.tag_name = nextTag;\n }\n if (typeof body.target_commitish === \"string\" && body.target_commitish.trim()) {\n patch.target_commitish = body.target_commitish.trim();\n }\n if (typeof body.name === \"string\" || body.name === null) patch.name = body.name as string | null;\n if (typeof body.body === \"string\" || body.body === null) patch.body = body.body as string | null;\n if (typeof body.draft === \"boolean\") patch.draft = body.draft;\n if (typeof body.prerelease === \"boolean\") patch.prerelease = body.prerelease;\n\n const wasDraft = release.draft;\n let publishedJustNow = false;\n if (wasDraft && typeof body.draft === \"boolean\" && body.draft === false) {\n patch.published_at = timestamp();\n publishedJustNow = true;\n }\n\n const updated = gh.releases.update(release.id, patch);\n if (!updated) throw notFoundResponse();\n\n if (publishedJustNow) {\n dispatchReleaseWebhook(webhooks, gh, repo, actor, updated, \"published\", baseUrl);\n }\n\n const fmt = formatRelease(updated, gh, baseUrl);\n if (!fmt) throw notFoundResponse();\n return c.json(fmt);\n });\n\n app.delete(\"/repos/:owner/:repo/releases/:release_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const releaseId = parseInt(c.req.param(\"release_id\")!, 10);\n if (!Number.isFinite(releaseId)) throw notFoundResponse();\n\n const release = findReleaseById(gh, repo.id, releaseId);\n if (!release) throw notFoundResponse();\n\n deleteAssetsForRelease(gh, release.id);\n gh.releases.delete(release.id);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/releases/:release_id/assets\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n\n const releaseId = parseInt(c.req.param(\"release_id\")!, 10);\n if (!Number.isFinite(releaseId)) throw notFoundResponse();\n\n const release = findReleaseById(gh, repo.id, releaseId);\n if (!release) throw notFoundResponse();\n assertReleaseVisible(gh, c.get(\"authUser\"), release);\n\n let assets = gh.releaseAssets.findBy(\"release_id\", release.id);\n assets = [...assets].sort((a, b) => b.created_at.localeCompare(a.created_at));\n\n const { page, per_page } = parsePagination(c);\n const total = assets.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n const pageItems = assets.slice(start, start + per_page);\n\n return c.json(pageItems.map((a) => formatReleaseAsset(a, repo, baseUrl)));\n });\n\n app.post(\"/repos/:owner/:repo/releases/:release_id/assets\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n\n const releaseId = parseInt(c.req.param(\"release_id\")!, 10);\n if (!Number.isFinite(releaseId)) throw notFoundResponse();\n\n const release = findReleaseById(gh, repo.id, releaseId);\n if (!release) throw notFoundResponse();\n\n const nameQ = c.req.query(\"name\");\n if (!nameQ || !nameQ.trim()) {\n throw new ApiError(422, \"Validation failed\");\n }\n const assetName = nameQ.trim();\n const labelRaw = c.req.query(\"label\");\n const label = labelRaw === undefined || labelRaw === \"\" ? null : labelRaw;\n\n const buf = await c.req.arrayBuffer();\n const size = buf.byteLength;\n\n const contentType = c.req.header(\"Content-Type\")?.split(\";\")[0]?.trim() || \"application/octet-stream\";\n\n const row = gh.releaseAssets.insert({\n node_id: \"\",\n release_id: release.id,\n repo_id: repo.id,\n name: assetName,\n label,\n state: \"uploaded\",\n content_type: contentType,\n size,\n download_count: 0,\n uploader_id: actor.id,\n } as Omit<GitHubReleaseAsset, \"id\" | \"created_at\" | \"updated_at\">);\n gh.releaseAssets.update(row.id, { node_id: generateNodeId(\"ReleaseAsset\", row.id) });\n\n const asset = gh.releaseAssets.get(row.id)!;\n return c.json(formatReleaseAsset(asset, repo, baseUrl), 201);\n });\n}\n","import type { RouteContext, AuthUser, WebhookDelivery } from \"@emulators/core\";\nimport { ApiError, forbidden, parseJsonBody, parsePagination, setLinkHeader, unauthorized } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type { GitHubOrg, GitHubRepo, GitHubUser, GitHubWebhook } from \"../entities.js\";\nimport { formatRepo, formatUser, formatWebhook, lookupRepo } from \"../helpers.js\";\nimport { assertRepoAdmin, getActorUser, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\nfunction teamsForOrg(gh: GitHubStore, orgId: number) {\n return gh.teams.findBy(\"org_id\", orgId);\n}\n\nfunction listOrgMembersDeduped(gh: GitHubStore, orgId: number): { user: GitHubUser; orgRole: \"admin\" | \"member\" }[] {\n const byUser = new Map<number, { user: GitHubUser; isAdmin: boolean }>();\n for (const team of teamsForOrg(gh, orgId)) {\n for (const m of gh.teamMembers.findBy(\"team_id\", team.id)) {\n const user = gh.users.get(m.user_id);\n if (!user) continue;\n const isAdmin = m.role === \"maintainer\";\n const prev = byUser.get(user.id);\n if (!prev) {\n byUser.set(user.id, { user, isAdmin });\n } else {\n byUser.set(user.id, { user, isAdmin: prev.isAdmin || isAdmin });\n }\n }\n }\n return [...byUser.values()]\n .map(({ user, isAdmin }) => ({\n user,\n orgRole: isAdmin ? (\"admin\" as const) : (\"member\" as const),\n }))\n .sort((a, b) => a.user.id - b.user.id);\n}\n\nfunction orgRoleForUser(gh: GitHubStore, orgId: number, userId: number): \"admin\" | \"member\" | null {\n const row = listOrgMembersDeduped(gh, orgId).find((r) => r.user.id === userId);\n return row?.orgRole ?? null;\n}\n\nfunction assertOrgAdmin(gh: GitHubStore, authUser: AuthUser | undefined, org: GitHubOrg) {\n if (!authUser) throw unauthorized();\n const user = getActorUser(gh, authUser);\n if (!user) throw unauthorized();\n if (orgRoleForUser(gh, org.id, user.id) === \"admin\") return;\n throw forbidden();\n}\n\nfunction getOrgByLogin(gh: GitHubStore, login: string): GitHubOrg | undefined {\n return gh.orgs.findOneBy(\"login\", login);\n}\n\nfunction pathPrefixForWebhook(wh: GitHubWebhook, ownerPath: string): string {\n return wh.repo_id != null ? `repos/${ownerPath}` : `orgs/${ownerPath}`;\n}\n\nfunction findRepoHook(gh: GitHubStore, repoId: number, hookId: number): GitHubWebhook | undefined {\n const wh = gh.webhooks.get(hookId);\n if (!wh || wh.repo_id !== repoId) return undefined;\n return wh;\n}\n\nfunction findOrgHook(gh: GitHubStore, orgId: number, hookId: number): GitHubWebhook | undefined {\n const wh = gh.webhooks.get(hookId);\n if (!wh || wh.org_id !== orgId) return undefined;\n return wh;\n}\n\nfunction webhooksForRepo(gh: GitHubStore, repoId: number): GitHubWebhook[] {\n return gh.webhooks.findBy(\"repo_id\", repoId).filter((w) => w.repo_id === repoId);\n}\n\nfunction webhooksForOrg(gh: GitHubStore, orgId: number): GitHubWebhook[] {\n return gh.webhooks.findBy(\"org_id\", orgId).filter((w) => w.org_id === orgId);\n}\n\nfunction normalizeInsecureSsl(v: unknown): string {\n if (v === true) return \"1\";\n if (v === false) return \"0\";\n if (typeof v === \"string\" && (v === \"0\" || v === \"1\")) return v;\n return \"0\";\n}\n\nfunction parseHookConfig(raw: unknown, existing?: GitHubWebhook[\"config\"]): GitHubWebhook[\"config\"] | null {\n if (raw === undefined && existing) return existing;\n if (!raw || typeof raw !== \"object\") return null;\n const o = raw as Record<string, unknown>;\n const urlRaw = typeof o.url === \"string\" ? o.url.trim() : \"\";\n const url = urlRaw || existing?.url || \"\";\n if (!url) return null;\n const content_type =\n typeof o.content_type === \"string\" && o.content_type ? o.content_type : (existing?.content_type ?? \"json\");\n let secret: string | undefined;\n if (o.secret === null) {\n secret = undefined;\n } else if (typeof o.secret === \"string\") {\n secret = o.secret;\n } else if (existing?.secret !== undefined) {\n secret = existing.secret;\n }\n const insecure_ssl = normalizeInsecureSsl(\n o.insecure_ssl !== undefined ? o.insecure_ssl : (existing?.insecure_ssl ?? \"0\"),\n );\n return { url, content_type, secret, insecure_ssl };\n}\n\nfunction formatHookDelivery(d: WebhookDelivery, baseUrl: string, pathPrefix: string, hookId: number) {\n return {\n id: d.id,\n guid: `${d.hook_id}-${d.id}-${d.delivered_at}`,\n delivered_at: d.delivered_at,\n redelivery: false,\n duration: d.duration,\n status: d.success ? \"OK\" : \"Failed\",\n status_code: d.status_code,\n event: d.event,\n action: d.action ?? null,\n url: `${baseUrl}/${pathPrefix}/hooks/${hookId}/deliveries/${d.id}`,\n };\n}\n\nexport function webhooksRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n // --- Repository webhooks ---\n\n app.get(\"/repos/:owner/:repo/hooks\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n\n let list = webhooksForRepo(gh, repo.id).sort((a, b) => a.id - b.id);\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n list = list.slice(start, start + per_page);\n\n const ownerPath = `${owner}/${repoName}`;\n return c.json(list.map((wh) => formatWebhook(wh, baseUrl, ownerPath)));\n });\n\n app.post(\"/repos/:owner/:repo/hooks\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" && body.name.trim() ? body.name.trim() : \"web\";\n const events = Array.isArray(body.events)\n ? (body.events as unknown[]).filter((e): e is string => typeof e === \"string\")\n : [\"push\"];\n const active = typeof body.active === \"boolean\" ? body.active : true;\n const config = parseHookConfig(body.config);\n if (!config) throw new ApiError(422, \"config.url is required\");\n\n const wh = gh.webhooks.insert({\n repo_id: repo.id,\n org_id: null,\n name,\n active,\n events,\n config,\n last_response: { code: null, status: \"unused\", message: null },\n });\n\n webhooks.register({\n id: wh.id,\n url: wh.config.url,\n events: wh.events,\n active: wh.active,\n secret: wh.config.secret,\n owner,\n repo: repo.name,\n });\n\n const ownerPath = `${owner}/${repoName}`;\n return c.json(formatWebhook(wh, baseUrl, ownerPath), 201);\n });\n\n app.get(\"/repos/:owner/:repo/hooks/:hook_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n const ownerPath = `${owner}/${repoName}`;\n return c.json(formatWebhook(wh, baseUrl, ownerPath));\n });\n\n app.patch(\"/repos/:owner/:repo/hooks/:hook_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const existing = findRepoHook(gh, repo.id, hookId);\n if (!existing) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name.trim() : existing.name;\n const events = Array.isArray(body.events)\n ? (body.events as unknown[]).filter((e): e is string => typeof e === \"string\")\n : existing.events;\n const active = typeof body.active === \"boolean\" ? body.active : existing.active;\n const config = body.config !== undefined ? parseHookConfig(body.config, existing.config) : existing.config;\n if (!config) throw new ApiError(422, \"Invalid config\");\n\n const wh = gh.webhooks.update(hookId, { name, active, events, config })!;\n webhooks.updateSubscription(hookId, {\n url: wh.config.url,\n events: wh.events,\n active: wh.active,\n secret: wh.config.secret,\n });\n\n const ownerPath = `${owner}/${repoName}`;\n return c.json(formatWebhook(wh, baseUrl, ownerPath));\n });\n\n app.delete(\"/repos/:owner/:repo/hooks/:hook_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n webhooks.unregister(hookId);\n gh.webhooks.delete(hookId);\n return c.body(null, 204);\n });\n\n app.post(\"/repos/:owner/:repo/hooks/:hook_id/pings\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n const ownerPath = `${owner}/${repoName}`;\n await webhooks.dispatch(\n \"ping\",\n undefined,\n {\n zen: \"Keep it logically awesome.\",\n hook_id: wh.id,\n hook: formatWebhook(wh, baseUrl, ownerPath),\n },\n owner,\n repo.name,\n );\n return c.body(null, 204);\n });\n\n app.post(\"/repos/:owner/:repo/hooks/:hook_id/tests\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n const ownerLogin = ownerLoginOf(gh, repo);\n const actor = getActorUser(gh, c.get(\"authUser\")!) ?? gh.users.get(repo.owner_id) ?? gh.users.all()[0];\n const testPayload = {\n ref: \"refs/heads/main\",\n before: \"0000000000000000000000000000000000000000\",\n after: \"0000000000000000000000000000000000000000\",\n repository: formatRepo(repo, gh, baseUrl),\n pusher: actor ? formatUser(actor, baseUrl) : null,\n sender: actor ? formatUser(actor, baseUrl) : null,\n };\n await webhooks.dispatch(\"push\", undefined, testPayload, ownerLogin, repo.name);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/hooks/:hook_id/deliveries\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n let list = webhooks.getDeliveries(wh.id).sort((a, b) => b.id - a.id);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n list = list.slice(start, start + per_page);\n\n const pp = pathPrefixForWebhook(wh, `${owner}/${repoName}`);\n return c.json(list.map((d) => formatHookDelivery(d, baseUrl, pp, wh.id)));\n });\n\n app.get(\"/repos/:owner/:repo/hooks/:hook_id/deliveries/:delivery_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const deliveryId = Number(c.req.param(\"delivery_id\"));\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n if (!Number.isFinite(hookId) || !Number.isFinite(deliveryId)) throw notFoundResponse();\n\n const wh = findRepoHook(gh, repo.id, hookId);\n if (!wh) throw notFoundResponse();\n\n const d = webhooks.getDeliveries(wh.id).find((x) => x.id === deliveryId);\n if (!d) throw notFoundResponse();\n\n const pp = pathPrefixForWebhook(wh, `${owner}/${repoName}`);\n return c.json(formatHookDelivery(d, baseUrl, pp, wh.id));\n });\n\n // --- Organization webhooks ---\n\n app.get(\"/orgs/:org/hooks\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n\n let list = webhooksForOrg(gh, org.id).sort((a, b) => a.id - b.id);\n const { page, per_page } = parsePagination(c);\n const total = list.length;\n setLinkHeader(c, total, page, per_page);\n const start = (page - 1) * per_page;\n list = list.slice(start, start + per_page);\n\n return c.json(list.map((wh) => formatWebhook(wh, baseUrl, org.login)));\n });\n\n app.post(\"/orgs/:org/hooks\", async (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" && body.name.trim() ? body.name.trim() : \"web\";\n const events = Array.isArray(body.events)\n ? (body.events as unknown[]).filter((e): e is string => typeof e === \"string\")\n : [\"push\"];\n const active = typeof body.active === \"boolean\" ? body.active : true;\n const config = parseHookConfig(body.config);\n if (!config) throw new ApiError(422, \"config.url is required\");\n\n const wh = gh.webhooks.insert({\n repo_id: null,\n org_id: org.id,\n name,\n active,\n events,\n config,\n last_response: { code: null, status: \"unused\", message: null },\n });\n\n webhooks.register({\n id: wh.id,\n url: wh.config.url,\n events: wh.events,\n active: wh.active,\n secret: wh.config.secret,\n owner: org.login,\n repo: undefined,\n });\n\n return c.json(formatWebhook(wh, baseUrl, org.login), 201);\n });\n\n app.get(\"/orgs/:org/hooks/:hook_id\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findOrgHook(gh, org.id, hookId);\n if (!wh) throw notFoundResponse();\n\n return c.json(formatWebhook(wh, baseUrl, org.login));\n });\n\n app.patch(\"/orgs/:org/hooks/:hook_id\", async (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const existing = findOrgHook(gh, org.id, hookId);\n if (!existing) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n const name = typeof body.name === \"string\" ? body.name.trim() : existing.name;\n const events = Array.isArray(body.events)\n ? (body.events as unknown[]).filter((e): e is string => typeof e === \"string\")\n : existing.events;\n const active = typeof body.active === \"boolean\" ? body.active : existing.active;\n const config = body.config !== undefined ? parseHookConfig(body.config, existing.config) : existing.config;\n if (!config) throw new ApiError(422, \"Invalid config\");\n\n const wh = gh.webhooks.update(hookId, { name, active, events, config })!;\n webhooks.updateSubscription(hookId, {\n url: wh.config.url,\n events: wh.events,\n active: wh.active,\n secret: wh.config.secret,\n });\n\n return c.json(formatWebhook(wh, baseUrl, org.login));\n });\n\n app.delete(\"/orgs/:org/hooks/:hook_id\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findOrgHook(gh, org.id, hookId);\n if (!wh) throw notFoundResponse();\n\n webhooks.unregister(hookId);\n gh.webhooks.delete(hookId);\n return c.body(null, 204);\n });\n\n app.post(\"/orgs/:org/hooks/:hook_id/pings\", async (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const hookId = Number(c.req.param(\"hook_id\"));\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n if (!Number.isFinite(hookId)) throw notFoundResponse();\n\n const wh = findOrgHook(gh, org.id, hookId);\n if (!wh) throw notFoundResponse();\n\n await webhooks.dispatch(\n \"ping\",\n undefined,\n {\n zen: \"Keep it logically awesome.\",\n hook_id: wh.id,\n hook: formatWebhook(wh, baseUrl, org.login),\n },\n org.login,\n undefined,\n );\n return c.body(null, 204);\n });\n}\n","import type { RouteContext, AuthUser } from \"@emulators/core\";\nimport { ApiError, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubBlob,\n GitHubCommit,\n GitHubIssue,\n GitHubOrg,\n GitHubPullRequest,\n GitHubRepo,\n GitHubUser,\n} from \"../entities.js\";\nimport { formatIssue, formatOrgBrief, formatPullRequest, formatRepo, formatUser, lookupRepo } from \"../helpers.js\";\nimport { canAccessRepo } from \"../route-helpers.js\";\n\n/** Parsed GitHub-style search query (q parameter). */\nexport interface ParsedSearchQuery {\n text: string;\n qualifiers: Map<string, string[]>;\n negations: Map<string, string[]>;\n ranges: Map<string, Array<{ op: string; value: number | string }>>;\n}\n\nfunction tokenizeSearchQuery(q: string): string[] {\n const tokens: string[] = [];\n let i = 0;\n let buf = \"\";\n let quote: '\"' | \"'\" | null = null;\n while (i < q.length) {\n const c = q[i]!;\n if (quote) {\n if (c === quote) {\n quote = null;\n i++;\n continue;\n }\n buf += c;\n i++;\n continue;\n }\n if (c === '\"' || c === \"'\") {\n quote = c;\n i++;\n continue;\n }\n if (c === \" \" || c === \"\\t\" || c === \"\\n\" || c === \"\\r\") {\n if (buf.length) {\n tokens.push(buf);\n buf = \"\";\n }\n i++;\n continue;\n }\n buf += c;\n i++;\n }\n if (buf.length) tokens.push(buf);\n return tokens;\n}\n\nfunction parseRangeToken(raw: string): { op: string; value: number | string } | null {\n const range = /^(\\d+)\\.\\.(\\d+)$/.exec(raw);\n if (range) {\n return { op: \"..\", value: `${range[1]}..${range[2]}` };\n }\n const cmp = /^(>=|<=|>|<)(\\d+)$/.exec(raw);\n if (cmp) {\n return { op: cmp[1]!, value: parseInt(cmp[2]!, 10) };\n }\n if (/^\\d+$/.test(raw)) {\n return { op: \"=\", value: parseInt(raw, 10) };\n }\n return null;\n}\n\n/**\n * Splits `q` into free text vs qualifiers, handles `-qualifier:value` negation,\n * and numeric ranges (`stars:>10`, `stars:10..50`).\n */\nexport function parseSearchQuery(q: string): ParsedSearchQuery {\n const qualifiers = new Map<string, string[]>();\n const negations = new Map<string, string[]>();\n const ranges = new Map<string, Array<{ op: string; value: number | string }>>();\n const textParts: string[] = [];\n\n for (const rawTok of tokenizeSearchQuery(q.trim())) {\n let neg = false;\n let tok = rawTok;\n if (tok.startsWith(\"-\") && tok.includes(\":\") && tok.length > 1) {\n neg = true;\n tok = tok.slice(1);\n }\n\n const colon = tok.indexOf(\":\");\n if (colon <= 0) {\n textParts.push(rawTok);\n continue;\n }\n\n const key = tok.slice(0, colon).toLowerCase();\n const rawVal = tok.slice(colon + 1);\n if (!rawVal.length) {\n textParts.push(rawTok);\n continue;\n }\n\n const rangePred = parseRangeToken(rawVal);\n const isRangeKey =\n key === \"stars\" ||\n key === \"forks\" ||\n key === \"repos\" ||\n key === \"followers\" ||\n key === \"comments\" ||\n key === \"size\";\n\n if (rangePred && (rangePred.op !== \"=\" || isRangeKey)) {\n if (neg) {\n if (!negations.has(key)) negations.set(key, []);\n negations.get(key)!.push(rawVal);\n } else {\n if (!ranges.has(key)) ranges.set(key, []);\n ranges.get(key)!.push(rangePred);\n }\n continue;\n }\n\n if (neg) {\n if (!negations.has(key)) negations.set(key, []);\n negations.get(key)!.push(rawVal);\n } else {\n if (!qualifiers.has(key)) qualifiers.set(key, []);\n qualifiers.get(key)!.push(rawVal);\n }\n }\n\n return {\n text: textParts.join(\" \").trim(),\n qualifiers,\n negations,\n ranges,\n };\n}\n\nfunction textMatches(haystack: string, needle: string): boolean {\n if (!needle.trim()) return true;\n return haystack.toLowerCase().includes(needle.toLowerCase());\n}\n\nfunction repoVisibleForSearch(repo: GitHubRepo, gh: GitHubStore, authUser: AuthUser | undefined): boolean {\n return canAccessRepo(gh, authUser, repo);\n}\n\nfunction ownerLogin(gh: GitHubStore, repo: GitHubRepo): string {\n if (repo.owner_type === \"User\") {\n return gh.users.get(repo.owner_id)?.login ?? \"\";\n }\n return gh.orgs.get(repo.owner_id)?.login ?? \"\";\n}\n\nfunction matchesNumericPredicate(\n actual: number,\n preds: Array<{ op: string; value: number | string }>,\n equalsFromQualifiers: string[],\n): boolean {\n for (const e of equalsFromQualifiers) {\n if (/^\\d+$/.test(e) && actual !== parseInt(e, 10)) return false;\n }\n for (const p of preds) {\n if (p.op === \"..\") {\n const m = /^(\\d+)\\.\\.(\\d+)$/.exec(String(p.value));\n if (m) {\n const lo = parseInt(m[1]!, 10);\n const hi = parseInt(m[2]!, 10);\n if (actual < lo || actual > hi) return false;\n }\n } else if (p.op === \">\") {\n if (!(actual > Number(p.value))) return false;\n } else if (p.op === \"<\") {\n if (!(actual < Number(p.value))) return false;\n } else if (p.op === \">=\") {\n if (!(actual >= Number(p.value))) return false;\n } else if (p.op === \"<=\") {\n if (!(actual <= Number(p.value))) return false;\n } else if (p.op === \"=\") {\n if (actual !== Number(p.value)) return false;\n }\n }\n return true;\n}\n\nfunction filterRepos(\n gh: GitHubStore,\n repos: GitHubRepo[],\n parsed: ParsedSearchQuery,\n authUser: AuthUser | undefined,\n): GitHubRepo[] {\n const qUser = parsed.qualifiers.get(\"user\")?.[0];\n const qOrg = parsed.qualifiers.get(\"org\")?.[0];\n const negUser = parsed.negations.get(\"user\") ?? [];\n const negOrg = parsed.negations.get(\"org\") ?? [];\n\n const inScopes = parsed.qualifiers.get(\"in\") ?? [];\n const negIn = parsed.negations.get(\"in\") ?? [];\n\n return repos.filter((repo) => {\n if (!repoVisibleForSearch(repo, gh, authUser)) return false;\n\n const ologin = ownerLogin(gh, repo);\n if (qUser && ologin.toLowerCase() !== qUser.toLowerCase()) return false;\n if (qOrg && ologin.toLowerCase() !== qOrg.toLowerCase()) return false;\n if (repo.owner_type === \"User\" && negUser.some((n) => ologin.toLowerCase() === n.toLowerCase())) {\n return false;\n }\n if (repo.owner_type === \"Organization\" && negOrg.some((n) => ologin.toLowerCase() === n.toLowerCase())) {\n return false;\n }\n\n for (const lang of parsed.qualifiers.get(\"language\") ?? []) {\n if (!repo.language || repo.language.toLowerCase() !== lang.toLowerCase()) return false;\n }\n for (const lang of parsed.negations.get(\"language\") ?? []) {\n if (repo.language && repo.language.toLowerCase() === lang.toLowerCase()) return false;\n }\n\n for (const topic of parsed.qualifiers.get(\"topic\") ?? []) {\n if (!repo.topics.some((t) => t.toLowerCase() === topic.toLowerCase())) return false;\n }\n for (const topic of parsed.negations.get(\"topic\") ?? []) {\n if (repo.topics.some((t) => t.toLowerCase() === topic.toLowerCase())) return false;\n }\n\n const starRanges = parsed.ranges.get(\"stars\") ?? [];\n const starEq = parsed.qualifiers.get(\"stars\") ?? [];\n if (!matchesNumericPredicate(repo.stargazers_count, starRanges, starEq)) return false;\n for (const nv of parsed.negations.get(\"stars\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(repo.stargazers_count, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && repo.stargazers_count === parseInt(nv, 10)) {\n return false;\n }\n }\n\n const forkRanges = parsed.ranges.get(\"forks\") ?? [];\n const forkEq = parsed.qualifiers.get(\"forks\") ?? [];\n if (!matchesNumericPredicate(repo.forks_count, forkRanges, forkEq)) return false;\n const negForkVals = parsed.negations.get(\"forks\") ?? [];\n if (negForkVals.length) {\n const negPreds = negForkVals.flatMap((s) => {\n const r = parseRangeToken(s);\n return r ? [r] : [];\n });\n const negEq = negForkVals.filter((s) => /^\\d+$/.test(s));\n if (matchesNumericPredicate(repo.forks_count, negPreds, negEq)) return false;\n }\n\n for (const a of parsed.qualifiers.get(\"archived\") ?? []) {\n const want = a === \"true\";\n if (repo.archived !== want) return false;\n }\n for (const a of parsed.negations.get(\"archived\") ?? []) {\n const want = a === \"true\";\n if (repo.archived === want) return false;\n }\n\n const isVals = parsed.qualifiers.get(\"is\") ?? [];\n for (const is of isVals) {\n if (is === \"public\" && repo.private) return false;\n if (is === \"private\" && !repo.private) return false;\n }\n for (const is of parsed.negations.get(\"is\") ?? []) {\n if (is === \"public\" && !repo.private) return false;\n if (is === \"private\" && repo.private) return false;\n }\n\n for (const f of parsed.qualifiers.get(\"fork\") ?? []) {\n const v = f.toLowerCase();\n if (v === \"true\" && !repo.fork) return false;\n if (v === \"false\" && repo.fork) return false;\n if (v === \"only\" && !repo.fork) return false;\n }\n for (const f of parsed.negations.get(\"fork\") ?? []) {\n const v = f.toLowerCase();\n if (v === \"true\" && repo.fork) return false;\n if (v === \"false\" && !repo.fork) return false;\n if (v === \"only\" && repo.fork) return false;\n }\n\n const searchIn = inScopes.length > 0 ? inScopes.map((s) => s.toLowerCase()) : [\"name\", \"description\", \"topics\"];\n\n const text = parsed.text;\n if (text.length) {\n const nameMatch = textMatches(repo.name, text);\n const fullMatch = textMatches(repo.full_name, text);\n const descMatch = repo.description ? textMatches(repo.description, text) : false;\n const topicsMatch = repo.topics.some((t) => textMatches(t, text));\n\n let ok = false;\n if (searchIn.includes(\"name\") && (nameMatch || fullMatch)) ok = true;\n if (searchIn.includes(\"description\") && descMatch) ok = true;\n if (searchIn.includes(\"topics\") && topicsMatch) ok = true;\n if (!ok) return false;\n }\n\n for (const n of negIn) {\n const scope = n.toLowerCase();\n if (scope === \"name\" && (textMatches(repo.name, parsed.text) || textMatches(repo.full_name, parsed.text))) {\n return false;\n }\n if (scope === \"description\" && repo.description && textMatches(repo.description, parsed.text)) {\n return false;\n }\n if (scope === \"topics\" && repo.topics.some((t) => textMatches(t, parsed.text))) {\n return false;\n }\n }\n\n return true;\n });\n}\n\nfunction repoRelevance(repo: GitHubRepo, parsed: ParsedSearchQuery): number {\n const t = parsed.text.trim().toLowerCase();\n if (!t) return 1;\n let score = 0;\n if (repo.name.toLowerCase().includes(t)) score += 5;\n if (repo.full_name.toLowerCase().includes(t)) score += 4;\n if (repo.description?.toLowerCase().includes(t)) score += 2;\n if (repo.topics.some((x) => x.toLowerCase().includes(t))) score += 1;\n return score;\n}\n\nfunction resolveRepoQualifier(gh: GitHubStore, spec: string): GitHubRepo | null {\n const trimmed = spec.trim();\n if (!trimmed.includes(\"/\")) return null;\n return lookupRepo(gh, trimmed.split(\"/\")[0]!, trimmed.split(\"/\")[1]!) ?? null;\n}\n\nfunction issuePrMatchesFilters(\n gh: GitHubStore,\n parsed: ParsedSearchQuery,\n repo: GitHubRepo,\n issue: GitHubIssue | null,\n pr: GitHubPullRequest | null,\n): boolean {\n const repoSpecs = parsed.qualifiers.get(\"repo\") ?? [];\n for (const rs of repoSpecs) {\n const r = resolveRepoQualifier(gh, rs);\n if (!r || r.id !== repo.id) return false;\n }\n for (const rs of parsed.negations.get(\"repo\") ?? []) {\n const r = resolveRepoQualifier(gh, rs);\n if (r && r.id === repo.id) return false;\n }\n\n const isVals = [...(parsed.qualifiers.get(\"is\") ?? []), ...(parsed.qualifiers.get(\"type\") ?? [])].map((x) =>\n x.toLowerCase(),\n );\n const negIs = [...(parsed.negations.get(\"is\") ?? []), ...(parsed.negations.get(\"type\") ?? [])].map((x) =>\n x.toLowerCase(),\n );\n\n const isPr = pr !== null || issue?.is_pull_request === true;\n\n if (isVals.includes(\"issue\") && isPr) return false;\n if (isVals.includes(\"pr\") && !isPr) return false;\n\n if (negIs.includes(\"issue\") && !isPr) return false;\n if (negIs.includes(\"pr\") && isPr) return false;\n\n const stateVals = parsed.qualifiers.get(\"state\") ?? [];\n for (const s of stateVals) {\n const sl = s.toLowerCase();\n if (isPr && pr) {\n if (sl === \"open\" && pr.state !== \"open\") return false;\n if (sl === \"closed\" && pr.state !== \"closed\") return false;\n } else if (issue) {\n if (sl === \"open\" && issue.state !== \"open\") return false;\n if (sl === \"closed\" && issue.state !== \"closed\") return false;\n }\n }\n\n for (const iv of isVals) {\n if (iv === \"open\") {\n if (isPr && pr && pr.state !== \"open\") return false;\n if (!isPr && issue && issue.state !== \"open\") return false;\n }\n if (iv === \"closed\") {\n if (isPr && pr && pr.state !== \"closed\") return false;\n if (!isPr && issue && issue.state !== \"closed\") return false;\n }\n if (iv === \"merged\") {\n if (!isPr || !pr || !pr.merged) return false;\n }\n if (iv === \"draft\") {\n if (!isPr || !pr || !pr.draft) return false;\n }\n }\n\n for (const iv of negIs) {\n if (iv === \"open\") {\n if (isPr && pr && pr.state === \"open\") return false;\n if (!isPr && issue && issue.state === \"open\") return false;\n }\n if (iv === \"closed\") {\n if (isPr && pr && pr.state === \"closed\") return false;\n if (!isPr && issue && issue.state === \"closed\") return false;\n }\n if (iv === \"merged\") {\n if (isPr && pr && pr.merged) return false;\n }\n if (iv === \"draft\") {\n if (isPr && pr && pr.draft) return false;\n }\n }\n\n const authors = parsed.qualifiers.get(\"author\") ?? [];\n for (const a of authors) {\n const u = gh.users.findOneBy(\"login\", a);\n const uid = u?.id;\n if (isPr && pr) {\n if (!uid || pr.user_id !== uid) return false;\n } else if (issue) {\n if (!uid || issue.user_id !== uid) return false;\n }\n }\n for (const a of parsed.negations.get(\"author\") ?? []) {\n const u = gh.users.findOneBy(\"login\", a);\n const uid = u?.id;\n if (isPr && pr && uid !== undefined && pr.user_id === uid) return false;\n if (!isPr && issue && uid !== undefined && issue.user_id === uid) return false;\n }\n\n const assignees = parsed.qualifiers.get(\"assignee\") ?? [];\n for (const a of assignees) {\n const u = gh.users.findOneBy(\"login\", a);\n const uid = u?.id;\n if (!uid) return false;\n const ids = isPr && pr ? pr.assignee_ids : (issue?.assignee_ids ?? []);\n if (!ids.includes(uid)) return false;\n }\n for (const a of parsed.negations.get(\"assignee\") ?? []) {\n const u = gh.users.findOneBy(\"login\", a);\n const uid = u?.id;\n if (uid === undefined) continue;\n const ids = isPr && pr ? pr.assignee_ids : (issue?.assignee_ids ?? []);\n if (ids.includes(uid)) return false;\n }\n\n const labels = parsed.qualifiers.get(\"label\") ?? [];\n for (const lb of labels) {\n const labelIds = isPr && pr ? pr.label_ids : (issue?.label_ids ?? []);\n const names = labelIds\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => l!.name.toLowerCase());\n if (!names.includes(lb.toLowerCase())) return false;\n }\n for (const lb of parsed.negations.get(\"label\") ?? []) {\n const labelIds = isPr && pr ? pr.label_ids : (issue?.label_ids ?? []);\n const names = labelIds\n .map((id) => gh.labels.get(id))\n .filter(Boolean)\n .map((l) => l!.name.toLowerCase());\n if (names.includes(lb.toLowerCase())) return false;\n }\n\n const milestones = parsed.qualifiers.get(\"milestone\") ?? [];\n for (const ms of milestones) {\n const mid = isPr && pr ? pr.milestone_id : issue?.milestone_id;\n const m = mid ? gh.milestones.get(mid) : null;\n if (!m || m.title.toLowerCase() !== ms.toLowerCase()) return false;\n }\n for (const ms of parsed.negations.get(\"milestone\") ?? []) {\n const mid = isPr && pr ? pr.milestone_id : issue?.milestone_id;\n const m = mid ? gh.milestones.get(mid) : null;\n if (m && m.title.toLowerCase() === ms.toLowerCase()) return false;\n }\n\n const commentRanges = parsed.ranges.get(\"comments\") ?? [];\n const commentEq = parsed.qualifiers.get(\"comments\") ?? [];\n const n = isPr && pr ? pr.comments : (issue?.comments ?? 0);\n if (!matchesNumericPredicate(n, commentRanges, commentEq)) return false;\n for (const nv of parsed.negations.get(\"comments\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(n, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && n === parseInt(nv, 10)) return false;\n }\n\n const text = parsed.text.trim();\n if (text.length) {\n const title = isPr && pr ? pr.title : (issue?.title ?? \"\");\n const body = isPr && pr ? (pr.body ?? \"\") : (issue?.body ?? \"\");\n if (!textMatches(title, text) && !textMatches(body, text)) return false;\n }\n\n return true;\n}\n\nfunction userMatchesSearch(gh: GitHubStore, u: GitHubUser, parsed: ParsedSearchQuery): boolean {\n const types = parsed.qualifiers.get(\"type\") ?? [];\n if (types.length && !types.map((t) => t.toLowerCase()).includes(\"user\")) return false;\n for (const t of parsed.negations.get(\"type\") ?? []) {\n if (t.toLowerCase() === \"user\") return false;\n }\n\n const inScopes = parsed.qualifiers.get(\"in\") ?? [];\n const searchIn = inScopes.length > 0 ? inScopes.map((s) => s.toLowerCase()) : [\"login\", \"email\", \"fullname\"];\n\n const text = parsed.text.trim();\n if (text.length) {\n let ok = false;\n if (searchIn.includes(\"login\") && textMatches(u.login, text)) ok = true;\n if (searchIn.includes(\"email\") && u.email && textMatches(u.email, text)) ok = true;\n if (searchIn.includes(\"fullname\") && u.name && textMatches(u.name, text)) ok = true;\n if (!ok) return false;\n }\n\n const rpred = parsed.ranges.get(\"repos\") ?? [];\n const req = parsed.qualifiers.get(\"repos\") ?? [];\n if (!matchesNumericPredicate(u.public_repos, rpred, req)) return false;\n for (const nv of parsed.negations.get(\"repos\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(u.public_repos, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && u.public_repos === parseInt(nv, 10)) return false;\n }\n\n const fpred = parsed.ranges.get(\"followers\") ?? [];\n const feq = parsed.qualifiers.get(\"followers\") ?? [];\n if (!matchesNumericPredicate(u.followers, fpred, feq)) return false;\n for (const nv of parsed.negations.get(\"followers\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(u.followers, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && u.followers === parseInt(nv, 10)) return false;\n }\n\n return true;\n}\n\nfunction orgMatchesSearch(gh: GitHubStore, o: GitHubOrg, parsed: ParsedSearchQuery): boolean {\n void gh;\n const types = parsed.qualifiers.get(\"type\") ?? [];\n if (types.length && !types.map((t) => t.toLowerCase()).includes(\"org\")) return false;\n for (const t of parsed.negations.get(\"type\") ?? []) {\n if (t.toLowerCase() === \"org\") return false;\n }\n\n const inScopes = parsed.qualifiers.get(\"in\") ?? [];\n const searchIn = inScopes.length > 0 ? inScopes.map((s) => s.toLowerCase()) : [\"login\", \"email\", \"fullname\"];\n\n const text = parsed.text.trim();\n if (text.length) {\n let ok = false;\n if (searchIn.includes(\"login\") && textMatches(o.login, text)) ok = true;\n if (searchIn.includes(\"email\") && o.email && textMatches(o.email, text)) ok = true;\n if (searchIn.includes(\"fullname\") && o.name && textMatches(o.name, text)) ok = true;\n if (!ok) return false;\n }\n\n const rpred = parsed.ranges.get(\"repos\") ?? [];\n const req = parsed.qualifiers.get(\"repos\") ?? [];\n if (!matchesNumericPredicate(o.public_repos, rpred, req)) return false;\n for (const nv of parsed.negations.get(\"repos\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(o.public_repos, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && o.public_repos === parseInt(nv, 10)) return false;\n }\n\n const fpred = parsed.ranges.get(\"followers\") ?? [];\n const feq = parsed.qualifiers.get(\"followers\") ?? [];\n if (!matchesNumericPredicate(o.followers, fpred, feq)) return false;\n for (const nv of parsed.negations.get(\"followers\") ?? []) {\n const r = parseRangeToken(nv);\n if (r) {\n if (matchesNumericPredicate(o.followers, [r], [])) return false;\n } else if (/^\\d+$/.test(nv) && o.followers === parseInt(nv, 10)) return false;\n }\n\n return true;\n}\n\nfunction blobText(blob: GitHubBlob): string {\n if (blob.encoding === \"base64\") {\n try {\n return Buffer.from(blob.content, \"base64\").toString(\"utf8\");\n } catch {\n return \"\";\n }\n }\n return blob.content;\n}\n\nfunction buildBlobPathIndex(gh: GitHubStore): Map<string, string> {\n const byRepo = new Map<number, Map<string, string>>();\n for (const tree of gh.trees.all()) {\n let map = byRepo.get(tree.repo_id);\n if (!map) {\n map = new Map();\n byRepo.set(tree.repo_id, map);\n }\n for (const e of tree.tree) {\n if (e.type === \"blob\") {\n if (!map.has(e.sha)) map.set(e.sha, e.path);\n }\n }\n }\n const key = (repoId: number, sha: string) => `${repoId}:${sha}`;\n const flat = new Map<string, string>();\n for (const [repoId, m] of byRepo) {\n for (const [sha, path] of m) {\n flat.set(key(repoId, sha), path);\n }\n }\n return flat;\n}\n\nfunction formatSearchCommit(gh: GitHubStore, commit: GitHubCommit, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n sha: commit.sha,\n node_id: commit.node_id,\n url: `${repoUrl}/commits/${commit.sha}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${commit.sha}`,\n comments_url: `${repoUrl}/comments/${commit.sha}`,\n repository: formatRepo(repo, gh, baseUrl),\n commit: {\n url: `${repoUrl}/git/commits/${commit.sha}`,\n author: {\n name: commit.author_name,\n email: commit.author_email,\n date: commit.author_date,\n },\n committer: {\n name: commit.committer_name,\n email: commit.committer_email,\n date: commit.committer_date,\n },\n message: commit.message,\n },\n author: null as null,\n committer: null as null,\n parents: commit.parent_shas.map((sha) => ({\n sha,\n url: `${repoUrl}/commits/${sha}`,\n })),\n };\n}\n\nfunction loginMatchesCommitAuthor(\n gh: GitHubStore,\n login: string,\n commit: GitHubCommit,\n role: \"author\" | \"committer\",\n): boolean {\n const u = gh.users.findOneBy(\"login\", login);\n const email = (role === \"author\" ? commit.author_email : commit.committer_email).toLowerCase();\n if (u) {\n if (u.email && u.email.toLowerCase() === email) return true;\n if (commit.user_id != null && commit.user_id === u.id) return true;\n }\n const expect = `${login.toLowerCase()}@users.noreply.github.com`;\n return email === expect || email.startsWith(`${login.toLowerCase()}+`);\n}\n\nexport function searchRoutes({ app, store, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/search/repositories\", (c) => {\n const q = c.req.query(\"q\");\n if (q === undefined || q.trim() === \"\") {\n throw new ApiError(422, \"Validation Failed\");\n }\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const sortRaw = (c.req.query(\"sort\") ?? \"best-match\").toLowerCase();\n const order = (c.req.query(\"order\") ?? \"desc\").toLowerCase() === \"asc\" ? \"asc\" : \"desc\";\n const authUser = c.get(\"authUser\");\n\n let list = gh.repos.all().filter((r) => repoVisibleForSearch(r, gh, authUser));\n list = filterRepos(gh, list, parsed, authUser);\n\n if (sortRaw === \"stars\") {\n list.sort((a, b) =>\n order === \"desc\" ? b.stargazers_count - a.stargazers_count : a.stargazers_count - b.stargazers_count,\n );\n } else if (sortRaw === \"forks\") {\n list.sort((a, b) => (order === \"desc\" ? b.forks_count - a.forks_count : a.forks_count - b.forks_count));\n } else if (sortRaw === \"updated\") {\n list.sort((a, b) =>\n order === \"desc\" ? b.updated_at.localeCompare(a.updated_at) : a.updated_at.localeCompare(b.updated_at),\n );\n } else {\n list.sort((a, b) => repoRelevance(b, parsed) - repoRelevance(a, parsed));\n }\n\n const total = list.length;\n const slice = list.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json({\n total_count: total,\n incomplete_results: false,\n items: slice.map((r) => formatRepo(r, gh, baseUrl)),\n });\n });\n\n app.get(\"/search/issues\", (c) => {\n const q = c.req.query(\"q\");\n if (q === undefined || q.trim() === \"\") {\n throw new ApiError(422, \"Validation Failed\");\n }\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const sortRaw = (c.req.query(\"sort\") ?? \"best-match\").toLowerCase();\n const order = (c.req.query(\"order\") ?? \"desc\").toLowerCase() === \"asc\" ? \"asc\" : \"desc\";\n\n const authUser = c.get(\"authUser\");\n type Hit = { kind: \"issue\"; issue: GitHubIssue } | { kind: \"pr\"; pr: GitHubPullRequest };\n const hits: Hit[] = [];\n\n for (const issue of gh.issues.all()) {\n const repo = gh.repos.get(issue.repo_id);\n if (!repo) continue;\n if (!repoVisibleForSearch(repo, gh, authUser)) continue;\n if (issue.is_pull_request) {\n const pr = gh.pullRequests.findBy(\"repo_id\", issue.repo_id).find((p) => p.number === issue.number);\n if (!pr) continue;\n if (!issuePrMatchesFilters(gh, parsed, repo, issue, pr)) continue;\n hits.push({ kind: \"pr\", pr });\n } else {\n if (!issuePrMatchesFilters(gh, parsed, repo, issue, null)) continue;\n hits.push({ kind: \"issue\", issue });\n }\n }\n\n function relevance(h: Hit): number {\n const title = h.kind === \"issue\" ? h.issue.title : h.pr.title;\n const body = h.kind === \"issue\" ? (h.issue.body ?? \"\") : (h.pr.body ?? \"\");\n const t = parsed.text.trim().toLowerCase();\n if (!t) return 1;\n let s = 0;\n if (title.toLowerCase().includes(t)) s += 3;\n if (body.toLowerCase().includes(t)) s += 1;\n return s;\n }\n\n const sorted = [...hits];\n if (sortRaw === \"created\") {\n sorted.sort((a, b) => {\n const ca = a.kind === \"issue\" ? a.issue.created_at : a.pr.created_at;\n const cb = b.kind === \"issue\" ? b.issue.created_at : b.pr.created_at;\n const cmp = ca.localeCompare(cb);\n return order === \"desc\" ? -cmp : cmp;\n });\n } else if (sortRaw === \"updated\") {\n sorted.sort((a, b) => {\n const ca = a.kind === \"issue\" ? a.issue.updated_at : a.pr.updated_at;\n const cb = b.kind === \"issue\" ? b.issue.updated_at : b.pr.updated_at;\n const cmp = ca.localeCompare(cb);\n return order === \"desc\" ? -cmp : cmp;\n });\n } else if (sortRaw === \"comments\") {\n sorted.sort((a, b) => {\n const ca = a.kind === \"issue\" ? a.issue.comments : a.pr.comments;\n const cb = b.kind === \"issue\" ? b.issue.comments : b.pr.comments;\n return order === \"desc\" ? cb - ca : ca - cb;\n });\n } else {\n sorted.sort((a, b) => relevance(b) - relevance(a));\n }\n\n const total = sorted.length;\n const slice = sorted.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const items = slice.map((h) => {\n if (h.kind === \"issue\") {\n return formatIssue(h.issue, gh, baseUrl);\n }\n return formatPullRequest(h.pr, gh, baseUrl);\n });\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items: items.filter(Boolean),\n });\n });\n\n app.get(\"/search/users\", (c) => {\n const q = c.req.query(\"q\");\n if (q === undefined || q.trim() === \"\") {\n throw new ApiError(422, \"Validation Failed\");\n }\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const sortRaw = (c.req.query(\"sort\") ?? \"best-match\").toLowerCase();\n const order = (c.req.query(\"order\") ?? \"desc\").toLowerCase() === \"asc\" ? \"asc\" : \"desc\";\n\n type UHit = { kind: \"user\"; u: GitHubUser } | { kind: \"org\"; o: GitHubOrg };\n const hits: UHit[] = [];\n\n const typeFilters = parsed.qualifiers.get(\"type\")?.map((t) => t.toLowerCase()) ?? [];\n\n if (!typeFilters.length || typeFilters.includes(\"user\")) {\n for (const u of gh.users.all()) {\n if (u.type === \"Organization\") continue;\n if (userMatchesSearch(gh, u, parsed)) hits.push({ kind: \"user\", u });\n }\n }\n if (!typeFilters.length || typeFilters.includes(\"org\")) {\n for (const o of gh.orgs.all()) {\n if (orgMatchesSearch(gh, o, parsed)) hits.push({ kind: \"org\", o });\n }\n }\n\n function rel(h: UHit): number {\n const text = parsed.text.trim().toLowerCase();\n if (!text) return 1;\n if (h.kind === \"user\") {\n let s = 0;\n if (h.u.login.toLowerCase().includes(text)) s += 3;\n if (h.u.name?.toLowerCase().includes(text)) s += 1;\n return s;\n }\n let s = 0;\n if (h.o.login.toLowerCase().includes(text)) s += 3;\n if (h.o.name?.toLowerCase().includes(text)) s += 1;\n return s;\n }\n\n const list = [...hits];\n if (sortRaw === \"followers\") {\n list.sort((a, b) => {\n const fa = a.kind === \"user\" ? a.u.followers : a.o.followers;\n const fb = b.kind === \"user\" ? b.u.followers : b.o.followers;\n return order === \"desc\" ? fb - fa : fa - fb;\n });\n } else if (sortRaw === \"repositories\") {\n list.sort((a, b) => {\n const ra = a.kind === \"user\" ? a.u.public_repos : a.o.public_repos;\n const rb = b.kind === \"user\" ? b.u.public_repos : b.o.public_repos;\n return order === \"desc\" ? rb - ra : ra - rb;\n });\n } else if (sortRaw === \"joined\") {\n list.sort((a, b) => {\n const ca = a.kind === \"user\" ? a.u.created_at : a.o.created_at;\n const cb = b.kind === \"user\" ? b.u.created_at : b.o.created_at;\n const cmp = ca.localeCompare(cb);\n return order === \"desc\" ? -cmp : cmp;\n });\n } else {\n list.sort((a, b) => rel(b) - rel(a));\n }\n\n const total = list.length;\n const slice = list.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const items = slice.map((h) => (h.kind === \"user\" ? formatUser(h.u, baseUrl) : formatOrgBrief(h.o, baseUrl)));\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items,\n });\n });\n\n app.get(\"/search/code\", (c) => {\n const q = c.req.query(\"q\") ?? \"\";\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const authUser = c.get(\"authUser\");\n const blobs = gh.blobs.all();\n if (blobs.length === 0) {\n setLinkHeader(c, 0, 1, per_page);\n return c.json({\n total_count: 0,\n incomplete_results: false,\n items: [],\n });\n }\n\n const pathIdx = buildBlobPathIndex(gh);\n const text = parsed.text.trim();\n const repoSpecs = parsed.qualifiers.get(\"repo\") ?? [];\n const langs = parsed.qualifiers.get(\"language\") ?? [];\n const paths = parsed.qualifiers.get(\"path\") ?? [];\n const filenames = parsed.qualifiers.get(\"filename\") ?? [];\n const inScopes = (parsed.qualifiers.get(\"in\") ?? []).map((x) => x.toLowerCase());\n\n const matches: Array<{\n name: string;\n path: string;\n sha: string;\n score: number;\n repo: GitHubRepo;\n }> = [];\n\n for (const blob of blobs) {\n const repo = gh.repos.get(blob.repo_id);\n if (!repo) continue;\n if (!repoVisibleForSearch(repo, gh, authUser)) continue;\n if (repoSpecs.length) {\n const ok = repoSpecs.some((rs) => {\n const r = resolveRepoQualifier(gh, rs);\n return r && r.id === repo.id;\n });\n if (!ok) continue;\n }\n if (langs.length) {\n const lang = repo.language;\n if (!lang || !langs.some((l) => l.toLowerCase() === lang.toLowerCase())) continue;\n }\n\n const path = pathIdx.get(`${blob.repo_id}:${blob.sha}`) ?? `unknown/${blob.sha.slice(0, 7)}`;\n const base = path.split(\"/\").pop() ?? path;\n if (paths.length && !paths.some((p) => path.toLowerCase().includes(p.toLowerCase()))) continue;\n if (filenames.length && !filenames.some((p) => base.toLowerCase().includes(p.toLowerCase()))) continue;\n\n const content = blobText(blob);\n if (text.length) {\n const inFile = content.toLowerCase().includes(text.toLowerCase());\n const inPath = path.toLowerCase().includes(text.toLowerCase());\n let hit = false;\n if (!inScopes.length) hit = inFile || inPath;\n else {\n if (inScopes.includes(\"file\") && inFile) hit = true;\n if (inScopes.includes(\"path\") && inPath) hit = true;\n }\n if (!hit) continue;\n }\n\n matches.push({\n name: path.split(\"/\").pop() ?? blob.sha,\n path,\n sha: blob.sha,\n score: text.length ? (content.toLowerCase().includes(text.toLowerCase()) ? 2 : 1) : 1,\n repo,\n });\n }\n\n matches.sort((a, b) => b.score - a.score);\n const total = matches.length;\n const slice = matches.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const items = slice.map((m) => {\n const repoUrl = `${baseUrl}/repos/${m.repo.full_name}`;\n return {\n name: m.name,\n path: m.path,\n sha: m.sha,\n url: `${repoUrl}/contents/${m.path}?ref=HEAD`,\n git_url: `${repoUrl}/git/blobs/${m.sha}`,\n html_url: `${baseUrl}/${m.repo.full_name}/blob/HEAD/${m.path}`,\n repository: formatRepo(m.repo, gh, baseUrl),\n score: 1,\n };\n });\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items,\n });\n });\n\n app.get(\"/search/commits\", (c) => {\n const q = c.req.query(\"q\");\n if (q === undefined || q.trim() === \"\") {\n throw new ApiError(422, \"Validation Failed\");\n }\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const sortRaw = (c.req.query(\"sort\") ?? \"best-match\").toLowerCase();\n const order = (c.req.query(\"order\") ?? \"desc\").toLowerCase() === \"asc\" ? \"asc\" : \"desc\";\n\n const authUser = c.get(\"authUser\");\n const repoSpecs = parsed.qualifiers.get(\"repo\") ?? [];\n const authors = parsed.qualifiers.get(\"author\") ?? [];\n const committers = parsed.qualifiers.get(\"committer\") ?? [];\n const mergeVals = parsed.qualifiers.get(\"merge\") ?? [];\n\n let list: GitHubCommit[] = [];\n for (const commit of gh.commits.all()) {\n const repo = gh.repos.get(commit.repo_id);\n if (!repo) continue;\n if (!repoVisibleForSearch(repo, gh, authUser)) continue;\n if (repoSpecs.length) {\n const ok = repoSpecs.some((rs) => {\n const r = resolveRepoQualifier(gh, rs);\n return r && r.id === repo.id;\n });\n if (!ok) continue;\n }\n if (authors.length) {\n const ok = authors.some((a) => loginMatchesCommitAuthor(gh, a, commit, \"author\"));\n if (!ok) continue;\n }\n if (committers.length) {\n const ok = committers.some((a) => loginMatchesCommitAuthor(gh, a, commit, \"committer\"));\n if (!ok) continue;\n }\n if (mergeVals.length) {\n const isMerge = commit.parent_shas.length > 1;\n const ok = mergeVals.every((m) => {\n if (m === \"true\") return isMerge;\n if (m === \"false\") return !isMerge;\n return true;\n });\n if (!ok) continue;\n }\n const t = parsed.text.trim();\n if (t.length && !textMatches(commit.message, t)) continue;\n list.push(commit);\n }\n\n function rel(cm: GitHubCommit): number {\n const t = parsed.text.trim().toLowerCase();\n if (!t) return 1;\n return cm.message.toLowerCase().includes(t) ? 2 : 1;\n }\n\n if (sortRaw === \"author-date\") {\n list = [...list].sort((a, b) => {\n const cmp = a.author_date.localeCompare(b.author_date);\n return order === \"desc\" ? -cmp : cmp;\n });\n } else if (sortRaw === \"committer-date\") {\n list = [...list].sort((a, b) => {\n const cmp = a.committer_date.localeCompare(b.committer_date);\n return order === \"desc\" ? -cmp : cmp;\n });\n } else {\n list = [...list].sort((a, b) => rel(b) - rel(a));\n }\n\n const total = list.length;\n const slice = list.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const items = slice.map((commit) => {\n const repo = gh.repos.get(commit.repo_id)!;\n return formatSearchCommit(gh, commit, repo, baseUrl);\n });\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items,\n });\n });\n\n app.get(\"/search/topics\", (c) => {\n const q = c.req.query(\"q\") ?? \"\";\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const text = parsed.text.trim().toLowerCase();\n\n const topicSet = new Map<string, { name: string; updated: string }>();\n for (const repo of gh.repos.all()) {\n for (const t of repo.topics) {\n const key = t.toLowerCase();\n if (!topicSet.has(key)) {\n topicSet.set(key, { name: t, updated: repo.updated_at });\n } else {\n const cur = topicSet.get(key)!;\n if (repo.updated_at > cur.updated) topicSet.set(key, { name: t, updated: repo.updated_at });\n }\n }\n }\n\n let topics = Array.from(topicSet.values());\n if (text.length) {\n topics = topics.filter((t) => t.name.toLowerCase().includes(text));\n }\n\n topics.sort((a, b) => a.name.localeCompare(b.name));\n const total = topics.length;\n const slice = topics.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const items = slice.map((t) => ({\n name: t.name,\n display_name: t.name,\n short_description: \"\",\n created_by: null as string | null,\n created_at: t.updated,\n updated_at: t.updated,\n }));\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items,\n });\n });\n\n app.get(\"/search/labels\", (c) => {\n const q = c.req.query(\"q\") ?? \"\";\n const rawId = c.req.query(\"repository_id\");\n if (rawId === undefined || rawId === \"\") {\n throw new ApiError(422, \"Validation Failed: repository_id is required\");\n }\n const repositoryId = parseInt(rawId, 10);\n if (Number.isNaN(repositoryId)) {\n throw new ApiError(422, \"Validation Failed: invalid repository_id\");\n }\n const repo = gh.repos.get(repositoryId);\n if (!repo) {\n throw new ApiError(404, \"Not Found\");\n }\n\n const parsed = parseSearchQuery(q);\n const { page, per_page } = parsePagination(c);\n const text = parsed.text.trim().toLowerCase();\n\n let labels = gh.labels.findBy(\"repo_id\", repositoryId);\n if (text.length) {\n labels = labels.filter(\n (l) => l.name.toLowerCase().includes(text) || (l.description && l.description.toLowerCase().includes(text)),\n );\n }\n\n labels.sort((a, b) => a.name.localeCompare(b.name));\n const total = labels.length;\n const slice = labels.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n return c.json({\n total_count: total,\n incomplete_results: false,\n items: slice.map((l) => ({\n id: l.id,\n node_id: l.node_id,\n url: `${baseUrl}/repos/${repo.full_name}/labels/${encodeURIComponent(l.name)}`,\n name: l.name,\n color: l.color,\n default: l.default,\n description: l.description,\n })),\n });\n });\n}\n","import type { RouteContext, AuthUser } from \"@emulators/core\";\nimport { ApiError, forbidden, parseJsonBody, parsePagination, setLinkHeader, unauthorized } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubArtifact,\n GitHubJob,\n GitHubOrg,\n GitHubRepo,\n GitHubSecret,\n GitHubUser,\n GitHubWorkflow,\n GitHubWorkflowRun,\n} from \"../entities.js\";\nimport { formatRepo, formatUser, generateNodeId, generateSha, lookupRepo, timestamp } from \"../helpers.js\";\nimport {\n assertAuthenticatedUser,\n assertRepoAdmin,\n assertRepoRead,\n getActorUser,\n notFoundResponse,\n ownerLoginOf,\n} from \"../route-helpers.js\";\n\nfunction listOrgMembersDeduped(gh: GitHubStore, orgId: number): { user: GitHubUser; orgRole: \"admin\" | \"member\" }[] {\n const byUser = new Map<number, { user: GitHubUser; isAdmin: boolean }>();\n for (const team of gh.teams.findBy(\"org_id\", orgId)) {\n for (const m of gh.teamMembers.findBy(\"team_id\", team.id)) {\n const user = gh.users.get(m.user_id);\n if (!user) continue;\n const isAdmin = m.role === \"maintainer\";\n const prev = byUser.get(user.id);\n if (!prev) {\n byUser.set(user.id, { user, isAdmin });\n } else {\n byUser.set(user.id, { user, isAdmin: prev.isAdmin || isAdmin });\n }\n }\n }\n return [...byUser.values()]\n .map(({ user, isAdmin }) => ({\n user,\n orgRole: isAdmin ? (\"admin\" as const) : (\"member\" as const),\n }))\n .sort((a, b) => a.user.id - b.user.id);\n}\n\nfunction orgRoleForUser(gh: GitHubStore, orgId: number, userId: number): \"admin\" | \"member\" | null {\n const row = listOrgMembersDeduped(gh, orgId).find((r) => r.user.id === userId);\n return row?.orgRole ?? null;\n}\n\nfunction assertOrgAdmin(gh: GitHubStore, authUser: AuthUser | undefined, org: GitHubOrg) {\n if (!authUser) throw unauthorized();\n const user = getActorUser(gh, authUser);\n if (!user) throw unauthorized();\n if (orgRoleForUser(gh, org.id, user.id) === \"admin\") return;\n throw forbidden();\n}\n\nfunction getOrgByLogin(gh: GitHubStore, login: string): GitHubOrg | undefined {\n return gh.orgs.findOneBy(\"login\", login);\n}\n\nfunction resolveWorkflow(gh: GitHubStore, repoId: number, param: string): GitHubWorkflow | undefined {\n const trimmed = param.trim();\n const asNum = parseInt(trimmed, 10);\n if (!Number.isNaN(asNum) && String(asNum) === trimmed) {\n const w = gh.workflows.get(asNum);\n if (w && w.repo_id === repoId) return w;\n }\n const decoded = decodeURIComponent(trimmed);\n return gh.workflows\n .findBy(\"repo_id\", repoId)\n .find((w) => w.path === decoded || w.path.endsWith(`/${decoded}`) || w.name === decoded);\n}\n\nfunction resolveRefToBranchAndSha(gh: GitHubStore, repo: GitHubRepo, ref: string): { branch: string; sha: string } {\n const name = ref.replace(/^refs\\/heads\\//, \"\").replace(/^refs\\/tags\\//, \"\");\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === name);\n if (branch) return { branch: branch.name, sha: branch.sha };\n return { branch: name, sha: generateSha() };\n}\n\nfunction nextRunNumber(gh: GitHubStore, workflowId: number, repoId: number): number {\n const runs = gh.workflowRuns.findBy(\"workflow_id\", workflowId).filter((r) => r.repo_id === repoId);\n return runs.reduce((m, r) => Math.max(m, r.run_number), 0) + 1;\n}\n\nfunction findRepoSecret(gh: GitHubStore, repoId: number, name: string): GitHubSecret | undefined {\n return gh.secrets.all().find((s) => s.repo_id === repoId && s.org_id === null && s.name === name);\n}\n\nfunction findOrgSecret(gh: GitHubStore, orgId: number, name: string): GitHubSecret | undefined {\n return gh.secrets.all().find((s) => s.org_id === orgId && s.repo_id === null && s.name === name);\n}\n\nfunction listRepoSecrets(gh: GitHubStore, repoId: number): GitHubSecret[] {\n return gh.secrets.all().filter((s) => s.repo_id === repoId && s.org_id === null);\n}\n\nfunction listOrgSecrets(gh: GitHubStore, orgId: number): GitHubSecret[] {\n return gh.secrets.all().filter((s) => s.org_id === orgId && s.repo_id === null);\n}\n\nfunction deleteJobsForRun(gh: GitHubStore, runId: number) {\n for (const j of gh.jobs.findBy(\"run_id\", runId)) {\n gh.jobs.delete(j.id);\n }\n}\n\nfunction deleteArtifactsForRun(gh: GitHubStore, runId: number) {\n for (const a of gh.artifacts.findBy(\"run_id\", runId)) {\n gh.artifacts.delete(a.id);\n }\n}\n\nfunction seedStubJobs(gh: GitHubStore, repo: GitHubRepo, run: GitHubWorkflowRun) {\n const job = gh.jobs.insert({\n node_id: \"\",\n repo_id: repo.id,\n run_id: run.id,\n name: \"build\",\n status: run.status === \"completed\" ? \"completed\" : \"in_progress\",\n conclusion: run.status === \"completed\" ? run.conclusion : null,\n started_at: run.run_started_at,\n completed_at: run.status === \"completed\" ? run.updated_at : null,\n runner_id: 1,\n runner_name: \"Hosted Agent\",\n steps: [\n {\n name: \"Set up job\",\n status: run.status === \"completed\" ? \"completed\" : \"in_progress\",\n conclusion: run.status === \"completed\" ? run.conclusion : null,\n number: 1,\n started_at: run.run_started_at,\n completed_at: run.status === \"completed\" ? run.updated_at : null,\n },\n ],\n } as Omit<GitHubJob, \"id\" | \"created_at\" | \"updated_at\">);\n gh.jobs.update(job.id, { node_id: generateNodeId(\"Job\", job.id) });\n}\n\nfunction formatWorkflow(w: GitHubWorkflow, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n id: w.id,\n node_id: w.node_id,\n name: w.name,\n path: w.path,\n state: w.state,\n created_at: w.created_at,\n updated_at: w.updated_at,\n url: `${repoUrl}/actions/workflows/${w.id}`,\n html_url: `${baseUrl}/${repo.full_name}/blob/${repo.default_branch}/${w.path}`,\n badge_url:\n w.badge_url ||\n `${baseUrl}/${repo.full_name}/workflows/${encodeURIComponent(w.path.replace(/^\\/.github\\/workflows\\//, \"\"))}/badge.svg`,\n };\n}\n\nfunction formatWorkflowRun(run: GitHubWorkflowRun, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const wf = gh.workflows.get(run.workflow_id);\n const actor = gh.users.get(run.actor_id);\n const wfPath = wf?.path ?? \".github/workflows/main.yml\";\n return {\n id: run.id,\n name: run.name,\n node_id: run.node_id,\n head_branch: run.head_branch,\n head_sha: run.head_sha,\n path: wfPath,\n display_title: run.name,\n run_number: run.run_number,\n event: run.event,\n status: run.status,\n conclusion: run.conclusion,\n workflow_id: run.workflow_id,\n check_suite_id: null,\n url: `${repoUrl}/actions/runs/${run.id}`,\n html_url: `${baseUrl}/${repo.full_name}/actions/runs/${run.id}`,\n pull_requests: [],\n created_at: run.created_at,\n updated_at: run.updated_at,\n actor: actor ? formatUser(actor, baseUrl) : null,\n run_attempt: run.run_attempt,\n run_started_at: run.run_started_at,\n triggering_actor: actor ? formatUser(actor, baseUrl) : null,\n workflow_url: wf ? `${repoUrl}/actions/workflows/${wf.id}` : null,\n repository: formatRepo(repo, gh, baseUrl),\n head_commit: {\n id: run.head_sha,\n tree_id: generateSha(),\n message: \"Workflow run\",\n timestamp: run.created_at,\n author: actor\n ? { name: actor.login, email: `${actor.login}@users.noreply.github.com` }\n : { name: \"unknown\", email: \"unknown@users.noreply.github.com\" },\n },\n };\n}\n\nfunction formatJob(job: GitHubJob, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const run = gh.workflowRuns.get(job.run_id);\n const headSha = run?.head_sha ?? \"\";\n return {\n id: job.id,\n run_id: job.run_id,\n workflow_name: run?.name ?? \"workflow\",\n head_branch: run?.head_branch ?? \"\",\n run_url: `${repoUrl}/actions/runs/${job.run_id}`,\n node_id: job.node_id,\n head_sha: headSha,\n status: job.status,\n conclusion: job.conclusion,\n started_at: job.started_at,\n completed_at: job.completed_at,\n name: job.name,\n steps: job.steps,\n url: `${repoUrl}/actions/jobs/${job.id}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${headSha}/checks`,\n check_run_url: `${baseUrl}/repos/${repo.full_name}/check-runs/${job.id}`,\n labels: [\"hosted\"],\n runner_id: job.runner_id,\n runner_name: job.runner_name,\n runner_group_id: 1,\n runner_group_name: \"GitHub Actions\",\n created_at: job.created_at,\n updated_at: job.updated_at,\n };\n}\n\nfunction formatArtifact(a: GitHubArtifact, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const run = gh.workflowRuns.get(a.run_id);\n return {\n id: a.id,\n node_id: a.node_id,\n name: a.name,\n size_in_bytes: a.size_in_bytes,\n url: `${repoUrl}/actions/artifacts/${a.id}`,\n archive_download_url: `${repoUrl}/actions/artifacts/${a.id}/zip`,\n expired: a.expired,\n digest: null,\n created_at: a.created_at,\n expires_at: a.expires_at,\n workflow_run: run\n ? {\n id: run.id,\n repository_id: repo.id,\n head_repository_id: repo.id,\n head_branch: run.head_branch,\n head_sha: run.head_sha,\n }\n : null,\n };\n}\n\nfunction filterRuns(\n gh: GitHubStore,\n runs: GitHubWorkflowRun[],\n q: { actor?: string; branch?: string; event?: string; status?: string },\n) {\n let out = runs;\n if (q.actor) {\n const u = gh.users.findOneBy(\"login\", q.actor);\n out = u ? out.filter((r) => r.actor_id === u.id) : [];\n }\n if (q.branch) {\n out = out.filter((r) => r.head_branch === q.branch);\n }\n if (q.event) {\n out = out.filter((r) => r.event === q.event);\n }\n if (q.status) {\n out = out.filter((r) => r.status === q.status);\n }\n return out.sort((a, b) => b.created_at.localeCompare(a.created_at));\n}\n\nexport function actionsRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n app.get(\"/repos/:owner/:repo/actions/workflows\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const workflows = gh.workflows.findBy(\"repo_id\", repo.id).sort((a, b) => a.path.localeCompare(b.path));\n return c.json({\n total_count: workflows.length,\n workflows: workflows.map((w) => formatWorkflow(w, repo, gh, baseUrl)),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/workflows/:workflow_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const w = resolveWorkflow(gh, repo.id, c.req.param(\"workflow_id\")!);\n if (!w) throw notFoundResponse();\n return c.json(formatWorkflow(w, repo, gh, baseUrl));\n });\n\n app.put(\"/repos/:owner/:repo/actions/workflows/:workflow_id/disable\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const w = resolveWorkflow(gh, repo.id, c.req.param(\"workflow_id\")!);\n if (!w) throw notFoundResponse();\n gh.workflows.update(w.id, { state: \"disabled_manually\" });\n return c.body(null, 204);\n });\n\n app.put(\"/repos/:owner/:repo/actions/workflows/:workflow_id/enable\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const w = resolveWorkflow(gh, repo.id, c.req.param(\"workflow_id\")!);\n if (!w) throw notFoundResponse();\n gh.workflows.update(w.id, { state: \"active\" });\n return c.body(null, 204);\n });\n\n app.post(\"/repos/:owner/:repo/actions/workflows/:workflow_id/dispatches\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertAuthenticatedUser(gh, c.get(\"authUser\"));\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const w = resolveWorkflow(gh, repo.id, c.req.param(\"workflow_id\")!);\n if (!w) throw notFoundResponse();\n if (w.state !== \"active\") {\n throw new ApiError(422, \"Workflow is not active\");\n }\n const body = await parseJsonBody(c);\n const ref = typeof body.ref === \"string\" ? body.ref : repo.default_branch;\n const { branch, sha } = resolveRefToBranchAndSha(gh, repo, ref);\n const now = timestamp();\n const runNumber = nextRunNumber(gh, w.id, repo.id);\n const run = gh.workflowRuns.insert({\n node_id: \"\",\n repo_id: repo.id,\n workflow_id: w.id,\n name: w.name,\n head_branch: branch,\n head_sha: sha,\n run_number: runNumber,\n event: \"workflow_dispatch\",\n status: \"queued\",\n conclusion: null,\n actor_id: actor.id,\n run_attempt: 1,\n run_started_at: now,\n } as Omit<GitHubWorkflowRun, \"id\" | \"created_at\" | \"updated_at\">);\n gh.workflowRuns.update(run.id, { node_id: generateNodeId(\"WorkflowRun\", run.id) });\n const created = gh.workflowRuns.get(run.id)!;\n seedStubJobs(gh, repo, created);\n const ownerLogin = ownerLoginOf(gh, repo);\n void webhooks.dispatch(\n \"workflow_dispatch\",\n undefined,\n {\n ref: `refs/heads/${branch}`,\n inputs: typeof body.inputs === \"object\" && body.inputs ? body.inputs : {},\n workflow: formatWorkflow(w, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n void webhooks.dispatch(\n \"workflow_run\",\n \"requested\",\n {\n workflow_run: formatWorkflowRun(created, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/actions/runs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const { page, per_page } = parsePagination(c);\n const actor = c.req.query(\"actor\") ?? undefined;\n const branch = c.req.query(\"branch\") ?? undefined;\n const event = c.req.query(\"event\") ?? undefined;\n const status = c.req.query(\"status\") ?? undefined;\n const all = gh.workflowRuns.findBy(\"repo_id\", repo.id);\n const filtered = filterRuns(gh, all, { actor, branch, event, status });\n const total = filtered.length;\n const slice = filtered.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json({\n total_count: total,\n workflow_runs: slice.map((r) => formatWorkflowRun(r, repo, gh, baseUrl)),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/runs/:run_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n return c.json(formatWorkflowRun(run, repo, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/actions/workflows/:workflow_id/runs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const w = resolveWorkflow(gh, repo.id, c.req.param(\"workflow_id\")!);\n if (!w) throw notFoundResponse();\n const { page, per_page } = parsePagination(c);\n const actor = c.req.query(\"actor\") ?? undefined;\n const branch = c.req.query(\"branch\") ?? undefined;\n const event = c.req.query(\"event\") ?? undefined;\n const status = c.req.query(\"status\") ?? undefined;\n const all = gh.workflowRuns.findBy(\"repo_id\", repo.id).filter((r) => r.workflow_id === w.id);\n const filtered = filterRuns(gh, all, { actor, branch, event, status });\n const total = filtered.length;\n const slice = filtered.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json({\n total_count: total,\n workflow_runs: slice.map((r) => formatWorkflowRun(r, repo, gh, baseUrl)),\n });\n });\n\n app.post(\"/repos/:owner/:repo/actions/runs/:run_id/cancel\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n gh.workflowRuns.update(run.id, { status: \"completed\", conclusion: \"cancelled\" });\n const updated = gh.workflowRuns.get(run.id)!;\n const ownerLogin = ownerLoginOf(gh, repo);\n const actor = gh.users.get(run.actor_id);\n void webhooks.dispatch(\n \"workflow_run\",\n \"completed\",\n {\n workflow_run: formatWorkflowRun(updated, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: actor ? formatUser(actor, baseUrl) : null,\n },\n ownerLogin,\n repo.name,\n );\n return c.body(null, 202);\n });\n\n app.post(\"/repos/:owner/:repo/actions/runs/:run_id/rerun\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const parent = gh.workflowRuns.get(runId);\n if (!parent || parent.repo_id !== repo.id) throw notFoundResponse();\n const wf = gh.workflows.get(parent.workflow_id);\n if (!wf) throw notFoundResponse();\n const now = timestamp();\n const runNumber = nextRunNumber(gh, wf.id, repo.id);\n const run = gh.workflowRuns.insert({\n node_id: \"\",\n repo_id: repo.id,\n workflow_id: wf.id,\n name: parent.name,\n head_branch: parent.head_branch,\n head_sha: parent.head_sha,\n run_number: runNumber,\n event: parent.event,\n status: \"queued\",\n conclusion: null,\n actor_id: parent.actor_id,\n run_attempt: parent.run_attempt + 1,\n run_started_at: now,\n } as Omit<GitHubWorkflowRun, \"id\" | \"created_at\" | \"updated_at\">);\n gh.workflowRuns.update(run.id, { node_id: generateNodeId(\"WorkflowRun\", run.id) });\n const created = gh.workflowRuns.get(run.id)!;\n seedStubJobs(gh, repo, created);\n const ownerLogin = ownerLoginOf(gh, repo);\n const actor = gh.users.get(created.actor_id);\n void webhooks.dispatch(\n \"workflow_run\",\n \"requested\",\n {\n workflow_run: formatWorkflowRun(created, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: actor ? formatUser(actor, baseUrl) : null,\n },\n ownerLogin,\n repo.name,\n );\n return c.json(formatWorkflowRun(created, repo, gh, baseUrl), 201);\n });\n\n app.delete(\"/repos/:owner/:repo/actions/runs/:run_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n deleteArtifactsForRun(gh, run.id);\n deleteJobsForRun(gh, run.id);\n gh.workflowRuns.delete(run.id);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/actions/runs/:run_id/logs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n return c.text(`2025-01-01T00:00:00.0000000Z Workflow run ${run.id} logs (stub)\\n${run.head_sha}\\n`, 200, {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/runs/:run_id/jobs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n const jobs = gh.jobs.findBy(\"run_id\", runId).filter((j) => j.repo_id === repo.id);\n return c.json({\n total_count: jobs.length,\n jobs: jobs.map((j) => formatJob(j, repo, gh, baseUrl)),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/jobs/:job_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const jobId = parseInt(c.req.param(\"job_id\")!, 10);\n const job = gh.jobs.get(jobId);\n if (!job || job.repo_id !== repo.id) throw notFoundResponse();\n return c.json(formatJob(job, repo, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/actions/jobs/:job_id/logs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const jobId = parseInt(c.req.param(\"job_id\")!, 10);\n const job = gh.jobs.get(jobId);\n if (!job || job.repo_id !== repo.id) throw notFoundResponse();\n return c.text(`2025-01-01T00:00:00.0000000Z Job ${job.id} logs (stub)\\n`, 200, {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/artifacts\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const { page, per_page } = parsePagination(c);\n const all = gh.artifacts.findBy(\"repo_id\", repo.id).sort((a, b) => b.created_at.localeCompare(a.created_at));\n const total = all.length;\n const slice = all.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json({\n total_count: total,\n artifacts: slice.map((a) => formatArtifact(a, repo, gh, baseUrl)),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/runs/:run_id/artifacts\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"run_id\")!, 10);\n const run = gh.workflowRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n const arts = gh.artifacts.findBy(\"run_id\", runId).filter((a) => a.repo_id === repo.id);\n return c.json({\n total_count: arts.length,\n artifacts: arts.map((a) => formatArtifact(a, repo, gh, baseUrl)),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/artifacts/:artifact_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const artifactId = parseInt(c.req.param(\"artifact_id\")!, 10);\n const a = gh.artifacts.get(artifactId);\n if (!a || a.repo_id !== repo.id) throw notFoundResponse();\n return c.json(formatArtifact(a, repo, gh, baseUrl));\n });\n\n app.delete(\"/repos/:owner/:repo/actions/artifacts/:artifact_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const artifactId = parseInt(c.req.param(\"artifact_id\")!, 10);\n const a = gh.artifacts.get(artifactId);\n if (!a || a.repo_id !== repo.id) throw notFoundResponse();\n gh.artifacts.delete(a.id);\n return c.body(null, 204);\n });\n\n app.get(\"/repos/:owner/:repo/actions/secrets\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const secrets = listRepoSecrets(gh, repo.id).sort((a, b) => a.name.localeCompare(b.name));\n return c.json({\n total_count: secrets.length,\n secrets: secrets.map((s) => ({\n name: s.name,\n created_at: s.created_at,\n updated_at: s.updated_at,\n })),\n });\n });\n\n app.get(\"/repos/:owner/:repo/actions/secrets/:secret_name\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const name = c.req.param(\"secret_name\")!;\n const s = findRepoSecret(gh, repo.id, name);\n if (!s) throw notFoundResponse();\n return c.json({\n name: s.name,\n visibility: s.visibility,\n created_at: s.created_at,\n updated_at: s.updated_at,\n });\n });\n\n app.put(\"/repos/:owner/:repo/actions/secrets/:secret_name\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n await parseJsonBody(c);\n const name = c.req.param(\"secret_name\")!;\n const existing = findRepoSecret(gh, repo.id, name);\n if (existing) {\n gh.secrets.update(existing.id, { visibility: existing.visibility });\n return c.body(null, 204);\n }\n gh.secrets.insert({\n repo_id: repo.id,\n org_id: null,\n name,\n visibility: \"all\",\n } as Omit<GitHubSecret, \"id\" | \"created_at\" | \"updated_at\">);\n return c.body(null, 201);\n });\n\n app.delete(\"/repos/:owner/:repo/actions/secrets/:secret_name\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoAdmin(gh, c.get(\"authUser\"), repo);\n const name = c.req.param(\"secret_name\")!;\n const s = findRepoSecret(gh, repo.id, name);\n if (!s) throw notFoundResponse();\n gh.secrets.delete(s.id);\n return c.body(null, 204);\n });\n\n app.get(\"/orgs/:org/actions/secrets\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n const secrets = listOrgSecrets(gh, org.id).sort((a, b) => a.name.localeCompare(b.name));\n return c.json({\n total_count: secrets.length,\n secrets: secrets.map((s) => ({\n name: s.name,\n created_at: s.created_at,\n updated_at: s.updated_at,\n })),\n });\n });\n\n app.get(\"/orgs/:org/actions/secrets/:secret_name\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n const name = c.req.param(\"secret_name\")!;\n const s = findOrgSecret(gh, org.id, name);\n if (!s) throw notFoundResponse();\n return c.json({\n name: s.name,\n visibility: s.visibility,\n created_at: s.created_at,\n updated_at: s.updated_at,\n });\n });\n\n app.put(\"/orgs/:org/actions/secrets/:secret_name\", async (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n await parseJsonBody(c);\n const name = c.req.param(\"secret_name\")!;\n const existing = findOrgSecret(gh, org.id, name);\n if (existing) {\n gh.secrets.update(existing.id, { visibility: existing.visibility });\n return c.body(null, 204);\n }\n gh.secrets.insert({\n repo_id: null,\n org_id: org.id,\n name,\n visibility: \"all\",\n } as Omit<GitHubSecret, \"id\" | \"created_at\" | \"updated_at\">);\n return c.body(null, 201);\n });\n\n app.delete(\"/orgs/:org/actions/secrets/:secret_name\", (c) => {\n const orgLogin = c.req.param(\"org\")!;\n const org = getOrgByLogin(gh, orgLogin);\n if (!org) throw notFoundResponse();\n assertOrgAdmin(gh, c.get(\"authUser\"), org);\n const name = c.req.param(\"secret_name\")!;\n const s = findOrgSecret(gh, org.id, name);\n if (!s) throw notFoundResponse();\n gh.secrets.delete(s.id);\n return c.body(null, 204);\n });\n}\n","import type { RouteContext, WebhookDispatcher } from \"@emulators/core\";\nimport { ApiError, parseJsonBody, parsePagination, setLinkHeader } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport type { GitHubStore } from \"../store.js\";\nimport type {\n GitHubCheckRun,\n GitHubCheckSuite,\n GitHubCommit,\n GitHubRepo,\n GitHubUser,\n GitHubCheckAnnotation,\n} from \"../entities.js\";\nimport { formatRepo, formatUser, generateNodeId, lookupRepo, timestamp } from \"../helpers.js\";\nimport { assertRepoRead, assertRepoWrite, notFoundResponse, ownerLoginOf } from \"../route-helpers.js\";\n\nconst CONCLUSION_RANK: Record<string, number> = {\n success: 0,\n neutral: 1,\n skipped: 2,\n cancelled: 3,\n timed_out: 4,\n action_required: 5,\n failure: 6,\n};\n\nfunction findCommitInRepo(gh: GitHubStore, repoId: number, shaParam: string): GitHubCommit | undefined {\n const want = shaParam.toLowerCase();\n const list = gh.commits.findBy(\"repo_id\", repoId);\n return list.find((c) => c.sha === shaParam || c.sha.toLowerCase() === want || c.sha.startsWith(shaParam));\n}\n\nfunction resolveRefToHeadSha(gh: GitHubStore, repo: GitHubRepo, refParam: string): string | undefined {\n const commit = findCommitInRepo(gh, repo.id, refParam);\n if (commit) return commit.sha;\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.name === refParam);\n if (branch) return branch.sha;\n const fullRef = refParam.startsWith(\"refs/\") ? refParam : `refs/heads/${refParam}`;\n const r = gh.refs.findBy(\"repo_id\", repo.id).find((x) => x.ref === fullRef);\n if (r) return r.sha;\n return undefined;\n}\n\nfunction headBranchForSha(gh: GitHubStore, repo: GitHubRepo, headSha: string): string {\n const branch = gh.branches.findBy(\"repo_id\", repo.id).find((b) => b.sha === headSha);\n if (branch) return branch.name;\n return repo.default_branch;\n}\n\nfunction getOrCreateCheckSuite(\n gh: GitHubStore,\n repo: GitHubRepo,\n headSha: string,\n headBranch?: string | null,\n): GitHubCheckSuite {\n const existing = gh.checkSuites.findBy(\"repo_id\", repo.id).find((s) => s.head_sha === headSha);\n if (existing) return existing;\n\n const hb = headBranch?.trim() || headBranchForSha(gh, repo, headSha);\n const row = gh.checkSuites.insert({\n node_id: \"\",\n repo_id: repo.id,\n head_branch: hb,\n head_sha: headSha,\n status: \"queued\",\n conclusion: null,\n before: \"\",\n after: headSha,\n app_id: null,\n } as Omit<GitHubCheckSuite, \"id\" | \"created_at\" | \"updated_at\">);\n gh.checkSuites.update(row.id, { node_id: generateNodeId(\"CheckSuite\", row.id) });\n return gh.checkSuites.get(row.id)!;\n}\n\nfunction worstConclusion(\n conclusions: NonNullable<GitHubCheckRun[\"conclusion\"]>[],\n): NonNullable<GitHubCheckSuite[\"conclusion\"]> {\n let best: NonNullable<GitHubCheckSuite[\"conclusion\"]> = \"success\";\n let rank = -1;\n for (const c of conclusions) {\n const r = CONCLUSION_RANK[c] ?? 3;\n if (r > rank) {\n rank = r;\n best = c;\n }\n }\n return best;\n}\n\nfunction recomputeSuiteFromRuns(runs: GitHubCheckRun[]): {\n status: GitHubCheckSuite[\"status\"];\n conclusion: GitHubCheckSuite[\"conclusion\"];\n} {\n if (runs.length === 0) {\n return { status: \"completed\", conclusion: null };\n }\n const allDone = runs.every((r) => r.status === \"completed\");\n if (allDone) {\n const conclusions = runs.map((r) => r.conclusion).filter((c): c is NonNullable<typeof c> => c != null);\n return {\n status: \"completed\",\n conclusion: conclusions.length ? worstConclusion(conclusions) : null,\n };\n }\n const anyInProgress = runs.some((r) => r.status === \"in_progress\");\n if (anyInProgress) {\n return { status: \"in_progress\", conclusion: null };\n }\n const anyQueued = runs.some((r) => r.status === \"queued\");\n const anyCompleted = runs.some((r) => r.status === \"completed\");\n if (anyCompleted && anyQueued) {\n return { status: \"in_progress\", conclusion: null };\n }\n if (anyQueued) {\n return { status: \"queued\", conclusion: null };\n }\n return { status: \"in_progress\", conclusion: null };\n}\n\nfunction recomputeCheckSuite(gh: GitHubStore, suiteId: number) {\n const suite = gh.checkSuites.get(suiteId);\n if (!suite) return;\n const runs = gh.checkRuns.findBy(\"repo_id\", suite.repo_id).filter((r) => r.check_suite_id === suiteId);\n const { status, conclusion } = recomputeSuiteFromRuns(runs);\n gh.checkSuites.update(suiteId, { status, conclusion });\n}\n\nfunction parseConclusion(raw: unknown): GitHubCheckRun[\"conclusion\"] | undefined {\n if (raw === undefined) return undefined;\n if (raw === null) return null;\n if (typeof raw !== \"string\") throw new ApiError(422, \"Invalid conclusion\");\n const allowed = new Set([\"success\", \"failure\", \"neutral\", \"cancelled\", \"skipped\", \"timed_out\", \"action_required\"]);\n if (!allowed.has(raw)) throw new ApiError(422, \"Invalid conclusion\");\n return raw as GitHubCheckRun[\"conclusion\"];\n}\n\nfunction parseStatus(raw: unknown, fallback: GitHubCheckRun[\"status\"]): GitHubCheckRun[\"status\"] {\n if (raw === undefined || raw === null) return fallback;\n if (raw !== \"queued\" && raw !== \"in_progress\" && raw !== \"completed\") {\n throw new ApiError(422, \"Invalid status\");\n }\n return raw;\n}\n\nfunction normalizeAnnotations(raw: unknown): GitHubCheckAnnotation[] {\n if (raw === undefined || raw === null) return [];\n if (!Array.isArray(raw)) throw new ApiError(422, \"Invalid annotations\");\n const out: GitHubCheckAnnotation[] = [];\n for (const a of raw) {\n if (!a || typeof a !== \"object\") throw new ApiError(422, \"Invalid annotation\");\n const o = a as Record<string, unknown>;\n const path = typeof o.path === \"string\" ? o.path : null;\n const message = typeof o.message === \"string\" ? o.message : null;\n const start_line = typeof o.start_line === \"number\" ? o.start_line : parseInt(String(o.start_line), 10);\n const end_line = typeof o.end_line === \"number\" ? o.end_line : parseInt(String(o.end_line), 10);\n const annotation_level = typeof o.annotation_level === \"string\" ? o.annotation_level : \"notice\";\n if (!path || !message || !Number.isFinite(start_line) || !Number.isFinite(end_line)) {\n throw new ApiError(422, \"Invalid annotation fields\");\n }\n out.push({\n path,\n start_line,\n end_line,\n annotation_level,\n message,\n });\n }\n return out;\n}\n\nfunction formatCheckSuiteBrief(suite: GitHubCheckSuite, repo: GitHubRepo, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n id: suite.id,\n node_id: suite.node_id,\n head_branch: suite.head_branch,\n head_sha: suite.head_sha,\n url: `${repoUrl}/check-suites/${suite.id}`,\n };\n}\n\nfunction formatRepoBrief(repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const owner = formatRepo(repo, gh, baseUrl).owner;\n return {\n id: repo.id,\n node_id: repo.node_id,\n name: repo.name,\n full_name: repo.full_name,\n private: repo.private,\n owner,\n url: `${baseUrl}/repos/${repo.full_name}`,\n html_url: `${baseUrl}/${repo.full_name}`,\n };\n}\n\nfunction formatCheckRun(run: GitHubCheckRun, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n const suite = run.check_suite_id ? gh.checkSuites.get(run.check_suite_id) : null;\n return {\n id: run.id,\n node_id: run.node_id,\n head_sha: run.head_sha,\n name: run.name,\n status: run.status,\n conclusion: run.conclusion,\n started_at: run.started_at,\n completed_at: run.completed_at,\n external_id: run.external_id,\n url: `${repoUrl}/check-runs/${run.id}`,\n html_url: `${baseUrl}/${repo.full_name}/commit/${run.head_sha}/checks/${run.id}`,\n details_url: run.details_url,\n output: {\n title: run.output.title,\n summary: run.output.summary,\n text: run.output.text,\n annotations_count: run.output.annotations_count,\n },\n check_suite: suite ? formatCheckSuiteBrief(suite, repo, baseUrl) : null,\n app: null,\n pull_requests: [] as unknown[],\n };\n}\n\nfunction formatCheckSuite(suite: GitHubCheckSuite, repo: GitHubRepo, gh: GitHubStore, baseUrl: string) {\n const repoUrl = `${baseUrl}/repos/${repo.full_name}`;\n return {\n id: suite.id,\n node_id: suite.node_id,\n head_branch: suite.head_branch,\n head_sha: suite.head_sha,\n status: suite.status,\n conclusion: suite.conclusion,\n url: `${repoUrl}/check-suites/${suite.id}`,\n before: suite.before,\n after: suite.after,\n pull_requests: [],\n app: null,\n repository: formatRepoBrief(repo, gh, baseUrl),\n created_at: suite.created_at,\n updated_at: suite.updated_at,\n };\n}\n\nfunction dispatchCheckRun(\n webhooks: WebhookDispatcher,\n gh: GitHubStore,\n repo: GitHubRepo,\n run: GitHubCheckRun,\n actor: GitHubUser,\n baseUrl: string,\n action: string | undefined,\n) {\n const ownerLogin = ownerLoginOf(gh, repo);\n void webhooks.dispatch(\n \"check_run\",\n action,\n {\n action,\n check_run: formatCheckRun(run, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n}\n\nfunction dispatchCheckSuite(\n webhooks: WebhookDispatcher,\n gh: GitHubStore,\n repo: GitHubRepo,\n suite: GitHubCheckSuite,\n actor: GitHubUser,\n baseUrl: string,\n action: string | undefined,\n) {\n const ownerLogin = ownerLoginOf(gh, repo);\n void webhooks.dispatch(\n \"check_suite\",\n action,\n {\n action,\n check_suite: formatCheckSuite(suite, repo, gh, baseUrl),\n repository: formatRepo(repo, gh, baseUrl),\n sender: formatUser(actor, baseUrl),\n },\n ownerLogin,\n repo.name,\n );\n}\n\nexport function checksRoutes({ app, store, webhooks, baseUrl }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n // --- Preferences (static path before :check_suite_id) ---\n app.patch(\"/repos/:owner/:repo/check-suites/preferences\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n const auto =\n Array.isArray(body.auto_trigger_checks) && body.auto_trigger_checks.every((x) => x && typeof x === \"object\")\n ? body.auto_trigger_checks\n : [];\n return c.json({\n preferences: {\n auto_trigger_checks: auto,\n },\n });\n });\n\n app.post(\"/repos/:owner/:repo/check-suites\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n if (typeof body.head_sha !== \"string\" || !body.head_sha.trim()) {\n throw new ApiError(422, \"head_sha is required\");\n }\n const headSha = body.head_sha.trim();\n const headBranch = typeof body.head_branch === \"string\" && body.head_branch.trim() ? body.head_branch.trim() : null;\n\n const suite = getOrCreateCheckSuite(gh, repo, headSha, headBranch);\n if (headBranch && suite.head_branch !== headBranch) {\n gh.checkSuites.update(suite.id, { head_branch: headBranch });\n }\n const updated = gh.checkSuites.get(suite.id)!;\n dispatchCheckSuite(webhooks, gh, repo, updated, actor, baseUrl, \"requested\");\n return c.json(formatCheckSuite(updated, repo, gh, baseUrl), 201);\n });\n\n app.get(\"/repos/:owner/:repo/check-suites/:check_suite_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const suiteId = parseInt(c.req.param(\"check_suite_id\")!, 10);\n const suite = gh.checkSuites.get(suiteId);\n if (!suite || suite.repo_id !== repo.id) throw notFoundResponse();\n return c.json(formatCheckSuite(suite, repo, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/check-suites/:check_suite_id/check-runs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const suiteId = parseInt(c.req.param(\"check_suite_id\")!, 10);\n const suite = gh.checkSuites.get(suiteId);\n if (!suite || suite.repo_id !== repo.id) throw notFoundResponse();\n const { page, per_page } = parsePagination(c);\n let runs = gh.checkRuns.findBy(\"repo_id\", repo.id).filter((r) => r.check_suite_id === suiteId);\n runs = runs.sort((a, b) => b.id - a.id);\n const total = runs.length;\n const slice = runs.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n return c.json({\n total_count: total,\n check_runs: slice.map((r) => formatCheckRun(r, repo, gh, baseUrl)),\n });\n });\n\n app.post(\"/repos/:owner/:repo/check-suites/:check_suite_id/rerequest\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const suiteId = parseInt(c.req.param(\"check_suite_id\")!, 10);\n const suite = gh.checkSuites.get(suiteId);\n if (!suite || suite.repo_id !== repo.id) throw notFoundResponse();\n\n const runs = gh.checkRuns.findBy(\"repo_id\", repo.id).filter((r) => r.check_suite_id === suiteId);\n const now = timestamp();\n for (const r of runs) {\n gh.checkRuns.update(r.id, {\n status: \"queued\",\n conclusion: null,\n completed_at: null,\n started_at: null,\n updated_at: now,\n });\n }\n gh.checkSuites.update(suiteId, { status: \"queued\", conclusion: null });\n const suiteAfter = gh.checkSuites.get(suiteId)!;\n dispatchCheckSuite(webhooks, gh, repo, suiteAfter, actor, baseUrl, \"rerequested\");\n return c.body(null, 201);\n });\n\n app.get(\"/repos/:owner/:repo/commits/:ref/check-suites\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const ref = c.req.param(\"ref\")!;\n const headSha = resolveRefToHeadSha(gh, repo, ref);\n if (!headSha) throw notFoundResponse();\n const suites = gh.checkSuites\n .findBy(\"repo_id\", repo.id)\n .filter((s) => s.head_sha === headSha)\n .sort((a, b) => b.id - a.id);\n return c.json({\n total_count: suites.length,\n check_suites: suites.map((s) => formatCheckSuite(s, repo, gh, baseUrl)),\n });\n });\n\n // --- Check runs ---\n app.post(\"/repos/:owner/:repo/check-runs\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const body = await parseJsonBody(c);\n\n if (typeof body.name !== \"string\" || !body.name.trim()) {\n throw new ApiError(422, \"name is required\");\n }\n if (typeof body.head_sha !== \"string\" || !body.head_sha.trim()) {\n throw new ApiError(422, \"head_sha is required\");\n }\n\n const name = body.name.trim();\n const headSha = body.head_sha.trim();\n const status = parseStatus(body.status, \"queued\");\n let conclusion = parseConclusion(body.conclusion);\n if (status === \"completed\" && (conclusion === undefined || conclusion === null)) {\n throw new ApiError(422, \"conclusion is required when status is completed\");\n }\n if (status !== \"completed\") {\n conclusion = null;\n }\n\n const details_url =\n typeof body.details_url === \"string\" || body.details_url === null ? (body.details_url as string | null) : null;\n const external_id =\n typeof body.external_id === \"string\"\n ? body.external_id\n : body.external_id == null\n ? \"\"\n : String(body.external_id);\n\n const started_at =\n body.started_at === undefined\n ? null\n : body.started_at === null\n ? null\n : typeof body.started_at === \"string\"\n ? body.started_at\n : null;\n let completed_at =\n body.completed_at === undefined\n ? null\n : body.completed_at === null\n ? null\n : typeof body.completed_at === \"string\"\n ? body.completed_at\n : null;\n\n if (status === \"completed\" && !completed_at) {\n completed_at = timestamp();\n }\n\n const outRaw = body.output && typeof body.output === \"object\" ? (body.output as Record<string, unknown>) : {};\n const annotations = normalizeAnnotations(outRaw.annotations);\n const output = {\n title: typeof outRaw.title === \"string\" ? outRaw.title : outRaw.title === null ? null : null,\n summary: typeof outRaw.summary === \"string\" ? outRaw.summary : outRaw.summary === null ? null : null,\n text: typeof outRaw.text === \"string\" ? outRaw.text : outRaw.text === null ? null : null,\n annotations_count: annotations.length,\n annotations,\n };\n\n let actions: GitHubCheckRun[\"actions\"] = null;\n if (Array.isArray(body.actions)) {\n actions = [];\n for (const act of body.actions) {\n if (!act || typeof act !== \"object\") continue;\n const a = act as Record<string, unknown>;\n if (typeof a.id === \"string\" && typeof a.label === \"string\" && typeof a.description === \"string\") {\n actions.push({ id: a.id, label: a.label, description: a.description });\n }\n }\n if (actions.length === 0) actions = null;\n }\n\n const suite = getOrCreateCheckSuite(gh, repo, headSha, null);\n\n const row = gh.checkRuns.insert({\n node_id: \"\",\n repo_id: repo.id,\n head_sha: headSha,\n name,\n status,\n conclusion: conclusion ?? null,\n started_at,\n completed_at,\n external_id,\n details_url,\n actions,\n output,\n check_suite_id: suite.id,\n app_id: typeof body.app_id === \"number\" ? body.app_id : null,\n } as Omit<GitHubCheckRun, \"id\" | \"created_at\" | \"updated_at\">);\n gh.checkRuns.update(row.id, { node_id: generateNodeId(\"CheckRun\", row.id) });\n const run = gh.checkRuns.get(row.id)!;\n\n recomputeCheckSuite(gh, suite.id);\n\n dispatchCheckRun(webhooks, gh, repo, run, actor, baseUrl, \"created\");\n return c.json(formatCheckRun(run, repo, gh, baseUrl), 201);\n });\n\n app.patch(\"/repos/:owner/:repo/check-runs/:check_run_id\", async (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"check_run_id\")!, 10);\n const prev = gh.checkRuns.get(runId);\n if (!prev || prev.repo_id !== repo.id) throw notFoundResponse();\n\n const body = await parseJsonBody(c);\n\n const patch: Partial<GitHubCheckRun> = {};\n\n if (body.name !== undefined) {\n if (typeof body.name !== \"string\" || !body.name.trim()) throw new ApiError(422, \"Invalid name\");\n patch.name = body.name.trim();\n }\n if (body.head_sha !== undefined) {\n if (typeof body.head_sha !== \"string\" || !body.head_sha.trim()) throw new ApiError(422, \"Invalid head_sha\");\n patch.head_sha = body.head_sha.trim();\n }\n if (body.status !== undefined) {\n patch.status = parseStatus(body.status, prev.status);\n }\n if (body.conclusion !== undefined) {\n const pc = parseConclusion(body.conclusion);\n patch.conclusion = pc === undefined ? null : pc;\n }\n if (body.details_url !== undefined) {\n patch.details_url =\n typeof body.details_url === \"string\" || body.details_url === null ? (body.details_url as string | null) : null;\n }\n if (body.external_id !== undefined) {\n patch.external_id = typeof body.external_id === \"string\" ? body.external_id : String(body.external_id ?? \"\");\n }\n if (body.started_at !== undefined) {\n patch.started_at = body.started_at === null ? null : typeof body.started_at === \"string\" ? body.started_at : null;\n }\n if (body.completed_at !== undefined) {\n patch.completed_at =\n body.completed_at === null ? null : typeof body.completed_at === \"string\" ? body.completed_at : null;\n }\n if (body.app_id !== undefined) {\n patch.app_id = typeof body.app_id === \"number\" ? body.app_id : null;\n }\n if (body.actions !== undefined) {\n if (body.actions === null) {\n patch.actions = null;\n } else if (Array.isArray(body.actions)) {\n const actions: NonNullable<GitHubCheckRun[\"actions\"]> = [];\n for (const act of body.actions) {\n if (!act || typeof act !== \"object\") continue;\n const a = act as Record<string, unknown>;\n if (typeof a.id === \"string\" && typeof a.label === \"string\" && typeof a.description === \"string\") {\n actions.push({ id: a.id, label: a.label, description: a.description });\n }\n }\n patch.actions = actions.length ? actions : null;\n }\n }\n\n if (body.output !== undefined && body.output !== null && typeof body.output === \"object\") {\n const outRaw = body.output as Record<string, unknown>;\n const annotations = normalizeAnnotations(outRaw.annotations);\n patch.output = {\n title: outRaw.title === undefined ? prev.output.title : typeof outRaw.title === \"string\" ? outRaw.title : null,\n summary:\n outRaw.summary === undefined\n ? prev.output.summary\n : typeof outRaw.summary === \"string\"\n ? outRaw.summary\n : null,\n text: outRaw.text === undefined ? prev.output.text : typeof outRaw.text === \"string\" ? outRaw.text : null,\n annotations_count: annotations.length,\n annotations,\n };\n }\n\n const nextStatus = patch.status ?? prev.status;\n const nextConclusion: GitHubCheckRun[\"conclusion\"] =\n patch.conclusion !== undefined ? patch.conclusion : prev.conclusion;\n\n if (patch.head_sha && patch.head_sha !== prev.head_sha) {\n const newSuite = getOrCreateCheckSuite(gh, repo, patch.head_sha, null);\n patch.check_suite_id = newSuite.id;\n }\n\n if (nextStatus === \"completed\") {\n if (nextConclusion === undefined || nextConclusion === null) {\n throw new ApiError(422, \"conclusion is required when status is completed\");\n }\n patch.conclusion = nextConclusion;\n const nextCompleted = patch.completed_at !== undefined ? patch.completed_at : prev.completed_at;\n if (!nextCompleted) {\n patch.completed_at = timestamp();\n }\n } else {\n patch.conclusion = null;\n patch.completed_at = null;\n }\n\n gh.checkRuns.update(runId, patch);\n const run = gh.checkRuns.get(runId)!;\n\n if (run.check_suite_id) {\n recomputeCheckSuite(gh, run.check_suite_id);\n }\n\n if (prev.status !== \"completed\" && run.status === \"completed\") {\n dispatchCheckRun(webhooks, gh, repo, run, actor, baseUrl, \"completed\");\n }\n\n return c.json(formatCheckRun(run, repo, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/check-runs/:check_run_id\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"check_run_id\")!, 10);\n const run = gh.checkRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n return c.json(formatCheckRun(run, repo, gh, baseUrl));\n });\n\n app.get(\"/repos/:owner/:repo/check-runs/:check_run_id/annotations\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"check_run_id\")!, 10);\n const run = gh.checkRuns.get(runId);\n if (!run || run.repo_id !== repo.id) throw notFoundResponse();\n\n const { page, per_page } = parsePagination(c);\n const annotations = run.output.annotations;\n const total = annotations.length;\n const slice = annotations.slice((page - 1) * per_page, (page - 1) * per_page + per_page);\n setLinkHeader(c, total, page, per_page);\n\n const check_annotations = slice.map((a, i) => ({\n path: a.path,\n blob_href: `${baseUrl}/${repo.full_name}/blob/${run.head_sha}/${a.path}`,\n start_line: a.start_line,\n end_line: a.end_line,\n message: a.message,\n title: null as string | null,\n raw_details: null as string | null,\n start_column: null as number | null,\n end_column: null as number | null,\n annotation_level: a.annotation_level,\n id: (page - 1) * per_page + i + 1,\n }));\n\n return c.json({\n total_count: total,\n check_annotations,\n });\n });\n\n app.post(\"/repos/:owner/:repo/check-runs/:check_run_id/rerequest\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n const actor = assertRepoWrite(gh, c.get(\"authUser\"), repo);\n const runId = parseInt(c.req.param(\"check_run_id\")!, 10);\n const prev = gh.checkRuns.get(runId);\n if (!prev || prev.repo_id !== repo.id) throw notFoundResponse();\n\n const now = timestamp();\n gh.checkRuns.update(runId, {\n status: \"queued\",\n conclusion: null,\n completed_at: null,\n started_at: null,\n updated_at: now,\n });\n const run = gh.checkRuns.get(runId)!;\n if (run.check_suite_id) {\n recomputeCheckSuite(gh, run.check_suite_id);\n }\n dispatchCheckRun(webhooks, gh, repo, run, actor, baseUrl, \"rerequested\");\n return c.body(null, 201);\n });\n\n app.get(\"/repos/:owner/:repo/commits/:ref/check-runs\", (c) => {\n const owner = c.req.param(\"owner\")!;\n const repoName = c.req.param(\"repo\")!;\n const repo = lookupRepo(gh, owner, repoName);\n if (!repo) throw notFoundResponse();\n assertRepoRead(gh, c.get(\"authUser\"), repo);\n const ref = c.req.param(\"ref\")!;\n const headSha = resolveRefToHeadSha(gh, repo, ref);\n if (!headSha) throw notFoundResponse();\n\n const check_name = c.req.query(\"check_name\")?.trim();\n const statusQ = c.req.query(\"status\")?.trim() as GitHubCheckRun[\"status\"] | undefined;\n const filter = (c.req.query(\"filter\") ?? \"latest\").toLowerCase();\n\n let runs = gh.checkRuns.findBy(\"repo_id\", repo.id).filter((r) => r.head_sha === headSha);\n if (check_name) {\n runs = runs.filter((r) => r.name === check_name);\n }\n if (statusQ && (statusQ === \"queued\" || statusQ === \"in_progress\" || statusQ === \"completed\")) {\n runs = runs.filter((r) => r.status === statusQ);\n }\n\n runs = runs.sort((a, b) => b.id - a.id);\n\n if (filter === \"latest\") {\n const byName = new Map<string, GitHubCheckRun>();\n for (const r of runs.sort((a, b) => a.id - b.id)) {\n byName.set(r.name, r);\n }\n runs = [...byName.values()].sort((a, b) => b.id - a.id);\n }\n\n return c.json({\n total_count: runs.length,\n check_runs: runs.map((r) => formatCheckRun(r, repo, gh, baseUrl)),\n });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\n\nexport function rateLimitRoutes({ app }: RouteContext): void {\n app.get(\"/rate_limit\", (c) => {\n const now = Math.floor(Date.now() / 1000);\n const reset = now + 3600;\n const rateLimit = {\n limit: 5000,\n remaining: 4999,\n reset,\n used: 1,\n resource: \"core\",\n };\n\n return c.json({\n resources: {\n core: rateLimit,\n search: { limit: 30, remaining: 29, reset, used: 1, resource: \"search\" },\n graphql: { limit: 5000, remaining: 4999, reset, used: 1, resource: \"graphql\" },\n integration_manifest: { limit: 5000, remaining: 4999, reset, used: 1, resource: \"integration_manifest\" },\n source_import: { limit: 100, remaining: 99, reset, used: 1, resource: \"source_import\" },\n code_scanning_upload: { limit: 500, remaining: 499, reset, used: 1, resource: \"code_scanning_upload\" },\n actions_runner_registration: {\n limit: 10000,\n remaining: 9999,\n reset,\n used: 1,\n resource: \"actions_runner_registration\",\n },\n scim: { limit: 15000, remaining: 14999, reset, used: 1, resource: \"scim\" },\n },\n rate: rateLimit,\n });\n });\n}\n","import type { RouteContext } from \"@emulators/core\";\n\nexport function metaRoutes({ app, baseUrl }: RouteContext): void {\n app.get(\"/meta\", (c) => {\n return c.json({\n verifiable_password_authentication: true,\n ssh_key_fingerprints: {\n SHA256_RSA: \"placeholder\",\n SHA256_DSA: \"placeholder\",\n SHA256_ECDSA: \"placeholder\",\n SHA256_ED25519: \"placeholder\",\n },\n ssh_keys: [\"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIPlaceholder\"],\n hooks: [\"127.0.0.1/32\"],\n web: [\"127.0.0.1/32\"],\n api: [\"127.0.0.1/32\"],\n git: [\"127.0.0.1/32\"],\n github_enterprise_importer: [\"127.0.0.1/32\"],\n packages: [\"127.0.0.1/32\"],\n pages: [\"127.0.0.1/32\"],\n importer: [\"127.0.0.1/32\"],\n actions: [\"127.0.0.1/32\"],\n actions_macos: [\"127.0.0.1/32\"],\n dependabot: [\"127.0.0.1/32\"],\n copilot: [\"127.0.0.1/32\"],\n domains: {\n website: [\"localhost\"],\n codespaces: [\"localhost\"],\n copilot: [\"localhost\"],\n packages: [\"localhost\"],\n actions: [\"localhost\"],\n artifact_attestations: { trust_domain: \"localhost\" },\n },\n });\n });\n\n app.get(\"/octocat\", (c) => {\n const say = c.req.query(\"s\") ?? \"emulate says hello!\";\n const art = `\n MMM. .MMM\n MMMMMMMMMMMMMMMMMMM\n MMMMMMMMMMMMMMMMMMM ____________________________\n MMMMMMMMMMMMMMMMMMMMM | |\n MMMMMMMMMMMMMMMMMMMMMMM | ${say.padEnd(26)} |\n MMMMMMMMMMMMMMMMMMMMMMMM |_ ________________________|\n MMMM::- -:::::::- -::MMMM |/\n MM~:~ 00~:::::~ 00~:~MM\n .. .. :~M]:[~:M. . ..\n .MM. ~MM. MM~ .MM.\n MMMM. ~MM:~MM~ .MMMM\n MMMMMM. ~MMMMMMMM~ .MMMMMM\n MMMMMMMMMMMMMMMMMMMMMMMMMMMM\n .MMMMMMMMMMMMMMMMMMMMMM.\n MMMMMMMMMMMMMMMMMM\n ;MMMMMMMMMMMMMMM;\n :MMMMMMMMMMMM:\n .MMMMMMMMMMM.\n MMMMMMMMMMM\n MMMMMMMMM\n MMMMMMM\n MMMMM\n MMM\n M\n`;\n c.header(\"Content-Type\", \"application/octocat-stream\");\n return c.text(art.trim());\n });\n\n app.get(\"/emojis\", (c) => {\n return c.json({\n \"+1\": `${baseUrl}/emojis/+1.png`,\n \"-1\": `${baseUrl}/emojis/-1.png`,\n \"100\": `${baseUrl}/emojis/100.png`,\n tada: `${baseUrl}/emojis/tada.png`,\n rocket: `${baseUrl}/emojis/rocket.png`,\n heart: `${baseUrl}/emojis/heart.png`,\n eyes: `${baseUrl}/emojis/eyes.png`,\n thinking: `${baseUrl}/emojis/thinking.png`,\n thumbsup: `${baseUrl}/emojis/thumbsup.png`,\n thumbsdown: `${baseUrl}/emojis/thumbsdown.png`,\n });\n });\n\n app.get(\"/zen\", (c) => {\n const phrases = [\n \"Non-blocking is better than blocking.\",\n \"Design for failure.\",\n \"Half measures are as bad as nothing at all.\",\n \"Encourage flow.\",\n \"Anything added dilutes everything else.\",\n \"Approachable is better than simple.\",\n \"Mind your words, they are important.\",\n \"Speak like a human.\",\n \"It's not fully shipped until it's fast.\",\n \"Responsive is better than fast.\",\n \"Keep it logically awesome.\",\n \"Favor focus over features.\",\n \"Avoid administrative distraction.\",\n ];\n return c.text(phrases[Math.floor(Math.random() * phrases.length)]);\n });\n\n app.get(\"/versions\", (c) => {\n return c.json([\"2022-11-28\", \"2022-08-09\"]);\n });\n}\n","import { randomBytes } from \"crypto\";\nimport type { Context } from \"@emulators/core\";\nimport type { RouteContext, Store, AuthUser, AppEnv } from \"@emulators/core\";\nimport {\n unauthorized,\n escapeHtml,\n escapeAttr,\n renderCardPage,\n renderErrorPage,\n renderSettingsPage,\n renderUserButton,\n matchesRedirectUri,\n constantTimeSecretEqual,\n parseCookies,\n debug,\n} from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport { formatUser, formatUserFull } from \"../helpers.js\";\n\ntype PendingCode = {\n login: string;\n scope: string;\n redirectUri: string;\n clientId: string;\n created_at: number;\n};\n\nconst PENDING_CODE_TTL_MS = 10 * 60 * 1000;\n\nfunction getPendingCodes(store: Store): Map<string, PendingCode> {\n let map = store.getData<Map<string, PendingCode>>(\"github.oauth.pendingCodes\");\n if (!map) {\n map = new Map();\n store.setData(\"github.oauth.pendingCodes\", map);\n }\n return map;\n}\n\nfunction getTokenToClientId(store: Store): Map<string, string> {\n let map = store.getData<Map<string, string>>(\"github.oauth.tokenToClientId\");\n if (!map) {\n map = new Map();\n store.setData(\"github.oauth.tokenToClientId\", map);\n }\n return map;\n}\n\nfunction getSessionMap(store: Store): Map<string, string> {\n let map = store.getData<Map<string, string>>(\"github.oauth.sessionMap\");\n if (!map) {\n map = new Map();\n store.setData(\"github.oauth.sessionMap\", map);\n }\n return map;\n}\n\n/** On read: drops entries older than {@link PENDING_CODE_TTL_MS}. */\nfunction getPendingCodeIfValid(store: Store, code: string): PendingCode | undefined {\n const map = getPendingCodes(store);\n const pending = map.get(code);\n if (!pending) return undefined;\n if (Date.now() - pending.created_at > PENDING_CODE_TTL_MS) {\n map.delete(code);\n return undefined;\n }\n return pending;\n}\n\nconst SERVICE_LABEL = \"GitHub\";\n\nexport function oauthRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n function resolveSessionUser(c: Context<AppEnv>): { login: string; id: number } | null {\n const authUser = c.get(\"authUser\") as AuthUser | undefined;\n if (authUser) {\n const user = gh.users.findOneBy(\"login\", authUser.login);\n if (user) return { login: user.login, id: user.id };\n }\n const cookieHeader = c.req.header(\"Cookie\") ?? \"\";\n const cookies = parseCookies(cookieHeader);\n const sessionId = cookies[\"_emu_session\"];\n if (sessionId) {\n const login = getSessionMap(store).get(sessionId);\n if (login) {\n const user = gh.users.findOneBy(\"login\", login);\n if (user) return { login: user.login, id: user.id };\n }\n }\n return null;\n }\n\n // ---------- OAuth authorize page ----------\n\n app.get(\"/login/oauth/authorize\", (c) => {\n const client_id = c.req.query(\"client_id\") ?? \"\";\n const redirect_uri = c.req.query(\"redirect_uri\") ?? \"\";\n const scope = c.req.query(\"scope\") ?? \"\";\n const state = c.req.query(\"state\") ?? \"\";\n\n const oauthAppsConfigured = gh.oauthApps.all().length > 0;\n let oauthAppForSubtitle: { name: string } | undefined;\n if (oauthAppsConfigured) {\n const oauthApp = gh.oauthApps.findOneBy(\"client_id\", client_id);\n if (!oauthApp) {\n return c.html(\n renderErrorPage(\"Application not found\", `The client_id '${client_id}' is not registered.`, SERVICE_LABEL),\n 400,\n );\n }\n if (redirect_uri && !matchesRedirectUri(redirect_uri, oauthApp.redirect_uris)) {\n console.warn(\n `[OAuth] redirect_uri mismatch: got \"${redirect_uri}\", registered: ${JSON.stringify(oauthApp.redirect_uris)}`,\n );\n return c.html(\n renderErrorPage(\n \"Redirect URI mismatch\",\n \"The redirect_uri is not registered for this application.\",\n SERVICE_LABEL,\n ),\n 400,\n );\n }\n oauthAppForSubtitle = oauthApp;\n }\n\n const users = [...gh.users.all()].sort((a, b) => a.login.localeCompare(b.login));\n\n const subtitleText = oauthAppForSubtitle\n ? `Authorize <strong>${escapeHtml(oauthAppForSubtitle.name)}</strong> to access your account.`\n : \"Choose a seeded user to authorize this application.\";\n\n const userButtons = users\n .map((u) => {\n const brief = formatUser(u, baseUrl);\n const full = formatUserFull(u, baseUrl);\n return renderUserButton({\n letter: (brief.login[0] ?? \"?\").toUpperCase(),\n login: full.login,\n name: full.name ?? undefined,\n email: full.email ?? undefined,\n formAction: `${baseUrl}/login/oauth/callback`,\n hiddenFields: {\n login: u.login,\n redirect_uri,\n scope,\n state,\n client_id,\n },\n });\n })\n .join(\"\\n\");\n\n const body = users.length === 0 ? '<p class=\"empty\">No users in the emulator store.</p>' : userButtons;\n\n return c.html(renderCardPage(\"Sign in to GitHub\", subtitleText, body, SERVICE_LABEL));\n });\n\n // ---------- OAuth callback (user selection) ----------\n\n app.post(\"/login/oauth/callback\", async (c) => {\n const body = (await c.req.parseBody()) as Record<string, string>;\n const login = String(body.login ?? \"\");\n const redirect_uri = String(body.redirect_uri ?? \"\");\n const scope = String(body.scope ?? \"\");\n const state = String(body.state ?? \"\");\n const client_id = String(body.client_id ?? \"\");\n\n const code = randomBytes(20).toString(\"hex\");\n getPendingCodes(store).set(code, {\n login,\n scope,\n redirectUri: redirect_uri,\n clientId: client_id,\n created_at: Date.now(),\n });\n\n debug(\n \"github.oauth\",\n `[OAuth callback] generated code: ${code.slice(0, 8)}... for login=${login}, pendingCodes size: ${getPendingCodes(store).size}`,\n );\n\n const sessionId = randomBytes(24).toString(\"base64url\");\n getSessionMap(store).set(sessionId, login);\n c.header(\"Set-Cookie\", `_emu_session=${sessionId}; Path=/; HttpOnly; SameSite=Lax`);\n\n const sep = redirect_uri.includes(\"?\") ? \"&\" : \"?\";\n const target = `${redirect_uri}${sep}code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}`;\n debug(\"github.oauth\", `[OAuth callback] redirecting to: ${target.slice(0, 120)}...`);\n return c.redirect(target, 302);\n });\n\n // ---------- Token exchange ----------\n\n app.post(\"/login/oauth/access_token\", async (c) => {\n const contentType = c.req.header(\"Content-Type\") ?? \"\";\n const accept = c.req.header(\"Accept\") ?? \"\";\n debug(\"github.oauth\", `[OAuth token] Content-Type: ${contentType}`);\n debug(\"github.oauth\", `[OAuth token] Accept: ${accept}`);\n debug(\"github.oauth\", `[OAuth token] pendingCodes size: ${getPendingCodes(store).size}`);\n debug(\n \"github.oauth\",\n `[OAuth token] pendingCodes keys: ${[...getPendingCodes(store).keys()].map((k) => k.slice(0, 8) + \"...\").join(\", \")}`,\n );\n\n const rawText = await c.req.text();\n debug(\"github.oauth\", `[OAuth token] raw body: ${rawText.slice(0, 500)}`);\n\n let raw: Record<string, unknown>;\n if (contentType.includes(\"application/json\")) {\n try {\n raw = JSON.parse(rawText);\n } catch {\n raw = {};\n }\n } else {\n raw = Object.fromEntries(new URLSearchParams(rawText));\n }\n\n debug(\"github.oauth\", `[OAuth token] parsed keys: ${Object.keys(raw).join(\", \")}`);\n\n const code = String(raw.code ?? \"\");\n const bodyClientId = String(raw.client_id ?? \"\");\n const bodyClientSecret = String(raw.client_secret ?? \"\").slice(0, 4) + \"****\";\n\n debug(\"github.oauth\", `[OAuth token] code: ${code.slice(0, 8)}... (len=${code.length})`);\n debug(\"github.oauth\", `[OAuth token] client_id: ${bodyClientId}`);\n debug(\"github.oauth\", `[OAuth token] client_secret: ${bodyClientSecret}`);\n\n const actualSecret = String(raw.client_secret ?? \"\");\n\n const incorrectClientCredentials = () => {\n debug(\"github.oauth\", `[OAuth token] REJECTED: incorrect_client_credentials`);\n return c.json(\n {\n error: \"incorrect_client_credentials\",\n error_description: \"The client_id and/or client_secret passed are incorrect.\",\n },\n 200,\n );\n };\n\n const oauthAppsConfigured = gh.oauthApps.all().length > 0;\n if (oauthAppsConfigured) {\n const oauthApp = gh.oauthApps.findOneBy(\"client_id\", bodyClientId);\n if (!oauthApp) {\n debug(\"github.oauth\", `[OAuth token] REJECTED: client_id not found in oauthApps`);\n return incorrectClientCredentials();\n }\n if (!constantTimeSecretEqual(actualSecret, oauthApp.client_secret)) {\n debug(\"github.oauth\", `[OAuth token] REJECTED: client_secret mismatch`);\n return incorrectClientCredentials();\n }\n debug(\"github.oauth\", `[OAuth token] client credentials OK (app: ${oauthApp.name})`);\n } else {\n debug(\"github.oauth\", `[OAuth token] no oauth apps configured, skipping client validation`);\n }\n\n const pending = getPendingCodeIfValid(store, code);\n if (!pending) {\n debug(\"github.oauth\", `[OAuth token] REJECTED: code not found in pendingCodes or expired`);\n return c.json(\n { error: \"bad_verification_code\", error_description: \"The code passed is incorrect or expired.\" },\n 200,\n );\n }\n\n debug(\"github.oauth\", `[OAuth token] code valid, login=${pending.login}, scope=${pending.scope}`);\n getPendingCodes(store).delete(code);\n\n const user = gh.users.findOneBy(\"login\", pending.login);\n if (!user) {\n debug(\"github.oauth\", `[OAuth token] REJECTED: user \"${pending.login}\" not found in store`);\n return c.json(\n { error: \"bad_verification_code\", error_description: \"The code passed is incorrect or expired.\" },\n 200,\n );\n }\n\n const token = \"gho_\" + randomBytes(20).toString(\"base64url\");\n const scopes = pending.scope ? pending.scope.split(/[,\\s]+/).filter(Boolean) : [\"repo\", \"user\"];\n\n if (tokenMap) {\n tokenMap.set(token, { login: user.login, id: user.id, scopes });\n }\n\n const oauthApp = gh.oauthApps.findOneBy(\"client_id\", pending.clientId);\n if (oauthApp) {\n const existingGrant = gh.oauthGrants.all().find((g) => g.user_id === user.id && g.client_id === pending.clientId);\n const orgAccess: Record<string, \"granted\" | \"denied\" | \"requested\"> = {};\n for (const org of gh.orgs.all()) {\n const isMember = gh.teamMembers\n .all()\n .some((tm) => tm.user_id === user.id && gh.teams.get(tm.team_id)?.org_id === org.id);\n if (isMember) orgAccess[org.login] = \"granted\";\n }\n\n if (existingGrant) {\n gh.oauthGrants.update(existingGrant.id, { scopes, org_access: orgAccess });\n } else {\n gh.oauthGrants.insert({\n user_id: user.id,\n oauth_app_id: oauthApp.id,\n client_id: pending.clientId,\n scopes,\n org_access: orgAccess,\n });\n }\n getTokenToClientId(store).set(token, pending.clientId);\n }\n\n debug(\"github.oauth\", `[OAuth token] SUCCESS: issued token for ${user.login} (scopes: ${scopes.join(\",\")})`);\n\n const wantsFormEncoded = accept.includes(\"application/x-www-form-urlencoded\");\n const scopeOut = pending.scope;\n\n if (wantsFormEncoded) {\n const formBody = `access_token=${encodeURIComponent(token)}&token_type=bearer&scope=${encodeURIComponent(scopeOut)}`;\n c.header(\"Content-Type\", \"application/x-www-form-urlencoded\");\n return c.body(formBody, 200);\n }\n\n return c.json({\n access_token: token,\n token_type: \"bearer\",\n scope: scopeOut,\n });\n });\n\n // ---------- User emails ----------\n\n app.get(\"/user/emails\", (c) => {\n const authUser = c.get(\"authUser\");\n if (!authUser) {\n throw unauthorized();\n }\n const user = gh.users.findOneBy(\"login\", authUser.login);\n if (!user) {\n throw unauthorized();\n }\n const email = user.email || `${user.login}@users.noreply.localhost`;\n return c.json([\n {\n email,\n primary: true,\n verified: true,\n visibility: \"public\",\n },\n ]);\n });\n\n // ---------- Settings: list authorized apps ----------\n\n const SCOPE_LABELS: Record<string, string> = {\n repo: \"Full control of private repositories\",\n \"read:user\": \"Read all user profile data\",\n \"user:email\": \"Access user email addresses (read-only)\",\n user: \"Full control of user profile\",\n workflow: \"Update GitHub action workflows\",\n \"admin:org\": \"Full control of orgs and teams\",\n \"admin:repo_hook\": \"Full control of repository hooks\",\n \"read:org\": \"Read org and team membership\",\n \"write:repo_hook\": \"Write repository hooks\",\n \"read:repo_hook\": \"Read repository hooks\",\n delete_repo: \"Delete repositories\",\n gist: \"Create gists\",\n notifications: \"Access notifications\",\n \"write:packages\": \"Upload packages\",\n \"read:packages\": \"Download packages\",\n \"admin:gpg_key\": \"Full control of GPG keys\",\n \"admin:public_key\": \"Full control of public keys\",\n };\n\n function scopeLabel(scope: string): string {\n return SCOPE_LABELS[scope] ?? scope;\n }\n\n const sidebarHtml = `\n <a href=\"/settings/applications\" class=\"active\">Authorized Apps</a>`;\n\n app.get(\"/settings/applications\", (c) => {\n const sessionUser = resolveSessionUser(c);\n if (!sessionUser) {\n return c.html(\n renderErrorPage(\"Unauthorized\", \"You must be authenticated to view this page.\", SERVICE_LABEL),\n 401,\n );\n }\n\n const grants = gh.oauthGrants.findBy(\"user_id\", sessionUser.id);\n\n let bodyHtml: string;\n if (grants.length === 0) {\n bodyHtml = `\n <div class=\"section-heading\">Authorized OAuth Apps</div>\n <div class=\"s-card\">\n <p class=\"empty\">No authorized applications. Apps you authorize will appear here.</p>\n </div>`;\n } else {\n const appLinks = grants\n .map((grant) => {\n const oauthApp = gh.oauthApps.findOneBy(\"client_id\", grant.client_id);\n const name = oauthApp?.name ?? grant.client_id;\n const letter = escapeHtml((name[0] ?? \"?\").toUpperCase());\n const scopeText = grant.scopes.length > 0 ? grant.scopes.join(\", \") : \"No scopes\";\n return `<a href=\"/settings/connections/applications/${escapeAttr(grant.client_id)}\" class=\"app-link\">\n <div class=\"s-icon\">${letter}</div>\n <div>\n <div class=\"app-link-name\">${escapeHtml(name)}</div>\n <div class=\"app-link-scopes\">${escapeHtml(scopeText)}</div>\n </div>\n </a>`;\n })\n .join(\"\\n\");\n\n bodyHtml = `\n <div class=\"section-heading\">Authorized OAuth Apps</div>\n <div class=\"s-card\">${appLinks}</div>`;\n }\n\n return c.html(renderSettingsPage(\"Authorized OAuth Apps\", sidebarHtml, bodyHtml, SERVICE_LABEL));\n });\n\n // ---------- Settings: app detail ----------\n\n app.get(\"/settings/connections/applications/:client_id\", (c) => {\n const sessionUser = resolveSessionUser(c);\n if (!sessionUser) {\n return c.html(\n renderErrorPage(\"Unauthorized\", \"You must be authenticated to view this page.\", SERVICE_LABEL),\n 401,\n );\n }\n\n const clientId = c.req.param(\"client_id\");\n\n const grant = gh.oauthGrants.all().find((g) => g.user_id === sessionUser.id && g.client_id === clientId);\n if (!grant) {\n return c.html(renderErrorPage(\"Not Found\", \"No authorization found for this application.\", SERVICE_LABEL), 404);\n }\n\n const oauthApp = gh.oauthApps.findOneBy(\"client_id\", clientId);\n const appName = oauthApp?.name ?? clientId;\n const appLetter = escapeHtml((appName[0] ?? \"?\").toUpperCase());\n const lastUsed = new Date(grant.updated_at).toLocaleDateString(\"en-US\", {\n year: \"numeric\",\n month: \"long\",\n day: \"numeric\",\n });\n\n const permRows = grant.scopes\n .map((s) => `<li><span class=\"check\">&#10003;</span> ${escapeHtml(scopeLabel(s))}</li>`)\n .join(\"\\n\");\n\n const orgRows = Object.entries(grant.org_access)\n .map(([org, status]) => {\n const letter = escapeHtml((org[0] ?? \"?\").toUpperCase());\n const badgeClass =\n status === \"granted\" ? \"badge-granted\" : status === \"denied\" ? \"badge-denied\" : \"badge-requested\";\n const icon = status === \"granted\" ? \"&#10003;\" : status === \"denied\" ? \"&#10007;\" : \"&#8943;\";\n return `<div class=\"org-row\">\n <div class=\"org-icon\">${letter}</div>\n <span class=\"org-name\">${escapeHtml(org)}</span>\n <span class=\"badge ${badgeClass}\">${icon}</span>\n </div>`;\n })\n .join(\"\\n\");\n\n const bodyHtml = `\n <div class=\"s-card\">\n <div class=\"s-card-header\">\n <div class=\"s-icon\">${appLetter}</div>\n <div>\n <div class=\"s-title\">${escapeHtml(appName)}</div>\n <div class=\"s-subtitle\">Last used: ${escapeHtml(lastUsed)}</div>\n </div>\n </div>\n </div>\n\n <div class=\"s-card\">\n <div class=\"section-heading\">\n <span>Permissions</span>\n <form method=\"post\" action=\"/settings/connections/applications/${escapeAttr(clientId)}/revoke\" style=\"display:inline\">\n <button type=\"submit\" class=\"btn-revoke\">Revoke access</button>\n </form>\n </div>\n <ul class=\"perm-list\">\n ${permRows || '<li style=\"color:#1a8c00\">No specific permissions granted.</li>'}\n </ul>\n </div>\n\n ${\n orgRows\n ? `<div class=\"s-card\">\n <div class=\"section-heading\">Organization access</div>\n ${orgRows}\n <p class=\"info-text\">Applications act on your behalf. Organizations control which apps may access their private data.</p>\n </div>`\n : \"\"\n }`;\n\n return c.html(renderSettingsPage(appName, sidebarHtml, bodyHtml, SERVICE_LABEL));\n });\n\n // ---------- Settings: revoke ----------\n\n app.post(\"/settings/connections/applications/:client_id/revoke\", (c) => {\n const sessionUser = resolveSessionUser(c);\n if (!sessionUser) {\n return c.html(\n renderErrorPage(\"Unauthorized\", \"You must be authenticated to perform this action.\", SERVICE_LABEL),\n 401,\n );\n }\n\n const clientId = c.req.param(\"client_id\");\n\n const grant = gh.oauthGrants.all().find((g) => g.user_id === sessionUser.id && g.client_id === clientId);\n if (grant) {\n gh.oauthGrants.delete(grant.id);\n }\n\n if (tokenMap) {\n for (const [token, tokenUser] of tokenMap.entries()) {\n if (tokenUser.login === sessionUser.login && getTokenToClientId(store).get(token) === clientId) {\n tokenMap.delete(token);\n getTokenToClientId(store).delete(token);\n }\n }\n }\n\n return c.redirect(\"/settings/applications\", 302);\n });\n}\n","import { randomBytes } from \"crypto\";\nimport type { RouteContext, AuthApp } from \"@emulators/core\";\nimport { getGitHubStore } from \"../store.js\";\nimport { generateNodeId } from \"../helpers.js\";\n\nexport function appsRoutes({ app, store, baseUrl, tokenMap }: RouteContext): void {\n const gh = getGitHubStore(store);\n\n function requireApp(c: any): AuthApp | null {\n const authApp = c.get(\"authApp\") as AuthApp | undefined;\n if (!authApp) {\n c.status(401);\n return null;\n }\n return authApp;\n }\n\n app.get(\"/app\", (c) => {\n const authApp = requireApp(c);\n if (!authApp) {\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: \"https://docs.github.com/rest\",\n },\n 401,\n );\n }\n\n const ghApp = gh.apps.all().find((a) => a.app_id === authApp.appId);\n if (!ghApp) {\n return c.json({ message: \"Not Found\" }, 404);\n }\n\n const installations = gh.appInstallations.findBy(\"app_id\", ghApp.app_id);\n\n return c.json({\n id: ghApp.app_id,\n slug: ghApp.slug,\n node_id: generateNodeId(\"App\", ghApp.app_id),\n name: ghApp.name,\n description: ghApp.description,\n external_url: `${baseUrl}/apps/${ghApp.slug}`,\n html_url: `${baseUrl}/apps/${ghApp.slug}`,\n created_at: ghApp.created_at,\n updated_at: ghApp.updated_at,\n permissions: ghApp.permissions,\n events: ghApp.events,\n installations_count: installations.length,\n owner: null,\n });\n });\n\n app.get(\"/app/installations\", (c) => {\n const authApp = requireApp(c);\n if (!authApp) {\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: \"https://docs.github.com/rest\",\n },\n 401,\n );\n }\n\n const installations = gh.appInstallations.findBy(\"app_id\", authApp.appId);\n const ghApp = gh.apps.all().find((a) => a.app_id === authApp.appId);\n\n return c.json(installations.map((inst) => formatInstallation(inst, ghApp, baseUrl)));\n });\n\n app.get(\"/app/installations/:installation_id\", (c) => {\n const authApp = requireApp(c);\n if (!authApp) {\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: \"https://docs.github.com/rest\",\n },\n 401,\n );\n }\n\n const installationId = parseInt(c.req.param(\"installation_id\"), 10);\n const inst = gh.appInstallations\n .all()\n .find((i) => i.installation_id === installationId && i.app_id === authApp.appId);\n\n if (!inst) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const ghApp = gh.apps.all().find((a) => a.app_id === authApp.appId);\n return c.json(formatInstallation(inst, ghApp, baseUrl));\n });\n\n app.post(\"/app/installations/:installation_id/access_tokens\", async (c) => {\n const authApp = requireApp(c);\n if (!authApp) {\n return c.json(\n {\n message: \"A JSON web token could not be decoded\",\n documentation_url: \"https://docs.github.com/rest\",\n },\n 401,\n );\n }\n\n const installationId = parseInt(c.req.param(\"installation_id\"), 10);\n const inst = gh.appInstallations\n .all()\n .find((i) => i.installation_id === installationId && i.app_id === authApp.appId);\n\n if (!inst) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n let requestedPermissions = inst.permissions;\n let requestedRepoIds = inst.repository_ids;\n\n try {\n const body = (await c.req.json()) as Record<string, unknown>;\n if (body.permissions && typeof body.permissions === \"object\") {\n requestedPermissions = body.permissions as Record<string, string>;\n }\n if (Array.isArray(body.repository_ids)) {\n requestedRepoIds = (body.repository_ids as number[]).filter(\n (id) => inst.repository_selection === \"all\" || inst.repository_ids.includes(id),\n );\n }\n } catch {\n // No body or invalid JSON, use installation defaults\n }\n\n const token = \"ghs_\" + randomBytes(20).toString(\"base64url\");\n const expiresAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();\n\n if (tokenMap) {\n tokenMap.set(token, {\n login: inst.account_login,\n id: inst.account_id,\n scopes: Object.entries(requestedPermissions).map(([k, v]) => `${k}:${v}`),\n });\n }\n\n const repos = requestedRepoIds\n .map((id) => gh.repos.get(id))\n .filter(Boolean)\n .map((r) => ({\n id: r!.id,\n node_id: r!.node_id,\n name: r!.name,\n full_name: r!.full_name,\n private: r!.private,\n }));\n\n return c.json(\n {\n token,\n expires_at: expiresAt,\n permissions: requestedPermissions,\n repository_selection: inst.repository_selection,\n ...(inst.repository_selection === \"selected\" ? { repositories: repos } : {}),\n },\n 201,\n );\n });\n\n app.get(\"/repos/:owner/:repo/installation\", (c) => {\n const owner = c.req.param(\"owner\");\n const repoName = c.req.param(\"repo\");\n const fullName = `${owner}/${repoName}`;\n const repo = gh.repos.findOneBy(\"full_name\", fullName);\n if (!repo) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const ownerEntity = gh.users.findOneBy(\"login\", owner) ?? gh.orgs.findOneBy(\"login\", owner);\n\n for (const inst of gh.appInstallations.all()) {\n if (inst.repository_selection === \"all\" && ownerEntity && inst.account_id === ownerEntity.id) {\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n return c.json(formatInstallation(inst, ghApp, baseUrl));\n }\n if (inst.repository_selection === \"selected\" && inst.repository_ids.includes(repo.id)) {\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n return c.json(formatInstallation(inst, ghApp, baseUrl));\n }\n }\n\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n });\n\n app.get(\"/orgs/:org/installation\", (c) => {\n const orgLogin = c.req.param(\"org\");\n const org = gh.orgs.findOneBy(\"login\", orgLogin);\n if (!org) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const inst = gh.appInstallations.all().find((i) => i.account_id === org.id && i.account_type === \"Organization\");\n if (!inst) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n return c.json(formatInstallation(inst, ghApp, baseUrl));\n });\n\n app.get(\"/users/:username/installation\", (c) => {\n const username = c.req.param(\"username\");\n const user = gh.users.findOneBy(\"login\", username);\n if (!user) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const inst = gh.appInstallations.all().find((i) => i.account_id === user.id && i.account_type === \"User\");\n if (!inst) {\n return c.json({ message: \"Not Found\", documentation_url: \"https://docs.github.com/rest\" }, 404);\n }\n\n const ghApp = gh.apps.all().find((a) => a.app_id === inst.app_id);\n return c.json(formatInstallation(inst, ghApp, baseUrl));\n });\n\n function formatInstallation(inst: any, ghApp: any, baseUrl: string) {\n const account = inst.account_type === \"Organization\" ? gh.orgs.get(inst.account_id) : gh.users.get(inst.account_id);\n\n return {\n id: inst.installation_id,\n account: account\n ? {\n login: account.login,\n id: account.id,\n node_id: account.node_id,\n type: inst.account_type,\n avatar_url: `${baseUrl}/avatars/u/${account.login}`,\n url: `${baseUrl}/${inst.account_type === \"Organization\" ? \"orgs\" : \"users\"}/${account.login}`,\n }\n : null,\n repository_selection: inst.repository_selection,\n access_tokens_url: `${baseUrl}/app/installations/${inst.installation_id}/access_tokens`,\n repositories_url: `${baseUrl}/installation/repositories`,\n html_url: `${baseUrl}/settings/installations/${inst.installation_id}`,\n app_id: inst.app_id,\n app_slug: ghApp?.slug ?? null,\n target_type: inst.account_type,\n permissions: inst.permissions,\n events: inst.events,\n created_at: inst.created_at,\n updated_at: inst.updated_at,\n single_file_name: null,\n has_multiple_single_files: false,\n single_file_paths: [],\n suspended_by: null,\n suspended_at: inst.suspended_at,\n };\n }\n}\n","import type { RouteContext } from \"@emulators/core\";\n\n// OpenAPI 3.1 document for this GitHub emulator instance, pointed at itself, with\n// an HTTP bearer (personal access token) security scheme. Mint a token via\n// POST /__token and use it as the client's bearer credential.\nexport function openapiRoutes({ app, baseUrl }: RouteContext): void {\n app.get(\"/openapi.json\", (c) => c.json(buildSpec(baseUrl)));\n}\n\nconst ok = (description: string) => ({\n description,\n content: { \"application/json\": { schema: { type: \"object\" } } },\n});\nconst owner = { name: \"owner\", in: \"path\", required: true, schema: { type: \"string\" } };\nconst repo = { name: \"repo\", in: \"path\", required: true, schema: { type: \"string\" } };\n\nfunction buildSpec(baseUrl: string): Record<string, unknown> {\n return {\n openapi: \"3.1.0\",\n info: {\n title: \"GitHub REST API (Emulated)\",\n version: \"1.0.0\",\n description:\n \"Emulated subset of the GitHub REST API. Authenticate with a bearer token (mint one via POST /__token, or use a seeded token).\",\n },\n servers: [{ url: baseUrl }],\n components: {\n securitySchemes: {\n githubToken: { type: \"http\", scheme: \"bearer\", description: \"Personal access token (emu_github_…).\" },\n },\n },\n security: [{ githubToken: [] }],\n paths: {\n \"/user\": {\n get: {\n operationId: \"getAuthenticatedUser\",\n summary: \"Get the authenticated user\",\n responses: { \"200\": ok(\"User object.\") },\n },\n },\n \"/users/{username}\": {\n get: {\n operationId: \"getUser\",\n summary: \"Get a user\",\n parameters: [{ name: \"username\", in: \"path\", required: true, schema: { type: \"string\" } }],\n responses: { \"200\": ok(\"User object.\") },\n },\n },\n \"/user/repos\": {\n get: {\n operationId: \"listAuthenticatedUserRepos\",\n summary: \"List repositories for the authenticated user\",\n responses: { \"200\": ok(\"Repository list.\") },\n },\n },\n \"/repos/{owner}/{repo}\": {\n get: {\n operationId: \"getRepo\",\n summary: \"Get a repository\",\n parameters: [owner, repo],\n responses: { \"200\": ok(\"Repository object.\") },\n },\n },\n \"/repos/{owner}/{repo}/issues\": {\n get: {\n operationId: \"listIssues\",\n summary: \"List issues in a repository\",\n parameters: [owner, repo, { name: \"state\", in: \"query\", required: false, schema: { type: \"string\" } }],\n responses: { \"200\": ok(\"Issue list.\") },\n },\n post: {\n operationId: \"createIssue\",\n summary: \"Create an issue\",\n parameters: [owner, repo],\n requestBody: {\n required: true,\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n required: [\"title\"],\n properties: { title: { type: \"string\" }, body: { type: \"string\" } },\n },\n },\n },\n },\n responses: { \"201\": ok(\"Created issue.\") },\n },\n },\n \"/search/repositories\": {\n get: {\n operationId: \"searchRepositories\",\n summary: \"Search repositories\",\n parameters: [{ name: \"q\", in: \"query\", required: true, schema: { type: \"string\" } }],\n responses: { \"200\": ok(\"Search results.\") },\n },\n },\n },\n };\n}\n","import type { ServiceManifest } from \"@emulators/core\";\n\n/**\n * GitHub's machine-readable service manifest. This is the single source of truth\n * for GitHub's surfaces, auth, specs, seed shape, and copyable connection\n * snippets, consumed by the CLI registry, the Cloudflare host, and the console.\n */\nexport const manifest: ServiceManifest = {\n id: \"github\",\n name: \"GitHub\",\n description: \"Stateful GitHub emulator for REST, GraphQL, OAuth, GitHub Apps, webhooks, and MCP flows.\",\n docsUrl: \"https://docs.emulators.dev/github\",\n surfaces: [\n { id: \"rest\", kind: \"rest\", title: \"REST API\", status: \"partial\", basePath: \"/\" },\n { id: \"graphql\", kind: \"graphql\", title: \"GraphQL API\", status: \"partial\", basePath: \"/graphql\" },\n { id: \"oauth\", kind: \"oauth\", title: \"OAuth app flow\", status: \"supported\", basePath: \"/login/oauth\" },\n { id: \"apps\", kind: \"provider-specific\", title: \"GitHub App auth\", status: \"partial\" },\n { id: \"mcp\", kind: \"mcp\", title: \"GitHub MCP surface\", status: \"partial\", basePath: \"/mcp\" },\n { id: \"webhooks\", kind: \"webhooks\", title: \"Webhooks\", status: \"partial\" },\n ],\n auth: [\n { id: \"bearer\", title: \"Bearer token\", type: \"bearer-token\", status: \"partial\" },\n { id: \"oauth-code\", title: \"OAuth authorization code\", type: \"oauth-authorization-code\", status: \"supported\" },\n { id: \"github-app-jwt\", title: \"GitHub App JWT\", type: \"jwt-app\", status: \"partial\" },\n {\n id: \"mcp-dcr\",\n title: \"MCP dynamic client registration\",\n type: \"dynamic-client-registration\",\n status: \"partial\",\n },\n { id: \"webhook-secret\", title: \"Webhook secret\", type: \"webhook-secret\", status: \"partial\" },\n ],\n specs: [\n {\n kind: \"openapi\",\n title: \"GitHub REST API subset\",\n coverage: \"hand-authored\",\n operations: [\n { operationId: \"users/getAuthenticated\", method: \"GET\", path: \"/user\", status: \"hand-authored\" },\n { operationId: \"users/getByUsername\", method: \"GET\", path: \"/users/:username\", status: \"hand-authored\" },\n { operationId: \"repos/get\", method: \"GET\", path: \"/repos/:owner/:repo\", status: \"hand-authored\" },\n {\n operationId: \"repos/createForAuthenticatedUser\",\n method: \"POST\",\n path: \"/user/repos\",\n status: \"hand-authored\",\n },\n {\n operationId: \"issues/listForRepo\",\n method: \"GET\",\n path: \"/repos/:owner/:repo/issues\",\n status: \"hand-authored\",\n },\n { operationId: \"issues/create\", method: \"POST\", path: \"/repos/:owner/:repo/issues\", status: \"hand-authored\" },\n { operationId: \"pulls/list\", method: \"GET\", path: \"/repos/:owner/:repo/pulls\", status: \"hand-authored\" },\n { operationId: \"pulls/create\", method: \"POST\", path: \"/repos/:owner/:repo/pulls\", status: \"hand-authored\" },\n {\n operationId: \"actions/listWorkflowRuns\",\n method: \"GET\",\n path: \"/repos/:owner/:repo/actions/runs\",\n status: \"partial\",\n },\n ],\n },\n { kind: \"graphql\", title: \"GitHub GraphQL subset\", coverage: \"hand-authored\" },\n { kind: \"mcp\", title: \"GitHub MCP tool subset\", coverage: \"hand-authored\" },\n { kind: \"manual\", title: \"GitHub App and webhook behavior\", coverage: \"partial\" },\n ],\n scenarios: [\n { id: \"empty\", title: \"Empty account\", description: \"A single authenticated user with no repositories.\" },\n { id: \"repo-with-pr\", title: \"Repository with pull request\", description: \"An org repo seeded with an open PR.\" },\n ],\n seedSchema: {\n description: \"Seed users, organizations, repositories, and OAuth apps.\",\n fields: [\n {\n key: \"users\",\n title: \"Users\",\n description: \"Accounts addressable by login.\",\n example: [{ login: \"octocat\", name: \"The Octocat\" }],\n },\n { key: \"orgs\", title: \"Organizations\", example: [{ login: \"my-org\", name: \"My Organization\" }] },\n { key: \"repos\", title: \"Repositories\", example: [{ owner: \"octocat\", name: \"hello-world\", auto_init: true }] },\n {\n key: \"oauth_apps\",\n title: \"OAuth apps\",\n example: [{ client_id: \"Iv1.example\", client_secret: \"example\", name: \"My App\" }],\n },\n ],\n example: {\n users: [{ login: \"octocat\", name: \"The Octocat\", email: \"octocat@github.com\" }],\n orgs: [{ login: \"my-org\", name: \"My Organization\" }],\n repos: [{ owner: \"octocat\", name: \"hello-world\", description: \"My first repository\", auto_init: true }],\n },\n },\n stateModel: {\n description: \"Entities mutated by GitHub provider calls.\",\n collections: [\n { name: \"users\" },\n { name: \"repos\" },\n { name: \"issues\" },\n { name: \"pulls\" },\n { name: \"orgs\" },\n { name: \"teams\" },\n { name: \"releases\" },\n { name: \"apps\" },\n { name: \"oauth_apps\" },\n ],\n },\n connections: [\n {\n id: \"octokit\",\n title: \"Octokit (TypeScript)\",\n kind: \"sdk\",\n language: \"typescript\",\n description: \"Point Octokit at the emulator instance.\",\n template:\n 'import { Octokit } from \"@octokit/rest\";\\n\\nconst octokit = new Octokit({\\n baseUrl: \"{{baseUrl}}\",\\n auth: \"{{token}}\",\\n});',\n },\n {\n id: \"gh-env\",\n title: \"GitHub API base URL (env)\",\n kind: \"env\",\n language: \"bash\",\n description: \"Many GitHub SDKs and the gh CLI honor GITHUB_API_URL.\",\n template: \"GITHUB_API_URL={{baseUrl}}\\nGITHUB_TOKEN={{token}}\",\n },\n {\n id: \"curl\",\n title: \"curl\",\n kind: \"curl\",\n language: \"bash\",\n description: \"Call the REST API directly.\",\n template: 'curl -s {{baseUrl}}/user -H \"authorization: Bearer {{token}}\"',\n },\n ],\n};\n","/** @internal */\nexport function devAssert(condition, message) {\n const booleanCondition = Boolean(condition);\n\n if (!booleanCondition) {\n throw new Error(message);\n }\n}\n","/**\n * Returns true if the value acts like a Promise, i.e. has a \"then\" function,\n * otherwise returns false.\n *\n * @internal\n */\nexport function isPromise(value) {\n return (\n typeof (value === null || value === void 0 ? void 0 : value.then) ===\n 'function'\n );\n}\n","/**\n * Return true if `value` is object-like. A value is object-like if it's not\n * `null` and has a `typeof` result of \"object\".\n *\n * @internal\n */\nexport function isObjectLike(value) {\n return typeof value == 'object' && value !== null;\n}\n","/** @internal */\nexport function invariant(condition, message) {\n const booleanCondition = Boolean(condition);\n\n if (!booleanCondition) {\n throw new Error(\n message != null ? message : 'Unexpected invariant triggered.',\n );\n }\n}\n","/** @category Source */\nimport { invariant } from '../jsutils/invariant.mjs';\nconst LineRegExp = /\\r\\n|[\\n\\r]/g;\n/** Represents a location in a Source. */\n\n/**\n * Takes a Source and a UTF-8 character offset, and returns the corresponding\n * line and column as a SourceLocation.\n * @param source - The source document that contains the position.\n * @param position - The UTF-8 character offset in the source body.\n * @returns The 1-indexed line and column for the given source position.\n * @example\n * ```ts\n * import { Source, getLocation } from 'graphql/language';\n *\n * const source = new Source('type Query { hello: String }');\n * const location = getLocation(source, 13);\n *\n * location; // => { line: 1, column: 14 }\n * ```\n */\nexport function getLocation(source, position) {\n let lastLineStart = 0;\n let line = 1;\n\n for (const match of source.body.matchAll(LineRegExp)) {\n typeof match.index === 'number' || invariant(false);\n\n if (match.index >= position) {\n break;\n }\n\n lastLineStart = match.index + match[0].length;\n line += 1;\n }\n\n return {\n line,\n column: position + 1 - lastLineStart,\n };\n}\n","/** @category Source */\nimport { getLocation } from './location.mjs';\n\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n * @param location - The AST location to print.\n * @returns A formatted source excerpt with line and column information.\n * @example\n * ```ts\n * import { parse, printLocation } from 'graphql/language';\n *\n * const document = parse('type Query { hello: String }');\n * const location = document.definitions[0].loc;\n *\n * if (location) {\n * const printed = printLocation(location);\n *\n * printed; // => 'GraphQL request:1:1\\n1 | type Query { hello: String }\\n | ^'\n * }\n * ```\n */\nexport function printLocation(location) {\n return printSourceLocation(\n location.source,\n getLocation(location.source, location.start),\n );\n}\n/**\n * Render a helpful description of the location in the GraphQL Source document.\n * @param source - The source document that contains the location.\n * @param sourceLocation - The 1-indexed line and column to print.\n * @returns A formatted source excerpt with line and column information.\n * @example\n * ```ts\n * import { Source, printSourceLocation } from 'graphql/language';\n *\n * const source = new Source('type Query { hello: String }');\n * const printed = printSourceLocation(source, { line: 1, column: 14 });\n *\n * printed; // => 'GraphQL request:1:14\\n1 | type Query { hello: String }\\n | ^'\n * ```\n */\n\nexport function printSourceLocation(source, sourceLocation) {\n const firstLineColumnOffset = source.locationOffset.column - 1;\n const body = ''.padStart(firstLineColumnOffset) + source.body;\n const lineIndex = sourceLocation.line - 1;\n const lineOffset = source.locationOffset.line - 1;\n const lineNum = sourceLocation.line + lineOffset;\n const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0;\n const columnNum = sourceLocation.column + columnOffset;\n const locationStr = `${source.name}:${lineNum}:${columnNum}\\n`;\n const lines = body.split(/\\r\\n|[\\n\\r]/g);\n const locationLine = lines[lineIndex]; // Special case for minified documents\n\n if (locationLine.length > 120) {\n const subLineIndex = Math.floor(columnNum / 80);\n const subLineColumnNum = columnNum % 80;\n const subLines = [];\n\n for (let i = 0; i < locationLine.length; i += 80) {\n subLines.push(locationLine.slice(i, i + 80));\n }\n\n return (\n locationStr +\n printPrefixedLines([\n [`${lineNum} |`, subLines[0]],\n ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]),\n ['|', '^'.padStart(subLineColumnNum)],\n ['|', subLines[subLineIndex + 1]],\n ])\n );\n }\n\n return (\n locationStr +\n printPrefixedLines([\n // Lines specified like this: [\"prefix\", \"string\"],\n [`${lineNum - 1} |`, lines[lineIndex - 1]],\n [`${lineNum} |`, locationLine],\n ['|', '^'.padStart(columnNum)],\n [`${lineNum + 1} |`, lines[lineIndex + 1]],\n ])\n );\n}\n\nfunction printPrefixedLines(lines) {\n const existingLines = lines.filter(([_, line]) => line !== undefined);\n const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length));\n return existingLines\n .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : ''))\n .join('\\n');\n}\n","/** @category Errors */\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { getLocation } from '../language/location.mjs';\nimport {\n printLocation,\n printSourceLocation,\n} from '../language/printLocation.mjs';\n\nfunction toNormalizedOptions(args) {\n const firstArg = args[0];\n\n if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) {\n return {\n nodes: firstArg,\n source: args[1],\n positions: args[2],\n path: args[3],\n originalError: args[4],\n extensions: args[5],\n };\n }\n\n return firstArg;\n}\n/**\n * A GraphQLError describes an Error found during the parse, validate, or\n * execute phases of performing a GraphQL operation. In addition to a message\n * and stack trace, it also includes information about the locations in a\n * GraphQL document and/or execution result that correspond to the Error.\n */\n\nexport class GraphQLError extends Error {\n /**\n * An array of `{ line, column }` locations within the source GraphQL document\n * which correspond to this error.\n *\n * Errors during validation often contain multiple locations, for example to\n * point out two things with the same name. Errors during execution include a\n * single location, the field which produced the error.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /**\n * An array describing the JSON-path into the execution response which\n * corresponds to this error. Only included for errors during execution.\n *\n * Enumerable, and appears in the result of JSON.stringify().\n */\n\n /** An array of GraphQL AST Nodes corresponding to this error. */\n\n /**\n * The source GraphQL document for the first location of this error.\n *\n * Note that if this Error represents more than one node, the source may not\n * represent nodes after the first node.\n */\n\n /**\n * An array of character offsets within the source GraphQL document\n * which correspond to this error.\n */\n\n /** Original error that caused this GraphQLError, if one exists. */\n\n /** Extension fields to add to the formatted error. */\n\n /**\n * Creates a GraphQLError instance.\n * @param message - Human-readable error message.\n * @param options - Error metadata such as source locations, response path, original error, and extensions.\n * This positional-arguments constructor overload is deprecated. Use the\n * `GraphQLError(message, options)` overload instead.\n * @example\n * ```ts\n * // Create an error from AST nodes and response metadata.\n * import { parse } from 'graphql/language';\n * import { GraphQLError } from 'graphql/error';\n *\n * const document = parse('{ greeting }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n * const error = new GraphQLError('Cannot query this field.', {\n * nodes: fieldNode,\n * path: ['greeting'],\n * extensions: { code: 'FORBIDDEN' },\n * });\n *\n * error.message; // => 'Cannot query this field.'\n * error.locations; // => [{ line: 1, column: 3 }]\n * error.path; // => ['greeting']\n * error.extensions; // => { code: 'FORBIDDEN' }\n * ```\n * @example\n * ```ts\n * // This variant derives locations from source positions and preserves the original error.\n * import { Source } from 'graphql/language';\n * import { GraphQLError } from 'graphql/error';\n *\n * const source = new Source('{ greeting }');\n * const originalError = new Error('Database unavailable.');\n * const error = new GraphQLError('Resolver failed.', {\n * source,\n * positions: [2],\n * path: ['greeting'],\n * originalError,\n * });\n *\n * error.locations; // => [{ line: 1, column: 3 }]\n * error.path; // => ['greeting']\n * error.originalError; // => originalError\n * ```\n */\n\n /**\n * Creates a GraphQLError instance using the legacy positional constructor.\n * This deprecated overload will be removed in v17. Prefer the\n * `GraphQLErrorOptions` object overload, which keeps optional error metadata\n * in a single options bag.\n * @param message - Human-readable error message.\n * @param nodes - AST node or nodes associated with this error.\n * @param source - Source document used to derive error locations.\n * @param positions - Character offsets in the source document associated with\n * this error.\n * @param path - Response path where this error occurred during execution.\n * @param originalError - Original error that caused this GraphQLError, if one\n * exists.\n * @param extensions - Extension fields to include in the formatted error.\n * @example\n * ```ts\n * import { Source } from 'graphql/language';\n * import { GraphQLError } from 'graphql/error';\n *\n * const source = new Source('{ greeting }');\n * const originalError = new Error('Database unavailable.');\n * const error = new GraphQLError(\n * 'Resolver failed.',\n * undefined,\n * source,\n * [2],\n * ['greeting'],\n * originalError,\n * { code: 'INTERNAL' },\n * );\n *\n * error.locations; // => [{ line: 1, column: 3 }]\n * error.path; // => ['greeting']\n * error.originalError; // => originalError\n * error.extensions; // => { code: 'INTERNAL' }\n * ```\n * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead.\n */\n constructor(message, ...rawArgs) {\n var _this$nodes, _nodeLocations$, _ref;\n\n const { nodes, source, positions, path, originalError, extensions } =\n toNormalizedOptions(rawArgs);\n super(message);\n this.name = 'GraphQLError';\n this.path = path !== null && path !== void 0 ? path : undefined;\n this.originalError =\n originalError !== null && originalError !== void 0\n ? originalError\n : undefined; // Compute list of blame nodes.\n\n this.nodes = undefinedIfEmpty(\n Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined,\n );\n const nodeLocations = undefinedIfEmpty(\n (_this$nodes = this.nodes) === null || _this$nodes === void 0\n ? void 0\n : _this$nodes.map((node) => node.loc).filter((loc) => loc != null),\n ); // Compute locations in the source for the given nodes/positions.\n\n this.source =\n source !== null && source !== void 0\n ? source\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : (_nodeLocations$ = nodeLocations[0]) === null ||\n _nodeLocations$ === void 0\n ? void 0\n : _nodeLocations$.source;\n this.positions =\n positions !== null && positions !== void 0\n ? positions\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : nodeLocations.map((loc) => loc.start);\n this.locations =\n positions && source\n ? positions.map((pos) => getLocation(source, pos))\n : nodeLocations === null || nodeLocations === void 0\n ? void 0\n : nodeLocations.map((loc) => getLocation(loc.source, loc.start));\n const originalExtensions = isObjectLike(\n originalError === null || originalError === void 0\n ? void 0\n : originalError.extensions,\n )\n ? originalError === null || originalError === void 0\n ? void 0\n : originalError.extensions\n : undefined;\n this.extensions =\n (_ref =\n extensions !== null && extensions !== void 0\n ? extensions\n : originalExtensions) !== null && _ref !== void 0\n ? _ref\n : Object.create(null); // Only properties prescribed by the spec should be enumerable.\n // Keep the rest as non-enumerable.\n\n Object.defineProperties(this, {\n message: {\n writable: true,\n enumerable: true,\n },\n name: {\n enumerable: false,\n },\n nodes: {\n enumerable: false,\n },\n source: {\n enumerable: false,\n },\n positions: {\n enumerable: false,\n },\n originalError: {\n enumerable: false,\n },\n }); // Include (non-enumerable) stack trace.\n\n /* c8 ignore start */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n\n if (\n originalError !== null &&\n originalError !== void 0 &&\n originalError.stack\n ) {\n Object.defineProperty(this, 'stack', {\n value: originalError.stack,\n writable: true,\n configurable: true,\n });\n } else if (Error.captureStackTrace) {\n Error.captureStackTrace(this, GraphQLError);\n } else {\n Object.defineProperty(this, 'stack', {\n value: Error().stack,\n writable: true,\n configurable: true,\n });\n }\n /* c8 ignore stop */\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLError';\n }\n /**\n * Returns this error as a human-readable message with source locations.\n * @returns The formatted error string.\n * @example\n * ```ts\n * import { Source } from 'graphql/language';\n * import { GraphQLError } from 'graphql/error';\n *\n * const error = new GraphQLError('Cannot query field \"name\".', {\n * source: new Source('{ name }'),\n * positions: [2],\n * });\n *\n * error.toString(); // => 'Cannot query field \"name\".\\n\\nGraphQL request:1:3\\n1 | { name }\\n | ^'\n * ```\n */\n\n toString() {\n let output = this.message;\n\n if (this.nodes) {\n for (const node of this.nodes) {\n if (node.loc) {\n output += '\\n\\n' + printLocation(node.loc);\n }\n }\n } else if (this.source && this.locations) {\n for (const location of this.locations) {\n output += '\\n\\n' + printSourceLocation(this.source, location);\n }\n }\n\n return output;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLError } from 'graphql/error';\n *\n * const error = new GraphQLError('Resolver failed.', {\n * path: ['viewer', 'name'],\n * extensions: { code: 'INTERNAL' },\n * });\n *\n * error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } }\n * ```\n */\n\n toJSON() {\n const formattedError = {\n message: this.message,\n };\n\n if (this.locations != null) {\n formattedError.locations = this.locations;\n }\n\n if (this.path != null) {\n formattedError.path = this.path;\n }\n\n if (this.extensions != null && Object.keys(this.extensions).length > 0) {\n formattedError.extensions = this.extensions;\n }\n\n return formattedError;\n }\n}\n\nfunction undefinedIfEmpty(array) {\n return array === undefined || array.length === 0 ? undefined : array;\n}\n/** See: https://spec.graphql.org/draft/#sec-Errors */\n\n/**\n * Prints a GraphQLError to a string, representing useful location information\n * about the error's position in the source. This deprecated helper is retained\n * for backwards compatibility; call `error.toString()` instead because\n * printError will be removed in v17.\n * @param error - The error to format.\n * @returns The printed string representation.\n * @example\n * ```ts\n * import { GraphQLError, printError } from 'graphql/error';\n *\n * const message = printError(new GraphQLError('Example error'));\n *\n * message; // => 'Example error'\n * ```\n * @deprecated Please use `error.toString` instead. Will be removed in v17\n */\nexport function printError(error) {\n return error.toString();\n}\n/**\n * Given a GraphQLError, format it according to the rules described by the\n * Response Format, Errors section of the GraphQL Specification. This deprecated\n * helper is retained for backwards compatibility; call `error.toJSON()`\n * instead because formatError will be removed in v17.\n * @param error - The error to format.\n * @returns The JSON-serializable formatted error.\n * @example\n * ```ts\n * import { GraphQLError, formatError } from 'graphql/error';\n *\n * const formatted = formatError(new GraphQLError('Example error'));\n *\n * formatted; // => { message: 'Example error' }\n * ```\n * @deprecated Please use `error.toJSON` instead. Will be removed in v17\n */\n\nexport function formatError(error) {\n return error.toJSON();\n}\n","/** @category Errors */\nimport { GraphQLError } from './GraphQLError.mjs';\n/**\n * Produces a GraphQLError representing a syntax error, containing useful\n * descriptive information about the syntax error's position in the source.\n * @param source - The GraphQL source containing the syntax error.\n * @param position - Character offset where the syntax error was encountered.\n * @param description - Human-readable description of the syntax error.\n * @returns A GraphQLError located at the syntax error position.\n * @example\n * ```ts\n * import { Source } from 'graphql/language';\n * import { syntaxError } from 'graphql/error';\n *\n * const error = syntaxError(new Source('query {'), 7, 'Expected Name');\n *\n * error.message; // => 'Syntax Error: Expected Name'\n * error.locations; // => [{ line: 1, column: 8 }]\n * ```\n */\n\nexport function syntaxError(source, position, description) {\n return new GraphQLError(`Syntax Error: ${description}`, {\n source,\n positions: [position],\n });\n}\n","/** @category AST */\n\n/**\n * Contains a range of UTF-8 character offsets and token references that\n * identify the region of the source from which the AST derived.\n */\nexport class Location {\n /** The character offset at which this Node begins. */\n\n /** The character offset at which this Node ends. */\n\n /** The Token at which this Node begins. */\n\n /** The Token at which this Node ends. */\n\n /** The Source document the AST represents. */\n\n /**\n * Creates a Location instance.\n * @param startToken - The start token.\n * @param endToken - The end token.\n * @param source - Source document used to derive error locations.\n * @example\n * ```ts\n * import { Location, Source, Token, TokenKind } from 'graphql/language';\n *\n * const source = new Source('{ hello }');\n * const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1);\n * const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9);\n * const location = new Location(startToken, endToken, source);\n *\n * location.start; // => 0\n * location.end; // => 9\n * location.source.body; // => '{ hello }'\n * ```\n */\n constructor(startToken, endToken, source) {\n this.start = startToken.start;\n this.end = endToken.end;\n this.startToken = startToken;\n this.endToken = endToken;\n this.source = source;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'Location';\n }\n /**\n * Returns a JSON representation of this location.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n *\n * const document = parse('{ hello }');\n * const location = document.loc?.toJSON();\n *\n * location; // => { start: 0, end: 9 }\n * ```\n */\n\n toJSON() {\n return {\n start: this.start,\n end: this.end,\n };\n }\n}\n/**\n * Represents a range of characters represented by a lexical token\n * within a Source.\n */\n\nexport class Token {\n /** The kind of Token. */\n\n /** The character offset at which this Node begins. */\n\n /** The character offset at which this Node ends. */\n\n /** The 1-indexed line number on which this Token appears. */\n\n /** The 1-indexed column number at which this Token begins. */\n\n /**\n * For non-punctuation tokens, represents the interpreted value of the token.\n *\n * Note: is undefined for punctuation tokens, but typed as string for\n * convenience in the parser.\n */\n\n /**\n * Tokens exist as nodes in a double-linked-list amongst all tokens\n * including ignored tokens. <SOF> is always the first node and <EOF>\n * the last.\n */\n\n /** Next token in the token stream, including ignored tokens. */\n\n /**\n * Creates a Token instance.\n * @param kind - Token kind produced by lexical analysis.\n * @param start - Character offset where this token begins.\n * @param end - Character offset where this token ends.\n * @param line - One-indexed line number where this token begins.\n * @param column - One-indexed column number where this token begins.\n * @param value - Interpreted value for non-punctuation tokens.\n * @example\n * ```ts\n * import { Token, TokenKind } from 'graphql/language';\n *\n * const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello');\n *\n * token.kind; // => TokenKind.NAME\n * token.value; // => 'hello'\n * token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 }\n * ```\n */\n constructor(kind, start, end, line, column, value) {\n this.kind = kind;\n this.start = start;\n this.end = end;\n this.line = line;\n this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n\n this.value = value;\n this.prev = null;\n this.next = null;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'Token';\n }\n /**\n * Returns a JSON representation of this token.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { Lexer, Source } from 'graphql/language';\n *\n * const lexer = new Lexer(new Source('{ hello }'));\n * const token = lexer.advance().toJSON();\n *\n * token; // => { kind: '{', value: undefined, line: 1, column: 1 }\n * ```\n */\n\n toJSON() {\n return {\n kind: this.kind,\n value: this.value,\n line: this.line,\n column: this.column,\n };\n }\n}\n/** The list of all possible AST node types. */\n\n/** @internal */\nexport const QueryDocumentKeys = {\n Name: [],\n Document: ['definitions'],\n OperationDefinition: [\n 'description',\n 'name',\n 'variableDefinitions',\n 'directives',\n 'selectionSet',\n ],\n VariableDefinition: [\n 'description',\n 'variable',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n Variable: ['name'],\n SelectionSet: ['selections'],\n Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'],\n Argument: ['name', 'value'],\n FragmentSpread: ['name', 'directives'],\n InlineFragment: ['typeCondition', 'directives', 'selectionSet'],\n FragmentDefinition: [\n 'description',\n 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0\n 'variableDefinitions',\n 'typeCondition',\n 'directives',\n 'selectionSet',\n ],\n IntValue: [],\n FloatValue: [],\n StringValue: [],\n BooleanValue: [],\n NullValue: [],\n EnumValue: [],\n ListValue: ['values'],\n ObjectValue: ['fields'],\n ObjectField: ['name', 'value'],\n Directive: ['name', 'arguments'],\n NamedType: ['name'],\n ListType: ['type'],\n NonNullType: ['type'],\n SchemaDefinition: ['description', 'directives', 'operationTypes'],\n OperationTypeDefinition: ['type'],\n ScalarTypeDefinition: ['description', 'name', 'directives'],\n ObjectTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'],\n InputValueDefinition: [\n 'description',\n 'name',\n 'type',\n 'defaultValue',\n 'directives',\n ],\n InterfaceTypeDefinition: [\n 'description',\n 'name',\n 'interfaces',\n 'directives',\n 'fields',\n ],\n UnionTypeDefinition: ['description', 'name', 'directives', 'types'],\n EnumTypeDefinition: ['description', 'name', 'directives', 'values'],\n EnumValueDefinition: ['description', 'name', 'directives'],\n InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'],\n DirectiveDefinition: [\n 'description',\n 'name',\n 'arguments',\n 'directives',\n 'locations',\n ],\n SchemaExtension: ['directives', 'operationTypes'],\n DirectiveExtension: ['name', 'directives'],\n ScalarTypeExtension: ['name', 'directives'],\n ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'],\n UnionTypeExtension: ['name', 'directives', 'types'],\n EnumTypeExtension: ['name', 'directives', 'values'],\n InputObjectTypeExtension: ['name', 'directives', 'fields'],\n TypeCoordinate: ['name'],\n MemberCoordinate: ['name', 'memberName'],\n ArgumentCoordinate: ['name', 'fieldName', 'argumentName'],\n DirectiveCoordinate: ['name'],\n DirectiveArgumentCoordinate: ['name', 'argumentName'],\n};\nconst kindValues = new Set(Object.keys(QueryDocumentKeys));\n/** @internal */\n\nexport function isNode(maybeNode) {\n const maybeKind =\n maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind;\n return typeof maybeKind === 'string' && kindValues.has(maybeKind);\n}\n/** An identifier in a GraphQL document. */\n\n/**\n * The operation types supported by GraphQL executable definitions.\n * @category Kinds\n */\nvar OperationTypeNode;\n\n(function (OperationTypeNode) {\n OperationTypeNode['QUERY'] = 'query';\n OperationTypeNode['MUTATION'] = 'mutation';\n OperationTypeNode['SUBSCRIPTION'] = 'subscription';\n})(OperationTypeNode || (OperationTypeNode = {}));\n\nexport { OperationTypeNode };\n/** A variable declaration in an operation or legacy fragment definition. */\n","/** @category Kinds */\n\n/** The set of allowed directive location values. */\nvar DirectiveLocation;\n\n(function (DirectiveLocation) {\n DirectiveLocation['QUERY'] = 'QUERY';\n DirectiveLocation['MUTATION'] = 'MUTATION';\n DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION';\n DirectiveLocation['FIELD'] = 'FIELD';\n DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION';\n DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD';\n DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT';\n DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION';\n DirectiveLocation['SCHEMA'] = 'SCHEMA';\n DirectiveLocation['SCALAR'] = 'SCALAR';\n DirectiveLocation['OBJECT'] = 'OBJECT';\n DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION';\n DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION';\n DirectiveLocation['INTERFACE'] = 'INTERFACE';\n DirectiveLocation['UNION'] = 'UNION';\n DirectiveLocation['ENUM'] = 'ENUM';\n DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE';\n DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT';\n DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION';\n DirectiveLocation['DIRECTIVE_DEFINITION'] = 'DIRECTIVE_DEFINITION';\n})(DirectiveLocation || (DirectiveLocation = {}));\n\nexport { DirectiveLocation };\n/**\n * Deprecated legacy alias for the enum type representing directive location\n * values. This alias will be removed in v17. In v17, `DirectiveLocation` is\n * exported as the single public symbol for both the runtime object and the\n * corresponding TypeScript type.\n * @deprecated Will be removed in v17. In v17, use `DirectiveLocation` as both\n * the runtime value and the type.\n */\n","/** @category Kinds */\n\n/** The set of allowed kind values for AST nodes. */\nvar Kind;\n\n(function (Kind) {\n Kind['NAME'] = 'Name';\n Kind['DOCUMENT'] = 'Document';\n Kind['OPERATION_DEFINITION'] = 'OperationDefinition';\n Kind['VARIABLE_DEFINITION'] = 'VariableDefinition';\n Kind['SELECTION_SET'] = 'SelectionSet';\n Kind['FIELD'] = 'Field';\n Kind['ARGUMENT'] = 'Argument';\n Kind['FRAGMENT_SPREAD'] = 'FragmentSpread';\n Kind['INLINE_FRAGMENT'] = 'InlineFragment';\n Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition';\n Kind['VARIABLE'] = 'Variable';\n Kind['INT'] = 'IntValue';\n Kind['FLOAT'] = 'FloatValue';\n Kind['STRING'] = 'StringValue';\n Kind['BOOLEAN'] = 'BooleanValue';\n Kind['NULL'] = 'NullValue';\n Kind['ENUM'] = 'EnumValue';\n Kind['LIST'] = 'ListValue';\n Kind['OBJECT'] = 'ObjectValue';\n Kind['OBJECT_FIELD'] = 'ObjectField';\n Kind['DIRECTIVE'] = 'Directive';\n Kind['NAMED_TYPE'] = 'NamedType';\n Kind['LIST_TYPE'] = 'ListType';\n Kind['NON_NULL_TYPE'] = 'NonNullType';\n Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition';\n Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition';\n Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition';\n Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition';\n Kind['FIELD_DEFINITION'] = 'FieldDefinition';\n Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition';\n Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition';\n Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition';\n Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition';\n Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition';\n Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition';\n Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition';\n Kind['SCHEMA_EXTENSION'] = 'SchemaExtension';\n Kind['DIRECTIVE_EXTENSION'] = 'DirectiveExtension';\n Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension';\n Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension';\n Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension';\n Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension';\n Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension';\n Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension';\n Kind['TYPE_COORDINATE'] = 'TypeCoordinate';\n Kind['MEMBER_COORDINATE'] = 'MemberCoordinate';\n Kind['ARGUMENT_COORDINATE'] = 'ArgumentCoordinate';\n Kind['DIRECTIVE_COORDINATE'] = 'DirectiveCoordinate';\n Kind['DIRECTIVE_ARGUMENT_COORDINATE'] = 'DirectiveArgumentCoordinate';\n})(Kind || (Kind = {}));\n\nexport { Kind };\n/**\n * Deprecated legacy alias for the enum type representing the possible kind\n * values of AST nodes. This alias will be removed in v17. In v17, `Kind` is\n * exported as the single public symbol for both the runtime object and the\n * corresponding TypeScript type.\n * @deprecated Will be removed in v17. In v17, use `Kind` as both the runtime\n * value and the type.\n */\n","/**\n * ```\n * WhiteSpace ::\n * - \"Horizontal Tab (U+0009)\"\n * - \"Space (U+0020)\"\n * ```\n * @internal\n */\nexport function isWhiteSpace(code) {\n return code === 0x0009 || code === 0x0020;\n}\n/**\n * ```\n * Digit :: one of\n * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * ```\n * @internal\n */\n\nexport function isDigit(code) {\n return code >= 0x0030 && code <= 0x0039;\n}\n/**\n * ```\n * Letter :: one of\n * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M`\n * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z`\n * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m`\n * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z`\n * ```\n * @internal\n */\n\nexport function isLetter(code) {\n return (\n (code >= 0x0061 && code <= 0x007a) || // A-Z\n (code >= 0x0041 && code <= 0x005a) // a-z\n );\n}\n/**\n * ```\n * NameStart ::\n * - Letter\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameStart(code) {\n return isLetter(code) || code === 0x005f;\n}\n/**\n * ```\n * NameContinue ::\n * - Letter\n * - Digit\n * - `_`\n * ```\n * @internal\n */\n\nexport function isNameContinue(code) {\n return isLetter(code) || isDigit(code) || code === 0x005f;\n}\n","import { isWhiteSpace } from './characterClasses.mjs';\n/**\n * Produces the value of a block string from its parsed raw value, similar to\n * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc.\n *\n * This implements the GraphQL spec's BlockStringValue() static algorithm.\n *\n * @internal\n */\n\nexport function dedentBlockStringLines(lines) {\n var _firstNonEmptyLine2;\n\n let commonIndent = Number.MAX_SAFE_INTEGER;\n let firstNonEmptyLine = null;\n let lastNonEmptyLine = -1;\n\n for (let i = 0; i < lines.length; ++i) {\n var _firstNonEmptyLine;\n\n const line = lines[i];\n const indent = leadingWhitespace(line);\n\n if (indent === line.length) {\n continue; // skip empty lines\n }\n\n firstNonEmptyLine =\n (_firstNonEmptyLine = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine !== void 0\n ? _firstNonEmptyLine\n : i;\n lastNonEmptyLine = i;\n\n if (i !== 0 && indent < commonIndent) {\n commonIndent = indent;\n }\n }\n\n return lines // Remove common indentation from all lines but first.\n .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines.\n .slice(\n (_firstNonEmptyLine2 = firstNonEmptyLine) !== null &&\n _firstNonEmptyLine2 !== void 0\n ? _firstNonEmptyLine2\n : 0,\n lastNonEmptyLine + 1,\n );\n}\n\nfunction leadingWhitespace(str) {\n let i = 0;\n\n while (i < str.length && isWhiteSpace(str.charCodeAt(i))) {\n ++i;\n }\n\n return i;\n}\n/** @internal */\n\nexport function isPrintableAsBlockString(value) {\n if (value === '') {\n return true; // empty string is printable\n }\n\n let isEmptyLine = true;\n let hasIndent = false;\n let hasCommonIndent = true;\n let seenNonEmptyLine = false;\n\n for (let i = 0; i < value.length; ++i) {\n switch (value.codePointAt(i)) {\n case 0x0000:\n case 0x0001:\n case 0x0002:\n case 0x0003:\n case 0x0004:\n case 0x0005:\n case 0x0006:\n case 0x0007:\n case 0x0008:\n case 0x000b:\n case 0x000c:\n case 0x000e:\n case 0x000f:\n return false;\n // Has non-printable characters\n\n case 0x000d:\n // \\r\n return false;\n // Has \\r or \\r\\n which will be replaced as \\n\n\n case 10:\n // \\n\n if (isEmptyLine && !seenNonEmptyLine) {\n return false; // Has leading new line\n }\n\n seenNonEmptyLine = true;\n isEmptyLine = true;\n hasIndent = false;\n break;\n\n case 9: // \\t\n\n case 32:\n // <space>\n hasIndent || (hasIndent = isEmptyLine);\n break;\n\n default:\n hasCommonIndent && (hasCommonIndent = hasIndent);\n isEmptyLine = false;\n }\n }\n\n if (isEmptyLine) {\n return false; // Has trailing empty lines\n }\n\n if (hasCommonIndent && seenNonEmptyLine) {\n return false; // Has internal indent\n }\n\n return true;\n}\n/**\n * Print a block string in the indented block form by adding a leading and\n * trailing blank line. However, if a block string starts with whitespace and is\n * a single-line, adding a leading blank line would strip that whitespace.\n *\n * @internal\n */\n\nexport function printBlockString(value, options) {\n const escapedValue = value.replace(/\"\"\"/g, '\\\\\"\"\"'); // Expand a block string's raw value into independent lines.\n\n const lines = escapedValue.split(/\\r\\n|[\\n\\r]/g);\n const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line\n\n const forceLeadingNewLine =\n lines.length > 1 &&\n lines\n .slice(1)\n .every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line\n\n const hasTrailingTripleQuotes = escapedValue.endsWith('\\\\\"\"\"'); // Trailing quote (single or double) or slash forces trailing new line\n\n const hasTrailingQuote = value.endsWith('\"') && !hasTrailingTripleQuotes;\n const hasTrailingSlash = value.endsWith('\\\\');\n const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash;\n const printAsMultipleLines =\n !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability\n (!isSingleLine ||\n value.length > 70 ||\n forceTrailingNewline ||\n forceLeadingNewLine ||\n hasTrailingTripleQuotes);\n let result = ''; // Format a multi-line block quote to account for leading space.\n\n const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0));\n\n if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) {\n result += '\\n';\n }\n\n result += escapedValue;\n\n if (printAsMultipleLines || forceTrailingNewline) {\n result += '\\n';\n }\n\n return '\"\"\"' + result + '\"\"\"';\n}\n","/** @category Lexing */\n\n/**\n * An exported enum describing the different kinds of tokens that the\n * lexer emits.\n */\nvar TokenKind;\n\n(function (TokenKind) {\n TokenKind['SOF'] = '<SOF>';\n TokenKind['EOF'] = '<EOF>';\n TokenKind['BANG'] = '!';\n TokenKind['DOLLAR'] = '$';\n TokenKind['AMP'] = '&';\n TokenKind['PAREN_L'] = '(';\n TokenKind['PAREN_R'] = ')';\n TokenKind['DOT'] = '.';\n TokenKind['SPREAD'] = '...';\n TokenKind['COLON'] = ':';\n TokenKind['EQUALS'] = '=';\n TokenKind['AT'] = '@';\n TokenKind['BRACKET_L'] = '[';\n TokenKind['BRACKET_R'] = ']';\n TokenKind['BRACE_L'] = '{';\n TokenKind['PIPE'] = '|';\n TokenKind['BRACE_R'] = '}';\n TokenKind['NAME'] = 'Name';\n TokenKind['INT'] = 'Int';\n TokenKind['FLOAT'] = 'Float';\n TokenKind['STRING'] = 'String';\n TokenKind['BLOCK_STRING'] = 'BlockString';\n TokenKind['COMMENT'] = 'Comment';\n})(TokenKind || (TokenKind = {}));\n\nexport { TokenKind };\n/**\n * Deprecated legacy alias for the enum type representing token kind values.\n * This alias will be removed in v17. In v17, `TokenKind` is exported as the\n * single public symbol for both the runtime object and the corresponding\n * TypeScript type.\n * @deprecated Will be removed in v17. In v17, use `TokenKind` as both the\n * runtime value and the type.\n */\n","/** @category Lexing */\nimport { syntaxError } from '../error/syntaxError.mjs';\nimport { Token } from './ast.mjs';\nimport { dedentBlockStringLines } from './blockString.mjs';\nimport { isDigit, isNameContinue, isNameStart } from './characterClasses.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/**\n * A Lexer interface which provides common properties and methods required for\n * lexing GraphQL source.\n *\n * @internal\n */\n\n/**\n * Given a Source object, creates a Lexer for that source.\n * A Lexer is a stateful stream generator in that every time\n * it is advanced, it returns the next token in the Source. Assuming the\n * source lexes, the final Token emitted by the lexer will be of kind\n * EOF, after which the lexer will repeatedly return the same EOF token\n * whenever called.\n */\nexport class Lexer {\n /** Source document used to derive error locations. */\n\n /** Most recent non-ignored token returned by the lexer. */\n\n /** Current non-ignored token at the lexer cursor. */\n\n /** The (1-indexed) line containing the current token. */\n\n /** Character offset where the current line starts. */\n\n /**\n * Creates a Lexer instance.\n * @param source - Source document used to derive error locations.\n * @example\n * ```ts\n * import { Lexer, Source, TokenKind } from 'graphql/language';\n *\n * const lexer = new Lexer(new Source('{ hello }'));\n *\n * lexer.token.kind; // => TokenKind.SOF\n * lexer.advance().kind; // => TokenKind.BRACE_L\n * lexer.advance().value; // => 'hello'\n * lexer.advance().kind; // => TokenKind.BRACE_R\n * ```\n */\n constructor(source) {\n const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0);\n this.source = source;\n this.lastToken = startOfFileToken;\n this.token = startOfFileToken;\n this.line = 1;\n this.lineStart = 0;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'Lexer';\n }\n /**\n * Advances the token stream to the next non-ignored token.\n * @returns The next non-ignored token.\n * @example\n * ```ts\n * import { Lexer, Source } from 'graphql/language';\n *\n * const lexer = new Lexer(new Source('{ hello }'));\n * const token = lexer.advance();\n *\n * token.kind; // => '{'\n * lexer.token; // => token\n * ```\n */\n\n advance() {\n this.lastToken = this.token;\n const token = (this.token = this.lookahead());\n return token;\n }\n /**\n * Looks ahead and returns the next non-ignored token, but does not change\n * the state of Lexer.\n * @returns The next non-ignored token without advancing the lexer.\n * @example\n * ```ts\n * import { Lexer, Source } from 'graphql/language';\n *\n * const lexer = new Lexer(new Source('{ hello }'));\n * const token = lexer.lookahead();\n *\n * token.kind; // => '{'\n * lexer.token.kind; // => '<SOF>'\n * ```\n */\n\n lookahead() {\n let token = this.token;\n\n if (token.kind !== TokenKind.EOF) {\n do {\n if (token.next) {\n token = token.next;\n } else {\n // Read the next token and form a link in the token linked-list.\n const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing.\n\n token.next = nextToken; // @ts-expect-error prev is only mutable during parsing.\n\n nextToken.prev = token;\n token = nextToken;\n }\n } while (token.kind === TokenKind.COMMENT);\n }\n\n return token;\n }\n}\n/** @internal */\n\nexport function isPunctuatorTokenKind(kind) {\n return (\n kind === TokenKind.BANG ||\n kind === TokenKind.DOLLAR ||\n kind === TokenKind.AMP ||\n kind === TokenKind.PAREN_L ||\n kind === TokenKind.PAREN_R ||\n kind === TokenKind.DOT ||\n kind === TokenKind.SPREAD ||\n kind === TokenKind.COLON ||\n kind === TokenKind.EQUALS ||\n kind === TokenKind.AT ||\n kind === TokenKind.BRACKET_L ||\n kind === TokenKind.BRACKET_R ||\n kind === TokenKind.BRACE_L ||\n kind === TokenKind.PIPE ||\n kind === TokenKind.BRACE_R\n );\n}\n/**\n * A Unicode scalar value is any Unicode code point except surrogate code\n * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and\n * 0xE000 to 0x10FFFF.\n *\n * SourceCharacter ::\n * - \"Any Unicode scalar value\"\n *\n * @internal\n */\n\nfunction isUnicodeScalarValue(code) {\n return (\n (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff)\n );\n}\n/**\n * The GraphQL specification defines source text as a sequence of unicode scalar\n * values (which Unicode defines to exclude surrogate code points). However\n * JavaScript defines strings as a sequence of UTF-16 code units which may\n * include surrogates. A surrogate pair is a valid source character as it\n * encodes a supplementary code point (above U+FFFF), but unpaired surrogate\n * code points are not valid source characters.\n *\n * @internal\n */\n\nfunction isSupplementaryCodePoint(body, location) {\n return (\n isLeadingSurrogate(body.charCodeAt(location)) &&\n isTrailingSurrogate(body.charCodeAt(location + 1))\n );\n}\n\nfunction isLeadingSurrogate(code) {\n return code >= 0xd800 && code <= 0xdbff;\n}\n\nfunction isTrailingSurrogate(code) {\n return code >= 0xdc00 && code <= 0xdfff;\n}\n/**\n * Prints the code point (or end of file reference) at a given location in a\n * source for use in error messages.\n *\n * Printable ASCII is printed quoted, while other points are printed in Unicode\n * code point form (ie. U+1234).\n *\n * @internal\n */\n\nexport function printCodePointAt(lexer, location) {\n const code = lexer.source.body.codePointAt(location);\n\n if (code === undefined) {\n return TokenKind.EOF;\n } else if (code >= 0x0020 && code <= 0x007e) {\n // Printable ASCII\n const char = String.fromCodePoint(code);\n return char === '\"' ? \"'\\\"'\" : `\"${char}\"`;\n } // Unicode code point\n\n return 'U+' + code.toString(16).toUpperCase().padStart(4, '0');\n}\n/**\n * Create a token with line and column location information.\n *\n * @internal\n */\n\nexport function createToken(lexer, kind, start, end, value) {\n const line = lexer.line;\n const col = 1 + start - lexer.lineStart;\n return new Token(kind, start, end, line, col, value);\n}\n/**\n * Gets the next token from the source starting at the given position.\n *\n * This skips over whitespace until it finds the next lexable token, then lexes\n * punctuators immediately or calls the appropriate helper function for more\n * complicated tokens.\n *\n * @internal\n */\n\nfunction readNextToken(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // SourceCharacter\n\n switch (code) {\n // Ignored ::\n // - UnicodeBOM\n // - WhiteSpace\n // - LineTerminator\n // - Comment\n // - Comma\n //\n // UnicodeBOM :: \"Byte Order Mark (U+FEFF)\"\n //\n // WhiteSpace ::\n // - \"Horizontal Tab (U+0009)\"\n // - \"Space (U+0020)\"\n //\n // Comma :: ,\n case 0xfeff: // <BOM>\n\n case 0x0009: // \\t\n\n case 0x0020: // <space>\n\n case 0x002c:\n // ,\n ++position;\n continue;\n // LineTerminator ::\n // - \"New Line (U+000A)\"\n // - \"Carriage Return (U+000D)\" [lookahead != \"New Line (U+000A)\"]\n // - \"Carriage Return (U+000D)\" \"New Line (U+000A)\"\n\n case 0x000a:\n // \\n\n ++position;\n ++lexer.line;\n lexer.lineStart = position;\n continue;\n\n case 0x000d:\n // \\r\n if (body.charCodeAt(position + 1) === 0x000a) {\n position += 2;\n } else {\n ++position;\n }\n\n ++lexer.line;\n lexer.lineStart = position;\n continue;\n // Comment\n\n case 0x0023:\n // #\n return readComment(lexer, position);\n // Token ::\n // - Punctuator\n // - Name\n // - IntValue\n // - FloatValue\n // - StringValue\n //\n // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | }\n\n case 0x0021:\n // !\n return createToken(lexer, TokenKind.BANG, position, position + 1);\n\n case 0x0024:\n // $\n return createToken(lexer, TokenKind.DOLLAR, position, position + 1);\n\n case 0x0026:\n // &\n return createToken(lexer, TokenKind.AMP, position, position + 1);\n\n case 0x0028:\n // (\n return createToken(lexer, TokenKind.PAREN_L, position, position + 1);\n\n case 0x0029:\n // )\n return createToken(lexer, TokenKind.PAREN_R, position, position + 1);\n\n case 0x002e:\n // .\n if (\n body.charCodeAt(position + 1) === 0x002e &&\n body.charCodeAt(position + 2) === 0x002e\n ) {\n return createToken(lexer, TokenKind.SPREAD, position, position + 3);\n }\n\n break;\n\n case 0x003a:\n // :\n return createToken(lexer, TokenKind.COLON, position, position + 1);\n\n case 0x003d:\n // =\n return createToken(lexer, TokenKind.EQUALS, position, position + 1);\n\n case 0x0040:\n // @\n return createToken(lexer, TokenKind.AT, position, position + 1);\n\n case 0x005b:\n // [\n return createToken(lexer, TokenKind.BRACKET_L, position, position + 1);\n\n case 0x005d:\n // ]\n return createToken(lexer, TokenKind.BRACKET_R, position, position + 1);\n\n case 0x007b:\n // {\n return createToken(lexer, TokenKind.BRACE_L, position, position + 1);\n\n case 0x007c:\n // |\n return createToken(lexer, TokenKind.PIPE, position, position + 1);\n\n case 0x007d:\n // }\n return createToken(lexer, TokenKind.BRACE_R, position, position + 1);\n // StringValue\n\n case 0x0022:\n // \"\n if (\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022\n ) {\n return readBlockString(lexer, position);\n }\n\n return readString(lexer, position);\n } // IntValue | FloatValue (Digit | -)\n\n if (isDigit(code) || code === 0x002d) {\n return readNumber(lexer, position, code);\n } // Name\n\n if (isNameStart(code)) {\n return readName(lexer, position);\n }\n\n throw syntaxError(\n lexer.source,\n position,\n code === 0x0027\n ? 'Unexpected single quote character (\\'), did you mean to use a double quote (\")?'\n : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position)\n ? `Unexpected character: ${printCodePointAt(lexer, position)}.`\n : `Invalid character: ${printCodePointAt(lexer, position)}.`,\n );\n }\n\n return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength);\n}\n/**\n * Reads a comment token from the source file.\n *\n * ```\n * Comment :: # CommentChar* [lookahead != CommentChar]\n *\n * CommentChar :: SourceCharacter but not LineTerminator\n * ```\n *\n * @internal\n */\n\nfunction readComment(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // LineTerminator (\\n | \\r)\n\n if (code === 0x000a || code === 0x000d) {\n break;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n break;\n }\n }\n\n return createToken(\n lexer,\n TokenKind.COMMENT,\n start,\n position,\n body.slice(start + 1, position),\n );\n}\n/**\n * Reads a number token from the source file, either a FloatValue or an IntValue\n * depending on whether a FractionalPart or ExponentPart is encountered.\n *\n * ```\n * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}]\n *\n * IntegerPart ::\n * - NegativeSign? 0\n * - NegativeSign? NonZeroDigit Digit*\n *\n * NegativeSign :: -\n *\n * NonZeroDigit :: Digit but not `0`\n *\n * FloatValue ::\n * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}]\n * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}]\n *\n * FractionalPart :: . Digit+\n *\n * ExponentPart :: ExponentIndicator Sign? Digit+\n *\n * ExponentIndicator :: one of `e` `E`\n *\n * Sign :: one of + -\n * ```\n *\n * @internal\n */\n\nfunction readNumber(lexer, start, firstCode) {\n const body = lexer.source.body;\n let position = start;\n let code = firstCode;\n let isFloat = false; // NegativeSign (-)\n\n if (code === 0x002d) {\n code = body.charCodeAt(++position);\n } // Zero (0)\n\n if (code === 0x0030) {\n code = body.charCodeAt(++position);\n\n if (isDigit(code)) {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid number, unexpected digit after 0: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n } else {\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // Full stop (.)\n\n if (code === 0x002e) {\n isFloat = true;\n code = body.charCodeAt(++position);\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // E e\n\n if (code === 0x0045 || code === 0x0065) {\n isFloat = true;\n code = body.charCodeAt(++position); // + -\n\n if (code === 0x002b || code === 0x002d) {\n code = body.charCodeAt(++position);\n }\n\n position = readDigits(lexer, position, code);\n code = body.charCodeAt(position);\n } // Numbers cannot be followed by . or NameStart\n\n if (code === 0x002e || isNameStart(code)) {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid number, expected digit but got: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n\n return createToken(\n lexer,\n isFloat ? TokenKind.FLOAT : TokenKind.INT,\n start,\n position,\n body.slice(start, position),\n );\n}\n/**\n * Returns the new position in the source after reading one or more digits.\n *\n * @internal\n */\n\nfunction readDigits(lexer, start, firstCode) {\n if (!isDigit(firstCode)) {\n throw syntaxError(\n lexer.source,\n start,\n `Invalid number, expected digit but got: ${printCodePointAt(\n lexer,\n start,\n )}.`,\n );\n }\n\n const body = lexer.source.body;\n let position = start + 1; // +1 to skip first firstCode\n\n while (isDigit(body.charCodeAt(position))) {\n ++position;\n }\n\n return position;\n}\n/**\n * Reads a single-quote string token from the source file.\n *\n * ```\n * StringValue ::\n * - `\"\"` [lookahead != `\"`]\n * - `\"` StringCharacter+ `\"`\n *\n * StringCharacter ::\n * - SourceCharacter but not `\"` or `\\` or LineTerminator\n * - `\\u` EscapedUnicode\n * - `\\` EscapedCharacter\n *\n * EscapedUnicode ::\n * - `{` HexDigit+ `}`\n * - HexDigit HexDigit HexDigit HexDigit\n *\n * EscapedCharacter :: one of `\"` `\\` `/` `b` `f` `n` `r` `t`\n * ```\n *\n * @internal\n */\n\nfunction readString(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n let chunkStart = position;\n let value = '';\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // Closing Quote (\")\n\n if (code === 0x0022) {\n value += body.slice(chunkStart, position);\n return createToken(lexer, TokenKind.STRING, start, position + 1, value);\n } // Escape Sequence (\\)\n\n if (code === 0x005c) {\n value += body.slice(chunkStart, position);\n const escape =\n body.charCodeAt(position + 1) === 0x0075 // u\n ? body.charCodeAt(position + 2) === 0x007b // {\n ? readEscapedUnicodeVariableWidth(lexer, position)\n : readEscapedUnicodeFixedWidth(lexer, position)\n : readEscapedCharacter(lexer, position);\n value += escape.value;\n position += escape.size;\n chunkStart = position;\n continue;\n } // LineTerminator (\\n | \\r)\n\n if (code === 0x000a || code === 0x000d) {\n break;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character within String: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n }\n\n throw syntaxError(lexer.source, position, 'Unterminated string.');\n} // The string value and lexed size of an escape sequence.\n\nfunction readEscapedUnicodeVariableWidth(lexer, position) {\n const body = lexer.source.body;\n let point = 0;\n let size = 3; // Cannot be larger than 12 chars (\\u{00000000}).\n\n while (size < 12) {\n const code = body.charCodeAt(position + size++); // Closing Brace (})\n\n if (code === 0x007d) {\n // Must be at least 5 chars (\\u{0}) and encode a Unicode scalar value.\n if (size < 5 || !isUnicodeScalarValue(point)) {\n break;\n }\n\n return {\n value: String.fromCodePoint(point),\n size,\n };\n } // Append this hex digit to the code point.\n\n point = (point << 4) | readHexDigit(code);\n\n if (point < 0) {\n break;\n }\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid Unicode escape sequence: \"${body.slice(\n position,\n position + size,\n )}\".`,\n );\n}\n\nfunction readEscapedUnicodeFixedWidth(lexer, position) {\n const body = lexer.source.body;\n const code = read16BitHexCode(body, position + 2);\n\n if (isUnicodeScalarValue(code)) {\n return {\n value: String.fromCodePoint(code),\n size: 6,\n };\n } // GraphQL allows JSON-style surrogate pair escape sequences, but only when\n // a valid pair is formed.\n\n if (isLeadingSurrogate(code)) {\n // \\u\n if (\n body.charCodeAt(position + 6) === 0x005c &&\n body.charCodeAt(position + 7) === 0x0075\n ) {\n const trailingCode = read16BitHexCode(body, position + 8);\n\n if (isTrailingSurrogate(trailingCode)) {\n // JavaScript defines strings as a sequence of UTF-16 code units and\n // encodes Unicode code points above U+FFFF using a surrogate pair of\n // code units. Since this is a surrogate pair escape sequence, just\n // include both codes into the JavaScript string value. Had JavaScript\n // not been internally based on UTF-16, then this surrogate pair would\n // be decoded to retrieve the supplementary code point.\n return {\n value: String.fromCodePoint(code, trailingCode),\n size: 12,\n };\n }\n }\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid Unicode escape sequence: \"${body.slice(position, position + 6)}\".`,\n );\n}\n/**\n * Reads four hexadecimal characters and returns the positive integer that 16bit\n * hexadecimal string represents. For example, \"000f\" will return 15, and \"dead\"\n * will return 57005.\n *\n * Returns a negative number if any char was not a valid hexadecimal digit.\n *\n * @internal\n */\n\nfunction read16BitHexCode(body, position) {\n // readHexDigit() returns -1 on error. ORing a negative value with any other\n // value always produces a negative value.\n return (\n (readHexDigit(body.charCodeAt(position)) << 12) |\n (readHexDigit(body.charCodeAt(position + 1)) << 8) |\n (readHexDigit(body.charCodeAt(position + 2)) << 4) |\n readHexDigit(body.charCodeAt(position + 3))\n );\n}\n/**\n * Reads a hexadecimal character and returns its positive integer value (0-15).\n *\n * '0' becomes 0, '9' becomes 9\n * 'A' becomes 10, 'F' becomes 15\n * 'a' becomes 10, 'f' becomes 15\n *\n * Returns -1 if the provided character code was not a valid hexadecimal digit.\n *\n * HexDigit :: one of\n * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9`\n * - `A` `B` `C` `D` `E` `F`\n * - `a` `b` `c` `d` `e` `f`\n *\n * @internal\n */\n\nfunction readHexDigit(code) {\n return code >= 0x0030 && code <= 0x0039 // 0-9\n ? code - 0x0030\n : code >= 0x0041 && code <= 0x0046 // A-F\n ? code - 0x0037\n : code >= 0x0061 && code <= 0x0066 // a-f\n ? code - 0x0057\n : -1;\n}\n/**\n * | Escaped Character | Code Point | Character Name |\n * | ----------------- | ---------- | ---------------------------- |\n * | `\"` | U+0022 | double quote |\n * | `\\` | U+005C | reverse solidus (back slash) |\n * | `/` | U+002F | solidus (forward slash) |\n * | `b` | U+0008 | backspace |\n * | `f` | U+000C | form feed |\n * | `n` | U+000A | line feed (new line) |\n * | `r` | U+000D | carriage return |\n * | `t` | U+0009 | horizontal tab |\n *\n * @internal\n */\n\nfunction readEscapedCharacter(lexer, position) {\n const body = lexer.source.body;\n const code = body.charCodeAt(position + 1);\n\n switch (code) {\n case 0x0022:\n // \"\n return {\n value: '\\u0022',\n size: 2,\n };\n\n case 0x005c:\n // \\\n return {\n value: '\\u005c',\n size: 2,\n };\n\n case 0x002f:\n // /\n return {\n value: '\\u002f',\n size: 2,\n };\n\n case 0x0062:\n // b\n return {\n value: '\\u0008',\n size: 2,\n };\n\n case 0x0066:\n // f\n return {\n value: '\\u000c',\n size: 2,\n };\n\n case 0x006e:\n // n\n return {\n value: '\\u000a',\n size: 2,\n };\n\n case 0x0072:\n // r\n return {\n value: '\\u000d',\n size: 2,\n };\n\n case 0x0074:\n // t\n return {\n value: '\\u0009',\n size: 2,\n };\n }\n\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character escape sequence: \"${body.slice(\n position,\n position + 2,\n )}\".`,\n );\n}\n/**\n * Reads a block string token from the source file.\n *\n * ```\n * StringValue ::\n * - `\"\"\"` BlockStringCharacter* `\"\"\"`\n *\n * BlockStringCharacter ::\n * - SourceCharacter but not `\"\"\"` or `\\\"\"\"`\n * - `\\\"\"\"`\n * ```\n *\n * @internal\n */\n\nfunction readBlockString(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let lineStart = lexer.lineStart;\n let position = start + 3;\n let chunkStart = position;\n let currentLine = '';\n const blockLines = [];\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position); // Closing Triple-Quote (\"\"\")\n\n if (\n code === 0x0022 &&\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022\n ) {\n currentLine += body.slice(chunkStart, position);\n blockLines.push(currentLine);\n const token = createToken(\n lexer,\n TokenKind.BLOCK_STRING,\n start,\n position + 3, // Return a string of the lines joined with U+000A.\n dedentBlockStringLines(blockLines).join('\\n'),\n );\n lexer.line += blockLines.length - 1;\n lexer.lineStart = lineStart;\n return token;\n } // Escaped Triple-Quote (\\\"\"\")\n\n if (\n code === 0x005c &&\n body.charCodeAt(position + 1) === 0x0022 &&\n body.charCodeAt(position + 2) === 0x0022 &&\n body.charCodeAt(position + 3) === 0x0022\n ) {\n currentLine += body.slice(chunkStart, position);\n chunkStart = position + 1; // skip only slash\n\n position += 4;\n continue;\n } // LineTerminator\n\n if (code === 0x000a || code === 0x000d) {\n currentLine += body.slice(chunkStart, position);\n blockLines.push(currentLine);\n\n if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) {\n position += 2;\n } else {\n ++position;\n }\n\n currentLine = '';\n chunkStart = position;\n lineStart = position;\n continue;\n } // SourceCharacter\n\n if (isUnicodeScalarValue(code)) {\n ++position;\n } else if (isSupplementaryCodePoint(body, position)) {\n position += 2;\n } else {\n throw syntaxError(\n lexer.source,\n position,\n `Invalid character within String: ${printCodePointAt(\n lexer,\n position,\n )}.`,\n );\n }\n }\n\n throw syntaxError(lexer.source, position, 'Unterminated string.');\n}\n/**\n * Reads an alphanumeric + underscore name from the source.\n *\n * ```\n * Name ::\n * - NameStart NameContinue* [lookahead != NameContinue]\n * ```\n *\n * @internal\n */\n\nexport function readName(lexer, start) {\n const body = lexer.source.body;\n const bodyLength = body.length;\n let position = start + 1;\n\n while (position < bodyLength) {\n const code = body.charCodeAt(position);\n\n if (isNameContinue(code)) {\n ++position;\n } else {\n break;\n }\n }\n\n return createToken(\n lexer,\n TokenKind.NAME,\n start,\n position,\n body.slice(start, position),\n );\n}\n","const MAX_ARRAY_LENGTH = 10;\nconst MAX_RECURSIVE_DEPTH = 2;\n/**\n * Used to print values in error messages.\n *\n * @internal\n */\n\nexport function inspect(value) {\n return formatValue(value, []);\n}\n\nfunction formatValue(value, seenValues) {\n switch (typeof value) {\n case 'string':\n return JSON.stringify(value);\n\n case 'function':\n return value.name ? `[function ${value.name}]` : '[function]';\n\n case 'object':\n return formatObjectValue(value, seenValues);\n\n default:\n return String(value);\n }\n}\n\nfunction formatObjectValue(value, previouslySeenValues) {\n if (value === null) {\n return 'null';\n }\n\n if (previouslySeenValues.includes(value)) {\n return '[Circular]';\n }\n\n const seenValues = [...previouslySeenValues, value];\n\n if (isJSONable(value)) {\n const jsonValue = value.toJSON(); // check for infinite recursion\n\n if (jsonValue !== value) {\n return typeof jsonValue === 'string'\n ? jsonValue\n : formatValue(jsonValue, seenValues);\n }\n } else if (Array.isArray(value)) {\n return formatArray(value, seenValues);\n }\n\n return formatObject(value, seenValues);\n}\n\nfunction isJSONable(value) {\n return typeof value.toJSON === 'function';\n}\n\nfunction formatObject(object, seenValues) {\n const entries = Object.entries(object);\n\n if (entries.length === 0) {\n return '{}';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[' + getObjectTag(object) + ']';\n }\n\n const properties = entries.map(\n ([key, value]) => key + ': ' + formatValue(value, seenValues),\n );\n return '{ ' + properties.join(', ') + ' }';\n}\n\nfunction formatArray(array, seenValues) {\n if (array.length === 0) {\n return '[]';\n }\n\n if (seenValues.length > MAX_RECURSIVE_DEPTH) {\n return '[Array]';\n }\n\n const len = Math.min(MAX_ARRAY_LENGTH, array.length);\n const remaining = array.length - len;\n const items = [];\n\n for (let i = 0; i < len; ++i) {\n items.push(formatValue(array[i], seenValues));\n }\n\n if (remaining === 1) {\n items.push('... 1 more item');\n } else if (remaining > 1) {\n items.push(`... ${remaining} more items`);\n }\n\n return '[' + items.join(', ') + ']';\n}\n\nfunction getObjectTag(object) {\n const tag = Object.prototype.toString\n .call(object)\n .replace(/^\\[object /, '')\n .replace(/]$/, '');\n\n if (tag === 'Object' && typeof object.constructor === 'function') {\n const name = object.constructor.name;\n\n if (typeof name === 'string' && name !== '') {\n return name;\n }\n }\n\n return tag;\n}\n","import { inspect } from './inspect.mjs';\n/* c8 ignore next 3 */\n\nconst isProduction =\n globalThis.process && // eslint-disable-next-line no-undef\n process.env.NODE_ENV === 'production';\n/**\n * A replacement for instanceof which includes an error warning when multi-realm\n * constructors are detected.\n * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production\n * See: https://webpack.js.org/guides/production/\n *\n * @internal\n */\n\nexport const instanceOf =\n /* c8 ignore next 6 */\n // FIXME: https://github.com/graphql/graphql-js/issues/2317\n isProduction\n ? function instanceOf(value, constructor) {\n return value instanceof constructor;\n }\n : function instanceOf(value, constructor) {\n if (value instanceof constructor) {\n return true;\n }\n\n if (typeof value === 'object' && value !== null) {\n var _value$constructor;\n\n // Prefer Symbol.toStringTag since it is immune to minification.\n const className = constructor.prototype[Symbol.toStringTag];\n const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library.\n Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009\n ? value[Symbol.toStringTag]\n : (_value$constructor = value.constructor) === null ||\n _value$constructor === void 0\n ? void 0\n : _value$constructor.name;\n\n if (className === valueClassName) {\n const stringifiedValue = inspect(value);\n throw new Error(`Cannot use ${className} \"${stringifiedValue}\" from another module or realm.\n\nEnsure that there is only one instance of \"graphql\" in the node_modules\ndirectory. If different versions of \"graphql\" are the dependencies of other\nrelied on modules, use \"resolutions\" to ensure only one version is installed.\n\nhttps://yarnpkg.com/en/docs/selective-version-resolutions\n\nDuplicate \"graphql\" modules cannot be used at the same time since different\nversions may have different capabilities and behavior. The data from one\nversion used in the function from another could produce confusing and\nspurious results.`);\n }\n }\n\n return false;\n };\n","/** @category Source */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\n\n/**\n * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are\n * optional, but they are useful for clients who store GraphQL documents in source files.\n * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might\n * be useful for `name` to be `\"Foo.graphql\"` and location to be `{ line: 40, column: 1 }`.\n * The `line` and `column` properties in `locationOffset` are 1-indexed.\n */\nexport class Source {\n /** The GraphQL source text. */\n\n /** Name used in diagnostics for this source, such as a file path or request name. */\n\n /** One-indexed line and column where this source begins. */\n\n /**\n * Creates a Source instance.\n * @param body - The GraphQL source text.\n * @param name - Name used in diagnostics for this source.\n * @param locationOffset - One-indexed line and column where this source begins.\n * @example\n * ```ts\n * import { Source } from 'graphql/language';\n *\n * const source = new Source(\n * 'type Query { greeting: String }',\n * 'schema.graphql',\n * { line: 10, column: 1 },\n * );\n *\n * source.body; // => 'type Query { greeting: String }'\n * source.name; // => 'schema.graphql'\n * source.locationOffset; // => { line: 10, column: 1 }\n * ```\n */\n constructor(\n body,\n name = 'GraphQL request',\n locationOffset = {\n line: 1,\n column: 1,\n },\n ) {\n typeof body === 'string' ||\n devAssert(false, `Body must be a string. Received: ${inspect(body)}.`);\n this.body = body;\n this.name = name;\n this.locationOffset = locationOffset;\n this.locationOffset.line > 0 ||\n devAssert(\n false,\n 'line in locationOffset is 1-indexed and must be positive.',\n );\n this.locationOffset.column > 0 ||\n devAssert(\n false,\n 'column in locationOffset is 1-indexed and must be positive.',\n );\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'Source';\n }\n}\n/**\n * Test if the given value is a Source object.\n *\n * @internal\n */\n\nexport function isSource(source) {\n return instanceOf(source, Source);\n}\n","/** @category Parsing */\nimport { syntaxError } from '../error/syntaxError.mjs';\nimport { Location, OperationTypeNode } from './ast.mjs';\nimport { DirectiveLocation } from './directiveLocation.mjs';\nimport { Kind } from './kinds.mjs';\nimport { isPunctuatorTokenKind, Lexer } from './lexer.mjs';\nimport { SchemaCoordinateLexer } from './schemaCoordinateLexer.mjs';\nimport { isSource, Source } from './source.mjs';\nimport { TokenKind } from './tokenKind.mjs';\n/** Configuration options to control parser behavior */\n\n/**\n * Given a GraphQL source, parses it into a Document.\n * Throws GraphQLError if a syntax error is encountered.\n * @param source - A GraphQL source string or source object.\n * @param options - Optional parser configuration.\n * @returns The parsed GraphQL document AST.\n * @example\n * ```ts\n * // Parse a GraphQL document with the default parser options.\n * import { parse } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n *\n * document.kind; // => 'Document'\n * ```\n * @example\n * ```ts\n * // This variant enables parser options and provides an explicit lexer.\n * import { Lexer, Source, parse } from 'graphql/language';\n *\n * const document = parse('fragment A($var: Boolean) on Query { field }', {\n * allowLegacyFragmentVariables: true,\n * maxTokens: 20,\n * noLocation: true,\n * });\n * const directiveDocument = parse('directive @foo @bar on FIELD', {\n * experimentalDirectivesOnDirectiveDefinitions: true,\n * });\n * const source = new Source('{ hero }');\n * const lexerDocument = parse(source, { lexer: new Lexer(source) });\n *\n * document.definitions[0].kind; // => 'FragmentDefinition'\n * document.loc; // => undefined\n * directiveDocument.definitions[0].kind; // => 'DirectiveDefinition'\n * lexerDocument.definitions[0].kind; // => 'OperationDefinition'\n * ```\n */\nexport function parse(source, options) {\n const parser = new Parser(source, options);\n const document = parser.parseDocument();\n Object.defineProperty(document, 'tokenCount', {\n enumerable: false,\n value: parser.tokenCount,\n });\n return document;\n}\n/**\n * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for\n * that value.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Values directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: valueFromAST().\n * @param source - A GraphQL source string or source object containing a value.\n * @param options - Optional parser configuration.\n * @returns The parsed GraphQL value AST.\n * @example\n * ```ts\n * import { parseValue } from 'graphql/language';\n *\n * const value = parseValue('[42]');\n *\n * value.kind; // => 'ListValue'\n * ```\n */\n\nexport function parseValue(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const value = parser.parseValueLiteral(false);\n parser.expectToken(TokenKind.EOF);\n return value;\n}\n/**\n * Similar to parseValue(), but raises a parse error if it encounters a\n * variable. The return type will be a constant value.\n * @param source - A GraphQL source string or source object containing a constant value.\n * @param options - Optional parser configuration.\n * @returns The parsed GraphQL constant value AST.\n * @example\n * ```ts\n * import { parseConstValue } from 'graphql/language';\n *\n * const value = parseConstValue('{ enabled: true }');\n *\n * value.kind; // => 'ObjectValue'\n * parseConstValue('$variable'); // throws an error\n * ```\n */\n\nexport function parseConstValue(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const value = parser.parseConstValueLiteral();\n parser.expectToken(TokenKind.EOF);\n return value;\n}\n/**\n * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for\n * that type.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * This is useful within tools that operate upon GraphQL Types directly and\n * in isolation of complete GraphQL documents.\n *\n * Consider providing the results to the utility function: typeFromAST().\n * @param source - A GraphQL source string or source object containing a type reference.\n * @param options - Optional parser configuration.\n * @returns The parsed GraphQL type AST.\n * @example\n * ```ts\n * import { parseType } from 'graphql/language';\n *\n * const type = parseType('[String!]');\n *\n * type.kind; // => 'ListType'\n * ```\n */\n\nexport function parseType(source, options) {\n const parser = new Parser(source, options);\n parser.expectToken(TokenKind.SOF);\n const type = parser.parseTypeReference();\n parser.expectToken(TokenKind.EOF);\n return type;\n}\n/**\n * Given a string containing a GraphQL Schema Coordinate (ex. `Type.field`),\n * parse the AST for that schema coordinate.\n * Throws GraphQLError if a syntax error is encountered.\n *\n * Consider providing the results to the utility function:\n * resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly\n * with an unparsed source.\n * @param source - A GraphQL source string or source object containing a schema coordinate.\n * @returns The parsed GraphQL schema coordinate AST.\n * @example\n * ```ts\n * import { parseSchemaCoordinate } from 'graphql/language';\n *\n * const coordinate = parseSchemaCoordinate('Query.hero');\n *\n * coordinate.kind; // => 'MemberCoordinate'\n * ```\n */\n\nexport function parseSchemaCoordinate(source) {\n const sourceObj = isSource(source) ? source : new Source(source);\n const lexer = new SchemaCoordinateLexer(sourceObj);\n const parser = new Parser(source, {\n lexer,\n });\n parser.expectToken(TokenKind.SOF);\n const coordinate = parser.parseSchemaCoordinate();\n parser.expectToken(TokenKind.EOF);\n return coordinate;\n}\n/**\n * This class is exported only to assist people in implementing their own parsers\n * without duplicating too much code and should be used only as last resort for cases\n * such as experimental syntax or if certain features could not be contributed upstream.\n *\n * It is still part of the internal API and is versioned, so any changes to it are never\n * considered breaking changes. If you still need to support multiple versions of the\n * library, please use the `versionInfo` variable for version detection.\n *\n * @internal\n */\n\nexport class Parser {\n constructor(source, options = {}) {\n const { lexer, ..._options } = options;\n\n if (lexer) {\n this._lexer = lexer;\n } else {\n const sourceObj = isSource(source) ? source : new Source(source);\n this._lexer = new Lexer(sourceObj);\n }\n\n this._options = _options;\n this._tokenCounter = 0;\n }\n\n get tokenCount() {\n return this._tokenCounter;\n }\n /**\n * Converts a name lex token into a name parse node.\n *\n * @internal\n */\n\n parseName() {\n const token = this.expectToken(TokenKind.NAME);\n return this.node(token, {\n kind: Kind.NAME,\n value: token.value,\n });\n } // Implements the parsing rules in the Document section.\n\n /**\n * Document : Definition+\n *\n * @internal\n */\n\n parseDocument() {\n return this.node(this._lexer.token, {\n kind: Kind.DOCUMENT,\n definitions: this.many(\n TokenKind.SOF,\n this.parseDefinition,\n TokenKind.EOF,\n ),\n });\n }\n /**\n * Definition :\n * - ExecutableDefinition\n * - TypeSystemDefinition\n * - TypeSystemExtension\n *\n * ExecutableDefinition :\n * - OperationDefinition\n * - FragmentDefinition\n *\n * TypeSystemDefinition :\n * - SchemaDefinition\n * - TypeDefinition\n * - DirectiveDefinition\n *\n * TypeDefinition :\n * - ScalarTypeDefinition\n * - ObjectTypeDefinition\n * - InterfaceTypeDefinition\n * - UnionTypeDefinition\n * - EnumTypeDefinition\n * - InputObjectTypeDefinition\n *\n * @internal\n */\n\n parseDefinition() {\n if (this.peek(TokenKind.BRACE_L)) {\n return this.parseOperationDefinition();\n } // Many definitions begin with a description and require a lookahead.\n\n const hasDescription = this.peekDescription();\n const keywordToken = hasDescription\n ? this._lexer.lookahead()\n : this._lexer.token;\n\n if (hasDescription && keywordToken.kind === TokenKind.BRACE_L) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n 'Unexpected description, descriptions are not supported on shorthand queries.',\n );\n }\n\n if (keywordToken.kind === TokenKind.NAME) {\n switch (keywordToken.value) {\n case 'schema':\n return this.parseSchemaDefinition();\n\n case 'scalar':\n return this.parseScalarTypeDefinition();\n\n case 'type':\n return this.parseObjectTypeDefinition();\n\n case 'interface':\n return this.parseInterfaceTypeDefinition();\n\n case 'union':\n return this.parseUnionTypeDefinition();\n\n case 'enum':\n return this.parseEnumTypeDefinition();\n\n case 'input':\n return this.parseInputObjectTypeDefinition();\n\n case 'directive':\n return this.parseDirectiveDefinition();\n }\n\n switch (keywordToken.value) {\n case 'query':\n case 'mutation':\n case 'subscription':\n return this.parseOperationDefinition();\n\n case 'fragment':\n return this.parseFragmentDefinition();\n }\n\n if (hasDescription) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n 'Unexpected description, only GraphQL definitions support descriptions.',\n );\n }\n\n switch (keywordToken.value) {\n case 'extend':\n return this.parseTypeSystemExtension();\n }\n }\n\n throw this.unexpected(keywordToken);\n } // Implements the parsing rules in the Operations section.\n\n /**\n * OperationDefinition :\n * - SelectionSet\n * - OperationType Name? VariableDefinitions? Directives? SelectionSet\n *\n * @internal\n */\n\n parseOperationDefinition() {\n const start = this._lexer.token;\n\n if (this.peek(TokenKind.BRACE_L)) {\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation: OperationTypeNode.QUERY,\n description: undefined,\n name: undefined,\n variableDefinitions: [],\n directives: [],\n selectionSet: this.parseSelectionSet(),\n });\n }\n\n const description = this.parseDescription();\n const operation = this.parseOperationType();\n let name;\n\n if (this.peek(TokenKind.NAME)) {\n name = this.parseName();\n }\n\n return this.node(start, {\n kind: Kind.OPERATION_DEFINITION,\n operation,\n description,\n name,\n variableDefinitions: this.parseVariableDefinitions(),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * OperationType : one of query mutation subscription\n *\n * @internal\n */\n\n parseOperationType() {\n const operationToken = this.expectToken(TokenKind.NAME);\n\n switch (operationToken.value) {\n case 'query':\n return OperationTypeNode.QUERY;\n\n case 'mutation':\n return OperationTypeNode.MUTATION;\n\n case 'subscription':\n return OperationTypeNode.SUBSCRIPTION;\n }\n\n throw this.unexpected(operationToken);\n }\n /**\n * VariableDefinitions : ( VariableDefinition+ )\n *\n * @internal\n */\n\n parseVariableDefinitions() {\n return this.optionalMany(\n TokenKind.PAREN_L,\n this.parseVariableDefinition,\n TokenKind.PAREN_R,\n );\n }\n /**\n * VariableDefinition : Variable : Type DefaultValue? Directives[Const]?\n *\n * @internal\n */\n\n parseVariableDefinition() {\n return this.node(this._lexer.token, {\n kind: Kind.VARIABLE_DEFINITION,\n description: this.parseDescription(),\n variable: this.parseVariable(),\n type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()),\n defaultValue: this.expectOptionalToken(TokenKind.EQUALS)\n ? this.parseConstValueLiteral()\n : undefined,\n directives: this.parseConstDirectives(),\n });\n }\n /**\n * Variable : $ Name\n *\n * @internal\n */\n\n parseVariable() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.DOLLAR);\n return this.node(start, {\n kind: Kind.VARIABLE,\n name: this.parseName(),\n });\n }\n /**\n * ```\n * SelectionSet : { Selection+ }\n * ```\n *\n * @internal\n */\n\n parseSelectionSet() {\n return this.node(this._lexer.token, {\n kind: Kind.SELECTION_SET,\n selections: this.many(\n TokenKind.BRACE_L,\n this.parseSelection,\n TokenKind.BRACE_R,\n ),\n });\n }\n /**\n * Selection :\n * - Field\n * - FragmentSpread\n * - InlineFragment\n *\n * @internal\n */\n\n parseSelection() {\n return this.peek(TokenKind.SPREAD)\n ? this.parseFragment()\n : this.parseField();\n }\n /**\n * Field : Alias? Name Arguments? Directives? SelectionSet?\n *\n * Alias : Name :\n *\n * @internal\n */\n\n parseField() {\n const start = this._lexer.token;\n const nameOrAlias = this.parseName();\n let alias;\n let name;\n\n if (this.expectOptionalToken(TokenKind.COLON)) {\n alias = nameOrAlias;\n name = this.parseName();\n } else {\n name = nameOrAlias;\n }\n\n return this.node(start, {\n kind: Kind.FIELD,\n alias,\n name,\n arguments: this.parseArguments(false),\n directives: this.parseDirectives(false),\n selectionSet: this.peek(TokenKind.BRACE_L)\n ? this.parseSelectionSet()\n : undefined,\n });\n }\n /**\n * Arguments[Const] : ( Argument[?Const]+ )\n *\n * @internal\n */\n\n parseArguments(isConst) {\n const item = isConst ? this.parseConstArgument : this.parseArgument;\n return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R);\n }\n /**\n * Argument[Const] : Name : Value[?Const]\n *\n * @internal\n */\n\n parseArgument(isConst = false) {\n const start = this._lexer.token;\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n return this.node(start, {\n kind: Kind.ARGUMENT,\n name,\n value: this.parseValueLiteral(isConst),\n });\n }\n\n parseConstArgument() {\n return this.parseArgument(true);\n } // Implements the parsing rules in the Fragments section.\n\n /**\n * Corresponds to both FragmentSpread and InlineFragment in the spec.\n *\n * FragmentSpread : ... FragmentName Directives?\n *\n * InlineFragment : ... TypeCondition? Directives? SelectionSet\n *\n * @internal\n */\n\n parseFragment() {\n const start = this._lexer.token;\n this.expectToken(TokenKind.SPREAD);\n const hasTypeCondition = this.expectOptionalKeyword('on');\n\n if (!hasTypeCondition && this.peek(TokenKind.NAME)) {\n return this.node(start, {\n kind: Kind.FRAGMENT_SPREAD,\n name: this.parseFragmentName(),\n directives: this.parseDirectives(false),\n });\n }\n\n return this.node(start, {\n kind: Kind.INLINE_FRAGMENT,\n typeCondition: hasTypeCondition ? this.parseNamedType() : undefined,\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * FragmentDefinition :\n * - fragment FragmentName on TypeCondition Directives? SelectionSet\n *\n * TypeCondition : NamedType\n *\n * @internal\n */\n\n parseFragmentDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes\n // the grammar of FragmentDefinition:\n // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet\n\n if (this._options.allowLegacyFragmentVariables === true) {\n return this.node(start, {\n kind: Kind.FRAGMENT_DEFINITION,\n description,\n name: this.parseFragmentName(),\n variableDefinitions: this.parseVariableDefinitions(),\n typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n\n return this.node(start, {\n kind: Kind.FRAGMENT_DEFINITION,\n description,\n name: this.parseFragmentName(),\n typeCondition: (this.expectKeyword('on'), this.parseNamedType()),\n directives: this.parseDirectives(false),\n selectionSet: this.parseSelectionSet(),\n });\n }\n /**\n * FragmentName : Name but not `on`\n *\n * @internal\n */\n\n parseFragmentName() {\n if (this._lexer.token.value === 'on') {\n throw this.unexpected();\n }\n\n return this.parseName();\n } // Implements the parsing rules in the Values section.\n\n /**\n * Value[Const] :\n * - [~Const] Variable\n * - IntValue\n * - FloatValue\n * - StringValue\n * - BooleanValue\n * - NullValue\n * - EnumValue\n * - ListValue[?Const]\n * - ObjectValue[?Const]\n *\n * BooleanValue : one of `true` `false`\n *\n * NullValue : `null`\n *\n * EnumValue : Name but not `true`, `false` or `null`\n *\n * @internal\n */\n\n parseValueLiteral(isConst) {\n const token = this._lexer.token;\n\n switch (token.kind) {\n case TokenKind.BRACKET_L:\n return this.parseList(isConst);\n\n case TokenKind.BRACE_L:\n return this.parseObject(isConst);\n\n case TokenKind.INT:\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.INT,\n value: token.value,\n });\n\n case TokenKind.FLOAT:\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.FLOAT,\n value: token.value,\n });\n\n case TokenKind.STRING:\n case TokenKind.BLOCK_STRING:\n return this.parseStringLiteral();\n\n case TokenKind.NAME:\n this.advanceLexer();\n\n switch (token.value) {\n case 'true':\n return this.node(token, {\n kind: Kind.BOOLEAN,\n value: true,\n });\n\n case 'false':\n return this.node(token, {\n kind: Kind.BOOLEAN,\n value: false,\n });\n\n case 'null':\n return this.node(token, {\n kind: Kind.NULL,\n });\n\n default:\n return this.node(token, {\n kind: Kind.ENUM,\n value: token.value,\n });\n }\n\n case TokenKind.DOLLAR:\n if (isConst) {\n this.expectToken(TokenKind.DOLLAR);\n\n if (this._lexer.token.kind === TokenKind.NAME) {\n const varName = this._lexer.token.value;\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Unexpected variable \"$${varName}\" in constant value.`,\n );\n } else {\n throw this.unexpected(token);\n }\n }\n\n return this.parseVariable();\n\n default:\n throw this.unexpected();\n }\n }\n\n parseConstValueLiteral() {\n return this.parseValueLiteral(true);\n }\n\n parseStringLiteral() {\n const token = this._lexer.token;\n this.advanceLexer();\n return this.node(token, {\n kind: Kind.STRING,\n value: token.value,\n block: token.kind === TokenKind.BLOCK_STRING,\n });\n }\n /**\n * ListValue[Const] :\n * - [ ]\n * - [ Value[?Const]+ ]\n *\n * @internal\n */\n\n parseList(isConst) {\n const item = () => this.parseValueLiteral(isConst);\n\n return this.node(this._lexer.token, {\n kind: Kind.LIST,\n values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R),\n });\n }\n /**\n * ```\n * ObjectValue[Const] :\n * - { }\n * - { ObjectField[?Const]+ }\n * ```\n *\n * @internal\n */\n\n parseObject(isConst) {\n const item = () => this.parseObjectField(isConst);\n\n return this.node(this._lexer.token, {\n kind: Kind.OBJECT,\n fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R),\n });\n }\n /**\n * ObjectField[Const] : Name : Value[?Const]\n *\n * @internal\n */\n\n parseObjectField(isConst) {\n const start = this._lexer.token;\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n return this.node(start, {\n kind: Kind.OBJECT_FIELD,\n name,\n value: this.parseValueLiteral(isConst),\n });\n } // Implements the parsing rules in the Directives section.\n\n /**\n * Directives[Const] : Directive[?Const]+\n *\n * @internal\n */\n\n parseDirectives(isConst) {\n const directives = [];\n\n while (this.peek(TokenKind.AT)) {\n directives.push(this.parseDirective(isConst));\n }\n\n return directives;\n }\n\n parseConstDirectives() {\n return this.parseDirectives(true);\n }\n /**\n * ```\n * Directive[Const] : @ Name Arguments[?Const]?\n * ```\n *\n * @internal\n */\n\n parseDirective(isConst) {\n const start = this._lexer.token;\n this.expectToken(TokenKind.AT);\n return this.node(start, {\n kind: Kind.DIRECTIVE,\n name: this.parseName(),\n arguments: this.parseArguments(isConst),\n });\n } // Implements the parsing rules in the Types section.\n\n /**\n * Type :\n * - NamedType\n * - ListType\n * - NonNullType\n *\n * @internal\n */\n\n parseTypeReference() {\n const start = this._lexer.token;\n let type;\n\n if (this.expectOptionalToken(TokenKind.BRACKET_L)) {\n const innerType = this.parseTypeReference();\n this.expectToken(TokenKind.BRACKET_R);\n type = this.node(start, {\n kind: Kind.LIST_TYPE,\n type: innerType,\n });\n } else {\n type = this.parseNamedType();\n }\n\n if (this.expectOptionalToken(TokenKind.BANG)) {\n return this.node(start, {\n kind: Kind.NON_NULL_TYPE,\n type,\n });\n }\n\n return type;\n }\n /**\n * NamedType : Name\n *\n * @internal\n */\n\n parseNamedType() {\n return this.node(this._lexer.token, {\n kind: Kind.NAMED_TYPE,\n name: this.parseName(),\n });\n } // Implements the parsing rules in the Type Definition section.\n\n peekDescription() {\n return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING);\n }\n /**\n * Description : StringValue\n *\n * @internal\n */\n\n parseDescription() {\n if (this.peekDescription()) {\n return this.parseStringLiteral();\n }\n }\n /**\n * ```\n * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ }\n * ```\n *\n * @internal\n */\n\n parseSchemaDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('schema');\n const directives = this.parseConstDirectives();\n const operationTypes = this.many(\n TokenKind.BRACE_L,\n this.parseOperationTypeDefinition,\n TokenKind.BRACE_R,\n );\n return this.node(start, {\n kind: Kind.SCHEMA_DEFINITION,\n description,\n directives,\n operationTypes,\n });\n }\n /**\n * OperationTypeDefinition : OperationType : NamedType\n *\n * @internal\n */\n\n parseOperationTypeDefinition() {\n const start = this._lexer.token;\n const operation = this.parseOperationType();\n this.expectToken(TokenKind.COLON);\n const type = this.parseNamedType();\n return this.node(start, {\n kind: Kind.OPERATION_TYPE_DEFINITION,\n operation,\n type,\n });\n }\n /**\n * ScalarTypeDefinition : Description? scalar Name Directives[Const]?\n *\n * @internal\n */\n\n parseScalarTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('scalar');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.SCALAR_TYPE_DEFINITION,\n description,\n name,\n directives,\n });\n }\n /**\n * ObjectTypeDefinition :\n * Description?\n * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition?\n *\n * @internal\n */\n\n parseObjectTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_DEFINITION,\n description,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * ImplementsInterfaces :\n * - implements `&`? NamedType\n * - ImplementsInterfaces & NamedType\n *\n * @internal\n */\n\n parseImplementsInterfaces() {\n return this.expectOptionalKeyword('implements')\n ? this.delimitedMany(TokenKind.AMP, this.parseNamedType)\n : [];\n }\n /**\n * ```\n * FieldsDefinition : { FieldDefinition+ }\n * ```\n *\n * @internal\n */\n\n parseFieldsDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseFieldDefinition,\n TokenKind.BRACE_R,\n );\n }\n /**\n * FieldDefinition :\n * - Description? Name ArgumentsDefinition? : Type Directives[Const]?\n *\n * @internal\n */\n\n parseFieldDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseName();\n const args = this.parseArgumentDefs();\n this.expectToken(TokenKind.COLON);\n const type = this.parseTypeReference();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.FIELD_DEFINITION,\n description,\n name,\n arguments: args,\n type,\n directives,\n });\n }\n /**\n * ArgumentsDefinition : ( InputValueDefinition+ )\n *\n * @internal\n */\n\n parseArgumentDefs() {\n return this.optionalMany(\n TokenKind.PAREN_L,\n this.parseInputValueDef,\n TokenKind.PAREN_R,\n );\n }\n /**\n * InputValueDefinition :\n * - Description? Name : Type DefaultValue? Directives[Const]?\n *\n * @internal\n */\n\n parseInputValueDef() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseName();\n this.expectToken(TokenKind.COLON);\n const type = this.parseTypeReference();\n let defaultValue;\n\n if (this.expectOptionalToken(TokenKind.EQUALS)) {\n defaultValue = this.parseConstValueLiteral();\n }\n\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.INPUT_VALUE_DEFINITION,\n description,\n name,\n type,\n defaultValue,\n directives,\n });\n }\n /**\n * InterfaceTypeDefinition :\n * - Description? interface Name Directives[Const]? FieldsDefinition?\n *\n * @internal\n */\n\n parseInterfaceTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_DEFINITION,\n description,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * UnionTypeDefinition :\n * - Description? union Name Directives[Const]? UnionMemberTypes?\n *\n * @internal\n */\n\n parseUnionTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('union');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const types = this.parseUnionMemberTypes();\n return this.node(start, {\n kind: Kind.UNION_TYPE_DEFINITION,\n description,\n name,\n directives,\n types,\n });\n }\n /**\n * UnionMemberTypes :\n * - = `|`? NamedType\n * - UnionMemberTypes | NamedType\n *\n * @internal\n */\n\n parseUnionMemberTypes() {\n return this.expectOptionalToken(TokenKind.EQUALS)\n ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType)\n : [];\n }\n /**\n * EnumTypeDefinition :\n * - Description? enum Name Directives[Const]? EnumValuesDefinition?\n *\n * @internal\n */\n\n parseEnumTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('enum');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const values = this.parseEnumValuesDefinition();\n return this.node(start, {\n kind: Kind.ENUM_TYPE_DEFINITION,\n description,\n name,\n directives,\n values,\n });\n }\n /**\n * ```\n * EnumValuesDefinition : { EnumValueDefinition+ }\n * ```\n *\n * @internal\n */\n\n parseEnumValuesDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseEnumValueDefinition,\n TokenKind.BRACE_R,\n );\n }\n /**\n * EnumValueDefinition : Description? EnumValue Directives[Const]?\n *\n * @internal\n */\n\n parseEnumValueDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n const name = this.parseEnumValueName();\n const directives = this.parseConstDirectives();\n return this.node(start, {\n kind: Kind.ENUM_VALUE_DEFINITION,\n description,\n name,\n directives,\n });\n }\n /**\n * EnumValue : Name but not `true`, `false` or `null`\n *\n * @internal\n */\n\n parseEnumValueName() {\n if (\n this._lexer.token.value === 'true' ||\n this._lexer.token.value === 'false' ||\n this._lexer.token.value === 'null'\n ) {\n throw syntaxError(\n this._lexer.source,\n this._lexer.token.start,\n `${getTokenDesc(\n this._lexer.token,\n )} is reserved and cannot be used for an enum value.`,\n );\n }\n\n return this.parseName();\n }\n /**\n * InputObjectTypeDefinition :\n * - Description? input Name Directives[Const]? InputFieldsDefinition?\n *\n * @internal\n */\n\n parseInputObjectTypeDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,\n description,\n name,\n directives,\n fields,\n });\n }\n /**\n * ```\n * InputFieldsDefinition : { InputValueDefinition+ }\n * ```\n *\n * @internal\n */\n\n parseInputFieldsDefinition() {\n return this.optionalMany(\n TokenKind.BRACE_L,\n this.parseInputValueDef,\n TokenKind.BRACE_R,\n );\n }\n /**\n * TypeSystemExtension :\n * - SchemaExtension\n * - TypeExtension\n *\n * TypeExtension :\n * - ScalarTypeExtension\n * - ObjectTypeExtension\n * - InterfaceTypeExtension\n * - UnionTypeExtension\n * - EnumTypeExtension\n * - InputObjectTypeDefinition\n * - DirectiveDefinitionExtension\n *\n * @internal\n */\n\n parseTypeSystemExtension() {\n const keywordToken = this._lexer.lookahead();\n\n if (keywordToken.kind === TokenKind.NAME) {\n switch (keywordToken.value) {\n case 'schema':\n return this.parseSchemaExtension();\n\n case 'scalar':\n return this.parseScalarTypeExtension();\n\n case 'type':\n return this.parseObjectTypeExtension();\n\n case 'interface':\n return this.parseInterfaceTypeExtension();\n\n case 'union':\n return this.parseUnionTypeExtension();\n\n case 'enum':\n return this.parseEnumTypeExtension();\n\n case 'input':\n return this.parseInputObjectTypeExtension();\n\n case 'directive':\n if (this._options.experimentalDirectivesOnDirectiveDefinitions) {\n return this.parseDirectiveDefinitionExtension();\n }\n\n break;\n }\n }\n\n throw this.unexpected(keywordToken);\n }\n /**\n * ```\n * SchemaExtension :\n * - extend schema Directives[Const]? { OperationTypeDefinition+ }\n * - extend schema Directives[Const]\n * ```\n *\n * @internal\n */\n\n parseSchemaExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('schema');\n const directives = this.parseConstDirectives();\n const operationTypes = this.optionalMany(\n TokenKind.BRACE_L,\n this.parseOperationTypeDefinition,\n TokenKind.BRACE_R,\n );\n\n if (directives.length === 0 && operationTypes.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.SCHEMA_EXTENSION,\n directives,\n operationTypes,\n });\n }\n /**\n * ScalarTypeExtension :\n * - extend scalar Name Directives[Const]\n *\n * @internal\n */\n\n parseScalarTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('scalar');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n\n if (directives.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.SCALAR_TYPE_EXTENSION,\n name,\n directives,\n });\n }\n /**\n * ObjectTypeExtension :\n * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n * - extend type Name ImplementsInterfaces? Directives[Const]\n * - extend type Name ImplementsInterfaces\n *\n * @internal\n */\n\n parseObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('type');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.OBJECT_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * InterfaceTypeExtension :\n * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition\n * - extend interface Name ImplementsInterfaces? Directives[Const]\n * - extend interface Name ImplementsInterfaces\n *\n * @internal\n */\n\n parseInterfaceTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('interface');\n const name = this.parseName();\n const interfaces = this.parseImplementsInterfaces();\n const directives = this.parseConstDirectives();\n const fields = this.parseFieldsDefinition();\n\n if (\n interfaces.length === 0 &&\n directives.length === 0 &&\n fields.length === 0\n ) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INTERFACE_TYPE_EXTENSION,\n name,\n interfaces,\n directives,\n fields,\n });\n }\n /**\n * UnionTypeExtension :\n * - extend union Name Directives[Const]? UnionMemberTypes\n * - extend union Name Directives[Const]\n *\n * @internal\n */\n\n parseUnionTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('union');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const types = this.parseUnionMemberTypes();\n\n if (directives.length === 0 && types.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.UNION_TYPE_EXTENSION,\n name,\n directives,\n types,\n });\n }\n /**\n * EnumTypeExtension :\n * - extend enum Name Directives[Const]? EnumValuesDefinition\n * - extend enum Name Directives[Const]\n *\n * @internal\n */\n\n parseEnumTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('enum');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const values = this.parseEnumValuesDefinition();\n\n if (directives.length === 0 && values.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.ENUM_TYPE_EXTENSION,\n name,\n directives,\n values,\n });\n }\n /**\n * InputObjectTypeExtension :\n * - extend input Name Directives[Const]? InputFieldsDefinition\n * - extend input Name Directives[Const]\n *\n * @internal\n */\n\n parseInputObjectTypeExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('input');\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n const fields = this.parseInputFieldsDefinition();\n\n if (directives.length === 0 && fields.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n name,\n directives,\n fields,\n });\n }\n\n parseDirectiveDefinitionExtension() {\n const start = this._lexer.token;\n this.expectKeyword('extend');\n this.expectKeyword('directive');\n this.expectToken(TokenKind.AT);\n const name = this.parseName();\n const directives = this.parseConstDirectives();\n\n if (directives.length === 0) {\n throw this.unexpected();\n }\n\n return this.node(start, {\n kind: Kind.DIRECTIVE_EXTENSION,\n name,\n directives,\n });\n }\n /**\n * ```\n * DirectiveDefinition :\n * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations\n * ```\n *\n * @internal\n */\n\n parseDirectiveDefinition() {\n const start = this._lexer.token;\n const description = this.parseDescription();\n this.expectKeyword('directive');\n this.expectToken(TokenKind.AT);\n const name = this.parseName();\n const args = this.parseArgumentDefs();\n const directives = this._options\n .experimentalDirectivesOnDirectiveDefinitions\n ? this.parseConstDirectives()\n : [];\n const repeatable = this.expectOptionalKeyword('repeatable');\n this.expectKeyword('on');\n const locations = this.parseDirectiveLocations();\n return this.node(start, {\n kind: Kind.DIRECTIVE_DEFINITION,\n description,\n name,\n arguments: args,\n directives,\n repeatable,\n locations,\n });\n }\n /**\n * DirectiveLocations :\n * - `|`? DirectiveLocation\n * - DirectiveLocations | DirectiveLocation\n *\n * @internal\n */\n\n parseDirectiveLocations() {\n return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation);\n }\n /*\n * DirectiveLocation :\n * - ExecutableDirectiveLocation\n * - TypeSystemDirectiveLocation\n *\n * ExecutableDirectiveLocation : one of\n * `QUERY`\n * `MUTATION`\n * `SUBSCRIPTION`\n * `FIELD`\n * `FRAGMENT_DEFINITION`\n * `FRAGMENT_SPREAD`\n * `INLINE_FRAGMENT`\n *\n * TypeSystemDirectiveLocation : one of\n * `SCHEMA`\n * `SCALAR`\n * `OBJECT`\n * `FIELD_DEFINITION`\n * `ARGUMENT_DEFINITION`\n * `INTERFACE`\n * `UNION`\n * `ENUM`\n * `ENUM_VALUE`\n * `INPUT_OBJECT`\n * `INPUT_FIELD_DEFINITION`\n * `DIRECTIVE_DEFINITION`\n */\n\n parseDirectiveLocation() {\n const start = this._lexer.token;\n const name = this.parseName();\n\n if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) {\n return name;\n }\n\n throw this.unexpected(start);\n } // Schema Coordinates\n\n /**\n * SchemaCoordinate :\n * - Name\n * - Name . Name\n * - Name . Name ( Name : )\n * - \\@ Name\n * - \\@ Name ( Name : )\n * @returns Parsed schema coordinate AST.\n * @example\n * ```ts\n * import { Parser, Source } from 'graphql/language';\n *\n * const typeCoordinate = new Parser(new Source('User.name')).parseSchemaCoordinate();\n * const directiveCoordinate = new Parser(new Source('@include(if:)')).parseSchemaCoordinate();\n *\n * typeCoordinate.name.value; // => 'User'\n * typeCoordinate.memberName?.value; // => 'name'\n * directiveCoordinate.name.value; // => 'deprecated'\n * directiveCoordinate.argumentName?.value; // => 'reason'\n * ```\n */\n\n parseSchemaCoordinate() {\n const start = this._lexer.token;\n const ofDirective = this.expectOptionalToken(TokenKind.AT);\n const name = this.parseName();\n let memberName;\n\n if (!ofDirective && this.expectOptionalToken(TokenKind.DOT)) {\n memberName = this.parseName();\n }\n\n let argumentName;\n\n if (\n (ofDirective || memberName) &&\n this.expectOptionalToken(TokenKind.PAREN_L)\n ) {\n argumentName = this.parseName();\n this.expectToken(TokenKind.COLON);\n this.expectToken(TokenKind.PAREN_R);\n }\n\n if (ofDirective) {\n if (argumentName) {\n return this.node(start, {\n kind: Kind.DIRECTIVE_ARGUMENT_COORDINATE,\n name,\n argumentName,\n });\n }\n\n return this.node(start, {\n kind: Kind.DIRECTIVE_COORDINATE,\n name,\n });\n } else if (memberName) {\n if (argumentName) {\n return this.node(start, {\n kind: Kind.ARGUMENT_COORDINATE,\n name,\n fieldName: memberName,\n argumentName,\n });\n }\n\n return this.node(start, {\n kind: Kind.MEMBER_COORDINATE,\n name,\n memberName,\n });\n }\n\n return this.node(start, {\n kind: Kind.TYPE_COORDINATE,\n name,\n });\n } // Core parsing utility functions\n\n /**\n * Returns a node that, if configured to do so, sets a \"loc\" field as a\n * location object, used to identify the place in the source that created a\n * given parsed object.\n *\n * @internal\n */\n\n node(startToken, node) {\n if (this._options.noLocation !== true) {\n node.loc = new Location(\n startToken,\n this._lexer.lastToken,\n this._lexer.source,\n );\n }\n\n return node;\n }\n /**\n * Determines if the next token is of a given kind\n *\n * @internal\n */\n\n peek(kind) {\n return this._lexer.token.kind === kind;\n }\n /**\n * If the next token is of the given kind, return that token after advancing the lexer.\n * Otherwise, do not change the parser state and throw an error.\n *\n * @internal\n */\n\n expectToken(kind) {\n const token = this._lexer.token;\n\n if (token.kind === kind) {\n this.advanceLexer();\n return token;\n }\n\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`,\n );\n }\n /**\n * If the next token is of the given kind, return \"true\" after advancing the lexer.\n * Otherwise, do not change the parser state and return \"false\".\n *\n * @internal\n */\n\n expectOptionalToken(kind) {\n const token = this._lexer.token;\n\n if (token.kind === kind) {\n this.advanceLexer();\n return true;\n }\n\n return false;\n }\n /**\n * If the next token is a given keyword, advance the lexer.\n * Otherwise, do not change the parser state and throw an error.\n *\n * @internal\n */\n\n expectKeyword(value) {\n const token = this._lexer.token;\n\n if (token.kind === TokenKind.NAME && token.value === value) {\n this.advanceLexer();\n } else {\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Expected \"${value}\", found ${getTokenDesc(token)}.`,\n );\n }\n }\n /**\n * If the next token is a given keyword, return \"true\" after advancing the lexer.\n * Otherwise, do not change the parser state and return \"false\".\n *\n * @internal\n */\n\n expectOptionalKeyword(value) {\n const token = this._lexer.token;\n\n if (token.kind === TokenKind.NAME && token.value === value) {\n this.advanceLexer();\n return true;\n }\n\n return false;\n }\n /**\n * Helper function for creating an error when an unexpected lexed token is encountered.\n *\n * @internal\n */\n\n unexpected(atToken) {\n const token =\n atToken !== null && atToken !== void 0 ? atToken : this._lexer.token;\n return syntaxError(\n this._lexer.source,\n token.start,\n `Unexpected ${getTokenDesc(token)}.`,\n );\n }\n /**\n * Returns a possibly empty list of parse nodes, determined by the parseFn.\n * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n *\n * @internal\n */\n\n any(openKind, parseFn, closeKind) {\n this.expectToken(openKind);\n const nodes = [];\n\n while (!this.expectOptionalToken(closeKind)) {\n nodes.push(parseFn.call(this));\n }\n\n return nodes;\n }\n /**\n * Returns a list of parse nodes, determined by the parseFn.\n * It can be empty only if open token is missing otherwise it will always return non-empty list\n * that begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n *\n * @internal\n */\n\n optionalMany(openKind, parseFn, closeKind) {\n if (this.expectOptionalToken(openKind)) {\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (!this.expectOptionalToken(closeKind));\n\n return nodes;\n }\n\n return [];\n }\n /**\n * Returns a non-empty list of parse nodes, determined by the parseFn.\n * This list begins with a lex token of openKind and ends with a lex token of closeKind.\n * Advances the parser to the next lex token after the closing token.\n *\n * @internal\n */\n\n many(openKind, parseFn, closeKind) {\n this.expectToken(openKind);\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (!this.expectOptionalToken(closeKind));\n\n return nodes;\n }\n /**\n * Returns a non-empty list of parse nodes, determined by the parseFn.\n * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind.\n * Advances the parser to the next lex token after last item in the list.\n *\n * @internal\n */\n\n delimitedMany(delimiterKind, parseFn) {\n this.expectOptionalToken(delimiterKind);\n const nodes = [];\n\n do {\n nodes.push(parseFn.call(this));\n } while (this.expectOptionalToken(delimiterKind));\n\n return nodes;\n }\n\n advanceLexer() {\n const { maxTokens } = this._options;\n\n const token = this._lexer.advance();\n\n if (token.kind !== TokenKind.EOF) {\n ++this._tokenCounter;\n\n if (maxTokens !== undefined && this._tokenCounter > maxTokens) {\n throw syntaxError(\n this._lexer.source,\n token.start,\n `Document contains more that ${maxTokens} tokens. Parsing aborted.`,\n );\n }\n }\n }\n}\n/**\n * A helper function to describe a token as a string for debugging.\n *\n * @internal\n */\n\nfunction getTokenDesc(token) {\n const value = token.value;\n return getTokenKindDesc(token.kind) + (value != null ? ` \"${value}\"` : '');\n}\n/**\n * A helper function to describe a token kind as a string for debugging.\n *\n * @internal\n */\n\nfunction getTokenKindDesc(kind) {\n return isPunctuatorTokenKind(kind) ? `\"${kind}\"` : kind;\n}\n","const MAX_SUGGESTIONS = 5;\n/**\n * Given [A, B, C] return ' Did you mean A, B, or C?'.\n *\n * @internal\n */\n\n/** @internal */\nexport function didYouMean(firstArg, secondArg) {\n const [subMessage, suggestionsArg] = secondArg\n ? [firstArg, secondArg]\n : [undefined, firstArg];\n let message = ' Did you mean ';\n\n if (subMessage) {\n message += subMessage + ' ';\n }\n\n const suggestions = suggestionsArg.map((x) => `\"${x}\"`);\n\n switch (suggestions.length) {\n case 0:\n return '';\n\n case 1:\n return message + suggestions[0] + '?';\n\n case 2:\n return message + suggestions[0] + ' or ' + suggestions[1] + '?';\n }\n\n const selected = suggestions.slice(0, MAX_SUGGESTIONS);\n const lastItem = selected.pop();\n return message + selected.join(', ') + ', or ' + lastItem + '?';\n}\n","/**\n * Returns the first argument it receives.\n *\n * @internal\n */\nexport function identityFunc(x) {\n return x;\n}\n","/**\n * Creates a keyed JS object from an array, given a function to produce the keys\n * for each value in the array.\n *\n * This provides a convenient lookup for the array items if the key function\n * produces unique results.\n * @internal\n * @example\n * ```ts\n * const phoneBook = [\n * { name: 'Jon', num: '555-1234' },\n * { name: 'Jenny', num: '867-5309' },\n * ];\n *\n * const entriesByName = keyMap(phoneBook, (entry) => entry.name);\n *\n * Object.keys(entriesByName); // => ['Jon', 'Jenny']\n * entriesByName['Jenny']; // => { name: 'Jenny', num: '867-5309' }\n * ```\n */\nexport function keyMap(list, keyFn) {\n const result = Object.create(null);\n\n for (const item of list) {\n result[keyFn(item)] = item;\n }\n\n return result;\n}\n","/**\n * Creates a keyed JS object from an array, given a function to produce the keys\n * and a function to produce the values from each item in the array.\n * @internal\n * @example\n * ```ts\n * const phoneBook = [\n * { name: 'Jon', num: '555-1234' },\n * { name: 'Jenny', num: '867-5309' },\n * ];\n *\n * const phonesByName = keyValMap(\n * phoneBook,\n * (entry) => entry.name,\n * (entry) => entry.num,\n * );\n *\n * phonesByName; // => { Jon: '555-1234', Jenny: '867-5309' }\n * ```\n */\nexport function keyValMap(list, keyFn, valFn) {\n const result = Object.create(null);\n\n for (const item of list) {\n result[keyFn(item)] = valFn(item);\n }\n\n return result;\n}\n","/**\n * Creates an object map with the same keys as `map` and values generated by\n * running each value of `map` thru `fn`.\n *\n * @internal\n */\nexport function mapValue(map, fn) {\n const result = Object.create(null);\n\n for (const key of Object.keys(map)) {\n result[key] = fn(map[key], key);\n }\n\n return result;\n}\n","/**\n * Returns a number indicating whether a reference string comes before, or after,\n * or is the same as the given string in natural sort order.\n *\n * See: https://en.wikipedia.org/wiki/Natural_sort_order\n *\n *\n * @internal\n */\nexport function naturalCompare(aStr, bStr) {\n let aIndex = 0;\n let bIndex = 0;\n\n while (aIndex < aStr.length && bIndex < bStr.length) {\n let aChar = aStr.charCodeAt(aIndex);\n let bChar = bStr.charCodeAt(bIndex);\n\n if (isDigit(aChar) && isDigit(bChar)) {\n let aNum = 0;\n\n do {\n ++aIndex;\n aNum = aNum * 10 + aChar - DIGIT_0;\n aChar = aStr.charCodeAt(aIndex);\n } while (isDigit(aChar) && aNum > 0);\n\n let bNum = 0;\n\n do {\n ++bIndex;\n bNum = bNum * 10 + bChar - DIGIT_0;\n bChar = bStr.charCodeAt(bIndex);\n } while (isDigit(bChar) && bNum > 0);\n\n if (aNum < bNum) {\n return -1;\n }\n\n if (aNum > bNum) {\n return 1;\n }\n } else {\n if (aChar < bChar) {\n return -1;\n }\n\n if (aChar > bChar) {\n return 1;\n }\n\n ++aIndex;\n ++bIndex;\n }\n }\n\n return aStr.length - bStr.length;\n}\nconst DIGIT_0 = 48;\nconst DIGIT_9 = 57;\n\nfunction isDigit(code) {\n return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9;\n}\n","import { naturalCompare } from './naturalCompare.mjs';\n/**\n * Given an invalid input string and a list of valid options, returns a filtered\n * list of valid options sorted based on their similarity with the input.\n *\n * @internal\n */\n\nexport function suggestionList(input, options) {\n const optionsByDistance = Object.create(null);\n const lexicalDistance = new LexicalDistance(input);\n const threshold = Math.floor(input.length * 0.4) + 1;\n\n for (const option of options) {\n const distance = lexicalDistance.measure(option, threshold);\n\n if (distance !== undefined) {\n optionsByDistance[option] = distance;\n }\n }\n\n return Object.keys(optionsByDistance).sort((a, b) => {\n const distanceDiff = optionsByDistance[a] - optionsByDistance[b];\n return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b);\n });\n}\n/**\n * Computes the lexical distance between strings A and B.\n *\n * The \"distance\" between two strings is given by counting the minimum number\n * of edits needed to transform string A into string B. An edit can be an\n * insertion, deletion, or substitution of a single character, or a swap of two\n * adjacent characters.\n *\n * Includes a custom alteration from Damerau-Levenshtein to treat case changes\n * as a single edit which helps identify mis-cased values with an edit distance\n * of 1.\n *\n * This distance can be useful for detecting typos in input or sorting\n *\n * @internal\n */\n\nclass LexicalDistance {\n constructor(input) {\n this._input = input;\n this._inputLowerCase = input.toLowerCase();\n this._inputArray = stringToArray(this._inputLowerCase);\n this._rows = [\n new Array(input.length + 1).fill(0),\n new Array(input.length + 1).fill(0),\n new Array(input.length + 1).fill(0),\n ];\n }\n\n measure(option, threshold) {\n if (this._input === option) {\n return 0;\n }\n\n const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit\n\n if (this._inputLowerCase === optionLowerCase) {\n return 1;\n }\n\n let a = stringToArray(optionLowerCase);\n let b = this._inputArray;\n\n if (a.length < b.length) {\n const tmp = a;\n a = b;\n b = tmp;\n }\n\n const aLength = a.length;\n const bLength = b.length;\n\n if (aLength - bLength > threshold) {\n return undefined;\n }\n\n const rows = this._rows;\n\n for (let j = 0; j <= bLength; j++) {\n rows[0][j] = j;\n }\n\n for (let i = 1; i <= aLength; i++) {\n const upRow = rows[(i - 1) % 3];\n const currentRow = rows[i % 3];\n let smallestCell = (currentRow[0] = i);\n\n for (let j = 1; j <= bLength; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n let currentCell = Math.min(\n upRow[j] + 1, // delete\n currentRow[j - 1] + 1, // insert\n upRow[j - 1] + cost, // substitute\n );\n\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n // transposition\n const doubleDiagonalCell = rows[(i - 2) % 3][j - 2];\n currentCell = Math.min(currentCell, doubleDiagonalCell + 1);\n }\n\n if (currentCell < smallestCell) {\n smallestCell = currentCell;\n }\n\n currentRow[j] = currentCell;\n } // Early exit, since distance can't go smaller than smallest element of the previous row.\n\n if (smallestCell > threshold) {\n return undefined;\n }\n }\n\n const distance = rows[aLength % 3][bLength];\n return distance <= threshold ? distance : undefined;\n }\n}\n\nfunction stringToArray(str) {\n const strLength = str.length;\n const array = new Array(strLength);\n\n for (let i = 0; i < strLength; ++i) {\n array[i] = str.charCodeAt(i);\n }\n\n return array;\n}\n","/** @internal */\nexport function toObjMap(obj) {\n if (obj == null) {\n return Object.create(null);\n }\n\n if (Object.getPrototypeOf(obj) === null) {\n return obj;\n }\n\n const map = Object.create(null);\n\n for (const [key, value] of Object.entries(obj)) {\n map[key] = value;\n }\n\n return map;\n}\n","/**\n * Prints a string as a GraphQL StringValue literal. Replaces control characters\n * and excluded characters (\" U+0022 and \\\\ U+005C) with escape sequences.\n *\n * @internal\n */\nexport function printString(str) {\n return `\"${str.replace(escapedRegExp, escapedReplacer)}\"`;\n}\n/** @internal */\n// eslint-disable-next-line no-control-regex\n\nconst escapedRegExp = /[\\x00-\\x1f\\x22\\x5c\\x7f-\\x9f]/g;\n\nfunction escapedReplacer(str) {\n return escapeSequences[str.charCodeAt(0)];\n} // prettier-ignore\n\nconst escapeSequences = [\n '\\\\u0000',\n '\\\\u0001',\n '\\\\u0002',\n '\\\\u0003',\n '\\\\u0004',\n '\\\\u0005',\n '\\\\u0006',\n '\\\\u0007',\n '\\\\b',\n '\\\\t',\n '\\\\n',\n '\\\\u000B',\n '\\\\f',\n '\\\\r',\n '\\\\u000E',\n '\\\\u000F',\n '\\\\u0010',\n '\\\\u0011',\n '\\\\u0012',\n '\\\\u0013',\n '\\\\u0014',\n '\\\\u0015',\n '\\\\u0016',\n '\\\\u0017',\n '\\\\u0018',\n '\\\\u0019',\n '\\\\u001A',\n '\\\\u001B',\n '\\\\u001C',\n '\\\\u001D',\n '\\\\u001E',\n '\\\\u001F',\n '',\n '',\n '\\\\\"',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 2F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 3F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 4F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '\\\\\\\\',\n '',\n '',\n '', // 5F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '', // 6F\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '',\n '\\\\u007F',\n '\\\\u0080',\n '\\\\u0081',\n '\\\\u0082',\n '\\\\u0083',\n '\\\\u0084',\n '\\\\u0085',\n '\\\\u0086',\n '\\\\u0087',\n '\\\\u0088',\n '\\\\u0089',\n '\\\\u008A',\n '\\\\u008B',\n '\\\\u008C',\n '\\\\u008D',\n '\\\\u008E',\n '\\\\u008F',\n '\\\\u0090',\n '\\\\u0091',\n '\\\\u0092',\n '\\\\u0093',\n '\\\\u0094',\n '\\\\u0095',\n '\\\\u0096',\n '\\\\u0097',\n '\\\\u0098',\n '\\\\u0099',\n '\\\\u009A',\n '\\\\u009B',\n '\\\\u009C',\n '\\\\u009D',\n '\\\\u009E',\n '\\\\u009F',\n];\n","/** @category Visiting */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { isNode, QueryDocumentKeys } from './ast.mjs';\nimport { Kind } from './kinds.mjs';\n/** A visitor defines the callbacks called during AST traversal. */\n\n/** A value that can be returned from a visitor function to stop traversal. */\nexport const BREAK = Object.freeze({});\n/**\n * visit() will walk through an AST using a depth-first traversal, calling\n * the visitor's enter function at each node in the traversal, and calling the\n * leave function after visiting that node and all of its child nodes.\n *\n * By returning different values from the enter and leave functions, the\n * behavior of the visitor can be altered, including skipping over a sub-tree of\n * the AST (by returning false), editing the AST by returning a value or null\n * to remove the value, or to stop the whole traversal by returning BREAK.\n *\n * When using visit() to edit an AST, the original AST will not be modified, and\n * a new version of the AST with the changes applied will be returned from the\n * visit function.\n * @param root - The AST node at which to start traversal.\n * @param visitor - The visitor or reducer functions to call while traversing.\n * @param visitorKeys - Optional map of child keys to visit for each AST node kind.\n * @returns The original AST, an edited AST, or a reduced value depending on the visitor.\n * @typeParam N - The root AST node type returned when visiting without reducing.\n * @example\n * ```ts\n * // Return values control traversal: undefined makes no change, false skips\n * // a subtree, BREAK stops traversal, null removes a node, and any other\n * // value replaces the current node.\n * import { Kind, parse, print, visit } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n * const editedAST = visit(document, {\n * Field: (node) => {\n * if (node.name.value === 'hero') {\n * return {\n * ...node,\n * name: { kind: Kind.NAME, value: 'human' },\n * };\n * }\n * },\n * });\n *\n * print(editedAST); // => '{\\n human {\\n name\\n }\\n}'\n * ```\n * @example\n * ```ts\n * // A named visitor function runs when entering nodes of that kind.\n * import { parse, visit } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n * const fieldNames = [];\n *\n * visit(document, {\n * Field: (node) => {\n * fieldNames.push(node.name.value);\n * },\n * });\n *\n * fieldNames; // => ['hero', 'name']\n * ```\n * @example\n * ```ts\n * // A named visitor object can provide separate enter and leave handlers for\n * // nodes of that kind.\n * import { parse, visit } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n * const events = [];\n *\n * visit(document, {\n * Field: {\n * enter: (node) => {\n * events.push(`enter:${node.name.value}`);\n * },\n * leave: (node) => {\n * events.push(`leave:${node.name.value}`);\n * },\n * },\n * });\n *\n * events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero']\n * ```\n * @example\n * ```ts\n * // Generic enter and leave handlers run for every node.\n * import { parse, visit } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n * let enterCount = 0;\n * let leaveCount = 0;\n *\n * visit(document, {\n * enter: (node) => {\n * enterCount += 1;\n * },\n * leave: (node) => {\n * leaveCount += 1;\n * },\n * });\n *\n * enterCount; // => leaveCount\n * enterCount > 0; // => true\n * ```\n */\n\n/** @internal */\nexport function visit(root, visitor, visitorKeys = QueryDocumentKeys) {\n const enterLeaveMap = new Map();\n\n for (const kind of Object.values(Kind)) {\n enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind));\n }\n /* eslint-disable no-undef-init */\n\n let stack = undefined;\n let inArray = Array.isArray(root);\n let keys = [root];\n let index = -1;\n let edits = [];\n let node = root;\n let key = undefined;\n let parent = undefined;\n const path = [];\n const ancestors = [];\n /* eslint-enable no-undef-init */\n\n do {\n index++;\n const isLeaving = index === keys.length;\n const isEdited = isLeaving && edits.length !== 0;\n\n if (isLeaving) {\n key = ancestors.length === 0 ? undefined : path[path.length - 1];\n node = parent;\n parent = ancestors.pop();\n\n if (isEdited) {\n if (inArray) {\n node = node.slice();\n let editOffset = 0;\n\n for (const [editKey, editValue] of edits) {\n const arrayKey = editKey - editOffset;\n\n if (editValue === null) {\n node.splice(arrayKey, 1);\n editOffset++;\n } else {\n node[arrayKey] = editValue;\n }\n }\n } else {\n node = { ...node };\n\n for (const [editKey, editValue] of edits) {\n node[editKey] = editValue;\n }\n }\n }\n\n index = stack.index;\n keys = stack.keys;\n edits = stack.edits;\n inArray = stack.inArray;\n stack = stack.prev;\n } else if (parent) {\n key = inArray ? index : keys[index];\n node = parent[key];\n\n if (node === null || node === undefined) {\n continue;\n }\n\n path.push(key);\n }\n\n let result;\n\n if (!Array.isArray(node)) {\n var _enterLeaveMap$get, _enterLeaveMap$get2;\n\n isNode(node) || devAssert(false, `Invalid AST Node: ${inspect(node)}.`);\n const visitFn = isLeaving\n ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null ||\n _enterLeaveMap$get === void 0\n ? void 0\n : _enterLeaveMap$get.leave\n : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null ||\n _enterLeaveMap$get2 === void 0\n ? void 0\n : _enterLeaveMap$get2.enter;\n result =\n visitFn === null || visitFn === void 0\n ? void 0\n : visitFn.call(visitor, node, key, parent, path, ancestors);\n\n if (result === BREAK) {\n break;\n }\n\n if (result === false) {\n if (!isLeaving) {\n path.pop();\n continue;\n }\n } else if (result !== undefined) {\n edits.push([key, result]);\n\n if (!isLeaving) {\n if (isNode(result)) {\n node = result;\n } else {\n path.pop();\n continue;\n }\n }\n }\n }\n\n if (result === undefined && isEdited) {\n edits.push([key, node]);\n }\n\n if (isLeaving) {\n path.pop();\n } else {\n var _node$kind;\n\n stack = {\n inArray,\n index,\n keys,\n edits,\n prev: stack,\n };\n inArray = Array.isArray(node);\n keys = inArray\n ? node\n : (_node$kind = visitorKeys[node.kind]) !== null &&\n _node$kind !== void 0\n ? _node$kind\n : [];\n index = -1;\n edits = [];\n\n if (parent) {\n ancestors.push(parent);\n }\n\n parent = node;\n }\n } while (stack !== undefined);\n\n if (edits.length !== 0) {\n // New root\n return edits[edits.length - 1][1];\n }\n\n return root;\n}\n/**\n * Creates a new visitor instance which delegates to many visitors to run in\n * parallel. Each visitor will be visited for each node before moving on.\n *\n * If a prior visitor edits a node, no following visitors will see that node.\n * @param visitors - The visitors to merge into one parallel visitor.\n * @returns A visitor that delegates traversal to each provided visitor.\n * @example\n * ```ts\n * import { parse, visit, visitInParallel } from 'graphql/language';\n *\n * const document = parse('{ hero { name } }');\n * const events = [];\n *\n * visit(\n * document,\n * visitInParallel([\n * { Field: (node) => { events.push(`field:${node.name.value}`); } },\n * { Name: (node) => { events.push(`name:${node.value}`); } },\n * ]),\n * );\n *\n * events; // => ['field:hero', 'name:hero', 'field:name', 'name:name']\n * ```\n */\n\nexport function visitInParallel(visitors) {\n const skipping = new Array(visitors.length).fill(null);\n const mergedVisitor = Object.create(null);\n\n for (const kind of Object.values(Kind)) {\n let hasVisitor = false;\n const enterList = new Array(visitors.length).fill(undefined);\n const leaveList = new Array(visitors.length).fill(undefined);\n\n for (let i = 0; i < visitors.length; ++i) {\n const { enter, leave } = getEnterLeaveForKind(visitors[i], kind);\n hasVisitor || (hasVisitor = enter != null || leave != null);\n enterList[i] = enter;\n leaveList[i] = leave;\n }\n\n if (!hasVisitor) {\n continue;\n }\n\n const mergedEnterLeave = {\n enter(...args) {\n const node = args[0];\n\n for (let i = 0; i < visitors.length; i++) {\n if (skipping[i] === null) {\n var _enterList$i;\n\n const result =\n (_enterList$i = enterList[i]) === null || _enterList$i === void 0\n ? void 0\n : _enterList$i.apply(visitors[i], args);\n\n if (result === false) {\n skipping[i] = node;\n } else if (result === BREAK) {\n skipping[i] = BREAK;\n } else if (result !== undefined) {\n return result;\n }\n }\n }\n },\n\n leave(...args) {\n const node = args[0];\n\n for (let i = 0; i < visitors.length; i++) {\n if (skipping[i] === null) {\n var _leaveList$i;\n\n const result =\n (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0\n ? void 0\n : _leaveList$i.apply(visitors[i], args);\n\n if (result === BREAK) {\n skipping[i] = BREAK;\n } else if (result !== undefined && result !== false) {\n return result;\n }\n } else if (skipping[i] === node) {\n skipping[i] = null;\n }\n }\n },\n };\n mergedVisitor[kind] = mergedEnterLeave;\n }\n\n return mergedVisitor;\n}\n/**\n * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind.\n * @param visitor - The visitor object to inspect.\n * @param kind - The AST node kind to resolve handlers for.\n * @returns The enter and leave handlers that apply for the given node kind.\n * @example\n * ```ts\n * import { Kind, getEnterLeaveForKind } from 'graphql/language';\n *\n * const handlers = getEnterLeaveForKind({ Field: () => {} }, Kind.FIELD);\n *\n * typeof handlers.enter; // => 'function'\n * handlers.leave; // => undefined\n * ```\n */\n\nexport function getEnterLeaveForKind(visitor, kind) {\n const kindVisitor = visitor[kind];\n\n if (typeof kindVisitor === 'object') {\n // { Kind: { enter() {}, leave() {} } }\n return kindVisitor;\n } else if (typeof kindVisitor === 'function') {\n // { Kind() {} }\n return {\n enter: kindVisitor,\n leave: undefined,\n };\n } // { enter() {}, leave() {} }\n\n return {\n enter: visitor.enter,\n leave: visitor.leave,\n };\n}\n/**\n * Given a visitor instance, if it is leaving or not, and a node kind, return\n * the function the visitor runtime should call. This deprecated compatibility\n * helper delegates to `getEnterLeaveForKind`; call `getEnterLeaveForKind`\n * directly because getVisitFn will be removed in v17.\n * @param visitor - The visitor object to inspect.\n * @param kind - The AST node kind to resolve a handler for.\n * @param isLeaving - Whether to resolve the leave handler instead of the enter handler.\n * @returns The visit function that applies for the given node kind and traversal phase, if one exists.\n * @example\n * ```ts\n * import { Kind, getVisitFn } from 'graphql/language';\n *\n * const enter = getVisitFn({ Field: () => {} }, Kind.FIELD, false);\n * const leave = getVisitFn({ Field: () => {} }, Kind.FIELD, true);\n *\n * typeof enter; // => 'function'\n * leave; // => undefined\n * ```\n * @category Visiting\n * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17\n */\n\n/* c8 ignore next 8 */\n\nexport function getVisitFn(visitor, kind, isLeaving) {\n const { enter, leave } = getEnterLeaveForKind(visitor, kind);\n return isLeaving ? leave : enter;\n}\n","/** @category Printing */\nimport { printBlockString } from './blockString.mjs';\nimport { printString } from './printString.mjs';\nimport { visit } from './visitor.mjs';\n/**\n * Converts an AST into a string, using one set of reasonable\n * formatting rules.\n * @param ast - The GraphQL AST node to print.\n * @returns A stable string representation of the AST.\n * @example\n * ```ts\n * import { parse, print } from 'graphql';\n *\n * const ast = parse('{ hero { name } }');\n * const text = print(ast);\n *\n * text; // => '{\\n hero {\\n name\\n }\\n}'\n * ```\n */\n\nexport function print(ast) {\n return visit(ast, printDocASTReducer);\n}\nconst MAX_LINE_LENGTH = 80;\nconst printDocASTReducer = {\n Name: {\n leave: (node) => node.value,\n },\n Variable: {\n leave: (node) => '$' + node.name,\n },\n // Document\n Document: {\n leave: (node) => join(node.definitions, '\\n\\n'),\n },\n OperationDefinition: {\n leave(node) {\n const varDefs = hasMultilineItems(node.variableDefinitions)\n ? wrap('(\\n', join(node.variableDefinitions, '\\n'), '\\n)')\n : wrap('(', join(node.variableDefinitions, ', '), ')');\n const prefix =\n wrap('', node.description, '\\n') +\n join(\n [\n node.operation,\n join([node.name, varDefs]),\n join(node.directives, ' '),\n ],\n ' ',\n ); // Anonymous queries with no directives or variable definitions can use\n // the query short form.\n\n return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet;\n },\n },\n VariableDefinition: {\n leave: ({ variable, type, defaultValue, directives, description }) =>\n wrap('', description, '\\n') +\n variable +\n ': ' +\n type +\n wrap(' = ', defaultValue) +\n wrap(' ', join(directives, ' ')),\n },\n SelectionSet: {\n leave: ({ selections }) => block(selections),\n },\n Field: {\n leave({ alias, name, arguments: args, directives, selectionSet }) {\n const prefix = wrap('', alias, ': ') + name;\n let argsLine = prefix + wrap('(', join(args, ', '), ')');\n\n if (argsLine.length > MAX_LINE_LENGTH) {\n argsLine = prefix + wrap('(\\n', indent(join(args, '\\n')), '\\n)');\n }\n\n return join([argsLine, join(directives, ' '), selectionSet], ' ');\n },\n },\n Argument: {\n leave: ({ name, value }) => name + ': ' + value,\n },\n // Fragments\n FragmentSpread: {\n leave: ({ name, directives }) =>\n '...' + name + wrap(' ', join(directives, ' ')),\n },\n InlineFragment: {\n leave: ({ typeCondition, directives, selectionSet }) =>\n join(\n [\n '...',\n wrap('on ', typeCondition),\n join(directives, ' '),\n selectionSet,\n ],\n ' ',\n ),\n },\n FragmentDefinition: {\n leave: ({\n name,\n typeCondition,\n variableDefinitions,\n directives,\n selectionSet,\n description,\n }) =>\n wrap('', description, '\\n') + // Note: fragment variable definitions are experimental and may be changed\n // or removed in the future.\n `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` +\n `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` +\n selectionSet,\n },\n // Value\n IntValue: {\n leave: ({ value }) => value,\n },\n FloatValue: {\n leave: ({ value }) => value,\n },\n StringValue: {\n leave: ({ value, block: isBlockString }) =>\n isBlockString ? printBlockString(value) : printString(value),\n },\n BooleanValue: {\n leave: ({ value }) => (value ? 'true' : 'false'),\n },\n NullValue: {\n leave: () => 'null',\n },\n EnumValue: {\n leave: ({ value }) => value,\n },\n ListValue: {\n leave: ({ values }) => '[' + join(values, ', ') + ']',\n },\n ObjectValue: {\n leave: ({ fields }) => '{' + join(fields, ', ') + '}',\n },\n ObjectField: {\n leave: ({ name, value }) => name + ': ' + value,\n },\n // Directive\n Directive: {\n leave: ({ name, arguments: args }) =>\n '@' + name + wrap('(', join(args, ', '), ')'),\n },\n // Type\n NamedType: {\n leave: ({ name }) => name,\n },\n ListType: {\n leave: ({ type }) => '[' + type + ']',\n },\n NonNullType: {\n leave: ({ type }) => type + '!',\n },\n // Type System Definitions\n SchemaDefinition: {\n leave: ({ description, directives, operationTypes }) =>\n wrap('', description, '\\n') +\n join(['schema', join(directives, ' '), block(operationTypes)], ' '),\n },\n OperationTypeDefinition: {\n leave: ({ operation, type }) => operation + ': ' + type,\n },\n ScalarTypeDefinition: {\n leave: ({ description, name, directives }) =>\n wrap('', description, '\\n') +\n join(['scalar', name, join(directives, ' ')], ' '),\n },\n ObjectTypeDefinition: {\n leave: ({ description, name, interfaces, directives, fields }) =>\n wrap('', description, '\\n') +\n join(\n [\n 'type',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n FieldDefinition: {\n leave: ({ description, name, arguments: args, type, directives }) =>\n wrap('', description, '\\n') +\n name +\n (hasMultilineItems(args)\n ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n : wrap('(', join(args, ', '), ')')) +\n ': ' +\n type +\n wrap(' ', join(directives, ' ')),\n },\n InputValueDefinition: {\n leave: ({ description, name, type, defaultValue, directives }) =>\n wrap('', description, '\\n') +\n join(\n [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')],\n ' ',\n ),\n },\n InterfaceTypeDefinition: {\n leave: ({ description, name, interfaces, directives, fields }) =>\n wrap('', description, '\\n') +\n join(\n [\n 'interface',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n UnionTypeDefinition: {\n leave: ({ description, name, directives, types }) =>\n wrap('', description, '\\n') +\n join(\n ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))],\n ' ',\n ),\n },\n EnumTypeDefinition: {\n leave: ({ description, name, directives, values }) =>\n wrap('', description, '\\n') +\n join(['enum', name, join(directives, ' '), block(values)], ' '),\n },\n EnumValueDefinition: {\n leave: ({ description, name, directives }) =>\n wrap('', description, '\\n') + join([name, join(directives, ' ')], ' '),\n },\n InputObjectTypeDefinition: {\n leave: ({ description, name, directives, fields }) =>\n wrap('', description, '\\n') +\n join(['input', name, join(directives, ' '), block(fields)], ' '),\n },\n DirectiveDefinition: {\n leave: ({\n description,\n name,\n arguments: args,\n directives,\n repeatable,\n locations,\n }) =>\n wrap('', description, '\\n') +\n 'directive @' +\n name +\n (hasMultilineItems(args)\n ? wrap('(\\n', indent(join(args, '\\n')), '\\n)')\n : wrap('(', join(args, ', '), ')')) +\n wrap(' ', join(directives, ' ')) +\n (repeatable ? ' repeatable' : '') +\n ' on ' +\n join(locations, ' | '),\n },\n SchemaExtension: {\n leave: ({ directives, operationTypes }) =>\n join(\n ['extend schema', join(directives, ' '), block(operationTypes)],\n ' ',\n ),\n },\n ScalarTypeExtension: {\n leave: ({ name, directives }) =>\n join(['extend scalar', name, join(directives, ' ')], ' '),\n },\n ObjectTypeExtension: {\n leave: ({ name, interfaces, directives, fields }) =>\n join(\n [\n 'extend type',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n InterfaceTypeExtension: {\n leave: ({ name, interfaces, directives, fields }) =>\n join(\n [\n 'extend interface',\n name,\n wrap('implements ', join(interfaces, ' & ')),\n join(directives, ' '),\n block(fields),\n ],\n ' ',\n ),\n },\n UnionTypeExtension: {\n leave: ({ name, directives, types }) =>\n join(\n [\n 'extend union',\n name,\n join(directives, ' '),\n wrap('= ', join(types, ' | ')),\n ],\n ' ',\n ),\n },\n EnumTypeExtension: {\n leave: ({ name, directives, values }) =>\n join(['extend enum', name, join(directives, ' '), block(values)], ' '),\n },\n InputObjectTypeExtension: {\n leave: ({ name, directives, fields }) =>\n join(['extend input', name, join(directives, ' '), block(fields)], ' '),\n },\n DirectiveExtension: {\n leave: ({ name, directives }) =>\n join(['extend directive @' + name, join(directives, ' ')], ' '),\n },\n // Schema Coordinates\n TypeCoordinate: {\n leave: ({ name }) => name,\n },\n MemberCoordinate: {\n leave: ({ name, memberName }) => join([name, wrap('.', memberName)]),\n },\n ArgumentCoordinate: {\n leave: ({ name, fieldName, argumentName }) =>\n join([name, wrap('.', fieldName), wrap('(', argumentName, ':)')]),\n },\n DirectiveCoordinate: {\n leave: ({ name }) => join(['@', name]),\n },\n DirectiveArgumentCoordinate: {\n leave: ({ name, argumentName }) =>\n join(['@', name, wrap('(', argumentName, ':)')]),\n },\n};\n/**\n * Given maybeArray, print an empty string if it is null or empty, otherwise\n * print all items together separated by separator if provided\n *\n * @internal\n */\n\nfunction join(maybeArray, separator = '') {\n var _maybeArray$filter$jo;\n\n return (_maybeArray$filter$jo =\n maybeArray === null || maybeArray === void 0\n ? void 0\n : maybeArray.filter((x) => x).join(separator)) !== null &&\n _maybeArray$filter$jo !== void 0\n ? _maybeArray$filter$jo\n : '';\n}\n/**\n * Given array, print each item on its own line, wrapped in an indented `{ }` block.\n *\n * @internal\n */\n\nfunction block(array) {\n return wrap('{\\n', indent(join(array, '\\n')), '\\n}');\n}\n/**\n * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string.\n *\n * @internal\n */\n\nfunction wrap(start, maybeString, end = '') {\n return maybeString != null && maybeString !== ''\n ? start + maybeString + end\n : '';\n}\n\nfunction indent(str) {\n return wrap(' ', str.replace(/\\n/g, '\\n '));\n}\n\nfunction hasMultilineItems(maybeArray) {\n var _maybeArray$some;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n return (_maybeArray$some =\n maybeArray === null || maybeArray === void 0\n ? void 0\n : maybeArray.some((str) => str.includes('\\n'))) !== null &&\n _maybeArray$some !== void 0\n ? _maybeArray$some\n : false;\n}\n","/** @category Values */\nimport { keyValMap } from '../jsutils/keyValMap.mjs';\nimport { Kind } from '../language/kinds.mjs';\n/**\n * Produces a JavaScript value given a GraphQL Value AST.\n *\n * Because no GraphQL type is provided, the returned JavaScript value reflects\n * the provided GraphQL value AST.\n *\n * | GraphQL Value | JavaScript Value |\n * | -------------------- | ---------------- |\n * | Input Object | Object |\n * | List | Array |\n * | Boolean | Boolean |\n * | String / Enum | String |\n * | Int / Float | Number |\n * | Null | null |\n * @param valueNode - GraphQL value AST node to convert.\n * @param variables - Optional runtime variable values keyed by variable name.\n * @returns JavaScript value represented by the GraphQL value AST.\n * @example\n * ```ts\n * import { parseValue } from 'graphql/language';\n * import { valueFromASTUntyped } from 'graphql/utilities';\n *\n * const value = valueFromASTUntyped(parseValue('[1, 2, 3]'));\n *\n * value; // => [1, 2, 3]\n * valueFromASTUntyped(parseValue('$name'), { name: 'Ada' }); // => 'Ada'\n * ```\n */\n\nexport function valueFromASTUntyped(valueNode, variables) {\n switch (valueNode.kind) {\n case Kind.NULL:\n return null;\n\n case Kind.INT:\n return parseInt(valueNode.value, 10);\n\n case Kind.FLOAT:\n return parseFloat(valueNode.value);\n\n case Kind.STRING:\n case Kind.ENUM:\n case Kind.BOOLEAN:\n return valueNode.value;\n\n case Kind.LIST:\n return valueNode.values.map((node) =>\n valueFromASTUntyped(node, variables),\n );\n\n case Kind.OBJECT:\n return keyValMap(\n valueNode.fields,\n (field) => field.name.value,\n (field) => valueFromASTUntyped(field.value, variables),\n );\n\n case Kind.VARIABLE:\n return variables === null || variables === void 0\n ? void 0\n : variables[valueNode.name.value];\n }\n}\n","/** @category Names */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { isNameContinue, isNameStart } from '../language/characterClasses.mjs';\n/**\n * Upholds the spec rules about naming.\n * @param name - The GraphQL name to validate.\n * @returns The validated GraphQL name.\n * @example\n * ```ts\n * import { assertName } from 'graphql/type';\n *\n * assertName('User'); // => 'User'\n * assertName('123User'); // throws an error\n * ```\n */\n\nexport function assertName(name) {\n name != null || devAssert(false, 'Must provide name.');\n typeof name === 'string' || devAssert(false, 'Expected name to be a string.');\n\n if (name.length === 0) {\n throw new GraphQLError('Expected name to be a non-empty string.');\n }\n\n for (let i = 1; i < name.length; ++i) {\n if (!isNameContinue(name.charCodeAt(i))) {\n throw new GraphQLError(\n `Names must only contain [_a-zA-Z0-9] but \"${name}\" does not.`,\n );\n }\n }\n\n if (!isNameStart(name.charCodeAt(0))) {\n throw new GraphQLError(\n `Names must start with [_a-zA-Z] but \"${name}\" does not.`,\n );\n }\n\n return name;\n}\n/**\n * Upholds the spec rules about naming enum values.\n * @param name - The GraphQL name to validate.\n * @returns The validated GraphQL name.\n * @example\n * ```ts\n * import { assertEnumValueName } from 'graphql/type';\n *\n * assertEnumValueName('ACTIVE'); // => 'ACTIVE'\n * assertEnumValueName('true'); // throws an error\n * ```\n */\n\nexport function assertEnumValueName(name) {\n if (name === 'true' || name === 'false' || name === 'null') {\n throw new GraphQLError(`Enum values cannot be named: ${name}`);\n }\n\n return assertName(name);\n}\n","/** @category Types */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { didYouMean } from '../jsutils/didYouMean.mjs';\nimport { identityFunc } from '../jsutils/identityFunc.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { keyValMap } from '../jsutils/keyValMap.mjs';\nimport { mapValue } from '../jsutils/mapValue.mjs';\nimport { suggestionList } from '../jsutils/suggestionList.mjs';\nimport { toObjMap } from '../jsutils/toObjMap.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { print } from '../language/printer.mjs';\nimport { valueFromASTUntyped } from '../utilities/valueFromASTUntyped.mjs';\nimport { assertEnumValueName, assertName } from './assertName.mjs';\n\n/**\n * Returns true when the value is any GraphQL type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is any GraphQL type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { GraphQLList, GraphQLString, isType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * isType(GraphQLString); // => true\n * isType(new GraphQLList(GraphQLString)); // => true\n * isType(schema.getType('Query')); // => true\n * isType('String'); // => false\n * ```\n */\nexport function isType(type) {\n return (\n isScalarType(type) ||\n isObjectType(type) ||\n isInterfaceType(type) ||\n isUnionType(type) ||\n isEnumType(type) ||\n isInputObjectType(type) ||\n isListType(type) ||\n isNonNullType(type)\n );\n}\n/**\n * Returns the value as a GraphQL type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const queryType = assertType(schema.getType('Query'));\n *\n * queryType.toString(); // => 'Query'\n * assertType('Query'); // throws an error\n * ```\n */\n\nexport function assertType(type) {\n if (!isType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL type.`);\n }\n\n return type;\n}\n/**\n * There are predicates for each kind of GraphQL type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLScalarType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isScalarType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * scalar DateTime\n *\n * type Query {\n * createdAt: DateTime\n * }\n * `);\n *\n * isScalarType(schema.getType('DateTime')); // => true\n * isScalarType(schema.getType('Query')); // => false\n * ```\n */\n\nexport function isScalarType(type) {\n return instanceOf(type, GraphQLScalarType);\n}\n/**\n * Returns the value as a GraphQLScalarType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLScalarType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertScalarType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * scalar DateTime\n *\n * type Query {\n * createdAt: DateTime\n * }\n * `);\n *\n * const dateTimeType = assertScalarType(schema.getType('DateTime'));\n *\n * dateTimeType.name; // => 'DateTime'\n * assertScalarType(schema.getType('Query')); // throws an error\n * ```\n */\n\nexport function assertScalarType(type) {\n if (!isScalarType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL Scalar type.`);\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLObjectType.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLObjectType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type User {\n * name: String\n * }\n *\n * type Query {\n * user: User\n * }\n * `);\n *\n * isObjectType(schema.getType('User')); // => true\n * isObjectType(schema.getType('ReviewInput')); // => false\n * ```\n */\n\nexport function isObjectType(type) {\n return instanceOf(type, GraphQLObjectType);\n}\n/**\n * Returns the value as a GraphQLObjectType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLObjectType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type User {\n * name: String\n * }\n *\n * type Query {\n * user: User\n * }\n * `);\n *\n * const userType = assertObjectType(schema.getType('User'));\n *\n * Object.keys(userType.getFields()); // => ['name']\n * assertObjectType(schema.getType('ReviewInput')); // throws an error\n * ```\n */\n\nexport function assertObjectType(type) {\n if (!isObjectType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL Object type.`);\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLInterfaceType.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLInterfaceType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * isInterfaceType(schema.getType('Node')); // => true\n * isInterfaceType(schema.getType('User')); // => false\n * ```\n */\n\nexport function isInterfaceType(type) {\n return instanceOf(type, GraphQLInterfaceType);\n}\n/**\n * Returns the value as a GraphQLInterfaceType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLInterfaceType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * const nodeType = assertInterfaceType(schema.getType('Node'));\n *\n * nodeType.name; // => 'Node'\n * assertInterfaceType(schema.getType('User')); // throws an error\n * ```\n */\n\nexport function assertInterfaceType(type) {\n if (!isInterfaceType(type)) {\n throw new Error(\n `Expected ${inspect(type)} to be a GraphQL Interface type.`,\n );\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLUnionType.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLUnionType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isUnionType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Photo {\n * url: String!\n * }\n *\n * type Video {\n * url: String!\n * }\n *\n * union Media = Photo | Video\n *\n * type Query {\n * media: [Media]\n * }\n * `);\n *\n * isUnionType(schema.getType('Media')); // => true\n * isUnionType(schema.getType('Photo')); // => false\n * ```\n */\n\nexport function isUnionType(type) {\n return instanceOf(type, GraphQLUnionType);\n}\n/**\n * Returns the value as a GraphQLUnionType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLUnionType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertUnionType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Photo {\n * url: String!\n * }\n *\n * type Video {\n * url: String!\n * }\n *\n * union Media = Photo | Video\n *\n * type Query {\n * media: [Media]\n * }\n * `);\n *\n * const mediaType = assertUnionType(schema.getType('Media'));\n *\n * mediaType.getTypes().map((type) => type.name); // => ['Photo', 'Video']\n * assertUnionType(schema.getType('Photo')); // throws an error\n * ```\n */\n\nexport function assertUnionType(type) {\n if (!isUnionType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL Union type.`);\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLEnumType.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLEnumType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isEnumType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * EMPIRE\n * }\n *\n * type Query {\n * favoriteEpisode: Episode\n * }\n * `);\n *\n * isEnumType(schema.getType('Episode')); // => true\n * isEnumType(schema.getType('Query')); // => false\n * ```\n */\n\nexport function isEnumType(type) {\n return instanceOf(type, GraphQLEnumType);\n}\n/**\n * Returns the value as a GraphQLEnumType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLEnumType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertEnumType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * EMPIRE\n * }\n *\n * type Query {\n * favoriteEpisode: Episode\n * }\n * `);\n *\n * const episodeType = assertEnumType(schema.getType('Episode'));\n *\n * episodeType.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE']\n * assertEnumType(schema.getType('Query')); // throws an error\n * ```\n */\n\nexport function assertEnumType(type) {\n if (!isEnumType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL Enum type.`);\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLInputObjectType.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLInputObjectType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isInputObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * isInputObjectType(schema.getType('ReviewInput')); // => true\n * isInputObjectType(schema.getType('Review')); // => false\n * ```\n */\n\nexport function isInputObjectType(type) {\n return instanceOf(type, GraphQLInputObjectType);\n}\n/**\n * Returns the value as a GraphQLInputObjectType, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLInputObjectType.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInputObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * const inputType = assertInputObjectType(schema.getType('ReviewInput'));\n *\n * Object.keys(inputType.getFields()); // => ['stars']\n * assertInputObjectType(schema.getType('Review')); // throws an error\n * ```\n */\n\nexport function assertInputObjectType(type) {\n if (!isInputObjectType(type)) {\n throw new Error(\n `Expected ${inspect(type)} to be a GraphQL Input Object type.`,\n );\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLList.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLList.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { GraphQLList, GraphQLString, isListType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * tags: [String!]!\n * }\n * `);\n *\n * const tagsField = schema.getQueryType()?.getFields().tags;\n *\n * isListType(new GraphQLList(GraphQLString)); // => true\n * isListType(GraphQLString); // => false\n * isListType(tagsField?.type); // => false\n * ```\n */\n\n/** @internal */\nexport function isListType(type) {\n return instanceOf(type, GraphQLList);\n}\n/**\n * Returns the value as a GraphQLList, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLList.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString, assertListType } from 'graphql/type';\n *\n * const listType = assertListType(new GraphQLList(GraphQLString));\n *\n * listType.ofType; // => GraphQLString\n * assertListType(GraphQLString); // throws an error\n * ```\n */\n\nexport function assertListType(type) {\n if (!isListType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL List type.`);\n }\n\n return type;\n}\n/**\n * Returns true when the value is a GraphQLNonNull.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQLNonNull.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String!\n * nickname: String\n * }\n * `);\n *\n * const fields = schema.getQueryType()?.getFields();\n *\n * isNonNullType(new GraphQLNonNull(GraphQLString)); // => true\n * isNonNullType(fields?.name.type); // => true\n * isNonNullType(fields?.nickname.type); // => false\n * ```\n */\n\n/** @internal */\nexport function isNonNullType(type) {\n return instanceOf(type, GraphQLNonNull);\n}\n/**\n * Returns the value as a GraphQLNonNull, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQLNonNull.\n * @example\n * ```ts\n * import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type';\n *\n * const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString));\n *\n * nonNullType.ofType; // => GraphQLString\n * assertNonNullType(GraphQLString); // throws an error\n * ```\n */\n\nexport function assertNonNullType(type) {\n if (!isNonNullType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL Non-Null type.`);\n }\n\n return type;\n}\n/** These types may be used as input types for arguments and directives. */\n\n/**\n * Returns true when the value can be used as a GraphQL input type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value can be used as a GraphQL input type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isInputType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * isInputType(schema.getType('ReviewInput')); // => true\n * isInputType(schema.getType('Review')); // => false\n * ```\n */\nexport function isInputType(type) {\n return (\n isScalarType(type) ||\n isEnumType(type) ||\n isInputObjectType(type) ||\n (isWrappingType(type) && isInputType(type.ofType))\n );\n}\n/**\n * Returns the value as a GraphQL input type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL input type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInputType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * const inputType = assertInputType(schema.getType('ReviewInput'));\n *\n * inputType.toString(); // => 'ReviewInput'\n * assertInputType(schema.getType('Review')); // throws an error\n * ```\n */\n\nexport function assertInputType(type) {\n if (!isInputType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL input type.`);\n }\n\n return type;\n}\n/** These types may be used as output types as the result of fields. */\n\n/**\n * Returns true when the value can be used as a GraphQL output type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value can be used as a GraphQL output type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isOutputType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * isOutputType(schema.getType('Review')); // => true\n * isOutputType(schema.getType('ReviewInput')); // => false\n * ```\n */\nexport function isOutputType(type) {\n return (\n isScalarType(type) ||\n isObjectType(type) ||\n isInterfaceType(type) ||\n isUnionType(type) ||\n isEnumType(type) ||\n (isWrappingType(type) && isOutputType(type.ofType))\n );\n}\n/**\n * Returns the value as a GraphQL output type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL output type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertOutputType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput): Review\n * }\n * `);\n *\n * const outputType = assertOutputType(schema.getType('Review'));\n *\n * outputType.toString(); // => 'Review'\n * assertOutputType(schema.getType('ReviewInput')); // throws an error\n * ```\n */\n\nexport function assertOutputType(type) {\n if (!isOutputType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL output type.`);\n }\n\n return type;\n}\n/** These types may describe types which may be leaf values. */\n\n/**\n * Returns true when the value is a GraphQL scalar or enum type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL scalar or enum type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isLeafType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * episode: Episode\n * review: Review\n * }\n * `);\n *\n * isLeafType(schema.getType('Episode')); // => true\n * isLeafType(schema.getType('String')); // => true\n * isLeafType(schema.getType('Review')); // => false\n * ```\n */\nexport function isLeafType(type) {\n return isScalarType(type) || isEnumType(type);\n}\n/**\n * Returns the value as a GraphQL leaf type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL leaf type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertLeafType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * }\n *\n * type Review {\n * stars: Int!\n * }\n *\n * type Query {\n * episode: Episode\n * review: Review\n * }\n * `);\n *\n * const episodeType = assertLeafType(schema.getType('Episode'));\n *\n * episodeType.toString(); // => 'Episode'\n * assertLeafType(schema.getType('Review')); // throws an error\n * ```\n */\n\nexport function assertLeafType(type) {\n if (!isLeafType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL leaf type.`);\n }\n\n return type;\n}\n/** These types may describe the parent context of a selection set. */\n\n/**\n * Returns true when the value is a GraphQL object, interface, or union type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL object, interface, or union type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isCompositeType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * union SearchResult = User\n *\n * type Query {\n * node: Node\n * search: [SearchResult]\n * }\n * `);\n *\n * isCompositeType(schema.getType('User')); // => true\n * isCompositeType(schema.getType('Node')); // => true\n * isCompositeType(schema.getType('SearchResult')); // => true\n * isCompositeType(schema.getType('String')); // => false\n * ```\n */\nexport function isCompositeType(type) {\n return isObjectType(type) || isInterfaceType(type) || isUnionType(type);\n}\n/**\n * Returns the value as a GraphQL composite type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL composite type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertCompositeType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * const userType = assertCompositeType(schema.getType('User'));\n *\n * userType.toString(); // => 'User'\n * assertCompositeType(schema.getType('String')); // throws an error\n * ```\n */\n\nexport function assertCompositeType(type) {\n if (!isCompositeType(type)) {\n throw new Error(\n `Expected ${inspect(type)} to be a GraphQL composite type.`,\n );\n }\n\n return type;\n}\n/** These types may describe the parent context of a selection set. */\n\n/**\n * Returns true when the value is a GraphQL interface or union type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL interface or union type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { isAbstractType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * union SearchResult = User\n *\n * type Query {\n * node: Node\n * search: [SearchResult]\n * }\n * `);\n *\n * isAbstractType(schema.getType('Node')); // => true\n * isAbstractType(schema.getType('SearchResult')); // => true\n * isAbstractType(schema.getType('User')); // => false\n * ```\n */\nexport function isAbstractType(type) {\n return isInterfaceType(type) || isUnionType(type);\n}\n/**\n * Returns the value as a GraphQL abstract type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL abstract type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertAbstractType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * const nodeType = assertAbstractType(schema.getType('Node'));\n *\n * nodeType.toString(); // => 'Node'\n * assertAbstractType(schema.getType('User')); // throws an error\n * ```\n */\n\nexport function assertAbstractType(type) {\n if (!isAbstractType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL abstract type.`);\n }\n\n return type;\n}\n/**\n * List Type Wrapper\n *\n * A list is a wrapping type which points to another type.\n * Lists are often created within the context of defining the fields of\n * an object type.\n * @typeParam T - The GraphQL type wrapped by this list type.\n * @example\n * ```ts\n * const PersonType = new GraphQLObjectType({\n * name: 'Person',\n * fields: () => ({\n * parents: { type: new GraphQLList(PersonType) },\n * children: { type: new GraphQLList(PersonType) },\n * })\n * })\n * ```\n */\n\nexport class GraphQLList {\n /** The type wrapped by this list or non-null type. */\n\n /**\n * Creates a GraphQLList instance.\n * @param ofType - The type to wrap.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString } from 'graphql/type';\n *\n * const stringList = new GraphQLList(GraphQLString);\n *\n * stringList.ofType; // => GraphQLString\n * String(stringList); // => '[String]'\n * ```\n */\n constructor(ofType) {\n isType(ofType) ||\n devAssert(false, `Expected ${inspect(ofType)} to be a GraphQL type.`);\n this.ofType = ofType;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLList';\n }\n /**\n * Returns this wrapping type as a GraphQL type-reference string.\n * @returns The GraphQL type-reference string.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type';\n *\n * const stringList = new GraphQLList(GraphQLString);\n * const requiredStringList = new GraphQLList(new GraphQLNonNull(GraphQLString));\n *\n * stringList.toString(); // => '[String]'\n * requiredStringList.toString(); // => '[String!]'\n * ```\n */\n\n toString() {\n return '[' + String(this.ofType) + ']';\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString } from 'graphql/type';\n *\n * const stringList = new GraphQLList(GraphQLString);\n *\n * stringList.toJSON(); // => '[String]'\n * JSON.stringify({ type: stringList }); // => '{\"type\":\"[String]\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n/**\n * Non-Null Type Wrapper\n *\n * A non-null is a wrapping type which points to another type.\n * Non-null types enforce that their values are never null and can ensure\n * an error is raised if this ever occurs during a request. It is useful for\n * fields which you can make a strong guarantee on non-nullability, for example\n * usually the id field of a database row will never be null.\n * @typeParam T - The nullable GraphQL type wrapped by this non-null type.\n * @example\n * ```ts\n * const RowType = new GraphQLObjectType({\n * name: 'Row',\n * fields: () => ({\n * id: { type: new GraphQLNonNull(GraphQLString) },\n * })\n * })\n * ```\n *\n * Note: the enforcement of non-nullability occurs within the executor.\n */\n\nexport class GraphQLNonNull {\n /** The type wrapped by this list or non-null type. */\n\n /**\n * Creates a GraphQLNonNull instance.\n * @param ofType - The type to wrap.\n * @example\n * ```ts\n * import { GraphQLNonNull, GraphQLString } from 'graphql/type';\n *\n * const requiredString = new GraphQLNonNull(GraphQLString);\n *\n * requiredString.ofType; // => GraphQLString\n * String(requiredString); // => 'String!'\n * ```\n */\n constructor(ofType) {\n isNullableType(ofType) ||\n devAssert(\n false,\n `Expected ${inspect(ofType)} to be a GraphQL nullable type.`,\n );\n this.ofType = ofType;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLNonNull';\n }\n /**\n * Returns this wrapping type as a GraphQL type-reference string.\n * @returns The GraphQL type-reference string.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type';\n *\n * const requiredString = new GraphQLNonNull(GraphQLString);\n * const requiredStringList = new GraphQLNonNull(\n * new GraphQLList(GraphQLString),\n * );\n *\n * requiredString.toString(); // => 'String!'\n * requiredStringList.toString(); // => '[String]!'\n * ```\n */\n\n toString() {\n return String(this.ofType) + '!';\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLNonNull, GraphQLString } from 'graphql/type';\n *\n * const requiredString = new GraphQLNonNull(GraphQLString);\n *\n * requiredString.toJSON(); // => 'String!'\n * JSON.stringify({ type: requiredString }); // => '{\"type\":\"String!\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n/** These types wrap and modify other types */\n\n/**\n * Returns true when the value is a GraphQL list or non-null wrapper type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL list or non-null wrapper type.\n * @example\n * ```ts\n * import {\n * GraphQLList,\n * GraphQLNonNull,\n * GraphQLString,\n * isWrappingType,\n * } from 'graphql/type';\n *\n * isWrappingType(new GraphQLList(GraphQLString)); // => true\n * isWrappingType(new GraphQLNonNull(GraphQLString)); // => true\n * isWrappingType(GraphQLString); // => false\n * ```\n */\nexport function isWrappingType(type) {\n return isListType(type) || isNonNullType(type);\n}\n/**\n * Returns the value as a GraphQL wrapping type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL wrapping type.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type';\n *\n * const wrappingType = assertWrappingType(new GraphQLList(GraphQLString));\n *\n * wrappingType.toString(); // => '[String]'\n * assertWrappingType(GraphQLString); // throws an error\n * ```\n */\n\nexport function assertWrappingType(type) {\n if (!isWrappingType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL wrapping type.`);\n }\n\n return type;\n}\n/** These types can all accept null as a value. */\n\n/**\n * Returns true when the value is a GraphQL type that can accept null.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL type that can accept null.\n * @example\n * ```ts\n * import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type';\n *\n * isNullableType(GraphQLString); // => true\n * isNullableType(new GraphQLNonNull(GraphQLString)); // => false\n * isNullableType(null); // => false\n * ```\n */\nexport function isNullableType(type) {\n return isType(type) && !isNonNullType(type);\n}\n/**\n * Returns the value as a nullable GraphQL type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a nullable GraphQL type.\n * @example\n * ```ts\n * import {\n * GraphQLNonNull,\n * GraphQLString,\n * assertNullableType,\n * } from 'graphql/type';\n *\n * const nullableType = assertNullableType(GraphQLString);\n *\n * nullableType; // => GraphQLString\n * assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error\n * ```\n */\n\nexport function assertNullableType(type) {\n if (!isNullableType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL nullable type.`);\n }\n\n return type;\n}\n/**\n * Returns the nullable type.\n * @param type - The GraphQL type to inspect.\n * @returns The nullable type after removing one non-null wrapper, if present.\n * @example\n * ```ts\n * import { getNullableType } from 'graphql/type';\n *\n * getNullableType(null); // => undefined\n * getNullableType(undefined); // => undefined\n * ```\n */\n\n/** @internal */\nexport function getNullableType(type) {\n if (type) {\n return isNonNullType(type) ? type.ofType : type;\n }\n}\n/** These named types do not include modifiers like List or NonNull. */\n\n/**\n * Returns true when the value is a GraphQL named type.\n * @param type - The GraphQL type to inspect.\n * @returns True when the value is a GraphQL named type.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type';\n *\n * isNamedType(GraphQLString); // => true\n * isNamedType(new GraphQLList(GraphQLString)); // => false\n * isNamedType(null); // => false\n * ```\n */\nexport function isNamedType(type) {\n return (\n isScalarType(type) ||\n isObjectType(type) ||\n isInterfaceType(type) ||\n isUnionType(type) ||\n isEnumType(type) ||\n isInputObjectType(type)\n );\n}\n/**\n * Returns the value as a GraphQL named type, or throws if it is not one.\n * @param type - The GraphQL type to inspect.\n * @returns The value typed as a GraphQL named type.\n * @example\n * ```ts\n * import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type';\n *\n * const namedType = assertNamedType(GraphQLString);\n *\n * namedType.name; // => 'String'\n * assertNamedType(new GraphQLList(GraphQLString)); // throws an error\n * ```\n */\n\nexport function assertNamedType(type) {\n if (!isNamedType(type)) {\n throw new Error(`Expected ${inspect(type)} to be a GraphQL named type.`);\n }\n\n return type;\n}\n/**\n * Returns the named type.\n * @param type - The GraphQL type to inspect.\n * @returns The named type after unwrapping all list and non-null wrappers.\n * @example\n * ```ts\n * import { getNamedType } from 'graphql/type';\n *\n * getNamedType(null); // => undefined\n * getNamedType(undefined); // => undefined\n * ```\n */\n\n/** @internal */\nexport function getNamedType(type) {\n if (type) {\n let unwrappedType = type;\n\n while (isWrappingType(unwrappedType)) {\n unwrappedType = unwrappedType.ofType;\n }\n\n return unwrappedType;\n }\n}\n/**\n * Used while defining GraphQL types to allow for circular references in\n * otherwise immutable type definitions.\n * @typeParam T - The element type returned by the thunk or array.\n */\n\n/**\n * Resolves a thunked readonly array.\n * @param thunk - The thunk or value to resolve.\n * @returns The resolved readonly array.\n * @typeParam T - The element type resolved from the thunk or array.\n * @example\n * ```ts\n * import { GraphQLString, resolveReadonlyArrayThunk } from 'graphql/type';\n *\n * const lazyFields = resolveReadonlyArrayThunk(() => [GraphQLString]);\n * const fields = resolveReadonlyArrayThunk([GraphQLString]);\n *\n * lazyFields; // => [GraphQLString]\n * fields; // => [GraphQLString]\n * ```\n */\nexport function resolveReadonlyArrayThunk(thunk) {\n return typeof thunk === 'function' ? thunk() : thunk;\n}\n/**\n * Resolves a thunked object map.\n * @param thunk - The thunk or value to resolve.\n * @returns The resolved object map.\n * @typeParam T - The object-map value type resolved from the thunk or map.\n * @example\n * ```ts\n * import { GraphQLString, resolveObjMapThunk } from 'graphql/type';\n *\n * const lazyFields = resolveObjMapThunk(() => ({ name: GraphQLString }));\n * const fields = resolveObjMapThunk({ name: GraphQLString });\n *\n * lazyFields.name; // => GraphQLString\n * fields.name; // => GraphQLString\n * ```\n */\n\nexport function resolveObjMapThunk(thunk) {\n return typeof thunk === 'function' ? thunk() : thunk;\n}\n/**\n * Custom extensions\n * @remarks\n * Use a unique identifier name for your extension, for example the name of\n * your library or project. Do not use a shortened identifier as this increases\n * the risk of conflicts. We recommend you add at most one extension field,\n * an object which can contain all the values you need.\n */\n\n/**\n * Scalar Type Definition\n *\n * Scalar types define the leaf values of a GraphQL response and the input\n * values accepted by arguments and input object fields. A scalar type has a\n * name and coercion functions that validate and convert runtime values and\n * GraphQL literals.\n *\n * If a type's serialize function returns `null` or does not return a value\n * (i.e. it returns `undefined`) then an error will be raised and a `null`\n * value will be returned in the response. Prefer validating inputs before\n * execution so clients receive input diagnostics before result coercion fails.\n * @typeParam TInternal - The internal runtime representation accepted by this scalar.\n * @typeParam TExternal - The serialized representation exposed in GraphQL results.\n * @example\n * ```ts\n * const OddType = new GraphQLScalarType({\n * name: 'Odd',\n * serialize: (value) => {\n * if (!Number.isFinite(value)) {\n * throw new Error(\n * `Scalar \"Odd\" cannot represent \"${value}\" since it is not a finite number.`,\n * );\n * }\n *\n * if (value % 2 === 0) {\n * throw new Error(`Scalar \"Odd\" cannot represent \"${value}\" since it is even.`);\n * }\n * return value;\n * }\n * });\n * ```\n */\nexport class GraphQLScalarType {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** URL identifying the behavior specified for this custom scalar. */\n\n /** Function that converts internal values to externally visible scalar values. */\n\n /** Function that converts variable input into this scalar's internal value. */\n\n /** Function that converts AST input literals into this scalar's internal value. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLScalarType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { Kind, parse } from 'graphql/language';\n * import { GraphQLScalarType } from 'graphql/type';\n *\n * const document = parse(`\n * \"Odd integer values.\"\n * scalar Odd @specifiedBy(url: \"https://example.com/odd\")\n *\n * extend scalar Odd @specifiedBy(url: \"https://example.com/odd-v2\")\n * `);\n *\n * const Odd = new GraphQLScalarType({\n * name: 'Odd',\n * description: 'Odd integer values.',\n * specifiedByURL: 'https://example.com/odd',\n * serialize: (value) => {\n * if (typeof value !== 'number' || value % 2 === 0) {\n * throw new TypeError('Odd can only serialize odd numbers.');\n * }\n * return value;\n * },\n * parseValue: (value) => {\n * if (typeof value !== 'number' || value % 2 === 0) {\n * throw new TypeError('Odd can only parse odd numbers.');\n * }\n * return value;\n * },\n * parseLiteral: (ast) => {\n * if (ast.kind !== Kind.INT) {\n * throw new TypeError('Odd can only parse integer literals.');\n * }\n * const value = Number(ast.value);\n * if (value % 2 === 0) {\n * throw new TypeError('Odd can only parse odd integer literals.');\n * }\n * return value;\n * },\n * extensions: { numeric: true },\n * astNode: document.definitions[0],\n * extensionASTNodes: [ document.definitions[1] ],\n * });\n *\n * Odd.description; // => 'Odd integer values.'\n * Odd.specifiedByURL; // => 'https://example.com/odd'\n * Odd.serialize(3); // => 3\n * Odd.parseValue(5); // => 5\n * Odd.extensions; // => { numeric: true }\n * ```\n */\n constructor(config) {\n var _config$parseValue,\n _config$serialize,\n _config$parseLiteral,\n _config$extensionASTN;\n\n const parseValue =\n (_config$parseValue = config.parseValue) !== null &&\n _config$parseValue !== void 0\n ? _config$parseValue\n : identityFunc;\n this.name = assertName(config.name);\n this.description = config.description;\n this.specifiedByURL = config.specifiedByURL;\n this.serialize =\n (_config$serialize = config.serialize) !== null &&\n _config$serialize !== void 0\n ? _config$serialize\n : identityFunc;\n this.parseValue = parseValue;\n this.parseLiteral =\n (_config$parseLiteral = config.parseLiteral) !== null &&\n _config$parseLiteral !== void 0\n ? _config$parseLiteral\n : (node, variables) => parseValue(valueFromASTUntyped(node, variables));\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN = config.extensionASTNodes) !== null &&\n _config$extensionASTN !== void 0\n ? _config$extensionASTN\n : [];\n config.specifiedByURL == null ||\n typeof config.specifiedByURL === 'string' ||\n devAssert(\n false,\n `${this.name} must provide \"specifiedByURL\" as a string, ` +\n `but got: ${inspect(config.specifiedByURL)}.`,\n );\n config.serialize == null ||\n typeof config.serialize === 'function' ||\n devAssert(\n false,\n `${this.name} must provide \"serialize\" function. If this custom Scalar is also used as an input type, ensure \"parseValue\" and \"parseLiteral\" functions are also provided.`,\n );\n\n if (config.parseLiteral) {\n (typeof config.parseValue === 'function' &&\n typeof config.parseLiteral === 'function') ||\n devAssert(\n false,\n `${this.name} must provide both \"parseValue\" and \"parseLiteral\" functions.`,\n );\n }\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLScalarType';\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { GraphQLScalarType } from 'graphql/type';\n *\n * const Url = new GraphQLScalarType({\n * name: 'Url',\n * description: 'An absolute URL string.',\n * specifiedByURL: 'https://url.spec.whatwg.org/',\n * });\n *\n * const config = Url.toConfig();\n * const UrlCopy = new GraphQLScalarType(config);\n *\n * config.name; // => 'Url'\n * config.specifiedByURL; // => 'https://url.spec.whatwg.org/'\n * UrlCopy.name; // => Url.name\n * ```\n */\n\n toConfig() {\n return {\n name: this.name,\n description: this.description,\n specifiedByURL: this.specifiedByURL,\n serialize: this.serialize,\n parseValue: this.parseValue,\n parseLiteral: this.parseLiteral,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this scalar type.\n * @returns The schema coordinate for this scalar type.\n * @example\n * ```ts\n * import { GraphQLScalarType } from 'graphql/type';\n *\n * const DateTime = new GraphQLScalarType({ name: 'DateTime' });\n *\n * DateTime.toString(); // => 'DateTime'\n * String(DateTime); // => 'DateTime'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLScalarType } from 'graphql/type';\n *\n * const DateTime = new GraphQLScalarType({ name: 'DateTime' });\n *\n * DateTime.toJSON(); // => 'DateTime'\n * JSON.stringify({ type: DateTime }); // => '{\"type\":\"DateTime\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n/**\n * Serializes a runtime value as a scalar output value.\n * @typeParam TExternal - The serialized representation returned for GraphQL results.\n */\n\n/**\n * Object Type Definition\n *\n * Almost all of the GraphQL types you define will be object types. Object types\n * have a name, but most importantly describe their fields.\n * @typeParam TSource - Source object type passed to resolvers.\n * @typeParam TContext - Context object type passed to resolvers.\n * @example\n * ```ts\n * const AddressType = new GraphQLObjectType({\n * name: 'Address',\n * fields: {\n * street: { type: GraphQLString },\n * number: { type: GraphQLInt },\n * formatted: {\n * type: GraphQLString,\n * resolve: (obj) => {\n * return obj.number + ' ' + obj.street\n * }\n * }\n * }\n * });\n * ```\n * @example\n * When two types need to refer to each other, or a type needs to refer to\n * itself in a field, you can use a function expression (aka a closure or a\n * thunk) to supply the fields lazily.\n *\n * ```ts\n * const PersonType = new GraphQLObjectType({\n * name: 'Person',\n * fields: () => ({\n * name: { type: GraphQLString },\n * bestFriend: { type: PersonType },\n * })\n * });\n * ```\n */\nexport class GraphQLObjectType {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Predicate used to determine whether a runtime value belongs to this object type. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLObjectType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * // Configure an object type with interfaces, fields, arguments, and metadata.\n * import { parse } from 'graphql/language';\n * import {\n * GraphQLID,\n * GraphQLInterfaceType,\n * GraphQLNonNull,\n * GraphQLObjectType,\n * GraphQLString,\n * } from 'graphql/type';\n *\n * const document = parse(`\n * type User implements Node {\n * id: ID!\n * name(format: String = \"short\"): String\n * }\n *\n * extend type User {\n * displayName: String\n * }\n * `);\n * const definition = document.definitions[0];\n * const nameField = definition.fields[1];\n * const formatArg = nameField.arguments[0];\n *\n * const Node = new GraphQLInterfaceType({\n * name: 'Node',\n * fields: {\n * id: { type: new GraphQLNonNull(GraphQLID) },\n * },\n * });\n *\n * const User = new GraphQLObjectType({\n * name: 'User',\n * description: 'A registered user.',\n * interfaces: [Node],\n * fields: {\n * id: { type: new GraphQLNonNull(GraphQLID) },\n * name: {\n * description: 'The formatted user name.',\n * type: GraphQLString,\n * args: {\n * format: {\n * description: 'Controls the name format.',\n * type: GraphQLString,\n * defaultValue: 'short',\n * deprecationReason: 'Use locale instead.',\n * extensions: { public: true },\n * astNode: formatArg,\n * },\n * },\n * resolve: (user, { format }) => {\n * return format === 'long' ? user.fullName : user.name;\n * },\n * deprecationReason: 'Use displayName.',\n * extensions: { cacheSeconds: 60 },\n * astNode: nameField,\n * },\n * },\n * isTypeOf: (value) => {\n * return typeof value === 'object' && value != null && 'id' in value;\n * },\n * extensions: { entity: 'User' },\n * astNode: definition,\n * extensionASTNodes: [ document.definitions[1] ],\n * });\n *\n * User.name; // => 'User'\n * User.getInterfaces(); // => [Node]\n * Object.keys(User.getFields()); // => ['id', 'name']\n * User.getFields().name.args[0].defaultValue; // => 'short'\n * User.extensions; // => { entity: 'User' }\n * ```\n * @example\n * ```ts\n * // This variant configures a subscription field with subscribe and resolve functions.\n * import { GraphQLObjectType, GraphQLString } from 'graphql/type';\n *\n * const Subscription = new GraphQLObjectType({\n * name: 'Subscription',\n * fields: {\n * greeting: {\n * type: GraphQLString,\n * subscribe: async function* () {\n * yield { greeting: 'Hello!' };\n * },\n * resolve: (event) => {\n * return event.greeting;\n * },\n * },\n * },\n * });\n *\n * typeof Subscription.getFields().greeting.subscribe; // => 'function'\n * ```\n */\n constructor(config) {\n var _config$extensionASTN2;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.isTypeOf = config.isTypeOf;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN2 = config.extensionASTNodes) !== null &&\n _config$extensionASTN2 !== void 0\n ? _config$extensionASTN2\n : [];\n\n this._fields = () => defineFieldMap(config);\n\n this._interfaces = () => defineInterfaces(config);\n\n config.isTypeOf == null ||\n typeof config.isTypeOf === 'function' ||\n devAssert(\n false,\n `${this.name} must provide \"isTypeOf\" as a function, ` +\n `but got: ${inspect(config.isTypeOf)}.`,\n );\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLObjectType';\n }\n /**\n * Returns the fields defined by this type.\n * @returns The fields keyed by field name.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type User {\n * id: ID!\n * name: String\n * }\n *\n * type Query {\n * viewer: User\n * }\n * `);\n *\n * const User = assertObjectType(schema.getType('User'));\n * const fields = User.getFields();\n *\n * Object.keys(fields); // => ['id', 'name']\n * String(fields.id.type); // => 'ID!'\n * ```\n */\n\n getFields() {\n if (typeof this._fields === 'function') {\n this._fields = this._fields();\n }\n\n return this._fields;\n }\n /**\n * Returns the interfaces implemented by this type.\n * @returns The implemented interfaces.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * viewer: User\n * }\n * `);\n *\n * const User = assertObjectType(schema.getType('User'));\n *\n * User.getInterfaces().map((type) => type.name); // => ['Node']\n * ```\n */\n\n getInterfaces() {\n if (typeof this._interfaces === 'function') {\n this._interfaces = this._interfaces();\n }\n\n return this._interfaces;\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { GraphQLObjectType, GraphQLString } from 'graphql/type';\n *\n * const User = new GraphQLObjectType({\n * name: 'User',\n * fields: {\n * name: { type: GraphQLString },\n * },\n * });\n *\n * const config = User.toConfig();\n * const UserCopy = new GraphQLObjectType(config);\n *\n * config.fields.name.type; // => GraphQLString\n * UserCopy.getFields().name.type; // => GraphQLString\n * ```\n */\n\n toConfig() {\n return {\n name: this.name,\n description: this.description,\n interfaces: this.getInterfaces(),\n fields: fieldsToFieldsConfig(this.getFields()),\n isTypeOf: this.isTypeOf,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this object type.\n * @returns The schema coordinate for this object type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type User {\n * name: String\n * }\n *\n * type Query {\n * viewer: User\n * }\n * `);\n *\n * const User = assertObjectType(schema.getType('User'));\n *\n * User.toString(); // => 'User'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLObjectType, GraphQLString } from 'graphql/type';\n *\n * const User = new GraphQLObjectType({\n * name: 'User',\n * fields: { name: { type: GraphQLString } },\n * });\n *\n * User.toJSON(); // => 'User'\n * JSON.stringify({ type: User }); // => '{\"type\":\"User\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n\nfunction defineInterfaces(config) {\n var _config$interfaces;\n\n const interfaces = resolveReadonlyArrayThunk(\n (_config$interfaces = config.interfaces) !== null &&\n _config$interfaces !== void 0\n ? _config$interfaces\n : [],\n );\n Array.isArray(interfaces) ||\n devAssert(\n false,\n `${config.name} interfaces must be an Array or a function which returns an Array.`,\n );\n return interfaces;\n}\n\nfunction defineFieldMap(config) {\n const fieldMap = resolveObjMapThunk(config.fields);\n isPlainObj(fieldMap) ||\n devAssert(\n false,\n `${config.name} fields must be an object with field names as keys or a function which returns such an object.`,\n );\n return mapValue(fieldMap, (fieldConfig, fieldName) => {\n var _fieldConfig$args;\n\n isPlainObj(fieldConfig) ||\n devAssert(\n false,\n `${config.name}.${fieldName} field config must be an object.`,\n );\n fieldConfig.resolve == null ||\n typeof fieldConfig.resolve === 'function' ||\n devAssert(\n false,\n `${config.name}.${fieldName} field resolver must be a function if ` +\n `provided, but got: ${inspect(fieldConfig.resolve)}.`,\n );\n const argsConfig =\n (_fieldConfig$args = fieldConfig.args) !== null &&\n _fieldConfig$args !== void 0\n ? _fieldConfig$args\n : {};\n isPlainObj(argsConfig) ||\n devAssert(\n false,\n `${config.name}.${fieldName} args must be an object with argument names as keys.`,\n );\n return {\n name: assertName(fieldName),\n description: fieldConfig.description,\n type: fieldConfig.type,\n args: defineArguments(argsConfig),\n resolve: fieldConfig.resolve,\n subscribe: fieldConfig.subscribe,\n deprecationReason: fieldConfig.deprecationReason,\n extensions: toObjMap(fieldConfig.extensions),\n astNode: fieldConfig.astNode,\n };\n });\n}\n/** @internal */\n\nexport function defineArguments(config) {\n return Object.entries(config).map(([argName, argConfig]) => ({\n name: assertName(argName),\n description: argConfig.description,\n type: argConfig.type,\n defaultValue: argConfig.defaultValue,\n deprecationReason: argConfig.deprecationReason,\n extensions: toObjMap(argConfig.extensions),\n astNode: argConfig.astNode,\n }));\n}\n\nfunction isPlainObj(obj) {\n return isObjectLike(obj) && !Array.isArray(obj);\n}\n\nfunction fieldsToFieldsConfig(fields) {\n return mapValue(fields, (field) => ({\n description: field.description,\n type: field.type,\n args: argsToArgsConfig(field.args),\n resolve: field.resolve,\n subscribe: field.subscribe,\n deprecationReason: field.deprecationReason,\n extensions: field.extensions,\n astNode: field.astNode,\n }));\n}\n/** @internal */\n\nexport function argsToArgsConfig(args) {\n return keyValMap(\n args,\n (arg) => arg.name,\n (arg) => ({\n description: arg.description,\n type: arg.type,\n defaultValue: arg.defaultValue,\n deprecationReason: arg.deprecationReason,\n extensions: arg.extensions,\n astNode: arg.astNode,\n }),\n );\n}\n/**\n * Configuration used to construct a GraphQLObjectType.\n * @typeParam TSource - Source object type passed to resolvers.\n * @typeParam TContext - Context object type passed to resolvers.\n */\n\n/**\n * Returns true when the argument is non-null and has no default value.\n * @param arg - The argument definition to inspect.\n * @returns True when the argument is non-null and has no default value.\n * @example\n * ```ts\n * import {\n * GraphQLInt,\n * GraphQLNonNull,\n * GraphQLString,\n * isRequiredArgument,\n * } from 'graphql/type';\n *\n * const requiredArgument = { name: 'id', type: new GraphQLNonNull(GraphQLInt) };\n * const optionalArgument = { name: 'name', type: GraphQLString };\n * const argumentWithDefault = {\n * name: 'limit',\n * type: new GraphQLNonNull(GraphQLInt),\n * defaultValue: 10,\n * };\n *\n * isRequiredArgument(requiredArgument); // => true\n * isRequiredArgument(optionalArgument); // => false\n * isRequiredArgument(argumentWithDefault); // => false\n * ```\n */\nexport function isRequiredArgument(arg) {\n return isNonNullType(arg.type) && arg.defaultValue === undefined;\n}\n/**\n * A map of field names to resolved field definitions.\n * @typeParam TSource - Source object type passed to resolvers.\n * @typeParam TContext - Context object type passed to resolvers.\n */\n\n/**\n * Interface Type Definition\n *\n * When a field can return one of a heterogeneous set of types, a Interface type\n * is used to describe what types are possible, what fields are in common across\n * all types, as well as a function to determine which type is actually used\n * when the field is resolved.\n * @example\n * ```ts\n * const EntityType = new GraphQLInterfaceType({\n * name: 'Entity',\n * fields: {\n * name: { type: GraphQLString }\n * }\n * });\n * ```\n */\nexport class GraphQLInterfaceType {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Function that resolves the concrete object type for this abstract type. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLInterfaceType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type';\n *\n * const document = parse(`\n * interface Node {\n * id: ID!\n * }\n *\n * interface Resource implements Node {\n * id: ID!\n * }\n *\n * extend interface Resource {\n * url: String\n * }\n * `);\n *\n * const Node = new GraphQLInterfaceType({\n * name: 'Node',\n * fields: {\n * id: { type: new GraphQLNonNull(GraphQLID) },\n * },\n * });\n *\n * const Resource = new GraphQLInterfaceType({\n * name: 'Resource',\n * description: 'An addressable resource.',\n * interfaces: [Node],\n * fields: {\n * id: { type: new GraphQLNonNull(GraphQLID) },\n * },\n * resolveType: (value) => {\n * return typeof value === 'object' && value != null && 'url' in value\n * ? 'WebPage'\n * : null;\n * },\n * extensions: { abstract: true },\n * astNode: document.definitions[1],\n * extensionASTNodes: [ document.definitions[2] ],\n * });\n *\n * Resource.name; // => 'Resource'\n * Resource.getInterfaces(); // => [Node]\n * Object.keys(Resource.getFields()); // => ['id']\n * Resource.extensions; // => { abstract: true }\n * ```\n */\n constructor(config) {\n var _config$extensionASTN3;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.resolveType = config.resolveType;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN3 = config.extensionASTNodes) !== null &&\n _config$extensionASTN3 !== void 0\n ? _config$extensionASTN3\n : [];\n this._fields = defineFieldMap.bind(undefined, config);\n this._interfaces = defineInterfaces.bind(undefined, config);\n config.resolveType == null ||\n typeof config.resolveType === 'function' ||\n devAssert(\n false,\n `${this.name} must provide \"resolveType\" as a function, ` +\n `but got: ${inspect(config.resolveType)}.`,\n );\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLInterfaceType';\n }\n /**\n * Returns the fields defined by this type.\n * @returns The fields keyed by field name.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * const Node = assertInterfaceType(schema.getType('Node'));\n * const fields = Node.getFields();\n *\n * Object.keys(fields); // => ['id']\n * String(fields.id.type); // => 'ID!'\n * ```\n */\n\n getFields() {\n if (typeof this._fields === 'function') {\n this._fields = this._fields();\n }\n\n return this._fields;\n }\n /**\n * Returns the interfaces implemented by this type.\n * @returns The implemented interfaces.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Resource {\n * url: String!\n * }\n *\n * interface Image implements Resource {\n * url: String!\n * width: Int\n * }\n *\n * type Photo implements Resource & Image {\n * url: String!\n * width: Int\n * }\n *\n * type Query {\n * image: Image\n * }\n * `);\n *\n * const Image = assertInterfaceType(schema.getType('Image'));\n *\n * Image.getInterfaces().map((type) => type.name); // => ['Resource']\n * ```\n */\n\n getInterfaces() {\n if (typeof this._interfaces === 'function') {\n this._interfaces = this._interfaces();\n }\n\n return this._interfaces;\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type';\n *\n * const Node = new GraphQLInterfaceType({\n * name: 'Node',\n * fields: {\n * id: { type: new GraphQLNonNull(GraphQLID) },\n * },\n * });\n *\n * const config = Node.toConfig();\n * const NodeCopy = new GraphQLInterfaceType(config);\n *\n * String(config.fields.id.type); // => 'ID!'\n * String(NodeCopy.getFields().id.type); // => 'ID!'\n * ```\n */\n\n toConfig() {\n return {\n name: this.name,\n description: this.description,\n interfaces: this.getInterfaces(),\n fields: fieldsToFieldsConfig(this.getFields()),\n resolveType: this.resolveType,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this interface type.\n * @returns The schema coordinate for this interface type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n *\n * const Node = assertInterfaceType(schema.getType('Node'));\n *\n * Node.toString(); // => 'Node'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLInterfaceType, GraphQLString } from 'graphql/type';\n *\n * const Named = new GraphQLInterfaceType({\n * name: 'Named',\n * fields: { name: { type: GraphQLString } },\n * });\n *\n * Named.toJSON(); // => 'Named'\n * JSON.stringify({ type: Named }); // => '{\"type\":\"Named\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n/**\n * Configuration used to construct a GraphQLInterfaceType.\n * @typeParam TSource - Source object type passed to resolvers.\n * @typeParam TContext - Context object type passed to resolvers.\n */\n\n/**\n * Union Type Definition\n *\n * When a field can return one of a heterogeneous set of types, a Union type\n * is used to describe what types are possible as well as providing a function\n * to determine which type is actually used when the field is resolved.\n * @example\n * ```ts\n * const PetType = new GraphQLUnionType({\n * name: 'Pet',\n * types: [DogType, CatType],\n * resolveType: (value) => {\n * if (value instanceof Dog) {\n * return DogType;\n * }\n * if (value instanceof Cat) {\n * return CatType;\n * }\n * }\n * });\n * ```\n */\nexport class GraphQLUnionType {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Function that resolves the concrete object type for this abstract type. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLUnionType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';\n *\n * const document = parse(`\n * union Media = Photo | Video\n *\n * extend union Media = Audio\n * `);\n *\n * const Photo = new GraphQLObjectType({\n * name: 'Photo',\n * fields: { url: { type: GraphQLString } },\n * });\n * const Video = new GraphQLObjectType({\n * name: 'Video',\n * fields: { url: { type: GraphQLString } },\n * });\n *\n * const Media = new GraphQLUnionType({\n * name: 'Media',\n * description: 'Media that can appear in a search result.',\n * types: [Photo, Video],\n * resolveType: (value) => {\n * return typeof value === 'object' && value != null && 'duration' in value\n * ? 'Video'\n * : 'Photo';\n * },\n * extensions: { searchable: true },\n * astNode: document.definitions[0],\n * extensionASTNodes: [ document.definitions[1] ],\n * });\n *\n * Media.description; // => 'Media that can appear in a search result.'\n * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video']\n * Media.extensions; // => { searchable: true }\n * ```\n */\n constructor(config) {\n var _config$extensionASTN4;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.resolveType = config.resolveType;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN4 = config.extensionASTNodes) !== null &&\n _config$extensionASTN4 !== void 0\n ? _config$extensionASTN4\n : [];\n this._types = defineTypes.bind(undefined, config);\n config.resolveType == null ||\n typeof config.resolveType === 'function' ||\n devAssert(\n false,\n `${this.name} must provide \"resolveType\" as a function, ` +\n `but got: ${inspect(config.resolveType)}.`,\n );\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLUnionType';\n }\n /**\n * Returns the object types included in this union.\n * @returns The union member object types.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertUnionType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Photo {\n * url: String!\n * }\n *\n * type Video {\n * url: String!\n * }\n *\n * union Media = Photo | Video\n *\n * type Query {\n * media: [Media]\n * }\n * `);\n *\n * const Media = assertUnionType(schema.getType('Media'));\n *\n * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video']\n * ```\n */\n\n getTypes() {\n if (typeof this._types === 'function') {\n this._types = this._types();\n }\n\n return this._types;\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';\n *\n * const Photo = new GraphQLObjectType({\n * name: 'Photo',\n * fields: { url: { type: GraphQLString } },\n * });\n * const Video = new GraphQLObjectType({\n * name: 'Video',\n * fields: { url: { type: GraphQLString } },\n * });\n * const Media = new GraphQLUnionType({\n * name: 'Media',\n * types: [Photo, Video],\n * });\n *\n * const config = Media.toConfig();\n * const MediaCopy = new GraphQLUnionType(config);\n *\n * MediaCopy.getTypes().map((type) => type.name); // => ['Photo', 'Video']\n * ```\n */\n\n toConfig() {\n return {\n name: this.name,\n description: this.description,\n types: this.getTypes(),\n resolveType: this.resolveType,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this union type.\n * @returns The schema coordinate for this union type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertUnionType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Photo {\n * url: String!\n * }\n *\n * union SearchResult = Photo\n *\n * type Query {\n * search: [SearchResult]\n * }\n * `);\n *\n * const SearchResult = assertUnionType(schema.getType('SearchResult'));\n *\n * SearchResult.toString(); // => 'SearchResult'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type';\n *\n * const Photo = new GraphQLObjectType({\n * name: 'Photo',\n * fields: { url: { type: GraphQLString } },\n * });\n * const SearchResult = new GraphQLUnionType({\n * name: 'SearchResult',\n * types: [Photo],\n * });\n *\n * SearchResult.toJSON(); // => 'SearchResult'\n * JSON.stringify({ type: SearchResult }); // => '{\"type\":\"SearchResult\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n\nfunction defineTypes(config) {\n const types = resolveReadonlyArrayThunk(config.types);\n Array.isArray(types) ||\n devAssert(\n false,\n `Must provide Array of types or a function which returns such an array for Union ${config.name}.`,\n );\n return types;\n}\n/**\n * Configuration used to construct a GraphQLUnionType.\n * @typeParam TSource - Source object type passed to resolvers.\n * @typeParam TContext - Context object type passed to resolvers.\n */\n\n/**\n * Enum Type Definition\n *\n * Enum types define leaf values whose serialized form is one of a fixed set\n * of GraphQL enum names. Internally, enum values can map to any runtime value,\n * often integers.\n * @example\n * ```ts\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const RGBType = new GraphQLEnumType({\n * name: 'RGB',\n * values: {\n * RED: { value: 0 },\n * GREEN: { value: 1 },\n * BLUE: { value: 2 },\n * },\n * });\n *\n * RGBType.getValue('GREEN')?.value; // => 1\n * ```\n *\n * Note: If a value is not provided in a definition, the name of the enum value\n * will be used as its internal value.\n */\nexport class GraphQLEnumType {\n /* <T> */\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLEnumType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const document = parse(`\n * enum Episode {\n * NEW_HOPE\n * EMPIRE\n * JEDI\n * }\n *\n * extend enum Episode {\n * FORCE_AWAKENS\n * }\n * `);\n * const definition = document.definitions[0];\n *\n * const Episode = new GraphQLEnumType({\n * name: 'Episode',\n * description: 'A Star Wars film episode.',\n * values: {\n * NEW_HOPE: {\n * value: 4,\n * description: 'Released in 1977.',\n * extensions: { trilogy: 'original' },\n * astNode: definition.values[0],\n * },\n * EMPIRE: { value: 5, astNode: definition.values[1] },\n * JEDI: {\n * value: 6,\n * deprecationReason: 'Use RETURN_OF_THE_JEDI.',\n * astNode: definition.values[2],\n * },\n * },\n * extensions: { catalog: 'films' },\n * astNode: definition,\n * extensionASTNodes: [ document.definitions[1] ],\n * });\n *\n * Episode.description; // => 'A Star Wars film episode.'\n * Episode.serialize(5); // => 'EMPIRE'\n * Episode.parseValue('JEDI'); // => 6\n * Episode.getValue('JEDI').deprecationReason; // => 'Use RETURN_OF_THE_JEDI.'\n * Episode.extensions; // => { catalog: 'films' }\n * ```\n */\n constructor(config) {\n var _config$extensionASTN5;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN5 = config.extensionASTNodes) !== null &&\n _config$extensionASTN5 !== void 0\n ? _config$extensionASTN5\n : [];\n this._values =\n typeof config.values === 'function'\n ? config.values\n : defineEnumValues(this.name, config.values);\n this._valueLookup = null;\n this._nameLookup = null;\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLEnumType';\n }\n /**\n * Returns the values defined by this enum type.\n * @returns Enum value definitions in schema order.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertEnumType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * EMPIRE\n * JEDI\n * }\n *\n * type Query {\n * episode: Episode\n * }\n * `);\n *\n * const Episode = assertEnumType(schema.getType('Episode'));\n *\n * Episode.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE', 'JEDI']\n * ```\n */\n\n getValues() {\n if (typeof this._values === 'function') {\n this._values = defineEnumValues(this.name, this._values());\n }\n\n return this._values;\n }\n /**\n * Returns the enum value definition for a value name.\n * @param name - The GraphQL name to look up.\n * @returns The matching enum value definition, if it exists.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertEnumType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * EMPIRE\n * }\n *\n * type Query {\n * episode: Episode\n * }\n * `);\n *\n * const Episode = assertEnumType(schema.getType('Episode'));\n *\n * Episode.getValue('EMPIRE')?.name; // => 'EMPIRE'\n * Episode.getValue('JEDI'); // => undefined\n * ```\n */\n\n getValue(name) {\n if (this._nameLookup === null) {\n this._nameLookup = keyMap(this.getValues(), (value) => value.name);\n }\n\n return this._nameLookup[name];\n }\n /**\n * Serializes a runtime enum value as a GraphQL enum name.\n * @param outputValue - Runtime enum value to serialize.\n * @returns The GraphQL enum name for the runtime value.\n * @example\n * ```ts\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const RGB = new GraphQLEnumType({\n * name: 'RGB',\n * values: {\n * RED: { value: 0 },\n * GREEN: { value: 1 },\n * BLUE: { value: 2 },\n * },\n * });\n *\n * RGB.serialize(1); // => 'GREEN'\n * RGB.serialize(3); // throws an error\n * ```\n */\n\n serialize(outputValue) {\n if (this._valueLookup === null) {\n this._valueLookup = new Map(\n this.getValues().map((enumValue) => [enumValue.value, enumValue]),\n );\n }\n\n const enumValue = this._valueLookup.get(outputValue);\n\n if (enumValue === undefined) {\n throw new GraphQLError(\n `Enum \"${this.name}\" cannot represent value: ${inspect(outputValue)}`,\n );\n }\n\n return enumValue.name;\n }\n /**\n * Parses a GraphQL enum name from variable input.\n * @param inputValue - Runtime input value to parse.\n * @returns The internal enum value represented by the input name.\n * @example\n * ```ts\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const RGB = new GraphQLEnumType({\n * name: 'RGB',\n * values: {\n * RED: { value: 0 },\n * GREEN: { value: 1 },\n * BLUE: { value: 2 },\n * },\n * });\n *\n * RGB.parseValue('BLUE'); // => 2\n * RGB.parseValue('PURPLE'); // throws an error\n * RGB.parseValue(2); // throws an error\n * ```\n */\n\n parseValue(inputValue) /* T */\n {\n if (typeof inputValue !== 'string') {\n const valueStr = inspect(inputValue);\n throw new GraphQLError(\n `Enum \"${this.name}\" cannot represent non-string value: ${valueStr}.` +\n didYouMeanEnumValue(this, valueStr),\n );\n }\n\n const enumValue = this.getValue(inputValue);\n\n if (enumValue == null) {\n throw new GraphQLError(\n `Value \"${inputValue}\" does not exist in \"${this.name}\" enum.` +\n didYouMeanEnumValue(this, inputValue),\n );\n }\n\n return enumValue.value;\n }\n /**\n * Parses a GraphQL enum name from an AST value literal.\n * @param valueNode - AST value literal to parse.\n * @param _variables - Runtime variable values; ignored because enum literals cannot contain variables.\n * @returns The internal enum value represented by the literal.\n * @example\n * ```ts\n * import { parseValue } from 'graphql/language';\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const RGB = new GraphQLEnumType({\n * name: 'RGB',\n * values: {\n * RED: { value: 0 },\n * GREEN: { value: 1 },\n * BLUE: { value: 2 },\n * },\n * });\n *\n * RGB.parseLiteral(parseValue('RED')); // => 0\n * RGB.parseLiteral(parseValue('\"RED\"')); // throws an error\n * ```\n */\n\n parseLiteral(valueNode, _variables) /* T */\n {\n // Note: variables will be resolved to a value before calling this function.\n if (valueNode.kind !== Kind.ENUM) {\n const valueStr = print(valueNode);\n throw new GraphQLError(\n `Enum \"${this.name}\" cannot represent non-enum value: ${valueStr}.` +\n didYouMeanEnumValue(this, valueStr),\n {\n nodes: valueNode,\n },\n );\n }\n\n const enumValue = this.getValue(valueNode.value);\n\n if (enumValue == null) {\n const valueStr = print(valueNode);\n throw new GraphQLError(\n `Value \"${valueStr}\" does not exist in \"${this.name}\" enum.` +\n didYouMeanEnumValue(this, valueStr),\n {\n nodes: valueNode,\n },\n );\n }\n\n return enumValue.value;\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const RGB = new GraphQLEnumType({\n * name: 'RGB',\n * values: {\n * RED: { value: 0 },\n * GREEN: { value: 1 },\n * BLUE: { value: 2 },\n * },\n * });\n *\n * const config = RGB.toConfig();\n * const RGBCopy = new GraphQLEnumType(config);\n *\n * config.values.GREEN.value; // => 1\n * RGBCopy.serialize(2); // => 'BLUE'\n * ```\n */\n\n toConfig() {\n const values = keyValMap(\n this.getValues(),\n (value) => value.name,\n (value) => ({\n description: value.description,\n value: value.value,\n deprecationReason: value.deprecationReason,\n extensions: value.extensions,\n astNode: value.astNode,\n }),\n );\n return {\n name: this.name,\n description: this.description,\n values,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this enum type.\n * @returns The schema coordinate for this enum type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertEnumType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * enum Episode {\n * NEW_HOPE\n * }\n *\n * type Query {\n * episode: Episode\n * }\n * `);\n *\n * const Episode = assertEnumType(schema.getType('Episode'));\n *\n * Episode.toString(); // => 'Episode'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLEnumType } from 'graphql/type';\n *\n * const Episode = new GraphQLEnumType({\n * name: 'Episode',\n * values: {\n * NEW_HOPE: {},\n * },\n * });\n *\n * Episode.toJSON(); // => 'Episode'\n * JSON.stringify({ type: Episode }); // => '{\"type\":\"Episode\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n\nfunction didYouMeanEnumValue(enumType, unknownValueStr) {\n const allNames = enumType.getValues().map((value) => value.name);\n const suggestedValues = suggestionList(unknownValueStr, allNames);\n return didYouMean('the enum value', suggestedValues);\n}\n\nfunction defineEnumValues(typeName, valueMap) {\n isPlainObj(valueMap) ||\n devAssert(\n false,\n `${typeName} values must be an object with value names as keys.`,\n );\n return Object.entries(valueMap).map(([valueName, valueConfig]) => {\n isPlainObj(valueConfig) ||\n devAssert(\n false,\n `${typeName}.${valueName} must refer to an object with a \"value\" key ` +\n `representing an internal value but got: ${inspect(valueConfig)}.`,\n );\n return {\n name: assertEnumValueName(valueName),\n description: valueConfig.description,\n value: valueConfig.value !== undefined ? valueConfig.value : valueName,\n deprecationReason: valueConfig.deprecationReason,\n extensions: toObjMap(valueConfig.extensions),\n astNode: valueConfig.astNode,\n };\n });\n}\n/** Configuration used to construct a GraphQLEnumType. */\n\n/**\n * Input Object Type Definition\n *\n * An input object defines a structured collection of fields which may be\n * supplied to a field argument.\n *\n * Using `NonNull` will ensure that a value must be provided by the query\n * @example\n * ```ts\n * const GeoPoint = new GraphQLInputObjectType({\n * name: 'GeoPoint',\n * fields: {\n * lat: { type: new GraphQLNonNull(GraphQLFloat) },\n * lon: { type: new GraphQLNonNull(GraphQLFloat) },\n * alt: { type: GraphQLFloat, defaultValue: 0 },\n * }\n * });\n * ```\n */\nexport class GraphQLInputObjectType {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /** Whether this input object uses the experimental OneOf input object semantics. */\n\n /**\n * Creates a GraphQLInputObjectType instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import {\n * GraphQLID,\n * GraphQLInputObjectType,\n * GraphQLInt,\n * GraphQLNonNull,\n * GraphQLString,\n * } from 'graphql/type';\n *\n * const document = parse(`\n * input ReviewInput {\n * stars: Int!\n * commentary: String\n * }\n *\n * extend input ReviewInput {\n * body: String\n * }\n * `);\n * const definition = document.definitions[0];\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * description: 'Input collected when reviewing a product.',\n * fields: {\n * stars: {\n * description: 'Star rating from one to five.',\n * type: new GraphQLNonNull(GraphQLInt),\n * extensions: { min: 1, max: 5 },\n * astNode: definition.fields[0],\n * },\n * commentary: {\n * type: GraphQLString,\n * defaultValue: '',\n * deprecationReason: 'Use body.',\n * astNode: definition.fields[1],\n * },\n * },\n * extensions: { form: 'review' },\n * astNode: definition,\n * extensionASTNodes: [ document.definitions[1] ],\n * isOneOf: false,\n * });\n * const SearchBy = new GraphQLInputObjectType({\n * name: 'SearchBy',\n * fields: {\n * id: { type: GraphQLID },\n * slug: { type: GraphQLString },\n * },\n * isOneOf: true,\n * });\n *\n * const fields = ReviewInput.getFields();\n *\n * ReviewInput.description; // => 'Input collected when reviewing a product.'\n * String(fields.stars.type); // => 'Int!'\n * fields.stars.extensions; // => { min: 1, max: 5 }\n * fields.commentary.defaultValue; // => ''\n * fields.commentary.deprecationReason; // => 'Use body.'\n * ReviewInput.isOneOf; // => false\n * SearchBy.isOneOf; // => true\n * ```\n */\n constructor(config) {\n var _config$extensionASTN6, _config$isOneOf;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN6 = config.extensionASTNodes) !== null &&\n _config$extensionASTN6 !== void 0\n ? _config$extensionASTN6\n : [];\n this.isOneOf =\n (_config$isOneOf = config.isOneOf) !== null && _config$isOneOf !== void 0\n ? _config$isOneOf\n : false;\n this._fields = defineInputFieldMap.bind(undefined, config);\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLInputObjectType';\n }\n /**\n * Returns the fields defined by this type.\n * @returns The fields keyed by field name.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInputObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * commentary: String = \"\"\n * }\n *\n * type Query {\n * reviews(filter: ReviewInput): [String]\n * }\n * `);\n *\n * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput'));\n * const fields = ReviewInput.getFields();\n *\n * Object.keys(fields); // => ['stars', 'commentary']\n * fields.commentary.defaultValue; // => ''\n * ```\n */\n\n getFields() {\n if (typeof this._fields === 'function') {\n this._fields = this._fields();\n }\n\n return this._fields;\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import {\n * GraphQLInputObjectType,\n * GraphQLInt,\n * GraphQLNonNull,\n * } from 'graphql/type';\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * fields: {\n * stars: { type: new GraphQLNonNull(GraphQLInt) },\n * },\n * });\n *\n * const config = ReviewInput.toConfig();\n * const ReviewInputCopy = new GraphQLInputObjectType(config);\n *\n * String(config.fields.stars.type); // => 'Int!'\n * String(ReviewInputCopy.getFields().stars.type); // => 'Int!'\n * ```\n */\n\n toConfig() {\n const fields = mapValue(this.getFields(), (field) => ({\n description: field.description,\n type: field.type,\n defaultValue: field.defaultValue,\n deprecationReason: field.deprecationReason,\n extensions: field.extensions,\n astNode: field.astNode,\n }));\n return {\n name: this.name,\n description: this.description,\n fields,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n isOneOf: this.isOneOf,\n };\n }\n /**\n * Returns the schema coordinate identifying this input object type.\n * @returns The schema coordinate for this input object type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInputObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Query {\n * reviews(filter: ReviewInput): [String]\n * }\n * `);\n *\n * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput'));\n *\n * ReviewInput.toString(); // => 'ReviewInput'\n * ```\n */\n\n toString() {\n return this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { GraphQLInputObjectType, GraphQLString } from 'graphql/type';\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * fields: {\n * commentary: { type: GraphQLString },\n * },\n * });\n *\n * ReviewInput.toJSON(); // => 'ReviewInput'\n * JSON.stringify({ type: ReviewInput }); // => '{\"type\":\"ReviewInput\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n\nfunction defineInputFieldMap(config) {\n const fieldMap = resolveObjMapThunk(config.fields);\n isPlainObj(fieldMap) ||\n devAssert(\n false,\n `${config.name} fields must be an object with field names as keys or a function which returns such an object.`,\n );\n return mapValue(fieldMap, (fieldConfig, fieldName) => {\n !('resolve' in fieldConfig) ||\n devAssert(\n false,\n `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`,\n );\n return {\n name: assertName(fieldName),\n description: fieldConfig.description,\n type: fieldConfig.type,\n defaultValue: fieldConfig.defaultValue,\n deprecationReason: fieldConfig.deprecationReason,\n extensions: toObjMap(fieldConfig.extensions),\n astNode: fieldConfig.astNode,\n };\n });\n}\n/** Configuration used to construct a GraphQLInputObjectType. */\n\n/**\n * Returns true when the input field is non-null and has no default value.\n * @param field - The input field definition to inspect.\n * @returns True when the input field is non-null and has no default value.\n * @example\n * ```ts\n * import {\n * GraphQLInt,\n * GraphQLNonNull,\n * GraphQLString,\n * isRequiredInputField,\n * } from 'graphql/type';\n *\n * const requiredField = { name: 'id', type: new GraphQLNonNull(GraphQLInt) };\n * const optionalField = { name: 'name', type: GraphQLString };\n * const fieldWithDefault = {\n * name: 'limit',\n * type: new GraphQLNonNull(GraphQLInt),\n * defaultValue: 10,\n * };\n *\n * isRequiredInputField(requiredField); // => true\n * isRequiredInputField(optionalField); // => false\n * isRequiredInputField(fieldWithDefault); // => false\n * ```\n */\nexport function isRequiredInputField(field) {\n return isNonNullType(field.type) && field.defaultValue === undefined;\n}\n/** A map of input field names to resolved input field definitions. */\n","/** @category Type Comparisons */\nimport {\n isAbstractType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n} from '../type/definition.mjs';\n\n/**\n * Provided two types, return true if the types are equal (invariant).\n * @param typeA - The first GraphQL type to compare.\n * @param typeB - The second GraphQL type to compare.\n * @returns True when both types are equal.\n * @example\n * ```ts\n * import {\n * GraphQLList,\n * GraphQLNonNull,\n * GraphQLString,\n * } from 'graphql/type';\n * import { isEqualType } from 'graphql/utilities';\n *\n * isEqualType(GraphQLString, GraphQLString); // => true\n * isEqualType(new GraphQLList(GraphQLString), new GraphQLList(GraphQLString)); // => true\n * isEqualType(new GraphQLNonNull(GraphQLString), GraphQLString); // => false\n * ```\n */\nexport function isEqualType(typeA, typeB) {\n // Equivalent types are equal.\n if (typeA === typeB) {\n return true;\n } // If either type is non-null, the other must also be non-null.\n\n if (isNonNullType(typeA) && isNonNullType(typeB)) {\n return isEqualType(typeA.ofType, typeB.ofType);\n } // If either type is a list, the other must also be a list.\n\n if (isListType(typeA) && isListType(typeB)) {\n return isEqualType(typeA.ofType, typeB.ofType);\n } // Otherwise the types are not equal.\n\n return false;\n}\n/**\n * Provided a type and a super type, return true if the first type is either\n * equal or a subset of the second super type (covariant).\n * @param schema - GraphQL schema to use.\n * @param maybeSubType - The possible subtype to compare.\n * @param superType - The possible supertype to compare.\n * @returns True when `maybeSubType` is equal to or a subtype of `superType`.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import {\n * GraphQLNonNull,\n * assertInterfaceType,\n * assertObjectType,\n * } from 'graphql/type';\n * import { isTypeSubTypeOf } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Query {\n * node: Node\n * }\n * `);\n * const Node = assertInterfaceType(schema.getType('Node'));\n * const User = assertObjectType(schema.getType('User'));\n *\n * isTypeSubTypeOf(schema, User, Node); // => true\n * isTypeSubTypeOf(schema, new GraphQLNonNull(User), Node); // => true\n * isTypeSubTypeOf(schema, Node, User); // => false\n * ```\n */\n\nexport function isTypeSubTypeOf(schema, maybeSubType, superType) {\n // Equivalent type is a valid subtype\n if (maybeSubType === superType) {\n return true;\n } // If superType is non-null, maybeSubType must also be non-null.\n\n if (isNonNullType(superType)) {\n if (isNonNullType(maybeSubType)) {\n return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);\n }\n\n return false;\n }\n\n if (isNonNullType(maybeSubType)) {\n // If superType is nullable, maybeSubType may be non-null or nullable.\n return isTypeSubTypeOf(schema, maybeSubType.ofType, superType);\n } // If superType type is a list, maybeSubType type must also be a list.\n\n if (isListType(superType)) {\n if (isListType(maybeSubType)) {\n return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType);\n }\n\n return false;\n }\n\n if (isListType(maybeSubType)) {\n // If superType is not a list, maybeSubType must also be not a list.\n return false;\n } // If superType type is an abstract type, check if it is super type of maybeSubType.\n // Otherwise, the child type is not a valid subtype of the parent type.\n\n return (\n isAbstractType(superType) &&\n (isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) &&\n schema.isSubType(superType, maybeSubType)\n );\n}\n/**\n * Provided two composite types, determine if they \"overlap\". Two composite\n * types overlap when the Sets of possible concrete types for each intersect.\n *\n * This is often used to determine if a fragment of a given type could possibly\n * be visited in a context of another type.\n *\n * This function is commutative.\n * @param schema - GraphQL schema to use.\n * @param typeA - The first GraphQL type to compare.\n * @param typeB - The second GraphQL type to compare.\n * @returns True when the two composite types can apply to at least one common object type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertObjectType, assertUnionType } from 'graphql/type';\n * import { doTypesOverlap } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Photo {\n * url: String!\n * }\n *\n * type Video {\n * url: String!\n * }\n *\n * union Media = Photo | Video\n * union StillImage = Photo\n *\n * type Query {\n * media: [Media]\n * }\n * `);\n * const Media = assertUnionType(schema.getType('Media'));\n * const StillImage = assertUnionType(schema.getType('StillImage'));\n * const Video = assertObjectType(schema.getType('Video'));\n *\n * doTypesOverlap(schema, Media, StillImage); // => true\n * doTypesOverlap(schema, StillImage, Video); // => false\n * ```\n */\n\nexport function doTypesOverlap(schema, typeA, typeB) {\n // Equivalent types overlap\n if (typeA === typeB) {\n return true;\n }\n\n if (isAbstractType(typeA)) {\n if (isAbstractType(typeB)) {\n // If both types are abstract, then determine if there is any intersection\n // between possible concrete types of each.\n return schema\n .getPossibleTypes(typeA)\n .some((type) => schema.isSubType(typeB, type));\n } // Determine if the latter type is a possible concrete type of the former.\n\n return schema.isSubType(typeA, typeB);\n }\n\n if (isAbstractType(typeB)) {\n // Determine if the former type is a possible concrete type of the latter.\n return schema.isSubType(typeB, typeA);\n } // Otherwise the types do not overlap.\n\n return false;\n}\n","/** @category Scalars */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { print } from '../language/printer.mjs';\nimport { GraphQLScalarType } from './definition.mjs';\n/**\n * Maximum possible Int value as per GraphQL Spec (32-bit signed integer).\n * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1\n */\n\nexport const GRAPHQL_MAX_INT = 2147483647;\n/**\n * Minimum possible Int value as per GraphQL Spec (32-bit signed integer).\n * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1)\n */\n\nexport const GRAPHQL_MIN_INT = -2147483648;\n/** The built-in `Int` scalar type. */\n\nexport const GraphQLInt = new GraphQLScalarType({\n name: 'Int',\n description:\n 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.',\n\n serialize(outputValue) {\n const coercedValue = serializeObject(outputValue);\n\n if (typeof coercedValue === 'boolean') {\n return coercedValue ? 1 : 0;\n }\n\n let num = coercedValue;\n\n if (typeof coercedValue === 'string' && coercedValue !== '') {\n num = Number(coercedValue);\n }\n\n if (typeof num !== 'number' || !Number.isInteger(num)) {\n throw new GraphQLError(\n `Int cannot represent non-integer value: ${inspect(coercedValue)}`,\n );\n }\n\n if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) {\n throw new GraphQLError(\n 'Int cannot represent non 32-bit signed integer value: ' +\n inspect(coercedValue),\n );\n }\n\n return num;\n },\n\n parseValue(inputValue) {\n if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) {\n throw new GraphQLError(\n `Int cannot represent non-integer value: ${inspect(inputValue)}`,\n );\n }\n\n if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) {\n throw new GraphQLError(\n `Int cannot represent non 32-bit signed integer value: ${inputValue}`,\n );\n }\n\n return inputValue;\n },\n\n parseLiteral(valueNode) {\n if (valueNode.kind !== Kind.INT) {\n throw new GraphQLError(\n `Int cannot represent non-integer value: ${print(valueNode)}`,\n {\n nodes: valueNode,\n },\n );\n }\n\n const num = parseInt(valueNode.value, 10);\n\n if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) {\n throw new GraphQLError(\n `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`,\n {\n nodes: valueNode,\n },\n );\n }\n\n return num;\n },\n});\n/** The built-in `Float` scalar type. */\n\nexport const GraphQLFloat = new GraphQLScalarType({\n name: 'Float',\n description:\n 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).',\n\n serialize(outputValue) {\n const coercedValue = serializeObject(outputValue);\n\n if (typeof coercedValue === 'boolean') {\n return coercedValue ? 1 : 0;\n }\n\n let num = coercedValue;\n\n if (typeof coercedValue === 'string' && coercedValue !== '') {\n num = Number(coercedValue);\n }\n\n if (typeof num !== 'number' || !Number.isFinite(num)) {\n throw new GraphQLError(\n `Float cannot represent non numeric value: ${inspect(coercedValue)}`,\n );\n }\n\n return num;\n },\n\n parseValue(inputValue) {\n if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) {\n throw new GraphQLError(\n `Float cannot represent non numeric value: ${inspect(inputValue)}`,\n );\n }\n\n return inputValue;\n },\n\n parseLiteral(valueNode) {\n if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) {\n throw new GraphQLError(\n `Float cannot represent non numeric value: ${print(valueNode)}`,\n valueNode,\n );\n }\n\n return parseFloat(valueNode.value);\n },\n});\n/** The built-in `String` scalar type. */\n\nexport const GraphQLString = new GraphQLScalarType({\n name: 'String',\n description:\n 'The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.',\n\n serialize(outputValue) {\n const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not\n // attempt to coerce object, function, symbol, or other types as strings.\n\n if (typeof coercedValue === 'string') {\n return coercedValue;\n }\n\n if (typeof coercedValue === 'boolean') {\n return coercedValue ? 'true' : 'false';\n }\n\n if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) {\n return coercedValue.toString();\n }\n\n throw new GraphQLError(\n `String cannot represent value: ${inspect(outputValue)}`,\n );\n },\n\n parseValue(inputValue) {\n if (typeof inputValue !== 'string') {\n throw new GraphQLError(\n `String cannot represent a non string value: ${inspect(inputValue)}`,\n );\n }\n\n return inputValue;\n },\n\n parseLiteral(valueNode) {\n if (valueNode.kind !== Kind.STRING) {\n throw new GraphQLError(\n `String cannot represent a non string value: ${print(valueNode)}`,\n {\n nodes: valueNode,\n },\n );\n }\n\n return valueNode.value;\n },\n});\n/** The built-in `Boolean` scalar type. */\n\nexport const GraphQLBoolean = new GraphQLScalarType({\n name: 'Boolean',\n description: 'The `Boolean` scalar type represents `true` or `false`.',\n\n serialize(outputValue) {\n const coercedValue = serializeObject(outputValue);\n\n if (typeof coercedValue === 'boolean') {\n return coercedValue;\n }\n\n if (Number.isFinite(coercedValue)) {\n return coercedValue !== 0;\n }\n\n throw new GraphQLError(\n `Boolean cannot represent a non boolean value: ${inspect(coercedValue)}`,\n );\n },\n\n parseValue(inputValue) {\n if (typeof inputValue !== 'boolean') {\n throw new GraphQLError(\n `Boolean cannot represent a non boolean value: ${inspect(inputValue)}`,\n );\n }\n\n return inputValue;\n },\n\n parseLiteral(valueNode) {\n if (valueNode.kind !== Kind.BOOLEAN) {\n throw new GraphQLError(\n `Boolean cannot represent a non boolean value: ${print(valueNode)}`,\n {\n nodes: valueNode,\n },\n );\n }\n\n return valueNode.value;\n },\n});\n/** The built-in `ID` scalar type. */\n\nexport const GraphQLID = new GraphQLScalarType({\n name: 'ID',\n description:\n 'The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\"4\"`) or integer (such as `4`) input value will be accepted as an ID.',\n\n serialize(outputValue) {\n const coercedValue = serializeObject(outputValue);\n\n if (typeof coercedValue === 'string') {\n return coercedValue;\n }\n\n if (Number.isInteger(coercedValue)) {\n return String(coercedValue);\n }\n\n throw new GraphQLError(\n `ID cannot represent value: ${inspect(outputValue)}`,\n );\n },\n\n parseValue(inputValue) {\n if (typeof inputValue === 'string') {\n return inputValue;\n }\n\n if (typeof inputValue === 'number' && Number.isInteger(inputValue)) {\n return inputValue.toString();\n }\n\n throw new GraphQLError(`ID cannot represent value: ${inspect(inputValue)}`);\n },\n\n parseLiteral(valueNode) {\n if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) {\n throw new GraphQLError(\n 'ID cannot represent a non-string and non-integer value: ' +\n print(valueNode),\n {\n nodes: valueNode,\n },\n );\n }\n\n return valueNode.value;\n },\n});\n/** All built-in scalar types defined by the GraphQL specification. */\n\nexport const specifiedScalarTypes = Object.freeze([\n GraphQLString,\n GraphQLInt,\n GraphQLFloat,\n GraphQLBoolean,\n GraphQLID,\n]);\n/**\n * Returns true when the scalar type is one of the scalars specified by GraphQL.\n * @param type - The GraphQL type to inspect.\n * @returns True when the scalar type is one of the scalars specified by GraphQL.\n * @example\n * ```ts\n * import {\n * GraphQLScalarType,\n * GraphQLString,\n * isSpecifiedScalarType,\n * } from 'graphql/type';\n *\n * const DateTime = new GraphQLScalarType({\n * name: 'DateTime',\n * });\n *\n * isSpecifiedScalarType(GraphQLString); // => true\n * isSpecifiedScalarType(DateTime); // => false\n * ```\n */\n\nexport function isSpecifiedScalarType(type) {\n return specifiedScalarTypes.some(({ name }) => type.name === name);\n} // Support serializing objects with custom valueOf() or toJSON() functions -\n// a common way to represent a complex value which can be represented as\n// a string (ex: MongoDB id objects).\n\nfunction serializeObject(outputValue) {\n if (isObjectLike(outputValue)) {\n if (typeof outputValue.valueOf === 'function') {\n const valueOfResult = outputValue.valueOf();\n\n if (!isObjectLike(valueOfResult)) {\n return valueOfResult;\n }\n }\n\n if (typeof outputValue.toJSON === 'function') {\n return outputValue.toJSON();\n }\n }\n\n return outputValue;\n}\n","/** @category Directives */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { toObjMap } from '../jsutils/toObjMap.mjs';\nimport { DirectiveLocation } from '../language/directiveLocation.mjs';\nimport { assertName } from './assertName.mjs';\nimport {\n argsToArgsConfig,\n defineArguments,\n GraphQLNonNull,\n} from './definition.mjs';\nimport { GraphQLBoolean, GraphQLString } from './scalars.mjs';\n/**\n * Test if the given value is a GraphQL directive.\n * @param directive - Value to inspect.\n * @returns True when the value is a GraphQLDirective.\n * @example\n * ```ts\n * import { DirectiveLocation } from 'graphql/language';\n * import { GraphQLDirective, GraphQLString, isDirective } from 'graphql/type';\n *\n * const upper = new GraphQLDirective({\n * name: 'upper',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * });\n *\n * isDirective(upper); // => true\n * isDirective(GraphQLString); // => false\n * ```\n */\n\nexport function isDirective(directive) {\n return instanceOf(directive, GraphQLDirective);\n}\n/**\n * Returns the value as a GraphQLDirective, or throws if it is not a directive.\n * @param directive - Value to inspect.\n * @returns The value typed as a GraphQLDirective.\n * @example\n * ```ts\n * import { DirectiveLocation } from 'graphql/language';\n * import { assertDirective, GraphQLDirective, GraphQLString } from 'graphql/type';\n *\n * const upper = new GraphQLDirective({\n * name: 'upper',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * });\n *\n * assertDirective(upper); // => upper\n * assertDirective(GraphQLString); // throws an error\n * ```\n */\n\nexport function assertDirective(directive) {\n if (!isDirective(directive)) {\n throw new Error(\n `Expected ${inspect(directive)} to be a GraphQL directive.`,\n );\n }\n\n return directive;\n}\n/**\n * Custom extensions\n * @remarks\n * Use a unique identifier name for your extension, for example the name of\n * your library or project. Do not use a shortened identifier as this increases\n * the risk of conflicts. We recommend you add at most one extension field,\n * an object which can contain all the values you need.\n */\n\n/**\n * Directives are used by the GraphQL runtime as a way of modifying execution\n * behavior. Type system creators will usually not create these directly.\n */\nexport class GraphQLDirective {\n /** The GraphQL name for this schema element. */\n\n /** Human-readable description for this schema element, if provided. */\n\n /** Locations where this directive may be applied. */\n\n /** Arguments accepted by this field or directive. */\n\n /** Whether this directive may appear more than once at the same location. */\n\n /** Reason this element is deprecated, if one was provided. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Creates a GraphQLDirective instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * import { DirectiveLocation, parse } from 'graphql/language';\n * import {\n * GraphQLBoolean,\n * GraphQLDirective,\n * GraphQLInt,\n * GraphQLNonNull,\n * } from 'graphql/type';\n *\n * const document = parse(`\n * directive @cacheControl(maxAge: Int) repeatable on FIELD_DEFINITION\n * extend directive @cacheControl(maxAge: Int) on FIELD_DEFINITION\n * `);\n * const definition = document.definitions[0];\n *\n * const cacheControl = new GraphQLDirective({\n * name: 'cacheControl',\n * description: 'Controls HTTP cache hints for a field.',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * args: {\n * inheritMaxAge: {\n * description: 'Inherit the parent cache hint.',\n * type: new GraphQLNonNull(GraphQLBoolean),\n * defaultValue: false,\n * deprecationReason: 'Use maxAge instead.',\n * extensions: { scope: 'cache' },\n * },\n * maxAge: {\n * type: GraphQLInt,\n * astNode: definition.arguments[0],\n * },\n * },\n * isRepeatable: true,\n * deprecationReason: 'Use @cache instead.',\n * extensions: { scope: 'cache' },\n * astNode: definition,\n * extensionASTNodes: [ document.definitions[1] ],\n * });\n *\n * cacheControl.name; // => 'cacheControl'\n * cacheControl.description; // => 'Controls HTTP cache hints for a field.'\n * cacheControl.args[0].name; // => 'inheritMaxAge'\n * cacheControl.args[0].defaultValue; // => false\n * cacheControl.isRepeatable; // => true\n * cacheControl.extensions; // => { scope: 'cache' }\n * ```\n */\n constructor(config) {\n var _config$isRepeatable, _config$extensionASTN, _config$args;\n\n this.name = assertName(config.name);\n this.description = config.description;\n this.locations = config.locations;\n this.isRepeatable =\n (_config$isRepeatable = config.isRepeatable) !== null &&\n _config$isRepeatable !== void 0\n ? _config$isRepeatable\n : false;\n this.deprecationReason = config.deprecationReason;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN = config.extensionASTNodes) !== null &&\n _config$extensionASTN !== void 0\n ? _config$extensionASTN\n : [];\n Array.isArray(config.locations) ||\n devAssert(false, `@${config.name} locations must be an Array.`);\n const args =\n (_config$args = config.args) !== null && _config$args !== void 0\n ? _config$args\n : {};\n (isObjectLike(args) && !Array.isArray(args)) ||\n devAssert(\n false,\n `@${config.name} args must be an object with argument names as keys.`,\n );\n this.args = defineArguments(args);\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLDirective';\n }\n /**\n * Returns a normalized configuration object for this object.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { DirectiveLocation } from 'graphql/language';\n * import { GraphQLDirective, GraphQLString } from 'graphql/type';\n *\n * const tag = new GraphQLDirective({\n * name: 'tag',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * args: {\n * name: { type: GraphQLString },\n * },\n * });\n *\n * const config = tag.toConfig();\n * const tagCopy = new GraphQLDirective(config);\n *\n * config.args.name.type; // => GraphQLString\n * tagCopy.args[0].name; // => 'name'\n * ```\n */\n\n toConfig() {\n return {\n name: this.name,\n description: this.description,\n locations: this.locations,\n args: argsToArgsConfig(this.args),\n isRepeatable: this.isRepeatable,\n deprecationReason: this.deprecationReason,\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n };\n }\n /**\n * Returns the schema coordinate identifying this directive.\n * @returns The directive schema coordinate.\n * @example\n * ```ts\n * import { DirectiveLocation } from 'graphql/language';\n * import { GraphQLDirective } from 'graphql/type';\n *\n * const tag = new GraphQLDirective({\n * name: 'tag',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * });\n *\n * tag.toString(); // => '@tag'\n * ```\n */\n\n toString() {\n return '@' + this.name;\n }\n /**\n * Returns the JSON representation used when this object is serialized.\n * @returns The JSON-serializable representation.\n * @example\n * ```ts\n * import { DirectiveLocation } from 'graphql/language';\n * import { GraphQLDirective } from 'graphql/type';\n *\n * const tag = new GraphQLDirective({\n * name: 'tag',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * });\n *\n * tag.toJSON(); // => '@tag'\n * JSON.stringify({ directive: tag }); // => '{\"directive\":\"@tag\"}'\n * ```\n */\n\n toJSON() {\n return this.toString();\n }\n}\n/** Configuration used to construct a GraphQLDirective. */\n\n/** Used to conditionally include fields or fragments. */\nexport const GraphQLIncludeDirective = new GraphQLDirective({\n name: 'include',\n description:\n 'Directs the executor to include this field or fragment only when the `if` argument is true.',\n locations: [\n DirectiveLocation.FIELD,\n DirectiveLocation.FRAGMENT_SPREAD,\n DirectiveLocation.INLINE_FRAGMENT,\n ],\n args: {\n if: {\n type: new GraphQLNonNull(GraphQLBoolean),\n description: 'Included when true.',\n },\n },\n});\n/** Used to conditionally skip (exclude) fields or fragments. */\n\nexport const GraphQLSkipDirective = new GraphQLDirective({\n name: 'skip',\n description:\n 'Directs the executor to skip this field or fragment when the `if` argument is true.',\n locations: [\n DirectiveLocation.FIELD,\n DirectiveLocation.FRAGMENT_SPREAD,\n DirectiveLocation.INLINE_FRAGMENT,\n ],\n args: {\n if: {\n type: new GraphQLNonNull(GraphQLBoolean),\n description: 'Skipped when true.',\n },\n },\n});\n/** Constant string used for default reason for a deprecation. */\n\nexport const DEFAULT_DEPRECATION_REASON = 'No longer supported';\n/**\n * Used to declare element of a GraphQL schema as deprecated.\n *\n * The optional `reason` argument defaults to `DEFAULT_DEPRECATION_REASON`.\n */\n\nexport const GraphQLDeprecatedDirective = new GraphQLDirective({\n name: 'deprecated',\n description: 'Marks an element of a GraphQL schema as no longer supported.',\n locations: [\n DirectiveLocation.FIELD_DEFINITION,\n DirectiveLocation.ARGUMENT_DEFINITION,\n DirectiveLocation.INPUT_FIELD_DEFINITION,\n DirectiveLocation.ENUM_VALUE,\n DirectiveLocation.DIRECTIVE_DEFINITION,\n ],\n args: {\n reason: {\n type: GraphQLString,\n description:\n 'Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).',\n defaultValue: DEFAULT_DEPRECATION_REASON,\n },\n },\n});\n/** Used to provide a URL for specifying the behavior of custom scalar definitions. */\n\nexport const GraphQLSpecifiedByDirective = new GraphQLDirective({\n name: 'specifiedBy',\n description: 'Exposes a URL that specifies the behavior of this scalar.',\n locations: [DirectiveLocation.SCALAR],\n args: {\n url: {\n type: new GraphQLNonNull(GraphQLString),\n description: 'The URL that specifies the behavior of this scalar.',\n },\n },\n});\n/** Used to indicate an Input Object is a OneOf Input Object. */\n\nexport const GraphQLOneOfDirective = new GraphQLDirective({\n name: 'oneOf',\n description:\n 'Indicates exactly one field must be supplied and this field must not be `null`.',\n locations: [DirectiveLocation.INPUT_OBJECT],\n args: {},\n});\n/** Full list of stable directives specified by GraphQL.js. */\n\nexport const specifiedDirectives = Object.freeze([\n GraphQLIncludeDirective,\n GraphQLSkipDirective,\n GraphQLDeprecatedDirective,\n GraphQLSpecifiedByDirective,\n GraphQLOneOfDirective,\n]);\n/**\n * Returns true when the directive is one of the directives specified by GraphQL.\n * @param directive - Directive to inspect.\n * @returns True when the directive is specified by GraphQL.\n * @example\n * ```ts\n * import {\n * GraphQLDirective,\n * GraphQLIncludeDirective,\n * isSpecifiedDirective,\n * } from 'graphql/type';\n * import { DirectiveLocation } from 'graphql/language';\n *\n * const customDirective = new GraphQLDirective({\n * name: 'auth',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * });\n *\n * isSpecifiedDirective(GraphQLIncludeDirective); // => true\n * isSpecifiedDirective(customDirective); // => false\n * ```\n */\n\nexport function isSpecifiedDirective(directive) {\n return specifiedDirectives.some(({ name }) => name === directive.name);\n}\n","/**\n * Returns true if the provided object is an Object (i.e. not a string literal)\n * and implements the Iterator protocol.\n *\n * This may be used in place of [Array.isArray()][isArray] to determine if\n * an object should be iterated-over e.g. Array, Map, Set, Int8Array,\n * TypedArray, etc. but excludes string literals.\n *\n * @internal\n * @example\n * ```ts\n * isIterableObject([1, 2, 3]); // => true\n * isIterableObject(new Map()); // => true\n * isIterableObject('ABC'); // => false\n * isIterableObject({ key: 'value' }); // => false\n * isIterableObject({ length: 1, 0: 'Alpha' }); // => false\n * ```\n */\nexport function isIterableObject(maybeIterable) {\n return (\n typeof maybeIterable === 'object' &&\n typeof (maybeIterable === null || maybeIterable === void 0\n ? void 0\n : maybeIterable[Symbol.iterator]) === 'function'\n );\n}\n","/** @category Values */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { isIterableObject } from '../jsutils/isIterableObject.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isEnumType,\n isInputObjectType,\n isLeafType,\n isListType,\n isNonNullType,\n} from '../type/definition.mjs';\nimport { GraphQLID } from '../type/scalars.mjs';\n/**\n * Produces a GraphQL Value AST given a JavaScript object.\n * Function will match JavaScript/JSON values to GraphQL AST schema format\n * by using suggested GraphQLInputType.\n *\n * A GraphQL type must be provided, which will be used to interpret different\n * JavaScript values.\n *\n * | JSON Value | GraphQL Value |\n * | ------------- | -------------------- |\n * | Object | Input Object |\n * | Array | List |\n * | Boolean | Boolean |\n * | String | String / Enum Value |\n * | Number | Int / Float |\n * | Unknown | Enum Value |\n * | null | NullValue |\n * @param value - Runtime value to convert.\n * @param type - The GraphQL type to inspect.\n * @returns A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it.\n * @example\n * ```ts\n * import { print } from 'graphql/language';\n * import {\n * GraphQLInputObjectType,\n * GraphQLInt,\n * GraphQLList,\n * GraphQLNonNull,\n * GraphQLString,\n * } from 'graphql/type';\n * import { astFromValue } from 'graphql/utilities';\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * fields: {\n * stars: { type: new GraphQLNonNull(GraphQLInt) },\n * tags: { type: new GraphQLList(GraphQLString) },\n * },\n * });\n *\n * const valueNode = astFromValue(\n * { stars: 5, tags: ['featured', 'verified'] },\n * ReviewInput,\n * );\n *\n * print(valueNode); // => '{ stars: 5, tags: [\"featured\", \"verified\"] }'\n * astFromValue(undefined, GraphQLString); // => null\n * astFromValue(null, new GraphQLNonNull(GraphQLString)); // => null\n * ```\n */\n\nexport function astFromValue(value, type) {\n if (isNonNullType(type)) {\n const astValue = astFromValue(value, type.ofType);\n\n if (\n (astValue === null || astValue === void 0 ? void 0 : astValue.kind) ===\n Kind.NULL\n ) {\n return null;\n }\n\n return astValue;\n } // only explicit null, not undefined, NaN\n\n if (value === null) {\n return {\n kind: Kind.NULL,\n };\n } // undefined\n\n if (value === undefined) {\n return null;\n } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but\n // the value is not an array, convert the value using the list's item type.\n\n if (isListType(type)) {\n const itemType = type.ofType;\n\n if (isIterableObject(value)) {\n const valuesNodes = [];\n\n for (const item of value) {\n const itemNode = astFromValue(item, itemType);\n\n if (itemNode != null) {\n valuesNodes.push(itemNode);\n }\n }\n\n return {\n kind: Kind.LIST,\n values: valuesNodes,\n };\n }\n\n return astFromValue(value, itemType);\n } // Populate the fields of the input object by creating ASTs from each value\n // in the JavaScript object according to the fields in the input type.\n\n if (isInputObjectType(type)) {\n if (!isObjectLike(value)) {\n return null;\n }\n\n const fieldNodes = [];\n\n for (const field of Object.values(type.getFields())) {\n const fieldValue = astFromValue(value[field.name], field.type);\n\n if (fieldValue) {\n fieldNodes.push({\n kind: Kind.OBJECT_FIELD,\n name: {\n kind: Kind.NAME,\n value: field.name,\n },\n value: fieldValue,\n });\n }\n }\n\n return {\n kind: Kind.OBJECT,\n fields: fieldNodes,\n };\n }\n\n if (isLeafType(type)) {\n // Since value is an internally represented value, it must be serialized\n // to an externally represented value before converting into an AST.\n const serialized = type.serialize(value);\n\n if (serialized == null) {\n return null;\n } // Others serialize based on their corresponding JavaScript scalar types.\n\n if (typeof serialized === 'boolean') {\n return {\n kind: Kind.BOOLEAN,\n value: serialized,\n };\n } // JavaScript numbers can be Int or Float values.\n\n if (typeof serialized === 'number' && Number.isFinite(serialized)) {\n const stringNum = String(serialized);\n return integerStringRegExp.test(stringNum)\n ? {\n kind: Kind.INT,\n value: stringNum,\n }\n : {\n kind: Kind.FLOAT,\n value: stringNum,\n };\n }\n\n if (typeof serialized === 'string') {\n // Enum types use Enum literals.\n if (isEnumType(type)) {\n return {\n kind: Kind.ENUM,\n value: serialized,\n };\n } // ID types can use Int literals.\n\n if (type === GraphQLID && integerStringRegExp.test(serialized)) {\n return {\n kind: Kind.INT,\n value: serialized,\n };\n }\n\n return {\n kind: Kind.STRING,\n value: serialized,\n };\n }\n\n throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}.`);\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered.\n\n false || invariant(false, 'Unexpected input type: ' + inspect(type));\n}\n/**\n * IntValue:\n * - NegativeSign? 0\n * - NegativeSign? NonZeroDigit ( Digit+ )?\n *\n * @internal\n */\n\nconst integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/;\n","/** @category Introspection */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { DirectiveLocation } from '../language/directiveLocation.mjs';\nimport { print } from '../language/printer.mjs';\nimport { astFromValue } from '../utilities/astFromValue.mjs';\nimport {\n GraphQLEnumType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n isAbstractType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from './definition.mjs';\nimport { GraphQLBoolean, GraphQLString } from './scalars.mjs';\n\n/** The introspection type describing a GraphQL schema. */\nexport const __Schema = new GraphQLObjectType({\n name: '__Schema',\n description:\n 'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.',\n fields: () => ({\n description: {\n type: GraphQLString,\n resolve: (schema) => schema.description,\n },\n types: {\n description: 'A list of all types supported by this server.',\n type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Type))),\n\n resolve(schema) {\n return Object.values(schema.getTypeMap());\n },\n },\n queryType: {\n description: 'The type that query operations will be rooted at.',\n type: new GraphQLNonNull(__Type),\n resolve: (schema) => schema.getQueryType(),\n },\n mutationType: {\n description:\n 'If this server supports mutation, the type that mutation operations will be rooted at.',\n type: __Type,\n resolve: (schema) => schema.getMutationType(),\n },\n subscriptionType: {\n description:\n 'If this server support subscription, the type that subscription operations will be rooted at.',\n type: __Type,\n resolve: (schema) => schema.getSubscriptionType(),\n },\n directives: {\n description: 'A list of all directives supported by this server.',\n type: new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(__Directive)),\n ),\n args: {\n includeDeprecated: {\n type: new GraphQLNonNull(GraphQLBoolean),\n defaultValue: false,\n },\n },\n resolve: (schema, { includeDeprecated }) =>\n includeDeprecated\n ? schema.getDirectives()\n : schema\n .getDirectives()\n .filter((directive) => directive.deprecationReason == null),\n },\n }),\n});\n/** The introspection type describing a GraphQL directive. */\n\nexport const __Directive = new GraphQLObjectType({\n name: '__Directive',\n description:\n \"A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\\n\\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.\",\n fields: () => ({\n name: {\n type: new GraphQLNonNull(GraphQLString),\n resolve: (directive) => directive.name,\n },\n description: {\n type: GraphQLString,\n resolve: (directive) => directive.description,\n },\n isRepeatable: {\n type: new GraphQLNonNull(GraphQLBoolean),\n resolve: (directive) => directive.isRepeatable,\n },\n locations: {\n type: new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(__DirectiveLocation)),\n ),\n resolve: (directive) => directive.locations,\n },\n args: {\n type: new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(__InputValue)),\n ),\n args: {\n includeDeprecated: {\n type: GraphQLBoolean,\n defaultValue: false,\n },\n },\n\n resolve(field, { includeDeprecated }) {\n return includeDeprecated\n ? field.args\n : field.args.filter((arg) => arg.deprecationReason == null);\n },\n },\n isDeprecated: {\n type: new GraphQLNonNull(GraphQLBoolean),\n resolve: (directive) => directive.deprecationReason != null,\n },\n deprecationReason: {\n type: GraphQLString,\n resolve: (directive) => directive.deprecationReason,\n },\n }),\n});\n/** The introspection enum describing directive locations. */\n\nexport const __DirectiveLocation = new GraphQLEnumType({\n name: '__DirectiveLocation',\n description:\n 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.',\n values: {\n QUERY: {\n value: DirectiveLocation.QUERY,\n description: 'Location adjacent to a query operation.',\n },\n MUTATION: {\n value: DirectiveLocation.MUTATION,\n description: 'Location adjacent to a mutation operation.',\n },\n SUBSCRIPTION: {\n value: DirectiveLocation.SUBSCRIPTION,\n description: 'Location adjacent to a subscription operation.',\n },\n FIELD: {\n value: DirectiveLocation.FIELD,\n description: 'Location adjacent to a field.',\n },\n FRAGMENT_DEFINITION: {\n value: DirectiveLocation.FRAGMENT_DEFINITION,\n description: 'Location adjacent to a fragment definition.',\n },\n FRAGMENT_SPREAD: {\n value: DirectiveLocation.FRAGMENT_SPREAD,\n description: 'Location adjacent to a fragment spread.',\n },\n INLINE_FRAGMENT: {\n value: DirectiveLocation.INLINE_FRAGMENT,\n description: 'Location adjacent to an inline fragment.',\n },\n VARIABLE_DEFINITION: {\n value: DirectiveLocation.VARIABLE_DEFINITION,\n description: 'Location adjacent to a variable definition.',\n },\n SCHEMA: {\n value: DirectiveLocation.SCHEMA,\n description: 'Location adjacent to a schema definition.',\n },\n SCALAR: {\n value: DirectiveLocation.SCALAR,\n description: 'Location adjacent to a scalar definition.',\n },\n OBJECT: {\n value: DirectiveLocation.OBJECT,\n description: 'Location adjacent to an object type definition.',\n },\n FIELD_DEFINITION: {\n value: DirectiveLocation.FIELD_DEFINITION,\n description: 'Location adjacent to a field definition.',\n },\n ARGUMENT_DEFINITION: {\n value: DirectiveLocation.ARGUMENT_DEFINITION,\n description: 'Location adjacent to an argument definition.',\n },\n INTERFACE: {\n value: DirectiveLocation.INTERFACE,\n description: 'Location adjacent to an interface definition.',\n },\n UNION: {\n value: DirectiveLocation.UNION,\n description: 'Location adjacent to a union definition.',\n },\n ENUM: {\n value: DirectiveLocation.ENUM,\n description: 'Location adjacent to an enum definition.',\n },\n ENUM_VALUE: {\n value: DirectiveLocation.ENUM_VALUE,\n description: 'Location adjacent to an enum value definition.',\n },\n INPUT_OBJECT: {\n value: DirectiveLocation.INPUT_OBJECT,\n description: 'Location adjacent to an input object type definition.',\n },\n INPUT_FIELD_DEFINITION: {\n value: DirectiveLocation.INPUT_FIELD_DEFINITION,\n description: 'Location adjacent to an input object field definition.',\n },\n DIRECTIVE_DEFINITION: {\n value: DirectiveLocation.DIRECTIVE_DEFINITION,\n description: 'Location adjacent to a directive definition.',\n },\n },\n});\n/** The introspection type describing GraphQL types. */\n\nexport const __Type = new GraphQLObjectType({\n name: '__Type',\n description:\n 'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\\n\\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByURL`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.',\n fields: () => ({\n kind: {\n type: new GraphQLNonNull(__TypeKind),\n\n resolve(type) {\n if (isScalarType(type)) {\n return TypeKind.SCALAR;\n }\n\n if (isObjectType(type)) {\n return TypeKind.OBJECT;\n }\n\n if (isInterfaceType(type)) {\n return TypeKind.INTERFACE;\n }\n\n if (isUnionType(type)) {\n return TypeKind.UNION;\n }\n\n if (isEnumType(type)) {\n return TypeKind.ENUM;\n }\n\n if (isInputObjectType(type)) {\n return TypeKind.INPUT_OBJECT;\n }\n\n if (isListType(type)) {\n return TypeKind.LIST;\n }\n\n if (isNonNullType(type)) {\n return TypeKind.NON_NULL;\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered)\n\n false || invariant(false, `Unexpected type: \"${inspect(type)}\".`);\n },\n },\n name: {\n type: GraphQLString,\n resolve: (type) => ('name' in type ? type.name : undefined),\n },\n description: {\n type: GraphQLString,\n resolve: (\n type, // FIXME: add test case\n ) =>\n /* c8 ignore next */\n 'description' in type ? type.description : undefined,\n },\n specifiedByURL: {\n type: GraphQLString,\n resolve: (obj) =>\n 'specifiedByURL' in obj ? obj.specifiedByURL : undefined,\n },\n fields: {\n type: new GraphQLList(new GraphQLNonNull(__Field)),\n args: {\n includeDeprecated: {\n type: GraphQLBoolean,\n defaultValue: false,\n },\n },\n\n resolve(type, { includeDeprecated }) {\n if (isObjectType(type) || isInterfaceType(type)) {\n const fields = Object.values(type.getFields());\n return includeDeprecated\n ? fields\n : fields.filter((field) => field.deprecationReason == null);\n }\n },\n },\n interfaces: {\n type: new GraphQLList(new GraphQLNonNull(__Type)),\n\n resolve(type) {\n if (isObjectType(type) || isInterfaceType(type)) {\n return type.getInterfaces();\n }\n },\n },\n possibleTypes: {\n type: new GraphQLList(new GraphQLNonNull(__Type)),\n\n resolve(type, _args, _context, { schema }) {\n if (isAbstractType(type)) {\n return schema.getPossibleTypes(type);\n }\n },\n },\n enumValues: {\n type: new GraphQLList(new GraphQLNonNull(__EnumValue)),\n args: {\n includeDeprecated: {\n type: GraphQLBoolean,\n defaultValue: false,\n },\n },\n\n resolve(type, { includeDeprecated }) {\n if (isEnumType(type)) {\n const values = type.getValues();\n return includeDeprecated\n ? values\n : values.filter((field) => field.deprecationReason == null);\n }\n },\n },\n inputFields: {\n type: new GraphQLList(new GraphQLNonNull(__InputValue)),\n args: {\n includeDeprecated: {\n type: GraphQLBoolean,\n defaultValue: false,\n },\n },\n\n resolve(type, { includeDeprecated }) {\n if (isInputObjectType(type)) {\n const values = Object.values(type.getFields());\n return includeDeprecated\n ? values\n : values.filter((field) => field.deprecationReason == null);\n }\n },\n },\n ofType: {\n type: __Type,\n resolve: (type) => ('ofType' in type ? type.ofType : undefined),\n },\n isOneOf: {\n type: GraphQLBoolean,\n resolve: (type) => {\n if (isInputObjectType(type)) {\n return type.isOneOf;\n }\n },\n },\n }),\n});\n/** The introspection type describing object and interface fields. */\n\nexport const __Field = new GraphQLObjectType({\n name: '__Field',\n description:\n 'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.',\n fields: () => ({\n name: {\n type: new GraphQLNonNull(GraphQLString),\n resolve: (field) => field.name,\n },\n description: {\n type: GraphQLString,\n resolve: (field) => field.description,\n },\n args: {\n type: new GraphQLNonNull(\n new GraphQLList(new GraphQLNonNull(__InputValue)),\n ),\n args: {\n includeDeprecated: {\n type: GraphQLBoolean,\n defaultValue: false,\n },\n },\n\n resolve(field, { includeDeprecated }) {\n return includeDeprecated\n ? field.args\n : field.args.filter((arg) => arg.deprecationReason == null);\n },\n },\n type: {\n type: new GraphQLNonNull(__Type),\n resolve: (field) => field.type,\n },\n isDeprecated: {\n type: new GraphQLNonNull(GraphQLBoolean),\n resolve: (field) => field.deprecationReason != null,\n },\n deprecationReason: {\n type: GraphQLString,\n resolve: (field) => field.deprecationReason,\n },\n }),\n});\n/** The introspection type describing arguments and input fields. */\n\nexport const __InputValue = new GraphQLObjectType({\n name: '__InputValue',\n description:\n 'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.',\n fields: () => ({\n name: {\n type: new GraphQLNonNull(GraphQLString),\n resolve: (inputValue) => inputValue.name,\n },\n description: {\n type: GraphQLString,\n resolve: (inputValue) => inputValue.description,\n },\n type: {\n type: new GraphQLNonNull(__Type),\n resolve: (inputValue) => inputValue.type,\n },\n defaultValue: {\n type: GraphQLString,\n description:\n 'A GraphQL-formatted string representing the default value for this input value.',\n\n resolve(inputValue) {\n const { type, defaultValue } = inputValue;\n const valueAST = astFromValue(defaultValue, type);\n return valueAST ? print(valueAST) : null;\n },\n },\n isDeprecated: {\n type: new GraphQLNonNull(GraphQLBoolean),\n resolve: (field) => field.deprecationReason != null,\n },\n deprecationReason: {\n type: GraphQLString,\n resolve: (obj) => obj.deprecationReason,\n },\n }),\n});\n/** The introspection type describing enum values. */\n\nexport const __EnumValue = new GraphQLObjectType({\n name: '__EnumValue',\n description:\n 'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.',\n fields: () => ({\n name: {\n type: new GraphQLNonNull(GraphQLString),\n resolve: (enumValue) => enumValue.name,\n },\n description: {\n type: GraphQLString,\n resolve: (enumValue) => enumValue.description,\n },\n isDeprecated: {\n type: new GraphQLNonNull(GraphQLBoolean),\n resolve: (enumValue) => enumValue.deprecationReason != null,\n },\n deprecationReason: {\n type: GraphQLString,\n resolve: (enumValue) => enumValue.deprecationReason,\n },\n }),\n});\n/**\n * The introspection enum describing the different kinds of GraphQL types.\n * @category Introspection\n */\n\nvar TypeKind;\n\n(function (TypeKind) {\n TypeKind['SCALAR'] = 'SCALAR';\n TypeKind['OBJECT'] = 'OBJECT';\n TypeKind['INTERFACE'] = 'INTERFACE';\n TypeKind['UNION'] = 'UNION';\n TypeKind['ENUM'] = 'ENUM';\n TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT';\n TypeKind['LIST'] = 'LIST';\n TypeKind['NON_NULL'] = 'NON_NULL';\n})(TypeKind || (TypeKind = {}));\n\nexport { TypeKind };\n/** The introspection enum describing GraphQL type kinds. */\n\nexport const __TypeKind = new GraphQLEnumType({\n name: '__TypeKind',\n description: 'An enum describing what kind of type a given `__Type` is.',\n values: {\n SCALAR: {\n value: TypeKind.SCALAR,\n description: 'Indicates this type is a scalar.',\n },\n OBJECT: {\n value: TypeKind.OBJECT,\n description:\n 'Indicates this type is an object. `fields` and `interfaces` are valid fields.',\n },\n INTERFACE: {\n value: TypeKind.INTERFACE,\n description:\n 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.',\n },\n UNION: {\n value: TypeKind.UNION,\n description:\n 'Indicates this type is a union. `possibleTypes` is a valid field.',\n },\n ENUM: {\n value: TypeKind.ENUM,\n description:\n 'Indicates this type is an enum. `enumValues` is a valid field.',\n },\n INPUT_OBJECT: {\n value: TypeKind.INPUT_OBJECT,\n description:\n 'Indicates this type is an input object. `inputFields` is a valid field.',\n },\n LIST: {\n value: TypeKind.LIST,\n description: 'Indicates this type is a list. `ofType` is a valid field.',\n },\n NON_NULL: {\n value: TypeKind.NON_NULL,\n description:\n 'Indicates this type is a non-null. `ofType` is a valid field.',\n },\n },\n});\n/**\n * Note that these are GraphQLField and not GraphQLFieldConfig,\n * so the format for args is different.\n */\n\nexport const SchemaMetaFieldDef = {\n name: '__schema',\n type: new GraphQLNonNull(__Schema),\n description: 'Access the current type schema of this server.',\n args: [],\n resolve: (_source, _args, _context, { schema }) => schema,\n deprecationReason: undefined,\n extensions: Object.create(null),\n astNode: undefined,\n};\n/** The `__type` meta field definition used by introspection. */\n\nexport const TypeMetaFieldDef = {\n name: '__type',\n type: __Type,\n description: 'Request the type information of a single type.',\n args: [\n {\n name: 'name',\n description: undefined,\n type: new GraphQLNonNull(GraphQLString),\n defaultValue: undefined,\n deprecationReason: undefined,\n extensions: Object.create(null),\n astNode: undefined,\n },\n ],\n resolve: (_source, { name }, _context, { schema }) => schema.getType(name),\n deprecationReason: undefined,\n extensions: Object.create(null),\n astNode: undefined,\n};\n/** The `__typename` meta field definition used by execution and introspection. */\n\nexport const TypeNameMetaFieldDef = {\n name: '__typename',\n type: new GraphQLNonNull(GraphQLString),\n description: 'The name of the current Object type at runtime.',\n args: [],\n resolve: (_source, _args, _context, { parentType }) => parentType.name,\n deprecationReason: undefined,\n extensions: Object.create(null),\n astNode: undefined,\n};\n/** All introspection types defined by the GraphQL specification. */\n\nexport const introspectionTypes = Object.freeze([\n __Schema,\n __Directive,\n __DirectiveLocation,\n __Type,\n __Field,\n __InputValue,\n __EnumValue,\n __TypeKind,\n]);\n/**\n * Returns true when the type is one of the built-in introspection types.\n * @param type - The GraphQL type to inspect.\n * @returns True when the type is one of the built-in introspection types.\n * @example\n * ```ts\n * import { GraphQLString, isIntrospectionType, __Type } from 'graphql/type';\n *\n * isIntrospectionType(__Type); // => true\n * isIntrospectionType(GraphQLString); // => false\n * ```\n */\n\nexport function isIntrospectionType(type) {\n return introspectionTypes.some(({ name }) => type.name === name);\n}\n","/** @category Schema */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { instanceOf } from '../jsutils/instanceOf.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { toObjMap } from '../jsutils/toObjMap.mjs';\nimport { OperationTypeNode } from '../language/ast.mjs';\nimport {\n getNamedType,\n isInputObjectType,\n isInterfaceType,\n isObjectType,\n isUnionType,\n} from './definition.mjs';\nimport { isDirective, specifiedDirectives } from './directives.mjs';\nimport { __Schema } from './introspection.mjs';\n/**\n * Test if the given value is a GraphQL schema.\n * @param schema - Value to inspect.\n * @returns True when the value is a GraphQLSchema.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { GraphQLString, isSchema } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * isSchema(schema); // => true\n * isSchema(GraphQLString); // => false\n * ```\n */\n\nexport function isSchema(schema) {\n return instanceOf(schema, GraphQLSchema);\n}\n/**\n * Returns the value as a GraphQLSchema, or throws if it is not a schema.\n * @param schema - GraphQL schema to use.\n * @returns The value typed as a GraphQLSchema.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertSchema, GraphQLString } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * assertSchema(schema); // => schema\n * assertSchema(GraphQLString); // throws an error\n * ```\n */\n\nexport function assertSchema(schema) {\n if (!isSchema(schema)) {\n throw new Error(`Expected ${inspect(schema)} to be a GraphQL schema.`);\n }\n\n return schema;\n}\n/**\n * Custom extensions\n * @remarks\n * Use a unique identifier name for your extension, for example the name of\n * your library or project. Do not use a shortened identifier as this increases\n * the risk of conflicts. We recommend you add at most one extension field,\n * an object which can contain all the values you need.\n */\n\n/**\n * Schema Definition\n *\n * A Schema is created by supplying the root types of each type of operation,\n * query and mutation (optional). A schema definition is then supplied to the\n * validator and executor.\n * @example\n * ```ts\n * const MyAppQueryRootType = new GraphQLObjectType({\n * name: 'Query',\n * fields: {\n * greeting: { type: GraphQLString },\n * },\n * });\n *\n * const MyAppMutationRootType = new GraphQLObjectType({\n * name: 'Mutation',\n * fields: {\n * setGreeting: { type: GraphQLString },\n * },\n * });\n *\n * const MyAppSchema = new GraphQLSchema({\n * query: MyAppQueryRootType,\n * mutation: MyAppMutationRootType,\n * });\n * ```\n * @example\n * When the schema is constructed, by default only the types that are reachable\n * by traversing the root types are included, other types must be explicitly\n * referenced.\n *\n * ```ts\n * const characterInterface = new GraphQLInterfaceType({\n * name: 'Character',\n * fields: {\n * name: { type: GraphQLString },\n * },\n * });\n *\n * const humanType = new GraphQLObjectType({\n * name: 'Human',\n * interfaces: [characterInterface],\n * fields: {\n * name: { type: GraphQLString },\n * },\n * });\n *\n * const droidType = new GraphQLObjectType({\n * name: 'Droid',\n * interfaces: [characterInterface],\n * fields: {\n * name: { type: GraphQLString },\n * },\n * });\n *\n * const schema = new GraphQLSchema({\n * query: new GraphQLObjectType({\n * name: 'Query',\n * fields: {\n * hero: { type: characterInterface },\n * },\n * }),\n * // Since this schema references only the `Character` interface it's\n * // necessary to explicitly list the types that implement it if\n * // you want them to be included in the final schema.\n * types: [humanType, droidType],\n * });\n * ```\n * @example\n * If an array of `directives` are provided to GraphQLSchema, that will be the\n * exact list of directives represented and allowed. If `directives` is not\n * provided then a default set of the specified directives (e.g. `@include` and\n * `@skip`) will be used. If you wish to provide *additional* directives to\n * these specified directives, you must explicitly declare them.\n *\n * ```ts\n * const MyAppSchema = new GraphQLSchema({\n * query: MyAppQueryRootType,\n * directives: specifiedDirectives.concat([myCustomDirective]),\n * });\n * ```\n */\nexport class GraphQLSchema {\n /** Human-readable description for this schema element, if provided. */\n\n /** Extension fields to include in the formatted result. */\n\n /** AST node from which this schema element was built, if available. */\n\n /** AST extension nodes applied to this schema element. */\n\n /**\n * Cached schema validation errors, if validation has already run.\n * @internal\n */\n\n /**\n * Creates a GraphQLSchema instance.\n * @param config - Configuration describing this object.\n * @example\n * ```ts\n * // Create a schema with the required query root.\n * import {\n * GraphQLObjectType,\n * GraphQLSchema,\n * GraphQLString,\n * } from 'graphql/type';\n *\n * const Query = new GraphQLObjectType({\n * name: 'Query',\n * fields: {\n * greeting: {\n * type: GraphQLString,\n * resolve: () => 'Hello',\n * },\n * },\n * });\n *\n * const schema = new GraphQLSchema({\n * description: 'The application schema.',\n * query: Query,\n * });\n *\n * schema.getQueryType(); // => Query\n * schema.description; // => 'The application schema.'\n * ```\n * @example\n * ```ts\n * // This variant configures every schema option, including directives and extensions.\n * import { DirectiveLocation, parse } from 'graphql/language';\n * import {\n * GraphQLBoolean,\n * GraphQLDirective,\n * GraphQLObjectType,\n * GraphQLSchema,\n * GraphQLString,\n * } from 'graphql/type';\n *\n * const Query = new GraphQLObjectType({\n * name: 'Query',\n * fields: { greeting: { type: GraphQLString } },\n * });\n * const Mutation = new GraphQLObjectType({\n * name: 'Mutation',\n * fields: { setGreeting: { type: GraphQLString } },\n * });\n * const Subscription = new GraphQLObjectType({\n * name: 'Subscription',\n * fields: { greetingChanged: { type: GraphQLString } },\n * });\n * const AuditEvent = new GraphQLObjectType({\n * name: 'AuditEvent',\n * fields: { message: { type: GraphQLString } },\n * });\n * const authDirective = new GraphQLDirective({\n * name: 'auth',\n * locations: [DirectiveLocation.FIELD_DEFINITION],\n * args: { required: { type: GraphQLBoolean } },\n * });\n * const schemaDocument = parse(`\n * schema {\n * query: Query\n * mutation: Mutation\n * subscription: Subscription\n * }\n *\n * extend schema @auth\n * `);\n *\n * const schema = new GraphQLSchema({\n * description: 'Operations exposed by the application.',\n * query: Query,\n * mutation: Mutation,\n * subscription: Subscription,\n * types: [AuditEvent],\n * directives: [authDirective],\n * extensions: { owner: 'platform' },\n * astNode: schemaDocument.definitions[0],\n * extensionASTNodes: [ schemaDocument.definitions[1] ],\n * assumeValid: true,\n * });\n *\n * schema.getMutationType(); // => Mutation\n * schema.getSubscriptionType(); // => Subscription\n * schema.getType('AuditEvent'); // => AuditEvent\n * schema.getDirective('auth'); // => authDirective\n * schema.extensions; // => { owner: 'platform' }\n * ```\n */\n constructor(config) {\n var _config$extensionASTN, _config$directives;\n\n // If this schema was built from a source known to be valid, then it may be\n // marked with assumeValid to avoid an additional type system validation.\n this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors.\n\n isObjectLike(config) ||\n devAssert(false, 'Must provide configuration object.');\n !config.types ||\n Array.isArray(config.types) ||\n devAssert(\n false,\n `\"types\" must be Array if provided but got: ${inspect(config.types)}.`,\n );\n !config.directives ||\n Array.isArray(config.directives) ||\n devAssert(\n false,\n '\"directives\" must be Array if provided but got: ' +\n `${inspect(config.directives)}.`,\n );\n this.description = config.description;\n this.extensions = toObjMap(config.extensions);\n this.astNode = config.astNode;\n this.extensionASTNodes =\n (_config$extensionASTN = config.extensionASTNodes) !== null &&\n _config$extensionASTN !== void 0\n ? _config$extensionASTN\n : [];\n this._queryType = config.query;\n this._mutationType = config.mutation;\n this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default.\n\n this._directives =\n (_config$directives = config.directives) !== null &&\n _config$directives !== void 0\n ? _config$directives\n : specifiedDirectives; // To preserve order of user-provided types, we add first to add them to\n // the set of \"collected\" types, so `collectReferencedTypes` ignore them.\n\n const allReferencedTypes = new Set(config.types);\n\n if (config.types != null) {\n for (const type of config.types) {\n // When we ready to process this type, we remove it from \"collected\" types\n // and then add it together with all dependent types in the correct position.\n allReferencedTypes.delete(type);\n collectReferencedTypes(type, allReferencedTypes);\n }\n }\n\n if (this._queryType != null) {\n collectReferencedTypes(this._queryType, allReferencedTypes);\n }\n\n if (this._mutationType != null) {\n collectReferencedTypes(this._mutationType, allReferencedTypes);\n }\n\n if (this._subscriptionType != null) {\n collectReferencedTypes(this._subscriptionType, allReferencedTypes);\n }\n\n for (const directive of this._directives) {\n // Directives are not validated until validateSchema() is called.\n if (isDirective(directive)) {\n for (const arg of directive.args) {\n collectReferencedTypes(arg.type, allReferencedTypes);\n }\n }\n }\n\n collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema.\n\n this._typeMap = Object.create(null);\n this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name.\n\n this._implementationsMap = Object.create(null);\n\n for (const namedType of allReferencedTypes) {\n if (namedType == null) {\n continue;\n }\n\n const typeName = namedType.name;\n typeName ||\n devAssert(\n false,\n 'One of the provided types for building the Schema is missing a name.',\n );\n\n if (this._typeMap[typeName] !== undefined) {\n throw new Error(\n `Schema must contain uniquely named types but contains multiple types named \"${typeName}\".`,\n );\n }\n\n this._typeMap[typeName] = namedType;\n\n if (isInterfaceType(namedType)) {\n // Store implementations by interface.\n for (const iface of namedType.getInterfaces()) {\n if (isInterfaceType(iface)) {\n let implementations = this._implementationsMap[iface.name];\n\n if (implementations === undefined) {\n implementations = this._implementationsMap[iface.name] = {\n objects: [],\n interfaces: [],\n };\n }\n\n implementations.interfaces.push(namedType);\n }\n }\n } else if (isObjectType(namedType)) {\n // Store implementations by objects.\n for (const iface of namedType.getInterfaces()) {\n if (isInterfaceType(iface)) {\n let implementations = this._implementationsMap[iface.name];\n\n if (implementations === undefined) {\n implementations = this._implementationsMap[iface.name] = {\n objects: [],\n interfaces: [],\n };\n }\n\n implementations.objects.push(namedType);\n }\n }\n }\n }\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'GraphQLSchema';\n }\n /**\n * Returns the root object type for query operations.\n * @returns The query root type, if this schema defines one.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * schema.getQueryType()?.name; // => 'Query'\n * ```\n */\n\n getQueryType() {\n return this._queryType;\n }\n /**\n * Returns the root object type for mutation operations.\n * @returns The mutation root type, if this schema defines one.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n *\n * type Mutation {\n * setGreeting(value: String!): String\n * }\n * `);\n *\n * schema.getMutationType()?.name; // => 'Mutation'\n * ```\n */\n\n getMutationType() {\n return this._mutationType;\n }\n /**\n * Returns the root object type for subscription operations.\n * @returns The subscription root type, if this schema defines one.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n *\n * type Subscription {\n * greetings: String\n * }\n * `);\n *\n * schema.getSubscriptionType()?.name; // => 'Subscription'\n * ```\n */\n\n getSubscriptionType() {\n return this._subscriptionType;\n }\n /**\n * Returns the root object type for the requested operation kind.\n * @param operation - Operation kind to resolve.\n * @returns The root object type for the operation kind, if this schema defines one.\n * @example\n * ```ts\n * import { OperationTypeNode } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n *\n * type Mutation {\n * setGreeting(value: String!): String\n * }\n * `);\n *\n * schema.getRootType(OperationTypeNode.QUERY)?.name; // => 'Query'\n * schema.getRootType(OperationTypeNode.MUTATION)?.name; // => 'Mutation'\n * schema.getRootType(OperationTypeNode.SUBSCRIPTION); // => undefined\n * ```\n */\n\n getRootType(operation) {\n switch (operation) {\n case OperationTypeNode.QUERY:\n return this.getQueryType();\n\n case OperationTypeNode.MUTATION:\n return this.getMutationType();\n\n case OperationTypeNode.SUBSCRIPTION:\n return this.getSubscriptionType();\n }\n }\n /**\n * Returns all named types known to this schema.\n * @returns A map of schema types keyed by type name.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type User {\n * name: String\n * }\n *\n * type Query {\n * viewer: User\n * }\n * `);\n *\n * const typeMap = schema.getTypeMap();\n *\n * typeMap.User.name; // => 'User'\n * typeMap.Query.name; // => 'Query'\n * typeMap.String.name; // => 'String'\n * ```\n */\n\n getTypeMap() {\n return this._typeMap;\n }\n /**\n * Returns the named type with the provided name.\n * @param name - The GraphQL name to look up.\n * @returns The named schema type, if one exists.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type User {\n * name: String\n * }\n *\n * type Query {\n * viewer: User\n * }\n * `);\n *\n * schema.getType('User')?.toString(); // => 'User'\n * schema.getType('Missing'); // => undefined\n * ```\n */\n\n getType(name) {\n return this.getTypeMap()[name];\n }\n /**\n * Returns object types that may be returned for an abstract type.\n * @param abstractType - Interface or union type to inspect.\n * @returns Object types that may satisfy the abstract type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType, assertUnionType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Organization implements Node {\n * id: ID!\n * }\n *\n * union SearchResult = User | Organization\n *\n * type Query {\n * node: Node\n * search: [SearchResult]\n * }\n * `);\n *\n * const Node = assertInterfaceType(schema.getType('Node'));\n * const SearchResult = assertUnionType(schema.getType('SearchResult'));\n *\n * schema.getPossibleTypes(Node).map((type) => type.name); // => ['User', 'Organization']\n * schema.getPossibleTypes(SearchResult).map((type) => type.name); // => ['User', 'Organization']\n * ```\n */\n\n getPossibleTypes(abstractType) {\n return isUnionType(abstractType)\n ? abstractType.getTypes()\n : this.getImplementations(abstractType).objects;\n }\n /**\n * Returns objects and interfaces that implement an interface type.\n * @param interfaceType - Interface type to inspect.\n * @returns Object and interface implementations of the interface.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Resource {\n * url: String!\n * }\n *\n * interface Image implements Resource {\n * url: String!\n * width: Int\n * }\n *\n * type Photo implements Resource & Image {\n * url: String!\n * width: Int\n * }\n *\n * type Query {\n * resource: Resource\n * }\n * `);\n *\n * const Resource = assertInterfaceType(schema.getType('Resource'));\n * const implementations = schema.getImplementations(Resource);\n *\n * implementations.interfaces.map((type) => type.name); // => ['Image']\n * implementations.objects.map((type) => type.name); // => ['Photo']\n * ```\n */\n\n getImplementations(interfaceType) {\n const implementations = this._implementationsMap[interfaceType.name];\n return implementations !== null && implementations !== void 0\n ? implementations\n : {\n objects: [],\n interfaces: [],\n };\n }\n /**\n * Returns whether one type is a possible runtime subtype of an abstract type.\n * @param abstractType - Interface or union type to inspect.\n * @param maybeSubType - Object or interface type to test as a possible subtype.\n * @returns True when the subtype may satisfy the abstract type.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { assertInterfaceType, assertObjectType } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * interface Node {\n * id: ID!\n * }\n *\n * type User implements Node {\n * id: ID!\n * }\n *\n * type Review {\n * body: String\n * }\n *\n * type Query {\n * node: Node\n * review: Review\n * }\n * `);\n *\n * const Node = assertInterfaceType(schema.getType('Node'));\n * const User = assertObjectType(schema.getType('User'));\n * const Review = assertObjectType(schema.getType('Review'));\n *\n * schema.isSubType(Node, User); // => true\n * schema.isSubType(Node, Review); // => false\n * ```\n */\n\n isSubType(abstractType, maybeSubType) {\n let map = this._subTypeMap[abstractType.name];\n\n if (map === undefined) {\n map = Object.create(null);\n\n if (isUnionType(abstractType)) {\n for (const type of abstractType.getTypes()) {\n map[type.name] = true;\n }\n } else {\n const implementations = this.getImplementations(abstractType);\n\n for (const type of implementations.objects) {\n map[type.name] = true;\n }\n\n for (const type of implementations.interfaces) {\n map[type.name] = true;\n }\n }\n\n this._subTypeMap[abstractType.name] = map;\n }\n\n return map[maybeSubType.name] !== undefined;\n }\n /**\n * Returns directives available in this schema.\n * @returns Directives available in this schema.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * directive @upper on FIELD_DEFINITION\n *\n * type Query {\n * greeting: String @upper\n * }\n * `);\n *\n * schema.getDirectives().map((directive) => directive.name); // => ['include', 'skip', 'deprecated', 'specifiedBy', 'oneOf', 'upper']\n * ```\n */\n\n getDirectives() {\n return this._directives;\n }\n /**\n * Returns the current directive definition.\n * @param name - The GraphQL name to look up.\n * @returns The current directive definition, if known.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * directive @upper on FIELD_DEFINITION\n *\n * type Query {\n * greeting: String @upper\n * }\n * `);\n *\n * schema.getDirective('upper')?.name; // => 'upper'\n * schema.getDirective('missing'); // => undefined\n * ```\n */\n\n getDirective(name) {\n return this.getDirectives().find((directive) => directive.name === name);\n }\n /**\n * Returns a normalized configuration object for this object.\n *\n * The returned config preserves the original `assumeValid` flag so the schema\n * can be recreated with the same validation behavior.\n * @returns A configuration object that can be used to recreate this object.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql/utilities';\n * import { GraphQLSchema } from 'graphql/type';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * const config = schema.toConfig();\n * const schemaCopy = new GraphQLSchema(config);\n *\n * config.query?.name; // => 'Query'\n * schemaCopy.getQueryType()?.name; // => 'Query'\n * ```\n */\n\n toConfig() {\n return {\n description: this.description,\n query: this.getQueryType(),\n mutation: this.getMutationType(),\n subscription: this.getSubscriptionType(),\n types: Object.values(this.getTypeMap()),\n directives: this.getDirectives(),\n extensions: this.extensions,\n astNode: this.astNode,\n extensionASTNodes: this.extensionASTNodes,\n assumeValid: this.__validationErrors !== undefined,\n };\n }\n}\n\nfunction collectReferencedTypes(type, typeSet) {\n const namedType = getNamedType(type);\n\n if (!typeSet.has(namedType)) {\n typeSet.add(namedType);\n\n if (isUnionType(namedType)) {\n for (const memberType of namedType.getTypes()) {\n collectReferencedTypes(memberType, typeSet);\n }\n } else if (isObjectType(namedType) || isInterfaceType(namedType)) {\n for (const interfaceType of namedType.getInterfaces()) {\n collectReferencedTypes(interfaceType, typeSet);\n }\n\n for (const field of Object.values(namedType.getFields())) {\n collectReferencedTypes(field.type, typeSet);\n\n for (const arg of field.args) {\n collectReferencedTypes(arg.type, typeSet);\n }\n }\n } else if (isInputObjectType(namedType)) {\n for (const field of Object.values(namedType.getFields())) {\n collectReferencedTypes(field.type, typeSet);\n }\n }\n }\n\n return typeSet;\n}\n","/** @category Validation */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { OperationTypeNode } from '../language/ast.mjs';\nimport { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators.mjs';\nimport {\n isEnumType,\n isInputObjectType,\n isInputType,\n isInterfaceType,\n isNamedType,\n isNonNullType,\n isObjectType,\n isOutputType,\n isRequiredArgument,\n isRequiredInputField,\n isUnionType,\n} from './definition.mjs';\nimport { GraphQLDeprecatedDirective, isDirective } from './directives.mjs';\nimport { isIntrospectionType } from './introspection.mjs';\nimport { assertSchema } from './schema.mjs';\n/**\n * Implements the \"Type Validation\" sub-sections of the specification's\n * \"Type System\" section.\n *\n * Validation runs synchronously, returning an array of encountered errors, or\n * an empty array if no errors were encountered and the Schema is valid.\n * @param schema - GraphQL schema to use.\n * @returns Schema validation errors, or an empty array when the schema is valid.\n * @example\n * ```ts\n * import { validateSchema } from 'graphql/type';\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n * const errors = validateSchema(schema);\n *\n * errors; // => []\n * ```\n */\n\nexport function validateSchema(schema) {\n // First check to ensure the provided value is in fact a GraphQLSchema.\n assertSchema(schema); // If this Schema has already been validated, return the previous results.\n\n if (schema.__validationErrors) {\n return schema.__validationErrors;\n } // Validate the schema, producing a list of errors.\n\n const context = new SchemaValidationContext(schema);\n validateRootTypes(context);\n validateDirectives(context);\n validateTypes(context); // Persist the results of validation before returning to ensure validation\n // does not run multiple times for this schema.\n\n const errors = context.getErrors();\n schema.__validationErrors = errors;\n return errors;\n}\n/**\n * Utility function which asserts a schema is valid by throwing an error if\n * it is invalid.\n * @param schema - GraphQL schema to use.\n * @example\n * ```ts\n * import { assertValidSchema } from 'graphql/type';\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * assertValidSchema(schema); // does not throw\n * ```\n */\n\nexport function assertValidSchema(schema) {\n const errors = validateSchema(schema);\n\n if (errors.length !== 0) {\n throw new Error(errors.map((error) => error.message).join('\\n\\n'));\n }\n}\n\nclass SchemaValidationContext {\n constructor(schema) {\n this._errors = [];\n this.schema = schema;\n }\n\n reportError(message, nodes) {\n const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes;\n\n this._errors.push(\n new GraphQLError(message, {\n nodes: _nodes,\n }),\n );\n }\n\n getErrors() {\n return this._errors;\n }\n}\n\nfunction validateRootTypes(context) {\n const schema = context.schema;\n const queryType = schema.getQueryType();\n\n if (!queryType) {\n context.reportError('Query root type must be provided.', schema.astNode);\n } else if (!isObjectType(queryType)) {\n var _getOperationTypeNode;\n\n context.reportError(\n `Query root type must be Object type, it cannot be ${inspect(\n queryType,\n )}.`,\n (_getOperationTypeNode = getOperationTypeNode(\n schema,\n OperationTypeNode.QUERY,\n )) !== null && _getOperationTypeNode !== void 0\n ? _getOperationTypeNode\n : queryType.astNode,\n );\n }\n\n const mutationType = schema.getMutationType();\n\n if (mutationType && !isObjectType(mutationType)) {\n var _getOperationTypeNode2;\n\n context.reportError(\n 'Mutation root type must be Object type if provided, it cannot be ' +\n `${inspect(mutationType)}.`,\n (_getOperationTypeNode2 = getOperationTypeNode(\n schema,\n OperationTypeNode.MUTATION,\n )) !== null && _getOperationTypeNode2 !== void 0\n ? _getOperationTypeNode2\n : mutationType.astNode,\n );\n }\n\n const subscriptionType = schema.getSubscriptionType();\n\n if (subscriptionType && !isObjectType(subscriptionType)) {\n var _getOperationTypeNode3;\n\n context.reportError(\n 'Subscription root type must be Object type if provided, it cannot be ' +\n `${inspect(subscriptionType)}.`,\n (_getOperationTypeNode3 = getOperationTypeNode(\n schema,\n OperationTypeNode.SUBSCRIPTION,\n )) !== null && _getOperationTypeNode3 !== void 0\n ? _getOperationTypeNode3\n : subscriptionType.astNode,\n );\n }\n}\n\nfunction getOperationTypeNode(schema, operation) {\n var _flatMap$find;\n\n return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes]\n .flatMap(\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n (schemaNode) => {\n var _schemaNode$operation;\n\n return (\n /* c8 ignore next */\n (_schemaNode$operation =\n schemaNode === null || schemaNode === void 0\n ? void 0\n : schemaNode.operationTypes) !== null &&\n _schemaNode$operation !== void 0\n ? _schemaNode$operation\n : []\n );\n },\n )\n .find((operationNode) => operationNode.operation === operation)) === null ||\n _flatMap$find === void 0\n ? void 0\n : _flatMap$find.type;\n}\n\nfunction validateDirectives(context) {\n for (const directive of context.schema.getDirectives()) {\n // Ensure all directives are in fact GraphQL directives.\n if (!isDirective(directive)) {\n context.reportError(\n `Expected directive but got: ${inspect(directive)}.`,\n directive === null || directive === void 0 ? void 0 : directive.astNode,\n );\n continue;\n } // Ensure they are named correctly.\n\n validateName(context, directive);\n\n if (directive.locations.length === 0) {\n context.reportError(\n `Directive @${directive.name} must include 1 or more locations.`,\n directive.astNode,\n );\n } // Ensure the arguments are valid.\n\n for (const arg of directive.args) {\n // Ensure they are named correctly.\n validateName(context, arg); // Ensure the type is an input type.\n\n if (!isInputType(arg.type)) {\n context.reportError(\n `The type of @${directive.name}(${arg.name}:) must be Input Type ` +\n `but got: ${inspect(arg.type)}.`,\n arg.astNode,\n );\n }\n\n if (isRequiredArgument(arg) && arg.deprecationReason != null) {\n var _arg$astNode;\n\n context.reportError(\n `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`,\n [\n getDeprecatedDirectiveNode(arg.astNode),\n (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0\n ? void 0\n : _arg$astNode.type,\n ],\n );\n }\n }\n }\n}\n\nfunction validateName(context, node) {\n // Ensure names are valid, however introspection types opt out.\n if (node.name.startsWith('__')) {\n context.reportError(\n `Name \"${node.name}\" must not begin with \"__\", which is reserved by GraphQL introspection.`,\n node.astNode,\n );\n }\n}\n\nfunction validateTypes(context) {\n const validateInputObjectCircularRefs =\n createInputObjectCircularRefsValidator(context);\n const typeMap = context.schema.getTypeMap();\n\n for (const type of Object.values(typeMap)) {\n // Ensure all provided types are in fact GraphQL type.\n if (!isNamedType(type)) {\n context.reportError(\n `Expected GraphQL named type but got: ${inspect(type)}.`,\n type.astNode,\n );\n continue;\n } // Ensure it is named correctly (excluding introspection types).\n\n if (!isIntrospectionType(type)) {\n validateName(context, type);\n }\n\n if (isObjectType(type)) {\n // Ensure fields are valid\n validateFields(context, type); // Ensure objects implement the interfaces they claim to.\n\n validateInterfaces(context, type);\n } else if (isInterfaceType(type)) {\n // Ensure fields are valid.\n validateFields(context, type); // Ensure interfaces implement the interfaces they claim to.\n\n validateInterfaces(context, type);\n } else if (isUnionType(type)) {\n // Ensure Unions include valid member types.\n validateUnionMembers(context, type);\n } else if (isEnumType(type)) {\n // Ensure Enums have valid values.\n validateEnumValues(context, type);\n } else if (isInputObjectType(type)) {\n // Ensure Input Object fields are valid.\n validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references\n\n validateInputObjectCircularRefs(type);\n }\n }\n}\n\nfunction validateFields(context, type) {\n const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields.\n\n if (fields.length === 0) {\n context.reportError(`Type ${type.name} must define one or more fields.`, [\n type.astNode,\n ...type.extensionASTNodes,\n ]);\n }\n\n for (const field of fields) {\n // Ensure they are named correctly.\n validateName(context, field); // Ensure the type is an output type\n\n if (!isOutputType(field.type)) {\n var _field$astNode;\n\n context.reportError(\n `The type of ${type.name}.${field.name} must be Output Type ` +\n `but got: ${inspect(field.type)}.`,\n (_field$astNode = field.astNode) === null || _field$astNode === void 0\n ? void 0\n : _field$astNode.type,\n );\n } // Ensure the arguments are valid\n\n for (const arg of field.args) {\n const argName = arg.name; // Ensure they are named correctly.\n\n validateName(context, arg); // Ensure the type is an input type\n\n if (!isInputType(arg.type)) {\n var _arg$astNode2;\n\n context.reportError(\n `The type of ${type.name}.${field.name}(${argName}:) must be Input ` +\n `Type but got: ${inspect(arg.type)}.`,\n (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0\n ? void 0\n : _arg$astNode2.type,\n );\n }\n\n if (isRequiredArgument(arg) && arg.deprecationReason != null) {\n var _arg$astNode3;\n\n context.reportError(\n `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`,\n [\n getDeprecatedDirectiveNode(arg.astNode),\n (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0\n ? void 0\n : _arg$astNode3.type,\n ],\n );\n }\n }\n }\n}\n\nfunction validateInterfaces(context, type) {\n const ifaceTypeNames = Object.create(null);\n\n for (const iface of type.getInterfaces()) {\n if (!isInterfaceType(iface)) {\n context.reportError(\n `Type ${inspect(type)} must only implement Interface types, ` +\n `it cannot implement ${inspect(iface)}.`,\n getAllImplementsInterfaceNodes(type, iface),\n );\n continue;\n }\n\n if (type === iface) {\n context.reportError(\n `Type ${type.name} cannot implement itself because it would create a circular reference.`,\n getAllImplementsInterfaceNodes(type, iface),\n );\n continue;\n }\n\n if (ifaceTypeNames[iface.name]) {\n context.reportError(\n `Type ${type.name} can only implement ${iface.name} once.`,\n getAllImplementsInterfaceNodes(type, iface),\n );\n continue;\n }\n\n ifaceTypeNames[iface.name] = true;\n validateTypeImplementsAncestors(context, type, iface);\n validateTypeImplementsInterface(context, type, iface);\n }\n}\n\nfunction validateTypeImplementsInterface(context, type, iface) {\n const typeFieldMap = type.getFields(); // Assert each interface field is implemented.\n\n for (const ifaceField of Object.values(iface.getFields())) {\n const fieldName = ifaceField.name;\n const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type.\n\n if (!typeField) {\n context.reportError(\n `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`,\n [ifaceField.astNode, type.astNode, ...type.extensionASTNodes],\n );\n continue;\n } // Assert interface field type is satisfied by type field type, by being\n // a valid subtype. (covariant)\n\n if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) {\n var _ifaceField$astNode, _typeField$astNode;\n\n context.reportError(\n `Interface field ${iface.name}.${fieldName} expects type ` +\n `${inspect(ifaceField.type)} but ${type.name}.${fieldName} ` +\n `is type ${inspect(typeField.type)}.`,\n [\n (_ifaceField$astNode = ifaceField.astNode) === null ||\n _ifaceField$astNode === void 0\n ? void 0\n : _ifaceField$astNode.type,\n (_typeField$astNode = typeField.astNode) === null ||\n _typeField$astNode === void 0\n ? void 0\n : _typeField$astNode.type,\n ],\n );\n } // Assert each interface field arg is implemented.\n\n for (const ifaceArg of ifaceField.args) {\n const argName = ifaceArg.name;\n const typeArg = typeField.args.find((arg) => arg.name === argName); // Assert interface field arg exists on object field.\n\n if (!typeArg) {\n context.reportError(\n `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`,\n [ifaceArg.astNode, typeField.astNode],\n );\n continue;\n } // Assert interface field arg type matches object field arg type.\n // (invariant)\n // TODO: change to contravariant?\n\n if (!isEqualType(ifaceArg.type, typeArg.type)) {\n var _ifaceArg$astNode, _typeArg$astNode;\n\n context.reportError(\n `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` +\n `expects type ${inspect(ifaceArg.type)} but ` +\n `${type.name}.${fieldName}(${argName}:) is type ` +\n `${inspect(typeArg.type)}.`,\n [\n (_ifaceArg$astNode = ifaceArg.astNode) === null ||\n _ifaceArg$astNode === void 0\n ? void 0\n : _ifaceArg$astNode.type,\n (_typeArg$astNode = typeArg.astNode) === null ||\n _typeArg$astNode === void 0\n ? void 0\n : _typeArg$astNode.type,\n ],\n );\n } // TODO: validate default values?\n } // Assert additional arguments must not be required.\n\n for (const typeArg of typeField.args) {\n const argName = typeArg.name;\n const ifaceArg = ifaceField.args.find((arg) => arg.name === argName);\n\n if (!ifaceArg && isRequiredArgument(typeArg)) {\n context.reportError(\n `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`,\n [typeArg.astNode, ifaceField.astNode],\n );\n }\n }\n }\n}\n\nfunction validateTypeImplementsAncestors(context, type, iface) {\n const ifaceInterfaces = type.getInterfaces();\n\n for (const transitive of iface.getInterfaces()) {\n if (!ifaceInterfaces.includes(transitive)) {\n context.reportError(\n transitive === type\n ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.`\n : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`,\n [\n ...getAllImplementsInterfaceNodes(iface, transitive),\n ...getAllImplementsInterfaceNodes(type, iface),\n ],\n );\n }\n }\n}\n\nfunction validateUnionMembers(context, union) {\n const memberTypes = union.getTypes();\n\n if (memberTypes.length === 0) {\n context.reportError(\n `Union type ${union.name} must define one or more member types.`,\n [union.astNode, ...union.extensionASTNodes],\n );\n }\n\n const includedTypeNames = Object.create(null);\n\n for (const memberType of memberTypes) {\n if (includedTypeNames[memberType.name]) {\n context.reportError(\n `Union type ${union.name} can only include type ${memberType.name} once.`,\n getUnionMemberTypeNodes(union, memberType.name),\n );\n continue;\n }\n\n includedTypeNames[memberType.name] = true;\n\n if (!isObjectType(memberType)) {\n context.reportError(\n `Union type ${union.name} can only include Object types, ` +\n `it cannot include ${inspect(memberType)}.`,\n getUnionMemberTypeNodes(union, String(memberType)),\n );\n }\n }\n}\n\nfunction validateEnumValues(context, enumType) {\n const enumValues = enumType.getValues();\n\n if (enumValues.length === 0) {\n context.reportError(\n `Enum type ${enumType.name} must define one or more values.`,\n [enumType.astNode, ...enumType.extensionASTNodes],\n );\n }\n\n for (const enumValue of enumValues) {\n // Ensure valid name.\n validateName(context, enumValue);\n }\n}\n\nfunction validateInputFields(context, inputObj) {\n const fields = Object.values(inputObj.getFields());\n\n if (fields.length === 0) {\n context.reportError(\n `Input Object type ${inputObj.name} must define one or more fields.`,\n [inputObj.astNode, ...inputObj.extensionASTNodes],\n );\n } // Ensure the arguments are valid\n\n for (const field of fields) {\n // Ensure they are named correctly.\n validateName(context, field); // Ensure the type is an input type\n\n if (!isInputType(field.type)) {\n var _field$astNode2;\n\n context.reportError(\n `The type of ${inputObj.name}.${field.name} must be Input Type ` +\n `but got: ${inspect(field.type)}.`,\n (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0\n ? void 0\n : _field$astNode2.type,\n );\n }\n\n if (isRequiredInputField(field) && field.deprecationReason != null) {\n var _field$astNode3;\n\n context.reportError(\n `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`,\n [\n getDeprecatedDirectiveNode(field.astNode),\n (_field$astNode3 = field.astNode) === null ||\n _field$astNode3 === void 0\n ? void 0\n : _field$astNode3.type,\n ],\n );\n }\n\n if (inputObj.isOneOf) {\n validateOneOfInputObjectField(inputObj, field, context);\n }\n }\n}\n\nfunction validateOneOfInputObjectField(type, field, context) {\n if (isNonNullType(field.type)) {\n var _field$astNode4;\n\n context.reportError(\n `OneOf input field ${type.name}.${field.name} must be nullable.`,\n (_field$astNode4 = field.astNode) === null || _field$astNode4 === void 0\n ? void 0\n : _field$astNode4.type,\n );\n }\n\n if (field.defaultValue !== undefined) {\n context.reportError(\n `OneOf input field ${type.name}.${field.name} cannot have a default value.`,\n field.astNode,\n );\n }\n}\n\nfunction createInputObjectCircularRefsValidator(context) {\n // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'.\n // Tracks already visited types to maintain O(N) and to ensure that cycles\n // are not redundantly reported.\n const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors\n\n const fieldPath = []; // Position in the type path\n\n const fieldPathIndexByTypeName = Object.create(null);\n return detectCycleRecursive; // This does a straight-forward DFS to find cycles.\n // It does not terminate when a cycle was found but continues to explore\n // the graph to find all possible cycles.\n\n function detectCycleRecursive(inputObj) {\n if (visitedTypes[inputObj.name]) {\n return;\n }\n\n visitedTypes[inputObj.name] = true;\n fieldPathIndexByTypeName[inputObj.name] = fieldPath.length;\n const fields = Object.values(inputObj.getFields());\n\n for (const field of fields) {\n if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) {\n const fieldType = field.type.ofType;\n const cycleIndex = fieldPathIndexByTypeName[fieldType.name];\n fieldPath.push(field);\n\n if (cycleIndex === undefined) {\n detectCycleRecursive(fieldType);\n } else {\n const cyclePath = fieldPath.slice(cycleIndex);\n const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.');\n context.reportError(\n `Cannot reference Input Object \"${fieldType.name}\" within itself through a series of non-null fields: \"${pathStr}\".`,\n cyclePath.map((fieldObj) => fieldObj.astNode),\n );\n }\n\n fieldPath.pop();\n }\n }\n\n fieldPathIndexByTypeName[inputObj.name] = undefined;\n }\n}\n\nfunction getAllImplementsInterfaceNodes(type, iface) {\n const { astNode, extensionASTNodes } = type;\n const nodes =\n astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n return nodes\n .flatMap((typeNode) => {\n var _typeNode$interfaces;\n\n return (\n /* c8 ignore next */\n (_typeNode$interfaces = typeNode.interfaces) !== null &&\n _typeNode$interfaces !== void 0\n ? _typeNode$interfaces\n : []\n );\n })\n .filter((ifaceNode) => ifaceNode.name.value === iface.name);\n}\n\nfunction getUnionMemberTypeNodes(union, typeName) {\n const { astNode, extensionASTNodes } = union;\n const nodes =\n astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n return nodes\n .flatMap((unionNode) => {\n var _unionNode$types;\n\n return (\n /* c8 ignore next */\n (_unionNode$types = unionNode.types) !== null &&\n _unionNode$types !== void 0\n ? _unionNode$types\n : []\n );\n })\n .filter((typeNode) => typeNode.name.value === typeName);\n}\n\nfunction getDeprecatedDirectiveNode(definitionNode) {\n var _definitionNode$direc;\n\n return definitionNode === null || definitionNode === void 0\n ? void 0\n : (_definitionNode$direc = definitionNode.directives) === null ||\n _definitionNode$direc === void 0\n ? void 0\n : _definitionNode$direc.find(\n (node) => node.name.value === GraphQLDeprecatedDirective.name,\n );\n}\n","/** @category Values */\nimport { Kind } from '../language/kinds.mjs';\nimport { GraphQLList, GraphQLNonNull } from '../type/definition.mjs';\n\n/** @internal */\nexport function typeFromAST(schema, typeNode) {\n switch (typeNode.kind) {\n case Kind.LIST_TYPE: {\n const innerType = typeFromAST(schema, typeNode.type);\n return innerType && new GraphQLList(innerType);\n }\n\n case Kind.NON_NULL_TYPE: {\n const innerType = typeFromAST(schema, typeNode.type);\n return innerType && new GraphQLNonNull(innerType);\n }\n\n case Kind.NAMED_TYPE:\n return schema.getType(typeNode.name.value);\n }\n}\n","/** @category Type Info */\nimport { isNode } from '../language/ast.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { getEnterLeaveForKind } from '../language/visitor.mjs';\nimport {\n getNamedType,\n getNullableType,\n isCompositeType,\n isEnumType,\n isInputObjectType,\n isInputType,\n isInterfaceType,\n isListType,\n isObjectType,\n isOutputType,\n} from '../type/definition.mjs';\nimport {\n SchemaMetaFieldDef,\n TypeMetaFieldDef,\n TypeNameMetaFieldDef,\n} from '../type/introspection.mjs';\nimport { typeFromAST } from './typeFromAST.mjs';\n/**\n * TypeInfo is a utility class which, given a GraphQL schema, can keep track\n * of the current field and type definitions at any point in a GraphQL document\n * AST during a recursive descent by calling `enter(node)` and `leave(node)`.\n */\n\nexport class TypeInfo {\n /**\n * Creates a TypeInfo instance.\n * @param schema - Schema used for type lookups.\n * @param initialType - Optional type to use at the start of traversal.\n * @param getFieldDefFn - Optional field definition lookup override.\n * @example\n * ```ts\n * // Track field types during a visitWithTypeInfo traversal.\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const seenTypes = [];\n *\n * visit(\n * parse('{ greeting }'),\n * visitWithTypeInfo(typeInfo, {\n * Field: () => {\n * seenTypes.push(String(typeInfo.getType()));\n * },\n * }),\n * );\n *\n * seenTypes; // => ['String']\n * ```\n * @example\n * ```ts\n * // This variant starts from an initial type and supplies a field definition resolver.\n * import { Kind } from 'graphql/language';\n * import { GraphQLString } from 'graphql/type';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema, schema.getQueryType(), () => ({\n * name: 'virtualGreeting',\n * description: undefined,\n * type: GraphQLString,\n * args: [],\n * resolve: undefined,\n * subscribe: undefined,\n * deprecationReason: undefined,\n * extensions: Object.create(null),\n * astNode: undefined,\n * }));\n *\n * typeInfo.enter({\n * kind: Kind.SELECTION_SET,\n * selections: [],\n * });\n * typeInfo.enter({\n * kind: Kind.FIELD,\n * name: { kind: Kind.NAME, value: 'ignored' },\n * });\n *\n * typeInfo.getFieldDef()?.name; // => 'virtualGreeting'\n * String(typeInfo.getType()); // => 'String'\n * ```\n */\n constructor(\n schema,\n /**\n * Initial type may be provided in rare cases to facilitate traversals\n * beginning somewhere other than documents.\n */\n initialType,\n /**\n * Deprecated field definition lookup override. Use TypeInfo's built-in\n * field definition lookup instead because this hook will be removed in v17.\n * @deprecated will be removed in 17.0.0\n */\n getFieldDefFn,\n ) {\n this._schema = schema;\n this._typeStack = [];\n this._parentTypeStack = [];\n this._inputTypeStack = [];\n this._fieldDefStack = [];\n this._defaultValueStack = [];\n this._directive = null;\n this._argument = null;\n this._enumValue = null;\n this._getFieldDef =\n getFieldDefFn !== null && getFieldDefFn !== void 0\n ? getFieldDefFn\n : getFieldDef;\n\n if (initialType) {\n if (isInputType(initialType)) {\n this._inputTypeStack.push(initialType);\n }\n\n if (isCompositeType(initialType)) {\n this._parentTypeStack.push(initialType);\n }\n\n if (isOutputType(initialType)) {\n this._typeStack.push(initialType);\n }\n }\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'TypeInfo';\n }\n /**\n * Returns the current output type at this point in traversal.\n * @returns The current output type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * viewer: User\n * }\n *\n * type User {\n * name: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const fieldTypes = {};\n *\n * visit(\n * parse('{ viewer { name } }'),\n * visitWithTypeInfo(typeInfo, {\n * Field: (node) => {\n * fieldTypes[node.name.value] = String(typeInfo.getType());\n * },\n * }),\n * );\n *\n * fieldTypes; // => { viewer: 'User', name: 'String' }\n * ```\n */\n\n getType() {\n if (this._typeStack.length > 0) {\n return this._typeStack[this._typeStack.length - 1];\n }\n }\n /**\n * Returns the current parent composite type.\n * @returns The current parent composite type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * viewer: User\n * }\n *\n * type User {\n * name: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const parentTypes = {};\n *\n * visit(\n * parse('{ viewer { name } }'),\n * visitWithTypeInfo(typeInfo, {\n * Field: (node) => {\n * parentTypes[node.name.value] = String(typeInfo.getParentType());\n * },\n * }),\n * );\n *\n * parentTypes; // => { viewer: 'Query', name: 'User' }\n * ```\n */\n\n getParentType() {\n if (this._parentTypeStack.length > 0) {\n return this._parentTypeStack[this._parentTypeStack.length - 1];\n }\n }\n /**\n * Returns the current input type at this point in traversal.\n * @returns The current input type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(stars: Int!, sort: Sort = NEWEST): [String]\n * }\n *\n * enum Sort {\n * NEWEST\n * OLDEST\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const inputTypes = {};\n *\n * visit(\n * parse('{ reviews(stars: 5, sort: OLDEST) }'),\n * visitWithTypeInfo(typeInfo, {\n * Argument: (node) => {\n * inputTypes[node.name.value] = String(typeInfo.getInputType());\n * },\n * }),\n * );\n *\n * inputTypes; // => { stars: 'Int!', sort: 'Sort' }\n * ```\n */\n\n getInputType() {\n if (this._inputTypeStack.length > 0) {\n return this._inputTypeStack[this._inputTypeStack.length - 1];\n }\n }\n /**\n * Returns the parent input type for the current input position.\n * @returns The parent input type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * input ReviewFilter {\n * stars: Int!\n * }\n *\n * type Query {\n * reviews(filter: ReviewFilter): [String]\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const parentInputTypes = {};\n *\n * visit(\n * parse('{ reviews(filter: { stars: 5 }) }'),\n * visitWithTypeInfo(typeInfo, {\n * ObjectField: (node) => {\n * parentInputTypes[node.name.value] = String(typeInfo.getParentInputType());\n * },\n * }),\n * );\n *\n * parentInputTypes; // => { stars: 'ReviewFilter' }\n * ```\n */\n\n getParentInputType() {\n if (this._inputTypeStack.length > 1) {\n return this._inputTypeStack[this._inputTypeStack.length - 2];\n }\n }\n /**\n * Returns the current field definition.\n * @returns The current field definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * let fieldName;\n *\n * visit(\n * parse('{ greeting }'),\n * visitWithTypeInfo(typeInfo, {\n * Field: () => {\n * fieldName = typeInfo.getFieldDef()?.name;\n * },\n * }),\n * );\n *\n * fieldName; // => 'greeting'\n * ```\n */\n\n getFieldDef() {\n if (this._fieldDefStack.length > 0) {\n return this._fieldDefStack[this._fieldDefStack.length - 1];\n }\n }\n /**\n * Returns the default value for the current input position.\n * @returns The current default value, if one is available.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(limit: Int = 10): [String]\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * let defaultLimit;\n *\n * visit(\n * parse('{ reviews(limit: 5) }'),\n * visitWithTypeInfo(typeInfo, {\n * Argument: () => {\n * defaultLimit = typeInfo.getDefaultValue();\n * },\n * }),\n * );\n *\n * defaultLimit; // => 10\n * ```\n */\n\n getDefaultValue() {\n if (this._defaultValueStack.length > 0) {\n return this._defaultValueStack[this._defaultValueStack.length - 1];\n }\n }\n /**\n * Returns the current directive definition.\n * @returns The current directive definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * let directiveName;\n *\n * visit(\n * parse('{ greeting @include(if: true) }'),\n * visitWithTypeInfo(typeInfo, {\n * Directive: () => {\n * directiveName = typeInfo.getDirective()?.name;\n * },\n * }),\n * );\n *\n * directiveName; // => 'include'\n * ```\n */\n\n getDirective() {\n return this._directive;\n }\n /**\n * Returns the current argument definition.\n * @returns The current argument definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(limit: Int = 10): [String]\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * let argumentName;\n *\n * visit(\n * parse('{ reviews(limit: 5) }'),\n * visitWithTypeInfo(typeInfo, {\n * Argument: () => {\n * argumentName = typeInfo.getArgument()?.name;\n * },\n * }),\n * );\n *\n * argumentName; // => 'limit'\n * ```\n */\n\n getArgument() {\n return this._argument;\n }\n /**\n * Returns the current enum value definition.\n * @returns The current enum value definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * enum Sort {\n * NEWEST\n * OLDEST\n * }\n *\n * type Query {\n * reviews(sort: Sort = NEWEST): [String]\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * let enumValueName;\n *\n * visit(\n * parse('{ reviews(sort: OLDEST) }'),\n * visitWithTypeInfo(typeInfo, {\n * EnumValue: () => {\n * enumValueName = typeInfo.getEnumValue()?.name;\n * },\n * }),\n * );\n *\n * enumValueName; // => 'OLDEST'\n * ```\n */\n\n getEnumValue() {\n return this._enumValue;\n }\n /**\n * Updates this TypeInfo instance for an entered AST node.\n * @param node - AST node being entered.\n * @returns Nothing.\n * @example\n * ```ts\n * import { Kind, parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const operation = document.definitions[0];\n * const selectionSet = operation.selectionSet;\n * const field = selectionSet.selections[0];\n * const typeInfo = new TypeInfo(schema);\n *\n * typeInfo.enter(operation);\n * typeInfo.enter(selectionSet);\n * typeInfo.enter(field);\n *\n * field.kind; // => Kind.FIELD\n * typeInfo.getParentType()?.name; // => 'Query'\n * String(typeInfo.getType()); // => 'String'\n * ```\n */\n\n enter(node) {\n const schema = this._schema; // Note: many of the types below are explicitly typed as \"unknown\" to drop\n // any assumptions of a valid schema to ensure runtime types are properly\n // checked before continuing since TypeInfo is used as part of validation\n // which occurs before guarantees of schema and document validity.\n\n switch (node.kind) {\n case Kind.SELECTION_SET: {\n const namedType = getNamedType(this.getType());\n\n this._parentTypeStack.push(\n isCompositeType(namedType) ? namedType : undefined,\n );\n\n break;\n }\n\n case Kind.FIELD: {\n const parentType = this.getParentType();\n let fieldDef;\n let fieldType;\n\n if (parentType) {\n fieldDef = this._getFieldDef(schema, parentType, node);\n\n if (fieldDef) {\n fieldType = fieldDef.type;\n }\n }\n\n this._fieldDefStack.push(fieldDef);\n\n this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined);\n\n break;\n }\n\n case Kind.DIRECTIVE:\n this._directive = schema.getDirective(node.name.value);\n break;\n\n case Kind.OPERATION_DEFINITION: {\n const rootType = schema.getRootType(node.operation);\n\n this._typeStack.push(isObjectType(rootType) ? rootType : undefined);\n\n break;\n }\n\n case Kind.INLINE_FRAGMENT:\n case Kind.FRAGMENT_DEFINITION: {\n const typeConditionAST = node.typeCondition;\n const outputType = typeConditionAST\n ? typeFromAST(schema, typeConditionAST)\n : getNamedType(this.getType());\n\n this._typeStack.push(isOutputType(outputType) ? outputType : undefined);\n\n break;\n }\n\n case Kind.VARIABLE_DEFINITION: {\n const inputType = typeFromAST(schema, node.type);\n\n this._inputTypeStack.push(\n isInputType(inputType) ? inputType : undefined,\n );\n\n break;\n }\n\n case Kind.ARGUMENT: {\n var _this$getDirective;\n\n let argDef;\n let argType;\n const fieldOrDirective =\n (_this$getDirective = this.getDirective()) !== null &&\n _this$getDirective !== void 0\n ? _this$getDirective\n : this.getFieldDef();\n\n if (fieldOrDirective) {\n argDef = fieldOrDirective.args.find(\n (arg) => arg.name === node.name.value,\n );\n\n if (argDef) {\n argType = argDef.type;\n }\n }\n\n this._argument = argDef;\n\n this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined);\n\n this._inputTypeStack.push(isInputType(argType) ? argType : undefined);\n\n break;\n }\n\n case Kind.LIST: {\n const listType = getNullableType(this.getInputType());\n const itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value.\n\n this._defaultValueStack.push(undefined);\n\n this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined);\n\n break;\n }\n\n case Kind.OBJECT_FIELD: {\n const objectType = getNamedType(this.getInputType());\n let inputFieldType;\n let inputField;\n\n if (isInputObjectType(objectType)) {\n inputField = objectType.getFields()[node.name.value];\n\n if (inputField) {\n inputFieldType = inputField.type;\n }\n }\n\n this._defaultValueStack.push(\n inputField ? inputField.defaultValue : undefined,\n );\n\n this._inputTypeStack.push(\n isInputType(inputFieldType) ? inputFieldType : undefined,\n );\n\n break;\n }\n\n case Kind.ENUM: {\n const enumType = getNamedType(this.getInputType());\n let enumValue;\n\n if (isEnumType(enumType)) {\n enumValue = enumType.getValue(node.value);\n }\n\n this._enumValue = enumValue;\n break;\n }\n\n default: // Ignore other nodes\n }\n }\n /**\n * Updates this TypeInfo instance for a left AST node.\n * @param node - AST node being entered.\n * @returns Nothing.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const operation = document.definitions[0];\n * const selectionSet = operation.selectionSet;\n * const field = selectionSet.selections[0];\n * const typeInfo = new TypeInfo(schema);\n *\n * typeInfo.enter(operation);\n * typeInfo.enter(selectionSet);\n * typeInfo.enter(field);\n * String(typeInfo.getType()); // => 'String'\n *\n * typeInfo.leave(field);\n * typeInfo.getType(); // => undefined\n * ```\n */\n\n leave(node) {\n switch (node.kind) {\n case Kind.SELECTION_SET:\n this._parentTypeStack.pop();\n\n break;\n\n case Kind.FIELD:\n this._fieldDefStack.pop();\n\n this._typeStack.pop();\n\n break;\n\n case Kind.DIRECTIVE:\n this._directive = null;\n break;\n\n case Kind.OPERATION_DEFINITION:\n case Kind.INLINE_FRAGMENT:\n case Kind.FRAGMENT_DEFINITION:\n this._typeStack.pop();\n\n break;\n\n case Kind.VARIABLE_DEFINITION:\n this._inputTypeStack.pop();\n\n break;\n\n case Kind.ARGUMENT:\n this._argument = null;\n\n this._defaultValueStack.pop();\n\n this._inputTypeStack.pop();\n\n break;\n\n case Kind.LIST:\n case Kind.OBJECT_FIELD:\n this._defaultValueStack.pop();\n\n this._inputTypeStack.pop();\n\n break;\n\n case Kind.ENUM:\n this._enumValue = null;\n break;\n\n default: // Ignore other nodes\n }\n }\n}\n\n/**\n * Not exactly the same as the executor's definition of getFieldDef, in this\n * statically evaluated environment we do not always have an Object type,\n * and need to handle Interface and Union types.\n *\n * @internal\n */\nfunction getFieldDef(schema, parentType, fieldNode) {\n const name = fieldNode.name.value;\n\n if (\n name === SchemaMetaFieldDef.name &&\n schema.getQueryType() === parentType\n ) {\n return SchemaMetaFieldDef;\n }\n\n if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) {\n return TypeMetaFieldDef;\n }\n\n if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) {\n return TypeNameMetaFieldDef;\n }\n\n if (isObjectType(parentType) || isInterfaceType(parentType)) {\n return parentType.getFields()[name];\n }\n}\n/**\n * Creates a new visitor instance which maintains a provided TypeInfo instance\n * along with visiting visitor.\n * @param typeInfo - TypeInfo instance to update during traversal.\n * @param visitor - Visitor callbacks to wrap with TypeInfo updates.\n * @returns A visitor that keeps TypeInfo in sync while delegating callbacks.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const typeInfo = new TypeInfo(schema);\n * const fields = [];\n *\n * visit(\n * parse('{ greeting }'),\n * visitWithTypeInfo(typeInfo, {\n * Field: (node) => {\n * fields.push({\n * name: node.name.value,\n * parentType: String(typeInfo.getParentType()),\n * type: String(typeInfo.getType()),\n * });\n * },\n * }),\n * );\n *\n * fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }]\n * ```\n */\n\nexport function visitWithTypeInfo(typeInfo, visitor) {\n return {\n enter(...args) {\n const node = args[0];\n typeInfo.enter(node);\n const fn = getEnterLeaveForKind(visitor, node.kind).enter;\n\n if (fn) {\n const result = fn.apply(visitor, args);\n\n if (result !== undefined) {\n typeInfo.leave(node);\n\n if (isNode(result)) {\n typeInfo.enter(result);\n }\n }\n\n return result;\n }\n },\n\n leave(...args) {\n const node = args[0];\n const fn = getEnterLeaveForKind(visitor, node.kind).leave;\n let result;\n\n if (fn) {\n result = fn.apply(visitor, args);\n }\n\n typeInfo.leave(node);\n return result;\n },\n };\n}\n","/** @category AST Predicates */\nimport { Kind } from './kinds.mjs';\n/**\n * Returns true when the AST node is a definition node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a definition node.\n * @example\n * ```ts\n * import { parse, isDefinitionNode } from 'graphql/language';\n *\n * const document = parse('{ hello }');\n *\n * isDefinitionNode(document.definitions[0]); // => true\n * isDefinitionNode(document); // => false\n * ```\n */\n\nexport function isDefinitionNode(node) {\n return (\n isExecutableDefinitionNode(node) ||\n isTypeSystemDefinitionNode(node) ||\n isTypeSystemExtensionNode(node)\n );\n}\n/**\n * Returns true when the AST node is an executable definition node.\n * @param node - The AST node to test.\n * @returns True when the AST node is an executable definition node.\n * @example\n * ```ts\n * import { parse, isExecutableDefinitionNode } from 'graphql/language';\n *\n * const query = parse('{ hello }');\n * const schema = parse('type Query { hello: String }');\n *\n * isExecutableDefinitionNode(query.definitions[0]); // => true\n * isExecutableDefinitionNode(schema.definitions[0]); // => false\n * ```\n */\n\nexport function isExecutableDefinitionNode(node) {\n return (\n node.kind === Kind.OPERATION_DEFINITION ||\n node.kind === Kind.FRAGMENT_DEFINITION\n );\n}\n/**\n * Returns true when the AST node is a selection node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a selection node.\n * @example\n * ```ts\n * import { Kind, isSelectionNode } from 'graphql/language';\n *\n * const field = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'hello' } };\n * const document = { kind: Kind.DOCUMENT, definitions: [] };\n *\n * isSelectionNode(field); // => true\n * isSelectionNode(document); // => false\n * ```\n */\n\nexport function isSelectionNode(node) {\n return (\n node.kind === Kind.FIELD ||\n node.kind === Kind.FRAGMENT_SPREAD ||\n node.kind === Kind.INLINE_FRAGMENT\n );\n}\n/**\n * Returns true when the AST node is a value node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a value node.\n * @example\n * ```ts\n * import { parseType, parseValue, isValueNode } from 'graphql/language';\n *\n * const value = parseValue('[42]');\n * const type = parseType('[String!]');\n *\n * isValueNode(value); // => true\n * isValueNode(type); // => false\n * ```\n */\n\nexport function isValueNode(node) {\n return (\n node.kind === Kind.VARIABLE ||\n node.kind === Kind.INT ||\n node.kind === Kind.FLOAT ||\n node.kind === Kind.STRING ||\n node.kind === Kind.BOOLEAN ||\n node.kind === Kind.NULL ||\n node.kind === Kind.ENUM ||\n node.kind === Kind.LIST ||\n node.kind === Kind.OBJECT\n );\n}\n/**\n * Returns true when the AST node is a constant value node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a constant value node.\n * @example\n * ```ts\n * import { parseConstValue, parseValue, isConstValueNode } from 'graphql/language';\n *\n * const value = parseConstValue('[42]');\n * const variable = parseValue('$id');\n *\n * isConstValueNode(value); // => true\n * isConstValueNode(variable); // => false\n * ```\n */\n\nexport function isConstValueNode(node) {\n return (\n isValueNode(node) &&\n (node.kind === Kind.LIST\n ? node.values.some(isConstValueNode)\n : node.kind === Kind.OBJECT\n ? node.fields.some((field) => isConstValueNode(field.value))\n : node.kind !== Kind.VARIABLE)\n );\n}\n/**\n * Returns true when the AST node is a type node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a type node.\n * @example\n * ```ts\n * import { parseType, parseValue, isTypeNode } from 'graphql/language';\n *\n * const type = parseType('[String!]');\n * const value = parseValue('[42]');\n *\n * isTypeNode(type); // => true\n * isTypeNode(value); // => false\n * ```\n */\n\nexport function isTypeNode(node) {\n return (\n node.kind === Kind.NAMED_TYPE ||\n node.kind === Kind.LIST_TYPE ||\n node.kind === Kind.NON_NULL_TYPE\n );\n}\n/**\n * Returns true when the AST node is a type system definition node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a type system definition node.\n * @example\n * ```ts\n * import { parse, isTypeSystemDefinitionNode } from 'graphql/language';\n *\n * const schema = parse('type Query { hello: String }');\n * const query = parse('{ hello }');\n *\n * isTypeSystemDefinitionNode(schema.definitions[0]); // => true\n * isTypeSystemDefinitionNode(query.definitions[0]); // => false\n * ```\n */\n\nexport function isTypeSystemDefinitionNode(node) {\n return (\n node.kind === Kind.SCHEMA_DEFINITION ||\n isTypeDefinitionNode(node) ||\n node.kind === Kind.DIRECTIVE_DEFINITION\n );\n}\n/**\n * Returns true when the AST node is a type definition node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a type definition node.\n * @example\n * ```ts\n * import { parse, isTypeDefinitionNode } from 'graphql/language';\n *\n * const typeDefinition = parse('type Query { hello: String }');\n * const directiveDefinition = parse('directive @cache on FIELD');\n *\n * isTypeDefinitionNode(typeDefinition.definitions[0]); // => true\n * isTypeDefinitionNode(directiveDefinition.definitions[0]); // => false\n * ```\n */\n\nexport function isTypeDefinitionNode(node) {\n return (\n node.kind === Kind.SCALAR_TYPE_DEFINITION ||\n node.kind === Kind.OBJECT_TYPE_DEFINITION ||\n node.kind === Kind.INTERFACE_TYPE_DEFINITION ||\n node.kind === Kind.UNION_TYPE_DEFINITION ||\n node.kind === Kind.ENUM_TYPE_DEFINITION ||\n node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION\n );\n}\n/**\n * Returns true when the AST node is a type system extension node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a type system extension node.\n * @example\n * ```ts\n * import { parse, isTypeSystemExtensionNode } from 'graphql/language';\n *\n * const extension = parse('extend type Query { hello: String }');\n * const definition = parse('type Query { hello: String }');\n *\n * isTypeSystemExtensionNode(extension.definitions[0]); // => true\n * isTypeSystemExtensionNode(definition.definitions[0]); // => false\n * ```\n */\n\nexport function isTypeSystemExtensionNode(node) {\n return (\n node.kind === Kind.SCHEMA_EXTENSION ||\n node.kind === Kind.DIRECTIVE_EXTENSION ||\n isTypeExtensionNode(node)\n );\n}\n/**\n * Returns true when the AST node is a type extension node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a type extension node.\n * @example\n * ```ts\n * import { parse, isTypeExtensionNode } from 'graphql/language';\n *\n * const extension = parse('extend type Query { hello: String }');\n * const schemaExtension = parse('extend schema { query: Query }');\n *\n * isTypeExtensionNode(extension.definitions[0]); // => true\n * isTypeExtensionNode(schemaExtension.definitions[0]); // => false\n * ```\n */\n\nexport function isTypeExtensionNode(node) {\n return (\n node.kind === Kind.SCALAR_TYPE_EXTENSION ||\n node.kind === Kind.OBJECT_TYPE_EXTENSION ||\n node.kind === Kind.INTERFACE_TYPE_EXTENSION ||\n node.kind === Kind.UNION_TYPE_EXTENSION ||\n node.kind === Kind.ENUM_TYPE_EXTENSION ||\n node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION\n );\n}\n/**\n * Returns true when the AST node is a schema coordinate node.\n * @param node - The AST node to test.\n * @returns True when the AST node is a schema coordinate node.\n * @example\n * ```ts\n * import {\n * parse,\n * parseSchemaCoordinate,\n * isSchemaCoordinateNode,\n * } from 'graphql/language';\n *\n * const coordinate = parseSchemaCoordinate('Query.hero');\n * const document = parse('{ hero }');\n *\n * isSchemaCoordinateNode(coordinate); // => true\n * isSchemaCoordinateNode(document); // => false\n * ```\n */\n\nexport function isSchemaCoordinateNode(node) {\n return (\n node.kind === Kind.TYPE_COORDINATE ||\n node.kind === Kind.MEMBER_COORDINATE ||\n node.kind === Kind.ARGUMENT_COORDINATE ||\n node.kind === Kind.DIRECTIVE_COORDINATE ||\n node.kind === Kind.DIRECTIVE_ARGUMENT_COORDINATE\n );\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { isExecutableDefinitionNode } from '../../language/predicates.mjs';\n\n/**\n * Executable definitions\n *\n * A GraphQL document is only valid for execution if all definitions are either\n * operation or fragment definitions.\n *\n * See https://spec.graphql.org/draft/#sec-Executable-Definitions\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { ExecutableDefinitionsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * type Extra { field: String }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [ExecutableDefinitionsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name }\n * `);\n * const validErrors = validate(schema, validDocument, [ExecutableDefinitionsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function ExecutableDefinitionsRule(context) {\n return {\n Document(node) {\n for (const definition of node.definitions) {\n if (!isExecutableDefinitionNode(definition)) {\n const defName =\n definition.kind === Kind.SCHEMA_DEFINITION ||\n definition.kind === Kind.SCHEMA_EXTENSION\n ? 'schema'\n : '\"' + definition.name.value + '\"';\n context.reportError(\n new GraphQLError(`The ${defName} definition is not executable.`, {\n nodes: definition,\n }),\n );\n }\n }\n\n return false;\n },\n };\n}\n","/** @category Validation Rules */\nimport { didYouMean } from '../../jsutils/didYouMean.mjs';\nimport { naturalCompare } from '../../jsutils/naturalCompare.mjs';\nimport { suggestionList } from '../../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport {\n isAbstractType,\n isInterfaceType,\n isObjectType,\n} from '../../type/definition.mjs';\n\n/**\n * Fields on correct type\n *\n * A GraphQL document is only valid if all fields selected are defined by the\n * parent type, or are an allowed meta field such as __typename.\n *\n * See https://spec.graphql.org/draft/#sec-Field-Selections\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { FieldsOnCorrectTypeRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { missing }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [FieldsOnCorrectTypeRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name }\n * `);\n * const validErrors = validate(schema, validDocument, [FieldsOnCorrectTypeRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function FieldsOnCorrectTypeRule(context) {\n return {\n Field(node) {\n const type = context.getParentType();\n\n if (type) {\n const fieldDef = context.getFieldDef();\n\n if (!fieldDef) {\n // This field doesn't exist, lets look for suggestions.\n const schema = context.getSchema();\n const fieldName = node.name.value; // First determine if there are any suggested types to condition on.\n\n let suggestion = didYouMean(\n 'to use an inline fragment on',\n getSuggestedTypeNames(schema, type, fieldName),\n ); // If there are no suggested types, then perhaps this was a typo?\n\n if (suggestion === '') {\n suggestion = didYouMean(getSuggestedFieldNames(type, fieldName));\n } // Report an error, including helpful suggestions.\n\n context.reportError(\n new GraphQLError(\n `Cannot query field \"${fieldName}\" on type \"${type.name}\".` +\n suggestion,\n {\n nodes: node,\n },\n ),\n );\n }\n }\n },\n };\n}\n/**\n * Go through all of the implementations of type, as well as the interfaces that\n * they implement. If any of those types include the provided field, suggest them,\n * sorted by how often the type is referenced.\n *\n * @internal\n */\n\nfunction getSuggestedTypeNames(schema, type, fieldName) {\n if (!isAbstractType(type)) {\n // Must be an Object type, which does not have possible fields.\n return [];\n }\n\n const suggestedTypes = new Set();\n const usageCount = Object.create(null);\n\n for (const possibleType of schema.getPossibleTypes(type)) {\n if (!possibleType.getFields()[fieldName]) {\n continue;\n } // This object type defines this field.\n\n suggestedTypes.add(possibleType);\n usageCount[possibleType.name] = 1;\n\n for (const possibleInterface of possibleType.getInterfaces()) {\n var _usageCount$possibleI;\n\n if (!possibleInterface.getFields()[fieldName]) {\n continue;\n } // This interface type defines this field.\n\n suggestedTypes.add(possibleInterface);\n usageCount[possibleInterface.name] =\n ((_usageCount$possibleI = usageCount[possibleInterface.name]) !==\n null && _usageCount$possibleI !== void 0\n ? _usageCount$possibleI\n : 0) + 1;\n }\n }\n\n return [...suggestedTypes]\n .sort((typeA, typeB) => {\n // Suggest both interface and object types based on how common they are.\n const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name];\n\n if (usageCountDiff !== 0) {\n return usageCountDiff;\n } // Suggest super types first followed by subtypes\n\n if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) {\n return -1;\n }\n\n if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) {\n return 1;\n }\n\n return naturalCompare(typeA.name, typeB.name);\n })\n .map((x) => x.name);\n}\n/**\n * For the field name provided, determine if there are any similar field names\n * that may be the result of a typo.\n *\n * @internal\n */\n\nfunction getSuggestedFieldNames(type, fieldName) {\n if (isObjectType(type) || isInterfaceType(type)) {\n const possibleFieldNames = Object.keys(type.getFields());\n return suggestionList(fieldName, possibleFieldNames);\n } // Otherwise, must be a Union type, which does not define fields.\n\n return [];\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { print } from '../../language/printer.mjs';\nimport { isCompositeType } from '../../type/definition.mjs';\nimport { typeFromAST } from '../../utilities/typeFromAST.mjs';\n\n/**\n * Fragments on composite type\n *\n * Fragments use a type condition to determine if they apply, since fragments\n * can only be spread into a composite type (object, interface, or union), the\n * type condition must also be a composite type.\n *\n * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { FragmentsOnCompositeTypesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * fragment Bad on String { length }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [FragmentsOnCompositeTypesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment Good on Query { name }\n * `);\n * const validErrors = validate(schema, validDocument, [FragmentsOnCompositeTypesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function FragmentsOnCompositeTypesRule(context) {\n return {\n InlineFragment(node) {\n const typeCondition = node.typeCondition;\n\n if (typeCondition) {\n const type = typeFromAST(context.getSchema(), typeCondition);\n\n if (type && !isCompositeType(type)) {\n const typeStr = print(typeCondition);\n context.reportError(\n new GraphQLError(\n `Fragment cannot condition on non composite type \"${typeStr}\".`,\n {\n nodes: typeCondition,\n },\n ),\n );\n }\n }\n },\n\n FragmentDefinition(node) {\n const type = typeFromAST(context.getSchema(), node.typeCondition);\n\n if (type && !isCompositeType(type)) {\n const typeStr = print(node.typeCondition);\n context.reportError(\n new GraphQLError(\n `Fragment \"${node.name.value}\" cannot condition on non composite type \"${typeStr}\".`,\n {\n nodes: node.typeCondition,\n },\n ),\n );\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { didYouMean } from '../../jsutils/didYouMean.mjs';\nimport { suggestionList } from '../../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { specifiedDirectives } from '../../type/directives.mjs';\n\n/**\n * Known argument names\n *\n * A GraphQL field is only valid if all supplied arguments are defined by\n * that field.\n *\n * See https://spec.graphql.org/draft/#sec-Argument-Names\n * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { KnownArgumentNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: String): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { field(unknown: \"1\") }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [KnownArgumentNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { field(arg: \"1\") }\n * `);\n * const validErrors = validate(schema, validDocument, [KnownArgumentNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function KnownArgumentNamesRule(context) {\n return {\n // eslint-disable-next-line new-cap\n ...KnownArgumentNamesOnDirectivesRule(context),\n\n Argument(argNode) {\n const argDef = context.getArgument();\n const fieldDef = context.getFieldDef();\n const parentType = context.getParentType();\n\n if (!argDef && fieldDef && parentType) {\n const argName = argNode.name.value;\n const knownArgsNames = fieldDef.args.map((arg) => arg.name);\n const suggestions = suggestionList(argName, knownArgsNames);\n context.reportError(\n new GraphQLError(\n `Unknown argument \"${argName}\" on field \"${parentType.name}.${fieldDef.name}\".` +\n didYouMean(suggestions),\n {\n nodes: argNode,\n },\n ),\n );\n }\n },\n };\n}\n/** @internal */\n\nexport function KnownArgumentNamesOnDirectivesRule(context) {\n const directiveArgs = Object.create(null);\n const schema = context.getSchema();\n const definedDirectives = schema\n ? schema.getDirectives()\n : specifiedDirectives;\n\n for (const directive of definedDirectives) {\n directiveArgs[directive.name] = directive.args.map((arg) => arg.name);\n }\n\n const astDefinitions = context.getDocument().definitions;\n\n for (const def of astDefinitions) {\n if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n var _def$arguments;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const argsNodes =\n (_def$arguments = def.arguments) !== null && _def$arguments !== void 0\n ? _def$arguments\n : [];\n directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value);\n }\n }\n\n return {\n Directive(directiveNode) {\n const directiveName = directiveNode.name.value;\n const knownArgs = directiveArgs[directiveName];\n\n if (directiveNode.arguments && knownArgs) {\n for (const argNode of directiveNode.arguments) {\n const argName = argNode.name.value;\n\n if (!knownArgs.includes(argName)) {\n const suggestions = suggestionList(argName, knownArgs);\n context.reportError(\n new GraphQLError(\n `Unknown argument \"${argName}\" on directive \"@${directiveName}\".` +\n didYouMean(suggestions),\n {\n nodes: argNode,\n },\n ),\n );\n }\n }\n }\n\n return false;\n },\n };\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { invariant } from '../../jsutils/invariant.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { OperationTypeNode } from '../../language/ast.mjs';\nimport { DirectiveLocation } from '../../language/directiveLocation.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { specifiedDirectives } from '../../type/directives.mjs';\n\n/**\n * Known directives\n *\n * A GraphQL document is only valid if all `@directives` are known by the\n * schema and legally positioned.\n *\n * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { KnownDirectivesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { name @unknown }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [KnownDirectivesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name @include(if: true) }\n * `);\n * const validErrors = validate(schema, validDocument, [KnownDirectivesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function KnownDirectivesRule(context) {\n const locationsMap = Object.create(null);\n const schema = context.getSchema();\n const definedDirectives = schema\n ? schema.getDirectives()\n : specifiedDirectives;\n\n for (const directive of definedDirectives) {\n locationsMap[directive.name] = directive.locations;\n }\n\n const astDefinitions = context.getDocument().definitions;\n\n for (const def of astDefinitions) {\n if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n locationsMap[def.name.value] = def.locations.map((name) => name.value);\n }\n }\n\n return {\n Directive(node, _key, _parent, _path, ancestors) {\n const name = node.name.value;\n const locations = locationsMap[name];\n\n if (!locations) {\n context.reportError(\n new GraphQLError(`Unknown directive \"@${name}\".`, {\n nodes: node,\n }),\n );\n return;\n }\n\n const candidateLocation = getDirectiveLocationForASTPath(ancestors);\n\n if (candidateLocation && !locations.includes(candidateLocation)) {\n context.reportError(\n new GraphQLError(\n `Directive \"@${name}\" may not be used on ${candidateLocation}.`,\n {\n nodes: node,\n },\n ),\n );\n }\n },\n };\n}\n\nfunction getDirectiveLocationForASTPath(ancestors) {\n const appliedTo = ancestors[ancestors.length - 1];\n 'kind' in appliedTo || invariant(false);\n\n switch (appliedTo.kind) {\n case Kind.OPERATION_DEFINITION:\n return getDirectiveLocationForOperation(appliedTo.operation);\n\n case Kind.FIELD:\n return DirectiveLocation.FIELD;\n\n case Kind.FRAGMENT_SPREAD:\n return DirectiveLocation.FRAGMENT_SPREAD;\n\n case Kind.INLINE_FRAGMENT:\n return DirectiveLocation.INLINE_FRAGMENT;\n\n case Kind.FRAGMENT_DEFINITION:\n return DirectiveLocation.FRAGMENT_DEFINITION;\n\n case Kind.VARIABLE_DEFINITION:\n return DirectiveLocation.VARIABLE_DEFINITION;\n\n case Kind.SCHEMA_DEFINITION:\n case Kind.SCHEMA_EXTENSION:\n return DirectiveLocation.SCHEMA;\n\n case Kind.SCALAR_TYPE_DEFINITION:\n case Kind.SCALAR_TYPE_EXTENSION:\n return DirectiveLocation.SCALAR;\n\n case Kind.OBJECT_TYPE_DEFINITION:\n case Kind.OBJECT_TYPE_EXTENSION:\n return DirectiveLocation.OBJECT;\n\n case Kind.FIELD_DEFINITION:\n return DirectiveLocation.FIELD_DEFINITION;\n\n case Kind.INTERFACE_TYPE_DEFINITION:\n case Kind.INTERFACE_TYPE_EXTENSION:\n return DirectiveLocation.INTERFACE;\n\n case Kind.UNION_TYPE_DEFINITION:\n case Kind.UNION_TYPE_EXTENSION:\n return DirectiveLocation.UNION;\n\n case Kind.ENUM_TYPE_DEFINITION:\n case Kind.ENUM_TYPE_EXTENSION:\n return DirectiveLocation.ENUM;\n\n case Kind.ENUM_VALUE_DEFINITION:\n return DirectiveLocation.ENUM_VALUE;\n\n case Kind.INPUT_OBJECT_TYPE_DEFINITION:\n case Kind.INPUT_OBJECT_TYPE_EXTENSION:\n return DirectiveLocation.INPUT_OBJECT;\n\n case Kind.INPUT_VALUE_DEFINITION: {\n const parentNode = ancestors[ancestors.length - 3];\n 'kind' in parentNode || invariant(false);\n return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION\n ? DirectiveLocation.INPUT_FIELD_DEFINITION\n : DirectiveLocation.ARGUMENT_DEFINITION;\n }\n\n case Kind.DIRECTIVE_DEFINITION:\n case Kind.DIRECTIVE_EXTENSION:\n return DirectiveLocation.DIRECTIVE_DEFINITION;\n // Not reachable, all possible types have been considered.\n\n /* c8 ignore next */\n\n default:\n false || invariant(false, 'Unexpected kind: ' + inspect(appliedTo.kind));\n }\n}\n\nfunction getDirectiveLocationForOperation(operation) {\n switch (operation) {\n case OperationTypeNode.QUERY:\n return DirectiveLocation.QUERY;\n\n case OperationTypeNode.MUTATION:\n return DirectiveLocation.MUTATION;\n\n case OperationTypeNode.SUBSCRIPTION:\n return DirectiveLocation.SUBSCRIPTION;\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Known fragment names\n *\n * A GraphQL document is only valid if all `...Fragment` fragment spreads refer\n * to fragments defined in the same document.\n *\n * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { KnownFragmentNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { ...Missing }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [KnownFragmentNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment NameFields on Query { name } query { ...NameFields }\n * `);\n * const validErrors = validate(schema, validDocument, [KnownFragmentNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function KnownFragmentNamesRule(context) {\n return {\n FragmentSpread(node) {\n const fragmentName = node.name.value;\n const fragment = context.getFragment(fragmentName);\n\n if (!fragment) {\n context.reportError(\n new GraphQLError(`Unknown fragment \"${fragmentName}\".`, {\n nodes: node.name,\n }),\n );\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { didYouMean } from '../../jsutils/didYouMean.mjs';\nimport { suggestionList } from '../../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport {\n isTypeDefinitionNode,\n isTypeSystemDefinitionNode,\n isTypeSystemExtensionNode,\n} from '../../language/predicates.mjs';\nimport { introspectionTypes } from '../../type/introspection.mjs';\nimport { specifiedScalarTypes } from '../../type/scalars.mjs';\n\n/**\n * Known type names\n *\n * A GraphQL document is only valid if referenced types (specifically\n * variable definitions and fragment conditions) are defined by the type schema.\n *\n * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { KnownTypeNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * fragment Bad on Missing { name }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [KnownTypeNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment Good on Query { name }\n * `);\n * const validErrors = validate(schema, validDocument, [KnownTypeNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function KnownTypeNamesRule(context) {\n const schema = context.getSchema();\n const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null);\n const definedTypes = Object.create(null);\n\n for (const def of context.getDocument().definitions) {\n if (isTypeDefinitionNode(def)) {\n definedTypes[def.name.value] = true;\n }\n }\n\n const typeNames = [\n ...Object.keys(existingTypesMap),\n ...Object.keys(definedTypes),\n ];\n return {\n NamedType(node, _1, parent, _2, ancestors) {\n const typeName = node.name.value;\n\n if (!existingTypesMap[typeName] && !definedTypes[typeName]) {\n var _ancestors$;\n\n const definitionNode =\n (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0\n ? _ancestors$\n : parent;\n const isSDL = definitionNode != null && isSDLNode(definitionNode);\n\n if (isSDL && standardTypeNames.includes(typeName)) {\n return;\n }\n\n const suggestedTypes = suggestionList(\n typeName,\n isSDL ? standardTypeNames.concat(typeNames) : typeNames,\n );\n context.reportError(\n new GraphQLError(\n `Unknown type \"${typeName}\".` + didYouMean(suggestedTypes),\n {\n nodes: node,\n },\n ),\n );\n }\n },\n };\n}\nconst standardTypeNames = [...specifiedScalarTypes, ...introspectionTypes].map(\n (type) => type.name,\n);\n\nfunction isSDLNode(value) {\n return (\n 'kind' in value &&\n (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value))\n );\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\n\n/**\n * Lone anonymous operation\n *\n * A GraphQL document is only valid if when it contains an anonymous operation\n * (the query short-hand) that it contains only that one operation definition.\n *\n * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { LoneAnonymousOperationRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query { name } query Other { name }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [LoneAnonymousOperationRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name }\n * `);\n * const validErrors = validate(schema, validDocument, [LoneAnonymousOperationRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function LoneAnonymousOperationRule(context) {\n let operationCount = 0;\n return {\n Document(node) {\n operationCount = node.definitions.filter(\n (definition) => definition.kind === Kind.OPERATION_DEFINITION,\n ).length;\n },\n\n OperationDefinition(node) {\n if (!node.name && operationCount > 1) {\n context.reportError(\n new GraphQLError(\n 'This anonymous operation must be the only defined operation.',\n {\n nodes: node,\n },\n ),\n );\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Lone Schema definition\n *\n * A GraphQL document is only valid if it contains only one schema definition.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { LoneSchemaDefinitionRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * schema { query: Query } schema { query: Query } type Query { name: String }\n * `;\n *\n * LoneSchemaDefinitionRule.name; // => 'LoneSchemaDefinitionRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * schema { query: Query } type Query { name: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function LoneSchemaDefinitionRule(context) {\n var _ref, _ref2, _oldSchema$astNode;\n\n const oldSchema = context.getSchema();\n const alreadyDefined =\n (_ref =\n (_ref2 =\n (_oldSchema$astNode =\n oldSchema === null || oldSchema === void 0\n ? void 0\n : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0\n ? _oldSchema$astNode\n : oldSchema === null || oldSchema === void 0\n ? void 0\n : oldSchema.getQueryType()) !== null && _ref2 !== void 0\n ? _ref2\n : oldSchema === null || oldSchema === void 0\n ? void 0\n : oldSchema.getMutationType()) !== null && _ref !== void 0\n ? _ref\n : oldSchema === null || oldSchema === void 0\n ? void 0\n : oldSchema.getSubscriptionType();\n let schemaDefinitionsCount = 0;\n return {\n SchemaDefinition(node) {\n if (alreadyDefined) {\n context.reportError(\n new GraphQLError(\n 'Cannot define a new schema within a schema extension.',\n {\n nodes: node,\n },\n ),\n );\n return;\n }\n\n if (schemaDefinitionsCount > 0) {\n context.reportError(\n new GraphQLError('Must provide only one schema definition.', {\n nodes: node,\n }),\n );\n }\n\n ++schemaDefinitionsCount;\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nconst MAX_LISTS_DEPTH = 3;\n/**\n * Implements the max introspection depth validation rule.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { MaxIntrospectionDepthRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { __schema { types { fields { type { fields { type { fields { name } } } } } } } }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [MaxIntrospectionDepthRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { __schema { queryType { name } } }\n * `);\n * const validErrors = validate(schema, validDocument, [MaxIntrospectionDepthRule]);\n *\n * validErrors; // => []\n * ```\n */\n\nexport function MaxIntrospectionDepthRule(context) {\n /**\n * Counts the depth of list fields in \"__Type\" recursively and\n * returns `true` if the limit has been reached.\n *\n * @internal\n */\n function checkDepth(node, visitedFragments = Object.create(null), depth = 0) {\n if (node.kind === Kind.FRAGMENT_SPREAD) {\n const fragmentName = node.name.value;\n\n if (visitedFragments[fragmentName] === true) {\n // Fragment cycles are handled by `NoFragmentCyclesRule`.\n return false;\n }\n\n const fragment = context.getFragment(fragmentName);\n\n if (!fragment) {\n // Missing fragments checks are handled by `KnownFragmentNamesRule`.\n return false;\n } // Rather than following an immutable programming pattern which has\n // significant memory and garbage collection overhead, we've opted to\n // take a mutable approach for efficiency's sake. Importantly visiting a\n // fragment twice is fine, so long as you don't do one visit inside the\n // other.\n\n try {\n visitedFragments[fragmentName] = true;\n return checkDepth(fragment, visitedFragments, depth);\n } finally {\n visitedFragments[fragmentName] = undefined;\n }\n }\n\n if (\n node.kind === Kind.FIELD && // check all introspection lists\n (node.name.value === 'fields' ||\n node.name.value === 'interfaces' ||\n node.name.value === 'possibleTypes' ||\n node.name.value === 'inputFields')\n ) {\n // eslint-disable-next-line no-param-reassign\n depth++;\n\n if (depth >= MAX_LISTS_DEPTH) {\n return true;\n }\n } // handles fields and inline fragments\n\n if ('selectionSet' in node && node.selectionSet) {\n for (const child of node.selectionSet.selections) {\n if (checkDepth(child, visitedFragments, depth)) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n return {\n Field(node) {\n if (node.name.value === '__schema' || node.name.value === '__type') {\n if (checkDepth(node)) {\n context.reportError(\n new GraphQLError('Maximum introspection depth exceeded', {\n nodes: [node],\n }),\n );\n return false;\n }\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * No fragment cycles\n *\n * The graph of fragment spreads must not form any cycles including spreading itself.\n * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data.\n *\n * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { NoFragmentCyclesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * fragment A on Query { ...B } fragment B on Query { ...A } query { ...A }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [NoFragmentCyclesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment A on Query { name } query { ...A }\n * `);\n * const validErrors = validate(schema, validDocument, [NoFragmentCyclesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function NoFragmentCyclesRule(context) {\n // Tracks already visited fragments to maintain O(N) and to ensure that cycles\n // are not redundantly reported.\n const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors\n\n const spreadPath = []; // Position in the spread path\n\n const spreadPathIndexByName = Object.create(null);\n return {\n OperationDefinition: () => false,\n\n FragmentDefinition(node) {\n detectCycleRecursive(node);\n return false;\n },\n }; // This does a straight-forward DFS to find cycles.\n // It does not terminate when a cycle was found but continues to explore\n // the graph to find all possible cycles.\n\n function detectCycleRecursive(fragment) {\n if (visitedFrags[fragment.name.value]) {\n return;\n }\n\n const fragmentName = fragment.name.value;\n visitedFrags[fragmentName] = true;\n const spreadNodes = context.getFragmentSpreads(fragment.selectionSet);\n\n if (spreadNodes.length === 0) {\n return;\n }\n\n spreadPathIndexByName[fragmentName] = spreadPath.length;\n\n for (const spreadNode of spreadNodes) {\n const spreadName = spreadNode.name.value;\n const cycleIndex = spreadPathIndexByName[spreadName];\n spreadPath.push(spreadNode);\n\n if (cycleIndex === undefined) {\n const spreadFragment = context.getFragment(spreadName);\n\n if (spreadFragment) {\n detectCycleRecursive(spreadFragment);\n }\n } else {\n const cyclePath = spreadPath.slice(cycleIndex);\n const viaPath = cyclePath\n .slice(0, -1)\n .map((s) => '\"' + s.name.value + '\"')\n .join(', ');\n context.reportError(\n new GraphQLError(\n `Cannot spread fragment \"${spreadName}\" within itself` +\n (viaPath !== '' ? ` via ${viaPath}.` : '.'),\n {\n nodes: cyclePath,\n },\n ),\n );\n }\n\n spreadPath.pop();\n }\n\n spreadPathIndexByName[fragmentName] = undefined;\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * No undefined variables\n *\n * A GraphQL operation is only valid if all variables encountered, both directly\n * and via fragment spreads, are defined by that operation.\n *\n * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { NoUndefinedVariablesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: ID): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query ($id: ID) { field(arg: $missing) }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [NoUndefinedVariablesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query ($id: ID) { field(arg: $id) }\n * `);\n * const validErrors = validate(schema, validDocument, [NoUndefinedVariablesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function NoUndefinedVariablesRule(context) {\n let variableNameDefined = Object.create(null);\n return {\n OperationDefinition: {\n enter() {\n variableNameDefined = Object.create(null);\n },\n\n leave(operation) {\n const usages = context.getRecursiveVariableUsages(operation);\n\n for (const { node } of usages) {\n const varName = node.name.value;\n\n if (variableNameDefined[varName] !== true) {\n context.reportError(\n new GraphQLError(\n operation.name\n ? `Variable \"$${varName}\" is not defined by operation \"${operation.name.value}\".`\n : `Variable \"$${varName}\" is not defined.`,\n {\n nodes: [node, operation],\n },\n ),\n );\n }\n }\n },\n },\n\n VariableDefinition(node) {\n variableNameDefined[node.variable.name.value] = true;\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * No unused fragments\n *\n * A GraphQL document is only valid if all fragment definitions are spread\n * within operations, or spread within other fragments spread within operations.\n *\n * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { NoUnusedFragmentsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * fragment Unused on Query { name } query { name }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [NoUnusedFragmentsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment Used on Query { name } query { ...Used }\n * `);\n * const validErrors = validate(schema, validDocument, [NoUnusedFragmentsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function NoUnusedFragmentsRule(context) {\n const operationDefs = [];\n const fragmentDefs = [];\n return {\n OperationDefinition(node) {\n operationDefs.push(node);\n return false;\n },\n\n FragmentDefinition(node) {\n fragmentDefs.push(node);\n return false;\n },\n\n Document: {\n leave() {\n const fragmentNameUsed = Object.create(null);\n\n for (const operation of operationDefs) {\n for (const fragment of context.getRecursivelyReferencedFragments(\n operation,\n )) {\n fragmentNameUsed[fragment.name.value] = true;\n }\n }\n\n for (const fragmentDef of fragmentDefs) {\n const fragName = fragmentDef.name.value;\n\n if (fragmentNameUsed[fragName] !== true) {\n context.reportError(\n new GraphQLError(`Fragment \"${fragName}\" is never used.`, {\n nodes: fragmentDef,\n }),\n );\n }\n }\n },\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * No unused variables\n *\n * A GraphQL operation is only valid if all variables defined by an operation\n * are used, either directly or within a spread fragment.\n *\n * See https://spec.graphql.org/draft/#sec-All-Variables-Used\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { NoUnusedVariablesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: ID): String\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query ($id: ID) { name }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [NoUnusedVariablesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query ($id: ID) { field(arg: $id) }\n * `);\n * const validErrors = validate(schema, validDocument, [NoUnusedVariablesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function NoUnusedVariablesRule(context) {\n let variableDefs = [];\n return {\n OperationDefinition: {\n enter() {\n variableDefs = [];\n },\n\n leave(operation) {\n const variableNameUsed = Object.create(null);\n const usages = context.getRecursiveVariableUsages(operation);\n\n for (const { node } of usages) {\n variableNameUsed[node.name.value] = true;\n }\n\n for (const variableDef of variableDefs) {\n const variableName = variableDef.variable.name.value;\n\n if (variableNameUsed[variableName] !== true) {\n context.reportError(\n new GraphQLError(\n operation.name\n ? `Variable \"$${variableName}\" is never used in operation \"${operation.name.value}\".`\n : `Variable \"$${variableName}\" is never used.`,\n {\n nodes: variableDef,\n },\n ),\n );\n }\n }\n },\n },\n\n VariableDefinition(def) {\n variableDefs.push(def);\n },\n };\n}\n","import { naturalCompare } from '../jsutils/naturalCompare.mjs';\nimport { Kind } from '../language/kinds.mjs';\n/**\n * Sort ValueNode.\n *\n * This function returns a sorted copy of the given ValueNode.\n *\n * @internal\n */\n\nexport function sortValueNode(valueNode) {\n switch (valueNode.kind) {\n case Kind.OBJECT:\n return { ...valueNode, fields: sortFields(valueNode.fields) };\n\n case Kind.LIST:\n return { ...valueNode, values: valueNode.values.map(sortValueNode) };\n\n case Kind.INT:\n case Kind.FLOAT:\n case Kind.STRING:\n case Kind.BOOLEAN:\n case Kind.NULL:\n case Kind.ENUM:\n case Kind.VARIABLE:\n return valueNode;\n }\n}\n\nfunction sortFields(fields) {\n return fields\n .map((fieldNode) => ({\n ...fieldNode,\n value: sortValueNode(fieldNode.value),\n }))\n .sort((fieldA, fieldB) =>\n naturalCompare(fieldA.name.value, fieldB.name.value),\n );\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { print } from '../../language/printer.mjs';\nimport {\n getNamedType,\n isInterfaceType,\n isLeafType,\n isListType,\n isNonNullType,\n isObjectType,\n} from '../../type/definition.mjs';\nimport { sortValueNode } from '../../utilities/sortValueNode.mjs';\nimport { typeFromAST } from '../../utilities/typeFromAST.mjs';\n\nfunction reasonMessage(reason) {\n if (Array.isArray(reason)) {\n return reason\n .map(\n ([responseName, subReason]) =>\n `subfields \"${responseName}\" conflict because ` +\n reasonMessage(subReason),\n )\n .join(' and ');\n }\n\n return reason;\n}\n/**\n * Overlapping fields can be merged\n *\n * A selection set is only valid if all fields (including spreading any\n * fragments) either correspond to distinct response names or can be merged\n * without ambiguity.\n *\n * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { OverlappingFieldsCanBeMergedRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * dog: Dog\n * }\n *\n * type Dog {\n * name: String\n * barkVolume: Int\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { dog { value: barkVolume value: name } }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [OverlappingFieldsCanBeMergedRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { dog { barkVolume name } }\n * `);\n * const validErrors = validate(schema, validDocument, [OverlappingFieldsCanBeMergedRule]);\n *\n * validErrors; // => []\n * ```\n */\n\nexport function OverlappingFieldsCanBeMergedRule(context) {\n // A memoization for when fields and a fragment or two fragments are compared\n // \"between\" each other for conflicts. Comparisons made be made many times,\n // so memoizing this can dramatically improve the performance of this validator.\n const comparedFieldsAndFragmentPairs = new OrderedPairSet();\n const comparedFragmentPairs = new PairSet(); // A cache for the \"field map\" and list of fragment names found in any given\n // selection set. Selection sets may be asked for this information multiple\n // times, so this improves the performance of this validator.\n\n const cachedFieldsAndFragmentNames = new Map();\n return {\n SelectionSet(selectionSet) {\n const conflicts = findConflictsWithinSelectionSet(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n context.getParentType(),\n selectionSet,\n );\n\n for (const [[responseName, reason], fields1, fields2] of conflicts) {\n const reasonMsg = reasonMessage(reason);\n context.reportError(\n new GraphQLError(\n `Fields \"${responseName}\" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`,\n {\n nodes: fields1.concat(fields2),\n },\n ),\n );\n }\n },\n };\n}\n\n/**\n * Find all conflicts found \"within\" a selection set, including those found\n * via spreading in fragments. Called when visiting each SelectionSet in the\n * GraphQL Document.\n *\n * Algorithm:\n *\n * Conflicts occur when two fields exist in a query which will produce the same\n * response name, but represent differing values, thus creating a conflict.\n * The algorithm below finds all conflicts via making a series of comparisons\n * between fields. In order to compare as few fields as possible, this makes\n * a series of comparisons \"within\" sets of fields and \"between\" sets of fields.\n *\n * Given any selection set, a collection produces both a set of fields by\n * also including all inline fragments, as well as a list of fragments\n * referenced by fragment spreads.\n *\n * A) Each selection set represented in the document first compares \"within\" its\n * collected set of fields, finding any conflicts between every pair of\n * overlapping fields.\n * Note: This is the *only time* that the fields \"within\" a set are compared\n * to each other. After this only fields \"between\" sets are compared.\n *\n * B) Also, if any fragment is referenced in a selection set, then a\n * comparison is made \"between\" the original set of fields and the\n * referenced fragment.\n *\n * C) Also, if multiple fragments are referenced, then comparisons\n * are made \"between\" each referenced fragment.\n *\n * D) When comparing \"between\" a set of fields and a referenced fragment, first\n * a comparison is made between each field in the original set of fields and\n * each field in the referenced set of fields.\n *\n * E) Also, if any fragment is referenced in the referenced selection set,\n * then a comparison is made \"between\" the original set of fields and the\n * referenced fragment (recursively referring to step D).\n *\n * F) When comparing \"between\" two fragments, first a comparison is made between\n * each field in the first referenced set of fields and each field in the\n * second referenced set of fields.\n *\n * G) Also, any fragments referenced by the first must be compared to the\n * second, and any fragments referenced by the second must be compared to the\n * first (recursively referring to step F).\n *\n * H) When comparing two fields, if both have selection sets, then a comparison\n * is made \"between\" both selection sets, first comparing the set of fields in\n * the first selection set with the set of fields in the second.\n *\n * I) Also, if any fragment is referenced in either selection set, then a\n * comparison is made \"between\" the other set of fields and the\n * referenced fragment.\n *\n * J) Also, if two fragments are referenced in both selection sets, then a\n * comparison is made \"between\" the two fragments.\n *\n * @internal\n */\nfunction findConflictsWithinSelectionSet(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n parentType,\n selectionSet,\n) {\n const conflicts = [];\n const [fieldMap, fragmentNames] = getFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n parentType,\n selectionSet,\n ); // (A) Find find all conflicts \"within\" the fields of this selection set.\n // Note: this is the *only place* `collectConflictsWithin` is called.\n\n collectConflictsWithin(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n fieldMap,\n );\n\n if (fragmentNames.length !== 0) {\n // (B) Then collect conflicts between these fields and those represented by\n // each spread fragment name found.\n for (let i = 0; i < fragmentNames.length; i++) {\n collectConflictsBetweenFieldsAndFragment(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n false,\n fieldMap,\n fragmentNames[i],\n ); // (C) Then compare this fragment with all other fragments found in this\n // selection set to collect conflicts between fragments spread together.\n // This compares each item in the list of fragment names to every other\n // item in that same list (except for itself).\n\n for (let j = i + 1; j < fragmentNames.length; j++) {\n collectConflictsBetweenFragments(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n false,\n fragmentNames[i],\n fragmentNames[j],\n );\n }\n }\n }\n\n return conflicts;\n} // Collect all conflicts found between a set of fields and a fragment reference\n// including via spreading in any nested fragments.\n\nfunction collectConflictsBetweenFieldsAndFragment(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap,\n fragmentName,\n) {\n // Memoize so the fields and fragments are not compared for conflicts more\n // than once.\n if (\n comparedFieldsAndFragmentPairs.has(\n fieldMap,\n fragmentName,\n areMutuallyExclusive,\n )\n ) {\n return;\n }\n\n comparedFieldsAndFragmentPairs.add(\n fieldMap,\n fragmentName,\n areMutuallyExclusive,\n );\n const fragment = context.getFragment(fragmentName);\n\n if (!fragment) {\n return;\n }\n\n const [fieldMap2, referencedFragmentNames] =\n getReferencedFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n fragment,\n ); // Do not compare a fragment's fieldMap to itself.\n\n if (fieldMap === fieldMap2) {\n return;\n } // (D) First collect any conflicts between the provided collection of fields\n // and the collection of fields represented by the given fragment.\n\n collectConflictsBetween(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap,\n fieldMap2,\n ); // (E) Then collect any conflicts between the provided collection of fields\n // and any fragment names found in the given fragment.\n\n for (const referencedFragmentName of referencedFragmentNames) {\n collectConflictsBetweenFieldsAndFragment(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap,\n referencedFragmentName,\n );\n }\n} // Collect all conflicts found between two fragments, including via spreading in\n// any nested fragments.\n\nfunction collectConflictsBetweenFragments(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fragmentName1,\n fragmentName2,\n) {\n // No need to compare a fragment to itself.\n if (fragmentName1 === fragmentName2) {\n return;\n } // Memoize so two fragments are not compared for conflicts more than once.\n\n if (\n comparedFragmentPairs.has(\n fragmentName1,\n fragmentName2,\n areMutuallyExclusive,\n )\n ) {\n return;\n }\n\n comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive);\n const fragment1 = context.getFragment(fragmentName1);\n const fragment2 = context.getFragment(fragmentName2);\n\n if (!fragment1 || !fragment2) {\n return;\n }\n\n const [fieldMap1, referencedFragmentNames1] =\n getReferencedFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n fragment1,\n );\n const [fieldMap2, referencedFragmentNames2] =\n getReferencedFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n fragment2,\n ); // (F) First, collect all conflicts between these two collections of fields\n // (not including any nested fragments).\n\n collectConflictsBetween(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap1,\n fieldMap2,\n ); // (G) Then collect conflicts between the first fragment and any nested\n // fragments spread in the second fragment.\n\n for (const referencedFragmentName2 of referencedFragmentNames2) {\n collectConflictsBetweenFragments(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fragmentName1,\n referencedFragmentName2,\n );\n } // (G) Then collect conflicts between the second fragment and any nested\n // fragments spread in the first fragment.\n\n for (const referencedFragmentName1 of referencedFragmentNames1) {\n collectConflictsBetweenFragments(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n referencedFragmentName1,\n fragmentName2,\n );\n }\n} // Find all conflicts found between two selection sets, including those found\n// via spreading in fragments. Called when determining if conflicts exist\n// between the sub-fields of two overlapping fields.\n\nfunction findConflictsBetweenSubSelectionSets(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n parentType1,\n selectionSet1,\n parentType2,\n selectionSet2,\n) {\n const conflicts = [];\n const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n parentType1,\n selectionSet1,\n );\n const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n parentType2,\n selectionSet2,\n ); // (H) First, collect all conflicts between these two collections of field.\n\n collectConflictsBetween(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap1,\n fieldMap2,\n ); // (I) Then collect conflicts between the first collection of fields and\n // those referenced by each fragment name associated with the second.\n\n for (const fragmentName2 of fragmentNames2) {\n collectConflictsBetweenFieldsAndFragment(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap1,\n fragmentName2,\n );\n } // (I) Then collect conflicts between the second collection of fields and\n // those referenced by each fragment name associated with the first.\n\n for (const fragmentName1 of fragmentNames1) {\n collectConflictsBetweenFieldsAndFragment(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fieldMap2,\n fragmentName1,\n );\n } // (J) Also collect conflicts between any fragment names by the first and\n // fragment names by the second. This compares each item in the first set of\n // names to each item in the second set of names.\n\n for (const fragmentName1 of fragmentNames1) {\n for (const fragmentName2 of fragmentNames2) {\n collectConflictsBetweenFragments(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n fragmentName1,\n fragmentName2,\n );\n }\n }\n\n return conflicts;\n} // Collect all Conflicts \"within\" one collection of fields.\n\nfunction collectConflictsWithin(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n fieldMap,\n) {\n // A field map is a keyed collection, where each key represents a response\n // name and the value at that key is a list of all fields which provide that\n // response name. For every response name, if there are multiple fields, they\n // must be compared to find a potential conflict.\n for (const [responseName, fields] of Object.entries(fieldMap)) {\n // This compares every field in the list to every other field in this list\n // (except to itself). If the list only has one item, nothing needs to\n // be compared.\n if (fields.length > 1) {\n for (let i = 0; i < fields.length; i++) {\n for (let j = i + 1; j < fields.length; j++) {\n const conflict = findConflict(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n false, // within one collection is never mutually exclusive\n responseName,\n fields[i],\n fields[j],\n );\n\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n }\n }\n} // Collect all Conflicts between two collections of fields. This is similar to,\n// but different from the `collectConflictsWithin` function above. This check\n// assumes that `collectConflictsWithin` has already been called on each\n// provided collection of fields. This is true because this validator traverses\n// each individual selection set.\n\nfunction collectConflictsBetween(\n context,\n conflicts,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n parentFieldsAreMutuallyExclusive,\n fieldMap1,\n fieldMap2,\n) {\n // A field map is a keyed collection, where each key represents a response\n // name and the value at that key is a list of all fields which provide that\n // response name. For any response name which appears in both provided field\n // maps, each field from the first field map must be compared to every field\n // in the second field map to find potential conflicts.\n for (const [responseName, fields1] of Object.entries(fieldMap1)) {\n const fields2 = fieldMap2[responseName];\n\n if (fields2) {\n for (const field1 of fields1) {\n for (const field2 of fields2) {\n const conflict = findConflict(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n parentFieldsAreMutuallyExclusive,\n responseName,\n field1,\n field2,\n );\n\n if (conflict) {\n conflicts.push(conflict);\n }\n }\n }\n }\n }\n} // Determines if there is a conflict between two particular fields, including\n// comparing their sub-fields.\n\nfunction findConflict(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n parentFieldsAreMutuallyExclusive,\n responseName,\n field1,\n field2,\n) {\n const [parentType1, node1, def1] = field1;\n const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same\n // time, due to the parent types, then it is safe to permit them to diverge\n // in aliased field or arguments used as they will not present any ambiguity\n // by differing.\n // It is known that two parent types could never overlap if they are\n // different Object types. Interface or Union types might overlap - if not\n // in the current state of the schema, then perhaps in some future version,\n // thus may not safely diverge.\n\n const areMutuallyExclusive =\n parentFieldsAreMutuallyExclusive ||\n (parentType1 !== parentType2 &&\n isObjectType(parentType1) &&\n isObjectType(parentType2));\n\n if (!areMutuallyExclusive) {\n // Two aliases must refer to the same field.\n const name1 = node1.name.value;\n const name2 = node2.name.value;\n\n if (name1 !== name2) {\n return [\n [responseName, `\"${name1}\" and \"${name2}\" are different fields`],\n [node1],\n [node2],\n ];\n } // Two field calls must have the same arguments.\n\n if (!sameArguments(node1, node2)) {\n return [\n [responseName, 'they have differing arguments'],\n [node1],\n [node2],\n ];\n }\n } // The return type for each field.\n\n const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type;\n const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type;\n\n if (type1 && type2 && doTypesConflict(type1, type2)) {\n return [\n [\n responseName,\n `they return conflicting types \"${inspect(type1)}\" and \"${inspect(\n type2,\n )}\"`,\n ],\n [node1],\n [node2],\n ];\n } // Collect and compare sub-fields. Use the same \"visited fragment names\" list\n // for both collections so fields in a fragment reference are never\n // compared to themselves.\n\n const selectionSet1 = node1.selectionSet;\n const selectionSet2 = node2.selectionSet;\n\n if (selectionSet1 && selectionSet2) {\n const conflicts = findConflictsBetweenSubSelectionSets(\n context,\n cachedFieldsAndFragmentNames,\n comparedFieldsAndFragmentPairs,\n comparedFragmentPairs,\n areMutuallyExclusive,\n getNamedType(type1),\n selectionSet1,\n getNamedType(type2),\n selectionSet2,\n );\n return subfieldConflicts(conflicts, responseName, node1, node2);\n }\n}\n\nfunction sameArguments(node1, node2) {\n const args1 = node1.arguments;\n const args2 = node2.arguments;\n\n if (args1 === undefined || args1.length === 0) {\n return args2 === undefined || args2.length === 0;\n }\n\n if (args2 === undefined || args2.length === 0) {\n return false;\n }\n /* c8 ignore next */\n\n if (args1.length !== args2.length) {\n /* c8 ignore next */\n return false;\n /* c8 ignore next */\n }\n\n const values2 = new Map(args2.map(({ name, value }) => [name.value, value]));\n return args1.every((arg1) => {\n const value1 = arg1.value;\n const value2 = values2.get(arg1.name.value);\n\n if (value2 === undefined) {\n return false;\n }\n\n return stringifyValue(value1) === stringifyValue(value2);\n });\n}\n\nfunction stringifyValue(value) {\n return print(sortValueNode(value));\n} // Two types conflict if both types could not apply to a value simultaneously.\n// Composite types are ignored as their individual field types will be compared\n// later recursively. However List and Non-Null types must match.\n\nfunction doTypesConflict(type1, type2) {\n if (isListType(type1)) {\n return isListType(type2)\n ? doTypesConflict(type1.ofType, type2.ofType)\n : true;\n }\n\n if (isListType(type2)) {\n return true;\n }\n\n if (isNonNullType(type1)) {\n return isNonNullType(type2)\n ? doTypesConflict(type1.ofType, type2.ofType)\n : true;\n }\n\n if (isNonNullType(type2)) {\n return true;\n }\n\n if (isLeafType(type1) || isLeafType(type2)) {\n return type1 !== type2;\n }\n\n return false;\n} // Given a selection set, return the collection of fields (a mapping of response\n// name to field nodes and definitions) as well as a list of fragment names\n// referenced via fragment spreads.\n\nfunction getFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n parentType,\n selectionSet,\n) {\n const cached = cachedFieldsAndFragmentNames.get(selectionSet);\n\n if (cached) {\n return cached;\n }\n\n const nodeAndDefs = Object.create(null);\n const fragmentNames = Object.create(null);\n\n _collectFieldsAndFragmentNames(\n context,\n parentType,\n selectionSet,\n nodeAndDefs,\n fragmentNames,\n );\n\n const result = [nodeAndDefs, Object.keys(fragmentNames)];\n cachedFieldsAndFragmentNames.set(selectionSet, result);\n return result;\n} // Given a reference to a fragment, return the represented collection of fields\n// as well as a list of nested fragment names referenced via fragment spreads.\n\nfunction getReferencedFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n fragment,\n) {\n // Short-circuit building a type from the node if possible.\n const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet);\n\n if (cached) {\n return cached;\n }\n\n const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition);\n return getFieldsAndFragmentNames(\n context,\n cachedFieldsAndFragmentNames,\n fragmentType,\n fragment.selectionSet,\n );\n}\n\nfunction _collectFieldsAndFragmentNames(\n context,\n parentType,\n selectionSet,\n nodeAndDefs,\n fragmentNames,\n) {\n for (const selection of selectionSet.selections) {\n switch (selection.kind) {\n case Kind.FIELD: {\n const fieldName = selection.name.value;\n let fieldDef;\n\n if (isObjectType(parentType) || isInterfaceType(parentType)) {\n fieldDef = parentType.getFields()[fieldName];\n }\n\n const responseName = selection.alias\n ? selection.alias.value\n : fieldName;\n\n if (!nodeAndDefs[responseName]) {\n nodeAndDefs[responseName] = [];\n }\n\n nodeAndDefs[responseName].push([parentType, selection, fieldDef]);\n break;\n }\n\n case Kind.FRAGMENT_SPREAD:\n fragmentNames[selection.name.value] = true;\n break;\n\n case Kind.INLINE_FRAGMENT: {\n const typeCondition = selection.typeCondition;\n const inlineFragmentType = typeCondition\n ? typeFromAST(context.getSchema(), typeCondition)\n : parentType;\n\n _collectFieldsAndFragmentNames(\n context,\n inlineFragmentType,\n selection.selectionSet,\n nodeAndDefs,\n fragmentNames,\n );\n\n break;\n }\n }\n }\n} // Given a series of Conflicts which occurred between two sub-fields, generate\n// a single Conflict.\n\nfunction subfieldConflicts(conflicts, responseName, node1, node2) {\n if (conflicts.length > 0) {\n return [\n [responseName, conflicts.map(([reason]) => reason)],\n [node1, ...conflicts.map(([, fields1]) => fields1).flat()],\n [node2, ...conflicts.map(([, , fields2]) => fields2).flat()],\n ];\n }\n}\n/**\n * A way to keep track of pairs of things where the ordering of the pair\n * matters.\n *\n * Provides a third argument for has/set to allow flagging the pair as\n * weakly or strongly present within the collection.\n *\n * @internal\n */\n\nclass OrderedPairSet {\n constructor() {\n this._data = new Map();\n }\n\n has(a, b, weaklyPresent) {\n var _this$_data$get;\n\n const result =\n (_this$_data$get = this._data.get(a)) === null ||\n _this$_data$get === void 0\n ? void 0\n : _this$_data$get.get(b);\n\n if (result === undefined) {\n return false;\n }\n\n return weaklyPresent ? true : weaklyPresent === result;\n }\n\n add(a, b, weaklyPresent) {\n const map = this._data.get(a);\n\n if (map === undefined) {\n this._data.set(a, new Map([[b, weaklyPresent]]));\n } else {\n map.set(b, weaklyPresent);\n }\n }\n}\n/**\n * A way to keep track of pairs of similar things when the ordering of the pair\n * does not matter.\n *\n * @internal\n */\n\nclass PairSet {\n constructor() {\n this._orderedPairSet = new OrderedPairSet();\n }\n\n has(a, b, weaklyPresent) {\n return a < b\n ? this._orderedPairSet.has(a, b, weaklyPresent)\n : this._orderedPairSet.has(b, a, weaklyPresent);\n }\n\n add(a, b, weaklyPresent) {\n if (a < b) {\n this._orderedPairSet.add(a, b, weaklyPresent);\n } else {\n this._orderedPairSet.add(b, a, weaklyPresent);\n }\n }\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { isCompositeType } from '../../type/definition.mjs';\nimport { doTypesOverlap } from '../../utilities/typeComparators.mjs';\nimport { typeFromAST } from '../../utilities/typeFromAST.mjs';\n\n/**\n * Possible fragment spread\n *\n * A fragment spread is only valid if the type condition could ever possibly\n * be true: if there is a non-empty intersection of the possible parent types,\n * and possible types which pass the type condition.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { PossibleFragmentSpreadsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * dog: Dog\n * }\n *\n * type Dog {\n * barkVolume: Int\n * }\n *\n * type Cat {\n * meowVolume: Int\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { dog { ... on Cat { meowVolume } } }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [PossibleFragmentSpreadsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { dog { ... on Dog { barkVolume } } }\n * `);\n * const validErrors = validate(schema, validDocument, [PossibleFragmentSpreadsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function PossibleFragmentSpreadsRule(context) {\n return {\n InlineFragment(node) {\n const fragType = context.getType();\n const parentType = context.getParentType();\n\n if (\n isCompositeType(fragType) &&\n isCompositeType(parentType) &&\n !doTypesOverlap(context.getSchema(), fragType, parentType)\n ) {\n const parentTypeStr = inspect(parentType);\n const fragTypeStr = inspect(fragType);\n context.reportError(\n new GraphQLError(\n `Fragment cannot be spread here as objects of type \"${parentTypeStr}\" can never be of type \"${fragTypeStr}\".`,\n {\n nodes: node,\n },\n ),\n );\n }\n },\n\n FragmentSpread(node) {\n const fragName = node.name.value;\n const fragType = getFragmentType(context, fragName);\n const parentType = context.getParentType();\n\n if (\n fragType &&\n parentType &&\n !doTypesOverlap(context.getSchema(), fragType, parentType)\n ) {\n const parentTypeStr = inspect(parentType);\n const fragTypeStr = inspect(fragType);\n context.reportError(\n new GraphQLError(\n `Fragment \"${fragName}\" cannot be spread here as objects of type \"${parentTypeStr}\" can never be of type \"${fragTypeStr}\".`,\n {\n nodes: node,\n },\n ),\n );\n }\n },\n };\n}\n\nfunction getFragmentType(context, name) {\n const frag = context.getFragment(name);\n\n if (frag) {\n const type = typeFromAST(context.getSchema(), frag.typeCondition);\n\n if (isCompositeType(type)) {\n return type;\n }\n }\n}\n","/** @category Validation Rules */\nimport { didYouMean } from '../../jsutils/didYouMean.mjs';\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { invariant } from '../../jsutils/invariant.mjs';\nimport { suggestionList } from '../../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { isTypeDefinitionNode } from '../../language/predicates.mjs';\nimport {\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from '../../type/definition.mjs';\n\n/**\n * Possible type extension\n *\n * A type extension is only valid if the type is defined and has the same kind.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { PossibleTypeExtensionsRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * extend type Missing { name: String } type Query { name: String }\n * `;\n *\n * PossibleTypeExtensionsRule.name; // => 'PossibleTypeExtensionsRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * type Query { name: String } extend type Query { other: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function PossibleTypeExtensionsRule(context) {\n const schema = context.getSchema();\n const definedTypes = Object.create(null);\n\n for (const def of context.getDocument().definitions) {\n if (isTypeDefinitionNode(def)) {\n definedTypes[def.name.value] = def;\n }\n }\n\n return {\n ScalarTypeExtension: checkExtension,\n ObjectTypeExtension: checkExtension,\n InterfaceTypeExtension: checkExtension,\n UnionTypeExtension: checkExtension,\n EnumTypeExtension: checkExtension,\n InputObjectTypeExtension: checkExtension,\n };\n\n function checkExtension(node) {\n const typeName = node.name.value;\n const defNode = definedTypes[typeName];\n const existingType =\n schema === null || schema === void 0 ? void 0 : schema.getType(typeName);\n let expectedKind;\n\n if (defNode) {\n expectedKind = defKindToExtKind[defNode.kind];\n } else if (existingType) {\n expectedKind = typeToExtKind(existingType);\n }\n\n if (expectedKind) {\n if (expectedKind !== node.kind) {\n const kindStr = extensionKindToTypeName(node.kind);\n context.reportError(\n new GraphQLError(`Cannot extend non-${kindStr} type \"${typeName}\".`, {\n nodes: defNode ? [defNode, node] : node,\n }),\n );\n }\n } else {\n const allTypeNames = Object.keys({\n ...definedTypes,\n ...(schema === null || schema === void 0\n ? void 0\n : schema.getTypeMap()),\n });\n const suggestedTypes = suggestionList(typeName, allTypeNames);\n context.reportError(\n new GraphQLError(\n `Cannot extend type \"${typeName}\" because it is not defined.` +\n didYouMean(suggestedTypes),\n {\n nodes: node.name,\n },\n ),\n );\n }\n }\n}\nconst defKindToExtKind = {\n [Kind.SCALAR_TYPE_DEFINITION]: Kind.SCALAR_TYPE_EXTENSION,\n [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,\n [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,\n [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,\n [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,\n [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n};\n\nfunction typeToExtKind(type) {\n if (isScalarType(type)) {\n return Kind.SCALAR_TYPE_EXTENSION;\n }\n\n if (isObjectType(type)) {\n return Kind.OBJECT_TYPE_EXTENSION;\n }\n\n if (isInterfaceType(type)) {\n return Kind.INTERFACE_TYPE_EXTENSION;\n }\n\n if (isUnionType(type)) {\n return Kind.UNION_TYPE_EXTENSION;\n }\n\n if (isEnumType(type)) {\n return Kind.ENUM_TYPE_EXTENSION;\n }\n\n if (isInputObjectType(type)) {\n return Kind.INPUT_OBJECT_TYPE_EXTENSION;\n }\n /* c8 ignore next 3 */\n // Not reachable. All possible types have been considered\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n}\n\nfunction extensionKindToTypeName(kind) {\n switch (kind) {\n case Kind.SCALAR_TYPE_EXTENSION:\n return 'scalar';\n\n case Kind.OBJECT_TYPE_EXTENSION:\n return 'object';\n\n case Kind.INTERFACE_TYPE_EXTENSION:\n return 'interface';\n\n case Kind.UNION_TYPE_EXTENSION:\n return 'union';\n\n case Kind.ENUM_TYPE_EXTENSION:\n return 'enum';\n\n case Kind.INPUT_OBJECT_TYPE_EXTENSION:\n return 'input object';\n // Not reachable. All possible types have been considered\n\n /* c8 ignore next */\n\n default:\n false || invariant(false, 'Unexpected kind: ' + inspect(kind));\n }\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { keyMap } from '../../jsutils/keyMap.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { print } from '../../language/printer.mjs';\nimport { isRequiredArgument, isType } from '../../type/definition.mjs';\nimport { specifiedDirectives } from '../../type/directives.mjs';\n\n/**\n * Provided required arguments\n *\n * A field or directive is only valid if all required (non-null without a\n * default value) field arguments have been provided.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { ProvidedRequiredArgumentsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(required: String!): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { field }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [ProvidedRequiredArgumentsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { field(required: \"x\") }\n * `);\n * const validErrors = validate(schema, validDocument, [ProvidedRequiredArgumentsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function ProvidedRequiredArgumentsRule(context) {\n return {\n // eslint-disable-next-line new-cap\n ...ProvidedRequiredArgumentsOnDirectivesRule(context),\n Field: {\n // Validate on leave to allow for deeper errors to appear first.\n leave(fieldNode) {\n var _fieldNode$arguments;\n\n const fieldDef = context.getFieldDef();\n\n if (!fieldDef) {\n return false;\n }\n\n const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203\n /* c8 ignore next */\n (_fieldNode$arguments = fieldNode.arguments) === null ||\n _fieldNode$arguments === void 0\n ? void 0\n : _fieldNode$arguments.map((arg) => arg.name.value),\n );\n\n for (const argDef of fieldDef.args) {\n if (!providedArgs.has(argDef.name) && isRequiredArgument(argDef)) {\n const argTypeStr = inspect(argDef.type);\n context.reportError(\n new GraphQLError(\n `Field \"${fieldDef.name}\" argument \"${argDef.name}\" of type \"${argTypeStr}\" is required, but it was not provided.`,\n {\n nodes: fieldNode,\n },\n ),\n );\n }\n }\n },\n },\n };\n}\n/** @internal */\n\nexport function ProvidedRequiredArgumentsOnDirectivesRule(context) {\n var _schema$getDirectives;\n\n const requiredArgsMap = Object.create(null);\n const schema = context.getSchema();\n const definedDirectives =\n (_schema$getDirectives =\n schema === null || schema === void 0\n ? void 0\n : schema.getDirectives()) !== null && _schema$getDirectives !== void 0\n ? _schema$getDirectives\n : specifiedDirectives;\n\n for (const directive of definedDirectives) {\n requiredArgsMap[directive.name] = keyMap(\n directive.args.filter(isRequiredArgument),\n (arg) => arg.name,\n );\n }\n\n const astDefinitions = context.getDocument().definitions;\n\n for (const def of astDefinitions) {\n if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n var _def$arguments;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const argNodes =\n (_def$arguments = def.arguments) !== null && _def$arguments !== void 0\n ? _def$arguments\n : [];\n requiredArgsMap[def.name.value] = keyMap(\n argNodes.filter(isRequiredArgumentNode),\n (arg) => arg.name.value,\n );\n }\n }\n\n return {\n Directive: {\n // Validate on leave to allow for deeper errors to appear first.\n leave(directiveNode) {\n const directiveName = directiveNode.name.value;\n const requiredArgs = requiredArgsMap[directiveName];\n\n if (requiredArgs) {\n var _directiveNode$argume;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const argNodes =\n (_directiveNode$argume = directiveNode.arguments) !== null &&\n _directiveNode$argume !== void 0\n ? _directiveNode$argume\n : [];\n const argNodeMap = new Set(argNodes.map((arg) => arg.name.value));\n\n for (const [argName, argDef] of Object.entries(requiredArgs)) {\n if (!argNodeMap.has(argName)) {\n const argType = isType(argDef.type)\n ? inspect(argDef.type)\n : print(argDef.type);\n context.reportError(\n new GraphQLError(\n `Directive \"@${directiveName}\" argument \"${argName}\" of type \"${argType}\" is required, but it was not provided.`,\n {\n nodes: directiveNode,\n },\n ),\n );\n }\n }\n }\n },\n },\n };\n}\n\nfunction isRequiredArgumentNode(arg) {\n return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null;\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { getNamedType, isLeafType } from '../../type/definition.mjs';\n\n/**\n * Scalar leafs\n *\n * A GraphQL document is valid only if all leaf fields (fields without\n * sub selections) are of scalar or enum types.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { ScalarLeafsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { name { length } }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [ScalarLeafsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name }\n * `);\n * const validErrors = validate(schema, validDocument, [ScalarLeafsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function ScalarLeafsRule(context) {\n return {\n Field(node) {\n const type = context.getType();\n const selectionSet = node.selectionSet;\n\n if (type) {\n if (isLeafType(getNamedType(type))) {\n if (selectionSet) {\n const fieldName = node.name.value;\n const typeStr = inspect(type);\n context.reportError(\n new GraphQLError(\n `Field \"${fieldName}\" must not have a selection since type \"${typeStr}\" has no subfields.`,\n {\n nodes: selectionSet,\n },\n ),\n );\n }\n } else if (!selectionSet) {\n const fieldName = node.name.value;\n const typeStr = inspect(type);\n context.reportError(\n new GraphQLError(\n `Field \"${fieldName}\" of type \"${typeStr}\" must have a selection of subfields. Did you mean \"${fieldName} { ... }\"?`,\n {\n nodes: node,\n },\n ),\n );\n } else if (selectionSet.selections.length === 0) {\n const fieldName = node.name.value;\n const typeStr = inspect(type);\n context.reportError(\n new GraphQLError(\n `Field \"${fieldName}\" of type \"${typeStr}\" must have at least one field selected.`,\n {\n nodes: node,\n },\n ),\n );\n }\n }\n },\n };\n}\n","/**\n * Build a string describing the path.\n *\n * @internal\n */\nexport function printPathArray(path) {\n return path\n .map((key) =>\n typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key,\n )\n .join('');\n}\n","/** @category Paths */\n\n/** Represents a linked response path from a field back to the root response. */\n\n/**\n * Given a Path and a key, return a new Path containing the new key.\n *\n * @internal\n */\nexport function addPath(prev, key, typename) {\n return {\n prev,\n key,\n typename,\n };\n}\n/**\n * Given a Path, return an Array of the path keys.\n * @param path - The linked response path to flatten.\n * @returns An array of response path keys from root to leaf.\n * @example\n * ```ts\n * import { pathToArray } from 'graphql/jsutils/Path';\n *\n * const path = {\n * prev: {\n * prev: {\n * prev: undefined,\n * key: 'viewer',\n * typename: 'Query',\n * },\n * key: 'friends',\n * typename: 'User',\n * },\n * key: 0,\n * typename: undefined,\n * };\n *\n * pathToArray(path); // => ['viewer', 'friends', 0]\n * pathToArray(undefined); // => []\n * ```\n */\n\nexport function pathToArray(path) {\n const flattened = [];\n let curr = path;\n\n while (curr) {\n flattened.push(curr.key);\n curr = curr.prev;\n }\n\n return flattened.reverse();\n}\n","/** @category Values */\nimport { didYouMean } from '../jsutils/didYouMean.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { isIterableObject } from '../jsutils/isIterableObject.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { addPath, pathToArray } from '../jsutils/Path.mjs';\nimport { printPathArray } from '../jsutils/printPathArray.mjs';\nimport { suggestionList } from '../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport {\n isInputObjectType,\n isLeafType,\n isListType,\n isNonNullType,\n} from '../type/definition.mjs';\n\n/**\n * Coerces a JavaScript value given a GraphQL Input Type.\n * @param inputValue - JavaScript value to coerce.\n * @param type - GraphQL input type to coerce the value against.\n * @param onError - Callback invoked for each coercion error.\n * @returns Coerced value, or undefined if coercion failed and errors were reported.\n * @example\n * ```ts\n * // Coerce runtime input values and throw on invalid input by default.\n * import {\n * GraphQLInputObjectType,\n * GraphQLInt,\n * GraphQLList,\n * GraphQLNonNull,\n * GraphQLString,\n * } from 'graphql/type';\n * import { coerceInputValue } from 'graphql/utilities';\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * fields: {\n * stars: { type: new GraphQLNonNull(GraphQLInt) },\n * tags: { type: new GraphQLList(GraphQLString) },\n * },\n * });\n *\n * coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] }\n * coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error\n * ```\n * @example\n * ```ts\n * // This variant collects coercion errors with a custom onError callback.\n * import { GraphQLInt, GraphQLNonNull } from 'graphql/type';\n * import { coerceInputValue } from 'graphql/utilities';\n *\n * const errors = [];\n * const value = coerceInputValue(\n * null,\n * new GraphQLNonNull(GraphQLInt),\n * (path, invalidValue, error) => {\n * errors.push({ path, invalidValue, message: error.message });\n * },\n * );\n *\n * value; // => undefined\n * errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type \"Int!\" not to be null.' } ]\n * ```\n */\nexport function coerceInputValue(inputValue, type, onError = defaultOnError) {\n return coerceInputValueImpl(inputValue, type, onError, undefined);\n}\n\nfunction defaultOnError(path, invalidValue, error) {\n let errorPrefix = 'Invalid value ' + inspect(invalidValue);\n\n if (path.length > 0) {\n errorPrefix += ` at \"value${printPathArray(path)}\"`;\n }\n\n error.message = errorPrefix + ': ' + error.message;\n throw error;\n}\n\nfunction coerceInputValueImpl(inputValue, type, onError, path) {\n if (isNonNullType(type)) {\n if (inputValue != null) {\n return coerceInputValueImpl(inputValue, type.ofType, onError, path);\n }\n\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(\n `Expected non-nullable type \"${inspect(type)}\" not to be null.`,\n ),\n );\n return;\n }\n\n if (inputValue == null) {\n // Explicitly return the value null.\n return null;\n }\n\n if (isListType(type)) {\n const itemType = type.ofType;\n\n if (isIterableObject(inputValue)) {\n return Array.from(inputValue, (itemValue, index) => {\n const itemPath = addPath(path, index, undefined);\n return coerceInputValueImpl(itemValue, itemType, onError, itemPath);\n });\n } // Lists accept a non-list value as a list of one.\n\n return [coerceInputValueImpl(inputValue, itemType, onError, path)];\n }\n\n if (isInputObjectType(type)) {\n if (!isObjectLike(inputValue) || Array.isArray(inputValue)) {\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(`Expected type \"${type.name}\" to be an object.`),\n );\n return;\n }\n\n const coercedValue = Object.create(null);\n const fieldDefs = type.getFields();\n\n for (const field of Object.values(fieldDefs)) {\n const fieldValue = inputValue[field.name];\n\n if (fieldValue === undefined) {\n if (field.defaultValue !== undefined) {\n coercedValue[field.name] = field.defaultValue;\n } else if (isNonNullType(field.type)) {\n const typeStr = inspect(field.type);\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(\n `Field \"${field.name}\" of required type \"${typeStr}\" was not provided.`,\n ),\n );\n }\n\n continue;\n }\n\n coercedValue[field.name] = coerceInputValueImpl(\n fieldValue,\n field.type,\n onError,\n addPath(path, field.name, type.name),\n );\n } // Ensure every provided field is defined.\n\n for (const fieldName of Object.keys(inputValue)) {\n if (!fieldDefs[fieldName]) {\n const suggestions = suggestionList(\n fieldName,\n Object.keys(type.getFields()),\n );\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(\n `Field \"${fieldName}\" is not defined by type \"${type.name}\".` +\n didYouMean(suggestions),\n ),\n );\n }\n }\n\n if (type.isOneOf) {\n const keys = Object.keys(coercedValue);\n\n if (keys.length !== 1) {\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(\n `Exactly one key must be specified for OneOf type \"${type.name}\".`,\n ),\n );\n }\n\n const key = keys[0];\n const value = coercedValue[key];\n\n if (value === null) {\n onError(\n pathToArray(path).concat(key),\n value,\n new GraphQLError(`Field \"${key}\" must be non-null.`),\n );\n }\n }\n\n return { ...coercedValue };\n }\n\n if (isLeafType(type)) {\n let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(),\n // which can throw to indicate failure. If it throws, maintain a reference\n // to the original error.\n\n try {\n parseResult = type.parseValue(inputValue);\n } catch (error) {\n if (error instanceof GraphQLError) {\n onError(pathToArray(path), inputValue, error);\n } else {\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(`Expected type \"${type.name}\". ` + error.message, {\n originalError: error,\n }),\n );\n }\n\n return;\n }\n\n if (parseResult === undefined) {\n onError(\n pathToArray(path),\n inputValue,\n new GraphQLError(`Expected type \"${type.name}\".`),\n );\n }\n\n return parseResult;\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible types have been considered.\n\n false || invariant(false, 'Unexpected input type: ' + inspect(type));\n}\n","/** @category Values */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isInputObjectType,\n isLeafType,\n isListType,\n isNonNullType,\n} from '../type/definition.mjs';\n/**\n * Produces a JavaScript value given a GraphQL Value AST.\n *\n * A GraphQL type must be provided, which will be used to interpret different\n * GraphQL Value literals.\n *\n * Returns `undefined` when the value could not be validly coerced according to\n * the provided type.\n *\n * | GraphQL Value | JSON Value |\n * | -------------------- | ------------- |\n * | Input Object | Object |\n * | List | Array |\n * | Boolean | Boolean |\n * | String | String |\n * | Int / Float | Number |\n * | Enum Value | Unknown |\n * | NullValue | null |\n * @param valueNode - GraphQL value AST node to convert.\n * @param type - The GraphQL type to inspect.\n * @param variables - Optional runtime variable values keyed by variable name.\n * @returns The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type.\n * @example\n * ```ts\n * // Coerce literal values without variables.\n * import { parseValue } from 'graphql/language';\n * import {\n * GraphQLInputObjectType,\n * GraphQLInt,\n * GraphQLList,\n * GraphQLNonNull,\n * GraphQLString,\n * } from 'graphql/type';\n * import { valueFromAST } from 'graphql/utilities';\n *\n * const ReviewInput = new GraphQLInputObjectType({\n * name: 'ReviewInput',\n * fields: {\n * stars: { type: new GraphQLNonNull(GraphQLInt) },\n * tags: { type: new GraphQLList(GraphQLString) },\n * },\n * });\n *\n * valueFromAST(parseValue('{ stars: 5, tags: [\"featured\"] }'), ReviewInput); // => { stars: 5, tags: ['featured'] }\n * valueFromAST(parseValue('{ stars: \"bad\" }'), ReviewInput); // => undefined\n * ```\n * @example\n * ```ts\n * // This variant resolves variable references from runtime values.\n * import { parseValue } from 'graphql/language';\n * import { GraphQLInt } from 'graphql/type';\n * import { valueFromAST } from 'graphql/utilities';\n *\n * valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5\n * valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined\n * ```\n */\n\nexport function valueFromAST(valueNode, type, variables) {\n if (!valueNode) {\n // When there is no node, then there is also no value.\n // Importantly, this is different from returning the value null.\n return;\n }\n\n if (valueNode.kind === Kind.VARIABLE) {\n const variableName = valueNode.name.value;\n\n if (\n variables == null ||\n variables[variableName] === undefined ||\n !hasOwnProperty(variables, variableName)\n ) {\n // No valid return value.\n return;\n }\n\n const variableValue = variables[variableName];\n\n if (variableValue === null && isNonNullType(type)) {\n return; // Invalid: intentionally return no value.\n } // Note: This does no further checking that this variable is correct.\n // This assumes that this query has been validated and the variable\n // usage here is of the correct type.\n\n return variableValue;\n }\n\n if (isNonNullType(type)) {\n if (valueNode.kind === Kind.NULL) {\n return; // Invalid: intentionally return no value.\n }\n\n return valueFromAST(valueNode, type.ofType, variables);\n }\n\n if (valueNode.kind === Kind.NULL) {\n // This is explicitly returning the value null.\n return null;\n }\n\n if (isListType(type)) {\n const itemType = type.ofType;\n\n if (valueNode.kind === Kind.LIST) {\n const coercedValues = [];\n\n for (const itemNode of valueNode.values) {\n if (isMissingVariable(itemNode, variables)) {\n // If an array contains a missing variable, it is either coerced to\n // null or if the item type is non-null, it considered invalid.\n if (isNonNullType(itemType)) {\n return; // Invalid: intentionally return no value.\n }\n\n coercedValues.push(null);\n } else {\n const itemValue = valueFromAST(itemNode, itemType, variables);\n\n if (itemValue === undefined) {\n return; // Invalid: intentionally return no value.\n }\n\n coercedValues.push(itemValue);\n }\n }\n\n return coercedValues;\n }\n\n const coercedValue = valueFromAST(valueNode, itemType, variables);\n\n if (coercedValue === undefined) {\n return; // Invalid: intentionally return no value.\n }\n\n return [coercedValue];\n }\n\n if (isInputObjectType(type)) {\n if (valueNode.kind !== Kind.OBJECT) {\n return; // Invalid: intentionally return no value.\n }\n\n const coercedObj = Object.create(null);\n const fieldNodes = keyMap(valueNode.fields, (field) => field.name.value);\n\n for (const field of Object.values(type.getFields())) {\n const fieldNode = fieldNodes[field.name];\n\n if (!fieldNode || isMissingVariable(fieldNode.value, variables)) {\n if (field.defaultValue !== undefined) {\n coercedObj[field.name] = field.defaultValue;\n } else if (isNonNullType(field.type)) {\n return; // Invalid: intentionally return no value.\n }\n\n continue;\n }\n\n const fieldValue = valueFromAST(fieldNode.value, field.type, variables);\n\n if (fieldValue === undefined) {\n return; // Invalid: intentionally return no value.\n }\n\n coercedObj[field.name] = fieldValue;\n }\n\n if (type.isOneOf) {\n const keys = Object.keys(coercedObj);\n\n if (keys.length !== 1) {\n return; // Invalid: not exactly one key, intentionally return no value.\n }\n\n if (coercedObj[keys[0]] === null) {\n return; // Invalid: value not non-null, intentionally return no value.\n }\n }\n\n return coercedObj;\n }\n\n if (isLeafType(type)) {\n // Scalars and Enums fulfill parsing a literal value via parseLiteral().\n // Invalid values represent a failure to parse correctly, in which case\n // no value is returned.\n let result;\n\n try {\n result = type.parseLiteral(valueNode, variables);\n } catch (_error) {\n return; // Invalid: intentionally return no value.\n }\n\n if (result === undefined) {\n return; // Invalid: intentionally return no value.\n }\n\n return result;\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible input types have been considered.\n\n false || invariant(false, 'Unexpected input type: ' + inspect(type));\n} // Returns true if the provided valueNode is a variable which is not defined\n// in the set of variables.\n\nfunction isMissingVariable(valueNode, variables) {\n return (\n valueNode.kind === Kind.VARIABLE &&\n (variables == null ||\n variables[valueNode.name.value] === undefined ||\n !hasOwnProperty(variables, valueNode.name.value))\n );\n}\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n","/** @category Values */\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { printPathArray } from '../jsutils/printPathArray.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { print } from '../language/printer.mjs';\nimport { isInputType, isNonNullType } from '../type/definition.mjs';\nimport { coerceInputValue } from '../utilities/coerceInputValue.mjs';\nimport { typeFromAST } from '../utilities/typeFromAST.mjs';\nimport { valueFromAST } from '../utilities/valueFromAST.mjs';\n\n/**\n * Prepares an object map of variableValues of the correct type based on the\n * provided variable definitions and arbitrary input. If the input cannot be\n * parsed to match the variable definitions, GraphQLError values are returned.\n *\n * Note: Returned value is a plain Object with a prototype, since it is\n * exposed to user code. Care should be taken to not pull values from the\n * Object prototype.\n * @param schema - GraphQL schema to use.\n * @param varDefNodes - The variable definition AST nodes to coerce.\n * @param inputs - The runtime variable values keyed by variable name.\n * @param options - Optional variable coercion options, including error limits.\n * @returns Coerced variable values, or request errors.\n * @example\n * ```ts\n * // Coerce provided variables and apply operation defaults.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { getVariableValues } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(stars: Int!, limit: Int = 10): [String]\n * }\n * `);\n * const document = parse(`\n * query ($stars: Int!, $limit: Int = 10) {\n * reviews(stars: $stars, limit: $limit)\n * }\n * `);\n * const operation = document.definitions[0];\n *\n * const result = getVariableValues(\n * schema,\n * operation.variableDefinitions,\n * { stars: '5' },\n * );\n *\n * result; // => { coerced: { stars: 5, limit: 10 } }\n * ```\n * @example\n * ```ts\n * // This variant uses maxErrors to cap reported coercion errors.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { getVariableValues } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput!): String\n * }\n * `);\n * const document = parse(`\n * query ($first: ReviewInput!, $second: ReviewInput!) {\n * first: review(input: $first)\n * second: review(input: $second)\n * }\n * `);\n * const operation = document.definitions[0];\n *\n * const result = getVariableValues(\n * schema,\n * operation.variableDefinitions,\n * { first: { stars: 'bad' }, second: { stars: 'also bad' } },\n * { maxErrors: 1 },\n * );\n *\n * result.errors.length; // => 2\n * result.errors[1].message; // matches /error limit reached/\n * ```\n */\nexport function getVariableValues(schema, varDefNodes, inputs, options) {\n const errors = [];\n const maxErrors =\n options === null || options === void 0 ? void 0 : options.maxErrors;\n\n try {\n const coerced = coerceVariableValues(\n schema,\n varDefNodes,\n inputs,\n (error) => {\n if (maxErrors != null && errors.length >= maxErrors) {\n throw new GraphQLError(\n 'Too many errors processing variables, error limit reached. Execution aborted.',\n );\n }\n\n errors.push(error);\n },\n );\n\n if (errors.length === 0) {\n return {\n coerced,\n };\n }\n } catch (error) {\n errors.push(error);\n }\n\n return {\n errors,\n };\n}\n\nfunction coerceVariableValues(schema, varDefNodes, inputs, onError) {\n const coercedValues = Object.create(null);\n\n for (const varDefNode of varDefNodes) {\n const varName = varDefNode.variable.name.value;\n const varType = typeFromAST(schema, varDefNode.type);\n\n if (!isInputType(varType)) {\n // Must use input types for variables. This should be caught during\n // validation, however is checked again here for safety.\n const varTypeStr = print(varDefNode.type);\n onError(\n new GraphQLError(\n `Variable \"$${varName}\" expected value of type \"${varTypeStr}\" which cannot be used as an input type.`,\n {\n nodes: varDefNode.type,\n },\n ),\n );\n continue;\n }\n\n if (!hasOwnProperty(inputs, varName)) {\n if (varDefNode.defaultValue) {\n coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType);\n } else if (isNonNullType(varType)) {\n const varTypeStr = inspect(varType);\n onError(\n new GraphQLError(\n `Variable \"$${varName}\" of required type \"${varTypeStr}\" was not provided.`,\n {\n nodes: varDefNode,\n },\n ),\n );\n }\n\n continue;\n }\n\n const value = inputs[varName];\n\n if (value === null && isNonNullType(varType)) {\n const varTypeStr = inspect(varType);\n onError(\n new GraphQLError(\n `Variable \"$${varName}\" of non-null type \"${varTypeStr}\" must not be null.`,\n {\n nodes: varDefNode,\n },\n ),\n );\n continue;\n }\n\n coercedValues[varName] = coerceInputValue(\n value,\n varType,\n (path, invalidValue, error) => {\n let prefix =\n `Variable \"$${varName}\" got invalid value ` + inspect(invalidValue);\n\n if (path.length > 0) {\n prefix += ` at \"${varName}${printPathArray(path)}\"`;\n }\n\n onError(\n new GraphQLError(prefix + '; ' + error.message, {\n nodes: varDefNode,\n originalError: error,\n }),\n );\n },\n );\n }\n\n return { ...coercedValues };\n}\n/**\n * Prepares an object map of argument values given a list of argument\n * definitions and list of argument AST nodes.\n *\n * Note: Returned value is a plain Object with a prototype, since it is\n * exposed to user code. Care should be taken to not pull values from the\n * Object prototype.\n * @param def - The field or directive definition whose arguments should be coerced.\n * @param node - The AST node to inspect.\n * @param variableValues - The runtime variable values keyed by variable name.\n * @returns Coerced argument values keyed by argument name.\n * @example\n * ```ts\n * // Read literal argument values and defaults.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { getArgumentValues } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(stars: Int!, limit: Int = 10): [String]\n * }\n * `);\n * const fieldDef = schema.getQueryType().getFields().reviews;\n * const document = parse('{ reviews(stars: 5) }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n *\n * getArgumentValues(fieldDef, fieldNode); // => { stars: 5, limit: 10 }\n * ```\n * @example\n * ```ts\n * // This variant resolves argument values from operation variables.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { getArgumentValues } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(stars: Int!): [String]\n * }\n * `);\n * const fieldDef = schema.getQueryType().getFields().reviews;\n * const document = parse('query ($stars: Int!) { reviews(stars: $stars) }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n *\n * getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 }\n * getArgumentValues(fieldDef, fieldNode, {}); // throws an error\n * ```\n */\n\nexport function getArgumentValues(def, node, variableValues) {\n var _node$arguments;\n\n const coercedValues = Object.create(null); // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const argumentNodes =\n (_node$arguments = node.arguments) !== null && _node$arguments !== void 0\n ? _node$arguments\n : [];\n const argNodeMap = keyMap(argumentNodes, (arg) => arg.name.value);\n\n for (const argDef of def.args) {\n const name = argDef.name;\n const argType = argDef.type;\n const argumentNode = argNodeMap[name];\n\n if (!argumentNode) {\n if (argDef.defaultValue !== undefined) {\n coercedValues[name] = argDef.defaultValue;\n } else if (isNonNullType(argType)) {\n throw new GraphQLError(\n `Argument \"${name}\" of required type \"${inspect(argType)}\" ` +\n 'was not provided.',\n {\n nodes: node,\n },\n );\n }\n\n continue;\n }\n\n const valueNode = argumentNode.value;\n let isNull = valueNode.kind === Kind.NULL;\n\n if (valueNode.kind === Kind.VARIABLE) {\n const variableName = valueNode.name.value;\n\n if (\n variableValues == null ||\n !hasOwnProperty(variableValues, variableName)\n ) {\n if (argDef.defaultValue !== undefined) {\n coercedValues[name] = argDef.defaultValue;\n } else if (isNonNullType(argType)) {\n throw new GraphQLError(\n `Argument \"${name}\" of required type \"${inspect(argType)}\" ` +\n `was provided the variable \"$${variableName}\" which was not provided a runtime value.`,\n {\n nodes: valueNode,\n },\n );\n }\n\n continue;\n }\n\n isNull = variableValues[variableName] == null;\n }\n\n if (isNull && isNonNullType(argType)) {\n throw new GraphQLError(\n `Argument \"${name}\" of non-null type \"${inspect(argType)}\" ` +\n 'must not be null.',\n {\n nodes: valueNode,\n },\n );\n }\n\n const coercedValue = valueFromAST(valueNode, argType, variableValues);\n\n if (coercedValue === undefined) {\n // Note: ValuesOfCorrectTypeRule validation should catch this before\n // execution. This is a runtime check to ensure execution does not\n // continue with an invalid argument value.\n throw new GraphQLError(\n `Argument \"${name}\" has invalid value ${print(valueNode)}.`,\n {\n nodes: valueNode,\n },\n );\n }\n\n coercedValues[name] = coercedValue;\n }\n\n return { ...coercedValues };\n}\n/**\n * AST node shape accepted by getDirectiveValues.\n * @internal\n */\n\n/**\n * Prepares an object map of argument values given a directive definition\n * and a AST node which may contain directives. Optionally also accepts a map\n * of variable values.\n *\n * If the directive does not exist on the node, returns undefined.\n *\n * Note: Returned value is a plain Object with a prototype, since it is\n * exposed to user code. Care should be taken to not pull values from the\n * Object prototype.\n * @param directiveDef - The directive definition whose arguments should be coerced.\n * @param node - The AST node to inspect.\n * @param variableValues - The runtime variable values keyed by variable name.\n * @returns Coerced directive argument values keyed by argument name.\n * @example\n * ```ts\n * // Read literal directive arguments from a node.\n * import { parse } from 'graphql/language';\n * import { GraphQLSkipDirective } from 'graphql/type';\n * import { getDirectiveValues } from 'graphql/execution';\n *\n * const document = parse('{ name @skip(if: true) }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n *\n * getDirectiveValues(GraphQLSkipDirective, fieldNode); // => { if: true }\n * ```\n * @example\n * ```ts\n * // This variant resolves directive arguments from variables and handles absent directives.\n * import { parse } from 'graphql/language';\n * import { GraphQLIncludeDirective } from 'graphql/type';\n * import { getDirectiveValues } from 'graphql/execution';\n *\n * const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n *\n * getDirectiveValues(GraphQLIncludeDirective, fieldNode, {\n * includeName: false,\n * }); // => { if: false }\n * getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined\n * ```\n */\nexport function getDirectiveValues(directiveDef, node, variableValues) {\n var _node$directives;\n\n const directiveNode =\n (_node$directives = node.directives) === null || _node$directives === void 0\n ? void 0\n : _node$directives.find(\n (directive) => directive.name.value === directiveDef.name,\n );\n\n if (directiveNode) {\n return getArgumentValues(directiveDef, directiveNode, variableValues);\n }\n}\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n","import { Kind } from '../language/kinds.mjs';\nimport { isAbstractType } from '../type/definition.mjs';\nimport {\n GraphQLIncludeDirective,\n GraphQLSkipDirective,\n} from '../type/directives.mjs';\nimport { typeFromAST } from '../utilities/typeFromAST.mjs';\nimport { getDirectiveValues } from './values.mjs';\n/**\n * Given a selectionSet, collects all of the fields and returns them.\n *\n * CollectFields requires the \"runtime type\" of an object. For a field that\n * returns an Interface or Union type, the \"runtime type\" will be the actual\n * object type returned by that field.\n *\n * @internal\n */\n\nexport function collectFields(\n schema,\n fragments,\n variableValues,\n runtimeType,\n selectionSet,\n) {\n const fields = new Map();\n collectFieldsImpl(\n schema,\n fragments,\n variableValues,\n runtimeType,\n selectionSet,\n fields,\n new Set(),\n );\n return fields;\n}\n/**\n * Given an array of field nodes, collects all of the subfields of the passed\n * in fields, and returns them at the end.\n *\n * CollectSubFields requires the \"return type\" of an object. For a field that\n * returns an Interface or Union type, the \"return type\" will be the actual\n * object type returned by that field.\n *\n * @internal\n */\n\nexport function collectSubfields(\n schema,\n fragments,\n variableValues,\n returnType,\n fieldNodes,\n) {\n const subFieldNodes = new Map();\n const visitedFragmentNames = new Set();\n\n for (const node of fieldNodes) {\n if (node.selectionSet) {\n collectFieldsImpl(\n schema,\n fragments,\n variableValues,\n returnType,\n node.selectionSet,\n subFieldNodes,\n visitedFragmentNames,\n );\n }\n }\n\n return subFieldNodes;\n}\n\nfunction collectFieldsImpl(\n schema,\n fragments,\n variableValues,\n runtimeType,\n selectionSet,\n fields,\n visitedFragmentNames,\n) {\n for (const selection of selectionSet.selections) {\n switch (selection.kind) {\n case Kind.FIELD: {\n if (!shouldIncludeNode(variableValues, selection)) {\n continue;\n }\n\n const name = getFieldEntryKey(selection);\n const fieldList = fields.get(name);\n\n if (fieldList !== undefined) {\n fieldList.push(selection);\n } else {\n fields.set(name, [selection]);\n }\n\n break;\n }\n\n case Kind.INLINE_FRAGMENT: {\n if (\n !shouldIncludeNode(variableValues, selection) ||\n !doesFragmentConditionMatch(schema, selection, runtimeType)\n ) {\n continue;\n }\n\n collectFieldsImpl(\n schema,\n fragments,\n variableValues,\n runtimeType,\n selection.selectionSet,\n fields,\n visitedFragmentNames,\n );\n break;\n }\n\n case Kind.FRAGMENT_SPREAD: {\n const fragName = selection.name.value;\n\n if (\n visitedFragmentNames.has(fragName) ||\n !shouldIncludeNode(variableValues, selection)\n ) {\n continue;\n }\n\n visitedFragmentNames.add(fragName);\n const fragment = fragments[fragName];\n\n if (\n !fragment ||\n !doesFragmentConditionMatch(schema, fragment, runtimeType)\n ) {\n continue;\n }\n\n collectFieldsImpl(\n schema,\n fragments,\n variableValues,\n runtimeType,\n fragment.selectionSet,\n fields,\n visitedFragmentNames,\n );\n break;\n }\n }\n }\n}\n/**\n * Determines if a field should be included based on the `@include` and `@skip`\n * directives, where `@skip` has higher precedence than `@include`.\n *\n * @internal\n */\n\nfunction shouldIncludeNode(variableValues, node) {\n const skip = getDirectiveValues(GraphQLSkipDirective, node, variableValues);\n\n if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) {\n return false;\n }\n\n const include = getDirectiveValues(\n GraphQLIncludeDirective,\n node,\n variableValues,\n );\n\n if (\n (include === null || include === void 0 ? void 0 : include.if) === false\n ) {\n return false;\n }\n\n return true;\n}\n/**\n * Determines if a fragment is applicable to the given type.\n *\n * @internal\n */\n\nfunction doesFragmentConditionMatch(schema, fragment, type) {\n const typeConditionNode = fragment.typeCondition;\n\n if (!typeConditionNode) {\n return true;\n }\n\n const conditionalType = typeFromAST(schema, typeConditionNode);\n\n if (conditionalType === type) {\n return true;\n }\n\n if (isAbstractType(conditionalType)) {\n return schema.isSubType(conditionalType, type);\n }\n\n return false;\n}\n/**\n * Implements the logic to compute the key of a given field's entry\n *\n * @internal\n */\n\nfunction getFieldEntryKey(node) {\n return node.alias ? node.alias.value : node.name.value;\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { collectFields } from '../../execution/collectFields.mjs';\n\n/**\n * Subscriptions must only include a non-introspection field.\n *\n * A GraphQL subscription is valid only if it contains a single root field and\n * that root field is not an introspection field.\n *\n * See https://spec.graphql.org/draft/#sec-Single-root-field\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { SingleFieldSubscriptionsRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n *\n * type Subscription {\n * a: String\n * b: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * subscription { a b }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [SingleFieldSubscriptionsRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * subscription { a }\n * `);\n * const validErrors = validate(schema, validDocument, [SingleFieldSubscriptionsRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function SingleFieldSubscriptionsRule(context) {\n return {\n OperationDefinition(node) {\n if (node.operation === 'subscription') {\n const schema = context.getSchema();\n const subscriptionType = schema.getSubscriptionType();\n\n if (subscriptionType) {\n const operationName = node.name ? node.name.value : null;\n const variableValues = Object.create(null);\n const document = context.getDocument();\n const fragments = Object.create(null);\n\n for (const definition of document.definitions) {\n if (definition.kind === Kind.FRAGMENT_DEFINITION) {\n fragments[definition.name.value] = definition;\n }\n }\n\n const fields = collectFields(\n schema,\n fragments,\n variableValues,\n subscriptionType,\n node.selectionSet,\n );\n\n if (fields.size > 1) {\n const fieldSelectionLists = [...fields.values()];\n const extraFieldSelectionLists = fieldSelectionLists.slice(1);\n const extraFieldSelections = extraFieldSelectionLists.flat();\n context.reportError(\n new GraphQLError(\n operationName != null\n ? `Subscription \"${operationName}\" must select only one top level field.`\n : 'Anonymous Subscription must select only one top level field.',\n {\n nodes: extraFieldSelections,\n },\n ),\n );\n }\n\n for (const fieldNodes of fields.values()) {\n const field = fieldNodes[0];\n const fieldName = field.name.value;\n\n if (fieldName.startsWith('__')) {\n context.reportError(\n new GraphQLError(\n operationName != null\n ? `Subscription \"${operationName}\" must not select an introspection top level field.`\n : 'Anonymous Subscription must not select an introspection top level field.',\n {\n nodes: fieldNodes,\n },\n ),\n );\n }\n }\n }\n }\n },\n };\n}\n","/**\n * Groups array items into a Map, given a function to produce grouping key.\n *\n * @internal\n */\nexport function groupBy(list, keyFn) {\n const result = new Map();\n\n for (const item of list) {\n const key = keyFn(item);\n const group = result.get(key);\n\n if (group === undefined) {\n result.set(key, [item]);\n } else {\n group.push(item);\n }\n }\n\n return result;\n}\n","/** @category Validation Rules */\nimport { groupBy } from '../../jsutils/groupBy.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique argument definition names\n *\n * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments.\n * A GraphQL Directive is only valid if all its arguments are uniquely named.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueArgumentDefinitionNamesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * type Query { field(arg: String, arg: Int): String }\n * `;\n *\n * UniqueArgumentDefinitionNamesRule.name; // => 'UniqueArgumentDefinitionNamesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * type Query { field(arg: String): String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueArgumentDefinitionNamesRule(context) {\n return {\n DirectiveDefinition(directiveNode) {\n var _directiveNode$argume;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const argumentNodes =\n (_directiveNode$argume = directiveNode.arguments) !== null &&\n _directiveNode$argume !== void 0\n ? _directiveNode$argume\n : [];\n return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes);\n },\n\n InterfaceTypeDefinition: checkArgUniquenessPerField,\n InterfaceTypeExtension: checkArgUniquenessPerField,\n ObjectTypeDefinition: checkArgUniquenessPerField,\n ObjectTypeExtension: checkArgUniquenessPerField,\n };\n\n function checkArgUniquenessPerField(typeNode) {\n var _typeNode$fields;\n\n const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const fieldNodes =\n (_typeNode$fields = typeNode.fields) !== null &&\n _typeNode$fields !== void 0\n ? _typeNode$fields\n : [];\n\n for (const fieldDef of fieldNodes) {\n var _fieldDef$arguments;\n\n const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const argumentNodes =\n (_fieldDef$arguments = fieldDef.arguments) !== null &&\n _fieldDef$arguments !== void 0\n ? _fieldDef$arguments\n : [];\n checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes);\n }\n\n return false;\n }\n\n function checkArgUniqueness(parentName, argumentNodes) {\n const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value);\n\n for (const [argName, argNodes] of seenArgs) {\n if (argNodes.length > 1) {\n context.reportError(\n new GraphQLError(\n `Argument \"${parentName}(${argName}:)\" can only be defined once.`,\n {\n nodes: argNodes.map((node) => node.name),\n },\n ),\n );\n }\n }\n\n return false;\n }\n}\n","/** @category Validation Rules */\nimport { groupBy } from '../../jsutils/groupBy.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique argument names\n *\n * A GraphQL field or directive is only valid if all supplied arguments are\n * uniquely named.\n *\n * See https://spec.graphql.org/draft/#sec-Argument-Names\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueArgumentNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: String): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { field(arg: \"1\", arg: \"2\") }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueArgumentNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { field(arg: \"1\") }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueArgumentNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueArgumentNamesRule(context) {\n return {\n Field: checkArgUniqueness,\n Directive: checkArgUniqueness,\n };\n\n function checkArgUniqueness(parentNode) {\n var _parentNode$arguments;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const argumentNodes =\n (_parentNode$arguments = parentNode.arguments) !== null &&\n _parentNode$arguments !== void 0\n ? _parentNode$arguments\n : [];\n const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value);\n\n for (const [argName, argNodes] of seenArgs) {\n if (argNodes.length > 1) {\n context.reportError(\n new GraphQLError(\n `There can be only one argument named \"${argName}\".`,\n {\n nodes: argNodes.map((node) => node.name),\n },\n ),\n );\n }\n }\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique directive names\n *\n * A GraphQL document is only valid if all defined directives have unique names.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueDirectiveNamesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * directive @tag on FIELD directive @tag on QUERY type Query { name: String }\n * `;\n *\n * UniqueDirectiveNamesRule.name; // => 'UniqueDirectiveNamesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * directive @tag on FIELD type Query { name: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueDirectiveNamesRule(context) {\n const knownDirectiveNames = Object.create(null);\n const schema = context.getSchema();\n return {\n DirectiveDefinition(node) {\n const directiveName = node.name.value;\n\n if (\n schema !== null &&\n schema !== void 0 &&\n schema.getDirective(directiveName)\n ) {\n context.reportError(\n new GraphQLError(\n `Directive \"@${directiveName}\" already exists in the schema. It cannot be redefined.`,\n {\n nodes: node.name,\n },\n ),\n );\n return;\n }\n\n if (knownDirectiveNames[directiveName]) {\n context.reportError(\n new GraphQLError(\n `There can be only one directive named \"@${directiveName}\".`,\n {\n nodes: [knownDirectiveNames[directiveName], node.name],\n },\n ),\n );\n } else {\n knownDirectiveNames[directiveName] = node.name;\n }\n\n return false;\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport {\n isTypeDefinitionNode,\n isTypeExtensionNode,\n} from '../../language/predicates.mjs';\nimport { specifiedDirectives } from '../../type/directives.mjs';\n\n/**\n * Unique directive names per location\n *\n * A GraphQL document is only valid if all non-repeatable directives at\n * a given location are uniquely named.\n *\n * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueDirectivesPerLocationRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { name @include(if: true) @include(if: false) }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueDirectivesPerLocationRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { name @include(if: true) }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueDirectivesPerLocationRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueDirectivesPerLocationRule(context) {\n const uniqueDirectiveMap = Object.create(null);\n const schema = context.getSchema();\n const definedDirectives = schema\n ? schema.getDirectives()\n : specifiedDirectives;\n\n for (const directive of definedDirectives) {\n uniqueDirectiveMap[directive.name] = !directive.isRepeatable;\n }\n\n const astDefinitions = context.getDocument().definitions;\n\n for (const def of astDefinitions) {\n if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n uniqueDirectiveMap[def.name.value] = !def.repeatable;\n }\n }\n\n const schemaDirectives = Object.create(null);\n const typeDirectivesMap = Object.create(null);\n const directiveDirectivesMap = Object.create(null);\n return {\n // Many different AST nodes may contain directives. Rather than listing\n // them all, just listen for entering any node, and check to see if it\n // defines any directives.\n enter(node) {\n if (!('directives' in node) || !node.directives) {\n return;\n }\n\n let seenDirectives;\n\n if (\n node.kind === Kind.SCHEMA_DEFINITION ||\n node.kind === Kind.SCHEMA_EXTENSION\n ) {\n seenDirectives = schemaDirectives;\n } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) {\n const typeName = node.name.value;\n seenDirectives = typeDirectivesMap[typeName];\n\n if (seenDirectives === undefined) {\n typeDirectivesMap[typeName] = seenDirectives = Object.create(null);\n }\n } else if (\n node.kind === Kind.DIRECTIVE_DEFINITION ||\n node.kind === Kind.DIRECTIVE_EXTENSION\n ) {\n const directiveName = node.name.value;\n seenDirectives = directiveDirectivesMap[directiveName];\n\n if (seenDirectives === undefined) {\n directiveDirectivesMap[directiveName] = seenDirectives =\n Object.create(null);\n }\n } else {\n seenDirectives = Object.create(null);\n }\n\n for (const directive of node.directives) {\n const directiveName = directive.name.value;\n\n if (uniqueDirectiveMap[directiveName]) {\n if (seenDirectives[directiveName]) {\n context.reportError(\n new GraphQLError(\n `The directive \"@${directiveName}\" can only be used once at this location.`,\n {\n nodes: [seenDirectives[directiveName], directive],\n },\n ),\n );\n } else {\n seenDirectives[directiveName] = directive;\n }\n }\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { isEnumType } from '../../type/definition.mjs';\n\n/**\n * Unique enum value names\n *\n * A GraphQL enum type is only valid if all its values are uniquely named.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueEnumValueNamesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * enum Status { ACTIVE ACTIVE } type Query { status: Status }\n * `;\n *\n * UniqueEnumValueNamesRule.name; // => 'UniqueEnumValueNamesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * enum Status { ACTIVE INACTIVE } type Query { status: Status }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueEnumValueNamesRule(context) {\n const schema = context.getSchema();\n const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);\n const knownValueNames = Object.create(null);\n return {\n EnumTypeDefinition: checkValueUniqueness,\n EnumTypeExtension: checkValueUniqueness,\n };\n\n function checkValueUniqueness(node) {\n var _node$values;\n\n const typeName = node.name.value;\n\n if (!knownValueNames[typeName]) {\n knownValueNames[typeName] = Object.create(null);\n } // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const valueNodes =\n (_node$values = node.values) !== null && _node$values !== void 0\n ? _node$values\n : [];\n const valueNames = knownValueNames[typeName];\n\n for (const valueDef of valueNodes) {\n const valueName = valueDef.name.value;\n const existingType = existingTypeMap[typeName];\n\n if (isEnumType(existingType) && existingType.getValue(valueName)) {\n context.reportError(\n new GraphQLError(\n `Enum value \"${typeName}.${valueName}\" already exists in the schema. It cannot also be defined in this type extension.`,\n {\n nodes: valueDef.name,\n },\n ),\n );\n } else if (valueNames[valueName]) {\n context.reportError(\n new GraphQLError(\n `Enum value \"${typeName}.${valueName}\" can only be defined once.`,\n {\n nodes: [valueNames[valueName], valueDef.name],\n },\n ),\n );\n } else {\n valueNames[valueName] = valueDef.name;\n }\n }\n\n return false;\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport {\n isInputObjectType,\n isInterfaceType,\n isObjectType,\n} from '../../type/definition.mjs';\n\n/**\n * Unique field definition names\n *\n * A GraphQL complex type is only valid if all its fields are uniquely named.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * type Query { name: String name: String }\n * `;\n *\n * UniqueFieldDefinitionNamesRule.name; // => 'UniqueFieldDefinitionNamesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * type Query { name: String other: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueFieldDefinitionNamesRule(context) {\n const schema = context.getSchema();\n const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null);\n const knownFieldNames = Object.create(null);\n return {\n InputObjectTypeDefinition: checkFieldUniqueness,\n InputObjectTypeExtension: checkFieldUniqueness,\n InterfaceTypeDefinition: checkFieldUniqueness,\n InterfaceTypeExtension: checkFieldUniqueness,\n ObjectTypeDefinition: checkFieldUniqueness,\n ObjectTypeExtension: checkFieldUniqueness,\n };\n\n function checkFieldUniqueness(node) {\n var _node$fields;\n\n const typeName = node.name.value;\n\n if (!knownFieldNames[typeName]) {\n knownFieldNames[typeName] = Object.create(null);\n } // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const fieldNodes =\n (_node$fields = node.fields) !== null && _node$fields !== void 0\n ? _node$fields\n : [];\n const fieldNames = knownFieldNames[typeName];\n\n for (const fieldDef of fieldNodes) {\n const fieldName = fieldDef.name.value;\n\n if (hasField(existingTypeMap[typeName], fieldName)) {\n context.reportError(\n new GraphQLError(\n `Field \"${typeName}.${fieldName}\" already exists in the schema. It cannot also be defined in this type extension.`,\n {\n nodes: fieldDef.name,\n },\n ),\n );\n } else if (fieldNames[fieldName]) {\n context.reportError(\n new GraphQLError(\n `Field \"${typeName}.${fieldName}\" can only be defined once.`,\n {\n nodes: [fieldNames[fieldName], fieldDef.name],\n },\n ),\n );\n } else {\n fieldNames[fieldName] = fieldDef.name;\n }\n }\n\n return false;\n }\n}\n\nfunction hasField(type, fieldName) {\n if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) {\n return type.getFields()[fieldName] != null;\n }\n\n return false;\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique fragment names\n *\n * A GraphQL document is only valid if all defined fragments have unique names.\n *\n * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueFragmentNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * fragment A on Query { name } fragment A on Query { name } query { ...A }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueFragmentNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * fragment A on Query { name } query { ...A }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueFragmentNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueFragmentNamesRule(context) {\n const knownFragmentNames = Object.create(null);\n return {\n OperationDefinition: () => false,\n\n FragmentDefinition(node) {\n const fragmentName = node.name.value;\n\n if (knownFragmentNames[fragmentName]) {\n context.reportError(\n new GraphQLError(\n `There can be only one fragment named \"${fragmentName}\".`,\n {\n nodes: [knownFragmentNames[fragmentName], node.name],\n },\n ),\n );\n } else {\n knownFragmentNames[fragmentName] = node.name;\n }\n\n return false;\n },\n };\n}\n","/** @category Validation Rules */\nimport { invariant } from '../../jsutils/invariant.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique input field names\n *\n * A GraphQL input object value is only valid if all supplied fields are\n * uniquely named.\n *\n * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueInputFieldNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * input Filter {\n * name: String\n * }\n *\n * type Query {\n * search(filter: Filter): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { search(filter: { name: \"a\", name: \"b\" }) }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueInputFieldNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { search(filter: { name: \"a\" }) }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueInputFieldNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueInputFieldNamesRule(context) {\n const knownNameStack = [];\n let knownNames = Object.create(null);\n return {\n ObjectValue: {\n enter() {\n knownNameStack.push(knownNames);\n knownNames = Object.create(null);\n },\n\n leave() {\n const prevKnownNames = knownNameStack.pop();\n prevKnownNames || invariant(false);\n knownNames = prevKnownNames;\n },\n },\n\n ObjectField(node) {\n const fieldName = node.name.value;\n\n if (knownNames[fieldName]) {\n context.reportError(\n new GraphQLError(\n `There can be only one input field named \"${fieldName}\".`,\n {\n nodes: [knownNames[fieldName], node.name],\n },\n ),\n );\n } else {\n knownNames[fieldName] = node.name;\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique operation names\n *\n * A GraphQL document is only valid if all defined operations have unique names.\n *\n * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueOperationNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query Same { name } query Same { name }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueOperationNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query One { name } query Two { name }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueOperationNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueOperationNamesRule(context) {\n const knownOperationNames = Object.create(null);\n return {\n OperationDefinition(node) {\n const operationName = node.name;\n\n if (operationName) {\n if (knownOperationNames[operationName.value]) {\n context.reportError(\n new GraphQLError(\n `There can be only one operation named \"${operationName.value}\".`,\n {\n nodes: [\n knownOperationNames[operationName.value],\n operationName,\n ],\n },\n ),\n );\n } else {\n knownOperationNames[operationName.value] = operationName;\n }\n }\n\n return false;\n },\n\n FragmentDefinition: () => false,\n };\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique operation types\n *\n * A GraphQL document is only valid if it has only one type per operation.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueOperationTypesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * schema { query: Query query: Other } type Query { name: String } type Other { name: String }\n * `;\n *\n * UniqueOperationTypesRule.name; // => 'UniqueOperationTypesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * schema { query: Query } type Query { name: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueOperationTypesRule(context) {\n const schema = context.getSchema();\n const definedOperationTypes = Object.create(null);\n const existingOperationTypes = schema\n ? {\n query: schema.getQueryType(),\n mutation: schema.getMutationType(),\n subscription: schema.getSubscriptionType(),\n }\n : {};\n return {\n SchemaDefinition: checkOperationTypes,\n SchemaExtension: checkOperationTypes,\n };\n\n function checkOperationTypes(node) {\n var _node$operationTypes;\n\n // See: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const operationTypesNodes =\n (_node$operationTypes = node.operationTypes) !== null &&\n _node$operationTypes !== void 0\n ? _node$operationTypes\n : [];\n\n for (const operationType of operationTypesNodes) {\n const operation = operationType.operation;\n const alreadyDefinedOperationType = definedOperationTypes[operation];\n\n if (existingOperationTypes[operation]) {\n context.reportError(\n new GraphQLError(\n `Type for ${operation} already defined in the schema. It cannot be redefined.`,\n {\n nodes: operationType,\n },\n ),\n );\n } else if (alreadyDefinedOperationType) {\n context.reportError(\n new GraphQLError(\n `There can be only one ${operation} type in schema.`,\n {\n nodes: [alreadyDefinedOperationType, operationType],\n },\n ),\n );\n } else {\n definedOperationTypes[operation] = operationType;\n }\n }\n\n return false;\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique type names\n *\n * A GraphQL document is only valid if all defined types have unique names.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema } from 'graphql';\n * import { UniqueTypeNamesRule } from 'graphql/validation';\n *\n * const invalidSDL = `\n * type Query { name: String } type Query { other: String }\n * `;\n *\n * UniqueTypeNamesRule.name; // => 'UniqueTypeNamesRule'\n * buildSchema(invalidSDL); // throws an error\n *\n * const validSDL = `\n * type Query { name: String } type Other { name: String }\n * `;\n *\n * buildSchema(validSDL); // does not throw\n * ```\n */\nexport function UniqueTypeNamesRule(context) {\n const knownTypeNames = Object.create(null);\n const schema = context.getSchema();\n return {\n ScalarTypeDefinition: checkTypeName,\n ObjectTypeDefinition: checkTypeName,\n InterfaceTypeDefinition: checkTypeName,\n UnionTypeDefinition: checkTypeName,\n EnumTypeDefinition: checkTypeName,\n InputObjectTypeDefinition: checkTypeName,\n };\n\n function checkTypeName(node) {\n const typeName = node.name.value;\n\n if (schema !== null && schema !== void 0 && schema.getType(typeName)) {\n context.reportError(\n new GraphQLError(\n `Type \"${typeName}\" already exists in the schema. It cannot also be defined in this type definition.`,\n {\n nodes: node.name,\n },\n ),\n );\n return;\n }\n\n if (knownTypeNames[typeName]) {\n context.reportError(\n new GraphQLError(`There can be only one type named \"${typeName}\".`, {\n nodes: [knownTypeNames[typeName], node.name],\n }),\n );\n } else {\n knownTypeNames[typeName] = node.name;\n }\n\n return false;\n }\n}\n","/** @category Validation Rules */\nimport { groupBy } from '../../jsutils/groupBy.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\n\n/**\n * Unique variable names\n *\n * A GraphQL operation is only valid if all its variables are uniquely named.\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { UniqueVariableNamesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: ID): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query ($id: ID, $id: ID) { field(arg: $id) }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [UniqueVariableNamesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query ($id: ID) { field(arg: $id) }\n * `);\n * const validErrors = validate(schema, validDocument, [UniqueVariableNamesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function UniqueVariableNamesRule(context) {\n return {\n OperationDefinition(operationNode) {\n var _operationNode$variab;\n\n // See: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n const variableDefinitions =\n (_operationNode$variab = operationNode.variableDefinitions) !== null &&\n _operationNode$variab !== void 0\n ? _operationNode$variab\n : [];\n const seenVariableDefinitions = groupBy(\n variableDefinitions,\n (node) => node.variable.name.value,\n );\n\n for (const [variableName, variableNodes] of seenVariableDefinitions) {\n if (variableNodes.length > 1) {\n context.reportError(\n new GraphQLError(\n `There can be only one variable named \"$${variableName}\".`,\n {\n nodes: variableNodes.map((node) => node.variable.name),\n },\n ),\n );\n }\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { didYouMean } from '../../jsutils/didYouMean.mjs';\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { keyMap } from '../../jsutils/keyMap.mjs';\nimport { suggestionList } from '../../jsutils/suggestionList.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport { print } from '../../language/printer.mjs';\nimport {\n getNamedType,\n getNullableType,\n isInputObjectType,\n isLeafType,\n isListType,\n isNonNullType,\n isRequiredInputField,\n} from '../../type/definition.mjs';\n\n/**\n * Value literals of correct type\n *\n * A GraphQL document is only valid if all value literals are of the type\n * expected at their position.\n *\n * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { ValuesOfCorrectTypeRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * count(limit: Int): Int\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * { count(limit: \"many\") }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [ValuesOfCorrectTypeRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * { count(limit: 1) }\n * `);\n * const validErrors = validate(schema, validDocument, [ValuesOfCorrectTypeRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function ValuesOfCorrectTypeRule(context) {\n return {\n ListValue(node) {\n // Note: TypeInfo will traverse into a list's item type, so look to the\n // parent input type to check if it is a list.\n const type = getNullableType(context.getParentInputType());\n\n if (!isListType(type)) {\n isValidValueNode(context, node);\n return false; // Don't traverse further.\n }\n },\n\n ObjectValue(node) {\n const type = getNamedType(context.getInputType());\n\n if (!isInputObjectType(type)) {\n isValidValueNode(context, node);\n return false; // Don't traverse further.\n } // Ensure every required field exists.\n\n const fieldNodeMap = keyMap(node.fields, (field) => field.name.value);\n\n for (const fieldDef of Object.values(type.getFields())) {\n const fieldNode = fieldNodeMap[fieldDef.name];\n\n if (!fieldNode && isRequiredInputField(fieldDef)) {\n const typeStr = inspect(fieldDef.type);\n context.reportError(\n new GraphQLError(\n `Field \"${type.name}.${fieldDef.name}\" of required type \"${typeStr}\" was not provided.`,\n {\n nodes: node,\n },\n ),\n );\n }\n }\n\n if (type.isOneOf) {\n validateOneOfInputObject(context, node, type, fieldNodeMap);\n }\n },\n\n ObjectField(node) {\n const parentType = getNamedType(context.getParentInputType());\n const fieldType = context.getInputType();\n\n if (!fieldType && isInputObjectType(parentType)) {\n const suggestions = suggestionList(\n node.name.value,\n Object.keys(parentType.getFields()),\n );\n context.reportError(\n new GraphQLError(\n `Field \"${node.name.value}\" is not defined by type \"${parentType.name}\".` +\n didYouMean(suggestions),\n {\n nodes: node,\n },\n ),\n );\n }\n },\n\n NullValue(node) {\n const type = context.getInputType();\n\n if (isNonNullType(type)) {\n context.reportError(\n new GraphQLError(\n `Expected value of type \"${inspect(type)}\", found ${print(node)}.`,\n {\n nodes: node,\n },\n ),\n );\n }\n },\n\n EnumValue: (node) => isValidValueNode(context, node),\n IntValue: (node) => isValidValueNode(context, node),\n FloatValue: (node) => isValidValueNode(context, node),\n // Descriptions are string values that would not validate according\n // to the below logic, but since (per the specification) descriptions must\n // not affect validation, they are ignored entirely when visiting the AST\n // and do not require special handling.\n // See https://spec.graphql.org/draft/#sec-Descriptions\n StringValue: (node) => isValidValueNode(context, node),\n BooleanValue: (node) => isValidValueNode(context, node),\n };\n}\n/**\n * Any value literal may be a valid representation of a Scalar, depending on\n * that scalar type.\n *\n * @internal\n */\n\nfunction isValidValueNode(context, node) {\n // Report any error at the full type expected by the location.\n const locationType = context.getInputType();\n\n if (!locationType) {\n return;\n }\n\n const type = getNamedType(locationType);\n\n if (!isLeafType(type)) {\n const typeStr = inspect(locationType);\n context.reportError(\n new GraphQLError(\n `Expected value of type \"${typeStr}\", found ${print(node)}.`,\n {\n nodes: node,\n },\n ),\n );\n return;\n } // Scalars and Enums determine if a literal value is valid via parseLiteral(),\n // which may throw or return an invalid value to indicate failure.\n\n try {\n const parseResult = type.parseLiteral(\n node,\n undefined,\n /* variables */\n );\n\n if (parseResult === undefined) {\n const typeStr = inspect(locationType);\n context.reportError(\n new GraphQLError(\n `Expected value of type \"${typeStr}\", found ${print(node)}.`,\n {\n nodes: node,\n },\n ),\n );\n }\n } catch (error) {\n const typeStr = inspect(locationType);\n\n if (error instanceof GraphQLError) {\n context.reportError(error);\n } else {\n context.reportError(\n new GraphQLError(\n `Expected value of type \"${typeStr}\", found ${print(node)}; ` +\n error.message,\n {\n nodes: node,\n originalError: error,\n },\n ),\n );\n }\n }\n}\n\nfunction validateOneOfInputObject(context, node, type, fieldNodeMap) {\n var _fieldNodeMap$keys$;\n\n const keys = Object.keys(fieldNodeMap);\n const isNotExactlyOneField = keys.length !== 1;\n\n if (isNotExactlyOneField) {\n context.reportError(\n new GraphQLError(\n `OneOf Input Object \"${type.name}\" must specify exactly one key.`,\n {\n nodes: [node],\n },\n ),\n );\n return;\n }\n\n const value =\n (_fieldNodeMap$keys$ = fieldNodeMap[keys[0]]) === null ||\n _fieldNodeMap$keys$ === void 0\n ? void 0\n : _fieldNodeMap$keys$.value;\n const isNullLiteral = !value || value.kind === Kind.NULL;\n\n if (isNullLiteral) {\n context.reportError(\n new GraphQLError(`Field \"${type.name}.${keys[0]}\" must be non-null.`, {\n nodes: [node],\n }),\n );\n }\n}\n","/** @category Validation Rules */\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { print } from '../../language/printer.mjs';\nimport { isInputType } from '../../type/definition.mjs';\nimport { typeFromAST } from '../../utilities/typeFromAST.mjs';\n\n/**\n * Variables are input types\n *\n * A GraphQL operation is only valid if all the variables it defines are of\n * input types (scalar, enum, or input object).\n *\n * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { VariablesAreInputTypesRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: ID): String\n * }\n *\n * type User {\n * name: String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query ($user: User) { field(arg: \"1\") }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [VariablesAreInputTypesRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query ($id: ID) { field(arg: $id) }\n * `);\n * const validErrors = validate(schema, validDocument, [VariablesAreInputTypesRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function VariablesAreInputTypesRule(context) {\n return {\n VariableDefinition(node) {\n const type = typeFromAST(context.getSchema(), node.type);\n\n if (type !== undefined && !isInputType(type)) {\n const variableName = node.variable.name.value;\n const typeName = print(node.type);\n context.reportError(\n new GraphQLError(\n `Variable \"$${variableName}\" cannot be non-input type \"${typeName}\".`,\n {\n nodes: node.type,\n },\n ),\n );\n }\n },\n };\n}\n","/** @category Validation Rules */\nimport { inspect } from '../../jsutils/inspect.mjs';\nimport { GraphQLError } from '../../error/GraphQLError.mjs';\nimport { Kind } from '../../language/kinds.mjs';\nimport {\n isInputObjectType,\n isNonNullType,\n isNullableType,\n} from '../../type/definition.mjs';\nimport { isTypeSubTypeOf } from '../../utilities/typeComparators.mjs';\nimport { typeFromAST } from '../../utilities/typeFromAST.mjs';\n\n/**\n * Variables in allowed position\n *\n * Variable usages must be compatible with the arguments they are passed to.\n *\n * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed\n * @param context - The validation context used while checking the document.\n * @returns A visitor that reports validation errors for this rule.\n * @example\n * ```ts\n * import { buildSchema, parse, validate } from 'graphql';\n * import { VariablesInAllowedPositionRule } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * field(arg: ID!): String\n * }\n * `);\n *\n * const invalidDocument = parse(`\n * query ($id: String) { field(arg: $id) }\n * `);\n * const invalidErrors = validate(schema, invalidDocument, [VariablesInAllowedPositionRule]);\n *\n * invalidErrors.length; // => 1\n *\n * const validDocument = parse(`\n * query ($id: ID!) { field(arg: $id) }\n * `);\n * const validErrors = validate(schema, validDocument, [VariablesInAllowedPositionRule]);\n *\n * validErrors; // => []\n * ```\n */\nexport function VariablesInAllowedPositionRule(context) {\n let varDefMap = Object.create(null);\n return {\n OperationDefinition: {\n enter() {\n varDefMap = Object.create(null);\n },\n\n leave(operation) {\n const usages = context.getRecursiveVariableUsages(operation);\n\n for (const { node, type, defaultValue, parentType } of usages) {\n const varName = node.name.value;\n const varDef = varDefMap[varName];\n\n if (varDef && type) {\n // A var type is allowed if it is the same or more strict (e.g. is\n // a subtype of) than the expected type. It can be more strict if\n // the variable type is non-null when the expected type is nullable.\n // If both are list types, the variable item type can be more strict\n // than the expected item type (contravariant).\n const schema = context.getSchema();\n const varType = typeFromAST(schema, varDef.type);\n\n if (\n varType &&\n !allowedVariableUsage(\n schema,\n varType,\n varDef.defaultValue,\n type,\n defaultValue,\n )\n ) {\n const varTypeStr = inspect(varType);\n const typeStr = inspect(type);\n context.reportError(\n new GraphQLError(\n `Variable \"$${varName}\" of type \"${varTypeStr}\" used in position expecting type \"${typeStr}\".`,\n {\n nodes: [varDef, node],\n },\n ),\n );\n }\n\n if (\n isInputObjectType(parentType) &&\n parentType.isOneOf &&\n isNullableType(varType)\n ) {\n context.reportError(\n new GraphQLError(\n `Variable \"$${varName}\" is of type \"${varType}\" but must be non-nullable to be used for OneOf Input Object \"${parentType}\".`,\n {\n nodes: [varDef, node],\n },\n ),\n );\n }\n }\n }\n },\n },\n\n VariableDefinition(node) {\n varDefMap[node.variable.name.value] = node;\n },\n };\n}\n/**\n * Returns true if the variable is allowed in the location it was found,\n * including considering if default values exist for either the variable\n * or the location at which it is located.\n *\n * OneOf Input Object Type fields are considered separately above to\n * provide a more descriptive error message.\n *\n * @internal\n */\n\nfunction allowedVariableUsage(\n schema,\n varType,\n varDefaultValue,\n locationType,\n locationDefaultValue,\n) {\n if (isNonNullType(locationType) && !isNonNullType(varType)) {\n const hasNonNullVariableDefaultValue =\n varDefaultValue != null && varDefaultValue.kind !== Kind.NULL;\n const hasLocationDefaultValue = locationDefaultValue !== undefined;\n\n if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) {\n return false;\n }\n\n const nullableLocationType = locationType.ofType;\n return isTypeSubTypeOf(schema, varType, nullableLocationType);\n }\n\n return isTypeSubTypeOf(schema, varType, locationType);\n}\n","/** @category Validation Rules */\n// Spec Section: \"Executable Definitions\"\nimport { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule.mjs'; // Spec Section: \"Field Selections on Objects, Interfaces, and Unions Types\"\n\nimport { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule.mjs'; // Spec Section: \"Fragments on Composite Types\"\n\nimport { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule.mjs'; // Spec Section: \"Argument Names\"\n\nimport {\n KnownArgumentNamesOnDirectivesRule,\n KnownArgumentNamesRule,\n} from './rules/KnownArgumentNamesRule.mjs'; // Spec Section: \"Directives Are Defined\"\n\nimport { KnownDirectivesRule } from './rules/KnownDirectivesRule.mjs'; // Spec Section: \"Fragment spread target defined\"\n\nimport { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule.mjs'; // Spec Section: \"Fragment Spread Type Existence\"\n\nimport { KnownTypeNamesRule } from './rules/KnownTypeNamesRule.mjs'; // Spec Section: \"Lone Anonymous Operation\"\n\nimport { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule.mjs'; // SDL-specific validation rules\n\nimport { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule.mjs'; // TODO: Spec Section\n\nimport { MaxIntrospectionDepthRule } from './rules/MaxIntrospectionDepthRule.mjs'; // Spec Section: \"Fragments must not form cycles\"\n\nimport { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule.mjs'; // Spec Section: \"All Variable Used Defined\"\n\nimport { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule.mjs'; // Spec Section: \"Fragments must be used\"\n\nimport { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule.mjs'; // Spec Section: \"All Variables Used\"\n\nimport { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule.mjs'; // Spec Section: \"Field Selection Merging\"\n\nimport { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule.mjs'; // Spec Section: \"Fragment spread is possible\"\n\nimport { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule.mjs';\nimport { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule.mjs'; // Spec Section: \"Argument Optionality\"\n\nimport {\n ProvidedRequiredArgumentsOnDirectivesRule,\n ProvidedRequiredArgumentsRule,\n} from './rules/ProvidedRequiredArgumentsRule.mjs'; // Spec Section: \"Leaf Field Selections\"\n\nimport { ScalarLeafsRule } from './rules/ScalarLeafsRule.mjs'; // Spec Section: \"Subscriptions with Single Root Field\"\n\nimport { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule.mjs';\nimport { UniqueArgumentDefinitionNamesRule } from './rules/UniqueArgumentDefinitionNamesRule.mjs'; // Spec Section: \"Argument Uniqueness\"\n\nimport { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule.mjs';\nimport { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule.mjs'; // Spec Section: \"Directives Are Unique Per Location\"\n\nimport { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule.mjs';\nimport { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule.mjs';\nimport { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule.mjs'; // Spec Section: \"Fragment Name Uniqueness\"\n\nimport { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule.mjs'; // Spec Section: \"Input Object Field Uniqueness\"\n\nimport { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule.mjs'; // Spec Section: \"Operation Name Uniqueness\"\n\nimport { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule.mjs';\nimport { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule.mjs';\nimport { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule.mjs'; // Spec Section: \"Variable Uniqueness\"\n\nimport { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule.mjs'; // Spec Section: \"Value Type Correctness\"\n\nimport { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule.mjs'; // Spec Section: \"Variables are Input Types\"\n\nimport { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule.mjs'; // Spec Section: \"All Variable Usages Are Allowed\"\n\nimport { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule.mjs';\n\n/**\n * Technically these aren't part of the spec but they are strongly encouraged\n * validation rules.\n */\nexport const recommendedRules = Object.freeze([MaxIntrospectionDepthRule]);\n/**\n * This set includes all validation rules defined by the GraphQL spec.\n *\n * The order of the rules in this list has been adjusted to lead to the\n * most clear output when encountering multiple validation errors.\n */\n\nexport const specifiedRules = Object.freeze([\n ExecutableDefinitionsRule,\n UniqueOperationNamesRule,\n LoneAnonymousOperationRule,\n SingleFieldSubscriptionsRule,\n KnownTypeNamesRule,\n FragmentsOnCompositeTypesRule,\n VariablesAreInputTypesRule,\n ScalarLeafsRule,\n FieldsOnCorrectTypeRule,\n UniqueFragmentNamesRule,\n KnownFragmentNamesRule,\n NoUnusedFragmentsRule,\n PossibleFragmentSpreadsRule,\n NoFragmentCyclesRule,\n UniqueVariableNamesRule,\n NoUndefinedVariablesRule,\n NoUnusedVariablesRule,\n KnownDirectivesRule,\n UniqueDirectivesPerLocationRule,\n KnownArgumentNamesRule,\n UniqueArgumentNamesRule,\n ValuesOfCorrectTypeRule,\n ProvidedRequiredArgumentsRule,\n VariablesInAllowedPositionRule,\n OverlappingFieldsCanBeMergedRule,\n UniqueInputFieldNamesRule,\n ...recommendedRules,\n]);\n/** @internal */\n\nexport const specifiedSDLRules = Object.freeze([\n LoneSchemaDefinitionRule,\n UniqueOperationTypesRule,\n UniqueTypeNamesRule,\n UniqueEnumValueNamesRule,\n UniqueFieldDefinitionNamesRule,\n UniqueArgumentDefinitionNamesRule,\n UniqueDirectiveNamesRule,\n KnownTypeNamesRule,\n KnownDirectivesRule,\n UniqueDirectivesPerLocationRule,\n PossibleTypeExtensionsRule,\n KnownArgumentNamesOnDirectivesRule,\n UniqueArgumentNamesRule,\n UniqueInputFieldNamesRule,\n ProvidedRequiredArgumentsOnDirectivesRule,\n]);\n","/** @category Validation Context */\nimport { Kind } from '../language/kinds.mjs';\nimport { visit } from '../language/visitor.mjs';\nimport { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo.mjs';\n\n/**\n * An instance of this class is passed as the \"this\" context to all validators,\n * allowing access to commonly useful contextual information from within a\n * validation rule.\n *\n * @internal\n */\nexport class ASTValidationContext {\n constructor(ast, onError) {\n this._ast = ast;\n this._fragments = undefined;\n this._fragmentSpreads = new Map();\n this._recursivelyReferencedFragments = new Map();\n this._onError = onError;\n }\n\n get [Symbol.toStringTag]() {\n return 'ASTValidationContext';\n }\n\n reportError(error) {\n this._onError(error);\n }\n\n getDocument() {\n return this._ast;\n }\n\n getFragment(name) {\n let fragments;\n\n if (this._fragments) {\n fragments = this._fragments;\n } else {\n fragments = Object.create(null);\n\n for (const defNode of this.getDocument().definitions) {\n if (defNode.kind === Kind.FRAGMENT_DEFINITION) {\n fragments[defNode.name.value] = defNode;\n }\n }\n\n this._fragments = fragments;\n }\n\n return fragments[name];\n }\n\n getFragmentSpreads(node) {\n let spreads = this._fragmentSpreads.get(node);\n\n if (!spreads) {\n spreads = [];\n const setsToVisit = [node];\n let set;\n\n while ((set = setsToVisit.pop())) {\n for (const selection of set.selections) {\n if (selection.kind === Kind.FRAGMENT_SPREAD) {\n spreads.push(selection);\n } else if (selection.selectionSet) {\n setsToVisit.push(selection.selectionSet);\n }\n }\n }\n\n this._fragmentSpreads.set(node, spreads);\n }\n\n return spreads;\n }\n\n getRecursivelyReferencedFragments(operation) {\n let fragments = this._recursivelyReferencedFragments.get(operation);\n\n if (!fragments) {\n fragments = [];\n const collectedNames = Object.create(null);\n const nodesToVisit = [operation.selectionSet];\n let node;\n\n while ((node = nodesToVisit.pop())) {\n for (const spread of this.getFragmentSpreads(node)) {\n const fragName = spread.name.value;\n\n if (collectedNames[fragName] !== true) {\n collectedNames[fragName] = true;\n const fragment = this.getFragment(fragName);\n\n if (fragment) {\n fragments.push(fragment);\n nodesToVisit.push(fragment.selectionSet);\n }\n }\n }\n }\n\n this._recursivelyReferencedFragments.set(operation, fragments);\n }\n\n return fragments;\n }\n}\n/** @internal */\n\n/** @internal */\nexport class SDLValidationContext extends ASTValidationContext {\n constructor(ast, schema, onError) {\n super(ast, onError);\n this._schema = schema;\n }\n\n get [Symbol.toStringTag]() {\n return 'SDLValidationContext';\n }\n\n getSchema() {\n return this._schema;\n }\n}\n/** @internal */\n\n/** Validation context passed to query validation rules. */\nexport class ValidationContext extends ASTValidationContext {\n /**\n * Creates a ValidationContext instance.\n * @param schema - Schema used to validate the document.\n * @param ast - Document AST being validated.\n * @param typeInfo - TypeInfo instance used to track traversal state.\n * @param onError - Callback invoked for each validation error.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { GraphQLError } from 'graphql/error';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const errors = [];\n * const context = new ValidationContext(\n * schema,\n * document,\n * new TypeInfo(schema),\n * (error) => errors.push(error),\n * );\n *\n * context.reportError(new GraphQLError('Example validation error.'));\n *\n * context.getSchema(); // => schema\n * errors[0].message; // => 'Example validation error.'\n * ```\n */\n constructor(schema, ast, typeInfo, onError) {\n super(ast, onError);\n this._schema = schema;\n this._typeInfo = typeInfo;\n this._variableUsages = new Map();\n this._recursiveVariableUsages = new Map();\n }\n /**\n * Returns the value used by `Object.prototype.toString`.\n * @returns The built-in string tag for this object.\n */\n\n get [Symbol.toStringTag]() {\n return 'ValidationContext';\n }\n /**\n * Returns the schema being used by this validation context.\n * @returns The schema being validated against.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const context = new ValidationContext(\n * schema,\n * parse('{ greeting }'),\n * new TypeInfo(schema),\n * () => {},\n * );\n *\n * context.getSchema().getQueryType()?.name; // => 'Query'\n * ```\n */\n\n getSchema() {\n return this._schema;\n }\n /**\n * Returns variable usages found directly within this node.\n * @param node - The AST node to inspect or visit.\n * @returns Variable usages found directly within this node.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting(name: String): String\n * }\n * `);\n * const document = parse('query ($name: String) { greeting(name: $name) }');\n * const operation = document.definitions[0];\n * const context = new ValidationContext(\n * schema,\n * document,\n * new TypeInfo(schema),\n * () => {},\n * );\n *\n * const usages = context.getVariableUsages(operation);\n *\n * usages[0].node.name.value; // => 'name'\n * String(usages[0].type); // => 'String'\n * ```\n */\n\n getVariableUsages(node) {\n let usages = this._variableUsages.get(node);\n\n if (!usages) {\n const newUsages = [];\n const typeInfo = new TypeInfo(this._schema);\n visit(\n node,\n visitWithTypeInfo(typeInfo, {\n VariableDefinition: () => false,\n\n Variable(variable) {\n newUsages.push({\n node: variable,\n type: typeInfo.getInputType(),\n defaultValue: typeInfo.getDefaultValue(),\n parentType: typeInfo.getParentInputType(),\n });\n },\n }),\n );\n usages = newUsages;\n\n this._variableUsages.set(node, usages);\n }\n\n return usages;\n }\n /**\n * Returns variable usages for an operation, including variables used by referenced fragments.\n * @param operation - Operation definition to inspect.\n * @returns Variable usages reachable from the operation.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * viewer: User\n * }\n *\n * type User {\n * name(prefix: String): String\n * }\n * `);\n * const document = parse(`\n * query ($prefix: String) {\n * viewer {\n * ...UserName\n * }\n * }\n *\n * fragment UserName on User {\n * name(prefix: $prefix)\n * }\n * `);\n * const operation = document.definitions[0];\n * const context = new ValidationContext(\n * schema,\n * document,\n * new TypeInfo(schema),\n * () => {},\n * );\n *\n * const usages = context.getRecursiveVariableUsages(operation);\n *\n * usages.map((usage) => usage.node.name.value); // => ['prefix']\n * ```\n */\n\n getRecursiveVariableUsages(operation) {\n let usages = this._recursiveVariableUsages.get(operation);\n\n if (!usages) {\n usages = this.getVariableUsages(operation);\n\n for (const frag of this.getRecursivelyReferencedFragments(operation)) {\n usages = usages.concat(this.getVariableUsages(frag));\n }\n\n this._recursiveVariableUsages.set(operation, usages);\n }\n\n return usages;\n }\n /**\n * Returns the current output type at this point in traversal.\n * @returns The current output type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let typeName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Field: () => {\n * typeName = String(context.getType());\n * },\n * }),\n * );\n *\n * typeName; // => 'String'\n * ```\n */\n\n getType() {\n return this._typeInfo.getType();\n }\n /**\n * Returns the current parent composite type.\n * @returns The current parent composite type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let parentTypeName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Field: () => {\n * parentTypeName = context.getParentType()?.name;\n * },\n * }),\n * );\n *\n * parentTypeName; // => 'Query'\n * ```\n */\n\n getParentType() {\n return this._typeInfo.getParentType();\n }\n /**\n * Returns the current input type at this point in traversal.\n * @returns The current input type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(limit: Int): [String]\n * }\n * `);\n * const document = parse('{ reviews(limit: 5) }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let inputTypeName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Argument: () => {\n * inputTypeName = String(context.getInputType());\n * },\n * }),\n * );\n *\n * inputTypeName; // => 'Int'\n * ```\n */\n\n getInputType() {\n return this._typeInfo.getInputType();\n }\n /**\n * Returns the parent input type for the current input position.\n * @returns The parent input type, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * input ReviewFilter {\n * stars: Int\n * }\n *\n * type Query {\n * reviews(filter: ReviewFilter): [String]\n * }\n * `);\n * const document = parse('{ reviews(filter: { stars: 5 }) }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let parentInputTypeName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * ObjectField: () => {\n * parentInputTypeName = String(context.getParentInputType());\n * },\n * }),\n * );\n *\n * parentInputTypeName; // => 'ReviewFilter'\n * ```\n */\n\n getParentInputType() {\n return this._typeInfo.getParentInputType();\n }\n /**\n * Returns the current field definition.\n * @returns The current field definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let fieldName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Field: () => {\n * fieldName = context.getFieldDef()?.name;\n * },\n * }),\n * );\n *\n * fieldName; // => 'greeting'\n * ```\n */\n\n getFieldDef() {\n return this._typeInfo.getFieldDef();\n }\n /**\n * Returns the current directive definition.\n * @returns The current directive definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting @include(if: true) }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let directiveName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Directive: () => {\n * directiveName = context.getDirective()?.name;\n * },\n * }),\n * );\n *\n * directiveName; // => 'include'\n * ```\n */\n\n getDirective() {\n return this._typeInfo.getDirective();\n }\n /**\n * Returns the current argument definition.\n * @returns The current argument definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * reviews(limit: Int): [String]\n * }\n * `);\n * const document = parse('{ reviews(limit: 5) }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let argumentName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * Argument: () => {\n * argumentName = context.getArgument()?.name;\n * },\n * }),\n * );\n *\n * argumentName; // => 'limit'\n * ```\n */\n\n getArgument() {\n return this._typeInfo.getArgument();\n }\n /**\n * Returns the current enum value definition.\n * @returns The current enum value definition, if known.\n * @example\n * ```ts\n * import { parse, visit } from 'graphql/language';\n * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities';\n * import { ValidationContext } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * enum Sort {\n * NEWEST\n * OLDEST\n * }\n *\n * type Query {\n * reviews(sort: Sort): [String]\n * }\n * `);\n * const document = parse('{ reviews(sort: OLDEST) }');\n * const typeInfo = new TypeInfo(schema);\n * const context = new ValidationContext(schema, document, typeInfo, () => {});\n * let enumValueName;\n *\n * visit(\n * document,\n * visitWithTypeInfo(typeInfo, {\n * EnumValue: () => {\n * enumValueName = context.getEnumValue()?.name;\n * },\n * }),\n * );\n *\n * enumValueName; // => 'OLDEST'\n * ```\n */\n\n getEnumValue() {\n return this._typeInfo.getEnumValue();\n }\n}\n/** A function that creates an AST visitor for validating a GraphQL document. */\n","/** @category Validation */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { mapValue } from '../jsutils/mapValue.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { QueryDocumentKeys } from '../language/ast.mjs';\nimport { visit, visitInParallel } from '../language/visitor.mjs';\nimport { assertValidSchema } from '../type/validate.mjs';\nimport { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo.mjs';\nimport { specifiedRules, specifiedSDLRules } from './specifiedRules.mjs';\nimport {\n SDLValidationContext,\n ValidationContext,\n} from './ValidationContext.mjs'; // Per the specification, descriptions must not affect validation.\n// See https://spec.graphql.org/draft/#sec-Descriptions\n\nconst QueryDocumentKeysToValidate = mapValue(QueryDocumentKeys, (keys) =>\n keys.filter((key) => key !== 'description'),\n);\n/**\n * Options used when validating a GraphQL document.\n * @internal\n */\n\n/**\n * Implements the \"Validation\" section of the spec.\n *\n * Validation runs synchronously, returning an array of encountered errors, or\n * an empty array if no errors were encountered and the document is valid.\n *\n * A list of specific validation rules may be provided. If not provided, the\n * default list of rules defined by the GraphQL specification will be used.\n *\n * Each validation rule is a function that returns a visitor\n * (see the language/visitor API). Visitor methods are expected to return\n * GraphQLErrors, or Arrays of GraphQLErrors when invalid.\n *\n * Validate will stop validation after a `maxErrors` limit has been reached.\n * Attackers can send pathologically invalid queries to induce a DoS attack,\n * so `maxErrors` defaults to 100 errors.\n *\n * Optionally a custom TypeInfo instance may be provided. If not provided, one\n * will be created from the provided schema.\n * @param schema - Schema to validate against.\n * @param documentAST - Document AST to validate.\n * @param rules - Validation rules to apply.\n * @param options - Validation options, including error limits.\n * @param typeInfo - TypeInfo instance to update during traversal.\n * @returns Validation errors, or an empty array when the document is valid.\n * @example\n * ```ts\n * // Validate with the default specified rules.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { validate } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * validate(schema, parse('{ greeting }')); // => []\n *\n * const errors = validate(schema, parse('{ missing }'));\n * errors[0].message; // => 'Cannot query field \"missing\" on type \"Query\".'\n * ```\n * @example\n * ```ts\n * // This variant uses a custom rule list, TypeInfo, and validation options.\n * import { parse } from 'graphql/language';\n * import { buildSchema, TypeInfo } from 'graphql/utilities';\n * import { FieldsOnCorrectTypeRule, validate } from 'graphql/validation';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ missingOne missingTwo }');\n *\n * const errors = validate(\n * schema,\n * document,\n * [FieldsOnCorrectTypeRule],\n * { maxErrors: 1 },\n * new TypeInfo(schema),\n * );\n *\n * errors.length; // => 2\n * errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.'\n * ```\n */\nexport function validate(\n schema,\n documentAST,\n rules = specifiedRules,\n options,\n /**\n * Deprecated TypeInfo instance used to track traversal state during\n * validation. Omit this argument so validate creates the TypeInfo instance.\n * @deprecated will be removed in 17.0.0\n */\n typeInfo = new TypeInfo(schema),\n) {\n var _options$maxErrors;\n\n const maxErrors =\n (_options$maxErrors =\n options === null || options === void 0 ? void 0 : options.maxErrors) !==\n null && _options$maxErrors !== void 0\n ? _options$maxErrors\n : 100;\n documentAST || devAssert(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error.\n\n assertValidSchema(schema);\n const abortObj = Object.freeze({});\n const errors = [];\n const context = new ValidationContext(\n schema,\n documentAST,\n typeInfo,\n (error) => {\n if (errors.length >= maxErrors) {\n errors.push(\n new GraphQLError(\n 'Too many validation errors, error limit reached. Validation aborted.',\n ),\n ); // eslint-disable-next-line @typescript-eslint/no-throw-literal\n\n throw abortObj;\n }\n\n errors.push(error);\n },\n ); // This uses a specialized visitor which runs multiple visitors in parallel,\n // while maintaining the visitor skip and break API.\n\n const visitor = visitInParallel(rules.map((rule) => rule(context))); // Visit the whole document with each instance of all provided rules.\n\n try {\n visit(\n documentAST,\n visitWithTypeInfo(typeInfo, visitor),\n QueryDocumentKeysToValidate,\n );\n } catch (e) {\n if (e !== abortObj) {\n throw e;\n }\n }\n\n return errors;\n}\n/** @internal */\n\nexport function validateSDL(\n documentAST,\n schemaToExtend,\n rules = specifiedSDLRules,\n) {\n const errors = [];\n const context = new SDLValidationContext(\n documentAST,\n schemaToExtend,\n (error) => {\n errors.push(error);\n },\n );\n const visitors = rules.map((rule) => rule(context));\n visit(documentAST, visitInParallel(visitors));\n return errors;\n}\n/**\n * Utility function which asserts a SDL document is valid by throwing an error\n * if it is invalid.\n *\n * @internal\n */\n\nexport function assertValidSDL(documentAST) {\n const errors = validateSDL(documentAST);\n\n if (errors.length !== 0) {\n throw new Error(errors.map((error) => error.message).join('\\n\\n'));\n }\n}\n/**\n * Utility function which asserts a SDL document is valid by throwing an error\n * if it is invalid.\n *\n * @internal\n */\n\nexport function assertValidSDLExtension(documentAST, schema) {\n const errors = validateSDL(documentAST, schema);\n\n if (errors.length !== 0) {\n throw new Error(errors.map((error) => error.message).join('\\n\\n'));\n }\n}\n","/**\n * Memoizes the provided three-argument function.\n *\n * @internal\n */\nexport function memoize3(fn) {\n let cache0;\n return function memoized(a1, a2, a3) {\n if (cache0 === undefined) {\n cache0 = new WeakMap();\n }\n\n let cache1 = cache0.get(a1);\n\n if (cache1 === undefined) {\n cache1 = new WeakMap();\n cache0.set(a1, cache1);\n }\n\n let cache2 = cache1.get(a2);\n\n if (cache2 === undefined) {\n cache2 = new WeakMap();\n cache1.set(a2, cache2);\n }\n\n let fnResult = cache2.get(a3);\n\n if (fnResult === undefined) {\n fnResult = fn(a1, a2, a3);\n cache2.set(a3, fnResult);\n }\n\n return fnResult;\n };\n}\n","/**\n * This function transforms a JS object `ObjMap<Promise<T>>` into\n * a `Promise<ObjMap<T>>`\n *\n * This is akin to bluebird's `Promise.props`, but implemented only using\n * `Promise.all` so it will work with any implementation of ES6 promises.\n *\n * @internal\n */\nexport function promiseForObject(object) {\n return Promise.all(Object.values(object)).then((resolvedValues) => {\n const resolvedObject = Object.create(null);\n\n for (const [i, key] of Object.keys(object).entries()) {\n resolvedObject[key] = resolvedValues[i];\n }\n\n return resolvedObject;\n });\n}\n","import { isPromise } from './isPromise.mjs';\n\n/**\n * Similar to Array.prototype.reduce(), however the reducing callback may return\n * a Promise, in which case reduction will continue after each promise resolves.\n *\n * If the callback does not return a Promise, then this function will also not\n * return a Promise.\n *\n * @internal\n */\nexport function promiseReduce(values, callbackFn, initialValue) {\n let accumulator = initialValue;\n\n for (const value of values) {\n accumulator = isPromise(accumulator)\n ? accumulator.then((resolved) => callbackFn(resolved, value))\n : callbackFn(accumulator, value);\n }\n\n return accumulator;\n}\n","import { inspect } from './inspect.mjs';\n/**\n * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface.\n *\n * @internal\n */\n\nexport function toError(thrownValue) {\n return thrownValue instanceof Error\n ? thrownValue\n : new NonErrorThrown(thrownValue);\n}\n\nclass NonErrorThrown extends Error {\n constructor(thrownValue) {\n super('Unexpected error value: ' + inspect(thrownValue));\n this.name = 'NonErrorThrown';\n this.thrownValue = thrownValue;\n }\n}\n","/** @category Errors */\nimport { toError } from '../jsutils/toError.mjs';\nimport { GraphQLError } from './GraphQLError.mjs';\n/**\n * Given an arbitrary value, presumably thrown while attempting to execute a\n * GraphQL operation, produce a new GraphQLError aware of the location in the\n * document responsible for the original Error.\n * @param rawOriginalError - The original error value to wrap.\n * @param nodes - The AST nodes associated with the error.\n * @param path - The response path associated with the error.\n * @returns The GraphQL error.\n * @example\n * ```ts\n * import { parse } from 'graphql/language';\n * import { locatedError } from 'graphql/error';\n *\n * const document = parse('{ viewer { name } }');\n * const fieldNode = document.definitions[0].selectionSet.selections[0];\n * const error = locatedError(new Error('Resolver failed'), fieldNode, [\n * 'viewer',\n * ]);\n *\n * error.message; // => 'Resolver failed'\n * error.locations; // => [{ line: 1, column: 3 }]\n * error.path; // => ['viewer']\n * ```\n */\n\nexport function locatedError(rawOriginalError, nodes, path) {\n var _nodes;\n\n const originalError = toError(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts.\n\n if (isLocatedGraphQLError(originalError)) {\n return originalError;\n }\n\n return new GraphQLError(originalError.message, {\n nodes:\n (_nodes = originalError.nodes) !== null && _nodes !== void 0\n ? _nodes\n : nodes,\n source: originalError.source,\n positions: originalError.positions,\n path,\n originalError,\n });\n}\n\nfunction isLocatedGraphQLError(error) {\n return Array.isArray(error.path);\n}\n","/** @category Execution */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { isIterableObject } from '../jsutils/isIterableObject.mjs';\nimport { isObjectLike } from '../jsutils/isObjectLike.mjs';\nimport { isPromise } from '../jsutils/isPromise.mjs';\nimport { memoize3 } from '../jsutils/memoize3.mjs';\nimport { addPath, pathToArray } from '../jsutils/Path.mjs';\nimport { promiseForObject } from '../jsutils/promiseForObject.mjs';\nimport { promiseReduce } from '../jsutils/promiseReduce.mjs';\nimport { GraphQLError } from '../error/GraphQLError.mjs';\nimport { locatedError } from '../error/locatedError.mjs';\nimport { OperationTypeNode } from '../language/ast.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isAbstractType,\n isLeafType,\n isListType,\n isNonNullType,\n isObjectType,\n} from '../type/definition.mjs';\nimport {\n SchemaMetaFieldDef,\n TypeMetaFieldDef,\n TypeNameMetaFieldDef,\n} from '../type/introspection.mjs';\nimport { assertValidSchema } from '../type/validate.mjs';\nimport {\n collectFields,\n collectSubfields as _collectSubfields,\n} from './collectFields.mjs';\nimport { getArgumentValues, getVariableValues } from './values.mjs';\n/**\n * A memoized collection of relevant subfields with regard to the return\n * type. Memoizing ensures the subfields are not repeatedly calculated, which\n * saves overhead when resolving lists of values.\n *\n * @internal\n */\n\nconst collectSubfields = memoize3((exeContext, returnType, fieldNodes) =>\n _collectSubfields(\n exeContext.schema,\n exeContext.fragments,\n exeContext.variableValues,\n returnType,\n fieldNodes,\n ),\n);\n/**\n * Terminology\n *\n * \"Definitions\" are the generic name for top-level statements in the document.\n * Examples of this include:\n * 1) Operations (such as a query)\n * 2) Fragments\n *\n * \"Operations\" are a generic name for requests in the document.\n * Examples of this include:\n * 1) query,\n * 2) mutation\n *\n * \"Selections\" are the definitions that can appear legally and at\n * single level of the query. These include:\n * 1) field references e.g `a`\n * 2) fragment \"spreads\" e.g. `...c`\n * 3) inline fragment \"spreads\" e.g. `...on Type { a }`\n */\n\n/**\n * Data that must be available at all points during query execution.\n *\n * Namely, schema of the type system that is currently executing,\n * and the fragments defined in the query document\n *\n * @internal\n */\n\nclass CollectedErrors {\n constructor() {\n this._errorPositions = new Set();\n this._errors = [];\n }\n\n get errors() {\n return this._errors;\n }\n\n add(error, path) {\n // Do not modify errors list if the execution position for this error or\n // any of its ancestors has already been nulled via error propagation.\n // This check should be unnecessary for implementations able to implement\n // actual cancellation.\n if (this._hasNulledPosition(path)) {\n return;\n }\n\n this._errorPositions.add(path);\n\n this._errors.push(error);\n }\n\n _hasNulledPosition(startPath) {\n let path = startPath;\n\n while (path !== undefined) {\n if (this._errorPositions.has(path)) {\n return true;\n }\n\n path = path.prev;\n }\n\n return this._errorPositions.has(undefined);\n }\n}\n/**\n * Represents the response produced by executing a GraphQL operation.\n * @typeParam TData - Shape of the execution data payload.\n * @typeParam TExtensions - Shape of the extensions payload.\n */\n\n/**\n * Implements the \"Executing requests\" section of the GraphQL specification.\n *\n * Returns either a synchronous ExecutionResult (if all encountered resolvers\n * are synchronous), or a Promise of an ExecutionResult that will eventually be\n * resolved and never rejected.\n *\n * If the arguments to this function do not result in a legal execution context,\n * a GraphQLError will be thrown immediately explaining the invalid input.\n *\n * Field errors are collected into the response instead of rejecting the\n * returned promise. Only the field that produced the error and its descendants\n * are omitted; sibling fields continue to execute. Errors from fields of\n * non-null type may propagate to the nearest nullable parent, which can be the\n * entire response data.\n * @param args - The arguments used to perform the operation.\n * @returns A completed execution result, or a promise resolving to one when execution is asynchronous.\n * @example\n * ```ts\n * // Execute an asynchronous operation with variables.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { execute } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting(name: String!): String\n * }\n * `);\n *\n * const result = await execute({\n * schema,\n * document: parse('query ($name: String!) { greeting(name: $name) }'),\n * rootValue: {\n * greeting: ({ name }) => `Hello, ${name}!`,\n * },\n * variableValues: { name: 'Ada' },\n * });\n *\n * result; // => { data: { greeting: 'Hello, Ada!' } }\n * ```\n * @example\n * ```ts\n * // This variant supplies context plus custom field and type resolvers.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { execute } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * interface Named {\n * name: String!\n * }\n *\n * type User implements Named {\n * name: String!\n * }\n *\n * type Query {\n * viewer: Named\n * }\n * `);\n *\n * const result = await execute({\n * schema,\n * document: parse('query Viewer { viewer { __typename name } }'),\n * rootValue: { viewer: { kind: 'user', name: 'Ada' } },\n * contextValue: { locale: 'en' },\n * operationName: 'Viewer',\n * fieldResolver: (source, _args, contextValue, info) => {\n * contextValue.locale; // => 'en'\n * return source[info.fieldName];\n * },\n * typeResolver: (value) => {\n * return value.kind === 'user' ? 'User' : undefined;\n * },\n * });\n *\n * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } }\n * ```\n * @example\n * ```ts\n * // This variant shows how resolver errors become field errors in the result.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { execute } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * broken: String\n * }\n * `);\n * const document = parse('{ broken }');\n *\n * const result = await execute({\n * schema,\n * document,\n * rootValue: {\n * broken: () => {\n * throw new Error('Resolver failed.');\n * },\n * },\n * });\n *\n * result.data.broken; // => null\n * result.errors[0].message; // => 'Resolver failed.'\n * ```\n * @example\n * ```ts\n * // This variant limits how many variable coercion errors are reported.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { execute } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * input ReviewInput {\n * stars: Int!\n * }\n *\n * type Query {\n * review(input: ReviewInput!): String\n * }\n * `);\n * const document = parse(`\n * query ($first: ReviewInput!, $second: ReviewInput!) {\n * first: review(input: $first)\n * second: review(input: $second)\n * }\n * `);\n *\n * const result = await execute({\n * schema,\n * document,\n * variableValues: {\n * first: { stars: 'bad' },\n * second: { stars: 'also bad' },\n * },\n * options: { maxCoercionErrors: 1 },\n * });\n *\n * result.errors.length; // => 2\n * result.errors[1].message; // matches /error limit reached/\n * ```\n */\nexport function execute(args) {\n // Temporary for v15 to v16 migration. Remove in v17\n arguments.length < 2 ||\n devAssert(\n false,\n 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',\n );\n const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error.\n\n assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments,\n // a \"Response\" with only errors is returned.\n\n const exeContext = buildExecutionContext(args); // Return early errors if execution context failed.\n\n if (!('schema' in exeContext)) {\n return {\n errors: exeContext,\n };\n }\n\n try {\n const { operation } = exeContext;\n const result = executeOperation(exeContext, operation, rootValue);\n\n if (isPromise(result)) {\n return result.then(\n (data) => buildResponse(data, exeContext.collectedErrors.errors),\n (error) => {\n exeContext.collectedErrors.add(error, undefined);\n return buildResponse(null, exeContext.collectedErrors.errors);\n },\n );\n }\n\n return buildResponse(result, exeContext.collectedErrors.errors);\n } catch (error) {\n exeContext.collectedErrors.add(error, undefined);\n return buildResponse(null, exeContext.collectedErrors.errors);\n }\n}\n/**\n * Also implements the \"Executing requests\" section of the GraphQL specification.\n * However, it guarantees to complete synchronously (or throw an error) assuming\n * that all field resolvers are also synchronous.\n * @param args - The arguments used to perform the operation.\n * @returns Completed execution output for a synchronous operation.\n * @example\n * ```ts\n * // Execute an operation synchronously when all resolvers are synchronous.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { executeSync } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const document = parse('{ greeting }');\n *\n * const result = executeSync({\n * schema,\n * document,\n * rootValue: {\n * greeting: 'Hello',\n * },\n * });\n *\n * result; // => { data: { greeting: 'Hello' } }\n * ```\n * @example\n * ```ts\n * // This variant shows executeSync throwing when a resolver returns a promise.\n * import { parse } from 'graphql/language';\n * import { buildSchema } from 'graphql/utilities';\n * import { executeSync } from 'graphql/execution';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * executeSync({\n * schema,\n * document: parse('{ greeting }'),\n * rootValue: {\n * greeting: async () => 'Hello',\n * },\n * }); // throws an error\n * ```\n */\n\nexport function executeSync(args) {\n const result = execute(args); // Assert that the execution was synchronous.\n\n if (isPromise(result)) {\n throw new Error('GraphQL execution failed to complete synchronously.');\n }\n\n return result;\n}\n/**\n * Given a completed execution context and data, build the `{ errors, data }`\n * response defined by the \"Response\" section of the GraphQL specification.\n *\n * @internal\n */\n\nfunction buildResponse(data, errors) {\n return errors.length === 0\n ? {\n data,\n }\n : {\n errors,\n data,\n };\n}\n/**\n * Essential assertions before executing to provide developer feedback for\n * improper use of the GraphQL library. This deprecated internal helper will be\n * removed in v17; call `assertValidSchema()` and rely on TypeScript checks\n * instead.\n *\n * @deprecated will be removed in v17 in favor of assertValidSchema() and TS checks\n * @internal\n */\n\nexport function assertValidExecutionArguments(\n schema,\n document,\n rawVariableValues,\n) {\n document || devAssert(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error.\n\n assertValidSchema(schema); // Variables, if provided, must be an object.\n\n rawVariableValues == null ||\n isObjectLike(rawVariableValues) ||\n devAssert(\n false,\n 'Variables must be provided as an Object where each property is a variable value. Perhaps look to see if an unparsed JSON string was provided.',\n );\n}\n/**\n * Constructs a ExecutionContext object from the arguments passed to\n * execute, which we will pass throughout the other execution methods.\n *\n * Throws a GraphQLError if a valid execution context cannot be created.\n *\n * @internal\n */\n\nexport function buildExecutionContext(args) {\n var _definition$name, _operation$variableDe, _options$maxCoercionE;\n\n const {\n schema,\n document,\n rootValue,\n contextValue,\n variableValues: rawVariableValues,\n operationName,\n fieldResolver,\n typeResolver,\n subscribeFieldResolver,\n options,\n } = args;\n let operation;\n const fragments = Object.create(null);\n\n for (const definition of document.definitions) {\n switch (definition.kind) {\n case Kind.OPERATION_DEFINITION:\n if (operationName == null) {\n if (operation !== undefined) {\n return [\n new GraphQLError(\n 'Must provide operation name if query contains multiple operations.',\n ),\n ];\n }\n\n operation = definition;\n } else if (\n ((_definition$name = definition.name) === null ||\n _definition$name === void 0\n ? void 0\n : _definition$name.value) === operationName\n ) {\n operation = definition;\n }\n\n break;\n\n case Kind.FRAGMENT_DEFINITION:\n fragments[definition.name.value] = definition;\n break;\n\n default: // ignore non-executable definitions\n }\n }\n\n if (!operation) {\n if (operationName != null) {\n return [new GraphQLError(`Unknown operation named \"${operationName}\".`)];\n }\n\n return [new GraphQLError('Must provide an operation.')];\n } // FIXME: https://github.com/graphql/graphql-js/issues/2203\n\n /* c8 ignore next */\n\n const variableDefinitions =\n (_operation$variableDe = operation.variableDefinitions) !== null &&\n _operation$variableDe !== void 0\n ? _operation$variableDe\n : [];\n const coercedVariableValues = getVariableValues(\n schema,\n variableDefinitions,\n rawVariableValues !== null && rawVariableValues !== void 0\n ? rawVariableValues\n : {},\n {\n maxErrors:\n (_options$maxCoercionE =\n options === null || options === void 0\n ? void 0\n : options.maxCoercionErrors) !== null &&\n _options$maxCoercionE !== void 0\n ? _options$maxCoercionE\n : 50,\n },\n );\n\n if (coercedVariableValues.errors) {\n return coercedVariableValues.errors;\n }\n\n return {\n schema,\n fragments,\n rootValue,\n contextValue,\n operation,\n variableValues: coercedVariableValues.coerced,\n fieldResolver:\n fieldResolver !== null && fieldResolver !== void 0\n ? fieldResolver\n : defaultFieldResolver,\n typeResolver:\n typeResolver !== null && typeResolver !== void 0\n ? typeResolver\n : defaultTypeResolver,\n subscribeFieldResolver:\n subscribeFieldResolver !== null && subscribeFieldResolver !== void 0\n ? subscribeFieldResolver\n : defaultFieldResolver,\n collectedErrors: new CollectedErrors(),\n };\n}\n/**\n * Implements the \"Executing operations\" section of the spec.\n *\n * @internal\n */\n\nfunction executeOperation(exeContext, operation, rootValue) {\n const rootType = exeContext.schema.getRootType(operation.operation);\n\n if (rootType == null) {\n throw new GraphQLError(\n `Schema is not configured to execute ${operation.operation} operation.`,\n {\n nodes: operation,\n },\n );\n }\n\n const rootFields = collectFields(\n exeContext.schema,\n exeContext.fragments,\n exeContext.variableValues,\n rootType,\n operation.selectionSet,\n );\n const path = undefined;\n\n switch (operation.operation) {\n case OperationTypeNode.QUERY:\n return executeFields(exeContext, rootType, rootValue, path, rootFields);\n\n case OperationTypeNode.MUTATION:\n return executeFieldsSerially(\n exeContext,\n rootType,\n rootValue,\n path,\n rootFields,\n );\n\n case OperationTypeNode.SUBSCRIPTION:\n // TODO: deprecate `subscribe` and move all logic here\n // Temporary solution until we finish merging execute and subscribe together\n return executeFields(exeContext, rootType, rootValue, path, rootFields);\n }\n}\n/**\n * Implements the \"Executing selection sets\" section of the spec\n * for fields that must be executed serially.\n *\n * @internal\n */\n\nfunction executeFieldsSerially(\n exeContext,\n parentType,\n sourceValue,\n path,\n fields,\n) {\n return promiseReduce(\n fields.entries(),\n (results, [responseName, fieldNodes]) => {\n const fieldPath = addPath(path, responseName, parentType.name);\n const result = executeField(\n exeContext,\n parentType,\n sourceValue,\n fieldNodes,\n fieldPath,\n );\n\n if (result === undefined) {\n return results;\n }\n\n if (isPromise(result)) {\n return result.then((resolvedResult) => {\n results[responseName] = resolvedResult;\n return results;\n });\n }\n\n results[responseName] = result;\n return results;\n },\n Object.create(null),\n );\n}\n/**\n * Implements the \"Executing selection sets\" section of the spec\n * for fields that may be executed in parallel.\n *\n * @internal\n */\n\nfunction executeFields(exeContext, parentType, sourceValue, path, fields) {\n const results = Object.create(null);\n let containsPromise = false;\n\n try {\n for (const [responseName, fieldNodes] of fields.entries()) {\n const fieldPath = addPath(path, responseName, parentType.name);\n const result = executeField(\n exeContext,\n parentType,\n sourceValue,\n fieldNodes,\n fieldPath,\n );\n\n if (result !== undefined) {\n results[responseName] = result;\n\n if (isPromise(result)) {\n containsPromise = true;\n }\n }\n }\n } catch (error) {\n if (containsPromise) {\n // Ensure that any promises returned by other fields are handled, as they may also reject.\n return promiseForObject(results).finally(() => {\n throw error;\n });\n }\n\n throw error;\n } // If there are no promises, we can just return the object\n\n if (!containsPromise) {\n return results;\n } // Otherwise, results is a map from field name to the result of resolving that\n // field, which is possibly a promise. Return a promise that will return this\n // same map, but with any promises replaced with the values they resolved to.\n\n return promiseForObject(results);\n}\n/**\n * Implements the \"Executing fields\" section of the spec\n * In particular, this function figures out the value that the field returns by\n * calling its resolve function, then calls completeValue to complete promises,\n * serialize scalars, or execute the sub-selection-set for objects.\n *\n * @internal\n */\n\nfunction executeField(exeContext, parentType, source, fieldNodes, path) {\n var _fieldDef$resolve;\n\n const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]);\n\n if (!fieldDef) {\n return;\n }\n\n const returnType = fieldDef.type;\n const resolveFn =\n (_fieldDef$resolve = fieldDef.resolve) !== null &&\n _fieldDef$resolve !== void 0\n ? _fieldDef$resolve\n : exeContext.fieldResolver;\n const info = buildResolveInfo(\n exeContext,\n fieldDef,\n fieldNodes,\n parentType,\n path,\n ); // Get the resolve function, regardless of if its result is normal or abrupt (error).\n\n try {\n // Build a JS object of arguments from the field.arguments AST, using the\n // variables scope to fulfill any variable references.\n // TODO: find a way to memoize, in case this field is within a List type.\n const args = getArgumentValues(\n fieldDef,\n fieldNodes[0],\n exeContext.variableValues,\n ); // The resolve function's optional third argument is a context value that\n // is provided to every resolve function within an execution. It is commonly\n // used to represent an authenticated user, or request-specific caches.\n\n const contextValue = exeContext.contextValue;\n const result = resolveFn(source, args, contextValue, info);\n let completed;\n\n if (isPromise(result)) {\n completed = result.then((resolved) =>\n completeValue(exeContext, returnType, fieldNodes, info, path, resolved),\n );\n } else {\n completed = completeValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n }\n\n if (isPromise(completed)) {\n // Note: we don't rely on a `catch` method, but we do expect \"thenable\"\n // to take a second callback for the error case.\n return completed.then(undefined, (rawError) => {\n const error = locatedError(rawError, fieldNodes, pathToArray(path));\n return handleFieldError(error, returnType, path, exeContext);\n });\n }\n\n return completed;\n } catch (rawError) {\n const error = locatedError(rawError, fieldNodes, pathToArray(path));\n return handleFieldError(error, returnType, path, exeContext);\n }\n}\n/** @internal */\n\nexport function buildResolveInfo(\n exeContext,\n fieldDef,\n fieldNodes,\n parentType,\n path,\n) {\n // The resolve function's optional fourth argument is a collection of\n // information about the current execution state.\n return {\n fieldName: fieldDef.name,\n fieldNodes,\n returnType: fieldDef.type,\n parentType,\n path,\n schema: exeContext.schema,\n fragments: exeContext.fragments,\n rootValue: exeContext.rootValue,\n operation: exeContext.operation,\n variableValues: exeContext.variableValues,\n };\n}\n\nfunction handleFieldError(error, returnType, path, exeContext) {\n // If the field type is non-nullable, then it is resolved without any\n // protection from errors, however it still properly locates the error.\n if (isNonNullType(returnType)) {\n throw error;\n } // Otherwise, error protection is applied, logging the error and resolving\n // a null value for this field if one is encountered.\n\n exeContext.collectedErrors.add(error, path);\n return null;\n}\n/**\n * Implements the instructions for completeValue as defined in the\n * \"Value Completion\" section of the spec.\n *\n * If the field type is Non-Null, then this recursively completes the value\n * for the inner type. It throws a field error if that completion returns null,\n * as per the \"Nullability\" section of the spec.\n *\n * If the field type is a List, then this recursively completes the value\n * for the inner type on each item in the list.\n *\n * If the field type is a Scalar or Enum, ensures the completed value is a legal\n * value of the type by calling the `serialize` method of GraphQL type\n * definition.\n *\n * If the field is an abstract type, determine the runtime type of the value\n * and then complete based on that type\n *\n * Otherwise, the field type expects a sub-selection set, and will complete the\n * value by executing all sub-selections.\n *\n * @internal\n */\n\nfunction completeValue(exeContext, returnType, fieldNodes, info, path, result) {\n // If result is an Error, throw a located error.\n if (result instanceof Error) {\n throw result;\n } // If field type is NonNull, complete for inner type, and throw field error\n // if result is null.\n\n if (isNonNullType(returnType)) {\n const completed = completeValue(\n exeContext,\n returnType.ofType,\n fieldNodes,\n info,\n path,\n result,\n );\n\n if (completed === null) {\n throw new Error(\n `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`,\n );\n }\n\n return completed;\n } // If result value is null or undefined then return null.\n\n if (result == null) {\n return null;\n } // If field type is List, complete each item in the list with the inner type\n\n if (isListType(returnType)) {\n return completeListValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n } // If field type is a leaf type, Scalar or Enum, serialize to a valid value,\n // returning null if serialization is not possible.\n\n if (isLeafType(returnType)) {\n return completeLeafValue(returnType, result);\n } // If field type is an abstract type, Interface or Union, determine the\n // runtime Object type and complete for that type.\n\n if (isAbstractType(returnType)) {\n return completeAbstractValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n } // If field type is Object, execute and complete all sub-selections.\n\n if (isObjectType(returnType)) {\n return completeObjectValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n );\n }\n /* c8 ignore next 6 */\n // Not reachable, all possible output types have been considered.\n\n false ||\n invariant(\n false,\n 'Cannot complete value of unexpected output type: ' + inspect(returnType),\n );\n}\n/**\n * Complete a list value by completing each item in the list with the\n * inner type\n *\n * @internal\n */\n\nfunction completeListValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n if (!isIterableObject(result)) {\n throw new GraphQLError(\n `Expected Iterable, but did not find one for field \"${info.parentType.name}.${info.fieldName}\".`,\n );\n } // This is specified as a simple map, however we're optimizing the path\n // where the list contains no Promises by avoiding creating another Promise.\n\n const itemType = returnType.ofType;\n let containsPromise = false;\n const completedResults = Array.from(result, (item, index) => {\n // No need to modify the info object containing the path,\n // since from here on it is not ever accessed by resolver functions.\n const itemPath = addPath(path, index, undefined);\n\n try {\n let completedItem;\n\n if (isPromise(item)) {\n completedItem = item.then((resolved) =>\n completeValue(\n exeContext,\n itemType,\n fieldNodes,\n info,\n itemPath,\n resolved,\n ),\n );\n } else {\n completedItem = completeValue(\n exeContext,\n itemType,\n fieldNodes,\n info,\n itemPath,\n item,\n );\n }\n\n if (isPromise(completedItem)) {\n containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect \"thenable\"\n // to take a second callback for the error case.\n\n return completedItem.then(undefined, (rawError) => {\n const error = locatedError(\n rawError,\n fieldNodes,\n pathToArray(itemPath),\n );\n return handleFieldError(error, itemType, itemPath, exeContext);\n });\n }\n\n return completedItem;\n } catch (rawError) {\n const error = locatedError(rawError, fieldNodes, pathToArray(itemPath));\n return handleFieldError(error, itemType, itemPath, exeContext);\n }\n });\n return containsPromise ? Promise.all(completedResults) : completedResults;\n}\n/**\n * Complete a Scalar or Enum by serializing to a valid value, returning\n * null if serialization is not possible.\n *\n * @internal\n */\n\nfunction completeLeafValue(returnType, result) {\n const serializedResult = returnType.serialize(result);\n\n if (serializedResult == null) {\n throw new Error(\n `Expected \\`${inspect(returnType)}.serialize(${inspect(result)})\\` to ` +\n `return non-nullable value, returned: ${inspect(serializedResult)}`,\n );\n }\n\n return serializedResult;\n}\n/**\n * Complete a value of an abstract type by determining the runtime object type\n * of that value, then complete the value for that type.\n *\n * @internal\n */\n\nfunction completeAbstractValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n var _returnType$resolveTy;\n\n const resolveTypeFn =\n (_returnType$resolveTy = returnType.resolveType) !== null &&\n _returnType$resolveTy !== void 0\n ? _returnType$resolveTy\n : exeContext.typeResolver;\n const contextValue = exeContext.contextValue;\n const runtimeType = resolveTypeFn(result, contextValue, info, returnType);\n\n if (isPromise(runtimeType)) {\n return runtimeType.then((resolvedRuntimeType) =>\n completeObjectValue(\n exeContext,\n ensureValidRuntimeType(\n resolvedRuntimeType,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n ),\n fieldNodes,\n info,\n path,\n result,\n ),\n );\n }\n\n return completeObjectValue(\n exeContext,\n ensureValidRuntimeType(\n runtimeType,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n ),\n fieldNodes,\n info,\n path,\n result,\n );\n}\n\nfunction ensureValidRuntimeType(\n runtimeTypeName,\n exeContext,\n returnType,\n fieldNodes,\n info,\n result,\n) {\n if (runtimeTypeName == null) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" must resolve to an Object type at runtime for field \"${info.parentType.name}.${info.fieldName}\". Either the \"${returnType.name}\" type should provide a \"resolveType\" function or each possible type should provide an \"isTypeOf\" function.`,\n fieldNodes,\n );\n } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType`\n // TODO: remove in 17.0.0 release\n\n if (isObjectType(runtimeTypeName)) {\n throw new GraphQLError(\n 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.',\n );\n }\n\n if (typeof runtimeTypeName !== 'string') {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" must resolve to an Object type at runtime for field \"${info.parentType.name}.${info.fieldName}\" with ` +\n `value ${inspect(result)}, received \"${inspect(runtimeTypeName)}\".`,\n );\n }\n\n const runtimeType = exeContext.schema.getType(runtimeTypeName);\n\n if (runtimeType == null) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" was resolved to a type \"${runtimeTypeName}\" that does not exist inside the schema.`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n if (!isObjectType(runtimeType)) {\n throw new GraphQLError(\n `Abstract type \"${returnType.name}\" was resolved to a non-object type \"${runtimeTypeName}\".`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n if (!exeContext.schema.isSubType(returnType, runtimeType)) {\n throw new GraphQLError(\n `Runtime Object type \"${runtimeType.name}\" is not a possible type for \"${returnType.name}\".`,\n {\n nodes: fieldNodes,\n },\n );\n }\n\n return runtimeType;\n}\n/**\n * Complete an Object value by executing all sub-selections.\n *\n * @internal\n */\n\nfunction completeObjectValue(\n exeContext,\n returnType,\n fieldNodes,\n info,\n path,\n result,\n) {\n // Collect sub-fields to execute to complete this value.\n const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the\n // current result. If isTypeOf returns false, then raise an error rather\n // than continuing execution.\n\n if (returnType.isTypeOf) {\n const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info);\n\n if (isPromise(isTypeOf)) {\n return isTypeOf.then((resolvedIsTypeOf) => {\n if (!resolvedIsTypeOf) {\n throw invalidReturnTypeError(returnType, result, fieldNodes);\n }\n\n return executeFields(\n exeContext,\n returnType,\n result,\n path,\n subFieldNodes,\n );\n });\n }\n\n if (!isTypeOf) {\n throw invalidReturnTypeError(returnType, result, fieldNodes);\n }\n }\n\n return executeFields(exeContext, returnType, result, path, subFieldNodes);\n}\n\nfunction invalidReturnTypeError(returnType, result, fieldNodes) {\n return new GraphQLError(\n `Expected value of type \"${returnType.name}\" but got: ${inspect(result)}.`,\n {\n nodes: fieldNodes,\n },\n );\n}\n/**\n * If a resolveType function is not given, then a default resolve behavior is\n * used which attempts two strategies:\n *\n * First, See if the provided value has a `__typename` field defined, if so, use\n * that value as name of the resolved type.\n *\n * Otherwise, test each possible type for the abstract type by calling\n * isTypeOf for the object being coerced, returning the first type that matches.\n */\n\nexport const defaultTypeResolver = function (\n value,\n contextValue,\n info,\n abstractType,\n) {\n // First, look for `__typename`.\n if (isObjectLike(value) && typeof value.__typename === 'string') {\n return value.__typename;\n } // Otherwise, test each possible type.\n\n const possibleTypes = info.schema.getPossibleTypes(abstractType);\n const promisedIsTypeOfResults = [];\n\n for (let i = 0; i < possibleTypes.length; i++) {\n const type = possibleTypes[i];\n\n if (type.isTypeOf) {\n const isTypeOfResult = type.isTypeOf(value, contextValue, info);\n\n if (isPromise(isTypeOfResult)) {\n promisedIsTypeOfResults[i] = isTypeOfResult;\n } else if (isTypeOfResult) {\n if (promisedIsTypeOfResults.length) {\n // Explicitly ignore any promise rejections\n Promise.allSettled(promisedIsTypeOfResults)\n /* c8 ignore next 3 */\n .catch(() => {\n // Do nothing\n });\n }\n\n return type.name;\n }\n }\n }\n\n if (promisedIsTypeOfResults.length) {\n return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => {\n for (let i = 0; i < isTypeOfResults.length; i++) {\n if (isTypeOfResults[i]) {\n return possibleTypes[i].name;\n }\n }\n });\n }\n};\n/**\n * If a resolve function is not given, then a default resolve behavior is used\n * which takes the property of the source object of the same name as the field\n * and returns it as the result, or if it's a function, returns the result\n * of calling that function while passing along args and context value.\n */\n\nexport const defaultFieldResolver = function (\n source,\n args,\n contextValue,\n info,\n) {\n // ensure source is a value for which property access is acceptable.\n if (isObjectLike(source) || typeof source === 'function') {\n const property = source[info.fieldName];\n\n if (typeof property === 'function') {\n return source[info.fieldName](args, contextValue, info);\n }\n\n return property;\n }\n};\n/**\n * This method looks up the field on the given type definition.\n * It has special casing for the three introspection fields,\n * __schema, __type and __typename. __typename is special because\n * it can always be queried as a field, even in situations where no\n * other fields are allowed, like on a Union. __schema and __type\n * could get automatically added to the query type, but that would\n * require mutating type definitions, which would cause issues.\n *\n * @internal\n */\n\nexport function getFieldDef(schema, parentType, fieldNode) {\n const fieldName = fieldNode.name.value;\n\n if (\n fieldName === SchemaMetaFieldDef.name &&\n schema.getQueryType() === parentType\n ) {\n return SchemaMetaFieldDef;\n } else if (\n fieldName === TypeMetaFieldDef.name &&\n schema.getQueryType() === parentType\n ) {\n return TypeMetaFieldDef;\n } else if (fieldName === TypeNameMetaFieldDef.name) {\n return TypeNameMetaFieldDef;\n }\n\n return parentType.getFields()[fieldName];\n}\n","import { devAssert } from './jsutils/devAssert.mjs';\nimport { isPromise } from './jsutils/isPromise.mjs';\nimport { parse } from './language/parser.mjs';\nimport { validateSchema } from './type/validate.mjs';\nimport { validate } from './validation/validate.mjs';\nimport { execute } from './execution/execute.mjs';\n/**\n * Describes the input object accepted by `graphql` and `graphqlSync`.\n *\n * These arguments describe the full parse, validate, and execute lifecycle for\n * a GraphQL request.\n * @category Request Pipeline\n */\n\n/**\n * Parses, validates, and executes a GraphQL document against a schema.\n *\n * This is the primary entry point for fulfilling GraphQL operations. Use this\n * when you want a single-call request lifecycle that returns a promise in all\n * cases.\n *\n * More sophisticated GraphQL servers, such as those which persist queries, may\n * wish to separate the validation and execution phases to a static-time tooling\n * step and a server runtime step.\n * @param args - Request execution arguments, including schema and source.\n * @returns A promise that resolves to an execution result or validation errors.\n * @example\n * ```ts\n * // Execute a complete asynchronous request with variables.\n * import { graphql, buildSchema } from 'graphql';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting(name: String!): String\n * }\n * `);\n *\n * const result = await graphql({\n * schema,\n * source: 'query SayHello($name: String!) { greeting(name: $name) }',\n * rootValue: {\n * greeting: ({ name }) => `Hello, ${name}!`,\n * },\n * variableValues: { name: 'Ada' },\n * operationName: 'SayHello',\n * });\n *\n * result; // => { data: { greeting: 'Hello, Ada!' } }\n * ```\n * @example\n * ```ts\n * // This variant supplies context plus custom field and type resolvers.\n * import { graphql, buildSchema } from 'graphql';\n *\n * const schema = buildSchema(`\n * interface Named {\n * name: String!\n * }\n *\n * type User implements Named {\n * name: String!\n * }\n *\n * type Query {\n * viewer: Named\n * }\n * `);\n *\n * const result = await graphql({\n * schema,\n * source: '{ viewer { __typename name } }',\n * rootValue: { viewer: { kind: 'user', name: 'Ada' } },\n * contextValue: { locale: 'en' },\n * fieldResolver: (source, _args, context, info) => {\n * context.locale; // => 'en'\n * return source[info.fieldName];\n * },\n * typeResolver: (value) => {\n * return value.kind === 'user' ? 'User' : undefined;\n * },\n * });\n *\n * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } }\n * ```\n * @category Request Pipeline\n */\nexport function graphql(args) {\n // Always return a Promise for a consistent API.\n return new Promise((resolve) => resolve(graphqlImpl(args)));\n}\n/**\n * Parses, validates, and executes a GraphQL document synchronously.\n *\n * This function guarantees that execution completes synchronously, or throws an\n * error, assuming that all field resolvers are also synchronous. It throws when\n * any resolver returns a promise.\n * @param args - Request execution arguments, including schema and source.\n * @returns Completed execution output, or request errors if parsing or\n * validation fails.\n * @example\n * ```ts\n * // Execute a complete synchronous request with variables.\n * import { graphqlSync, buildSchema } from 'graphql';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting(name: String!): String\n * }\n * `);\n *\n * const result = graphqlSync({\n * schema,\n * source: 'query SayHello($name: String!) { greeting(name: $name) }',\n * rootValue: {\n * greeting: ({ name }) => `Hello, ${name}!`,\n * },\n * variableValues: { name: 'Ada' },\n * operationName: 'SayHello',\n * });\n *\n * result; // => { data: { greeting: 'Hello, Ada!' } }\n * ```\n * @example\n * ```ts\n * // This variant uses a synchronous custom field resolver and context.\n * import { graphqlSync, buildSchema } from 'graphql';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n *\n * const result = graphqlSync({\n * schema,\n * source: '{ greeting }',\n * fieldResolver: (_source, _args, contextValue) => {\n * return contextValue.defaultGreeting;\n * },\n * contextValue: { defaultGreeting: 'Hello' },\n * });\n *\n * result; // => { data: { greeting: 'Hello' } }\n * ```\n * @category Request Pipeline\n */\n\nexport function graphqlSync(args) {\n const result = graphqlImpl(args); // Assert that the execution was synchronous.\n\n if (isPromise(result)) {\n throw new Error('GraphQL execution failed to complete synchronously.');\n }\n\n return result;\n}\n\nfunction graphqlImpl(args) {\n // Temporary for v15 to v16 migration. Remove in v17\n arguments.length < 2 ||\n devAssert(\n false,\n 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.',\n );\n const {\n schema,\n source,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n } = args; // Validate Schema\n\n const schemaValidationErrors = validateSchema(schema);\n\n if (schemaValidationErrors.length > 0) {\n return {\n errors: schemaValidationErrors,\n };\n } // Parse\n\n let document;\n\n try {\n document = parse(source);\n } catch (syntaxError) {\n return {\n errors: [syntaxError],\n };\n } // Validate\n\n const validationErrors = validate(schema, document);\n\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n };\n } // Execute\n\n return execute({\n schema,\n document,\n rootValue,\n contextValue,\n variableValues,\n operationName,\n fieldResolver,\n typeResolver,\n });\n}\n","/** @category Schema Construction */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { inspect } from '../jsutils/inspect.mjs';\nimport { invariant } from '../jsutils/invariant.mjs';\nimport { keyMap } from '../jsutils/keyMap.mjs';\nimport { mapValue } from '../jsutils/mapValue.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport {\n isTypeDefinitionNode,\n isTypeExtensionNode,\n} from '../language/predicates.mjs';\nimport {\n GraphQLEnumType,\n GraphQLInputObjectType,\n GraphQLInterfaceType,\n GraphQLList,\n GraphQLNonNull,\n GraphQLObjectType,\n GraphQLScalarType,\n GraphQLUnionType,\n isEnumType,\n isInputObjectType,\n isInterfaceType,\n isListType,\n isNonNullType,\n isObjectType,\n isScalarType,\n isUnionType,\n} from '../type/definition.mjs';\nimport {\n GraphQLDeprecatedDirective,\n GraphQLDirective,\n GraphQLOneOfDirective,\n GraphQLSpecifiedByDirective,\n} from '../type/directives.mjs';\nimport {\n introspectionTypes,\n isIntrospectionType,\n} from '../type/introspection.mjs';\nimport {\n isSpecifiedScalarType,\n specifiedScalarTypes,\n} from '../type/scalars.mjs';\nimport { assertSchema, GraphQLSchema } from '../type/schema.mjs';\nimport { assertValidSDLExtension } from '../validation/validate.mjs';\nimport { getDirectiveValues } from '../execution/values.mjs';\nimport { valueFromAST } from './valueFromAST.mjs';\n\n/**\n * Produces a new schema given an existing schema and a document which may\n * contain GraphQL type extensions and definitions. The original schema will\n * remain unaltered.\n *\n * Because a schema represents a graph of references, a schema cannot be\n * extended without effectively making an entire copy. We do not know until it's\n * too late if subgraphs remain unchanged.\n *\n * This algorithm copies the provided schema, applying extensions while\n * producing the copy. The original schema remains unaltered.\n * @param schema - GraphQL schema to use.\n * @param documentAST - The parsed GraphQL document AST.\n * @param options - Optional configuration for this operation.\n * @returns A new schema with the extensions and definitions applied.\n * @example\n * ```ts\n * // Extend a schema with new fields and types.\n * import { parse } from 'graphql/language';\n * import { buildSchema, extendSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const extensionAST = parse(`\n * extend type Query {\n * farewell: String\n * }\n *\n * type Review {\n * body: String\n * }\n * `);\n *\n * const extendedSchema = extendSchema(schema, extensionAST);\n *\n * schema.getType('Review'); // => undefined\n * extendedSchema.getType('Review')?.name; // => 'Review'\n * Object.keys(extendedSchema.getQueryType().getFields()); // => ['greeting', 'farewell']\n * ```\n * @example\n * ```ts\n * // This variant bypasses validation for an otherwise invalid extension.\n * import { parse } from 'graphql/language';\n * import { buildSchema, extendSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(`\n * type Query {\n * greeting: String\n * }\n * `);\n * const invalidExtension = parse(`\n * extend type Missing {\n * field: String\n * }\n * `);\n *\n * extendSchema(schema, invalidExtension); // throws an error\n * extendSchema(schema, invalidExtension, {\n * assumeValid: true,\n * assumeValidSDL: true,\n * }); // does not throw\n * ```\n */\nexport function extendSchema(schema, documentAST, options) {\n assertSchema(schema);\n (documentAST != null && documentAST.kind === Kind.DOCUMENT) ||\n devAssert(false, 'Must provide valid Document AST.');\n\n if (\n (options === null || options === void 0 ? void 0 : options.assumeValid) !==\n true &&\n (options === null || options === void 0\n ? void 0\n : options.assumeValidSDL) !== true\n ) {\n assertValidSDLExtension(documentAST, schema);\n }\n\n const schemaConfig = schema.toConfig();\n const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options);\n return schemaConfig === extendedConfig\n ? schema\n : new GraphQLSchema(extendedConfig);\n}\n/** @internal */\n\nexport function extendSchemaImpl(schemaConfig, documentAST, options) {\n var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid;\n\n // Collect the type definitions and extensions found in the document.\n const typeDefs = [];\n const typeExtensionsMap = Object.create(null);\n const directiveExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can\n // have the same name. For example, a type named \"skip\".\n\n const directiveDefs = [];\n let schemaDef; // Schema extensions are collected which may add additional operation types.\n\n const schemaExtensions = [];\n\n for (const def of documentAST.definitions) {\n if (def.kind === Kind.SCHEMA_DEFINITION) {\n schemaDef = def;\n } else if (def.kind === Kind.SCHEMA_EXTENSION) {\n schemaExtensions.push(def);\n } else if (isTypeDefinitionNode(def)) {\n typeDefs.push(def);\n } else if (isTypeExtensionNode(def)) {\n const extendedTypeName = def.name.value;\n const existingTypeExtensions = typeExtensionsMap[extendedTypeName];\n typeExtensionsMap[extendedTypeName] = existingTypeExtensions\n ? existingTypeExtensions.concat([def])\n : [def];\n } else if (def.kind === Kind.DIRECTIVE_DEFINITION) {\n directiveDefs.push(def);\n } else if (def.kind === Kind.DIRECTIVE_EXTENSION) {\n const extendedDirectiveName = def.name.value;\n const existingDirectiveExtensions =\n directiveExtensionsMap[extendedDirectiveName];\n directiveExtensionsMap[extendedDirectiveName] =\n existingDirectiveExtensions\n ? existingDirectiveExtensions.concat([def])\n : [def];\n }\n } // If this document contains no new types, extensions, or directives then\n // return the same unmodified GraphQLSchema instance.\n\n if (\n Object.keys(typeExtensionsMap).length === 0 &&\n typeDefs.length === 0 &&\n Object.keys(directiveExtensionsMap).length === 0 &&\n directiveDefs.length === 0 &&\n schemaExtensions.length === 0 &&\n schemaDef == null\n ) {\n return schemaConfig;\n }\n\n const typeMap = Object.create(null);\n\n for (const existingType of schemaConfig.types) {\n typeMap[existingType.name] = extendNamedType(existingType);\n }\n\n for (const typeNode of typeDefs) {\n var _stdTypeMap$name;\n\n const name = typeNode.name.value;\n typeMap[name] =\n (_stdTypeMap$name = stdTypeMap[name]) !== null &&\n _stdTypeMap$name !== void 0\n ? _stdTypeMap$name\n : buildType(typeNode);\n }\n\n const directiveMap = Object.create(null);\n\n for (const existingDirective of schemaConfig.directives) {\n directiveMap[existingDirective.name] = extendDirective(existingDirective);\n }\n\n const operationTypes = {\n // Get the extended root operation types.\n query: schemaConfig.query && replaceNamedType(schemaConfig.query),\n mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation),\n subscription:\n schemaConfig.subscription && replaceNamedType(schemaConfig.subscription),\n // Then, incorporate schema definition and all schema extensions.\n ...(schemaDef && getOperationTypes([schemaDef])),\n ...getOperationTypes(schemaExtensions),\n }; // Then produce and return a Schema config with these types.\n\n const directives = Object.values(directiveMap); // will be `Array<GraphQLDirective>`\n\n return {\n description:\n (_schemaDef = schemaDef) === null || _schemaDef === void 0\n ? void 0\n : (_schemaDef$descriptio = _schemaDef.description) === null ||\n _schemaDef$descriptio === void 0\n ? void 0\n : _schemaDef$descriptio.value,\n ...operationTypes,\n types: Object.values(typeMap),\n directives: [\n ...directives.map(replaceDirective),\n ...directiveDefs.map(buildDirective),\n ],\n extensions: Object.create(null),\n astNode:\n (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0\n ? _schemaDef2\n : schemaConfig.astNode,\n extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions),\n assumeValid:\n (_options$assumeValid =\n options === null || options === void 0\n ? void 0\n : options.assumeValid) !== null && _options$assumeValid !== void 0\n ? _options$assumeValid\n : false,\n }; // Below are functions used for producing this schema that have closed over\n // this scope and have access to the schema, cache, and newly defined types.\n\n function replaceType(type) {\n if (isListType(type)) {\n // @ts-expect-error\n return new GraphQLList(replaceType(type.ofType));\n }\n\n if (isNonNullType(type)) {\n // @ts-expect-error\n return new GraphQLNonNull(replaceType(type.ofType));\n } // @ts-expect-error FIXME\n\n return replaceNamedType(type);\n }\n\n function replaceNamedType(type) {\n // Note: While this could make early assertions to get the correctly\n // typed values, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n return typeMap[type.name];\n }\n\n function replaceDirective(directive) {\n const config = directive.toConfig();\n return new GraphQLDirective({\n ...config,\n args: mapValue(config.args, extendArg),\n });\n }\n\n function extendNamedType(type) {\n if (isIntrospectionType(type) || isSpecifiedScalarType(type)) {\n // Builtin types are not extended.\n return type;\n }\n\n if (isScalarType(type)) {\n return extendScalarType(type);\n }\n\n if (isObjectType(type)) {\n return extendObjectType(type);\n }\n\n if (isInterfaceType(type)) {\n return extendInterfaceType(type);\n }\n\n if (isUnionType(type)) {\n return extendUnionType(type);\n }\n\n if (isEnumType(type)) {\n return extendEnumType(type);\n }\n\n if (isInputObjectType(type)) {\n return extendInputObjectType(type);\n }\n /* c8 ignore next 3 */\n // Not reachable, all possible type definition nodes have been considered.\n\n false || invariant(false, 'Unexpected type: ' + inspect(type));\n }\n\n function extendInputObjectType(type) {\n var _typeExtensionsMap$co;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co !== void 0\n ? _typeExtensionsMap$co\n : [];\n return new GraphQLInputObjectType({\n ...config,\n fields: () => ({\n ...mapValue(config.fields, (field) => ({\n ...field,\n type: replaceType(field.type),\n })),\n ...buildInputFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendEnumType(type) {\n var _typeExtensionsMap$ty;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null &&\n _typeExtensionsMap$ty !== void 0\n ? _typeExtensionsMap$ty\n : [];\n return new GraphQLEnumType({\n ...config,\n values: { ...config.values, ...buildEnumValueMap(extensions) },\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendScalarType(type) {\n var _typeExtensionsMap$co2;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co2 !== void 0\n ? _typeExtensionsMap$co2\n : [];\n let specifiedByURL = config.specifiedByURL;\n\n for (const extensionNode of extensions) {\n var _getSpecifiedByURL;\n\n specifiedByURL =\n (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null &&\n _getSpecifiedByURL !== void 0\n ? _getSpecifiedByURL\n : specifiedByURL;\n }\n\n return new GraphQLScalarType({\n ...config,\n specifiedByURL,\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendObjectType(type) {\n var _typeExtensionsMap$co3;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co3 !== void 0\n ? _typeExtensionsMap$co3\n : [];\n return new GraphQLObjectType({\n ...config,\n interfaces: () => [\n ...type.getInterfaces().map(replaceNamedType),\n ...buildInterfaces(extensions),\n ],\n fields: () => ({\n ...mapValue(config.fields, extendField),\n ...buildFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendInterfaceType(type) {\n var _typeExtensionsMap$co4;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co4 !== void 0\n ? _typeExtensionsMap$co4\n : [];\n return new GraphQLInterfaceType({\n ...config,\n interfaces: () => [\n ...type.getInterfaces().map(replaceNamedType),\n ...buildInterfaces(extensions),\n ],\n fields: () => ({\n ...mapValue(config.fields, extendField),\n ...buildFieldMap(extensions),\n }),\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendUnionType(type) {\n var _typeExtensionsMap$co5;\n\n const config = type.toConfig();\n const extensions =\n (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null &&\n _typeExtensionsMap$co5 !== void 0\n ? _typeExtensionsMap$co5\n : [];\n return new GraphQLUnionType({\n ...config,\n types: () => [\n ...type.getTypes().map(replaceNamedType),\n ...buildUnionTypes(extensions),\n ],\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function extendField(field) {\n return {\n ...field,\n type: replaceType(field.type),\n args: field.args && mapValue(field.args, extendArg),\n };\n }\n\n function extendArg(arg) {\n return { ...arg, type: replaceType(arg.type) };\n }\n\n function getOperationTypes(nodes) {\n const opTypes = {};\n\n for (const node of nodes) {\n var _node$operationTypes;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const operationTypesNodes =\n /* c8 ignore next */\n (_node$operationTypes = node.operationTypes) !== null &&\n _node$operationTypes !== void 0\n ? _node$operationTypes\n : [];\n\n for (const operationType of operationTypesNodes) {\n // Note: While this could make early assertions to get the correctly\n // typed values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n opTypes[operationType.operation] = getNamedType(operationType.type);\n }\n }\n\n return opTypes;\n }\n\n function extendDirective(directive) {\n var _directiveExtensionsM, _config$deprecationRe;\n\n const config = directive.toConfig();\n const extensions =\n (_directiveExtensionsM = directiveExtensionsMap[config.name]) !== null &&\n _directiveExtensionsM !== void 0\n ? _directiveExtensionsM\n : [];\n const deprecationReason =\n (_config$deprecationRe = config.deprecationReason) !== null &&\n _config$deprecationRe !== void 0\n ? _config$deprecationRe\n : extensions\n .map((ext) => getDeprecationReason(ext))\n .find((reason) => reason != null);\n return new GraphQLDirective({\n ...config,\n deprecationReason,\n extensionASTNodes: config.extensionASTNodes.concat(extensions),\n });\n }\n\n function getNamedType(node) {\n var _stdTypeMap$name2;\n\n const name = node.name.value;\n const type =\n (_stdTypeMap$name2 = stdTypeMap[name]) !== null &&\n _stdTypeMap$name2 !== void 0\n ? _stdTypeMap$name2\n : typeMap[name];\n\n if (type === undefined) {\n throw new Error(`Unknown type: \"${name}\".`);\n }\n\n return type;\n }\n\n function getWrappedType(node) {\n if (node.kind === Kind.LIST_TYPE) {\n return new GraphQLList(getWrappedType(node.type));\n }\n\n if (node.kind === Kind.NON_NULL_TYPE) {\n return new GraphQLNonNull(getWrappedType(node.type));\n }\n\n return getNamedType(node);\n }\n\n function buildDirective(node) {\n var _directiveExtensionsM2, _getDeprecationReason, _node$description;\n\n const extensions =\n (_directiveExtensionsM2 = directiveExtensionsMap[node.name.value]) !==\n null && _directiveExtensionsM2 !== void 0\n ? _directiveExtensionsM2\n : [];\n const deprecationReason =\n (_getDeprecationReason = getDeprecationReason(node)) !== null &&\n _getDeprecationReason !== void 0\n ? _getDeprecationReason\n : extensions\n .map((ext) => getDeprecationReason(ext))\n .find((reason) => reason != null);\n return new GraphQLDirective({\n name: node.name.value,\n description:\n (_node$description = node.description) === null ||\n _node$description === void 0\n ? void 0\n : _node$description.value,\n // @ts-expect-error\n locations: node.locations.map(({ value }) => value),\n isRepeatable: node.repeatable,\n args: buildArgumentMap(node.arguments),\n deprecationReason,\n astNode: node,\n extensionASTNodes: extensions,\n });\n }\n\n function buildFieldMap(nodes) {\n const fieldConfigMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$fields;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const nodeFields =\n /* c8 ignore next */\n (_node$fields = node.fields) !== null && _node$fields !== void 0\n ? _node$fields\n : [];\n\n for (const field of nodeFields) {\n var _field$description;\n\n fieldConfigMap[field.name.value] = {\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n type: getWrappedType(field.type),\n description:\n (_field$description = field.description) === null ||\n _field$description === void 0\n ? void 0\n : _field$description.value,\n args: buildArgumentMap(field.arguments),\n deprecationReason: getDeprecationReason(field),\n astNode: field,\n };\n }\n }\n\n return fieldConfigMap;\n }\n\n function buildArgumentMap(args) {\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const argsNodes =\n /* c8 ignore next */\n args !== null && args !== void 0 ? args : [];\n const argConfigMap = Object.create(null);\n\n for (const arg of argsNodes) {\n var _arg$description;\n\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n const type = getWrappedType(arg.type);\n argConfigMap[arg.name.value] = {\n type,\n description:\n (_arg$description = arg.description) === null ||\n _arg$description === void 0\n ? void 0\n : _arg$description.value,\n defaultValue: valueFromAST(arg.defaultValue, type),\n deprecationReason: getDeprecationReason(arg),\n astNode: arg,\n };\n }\n\n return argConfigMap;\n }\n\n function buildInputFieldMap(nodes) {\n const inputFieldMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$fields2;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const fieldsNodes =\n /* c8 ignore next */\n (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0\n ? _node$fields2\n : [];\n\n for (const field of fieldsNodes) {\n var _field$description2;\n\n // Note: While this could make assertions to get the correctly typed\n // value, that would throw immediately while type system validation\n // with validateSchema() will produce more actionable results.\n const type = getWrappedType(field.type);\n inputFieldMap[field.name.value] = {\n type,\n description:\n (_field$description2 = field.description) === null ||\n _field$description2 === void 0\n ? void 0\n : _field$description2.value,\n defaultValue: valueFromAST(field.defaultValue, type),\n deprecationReason: getDeprecationReason(field),\n astNode: field,\n };\n }\n }\n\n return inputFieldMap;\n }\n\n function buildEnumValueMap(nodes) {\n const enumValueMap = Object.create(null);\n\n for (const node of nodes) {\n var _node$values;\n\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n const valuesNodes =\n /* c8 ignore next */\n (_node$values = node.values) !== null && _node$values !== void 0\n ? _node$values\n : [];\n\n for (const value of valuesNodes) {\n var _value$description;\n\n enumValueMap[value.name.value] = {\n description:\n (_value$description = value.description) === null ||\n _value$description === void 0\n ? void 0\n : _value$description.value,\n deprecationReason: getDeprecationReason(value),\n astNode: value,\n };\n }\n }\n\n return enumValueMap;\n }\n\n function buildInterfaces(nodes) {\n // Note: While this could make assertions to get the correctly typed\n // values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n return nodes.flatMap(\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n (node) => {\n var _node$interfaces$map, _node$interfaces;\n\n return (\n /* c8 ignore next */\n (_node$interfaces$map =\n (_node$interfaces = node.interfaces) === null ||\n _node$interfaces === void 0\n ? void 0\n : _node$interfaces.map(getNamedType)) !== null &&\n _node$interfaces$map !== void 0\n ? _node$interfaces$map\n : []\n );\n },\n );\n }\n\n function buildUnionTypes(nodes) {\n // Note: While this could make assertions to get the correctly typed\n // values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n // @ts-expect-error\n return nodes.flatMap(\n // FIXME: https://github.com/graphql/graphql-js/issues/2203\n (node) => {\n var _node$types$map, _node$types;\n\n return (\n /* c8 ignore next */\n (_node$types$map =\n (_node$types = node.types) === null || _node$types === void 0\n ? void 0\n : _node$types.map(getNamedType)) !== null &&\n _node$types$map !== void 0\n ? _node$types$map\n : []\n );\n },\n );\n }\n\n function buildType(astNode) {\n var _typeExtensionsMap$na;\n\n const name = astNode.name.value;\n const extensionASTNodes =\n (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null &&\n _typeExtensionsMap$na !== void 0\n ? _typeExtensionsMap$na\n : [];\n\n switch (astNode.kind) {\n case Kind.OBJECT_TYPE_DEFINITION: {\n var _astNode$description;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLObjectType({\n name,\n description:\n (_astNode$description = astNode.description) === null ||\n _astNode$description === void 0\n ? void 0\n : _astNode$description.value,\n interfaces: () => buildInterfaces(allNodes),\n fields: () => buildFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.INTERFACE_TYPE_DEFINITION: {\n var _astNode$description2;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLInterfaceType({\n name,\n description:\n (_astNode$description2 = astNode.description) === null ||\n _astNode$description2 === void 0\n ? void 0\n : _astNode$description2.value,\n interfaces: () => buildInterfaces(allNodes),\n fields: () => buildFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.ENUM_TYPE_DEFINITION: {\n var _astNode$description3;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLEnumType({\n name,\n description:\n (_astNode$description3 = astNode.description) === null ||\n _astNode$description3 === void 0\n ? void 0\n : _astNode$description3.value,\n values: buildEnumValueMap(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.UNION_TYPE_DEFINITION: {\n var _astNode$description4;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLUnionType({\n name,\n description:\n (_astNode$description4 = astNode.description) === null ||\n _astNode$description4 === void 0\n ? void 0\n : _astNode$description4.value,\n types: () => buildUnionTypes(allNodes),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.SCALAR_TYPE_DEFINITION: {\n var _astNode$description5;\n\n return new GraphQLScalarType({\n name,\n description:\n (_astNode$description5 = astNode.description) === null ||\n _astNode$description5 === void 0\n ? void 0\n : _astNode$description5.value,\n specifiedByURL: getSpecifiedByURL(astNode),\n astNode,\n extensionASTNodes,\n });\n }\n\n case Kind.INPUT_OBJECT_TYPE_DEFINITION: {\n var _astNode$description6;\n\n const allNodes = [astNode, ...extensionASTNodes];\n return new GraphQLInputObjectType({\n name,\n description:\n (_astNode$description6 = astNode.description) === null ||\n _astNode$description6 === void 0\n ? void 0\n : _astNode$description6.value,\n fields: () => buildInputFieldMap(allNodes),\n astNode,\n extensionASTNodes,\n isOneOf: isOneOf(astNode),\n });\n }\n }\n }\n}\nconst stdTypeMap = keyMap(\n [...specifiedScalarTypes, ...introspectionTypes],\n (type) => type.name,\n);\n/**\n * Given a field or enum value node, returns the string value for the\n * deprecation reason.\n *\n * @internal\n */\n\nfunction getDeprecationReason(node) {\n const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues`\n\n return deprecated === null || deprecated === void 0\n ? void 0\n : deprecated.reason;\n}\n/**\n * Given a scalar node, returns the string value for the specifiedByURL.\n *\n * @internal\n */\n\nfunction getSpecifiedByURL(node) {\n const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues`\n\n return specifiedBy === null || specifiedBy === void 0\n ? void 0\n : specifiedBy.url;\n}\n/**\n * Given an input object node, returns if the node should be OneOf.\n *\n * @internal\n */\n\nfunction isOneOf(node) {\n return Boolean(getDirectiveValues(GraphQLOneOfDirective, node));\n}\n","/** @category Schema Construction */\nimport { devAssert } from '../jsutils/devAssert.mjs';\nimport { Kind } from '../language/kinds.mjs';\nimport { parse } from '../language/parser.mjs';\nimport { specifiedDirectives } from '../type/directives.mjs';\nimport { GraphQLSchema } from '../type/schema.mjs';\nimport { assertValidSDL } from '../validation/validate.mjs';\nimport { extendSchemaImpl } from './extendSchema.mjs';\n/** Options used when building a schema from SDL or a parsed SDL document. */\n\n/**\n * Builds a GraphQLSchema from a parsed schema definition language document.\n *\n * If no schema definition is provided, then it will look for types named Query,\n * Mutation and Subscription.\n *\n * The resulting schema has no resolver functions, so execution will use the\n * default field resolver.\n * @param documentAST - The parsed GraphQL document AST.\n * @param options - Optional configuration for this operation.\n * @returns The schema built from the provided SDL document.\n * @example\n * ```ts\n * // Build a schema from a valid parsed SDL document.\n * import { parse } from 'graphql/language';\n * import { buildASTSchema } from 'graphql/utilities';\n *\n * const document = parse('type Query { hello: String }');\n * const schema = buildASTSchema(document);\n *\n * schema.getQueryType().name; // => 'Query'\n * ```\n * @example\n * ```ts\n * // This variant uses validation options when the SDL references unknown types.\n * import { parse } from 'graphql/language';\n * import { buildASTSchema } from 'graphql/utilities';\n *\n * const document = parse('type Query { broken: MissingType }');\n *\n * buildASTSchema(document); // throws an error\n * buildASTSchema(document, {\n * assumeValid: true,\n * assumeValidSDL: true,\n * }); // does not throw\n * ```\n */\nexport function buildASTSchema(documentAST, options) {\n (documentAST != null && documentAST.kind === Kind.DOCUMENT) ||\n devAssert(false, 'Must provide valid Document AST.');\n\n if (\n (options === null || options === void 0 ? void 0 : options.assumeValid) !==\n true &&\n (options === null || options === void 0\n ? void 0\n : options.assumeValidSDL) !== true\n ) {\n assertValidSDL(documentAST);\n }\n\n const emptySchemaConfig = {\n description: undefined,\n types: [],\n directives: [],\n extensions: Object.create(null),\n extensionASTNodes: [],\n assumeValid: false,\n };\n const config = extendSchemaImpl(emptySchemaConfig, documentAST, options);\n\n if (config.astNode == null) {\n for (const type of config.types) {\n switch (type.name) {\n // Note: While this could make early assertions to get the correctly\n // typed values below, that would throw immediately while type system\n // validation with validateSchema() will produce more actionable results.\n case 'Query':\n // @ts-expect-error validated in `validateSchema`\n config.query = type;\n break;\n\n case 'Mutation':\n // @ts-expect-error validated in `validateSchema`\n config.mutation = type;\n break;\n\n case 'Subscription':\n // @ts-expect-error validated in `validateSchema`\n config.subscription = type;\n break;\n }\n }\n }\n\n const directives = [\n ...config.directives, // If specified directives were not explicitly declared, add them.\n ...specifiedDirectives.filter((stdDirective) =>\n config.directives.every(\n (directive) => directive.name !== stdDirective.name,\n ),\n ),\n ];\n return new GraphQLSchema({ ...config, directives });\n}\n/**\n * Builds a GraphQLSchema directly from a schema definition language source.\n * @param source - The GraphQL source text or source object.\n * @param options - Optional configuration for this operation.\n * @returns The schema built from the provided SDL document.\n * @example\n * ```ts\n * // Build a schema from SDL source using the default options.\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema('type Query { hello: String }');\n *\n * schema.getQueryType().name; // => 'Query'\n * ```\n * @example\n * ```ts\n * // This variant enables parser options and omits source locations.\n * import { buildSchema } from 'graphql/utilities';\n *\n * const schema = buildSchema(\n * 'directive @tag on FIELD_DEFINITION\\n' +\n * 'directive @compose @tag on FIELD_DEFINITION',\n * {\n * experimentalDirectivesOnDirectiveDefinitions: true,\n * noLocation: true,\n * },\n * );\n *\n * const directive = schema.getDirective('compose');\n *\n * directive.name; // => 'compose'\n * directive.astNode.loc; // => undefined\n * ```\n */\n\nexport function buildSchema(source, options) {\n const document = parse(source, {\n noLocation:\n options === null || options === void 0 ? void 0 : options.noLocation,\n allowLegacyFragmentVariables:\n options === null || options === void 0\n ? void 0\n : options.allowLegacyFragmentVariables,\n experimentalDirectivesOnDirectiveDefinitions:\n options === null || options === void 0\n ? void 0\n : options.experimentalDirectivesOnDirectiveDefinitions,\n });\n return buildASTSchema(document, {\n assumeValidSDL:\n options === null || options === void 0 ? void 0 : options.assumeValidSDL,\n assumeValid:\n options === null || options === void 0 ? void 0 : options.assumeValid,\n });\n}\n"],"mappings":";AAAA,SAAS,kBAAkB;AEA3B,SAAS,mBAAmB;;;AuCCrB,SAAS,UAAU,WAAW,SAAS;AAC5C,QAAM,mBAAmB,QAAQ,SAAS;AAE1C,MAAI,CAAC,kBAAkB;AACrB,UAAM,IAAI,MAAM,OAAO;AAAA,EACzB;AACF;;;ACDO,SAAS,UAAU,OAAO;AAC/B,SACE,QAAQ,UAAU,QAAQ,UAAU,SAAS,SAAS,MAAM,UAC5D;AAEJ;;;ACLO,SAAS,aAAa,OAAO;AAClC,SAAO,OAAO,SAAS,YAAY,UAAU;AAC/C;;;ACPO,SAAS,UAAU,WAAW,SAAS;AAC5C,QAAM,mBAAmB,QAAQ,SAAS;AAE1C,MAAI,CAAC,kBAAkB;AACrB,UAAM,IAAI;AAAA,MACR,WAAW,OAAO,UAAU;AAAA,IAC9B;AAAA,EACF;AACF;;;ACPA,IAAM,aAAa;AAmBZ,SAAS,YAAY,QAAQ,UAAU;AAC5C,MAAI,gBAAgB;AACpB,MAAI,OAAO;AAEX,aAAW,SAAS,OAAO,KAAK,SAAS,UAAU,GAAG;AACpD,WAAO,MAAM,UAAU,YAAY,UAAU,KAAK;AAElD,Q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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA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K,eAAe,KAAK;AAE/B,UAAM,mBAAmB,SAAS,SAAS,KAAK,QAAQ;AACxD,aAAS,WAAW,OAClB,OACA,QACA,SACAD,QACAD,UACkB;AAClB,YAAM,gBAAgB,yBAAyB,IAAIC,QAAOD,OAAM,KAAK;AAErE,YAAM,kBACJ,cAAc,SAAS,IAAI,8BAA8B,SAAS,cAAc,CAAC,CAAC,IAAI;AAExF,YAAM,iBAAiB,OAAO,QAAQ,iBAAiBC,QAAOD,KAAI;AAClE,YAAM,wBAAwB,IAAI,OAAO,QAAQ,SAASC,QAAOD,KAAI;IACvE;AAEA,UAAM,MAAoB,EAAE,KAAK,OAAO,UAAU,SAAS,SAAS;AACpE,kBAAc,GAAG;AACjB,gBAAY,GAAG;AACf,gBAAY,GAAG;AACf,iBAAa,GAAG;AAChB,gBAAY,GAAG;AACf,mBAAe,GAAG;AAClB,kBAAc,GAAG;AACjB,8BAA0B,GAAG;AAC7B,yBAAqB,GAAG;AACxB,uBAAmB,GAAG;AACtB,mBAAe,GAAG;AAClB,mBAAe,GAAG;AAClB,iBAAa,GAAG;AAChB,kBAAc,GAAG;AACjB,iBAAa,GAAG;AAChB,oBAAgB,GAAG;AACnB,eAAW,GAAG;AACd,gBAAY,GAAG;AACf,eAAW,GAAG;AACd,kBAAc,GAAG;EACnB;EACA,KAAK,OAAc,SAAuB;AACxC,iBAAa,OAAO,OAAO;EAC7B;AACF;AAEA,IAAO,gBAAQ;","names":["OperationTypeNode","DirectiveLocation","Kind","indent","TokenKind","instanceOf","isDigit","enumValue","TypeKind","hasOwnProperty","collectSubfields","getFieldDef","collectSubfields","syntaxError","getNamedType","randomBytes","repo","owner","ownerLogin","c","adjustRepoOpenIssues","head","ok","lookupUserByLogin","findPull","adjustPrReviewCommentCount","sortComments","parseCommentSort","findIssueByNumber","insertIssueEvent","getOrCreateLabel","cmp","m","r","blob","repoUrl","saved","notFound","teamsForOrg","listOrgMembersDeduped","orgRoleForUser","getOrgByLogin","s","assertOrgAdmin","findCommitInRepo","oauthApp","baseUrl"]}