diff --git a/.gitattributes b/.gitattributes index 5a25dd4261782f65110556c12862cd755d6c76f7..e3d63f912db6c517355a9a1b6ada0f9e32d91ba5 100644 --- a/.gitattributes +++ b/.gitattributes @@ -40,3 +40,14 @@ node_modules/bare-url/prebuilds/win32-arm64/bare-url.bare filter=lfs diff=lfs me node_modules/bare-url/prebuilds/win32-x64/bare-url.bare filter=lfs diff=lfs merge=lfs -text node_modules/better-sqlite3/build/Release/better_sqlite3.node filter=lfs diff=lfs merge=lfs -text node_modules/exif-parser/test/starfish.jpg filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/hairstreak.jpg filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/lenna.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/nburling-public.gif filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png filter=lfs diff=lfs merge=lfs -text +node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif filter=lfs diff=lfs merge=lfs -text diff --git a/node_modules/get-tsconfig/LICENSE b/node_modules/get-tsconfig/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..51e4fd8646a1cfd17e90dd3b633f24eb8dbb01ac --- /dev/null +++ b/node_modules/get-tsconfig/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Hiroki Osame + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/get-tsconfig/README.md b/node_modules/get-tsconfig/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6161a8a88277091441386383570977319bddd7d8 --- /dev/null +++ b/node_modules/get-tsconfig/README.md @@ -0,0 +1,295 @@ +

+ +

+

+ get-tsconfig +
+ +

+ +Find and parse `tsconfig.json` files. + +## Features +- Tiny! `9 kB` Minified + Gzipped +- Tested against TypeScript for correctness +- Resolves [`extends`](https://www.typescriptlang.org/tsconfig/#extends) +- Fully typed `tsconfig.json` +- Validates and throws parsing errors + +
+ +

+ + +

+

Already a sponsor? Join the discussion in the Development repo!

+ +## Install + +```bash +npm install get-tsconfig +``` + +## Why? + +TypeScript tooling (bundlers, linters, loaders, test runners) needs to read `tsconfig.json` to understand compiler options, path aliases, and file inclusion rules. But TypeScript's own config parser is buried inside the compiler and requires TypeScript as a dependency. + +`get-tsconfig` provides the same functionality as a lightweight, standalone library — tested against TypeScript for correctness. + +## Quick start + +```ts +import { getTsconfig, isFileIncluded, resolvePathAlias } from 'get-tsconfig' + +// Find and parse the nearest tsconfig.json +const tsconfig = getTsconfig() + +// To resolve path aliases (compilerOptions.paths): +if (tsconfig) { + const resolved = resolvePathAlias(tsconfig, '@/utils/helper') + // → ['/project/src/utils/helper'] +} + +// To check if a file belongs to this tsconfig: +if (tsconfig && isFileIncluded(tsconfig, '/project/src/index.ts')) { + // Use tsconfig.config.compilerOptions for transformation +} +``` + +## Finding & reading tsconfig + +These functions find, read, and parse tsconfig files from the filesystem. All return a `TsconfigResult`: + +```ts +type TsconfigResult = { + path: string + config: Config + sources: string[] +} +``` + +- **path**: absolute path to the tsconfig file +- **config**: the fully resolved config (extends merged, options normalized) +- **sources**: paths of all tsconfig files that contributed to the resolved config via [`extends`](https://www.typescriptlang.org/tsconfig/#extends). When there are no `extends`, this is just `[path]`. Since `extends` can be an array, the order does not imply a linear chain. + +### getTsconfig(searchPath?, options?) + +Searches for a tsconfig file and parses it. If you already know the path, use [`readTsconfig`](#readtsconfigtsconfigpath-options) instead. Returns `undefined` if not found. + +#### searchPath +Type: `string` + +Default: `process.cwd()` + +Path to a file or directory. The directory tree is searched up for `tsconfig.json`. + +#### options +Type: `GetTsconfigOptions` + +```ts +type GetTsconfigOptions = { + configName?: string // default: 'tsconfig.json' + cache?: Map + includes?: boolean // default: false + typescriptVersion?: 'auto' | string | false // default: 'auto' +} +``` + +- **configName**: file name to search for (e.g. `'jsconfig.json'`) +- **cache**: snapshot cache for fs operations. Reusing after filesystem changes can return stale results. +- **includes**: when `true`, validates the file is a root file (matched by `include`/`files` globs, not excluded) before accepting the tsconfig. Matches VS Code's Language Server behavior. Default matches `tsc` CLI behavior (nearest tsconfig). Note: this checks glob matching only — a file can still be part of a TypeScript program via transitive imports even if not matched by `include`. +- **typescriptVersion**: applies unconditional compiler-option defaults from the target TypeScript version. Default `'auto'` detects the installed version; pass an explicit version string to pin, or `false` to disable. See [TypeScript version-aware defaults](#typescript-version-aware-defaults). + +#### Example + +```ts +import { getTsconfig } from 'get-tsconfig' + +// Find from current directory +getTsconfig() + +// Find from a file path +getTsconfig('./src/index.ts') + +// Search for jsconfig.json +getTsconfig('.', { configName: 'jsconfig.json' }) + +// Language Server behavior — validate the file is included +getTsconfig('./src/index.ts', { includes: true }) +``` + +### findTsconfig(searchPath?, options?) + +Like `getTsconfig`, but returns only the path (`string | undefined`) without parsing. Same options. + +```ts +import { findTsconfig } from 'get-tsconfig' + +findTsconfig() // → '/project/tsconfig.json' +``` + +### readTsconfig(tsconfigPath, options?) + +Reads and resolves a tsconfig at a known path. Used internally by `getTsconfig`. + +```ts +type ReadTsconfigOptions = { + cache?: Map + typescriptVersion?: 'auto' | string | false // default: 'auto' +} +``` + +- **typescriptVersion**: applies unconditional compiler-option defaults from the target TypeScript version. Default `'auto'` detects the installed version; pass an explicit version string to pin, or `false` to disable. See [TypeScript version-aware defaults](#typescript-version-aware-defaults). + +```ts +import { readTsconfig } from 'get-tsconfig' + +const { path, config } = readTsconfig('./tsconfig.json') +``` + +## Tsconfig `extends` + +`readTsconfig` and `getTsconfig` fully resolve the [`extends`](https://www.typescriptlang.org/tsconfig/#extends) chain and return a flattened config. These two functions expose the chain for use cases like watch mode and config auditing. + +### getExtendsChain(tsconfigPath, options?) + +Collects the full extends chain. Returns an array of `TsconfigResult` entries — each containing the raw (unmerged) config with `extends` resolved to absolute paths. (`TsconfigJson` is the raw tsconfig.json shape, including the `extends` field.) + +`chain[0]` is the root. Ancestors follow in resolution order. + +```ts +type GetExtendsChainOptions = { + cache?: Map +} +``` + +```ts +import { getExtendsChain } from 'get-tsconfig' + +const chain = getExtendsChain('./tsconfig.json') +// [ +// { path: '/project/tsconfig.json', config: { extends: '/project/base.json', ... } }, +// { path: '/project/base.json', config: { ... } }, +// ] + +// Watch all files in the extends chain +const filesToWatch = chain.map(entry => entry.path) +``` + +### resolveExtendsChain(chain) + +Merges a collected extends chain into a resolved tsconfig. Pure function — no filesystem access. + +```ts +import { getExtendsChain, resolveExtendsChain } from 'get-tsconfig' + +const chain = getExtendsChain('./tsconfig.json') + +// Modify before merging +chain[0].config.compilerOptions = { + ...chain[0].config.compilerOptions, + sourceMap: true +} + +const result = resolveExtendsChain(chain) +// TsconfigResult { path, config, sources } +``` + +## Working with a tsconfig + +These functions take a parsed `TsconfigResult` (from `getTsconfig` or `readTsconfig`) and answer questions about it. They cache compiled state per tsconfig object — do not mutate the tsconfig after the first call. + +### isFileIncluded(tsconfig, filePath) + +Checks whether an absolute file path matches a tsconfig's `files`, `include`, and `exclude` globs — i.e., whether it's a **root file**. Case sensitivity is auto-detected from the filesystem. Non-absolute paths return `false`. + +> [!NOTE] +> This checks glob matching only, not transitive imports. A file outside `include` can still be part of the TypeScript program if it's imported by a root file. `exclude` only filters the initial glob matching — it doesn't prevent transitively imported files from being compiled. + +```ts +import { getTsconfig, isFileIncluded } from 'get-tsconfig' + +const tsconfig = getTsconfig() + +if (tsconfig && isFileIncluded(tsconfig, '/path/to/file.ts')) { + // file is a root file of this tsconfig +} +``` + +### resolvePathAlias(tsconfig, specifier) + +Resolves an [import specifier](https://nodejs.org/api/esm.html#terminology) against [`compilerOptions.paths`](https://www.typescriptlang.org/tsconfig#paths). Returns an array of possible file paths, or an empty array if no match. Does not perform actual file resolution. + +```ts +import { getTsconfig, resolvePathAlias } from 'get-tsconfig' + +const tsconfig = getTsconfig() + +const tryPaths = tsconfig && resolvePathAlias(tsconfig, '@/utils/helper') +if (tryPaths?.length) { + // Check if paths in tryPaths exist +} +``` + +## TypeScript version-aware defaults + +TypeScript synthesizes some compiler options when the user doesn't set them — and the synthesized values change between versions. For example, TS 6.0 defaults `moduleResolution` to `'bundler'` and `strict` to `true`, while TS 5.x leaves them unset. + +By default, `get-tsconfig` mirrors what TypeScript itself would compute by detecting the installed TypeScript version near the tsconfig file: + +```ts +import { readTsconfig } from 'get-tsconfig' + +// Default: auto-detect TypeScript via node_modules walk-up +// (or the Yarn Berry pnp API when available). If TS is found, its +// version-aware defaults are applied. If not, no defaults are added. +readTsconfig('./tsconfig.json') + +// Pin a specific version explicitly +readTsconfig('./tsconfig.json', { typescriptVersion: '6.0.0' }) + +// Opt out — return only what's literally in the file (plus internal +// derivations like `strict: true` ⇒ strict-family flags) +readTsconfig('./tsconfig.json', { typescriptVersion: false }) +``` + +> [!IMPORTANT] +> Auto-detection means the parsed config can vary with the runtime environment. If you publish a library that runs both at dev time (with TypeScript installed) and in production (without it), pass an explicit version string or `false` for deterministic output. + +The defaults are tracked per-major (v4, v5, v6) and applied cumulatively. Source-of-truth references for each default live in [`src/version-defaults/`](./src/version-defaults). + +## FAQ + +### How can I use TypeScript to parse `tsconfig.json`? +This package is a re-implementation of TypeScript's `tsconfig.json` parser. + +However, if you already have TypeScript as a dependency, you can simply use it's API: + +```ts +import { + sys as tsSys, + findConfigFile, + readConfigFile, + parseJsonConfigFileContent +} from 'typescript' + +// Find tsconfig.json file +const tsconfigPath = findConfigFile(process.cwd(), tsSys.fileExists, 'tsconfig.json') + +// Read tsconfig.json file +const tsconfigFile = readConfigFile(tsconfigPath, tsSys.readFile) + +// Resolve extends +const parsedTsconfig = parseJsonConfigFileContent( + tsconfigFile.config, + tsSys, + path.dirname(tsconfigPath) +) +``` + +## Sponsors +

+ + + +

diff --git a/node_modules/get-tsconfig/package.json b/node_modules/get-tsconfig/package.json new file mode 100644 index 0000000000000000000000000000000000000000..9b5c9edb15e9a9a6487a5b860511bf20a70c7d66 --- /dev/null +++ b/node_modules/get-tsconfig/package.json @@ -0,0 +1,44 @@ +{ + "name": "get-tsconfig", + "version": "5.0.0-beta.5", + "description": "Find and parse the tsconfig.json file from a directory path", + "keywords": [ + "get-tsconfig", + "get", + "typescript", + "tsconfig", + "tsconfig.json" + ], + "license": "MIT", + "repository": "privatenumber/get-tsconfig", + "funding": "https://github.com/privatenumber/get-tsconfig?sponsor=1", + "author": { + "name": "Hiroki Osame", + "email": "hiroki.osame@gmail.com" + }, + "files": [ + "dist", + "skills" + ], + "sideEffects": false, + "type": "module", + "main": "./dist/index.mjs", + "types": "./dist/index.d.mts", + "exports": { + "types": "./dist/index.d.mts", + "default": "./dist/index.mjs" + }, + "imports": { + "#get-tsconfig": { + "types": "./src/index.ts", + "development": "./src/index.ts", + "default": "./dist/index.mjs" + } + }, + "engines": { + "node": ">=20.20.0" + }, + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + } +} \ No newline at end of file diff --git a/node_modules/get-tsconfig/skills/get-tsconfig/MIGRATION.md b/node_modules/get-tsconfig/skills/get-tsconfig/MIGRATION.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfbcc033129c50d17d71810fc1d67f977ad9e26 --- /dev/null +++ b/node_modules/get-tsconfig/skills/get-tsconfig/MIGRATION.md @@ -0,0 +1,194 @@ +--- +name: get-tsconfig-migration +description: Step-by-step guide for migrating from get-tsconfig v4 to v5. Use when upgrading the dependency, when seeing errors after the upgrade (e.g. parseTsconfig is not a function, TsConfigResult type missing, require() failing), or when adapting code that used createFilesMatcher / createPathsMatcher / parseTsconfig. +--- + +# Migrating from get-tsconfig v4 to v5 + +v5 is ESM-only, requires Node 20+, renames most APIs, and applies TypeScript-version-aware defaults to compiler options by default. The renames are mechanical; the behaviour change is silent — code keeps running but parsed configs now include synthesized fields that v4 left `undefined`. + +> [!IMPORTANT] +> **The biggest gotcha is the new default behaviour.** If your code branches on `compilerOptions.X === undefined` to mean "the user didn't set X," that check now fails — v5 fills X with the installed TypeScript's default (e.g. `moduleResolution: 'bundler'` for TS 6). Pass `typescriptVersion: false` to opt out. See [TypeScript-version-aware defaults](#typescript-version-aware-defaults). + +## Environment + +| Concern | v4 | v5 | +|---|---|---| +| Node | `>=12.20` | `>=20.20` | +| Module format | CJS + ESM dual build | **ESM only** — `require('get-tsconfig')` no longer works | + +Stay on `get-tsconfig@4` if you can't move to ESM or upgrade Node. + +## API renames + +```ts +// v4 +import { + parseTsconfig, + createFilesMatcher, + createPathsMatcher, + type TsConfigResult, +} from 'get-tsconfig' + +const config = parseTsconfig('./tsconfig.json') +const filesMatcher = createFilesMatcher({ path, config }) +const pathsMatcher = createPathsMatcher({ path, config }) + +if (filesMatcher(filePath)) { /* ... */ } +const candidates = pathsMatcher?.('@/foo') +``` + +```ts +// v5 +import { + readTsconfig, + isFileIncluded, + resolvePathAlias, + type TsconfigResult, +} from 'get-tsconfig' + +const result = readTsconfig('./tsconfig.json') +if (isFileIncluded(result, filePath)) { /* ... */ } +const candidates = resolvePathAlias(result, '@/foo') +``` + +`createFilesMatcher` / `createPathsMatcher` were factories returning a closure. `isFileIncluded` / `resolvePathAlias` are direct calls — no factory step. + +## Signature changes (positional → options) + +```ts +// v4 +getTsconfig(searchPath, configName, cache, includes) +findTsconfig(searchPath, configName, cache) +parseTsconfig(path, cache) + +// v5 +getTsconfig(searchPath, { configName, cache, includes, typescriptVersion }) +findTsconfig(searchPath, { configName, cache, includes }) +readTsconfig(path, { cache, typescriptVersion }) +``` + +## Return-value changes + +### `getTsconfig`: `null` → `undefined` + +Replace `=== null` checks. (`findTsconfig` already returned `string | undefined` in v4 — unchanged.) + +### `parseTsconfig` raw config → `readTsconfig` wrapper + +```ts +// v4 — returned the resolved compilerOptions directly +const compilerOptions = parseTsconfig('./tsconfig.json').compilerOptions + +// v5 — returns TsconfigResult { path, config, sources } +const compilerOptions = readTsconfig('./tsconfig.json').config.compilerOptions +``` + +### Matcher return shapes + +| API | v4 return when "no match" | v5 return | +|---|---|---| +| `createFilesMatcher(t)(p)` | `undefined` (matched: returned the config) | `isFileIncluded(t, p)` → `boolean` | +| `createPathsMatcher(t)` | `null` if no `paths`/`baseUrl` | `resolvePathAlias(t, s)` → `string[]` (empty if no aliases) | + +If you read the matched config out of `createFilesMatcher`'s return value, switch to reading from the `TsconfigResult` you already have: + +```ts +// v4 +const matched = filesMatcher(filePath) +if (matched) use(matched.compilerOptions) + +// v5 +if (isFileIncluded(tsconfig, filePath)) use(tsconfig.config.compilerOptions) +``` + +Other behaviour changes worth flagging: + +- **Non-absolute paths.** v4 `createFilesMatcher(t)(relativePath)` **threw** `'filePath must be absolute'`; v5 `isFileIncluded` returns `false` silently. Replace any `try/catch` around the call with an explicit `path.isAbsolute(...)` check. +- **`caseSensitivePaths` is gone.** `createFilesMatcher(t, false)` had no v5 equivalent — sensitivity is auto-detected via `is-fs-case-sensitive`. If you forced a value for cross-platform tests, handle that at the test layer. + +## Type renames and removals + +| v4 | v5 | +|---|---| +| `TsConfigResult` | `TsconfigResult` | +| `TsConfigJson` | `TsconfigJson` | +| `TsConfigJsonResolved` | `TsconfigJsonResolved` | +| `Cache` | `TsconfigCache` | + +Removed (no replacement — the matcher factories they typed are gone): + +- **`PathsMatcher`** — was the function type returned by `createPathsMatcher`. +- **`FileMatcher`** — was the function type returned by `createFilesMatcher`. + +If you imported either to annotate a variable, just delete the import. + +## TypeScript-version-aware defaults + +v5 detects the installed TypeScript version (default: `'auto'`) and applies its unconditional defaults. Parsed configs now include synthesized fields like `moduleResolution: 'bundler'` (TS 6) or `target: 'es5'` (TS 5) where v4 would have left them `undefined`. + +```ts +// v4 +parseTsconfig('./tsconfig.json').compilerOptions +// {} + +// v5 — defaults applied (if TS is installed) +readTsconfig('./tsconfig.json').config.compilerOptions +// { strict: true, target: 'es2025', moduleResolution: 'bundler', ... } + +// v5 with v4 behaviour preserved +readTsconfig('./tsconfig.json', { typescriptVersion: false }).config.compilerOptions +// {} +``` + +**Pass `typescriptVersion: false`** if any of the following apply: + +- Your code branches on `compilerOptions.X === undefined` to mean "the user didn't set X." +- You ship library code that runs both at dev time (with TypeScript installed) and in production (without it). Auto-detection returns `undefined` when TS is missing — output drifts between environments. `false` makes it deterministic. +- You want byte-for-byte parity with v4 output. + +You can also pin a specific version: `{ typescriptVersion: '6.0.0' }`. + +## Additive APIs in v5 (no migration needed) + +- **`getExtendsChain(path, options)`** — raw extends chain before merging. Useful for watch mode (`chain.map(e => e.path)`) or modifying configs before merge. +- **`resolveExtendsChain(chain, options)`** — pure merge function over a chain. No filesystem. +- **`TsconfigResult.sources`** — paths of every file in the resolved extends chain. +- **`typescriptVersion` option** — opt out with `false` for v4-style raw output, or pin a specific version string. + +## Quick search-and-replace + +```sh +# Macro renames (review the diff afterwards — these may overshoot in comments/strings) +sed -i '' ' + s/parseTsconfig/readTsconfig/g + s/createFilesMatcher/isFileIncluded/g + s/createPathsMatcher/resolvePathAlias/g + s/TsConfig/Tsconfig/g + s/\([^A-Za-z0-9_]\)Cache\b/\1TsconfigCache/g +' +``` + +The `Cache` substitution uses a word-boundary lookbehind to avoid mangling identifiers like `cacheMap` or `MyCache`. Review the diff and revert any false positives. + +Then manually: + +1. **Rewrite call sites.** `createFilesMatcher(t)(filePath)` → `isFileIncluded(t, filePath)`. Same for `createPathsMatcher(t)?.(spec)` → `resolvePathAlias(t, spec)`. +2. **Convert positional args to options objects** for `getTsconfig` / `findTsconfig` / `readTsconfig`. +3. **Replace `=== null`** with `=== undefined` (or `!result`) for `getTsconfig` returns. +4. **Update `parseTsconfig` consumers** to access the `.config` property on the result of `readTsconfig`. +5. **Decide on `typescriptVersion`.** Default `'auto'` matches what `tsc` would compute. Pass `false` if you ship to TS-less runtimes or rely on `=== undefined` checks. + +## Common errors after upgrading + +| Error | Cause | Fix | +|---|---|---| +| `Engine "node" is incompatible` | Bumped to Node 20+ | Upgrade Node, or pin `get-tsconfig@4` | +| `require('get-tsconfig')` throws `ERR_REQUIRE_ESM` | CJS dropped | Convert consumer to ESM, or pin `get-tsconfig@4` | +| `TypeError: parseTsconfig is not a function` | Renamed | `parseTsconfig(p)` → `readTsconfig(p).config` | +| `TypeError: createFilesMatcher is not a function` | Renamed + de-curried | `createFilesMatcher(t)(p)` → `isFileIncluded(t, p)` | +| `TypeError: createPathsMatcher is not a function` | Renamed + de-curried | `createPathsMatcher(t)?.(s)` → `resolvePathAlias(t, s)` | +| `Cannot find name 'TsConfigResult'` | Type renamed | `TsConfigResult` → `TsconfigResult` | +| `Cannot find name 'Cache'` | Type renamed | `Cache` → `TsconfigCache` | +| `Cannot find name 'PathsMatcher'` or `'FileMatcher'` | Type removed | Delete the import — no replacement | +| Test snapshots fail with new fields like `moduleResolution: 'bundler'` | Version-aware defaults now applied | Update snapshots, or pass `typescriptVersion: false` to restore v4 output | diff --git a/node_modules/get-tsconfig/skills/get-tsconfig/SKILL.md b/node_modules/get-tsconfig/skills/get-tsconfig/SKILL.md new file mode 100644 index 0000000000000000000000000000000000000000..779a3a16ec05c402913c1d2a20e7cef4fc6942ce --- /dev/null +++ b/node_modules/get-tsconfig/skills/get-tsconfig/SKILL.md @@ -0,0 +1,170 @@ +--- +name: get-tsconfig +description: Find, parse, and query tsconfig.json files — extends resolution, file matching, path alias resolution. Use when reading tsconfig.json, checking if a file belongs to a tsconfig, resolving TypeScript path aliases, or working with tsconfig extends chains. +--- + +# get-tsconfig + +Lightweight tsconfig.json parser. No TypeScript dependency. Tested against `tsc` for correctness. + +> [!NOTE] +> Upgrading from v4? See [MIGRATION.md](./MIGRATION.md) for the API renames, the ESM-only / Node 20+ requirements, and the new version-aware-defaults behaviour. + +## API + +| Function | Purpose | Returns | +|----------|---------|---------| +| `getTsconfig(searchPath?, options?)` | Find + parse nearest tsconfig | `TsconfigResult \| undefined` | +| `findTsconfig(searchPath?, options?)` | Find nearest tsconfig path only | `string \| undefined` | +| `readTsconfig(path, options?)` | Parse tsconfig at known path | `TsconfigResult` | +| `isFileIncluded(tsconfig, filePath)` | Check if file is a root file (matches include/exclude/files globs) | `boolean` | +| `resolvePathAlias(tsconfig, specifier)` | Resolve `compilerOptions.paths` alias | `string[]` | +| `getExtendsChain(path, options?)` | Get raw extends chain before merging | `TsconfigResult[]` | +| `resolveExtendsChain(chain)` | Merge a collected chain (pure, no fs) | `TsconfigResult` | + +## Types + +```ts +type TsconfigResult = { + path: string + config: Config +} + +// TsconfigJson = raw tsconfig shape (includes extends field) +// TsconfigJsonResolved = TsconfigJson without extends (fully merged) + +type GetTsconfigOptions = { + configName?: string // default: 'tsconfig.json' (use 'jsconfig.json' for JS projects) + cache?: Map + includes?: boolean // default: false — when true, validates file is a root file before accepting + typescriptVersion?: 'auto' | string | false // default: 'auto' — see Use cases +} + +type ReadTsconfigOptions = { + cache?: Map + typescriptVersion?: 'auto' | string | false // default: 'auto' +} +``` + +## Use cases + +### Build tool / loader integration + +```ts +import { getTsconfig, isFileIncluded, resolvePathAlias } from 'get-tsconfig' + +const tsconfig = getTsconfig() + +// Check if a file should be transformed with this tsconfig's options +if (tsconfig && isFileIncluded(tsconfig, absoluteFilePath)) { + const { compilerOptions } = tsconfig.config + // Pass to esbuild, SWC, etc. as tsconfigRaw +} + +// Resolve path aliases (returns candidate paths — check which exist) +const resolved = tsconfig && resolvePathAlias(tsconfig, '@/utils/helper') +// → ['/project/src/utils/helper'] or [] +``` + +### Monorepo — per-file tsconfig lookup + +The nearest tsconfig typically applies. Use `getTsconfig` with the file path — it walks up and finds the right one: + +```ts +const cache = new Map() + +const getConfigForFile = (filePath: string) => + getTsconfig(filePath, { cache }) +``` + +Cache deduplicates filesystem reads across calls. Create a new `Map()` to invalidate after filesystem changes. + +### Implied compiler options + +Implied options are already normalized — no need to check parent flags: + +```ts +const { compilerOptions } = getTsconfig().config + +compilerOptions.noImplicitAny // true (implied by strict: true) +compilerOptions.strictNullChecks // true (implied by strict: true) +compilerOptions.esModuleInterop // true (implied by module: 'nodenext') +compilerOptions.allowJs // true (implied by checkJs: true) +``` + +Options not set and not implied remain `undefined` (not `false`). Use `?? false` for boolean checks. + +### Watch mode — extends chain files + +```ts +import { getExtendsChain } from 'get-tsconfig' + +const chain = getExtendsChain('./tsconfig.json') +const filesToWatch = chain.map(entry => entry.path) +``` + +### Modify config before merging + +```ts +import { getExtendsChain, resolveExtendsChain } from 'get-tsconfig' + +const chain = getExtendsChain('./tsconfig.json') +chain[0].config.compilerOptions = { + ...chain[0].config.compilerOptions, + sourceMap: true, +} +const result = resolveExtendsChain(chain) +``` + +### Language Server behavior + +```ts +// Default: nearest tsconfig (tsc CLI behavior) +getTsconfig('./src/index.ts') + +// Validates file is a root file before accepting (VS Code behavior) +getTsconfig('./src/index.ts', { includes: true }) +``` + +### TypeScript version-aware defaults + +The parser auto-detects the installed TypeScript version and applies its unconditional defaults (e.g. TS 6.0 sets `moduleResolution: 'bundler'`, `strict: true`). This is the default behavior — the parsed config matches what `tsc` would compute. + +```ts +// Default — auto-detects via node_modules walk-up (or Yarn pnp) +readTsconfig('./tsconfig.json') + +// Pin a specific version (deterministic across environments) +readTsconfig('./tsconfig.json', { typescriptVersion: '6.0.0' }) + +// Disable — return only the literal config + within-config derivations +readTsconfig('./tsconfig.json', { typescriptVersion: false }) +``` + +**When to pass `false`:** library code that runs in environments where TypeScript may not be installed (production runtimes, trimmed Docker images). Auto-detection there would return `undefined` and behave inconsistently with dev. Passing `false` makes output deterministic. + +Per-major changes are tracked in `src/version-defaults/{v4,v5,v6}.ts` with links to the corresponding TypeScript source. + +## Understanding `isFileIncluded` + +Checks whether a file matches `include`/`exclude`/`files` globs — whether it's a **root file**. This is NOT the same as "is this file part of the TypeScript program." + +| Source | What it adds | Checked by `isFileIncluded`? | +|--------|-------------|-------------------------------| +| `include`/`files` globs | Root files | **Yes** | +| Transitive imports | Files imported by root files (recursive) | No | +| `@types` packages | Auto-discovered from `node_modules/@types/` | No | +| Triple-slash directives | `/// ` | No | + +- **`exclude` only filters glob matching** — if a root file imports an excluded file, that file is still in the program. +- **`isFileIncluded` returning `false` doesn't mean the file won't be compiled** — it may be pulled in via imports. +- For finding the nearest tsconfig regardless of glob matching, use `getTsconfig(filePath)` without `includes`. + +## Gotchas + +| Issue | Detail | +|-------|--------| +| Immutable tsconfig objects | `isFileIncluded` and `resolvePathAlias` cache per object identity. Do not mutate after first call. | +| `extends` must be resolved | `isFileIncluded` throws if `config.extends` is present. Use `getTsconfig`/`readTsconfig` output. | +| `resolvePathAlias` returns candidates | Returns paths from `compilerOptions.paths`, not verified files. Check existence yourself. | +| `getExtendsChain` resolves extends | The `extends` field in each entry is an absolute path, not the original string. | diff --git a/node_modules/gifwrap/.jshintrc b/node_modules/gifwrap/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..98cf8d721460e9af066f0013b001e749d55df268 --- /dev/null +++ b/node_modules/gifwrap/.jshintrc @@ -0,0 +1,4 @@ +{ + "esversion": 6, + "node": true +} diff --git a/node_modules/gifwrap/LICENSE b/node_modules/gifwrap/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a5d1aad71024eac740a285b3528d58c5e82a7014 --- /dev/null +++ b/node_modules/gifwrap/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2017 Joseph T. Lapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gifwrap/README.md b/node_modules/gifwrap/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82f6e75694c7bd3834627d4dbc6c278050d9a40b --- /dev/null +++ b/node_modules/gifwrap/README.md @@ -0,0 +1,668 @@ +# gifwrap + +A Jimp-compatible library for working with GIFs + +## Overview + +`gifwrap` is a minimalist library for working with GIFs in Javascript, supporting both single- and multi-frame GIFs. It reads GIFs into an internal representation that's easy to work with and allows for making GIFs from scratch. The frame class is structured to make it easy to move images between [`Jimp`](https://github.com/oliver-moran/jimp) and `gifwrap` for more sophisticated image manipulation in `Jimp`, but the module has no dependency on `Jimp`. + +The library uses Dean McNamee's [`omggif`](https://github.com/deanm/omggif) GIF encoder/decoder by default, but it employs an abstraction that allows using other encoders and decoders as well, once suitably wrapped. + +At present, the module only works in Node.js. Includes Typescript typings. + +## Installation + +``` +npm install gifwrap --save +``` + +or + +``` +yarn add gifwrap +``` + +## Usage + +You can work with either GIF files or GIF encodings, and you can create GIFs from scratch. + +The GifFrame class represents a single image frame, and the library largely represents a GIF as an array of GifFrame instances. For example, here is how you create a GIF from scratch: + +```js +const { GifFrame, GifUtil, GifCodec } = require('gifwrap'); +const width = 200, height = 100; +const frames = []; + +let frame = new GifFrame(width, height, { delayCentisecs: 10 }); +// modify the pixels at frame.bitmap.data +frames.push(frame); +frame = new GifFrame(width, height, { delayCentisecs: 15 }); +// modify the pixels at frame.bitmap.data +frames.push(frame); +// add more frames as desired... + +// to write to a file... +GifUtil.write("my-creation.gif", frames, { loops: 3 }).then(gif => { + console.log("written"); +}); + +// to get the byte encoding without writing to a file... +const codec = new GifCodec(); +codec.encodeGif(frames, { loops: 3 }).then(gif => { + // byte encoding is now in gif.buffer +}); + +``` + +Images are represented within a GifFrame exactly as they are in a `Jimp` image. In particular, each GifFrame instance has a `bitmap` property having the following structure: + +* `frame.bitmap.width` - Width of image in pixels +* `frame.bitmap.height` - Height of image in pixels +* `frame.bitmap.data` - A Node.js Buffer that can be accessed like an array of bytes. Every 4 adjacent bytes represents the RGBA values of a single pixel. These 4 bytes correspond to red, green, blue, and alpha, in that order. Each pixel begins at an index that is a multiple of 4. + +GIFs do not support partial transparency, so within `frame.bitmap.data`, pixels having alpha value 0x00 are treated as transparent and pixels of non-zero alpha value are treated as opaque. The encoder ignores the RGB values of transparent pixels. + +`gifwrap` also provides utilities for reading GIF files and for parsing raw encodings: + +```js +const { GifUtil } = require('gifwrap'); +GifUtil.read("fancy.gif").then(inputGif => { + + inputGif.frames.forEach(frame => { + + const buf = frame.bitmap.data; + frame.scanAllCoords((x, y, bi) => { + + // Halve all grays on right half of image. + + if (x > inputGif.width / 2) { + const r = buf[bi]; + const g = buf[bi + 1]; + const b = buf[bi + 2]; + const a = buf[bi + 3]; + if (r === g && r === b && a === 0xFF) { + buf[bi] /= 2; + buf[bi + 1] /= 2; + buf[bi + 2] /= 2; + } + } + }); + }); + + // Pass inputGif to write() to preserve the original GIF's specs. + return GifUtil.write("modified.gif", inputGif.frames, inputGif).then(outputGif => { + console.log("modified"); + }); +}); +``` + +```js +const { GifUtil, GifCodec } = require('gifwrap'); +const codec = new GifCodec(); +const byteEncodingBuffer = getByteEncodingForSomeGif(); + +codec.decodeGif(byteEncodingBuffer).then(sourceGif => { + + const edgeLength = Math.min(sourceGif.width, sourceGif.height); + sourceGif.frames.forEach(frame => { + + // Make each frame a centered square of size edgeLength x edgeLength. + // Note that frames may vary in size and that reframe() works even if + // the frame's image is smaller than the square. Should this happen, + // the space surrounding the original image will be transparent. + + const xOffset = (frame.bitmap.width - edgeLength)/2; + const yOffset = (frame.bitmap.height - edgeLength)/2; + frame.reframe(xOffset, yOffset, edgeLength, edgeLength); + }); + + // The encoder determines GIF size from the frames, not the provided spec (sourceGif). + return GifUtil.write("modified.gif", sourceGif.frames, sourceGif).then(outputGif => { + console.log("modified"); + }); +}); +``` + +Notice that both encoding and decoding yields a GIF object. This is an instance of class Gif, and it provides information about the GIF, such as its size and how many times it loops. Notice also that you never call the Gif constructor to create a GIF. Instead, GIFs are created by providing a GifFrame array and a specification of GIF options. That specification is a subset of the properties of a Gif, so you can pass a previously-loaded Gif as a specification when writing or encoding. The encoder only uses the properties that can't be inferred from the frames -- namely, how many times the GIF loops and how to attempt to package the color tables within the encoding. + +## Leveraging Jimp + +This module was originally written as a wrapper around Jimp images -- hence its name -- and then with frames as subclasses of Jimp images. Neither approach worked out well. The final approach requires just a tad of legwork to use `gifwrap` images within Jimp. + +Both Jimp images and GifFrame instances share the `bitmap` property. By transferring this property back and forth between Jimp images and GifFrame instances, an image can be moved back and forth between the two libraries. + +You can construct a GifFrame from a Jimp image as follows: + +```js +const { BitmapImage, GifFrame } = require('gifwrap'); +const Jimp = require('jimp'); +const j = new Jimp(200, 100, 0xFFFFFFFF); + +// create a frame clone of a Jip bitmap +const fCopied = new GifFrame(new BitmapImage(j.bitmap)); + +// create a frame that shares a bitmap with Jimp (one way) +const fShared1 = new GifFrame(j.bitmap); + +// create a frame that shares a bitmap with Jimp (another way) +const fShared2 = new GifFrame(1, 1, 0); // any GifFrame +fShared2.bitmap = j.bitmap; +``` + +And you can construct a Jimp instance from a GifFrame image as follows: + +```js +const { BitmapImage, GifFrame } = require('gifwrap'); +const Jimp = require('jimp'); +const frame = new GifFrame(200, 100, 0xFFFFFFFF); + +// create a Jimp containing a clone of the frame bitmap +jimpCopied = GifUtil.copyAsJimp(Jimp, frame); + +// create a Jimp that shares a bitmap with the frame +jimpShared = GifUtil.shareAsJimp(Jimp, frame); +``` + +## Encoders and Decoders + +`gifwrap` provides a default GIF encoder/decoder, but it is architected to be able to work with other encoders and decoders. The encoder and decoder may even be separate implementations. Encoders and decoders have varying capabilities, performance measures, and levels of reliability. + +GifCodec is the default implementation, and it's both an encoder and a decoder. It's an adapter that wraps the [`omggif`](https://github.com/deanm/omggif) module. `omggif` appears to support a broad variety of GIFs, although it cannot produce an interlaced encoding (which there is little need for anyway). Although `omggif` doesn't include a test suite at present, `gifwrap`'s test suite happens to test it reasonably well by virtue of using `omggif` underneath. + +An encoder need only implement GifCodec's [`encodeGif()`](#GifCodec+encodeGif) method, and a decoder need only implement its [`decodeGif()`](#GifCodec+decodeGif) method. See the descriptions of those methods for the requirement details. Although GifCodec is stateless, so that instances an be reused across multiple encodings and decodings, third party encoders and decoders need not be. However, applications that use the library with stateful encoders will need to be aware of the need to create new instances. + +To use a third-party encoder or decoder with the GifUtil `write()` and `read()` functions, just pass an instance of the encoder or decoder as the last parameter to `write()` or `read()`, respectively. For example: + +```js +const { GifUtil } = require('gifwrap'); +const SnazzyDecoder = require('gifwrap-snazzy-decoder'); +const AwesomeEncoder = require('gifwrap-awesome-encoder'); + +GifUtil.read("fancy.gif", new SnazzyDecoder()).then(gif => + + /*...*/ + + return GifUtil.write("modified.gif", gif.frames, gif, new AwesomeEncoder()).then(newGif => { + console.log("modified"); + }); +}); +``` + +## API Reference + +The [Typescript typings](https://github.com/jtlapp/gifwrap/blob/master/index.d.ts) provide an exact specification of the API and also serve as a cheat sheet. The classes and namespaces follow: + +* **gifwrap** + + * [.**Gif**](#new_Gif_new) + * [.**BitmapImage**](#BitmapImage) + * [.**GifFrame**](#GifFrame) + * [.**GifUtil**](#GifUtil) + * [.**GifCodec**](#GifCodec) + * [.**GifError**](#new_GifError_new) + + +* [BitmapImage](#BitmapImage) + + * [new BitmapImage()](#new_BitmapImage_new) + + * [.blit(toImage, toX, toY, fromX, fromY)](#BitmapImage+blit) + + * [.fillRGBA(rgba)](#BitmapImage+fillRGBA) + + * [.getRGBA(x, y)](#BitmapImage+getRGBA) + + * [.getRGBASet()](#BitmapImage+getRGBASet) + + * [.greyscale()](#BitmapImage+greyscale) + + * [.reframe(xOffset, yOffset, width, height, fillRGBA)](#BitmapImage+reframe) + + * [.scale(factor)](#BitmapImage+scale) + + * [.scanAllCoords(scanHandler)](#BitmapImage+scanAllCoords) + + * [.scanAllIndexes(scanHandler)](#BitmapImage+scanAllIndexes) + + + +* [GifFrame](#GifFrame) + + * [new GifFrame()](#new_GifFrame_new) + + * [.getPalette()](#GifFrame+getPalette) + + + +* [GifUtil](#GifUtil) + + * [.cloneFrames(frames)](#GifUtil.cloneFrames) + + * [.getColorInfo(frames, maxGlobalIndex)](#GifUtil.getColorInfo) + + * [.copyAsJimp(Reference, Instance)](#GifUtil.copyAsJimp) + + * [.getMaxDimensions(frames)](#GifUtil.getMaxDimensions) + + * [.quantizeDekker(imageOrImages, maxColorIndexes, dither)](#GifUtil.quantizeDekker) + + * [.quantizeSorokin(imageOrImages, maxColorIndexes, histogram, dither)](#GifUtil.quantizeSorokin) + + * [.quantizeWu(imageOrImages, maxColorIndexes, significantBits, dither)](#GifUtil.quantizeWu) + + * [.read(source, decoder)](#GifUtil.read) + + * [.shareAsJimp(Reference, Instance)](#GifUtil.shareAsJimp) + + * [.write(path, frames, spec, encoder)](#GifUtil.write) + + + +* [GifCodec](#GifCodec) + + * [new GifCodec(options)](#new_GifCodec_new) + + * [.decodeGif(buffer)](#GifCodec+decodeGif) + + * [.encodeGif(frames, spec)](#GifCodec+encodeGif) + + + + + +### new Gif(buffer, frames, spec) + +| Param | Type | Description | +| --- | --- | --- | +| buffer | Buffer | A Buffer containing the encoded bytes | +| frames | [Array.<GifFrame>](#GifFrame) | Array of frames found in the encoding | +| spec | object | Properties of the encoding as listed above | + +Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class. + +Property | Description +--- | --- +width | width of the GIF at its widest +height | height of the GIF at its highest +loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely +usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel +colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2). +frames | a array of GifFrame instances, one for each frame of the GIF +buffer | a Buffer holding the encoding's byte data + +Its constructor should only ever be called by the GIF encoder or decoder. + + + +### new BitmapImage() +BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties: + +Property | Description +--- | --- +bitmap.width | width of image in pixels +bitmap.height | height of image in pixels +bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel + +Its constructor supports the following signatures: + +* new BitmapImage(bitmap: { width: number, height: number, data: Buffer }) +* new BitmapImage(bitmapImage: BitmapImage) +* new BitmapImage(width: number, height: number, buffer: Buffer) +* new BitmapImage(width: number, height: number, backgroundRGBA?: number) + +When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other. + +`backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque. + + + +### *bitmapImage*.blit(toImage, toX, toY, fromX, fromY) + +| Param | Type | Description | +| --- | --- | --- | +| toImage | [BitmapImage](#BitmapImage) | Image into which to copy the square | +| toX | number | x-coord in toImage of upper-left corner of receiving square | +| toY | number | y-coord in toImage of upper-left corner of receiving square | +| fromX | number | x-coord in this image of upper-left corner of source square | +| fromY | number | y-coord in this image of upper-left corner of source square | + +Copy a square portion of this image into another image. + +**Returns**: [BitmapImage](#BitmapImage) - The present image to allow for chaining. + + +### *bitmapImage*.fillRGBA(rgba) + +| Param | Type | Description | +| --- | --- | --- | +| rgba | number | Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque. | + +Fills the image with a single color. + +**Returns**: [BitmapImage](#BitmapImage) - The present image to allow for chaining. + + +### *bitmapImage*.getRGBA(x, y) + +| Param | Type | Description | +| --- | --- | --- | +| x | number | x-coord of pixel | +| y | number | y-coord of pixel | + +Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs. + +**Returns**: number - RGBA of pixel in 0xRRGGBBAA form + + +### *bitmapImage*.getRGBASet() +Gets a set of all RGBA colors found within the image. + +**Returns**: Set - Set of all RGBA colors that the image contains. + + +### *bitmapImage*.greyscale() +Converts the image to greyscale using inferred Adobe metrics. + +**Returns**: [BitmapImage](#BitmapImage) - The present image to allow for chaining. + + +### *bitmapImage*.reframe(xOffset, yOffset, width, height, fillRGBA) + +| Param | Type | Description | +| --- | --- | --- | +| xOffset | number | The x-coord offset of the upper-left pixel of the desired image relative to the present image. | +| yOffset | number | The y-coord offset of the upper-left pixel of the desired image relative to the present image. | +| width | number | The width of the new image after reframing | +| height | number | The height of the new image after reframing | +| fillRGBA | number | The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop). | + +Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image. + +**Returns**: [BitmapImage](#BitmapImage) - The present image to allow for chaining. + + +### *bitmapImage*.scale(factor) + +| Param | Type | Description | +| --- | --- | --- | +| factor | number | The factor by which to scale up the image. Must be an integer >= 1. | + +Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels. + +**Returns**: [BitmapImage](#BitmapImage) - The present image to allow for chaining. + + +### *bitmapImage*.scanAllCoords(scanHandler) +**See**: scanAllIndexes + +| Param | Type | Description | +| --- | --- | --- | +| scanHandler | function | A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`. | + +Scans all coordinates of the image, handing each in turn to the provided handler function. + + + +### *bitmapImage*.scanAllIndexes(scanHandler) +**See**: scanAllCoords + +| Param | Type | Description | +| --- | --- | --- | +| scanHandler | function | A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`. | + +Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates. + + + +### new GifFrame() +GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame. + +Property | Description +--- | --- +xOffset | x-coord of position within GIF at which to render the image (defaults to 0) +yOffset | y-coord of position within GIF at which to render the image (defaults to 0) +disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color) +delayCentisecs | duration of the frame in hundreths of a second +interlaced | boolean indicating whether the frame renders interlaced + +Its constructor supports the following signatures: + +* new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?) +* new GifFrame(bitmapImage: BitmapImage, options?) +* new GifFrame(width: number, height: number, buffer: Buffer, options?) +* new GifFrame(width: number, height: number, backgroundRGBA?: number, options?) +* new GifFrame(frame: GifFrame) + +See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional. + +Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other. + + + +### *gifFrame*.getPalette() +Get a summary of the colors found within the frame. The return value is an object of the following form: + +Property | Description +--- | --- +colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent. +usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00. +indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency. + +**Returns**: object - An object representing a color palette as described above. + + +### *GifUtil*.cloneFrames(frames) + +| Param | Type | Description | +| --- | --- | --- | +| frames | [Array.<GifFrame>](#GifFrame) | An array of GifFrame instances to clone | + +cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once. + +**Returns**: [Array.<GifFrame>](#GifFrame) - An array of GifFrame clones of the provided frames. + + +### *GifUtil*.getColorInfo(frames, maxGlobalIndex) +**Throws**: + +- [GifError](#GifError) When any frame requires more than 256 color indexes. + + +| Param | Type | Description | +| --- | --- | --- | +| frames | [Array.<GifFrame>](#GifFrame) | Frames to examine for color and transparency. | +| maxGlobalIndex | number | Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default. | + +getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames. + +`maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency. + +**Returns**: object - Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF. + + +### *GifUtil*.copyAsJimp(Reference, Instance) + +| Param | Type | Description | +| --- | --- | --- | +| Reference | object | to the Jimp package, keeping this library from being dependent on Jimp. | +| Instance | bitmapImageToCopy | of BitmapImage (may be a GifUtil) with which to source the Jimp. | + +copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp. + +**Returns**: object - An new instance of Jimp containing a copy of the image in bitmapImageToCopy. + + +### *GifUtil*.getMaxDimensions(frames) + +| Param | Type | Description | +| --- | --- | --- | +| frames | [Array.<GifFrame>](#GifFrame) | Frames to measure for their aggregate maximum dimensions. | + +getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame. + +**Returns**: object - An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames. + + +### *GifUtil*.quantizeDekker(imageOrImages, maxColorIndexes, dither) + +| Param | Type | Description | +| --- | --- | --- | +| imageOrImages | [BitmapImage](#BitmapImage) \| [Array.<BitmapImage>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. | +| maxColorIndexes | number | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. | +| dither | object | (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. } | + +Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker. + +The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + +The method may increase the number of colors if there are fewer than the provided maximum. + + + +### *GifUtil*.quantizeSorokin(imageOrImages, maxColorIndexes, histogram, dither) + +| Param | Type | Description | +| --- | --- | --- | +| imageOrImages | [BitmapImage](#BitmapImage) \| [Array.<BitmapImage>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. | +| maxColorIndexes | number | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. | +| histogram | string | (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'. | +| dither | object | (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. | + +Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum. + +The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + + + +### *GifUtil*.quantizeWu(imageOrImages, maxColorIndexes, significantBits, dither) + +| Param | Type | Description | +| --- | --- | --- | +| imageOrImages | [BitmapImage](#BitmapImage) \| [Array.<BitmapImage>](#BitmapImage) | Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. | +| maxColorIndexes | number | The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. | +| significantBits | number | (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5. | +| dither | object | (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. | + +Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu. + +The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + +The method may increase the number of colors if there are fewer than the provided maximum. + + + +### *GifUtil*.read(source, decoder) + +| Param | Type | Description | +| --- | --- | --- | +| source | string \| Buffer | Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse. | +| decoder | object | An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec. | + +read() decodes an encoded GIF, whether provided as a filename or as a byte buffer. + +**Returns**: Promise - A Promise that resolves to an instance of the Gif class, representing the decoded GIF. + + +### *GifUtil*.shareAsJimp(Reference, Instance) + +| Param | Type | Description | +| --- | --- | --- | +| Reference | object | to the Jimp package, keeping this library from being dependent on Jimp. | +| Instance | bitmapImageToShare | of BitmapImage (may be a GifUtil) with which to source the Jimp. | + +shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp. + +**Returns**: object - An new instance of Jimp that shares the image in bitmapImageToShare. + + +### *GifUtil*.write(path, frames, spec, encoder) + +| Param | Type | Description | +| --- | --- | --- | +| path | string | Filename to write GIF out as. Will overwrite an existing file. | +| frames | [Array.<GifFrame>](#GifFrame) | Array of frames to be written into GIF. | +| spec | object | An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred. | +| encoder | object | An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec. | + +write() encodes a GIF and saves it as a file. + +**Returns**: Promise - A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + + +### new GifCodec(options) + +| Param | Type | Description | +| --- | --- | --- | +| options | object | Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000. | + +GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing. + +Instances of this class are stateless and can be shared across multiple encodings and decodings. + +Its constructor takes one option argument: + + + +### *gifCodec*.decodeGif(buffer) +**Throws**: + +- [GifError](#GifError) Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + + +| Param | Type | Description | +| --- | --- | --- | +| buffer | Buffer | Bytes of an encoded GIF to decode. | + +Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option. + +**Returns**: Promise - A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + + +### *gifCodec*.encodeGif(frames, spec) +**Throws**: + +- [GifError](#GifError) Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + + +| Param | Type | Description | +| --- | --- | --- | +| frames | [Array.<GifFrame>](#GifFrame) | Array of frames to encode | +| spec | object | An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred. | + +Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque. + +**Returns**: Promise - A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + + +### new GifError(messageOrError) + +| Param | Type | +| --- | --- | +| messageOrError | string \| Error | + +GifError is a class representing a GIF-related error + + +## LICENSE + +MIT License + +Copyright © 2017 Joseph T. Lapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gifwrap/index.d.ts b/node_modules/gifwrap/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dda0d0ef911dedb5275768334ab5876d359a0c35 --- /dev/null +++ b/node_modules/gifwrap/index.d.ts @@ -0,0 +1,153 @@ + +export interface GifSpec { + + loops?: number; + colorScope?: 0|1|2; +} + +export interface GifEncoder { + encodeGif(frames: GifFrame[], spec: GifSpec): Promise; +} + +export interface GifDecoder { + decodeGif(buffer: Buffer): Promise; +} + +export class Gif implements GifSpec { + + static readonly GlobalColorsPreferred: 0; + static readonly GlobalColorsOnly: 1; + static readonly LocalColorsOnly: 2; + + width: number; + height: number; + loops: number; + usesTransparency: boolean; + colorScope: 0|1|2; + + frames: GifFrame[]; + buffer: Buffer; + + constructor(frames: GifFrame[], buffer: Buffer, spec?: GifSpec); +} + +export interface GifFrameOptions { + xOffset?: number; + yOffset?: number; + disposalMethod?: 0|1|2|3; + delayCentisecs?: number; + isInterlaced?: boolean; +} + +export interface JimpBitmap { + width: number; + height: number; + data: Buffer; +} + +export interface GifPalette { + colors: number[]; + indexCount: number; + usesTransparency: boolean; +} + +export class BitmapImage { + bitmap: JimpBitmap; + + constructor(bitmap: JimpBitmap); + constructor(bitmapImage: BitmapImage); + constructor(width: number, height: number, buffer: Buffer); + constructor(width: number, height: number, backgroundRGBA?: number); + + blit(toImage: BitmapImage, toX: number, toY: number, fromX: number, fromY: number, + fromWidth: number, fromHeight: number): this; + fillRGBA(color: number): this; + getRGBA(x: number, y: number): number; + getRGBASet(): Set; + greyscale(): this; + reframe(xOffset: number, yOffset: number, width: number, height: number, fillRGBA?: number) + : this; + scale(factor: number): this; + scanAllCoords(handler: (x: number, y: number, bufferIndex: number) => void): void; + scanAllIndexes(handler: (bufferIndex: number) => void): void; +} + +export class GifFrame extends BitmapImage implements GifFrameOptions { + + static readonly DisposeToAnything: 0; + static readonly DisposeNothing: 1; + static readonly DisposeToBackgroundColor: 2; + static readonly DisposeToPrevious: 3; + + xOffset: number; + yOffset: number; + disposalMethod: 0|1|2|3; + delayCentisecs: number; + interlaced: boolean; + + constructor(bitmap: JimpBitmap, options?: GifFrameOptions); + constructor(bitmapImage: BitmapImage, options?: GifFrameOptions); + constructor(width: number, height: number, buffer: Buffer, options?: GifFrameOptions); + constructor(width: number, height: number, backgroundRGBA?: number, options?: GifFrameOptions); + constructor(frame: GifFrame); + + getPalette(): GifPalette; +} + +export interface GifCodecOptions { + transparentRGB?: number; +} + +export class GifCodec implements GifEncoder, GifDecoder { + + constructor(options?: GifCodecOptions); + + encodeGif(frames: GifFrame[], spec: GifSpec): Promise; + decodeGif(buffer: Buffer): Promise; +} + +export class GifError extends Error { + + constructor(message: string); +} + +export namespace GifUtil { + + function cloneFrames(frames: GifFrame[]): GifFrame[]; + function copyAsJimp(jimp: any, bitmapImageToCopy: BitmapImage): any; + function getColorInfo(frames: GifFrame[], maxGlobalIndex?: number): { + colors?: number[], + indexCount?: number, + usesTransparency: boolean, + palettes: GifPalette[] + } + function getMaxDimensions(frames: GifFrame[]): { maxWidth: number, maxHeight: number }; + function quantizeDekker(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number, + dither?: Dither): void; + function quantizeSorokin(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number, + histogram?: string, dither?: Dither): void; + function quantizeWu(imageOrImages: BitmapImage|BitmapImage[], maxColorIndexes: number, + significantBits?: number, dither?: Dither): void; + function read(source: string|Buffer, decoder?: GifDecoder): Promise; + function shareAsJimp(jimp: any, bitmapImageToCopy: BitmapImage): any; + function write(path: string, frames: GifFrame[], spec?: GifSpec, encoder?: GifEncoder): + Promise; +} + +export type DitherAlgorithm = + 'FloydSteinberg' | + 'FalseFloydSteinberg' | + 'Stucki' | + 'Atkinson' | + 'Jarvis' | + 'Burkes' | + 'Sierra' | + 'TwoSierra' | + 'SierraLite'; + +export type Dither = { + ditherAlgorithm: DitherAlgorithm, + minimumColorDistanceToDither?: number, // default = 0 + serpentine?: boolean, // default = true + calculateErrorLikeGIMP?: boolean // default = false +}; diff --git a/node_modules/gifwrap/package.json b/node_modules/gifwrap/package.json new file mode 100644 index 0000000000000000000000000000000000000000..71c2a6e2b3ca736de036615e62701b827eacffd1 --- /dev/null +++ b/node_modules/gifwrap/package.json @@ -0,0 +1,39 @@ +{ + "name": "gifwrap", + "version": "0.10.1", + "description": "A Jimp-compatible library for working with GIFs", + "main": "src/index.js", + "scripts": { + "test": "mocha --timeout=6000 ./test/*.js", + "docs": "jsdoc2md --plugin dmd-clear --template templates/README.hbs src/index.js src/gif.js src/bitmapimage.js src/gifframe.js src/gifutil.js src/gifcodec.js > README.md" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/jtlapp/gifwrap.git" + }, + "keywords": [ + "image", + "image", + "processing", + "image", + "manipulation", + "gif", + "javascript" + ], + "author": "Joseph T. Lapp", + "license": "MIT", + "bugs": { + "url": "https://github.com/jtlapp/gifwrap/issues" + }, + "homepage": "https://github.com/jtlapp/gifwrap#readme", + "dependencies": { + "image-q": "^4.0.0", + "omggif": "^1.0.10" + }, + "devDependencies": { + "chai": "^4.2.0", + "dmd-clear": "^0.1.2", + "jimp": "^0.2.28", + "mocha": "^9.2.2" + } +} diff --git a/node_modules/gifwrap/src/bitmapimage.js b/node_modules/gifwrap/src/bitmapimage.js new file mode 100644 index 0000000000000000000000000000000000000000..66bc6df5db7af89e28f3cf91900243ec770d61a9 --- /dev/null +++ b/node_modules/gifwrap/src/bitmapimage.js @@ -0,0 +1,310 @@ +'use strict'; + +/** @class BitmapImage */ + +class BitmapImage { + + /** + * BitmapImage is a class that hold an RGBA (red, green, blue, alpha) representation of an image. It's shape is borrowed from the Jimp package to make it easy to transfer GIF image frames into Jimp and Jimp images into GIF image frames. Each instance has a `bitmap` property having the following properties: + * + * Property | Description + * --- | --- + * bitmap.width | width of image in pixels + * bitmap.height | height of image in pixels + * bitmap.data | a Buffer whose every four bytes represents a pixel, each sequential byte of a pixel corresponding to the red, green, blue, and alpha values of the pixel + * + * Its constructor supports the following signatures: + * + * * new BitmapImage(bitmap: { width: number, height: number, data: Buffer }) + * * new BitmapImage(bitmapImage: BitmapImage) + * * new BitmapImage(width: number, height: number, buffer: Buffer) + * * new BitmapImage(width: number, height: number, backgroundRGBA?: number) + * + * When a `BitmapImage` is provided, the constructed `BitmapImage` is a deep clone of the provided one, so that each image's pixel data can subsequently be modified without affecting each other. + * + * `backgroundRGBA` is an optional parameter representing a pixel as a single number. In hex, the number is as follows: 0xRRGGBBAA, where RR is the red byte, GG the green byte, BB, the blue byte, and AA the alpha value. An AA of 0x00 is considered transparent, and all non-zero AA values are treated as opaque. + */ + + constructor(...args) { + // don't confirm the number of args, because a subclass may have + // additional args and pass them all to the superclass + if (args.length === 0) { + throw new Error("constructor requires parameters"); + } + const firstArg = args[0]; + if (firstArg !== null && typeof firstArg === 'object') { + if (firstArg instanceof BitmapImage) { + // copy a provided BitmapImage + const sourceBitmap = firstArg.bitmap; + this.bitmap = { + width: sourceBitmap.width, + height: sourceBitmap.height, + data: new Buffer(sourceBitmap.width * sourceBitmap.height * 4) + }; + sourceBitmap.data.copy(this.bitmap.data); + } + else if (firstArg.width && firstArg.height && firstArg.data) { + // share a provided bitmap + this.bitmap = firstArg; + } + else { + throw new Error("unrecognized constructor parameters"); + } + } + else if (typeof firstArg === 'number' && typeof args[1] === 'number') + { + const width = firstArg; + const height = args[1]; + const thirdArg = args[2]; + this.bitmap = { width, height }; + + if (Buffer.isBuffer(thirdArg)) { + this.bitmap.data = thirdArg; + } + else { + this.bitmap.data = new Buffer(width * height * 4); + if (typeof thirdArg === 'number') { + this.fillRGBA(thirdArg); + } + } + } + else { + throw new Error("unrecognized constructor parameters"); + } + } + + /** + * Copy a square portion of this image into another image. + * + * @param {BitmapImage} toImage Image into which to copy the square + * @param {number} toX x-coord in toImage of upper-left corner of receiving square + * @param {number} toY y-coord in toImage of upper-left corner of receiving square + * @param {number} fromX x-coord in this image of upper-left corner of source square + * @param {number} fromY y-coord in this image of upper-left corner of source square + * @return {BitmapImage} The present image to allow for chaining. + */ + + blit(toImage, toX, toY, fromX, fromY, fromWidth, fromHeight) { + if (fromX + fromWidth > this.bitmap.width) { + throw new Error("copy exceeds width of source bitmap"); + } + if (toX + fromWidth > toImage.bitmap.width) { + throw new Error("copy exceeds width of target bitmap"); + } + if (fromY + fromHeight > this.bitmap.height) { + throw new Error("copy exceeds height of source bitmap"); + } + if (toY + fromHeight > toImage.bitmap.height) { + throw new Erro("copy exceeds height of target bitmap"); + } + + const sourceBuf = this.bitmap.data; + const targetBuf = toImage.bitmap.data; + const sourceByteWidth = this.bitmap.width * 4; + const targetByteWidth = toImage.bitmap.width * 4; + const copyByteWidth = fromWidth * 4; + let si = fromY * sourceByteWidth + fromX * 4; + let ti = toY * targetByteWidth + toX * 4; + + while (--fromHeight >= 0) { + sourceBuf.copy(targetBuf, ti, si, si + copyByteWidth); + si += sourceByteWidth; + ti += targetByteWidth; + } + return this; + } + + /** + * Fills the image with a single color. + * + * @param {number} rgba Color with which to fill image, expressed as a singlenumber in the form 0xRRGGBBAA, where AA is 0x00 for transparent and any other value for opaque. + * @return {BitmapImage} The present image to allow for chaining. + */ + + fillRGBA(rgba) { + const buf = this.bitmap.data; + const bufByteWidth = this.bitmap.height * 4; + + let bi = 0; + while (bi < bufByteWidth) { + buf.writeUInt32BE(rgba, bi); + bi += 4; + } + while (bi < buf.length) { + buf.copy(buf, bi, 0, bufByteWidth); + bi += bufByteWidth; + } + return this; + } + + /** + * Gets the RGBA number of the pixel at the given coordinate in the form 0xRRGGBBAA, where AA is the alpha value, with alpha 0x00 encoding to transparency in GIFs. + * + * @param {number} x x-coord of pixel + * @param {number} y y-coord of pixel + * @return {number} RGBA of pixel in 0xRRGGBBAA form + */ + + getRGBA(x, y) { + const bi = (y * this.bitmap.width + x) * 4; + return this.bitmap.data.readUInt32BE(bi); + } + + /** + * Gets a set of all RGBA colors found within the image. + * + * @return {Set} Set of all RGBA colors that the image contains. + */ + + getRGBASet() { + const rgbaSet = new Set(); + const buf = this.bitmap.data; + for (let bi = 0; bi < buf.length; bi += 4) { + rgbaSet.add(buf.readUInt32BE(bi, true)); + } + return rgbaSet; + } + + /** + * Converts the image to greyscale using inferred Adobe metrics. + * + * @return {BitmapImage} The present image to allow for chaining. + */ + + greyscale() { + const buf = this.bitmap.data; + this.scan(0, 0, this.bitmap.width, this.bitmap.height, (x, y, idx) => { + const grey = Math.round( + 0.299 * buf[idx] + + 0.587 * buf[idx + 1] + + 0.114 * buf[idx + 2] + ); + buf[idx] = grey; + buf[idx + 1] = grey; + buf[idx + 2] = grey; + }); + return this; + } + + /** + * Reframes the image as if placing a frame around the original image and replacing the original image with the newly framed image. When the new frame is strictly within the boundaries of the original image, this method crops the image. When any of the new boundaries exceed those of the original image, the `fillRGBA` must be provided to indicate the color with which to fill the extra space added to the image. + * + * @param {number} xOffset The x-coord offset of the upper-left pixel of the desired image relative to the present image. + * @param {number} yOffset The y-coord offset of the upper-left pixel of the desired image relative to the present image. + * @param {number} width The width of the new image after reframing + * @param {number} height The height of the new image after reframing + * @param {number} fillRGBA The color with which to fill space added to the image as a result of the reframing, in 0xRRGGBBAA format, where AA is 0x00 to indicate transparent and a non-zero value to indicate opaque. This parameter is only required when the reframing exceeds the original boundaries (i.e. does not simply perform a crop). + * @return {BitmapImage} The present image to allow for chaining. + */ + + reframe(xOffset, yOffset, width, height, fillRGBA) { + const cropX = (xOffset < 0 ? 0 : xOffset); + const cropY = (yOffset < 0 ? 0 : yOffset); + const cropWidth = (width + cropX > this.bitmap.width ? + this.bitmap.width - cropX : width); + const cropHeight = (height + cropY > this.bitmap.height ? + this.bitmap.height - cropY : height); + const newX = (xOffset < 0 ? -xOffset : 0); + const newY = (yOffset < 0 ? -yOffset : 0); + + let image; + if (fillRGBA === undefined) { + if (cropX !== xOffset || cropY != yOffset || + cropWidth !== width || cropHeight !== height) + { + throw new GifError(`fillRGBA required for this reframing`); + } + image = new BitmapImage(width, height); + } + else { + image = new BitmapImage(width, height, fillRGBA); + } + this.blit(image, newX, newY, cropX, cropY, cropWidth, cropHeight); + this.bitmap = image.bitmap; + return this; + } + + /** + * Scales the image size up by an integer factor. Each pixel of the original image becomes a square of the same color in the new image having a size of `factor` x `factor` pixels. + * + * @param {number} factor The factor by which to scale up the image. Must be an integer >= 1. + * @return {BitmapImage} The present image to allow for chaining. + */ + + scale(factor) { + if (factor === 1) { + return; + } + if (!Number.isInteger(factor) || factor < 1) { + throw new Error("the scale must be an integer >= 1"); + } + const sourceWidth = this.bitmap.width; + const sourceHeight = this.bitmap.height; + const destByteWidth = sourceWidth * factor * 4; + const sourceBuf = this.bitmap.data; + const destBuf = new Buffer(sourceHeight * destByteWidth * factor); + let sourceIndex = 0; + let priorDestRowIndex; + let destIndex = 0; + for (let y = 0; y < sourceHeight; ++y) { + priorDestRowIndex = destIndex; + for (let x = 0; x < sourceWidth; ++x) { + const color = sourceBuf.readUInt32BE(sourceIndex, true); + for (let cx = 0; cx < factor; ++cx) { + destBuf.writeUInt32BE(color, destIndex); + destIndex += 4; + } + sourceIndex += 4; + } + for (let cy = 1; cy < factor; ++cy) { + destBuf.copy(destBuf, destIndex, priorDestRowIndex, destIndex); + destIndex += destByteWidth; + priorDestRowIndex += destByteWidth; + } + } + this.bitmap = { + width: sourceWidth * factor, + height: sourceHeight * factor, + data: destBuf + }; + return this; + } + + /** + * Scans all coordinates of the image, handing each in turn to the provided handler function. + * + * @param {function} scanHandler A function(x: number, y: number, bi: number) to be called for each pixel of the image with that pixel's x-coord, y-coord, and index into the `data` buffer. The function accesses the pixel at this coordinate by accessing the `this.data` at index `bi`. + * @see scanAllIndexes + */ + + scanAllCoords(scanHandler) { + const width = this.bitmap.width; + const bufferLength = this.bitmap.data.length; + let x = 0; + let y = 0; + + for (let bi = 0; bi < bufferLength; bi += 4) { + scanHandler(x, y, bi); + if (++x === width) { + x = 0; + ++y; + } + } + } + + /** + * Scans all pixels of the image, handing the index of each in turn to the provided handler function. Runs a bit faster than `scanAllCoords()`, should the handler not need pixel coordinates. + * + * @param {function} scanHandler A function(bi: number) to be called for each pixel of the image with that pixel's index into the `data` buffer. The pixels is found at index 'bi' within `this.data`. + * @see scanAllCoords + */ + + scanAllIndexes(scanHandler) { + const bufferLength = this.bitmap.data.length; + for (let bi = 0; bi < bufferLength; bi += 4) { + scanHandler(bi); + } + } +} + +module.exports = BitmapImage; diff --git a/node_modules/gifwrap/src/gif.js b/node_modules/gifwrap/src/gif.js new file mode 100644 index 0000000000000000000000000000000000000000..c40579a4bee13dcae5972acfef3cc6ec30856916 --- /dev/null +++ b/node_modules/gifwrap/src/gif.js @@ -0,0 +1,69 @@ +'use strict'; + +/** @class Gif */ + +class Gif { + + // width - width of GIF in pixels + // height - height of GIF in pixels + // loops - 0 = unending; (n > 0) = iterate n times + // usesTransparency - whether any frames have transparent pixels + // colorScope - scope of color tables in GIF + // frames - array of frames + // buffer - GIF-formatted data + + /** + * Gif is a class representing an encoded GIF. It is intended to be a read-only representation of a byte-encoded GIF. Only encoders and decoders should be creating instances of this class. + * + * Property | Description + * --- | --- + * width | width of the GIF at its widest + * height | height of the GIF at its highest + * loops | the number of times the GIF should loop before stopping; 0 => loop indefinitely + * usesTransparency | boolean indicating whether at least one frame contains at least one transparent pixel + * colorScope | the scope of the color tables as encoded within the GIF; either Gif.GlobalColorsOnly (== 1) or Gif.LocalColorsOnly (== 2). + * frames | a array of GifFrame instances, one for each frame of the GIF + * buffer | a Buffer holding the encoding's byte data + * + * Its constructor should only ever be called by the GIF encoder or decoder. + * + * @param {Buffer} buffer A Buffer containing the encoded bytes + * @param {GifFrame[]} frames Array of frames found in the encoding + * @param {object} spec Properties of the encoding as listed above + */ + + constructor(buffer, frames, spec) { + this.width = spec.width; + this.height = spec.height; + this.loops = spec.loops; + this.usesTransparency = spec.usesTransparency; + this.colorScope = spec.colorScope; + this.frames = frames; + this.buffer = buffer; + } +} + +Gif.GlobalColorsPreferred = 0; +Gif.GlobalColorsOnly = 1; +Gif.LocalColorsOnly = 2; + +/** @class GifError */ + +class GifError extends Error { + + /** + * GifError is a class representing a GIF-related error + * + * @param {string|Error} messageOrError + */ + + constructor(messageOrError) { + super(messageOrError); + if (messageOrError instanceof Error) { + this.stack = 'Gif' + messageOrError.stack; + } + } +} + +exports.Gif = Gif; +exports.GifError = GifError; diff --git a/node_modules/gifwrap/src/gifcodec.js b/node_modules/gifwrap/src/gifcodec.js new file mode 100644 index 0000000000000000000000000000000000000000..1663542740536f98b990fd14ad8f738625b8ca8d --- /dev/null +++ b/node_modules/gifwrap/src/gifcodec.js @@ -0,0 +1,404 @@ +'use strict'; + +const Omggif = require('omggif'); +const { Gif, GifError } = require('./gif'); + +// allow circular dependency with GifUtil +function GifUtil() { + const data = require('./gifutil'); + + GifUtil = function () { + return data; + }; + + return data; +} + +const { GifFrame } = require('./gifframe'); + +const PER_GIF_OVERHEAD = 200; // these are guesses at upper limits +const PER_FRAME_OVERHEAD = 100; + +// Note: I experimented with accepting a global color table when encoding and returning the global color table when decoding. Doing this properly greatly increased the complexity of the code and the amount of clock cycles required. The main issue is that each frame can specify any color of the global color table to be transparent within the frame, while this GIF library strives to hide GIF formatting details from its clients. E.g. it's possible to have 256 colors in the global color table and different transparencies in each frame, requiring clients to either provide per-frame transparency indexes, or for arcane reasons that won't be apparent to client developers, encode some GIFs with local color tables that previously decoded with global tables. + +/** @class GifCodec */ + +class GifCodec +{ + // _transparentRGBA - RGB given to transparent pixels (alpha=0) on decode; defaults to null indicating 0x000000, which is fastest + + /** + * GifCodec is a class that both encodes and decodes GIFs. It implements both the `encode()` method expected of an encoder and the `decode()` method expected of a decoder, and it wraps the `omggif` GIF encoder/decoder package. GifCodec serves as this library's default encoder and decoder, but it's possible to wrap other GIF encoders and decoders for use by `gifwrap` as well. GifCodec will not encode GIFs with interlacing. + * + * Instances of this class are stateless and can be shared across multiple encodings and decodings. + * + * Its constructor takes one option argument: + * + * @param {object} options Optionally takes an objection whose only possible property is `transparentRGB`. Images are internally represented in RGBA format, where A is the alpha value of a pixel. When `transparentRGB` is provided, this RGB value (excluding alpha) is assigned to transparent pixels, which are also given alpha value 0x00. (All opaque pixels are given alpha value 0xFF). The RGB color of transparent pixels shouldn't matter for most applications. Defaults to 0x000000. + */ + + constructor(options = {}) { + this._transparentRGB = null; // 0x000000 + if (typeof options.transparentRGB === 'number' && + options.transparentRGB !== 0) + { + this._transparentRGBA = options.transparentRGB * 256; + } + this._testInitialBufferSize = 0; // assume no buffer scaling test + } + + /** + * Decodes a GIF from a Buffer to yield an instance of Gif. Transparent pixels of the GIF are given alpha values of 0x00, and opaque pixels are given alpha values of 0xFF. The RGB values of transparent pixels default to 0x000000 but can be overridden by the constructor's `transparentRGB` option. + * + * @param {Buffer} buffer Bytes of an encoded GIF to decode. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + */ + + decodeGif(buffer) { + try { + let reader; + try { + reader = new Omggif.GifReader(buffer); + } + catch (err) { + throw new GifError(err); + } + const frameCount = reader.numFrames(); + const frames = []; + const spec = { + width: reader.width, + height: reader.height, + loops: reader.loopCount() + }; + + spec.usesTransparency = false; + for (let i = 0; i < frameCount; ++i) { + const frameInfo = + this._decodeFrame(reader, i, spec.usesTransparency); + frames.push(frameInfo.frame); + if (frameInfo.usesTransparency) { + spec.usesTransparency = true; + } + } + return Promise.resolve(new Gif(buffer, frames, spec)); + } + catch (err) { + return Promise.reject(err); + } + } + + /** + * Encodes a GIF from provided frames. Each pixel having an alpha value of 0x00 renders as transparent within the encoding, while all pixels of non-zero alpha value render as opaque. + * + * @param {GifFrame[]} frames Array of frames to encode + * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely. Set `loop` to null to disable looping, playing only once. `colorScope` defaults to Gif.GlobalColorsPreferred. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + * @throws {GifError} Error upon encountered an encoding-related problem with a GIF, so that the caller can distinguish between software errors and problems with GIFs. + */ + + encodeGif(frames, spec = {}) { + try { + if (frames === null || frames.length === 0) { + throw new GifError("there are no frames"); + } + const dims = GifUtil().getMaxDimensions(frames); + + spec = Object.assign({}, spec); // don't munge caller's spec + spec.width = dims.maxWidth; + spec.height = dims.maxHeight; + if (spec.loops === undefined) { + spec.loops = 0; + } + spec.colorScope = spec.colorScope || Gif.GlobalColorsPreferred; + + return Promise.resolve(this._encodeGif(frames, spec)); + } + catch (err) { + return Promise.reject(err); + } + } + + _decodeFrame(reader, frameIndex, alreadyUsedTransparency) { + let info, buffer; + try { + info = reader.frameInfo(frameIndex); + buffer = new Buffer(reader.width * reader.height * 4); + reader.decodeAndBlitFrameRGBA(frameIndex, buffer); + if (info.width !== reader.width || info.height !== reader.height) { + if (info.y) { + // skip unused rows + buffer = buffer.slice(info.y * reader.width * 4); + } + if (reader.width > info.width) { + // skip scanstride + for (let ii = 0; ii < info.height; ++ii) { + buffer.copy(buffer, ii * info.width * 4, + (info.x + ii * reader.width) * 4, + (info.x + ii * reader.width) * 4 + info.width * 4); + } + } + // trim buffer to size + buffer = buffer.slice(0, info.width * info.height * 4); + } + } + catch (err) { + throw new GifError(err); + } + + let usesTransparency = false; + if (this._transparentRGBA === null) { + if (!alreadyUsedTransparency) { + for (let i = 3; i < buffer.length; i += 4) { + if (buffer[i] === 0) { + usesTransparency = true; + i = buffer.length; + } + } + } + } + else { + for (let i = 3; i < buffer.length; i += 4) { + if (buffer[i] === 0) { + buffer.writeUInt32BE(this._transparentRGBA, i - 3); + usesTransparency = true; // GIF might encode unused index + } + } + } + + const frame = new GifFrame(info.width, info.height, buffer, { + xOffset: info.x, + yOffset: info.y, + disposalMethod: info.disposal, + interlaced: info.interlaced, + delayCentisecs: info.delay + }); + return { frame, usesTransparency }; + } + + _encodeGif(frames, spec) { + let colorInfo; + if (spec.colorScope === Gif.LocalColorsOnly) { + colorInfo = GifUtil().getColorInfo(frames, 0); + } + else { + colorInfo = GifUtil().getColorInfo(frames, 256); + if (!colorInfo.colors) { // if global palette impossible + if (spec.colorScope === Gif.GlobalColorsOnly) { + throw new GifError( + "Too many color indexes for global color table"); + } + spec.colorScope = Gif.LocalColorsOnly + } + } + spec.usesTransparency = colorInfo.usesTransparency; + + const localPalettes = colorInfo.palettes; + if (spec.colorScope === Gif.LocalColorsOnly) { + const localSizeEst = 2000; //this._getSizeEstimateLocal(localPalettes, frames); + return _encodeLocal(frames, spec, localSizeEst, localPalettes); + } + + const globalSizeEst = 2000; //this._getSizeEstimateGlobal(colorInfo, frames); + return _encodeGlobal(frames, spec, globalSizeEst, colorInfo); + } + + _getSizeEstimateGlobal(globalPalette, frames) { + if (this._testInitialBufferSize > 0) { + return this._testInitialBufferSize; + } + let sizeEst = PER_GIF_OVERHEAD + 3*256 /* max palette size*/; + const pixelBitWidth = _getPixelBitWidth(globalPalette); + frames.forEach(frame => { + sizeEst += _getFrameSizeEst(frame, pixelBitWidth); + }); + return sizeEst; // should be the upper limit + } + + _getSizeEstimateLocal(palettes, frames) { + if (this._testInitialBufferSize > 0) { + return this._testInitialBufferSize; + } + let sizeEst = PER_GIF_OVERHEAD; + for (let i = 0; i < frames.length; ++i ) { + const palette = palettes[i]; + const pixelBitWidth = _getPixelBitWidth(palette); + sizeEst += _getFrameSizeEst(frames[i], pixelBitWidth); + } + return sizeEst; // should be the upper limit + } +} +exports.GifCodec = GifCodec; + +function _colorLookupLinear(colors, color) { + const index = colors.indexOf(color); + return (index === -1 ? null : index); +} + +function _colorLookupBinary(colors, color) { + // adapted from https://stackoverflow.com/a/10264318/650894 + var lo = 0, hi = colors.length - 1, mid; + while (lo <= hi) { + mid = Math.floor((lo + hi)/2); + if (colors[mid] > color) + hi = mid - 1; + else if (colors[mid] < color) + lo = mid + 1; + else + return mid; + } + return null; +} + +function _encodeGlobal(frames, spec, bufferSizeEst, globalPalette) { + // would be inefficient for frames to lookup colors in extended palette + const extendedGlobalPalette = { + colors: globalPalette.colors.slice(), + usesTransparency: globalPalette.usesTransparency + }; + _extendPaletteToPowerOf2(extendedGlobalPalette); + const options = { + palette: extendedGlobalPalette.colors, + loop: spec.loops + }; + let buffer = new Buffer(bufferSizeEst); + let gifWriter; + try { + gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, + options); + } + catch (err) { + throw new GifError(err); + } + for (let i = 0; i < frames.length; ++i) { + buffer = _writeFrame(gifWriter, i, frames[i], globalPalette, false); + } + return new Gif(buffer.slice(0, gifWriter.end()), frames, spec); +} + +function _encodeLocal(frames, spec, bufferSizeEst, localPalettes) { + const options = { + loop: spec.loops + }; + let buffer = new Buffer(bufferSizeEst); + let gifWriter; + try { + gifWriter = new Omggif.GifWriter(buffer, spec.width, spec.height, + options); + } + catch (err) { + throw new GifError(err); + } + for (let i = 0; i < frames.length; ++i) { + buffer = _writeFrame(gifWriter, i, frames[i], localPalettes[i], true); + } + return new Gif(buffer.slice(0, gifWriter.end()), frames, spec); +} + +function _extendPaletteToPowerOf2(palette) { + const colors = palette.colors; + if (palette.usesTransparency) { + colors.push(0); + } + const colorCount = colors.length; + let powerOf2 = 2; + while (colorCount > powerOf2) { + powerOf2 <<= 1; + } + colors.length = powerOf2; + colors.fill(0, colorCount); +} + +function _getFrameSizeEst(frame, pixelBitWidth) { + let byteLength = frame.bitmap.width * frame.bitmap.height; + byteLength = Math.ceil(byteLength * pixelBitWidth / 8); + byteLength += Math.ceil(byteLength / 255); // add block size bytes + // assume maximum palete size because it might get extended for power of 2 + return (PER_FRAME_OVERHEAD + byteLength + 3 * 256 /* largest palette */); +} + +function _getIndexedImage(frameIndex, frame, palette) { + const colors = palette.colors; + const colorToIndexFunc = (colors.length <= 8 ? // guess at the break-even + _colorLookupLinear : _colorLookupBinary); + const colorBuffer = frame.bitmap.data; + const indexBuffer = new Buffer(colorBuffer.length/4); + let transparentIndex = colors.length; + let i = 0, j = 0; + + while (i < colorBuffer.length) { + if (colorBuffer[i + 3] !== 0) { + const color = (colorBuffer.readUInt32BE(i, true) >> 8) & 0xFFFFFF; + // caller guarantees that the color will be in the palette + indexBuffer[j] = colorToIndexFunc(colors, color); + } + else { + indexBuffer[j] = transparentIndex; + } + i += 4; // skip alpha + ++j; + } + + if (palette.usesTransparency) { + if (transparentIndex === 256) { + throw new GifError(`Frame ${frameIndex} already has 256 colors` + + `and so can't use transparency`); + } + } + else { + transparentIndex = null; + } + + return { buffer: indexBuffer, transparentIndex }; +} + +function _getPixelBitWidth(palette) { + let indexCount = palette.indexCount; + let pixelBitWidth = 0; + --indexCount; // start at maximum index + while (indexCount) { + ++pixelBitWidth; + indexCount >>= 1; + } + return (pixelBitWidth > 0 ? pixelBitWidth : 1); +} + +function _writeFrame(gifWriter, frameIndex, frame, palette, isLocalPalette) { + if (frame.interlaced) { + throw new GifError("writing interlaced GIFs is not supported"); + } + const frameInfo = _getIndexedImage(frameIndex, frame, palette); + const options = { + delay: frame.delayCentisecs, + disposal: frame.disposalMethod, + transparent: frameInfo.transparentIndex + }; + if (isLocalPalette) { + _extendPaletteToPowerOf2(palette); // ok 'cause palette never used again + options.palette = palette.colors; + } + try { + let buffer = gifWriter.getOutputBuffer(); + let startOfFrame = gifWriter.getOutputBufferPosition(); + let endOfFrame; + let tryAgain = true; + + while (tryAgain) { + endOfFrame = gifWriter.addFrame(frame.xOffset, frame.yOffset, + frame.bitmap.width, frame.bitmap.height, frameInfo.buffer, options); + tryAgain = false; + if (endOfFrame >= buffer.length - 1) { + const biggerBuffer = new Buffer(buffer.length * 1.5); + buffer.copy(biggerBuffer); + gifWriter.setOutputBuffer(biggerBuffer); + gifWriter.setOutputBufferPosition(startOfFrame); + buffer = biggerBuffer; + tryAgain = true; + } + } + return buffer; + } + catch (err) { + throw new GifError(err); + } +} diff --git a/node_modules/gifwrap/src/gifframe.js b/node_modules/gifwrap/src/gifframe.js new file mode 100644 index 0000000000000000000000000000000000000000..3b56c2698ccf873e04ad1e17a472844b930f79ac --- /dev/null +++ b/node_modules/gifwrap/src/gifframe.js @@ -0,0 +1,114 @@ +'use strict'; + +const BitmapImage = require('./bitmapimage'); +const { GifError } = require('./gif'); + +/** @class GifFrame */ + +class GifFrame extends BitmapImage { + + // xOffset - x offset of bitmap on GIF (defaults to 0) + // yOffset - y offset of bitmap on GIF (defaults to 0) + // disposalMethod - pixel disposal method when handling partial images + // delayCentisecs - duration of frame in hundredths of a second + // interlaced - whether the image is interlaced (defaults to false) + + /** + * GifFrame is a class representing an image frame of a GIF. GIFs contain one or more instances of GifFrame. + * + * Property | Description + * --- | --- + * xOffset | x-coord of position within GIF at which to render the image (defaults to 0) + * yOffset | y-coord of position within GIF at which to render the image (defaults to 0) + * disposalMethod | GIF disposal method; only relevant when the frames aren't all the same size (defaults to 2, disposing to background color) + * delayCentisecs | duration of the frame in hundreths of a second + * interlaced | boolean indicating whether the frame renders interlaced + * + * Its constructor supports the following signatures: + * + * * new GifFrame(bitmap: {width: number, height: number, data: Buffer}, options?) + * * new GifFrame(bitmapImage: BitmapImage, options?) + * * new GifFrame(width: number, height: number, buffer: Buffer, options?) + * * new GifFrame(width: number, height: number, backgroundRGBA?: number, options?) + * * new GifFrame(frame: GifFrame) + * + * See the base class BitmapImage for a discussion of all parameters but `options` and `frame`. `options` is an optional argument providing initial values for the above-listed GifFrame properties. Each property within option is itself optional. + * + * Provide a `frame` to the constructor to create a clone of the provided frame. The new frame includes a copy of the provided frame's pixel data so that each can subsequently be modified without affecting each other. + */ + + constructor(...args) { + super(...args); + if (args[0] instanceof GifFrame) { + // copy a provided GifFrame + const source = args[0]; + this.xOffset = source.xOffset; + this.yOffset = source.yOffset; + this.disposalMethod = source.disposalMethod; + this.delayCentisecs = source.delayCentisecs; + this.interlaced = source.interlaced; + } + else { + const lastArg = args[args.length - 1]; + let options = {}; + if (typeof lastArg === 'object' && !(lastArg instanceof BitmapImage)) { + options = lastArg; + } + this.xOffset = options.xOffset || 0; + this.yOffset = options.yOffset || 0; + this.disposalMethod = (options.disposalMethod !== undefined ? + options.disposalMethod : GifFrame.DisposeToBackgroundColor); + this.delayCentisecs = options.delayCentisecs || 8; + this.interlaced = options.interlaced || false; + } + } + + /** + * Get a summary of the colors found within the frame. The return value is an object of the following form: + * + * Property | Description + * --- | --- + * colors | An array of all the opaque colors found within the frame. Each color is given as an RGB number of the form 0xRRGGBB. The array is sorted by increasing number. Will be an empty array when the image is completely transparent. + * usesTransparency | boolean indicating whether there are any transparent pixels within the frame. A pixel is considered transparent if its alpha value is 0x00. + * indexCount | The number of color indexes required to represent this palette of colors. It is equal to the number of opaque colors plus one if the image includes transparency. + * + * @return {object} An object representing a color palette as described above. + */ + + getPalette() { + // returns with colors sorted low to high + const colorSet = new Set(); + const buf = this.bitmap.data; + let i = 0; + let usesTransparency = false; + while (i < buf.length) { + if (buf[i + 3] === 0) { + usesTransparency = true; + } + else { + // can eliminate the bitshift by starting one byte prior + const color = (buf.readUInt32BE(i, true) >> 8) & 0xFFFFFF; + colorSet.add(color); + } + i += 4; // skip alpha + } + const colors = new Array(colorSet.size); + const iter = colorSet.values(); + for (i = 0; i < colors.length; ++i) { + colors[i] = iter.next().value; + } + colors.sort((a, b) => (a - b)); + let indexCount = colors.length; + if (usesTransparency) { + ++indexCount; + } + return { colors, usesTransparency, indexCount }; + } +} + +GifFrame.DisposeToAnything = 0; +GifFrame.DisposeNothing = 1; +GifFrame.DisposeToBackgroundColor = 2; +GifFrame.DisposeToPrevious = 3; + +exports.GifFrame = GifFrame; diff --git a/node_modules/gifwrap/src/gifutil.js b/node_modules/gifwrap/src/gifutil.js new file mode 100644 index 0000000000000000000000000000000000000000..300ef926fff33f3dffa1b4fb2f519d6684e3bddf --- /dev/null +++ b/node_modules/gifwrap/src/gifutil.js @@ -0,0 +1,373 @@ +'use strict'; + +/** @namespace GifUtil */ + +const fs = require('fs'); +const ImageQ = require('image-q'); + +const BitmapImage = require('./bitmapimage'); +const { GifFrame } = require('./gifframe'); +const { GifError } = require('./gif'); +const { GifCodec } = require('./gifcodec'); + +const INVALID_SUFFIXES = ['.jpg', '.jpeg', '.png', '.bmp']; + +const defaultCodec = new GifCodec(); + +/** + * cloneFrames() clones provided frames. It's a utility method for cloning an entire array of frames at once. + * + * @function cloneFrames + * @memberof GifUtil + * @param {GifFrame[]} frames An array of GifFrame instances to clone + * @return {GifFrame[]} An array of GifFrame clones of the provided frames. + */ + +exports.cloneFrames = function (frames) { + let clones = []; + frames.forEach(frame => { + + clones.push(new GifFrame(frame)); + }); + return clones; +} + +/** + * getColorInfo() gets information about the colors used in the provided frames. The method is able to return an array of all colors found across all frames. + * + * `maxGlobalIndex` controls whether the computation short-circuits to avoid doing work that the caller doesn't need. The method only returns `colors` and `indexCount` for the colors across all frames when the number of indexes required to store the colors and transparency in a GIF (which is the value of `indexCount`) is less than or equal to `maxGlobalIndex`. Such short-circuiting is useful when the caller just needs to determine whether any frame includes transparency. + * + * @function getColorInfo + * @memberof GifUtil + * @param {GifFrame[]} frames Frames to examine for color and transparency. + * @param {number} maxGlobalIndex Maximum number of color indexes (including one for transparency) allowed among the returned compilation of colors. `colors` and `indexCount` are not returned if the number of color indexes required to accommodate all frames exceeds this number. Returns `colors` and `indexCount` by default. + * @returns {object} Object containing at least `palettes` and `usesTransparency`. `palettes` is an array of all the palettes returned by GifFrame#getPalette(). `usesTransparency` indicates whether at least one frame uses transparency. If `maxGlobalIndex` is not exceeded, the object also contains `colors`, an array of all colors (RGB) found across all palettes, sorted by increasing value, and `indexCount` indicating the number of indexes required to store the colors and the transparency in a GIF. + * @throws {GifError} When any frame requires more than 256 color indexes. + */ + +exports.getColorInfo = function (frames, maxGlobalIndex) { + let usesTransparency = false; + const palettes = []; + for (let i = 0; i < frames.length; ++i) { + let palette = frames[i].getPalette(); + if (palette.usesTransparency) { + usesTransparency = true; + } + if (palette.indexCount > 256) { + throw new GifError(`Frame ${i} uses more than 256 color indexes`); + } + palettes.push(palette); + } + if (maxGlobalIndex === 0) { + return { usesTransparency, palettes }; + } + + const globalColorSet = new Set(); + palettes.forEach(palette => { + + palette.colors.forEach(color => { + + globalColorSet.add(color); + }); + }); + let indexCount = globalColorSet.size; + if (usesTransparency) { + // odd that GIF requires a color table entry at transparent index + ++indexCount; + } + if (maxGlobalIndex && indexCount > maxGlobalIndex) { + return { usesTransparency, palettes }; + } + + const colors = new Array(globalColorSet.size); + const iter = globalColorSet.values(); + for (let i = 0; i < colors.length; ++i) { + colors[i] = iter.next().value; + } + colors.sort((a, b) => (a - b)); + return { colors, indexCount, usesTransparency, palettes }; +}; + +/** + * copyAsJimp() returns a Jimp that contains a copy of the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the Jimp does not affect the provided bitmap image. This method serves as a macro for simplifying working with Jimp. + * + * @function copyAsJimp + * @memberof GifUtil + * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp. + * @param {bitmapImageToCopy} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp. + * @return {object} An new instance of Jimp containing a copy of the image in bitmapImageToCopy. + */ + +exports.copyAsJimp = function (jimp, bitmapImageToCopy) { + return exports.shareAsJimp(jimp, new BitmapImage(bitmapImageToCopy)); +}; + +/** + * getMaxDimensions() returns the pixel width and height required to accommodate all of the provided frames, according to the offsets and dimensions of each frame. + * + * @function getMaxDimensions + * @memberof GifUtil + * @param {GifFrame[]} frames Frames to measure for their aggregate maximum dimensions. + * @return {object} An object of the form {maxWidth, maxHeight} indicating the maximum width and height required to accommodate all frames. + */ + +exports.getMaxDimensions = function (frames) { + let maxWidth = 0, maxHeight = 0; + frames.forEach(frame => { + const width = frame.xOffset + frame.bitmap.width; + if (width > maxWidth) { + maxWidth = width; + } + const height = frame.yOffset + frame.bitmap.height; + if (height > maxHeight) { + maxHeight = height; + } + }); + return { maxWidth, maxHeight }; +}; + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Anthony Dekker. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * The method may increase the number of colors if there are fewer than the provided maximum. + * + * @function quantizeDekker + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {object} dither (optional) An object configuring the dithering to apply. The properties are as followings, imported from the [`image-q` package](https://github.com/ibezkrovnyi/image-quantization) without explanation: { `ditherAlgorithm`: One of 'FloydSteinberg', 'FalseFloydSteinberg', 'Stucki', 'Atkinson', 'Jarvis', 'Burkes', 'Sierra', 'TwoSierra', 'SierraLite'; `minimumColorDistanceToDither`: (optional) A number defaulting to 0; `serpentine`: (optional) A boolean defaulting to true; `calculateErrorLikeGIMP`: (optional) A boolean defaulting to false. } + */ + +exports.quantizeDekker = function (imageOrImages, maxColorIndexes, dither) { + maxColorIndexes = maxColorIndexes || 256; + _quantize(imageOrImages, 'NeuQuantFloat', maxColorIndexes, 0, dither); +} + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Leon Sorokin. This quantization method differs from the other two by likely never increasing the number of colors, should there be fewer than the provided maximum. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * @function quantizeSorokin + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {string} histogram (optional) Histogram method: 'top-pop' for global top-population, 'min-pop' for minimum-population threshhold within subregions. Defaults to 'min-pop'. + * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. + */ + +exports.quantizeSorokin = function (imageOrImages, maxColorIndexes, histogram, dither) { + maxColorIndexes = maxColorIndexes || 256; + histogram = histogram || 'min-pop'; + let histogramID; + switch (histogram) { + case 'min-pop': + histogramID = 2; + break; + + case 'top-pop': + histogramID = 1; + break + + default: + throw new Error(`Invalid quantizeSorokin histogram '${histogram}'`); + } + _quantize(imageOrImages, 'RGBQuant', maxColorIndexes, histogramID, dither); +} + +/** + * Quantizes colors so that there are at most a given number of color indexes (including transparency) across all provided images. Uses an algorithm by Xiaolin Wu. + * + * The method treats different RGBA combinations as different colors, so if the frame has multiple alpha values or multiple RGB values for an alpha value, the caller may first want to normalize them by converting all transparent pixels to the same RGBA values. + * + * The method may increase the number of colors if there are fewer than the provided maximum. + * + * @function quantizeWu + * @memberof GifUtil + * @param {BitmapImage|BitmapImage[]} imageOrImages Image or array of images (such as GifFrame instances) to be color-quantized. Quantizing across multiple images ensures color consistency from frame to frame. + * @param {number} maxColorIndexes The maximum number of color indexes that will exist in the palette after completing quantization. Defaults to 256. + * @param {number} significantBits (optional) This is the number of significant high bits in each RGB color channel. Takes integer values from 1 through 8. Higher values correspond to higher quality. Defaults to 5. + * @param {object} dither (optional) An object configuring the dithering to apply, as explained for `quantizeDekker()`. + */ + +exports.quantizeWu = function (imageOrImages, maxColorIndexes, significantBits, dither) { + maxColorIndexes = maxColorIndexes || 256; + significantBits = significantBits || 5; + if (significantBits < 1 || significantBits > 8) { + throw new Error("Invalid quantization quality"); + } + _quantize(imageOrImages, 'WuQuant', maxColorIndexes, significantBits, dither); +} + +/** + * read() decodes an encoded GIF, whether provided as a filename or as a byte buffer. + * + * @function read + * @memberof GifUtil + * @param {string|Buffer} source Source to decode. When a string, it's the GIF filename to load and parse. When a Buffer, it's an encoded GIF to parse. + * @param {object} decoder An optional GIF decoder object implementing the `decode` method of class GifCodec. When provided, the method decodes the GIF using this decoder. When not provided, the method uses GifCodec. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the decoded GIF. + */ + +exports.read = function (source, decoder) { + decoder = decoder || defaultCodec; + if (Buffer.isBuffer(source)) { + return decoder.decodeGif(source); + } + return _readBinary(source) + .then(buffer => { + + return decoder.decodeGif(buffer); + }); +}; + +/** + * shareAsJimp() returns a Jimp that shares a bitmap with the provided bitmap image (which may be either a BitmapImage or a GifFrame). Modifying the image in either the Jimp or the BitmapImage affects the other objects. This method serves as a macro for simplifying working with Jimp. + * + * @function shareAsJimp + * @memberof GifUtil + * @param {object} Reference to the Jimp package, keeping this library from being dependent on Jimp. + * @param {bitmapImageToShare} Instance of BitmapImage (may be a GifUtil) with which to source the Jimp. + * @return {object} An new instance of Jimp that shares the image in bitmapImageToShare. + */ + +exports.shareAsJimp = function (jimp, bitmapImageToShare) { + const jimpImage = new jimp(bitmapImageToShare.bitmap.width, + bitmapImageToShare.bitmap.height, 0); + jimpImage.bitmap.data = bitmapImageToShare.bitmap.data; + return jimpImage; +}; + +/** + * write() encodes a GIF and saves it as a file. + * + * @function write + * @memberof GifUtil + * @param {string} path Filename to write GIF out as. Will overwrite an existing file. + * @param {GifFrame[]} frames Array of frames to be written into GIF. + * @param {object} spec An optional object that may provide values for `loops` and `colorScope`, as defined for the Gif class. However, `colorSpace` may also take the value Gif.GlobalColorsPreferred (== 0) to indicate that the encoder should attempt to create only a global color table. `loop` defaults to 0, looping indefinitely, and `colorScope` defaults to Gif.GlobalColorsPreferred. + * @param {object} encoder An optional GIF encoder object implementing the `encode` method of class GifCodec. When provided, the method encodes the GIF using this encoder. When not provided, the method uses GifCodec. + * @return {Promise} A Promise that resolves to an instance of the Gif class, representing the encoded GIF. + */ + +exports.write = function (path, frames, spec, encoder) { + encoder = encoder || defaultCodec; + const matches = path.match(/\.[a-zA-Z]+$/); // prevent accidents + if (matches !== null && + INVALID_SUFFIXES.includes(matches[0].toLowerCase())) + { + throw new Error(`GIF '${path}' has an unexpected suffix`); + } + + return encoder.encodeGif(frames, spec) + .then(gif => { + + return _writeBinary(path, gif.buffer) + .then(() => { + + return gif; + }); + }); +}; + +function _quantize(imageOrImages, method, maxColorIndexes, modifier, dither) { + const images = Array.isArray(imageOrImages) ? imageOrImages : [imageOrImages]; + const ditherAlgs = [ + 'FloydSteinberg', + 'FalseFloydSteinberg', + 'Stucki', + 'Atkinson', + 'Jarvis', + 'Burkes', + 'Sierra', + 'TwoSierra', + 'SierraLite' + ]; + + if (dither) { + if (ditherAlgs.indexOf(dither.ditherAlgorithm) < 0) { + throw new Error(`Invalid ditherAlgorithm '${dither.ditherAlgorithm}'`); + } + if (dither.serpentine === undefined) { + dither.serpentine = true; + } + if (dither.minimumColorDistanceToDither === undefined) { + dither.minimumColorDistanceToDither = 0; + } + if (dither.calculateErrorLikeGIMP === undefined) { + dither.calculateErrorLikeGIMP = false; + } + } + + const distCalculator = new ImageQ.distance.Euclidean(); + const quantizer = new ImageQ.palette[method](distCalculator, maxColorIndexes, modifier); + let imageMaker; + if (dither) { + imageMaker = new ImageQ.image.ErrorDiffusionArray( + distCalculator, + ImageQ.image.ErrorDiffusionArrayKernel[dither.ditherAlgorithm], + dither.serpentine, + dither.minimumColorDistanceToDither, + dither.calculateErrorLikeGIMP + ); + } + else { + imageMaker = new ImageQ.image.NearestColor(distCalculator); + } + + const inputContainers = []; + images.forEach(image => { + + const imageBuf = image.bitmap.data; + const inputBuf = new ArrayBuffer(imageBuf.length); + const inputArray = new Uint32Array(inputBuf); + for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) { + inputArray[ai] = imageBuf.readUInt32LE(bi, true); + } + const inputContainer = ImageQ.utils.PointContainer.fromUint32Array( + inputArray, image.bitmap.width, image.bitmap.height); + quantizer.sample(inputContainer); + inputContainers.push(inputContainer); + }); + + const limitedPalette = quantizer.quantizeSync(); + + for (let i = 0; i < images.length; ++i) { + const imageBuf = images[i].bitmap.data; + const outputContainer = imageMaker.quantizeSync(inputContainers[i], limitedPalette); + const outputArray = outputContainer.toUint32Array(); + for (let bi = 0, ai = 0; bi < imageBuf.length; bi += 4, ++ai) { + imageBuf.writeUInt32LE(outputArray[ai], bi); + } + } +} + +function _readBinary(path) { + // TBD: add support for URLs + return new Promise((resolve, reject) => { + + fs.readFile(path, (err, buffer) => { + + if (err) { + return reject(err); + } + return resolve(buffer); + }); + }); +} + +function _writeBinary(path, buffer) { + // TBD: add support for URLs + return new Promise((resolve, reject) => { + + fs.writeFile(path, buffer, err => { + + if (err) { + return reject(err); + } + return resolve(); + }); + }); +} diff --git a/node_modules/gifwrap/src/index.js b/node_modules/gifwrap/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7f367ecc4fe31fb4d7ffdccb5f2589e4c416acb6 --- /dev/null +++ b/node_modules/gifwrap/src/index.js @@ -0,0 +1,16 @@ +'use strict'; + +const BitmapImage = require('./bitmapimage'); +const { Gif, GifError } = require('./gif'); +const { GifCodec } = require('./gifcodec'); +const { GifFrame } = require('./gifframe'); +const GifUtil = require('./gifutil'); + +module.exports = { + BitmapImage, + Gif, + GifCodec, + GifFrame, + GifUtil, + GifError +}; diff --git a/node_modules/gifwrap/src/omggif.d.ts b/node_modules/gifwrap/src/omggif.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96f5248a7791111823e6bbc16dd2b231d60d179a --- /dev/null +++ b/node_modules/gifwrap/src/omggif.d.ts @@ -0,0 +1,56 @@ + +export type ByteArray = Uint8Array | Buffer; + +export interface OmggifModule { + GifWriter: GifWriter; + GifReader: GifReader; +} + +export interface GlobalOptions { + loop?: number; // 0 = unending loop; n > 0 = (n+1) iterations; null = once + palette?: number[]; // global palette RGB by color index + background?: number; // background index; most browsers may ignore this +} + +export interface FrameOptions { + palette?: number[]; // RGB by color index + delay?: number; // duation in 100s of a second + disposal?: number; // what to do with background color (0-3) + transparent?: number; // transparency index +} + +export interface GifWriter { + new (buffer: ByteArray, width: number, height: number, gopts?: GlobalOptions): GifWriter; + addFrame(x: number, y: number, width: number, height: number, indexedPixels: number[], opts?: FrameOptions): number; // returns size of buffer at end of frame + getOutputBuffer(): ByteArray; + setOutputBuffer(buffer: ByteArray): void; + getOutputBufferPosition(): number; + setOutputBufferPosition(position: number): void; + end(): number; // ends GIF and returns size of buffer +} + +export interface GifReader { + width: number; + height: number; + new (buffer: ByteArray): GifReader; + numFrames(): number; + loopCount(): number; + frameInfo(frameNumber: number): FrameInfo; + decodeAndBlitFrameBGRA(frameNumber: number, pixels: number[]): void; + decodeAndBlitFrameRGBA(frameNumber: number, pixels: number[]): void; +} + +export interface FrameInfo { + x: number; + y: number; + width: number; + height: number; + has_local_palette: boolean; + palette_offset: number; + data_offset: number; + data_length: number; + transparent_index: number; + interlaced: boolean; + delay: number; // 100ths of a second + disposal: number; +} diff --git a/node_modules/gifwrap/templates/README.hbs b/node_modules/gifwrap/templates/README.hbs new file mode 100644 index 0000000000000000000000000000000000000000..c8aadc96b8265423c940613662801d4df624ea89 --- /dev/null +++ b/node_modules/gifwrap/templates/README.hbs @@ -0,0 +1,267 @@ +# gifwrap + +A Jimp-compatible library for working with GIFs + +## Overview + +`gifwrap` is a minimalist library for working with GIFs in Javascript, supporting both single- and multi-frame GIFs. It reads GIFs into an internal representation that's easy to work with and allows for making GIFs from scratch. The frame class is structured to make it easy to move images between [`Jimp`](https://github.com/oliver-moran/jimp) and `gifwrap` for more sophisticated image manipulation in `Jimp`, but the module has no dependency on `Jimp`. + +The library uses Dean McNamee's [`omggif`](https://github.com/deanm/omggif) GIF encoder/decoder by default, but it employs an abstraction that allows using other encoders and decoders as well, once suitably wrapped. + +At present, the module only works in Node.js. Includes Typescript typings. + +## Installation + +``` +npm install gifwrap --save +``` + +or + +``` +yarn add gifwrap +``` + +## Usage + +You can work with either GIF files or GIF encodings, and you can create GIFs from scratch. + +The GifFrame class represents a single image frame, and the library largely represents a GIF as an array of GifFrame instances. For example, here is how you create a GIF from scratch: + +```js +const { GifFrame, GifUtil, GifCodec } = require('gifwrap'); +const width = 200, height = 100; +const frames = []; + +let frame = new GifFrame(width, height, { delayCentisecs: 10 }); +// modify the pixels at frame.bitmap.data +frames.push(frame); +frame = new GifFrame(width, height, { delayCentisecs: 15 }); +// modify the pixels at frame.bitmap.data +frames.push(frame); +// add more frames as desired... + +// to write to a file... +GifUtil.write("my-creation.gif", frames, { loops: 3 }).then(gif => { + console.log("written"); +}); + +// to get the byte encoding without writing to a file... +const codec = new GifCodec(); +codec.encodeGif(frames, { loops: 3 }).then(gif => { + // byte encoding is now in gif.buffer +}); + +``` + +Images are represented within a GifFrame exactly as they are in a `Jimp` image. In particular, each GifFrame instance has a `bitmap` property having the following structure: + +* `frame.bitmap.width` - Width of image in pixels +* `frame.bitmap.height` - Height of image in pixels +* `frame.bitmap.data` - A Node.js Buffer that can be accessed like an array of bytes. Every 4 adjacent bytes represents the RGBA values of a single pixel. These 4 bytes correspond to red, green, blue, and alpha, in that order. Each pixel begins at an index that is a multiple of 4. + +GIFs do not support partial transparency, so within `frame.bitmap.data`, pixels having alpha value 0x00 are treated as transparent and pixels of non-zero alpha value are treated as opaque. The encoder ignores the RGB values of transparent pixels. + +`gifwrap` also provides utilities for reading GIF files and for parsing raw encodings: + +```js +const { GifUtil } = require('gifwrap'); +GifUtil.read("fancy.gif").then(inputGif => { + + inputGif.frames.forEach(frame => { + + const buf = frame.bitmap.data; + frame.scanAllCoords((x, y, bi) => { + + // Halve all grays on right half of image. + + if (x > inputGif.width / 2) { + const r = buf[bi]; + const g = buf[bi + 1]; + const b = buf[bi + 2]; + const a = buf[bi + 3]; + if (r === g && r === b && a === 0xFF) { + buf[bi] /= 2; + buf[bi + 1] /= 2; + buf[bi + 2] /= 2; + } + } + }); + }); + + // Pass inputGif to write() to preserve the original GIF's specs. + return GifUtil.write("modified.gif", inputGif.frames, inputGif).then(outputGif => { + console.log("modified"); + }); +}); +``` + +```js +const { GifUtil, GifCodec } = require('gifwrap'); +const codec = new GifCodec(); +const byteEncodingBuffer = getByteEncodingForSomeGif(); + +codec.decodeGif(byteEncodingBuffer).then(sourceGif => { + + const edgeLength = Math.min(sourceGif.width, sourceGif.height); + sourceGif.frames.forEach(frame => { + + // Make each frame a centered square of size edgeLength x edgeLength. + // Note that frames may vary in size and that reframe() works even if + // the frame's image is smaller than the square. Should this happen, + // the space surrounding the original image will be transparent. + + const xOffset = (frame.bitmap.width - edgeLength)/2; + const yOffset = (frame.bitmap.height - edgeLength)/2; + frame.reframe(xOffset, yOffset, edgeLength, edgeLength); + }); + + // The encoder determines GIF size from the frames, not the provided spec (sourceGif). + return GifUtil.write("modified.gif", sourceGif.frames, sourceGif).then(outputGif => { + console.log("modified"); + }); +}); +``` + +Notice that both encoding and decoding yields a GIF object. This is an instance of class Gif, and it provides information about the GIF, such as its size and how many times it loops. Notice also that you never call the Gif constructor to create a GIF. Instead, GIFs are created by providing a GifFrame array and a specification of GIF options. That specification is a subset of the properties of a Gif, so you can pass a previously-loaded Gif as a specification when writing or encoding. The encoder only uses the properties that can't be inferred from the frames -- namely, how many times the GIF loops and how to attempt to package the color tables within the encoding. + +## Leveraging Jimp + +This module was originally written as a wrapper around Jimp images -- hence its name -- and then with frames as subclasses of Jimp images. Neither approach worked out well. The final approach requires just a tad of legwork to use `gifwrap` images within Jimp. + +Both Jimp images and GifFrame instances share the `bitmap` property. By transferring this property back and forth between Jimp images and GifFrame instances, an image can be moved back and forth between the two libraries. + +You can construct a GifFrame from a Jimp image as follows: + +```js +const { BitmapImage, GifFrame } = require('gifwrap'); +const Jimp = require('jimp'); +const j = new Jimp(200, 100, 0xFFFFFFFF); + +// create a frame clone of a Jip bitmap +const fCopied = new GifFrame(new BitmapImage(j.bitmap)); + +// create a frame that shares a bitmap with Jimp (one way) +const fShared1 = new GifFrame(j.bitmap); + +// create a frame that shares a bitmap with Jimp (another way) +const fShared2 = new GifFrame(1, 1, 0); // any GifFrame +fShared2.bitmap = j.bitmap; +``` + +And you can construct a Jimp instance from a GifFrame image as follows: + +```js +const { BitmapImage, GifFrame } = require('gifwrap'); +const Jimp = require('jimp'); +const frame = new GifFrame(200, 100, 0xFFFFFFFF); + +// create a Jimp containing a clone of the frame bitmap +jimpCopied = GifUtil.copyAsJimp(Jimp, frame); + +// create a Jimp that shares a bitmap with the frame +jimpShared = GifUtil.shareAsJimp(Jimp, frame); +``` + +## Encoders and Decoders + +`gifwrap` provides a default GIF encoder/decoder, but it is architected to be able to work with other encoders and decoders. The encoder and decoder may even be separate implementations. Encoders and decoders have varying capabilities, performance measures, and levels of reliability. + +GifCodec is the default implementation, and it's both an encoder and a decoder. It's an adapter that wraps the [`omggif`](https://github.com/deanm/omggif) module. `omggif` appears to support a broad variety of GIFs, although it cannot produce an interlaced encoding (which there is little need for anyway). Although `omggif` doesn't include a test suite at present, `gifwrap`'s test suite happens to test it reasonably well by virtue of using `omggif` underneath. + +An encoder need only implement GifCodec's [`encodeGif()`](#GifCodec+encodeGif) method, and a decoder need only implement its [`decodeGif()`](#GifCodec+decodeGif) method. See the descriptions of those methods for the requirement details. Although GifCodec is stateless, so that instances an be reused across multiple encodings and decodings, third party encoders and decoders need not be. However, applications that use the library with stateful encoders will need to be aware of the need to create new instances. + +To use a third-party encoder or decoder with the GifUtil `write()` and `read()` functions, just pass an instance of the encoder or decoder as the last parameter to `write()` or `read()`, respectively. For example: + +```js +const { GifUtil } = require('gifwrap'); +const SnazzyDecoder = require('gifwrap-snazzy-decoder'); +const AwesomeEncoder = require('gifwrap-awesome-encoder'); + +GifUtil.read("fancy.gif", new SnazzyDecoder()).then(gif => + + /*...*/ + + return GifUtil.write("modified.gif", gif.frames, gif, new AwesomeEncoder()).then(newGif => { + console.log("modified"); + }); +}); +``` + +## API Reference + +The [Typescript typings](https://github.com/jtlapp/gifwrap/blob/master/index.d.ts) provide an exact specification of the API and also serve as a cheat sheet. The classes and namespaces follow: + +* **gifwrap** + + * [.**Gif**](#new_Gif_new) + * [.**BitmapImage**](#BitmapImage) + * [.**GifFrame**](#GifFrame) + * [.**GifUtil**](#GifUtil) + * [.**GifCodec**](#GifCodec) + * [.**GifError**](#new_GifError_new) + +{{#class name="Gif"}} +{{>body~}} +{{>member-index~}} +{{/class}} +{{#class name="BitmapImage"}} +{{>body~}} +{{>member-index~}} +{{/class}} +{{#class name="GifFrame"}} +{{>body~}} +{{>member-index~}} +{{/class}} +{{#namespace name="GifUtil"}} +{{>body~}} +{{>member-index~}} +{{/namespace}} +{{#class name="GifCodec"}} +{{>body~}} +{{>member-index~}} +{{/class}} + +{{#class name="Gif"}} +{{>members~}} +{{/class}} +{{#class name="BitmapImage"}} +{{>members~}} +{{/class}} +{{#class name="GifFrame"}} +{{>members~}} +{{/class}} +{{#namespace name="GifUtil"}} +{{>members~}} +{{/namespace}} +{{#class name="GifCodec"}} +{{>members~}} +{{/class}} +{{#class name="GifError"}} +{{>body~}} +{{>members~}} +{{/class}} + +## LICENSE + +MIT License + +Copyright © 2017 Joseph T. Lapp + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gifwrap/test/fixtures/count5x7.gif b/node_modules/gifwrap/test/fixtures/count5x7.gif new file mode 100644 index 0000000000000000000000000000000000000000..df10bd664f1c8b18182ff51ad46e7dbf1d95e484 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/count5x7.gif differ diff --git a/node_modules/gifwrap/test/fixtures/countConstantDelay0.gif b/node_modules/gifwrap/test/fixtures/countConstantDelay0.gif new file mode 100644 index 0000000000000000000000000000000000000000..10ec9cbd6f9519c6ec93a257e3293c989d8d8057 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/countConstantDelay0.gif differ diff --git a/node_modules/gifwrap/test/fixtures/countConstantDelay1.gif b/node_modules/gifwrap/test/fixtures/countConstantDelay1.gif new file mode 100644 index 0000000000000000000000000000000000000000..11cafff19a2989184f4bf2149d94d7fe848b0ff8 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/countConstantDelay1.gif differ diff --git a/node_modules/gifwrap/test/fixtures/countConstantDelay3.gif b/node_modules/gifwrap/test/fixtures/countConstantDelay3.gif new file mode 100644 index 0000000000000000000000000000000000000000..ac2c6ec5dc7e288d7c1f098cb90b573473944770 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/countConstantDelay3.gif differ diff --git a/node_modules/gifwrap/test/fixtures/countIncreasingDelay.gif b/node_modules/gifwrap/test/fixtures/countIncreasingDelay.gif new file mode 100644 index 0000000000000000000000000000000000000000..48ede158ba2edad8c1cd3b1426401eaffb20fceb Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/countIncreasingDelay.gif differ diff --git a/node_modules/gifwrap/test/fixtures/hairstreak.jpg b/node_modules/gifwrap/test/fixtures/hairstreak.jpg new file mode 100644 index 0000000000000000000000000000000000000000..4a24fb94677aa2410fc05441f2ede2994c01d0c3 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/hairstreak.jpg differ diff --git a/node_modules/gifwrap/test/fixtures/lenna.png b/node_modules/gifwrap/test/fixtures/lenna.png new file mode 100644 index 0000000000000000000000000000000000000000..e9ad1e0275b0e6dae2fe6eacfc7a669e59ebfd93 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/lenna.png differ diff --git a/node_modules/gifwrap/test/fixtures/nburling-public.gif b/node_modules/gifwrap/test/fixtures/nburling-public.gif new file mode 100644 index 0000000000000000000000000000000000000000..eb5cc76d40691654293784634fdf4cf4728bc2f7 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/nburling-public.gif differ diff --git a/node_modules/gifwrap/test/fixtures/pelagrina.jpg b/node_modules/gifwrap/test/fixtures/pelagrina.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f2b63ac3be0cfb662e3deeb7c4f305144961b67a Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/pelagrina.jpg differ diff --git a/node_modules/gifwrap/test/fixtures/penguins.png b/node_modules/gifwrap/test/fixtures/penguins.png new file mode 100644 index 0000000000000000000000000000000000000000..c63f39ce8bdaef4dd33b5dbdb0b425418a0abf05 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/penguins.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..368d33901bccac77ffb200db1810b6a897f78511 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..d9ca126dea37696835899c255caae02f2ac01aee Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..c960ae3c76a809251fdb0adbb9b5bb0f10dc89a7 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak256_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..2b61328e5a6a91e1a8a9c1ba205ae2c40e97bcbd Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..97df5720fba1e0c7fab0a75d91e8b7af85b400f4 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..49de327ff681e21df38e66b7a665a18b6a93400d Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/hairstreak32_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..888266a3d76a55b103df0b0664e59484552512a8 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..e2bd88a240c30cc82add0aa3a1798748f201c87f Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..e10a146ed17cbc84ffd20cd4d5578f2d4af244d8 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans256_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..7775a8249e929ee0b2cab100c9c3bbe78286e516 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..47c578713d65b9cd4efee12a17242f077766a4c0 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..3a0ee317a2c5afa85e8fa96a35138c2339b6fb65 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/rosewithtrans32_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..f1371b09fec94f2dd0467e11666825aef2a3ca7a Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker_FloydSteinberg.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker_FloydSteinberg.png new file mode 100644 index 0000000000000000000000000000000000000000..ad5e22fc829b6179678e124410687b0cb875edba Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Dekker_FloydSteinberg.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..ee28e6183d3d0ba4a9eb2d0d498ab740d9b9a52e Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png new file mode 100644 index 0000000000000000000000000000000000000000..2495c7987f31a80581c7b80a6e1f1d6eb52dfb15 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Sorokin_FloydSteinberg.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..9b545cb4c4a674e1124aa54f208741ffe8b62e4c Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu_FloydSteinberg.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu_FloydSteinberg.png new file mode 100644 index 0000000000000000000000000000000000000000..dcdfa0d31f659ac45fce00620c8644ceb8f7e397 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap256_Wu_FloydSteinberg.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Dekker.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Dekker.png new file mode 100644 index 0000000000000000000000000000000000000000..8cca0aa91e2f4f9f0125713b14a4410e9b19fa0a Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Dekker.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Sorokin.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Sorokin.png new file mode 100644 index 0000000000000000000000000000000000000000..a71ce74e8a2254cc5d755e16d03dae8d250a1441 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Sorokin.png differ diff --git a/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Wu.png b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Wu.png new file mode 100644 index 0000000000000000000000000000000000000000..791031d9262209208e4aebee624e9c1d2a0cd2ea Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/quantized/sculptmap32_Wu.png differ diff --git a/node_modules/gifwrap/test/fixtures/rnaples-frame-10.png b/node_modules/gifwrap/test/fixtures/rnaples-frame-10.png new file mode 100644 index 0000000000000000000000000000000000000000..88c90d49540d5317a99e4b5d42fca7c127b01316 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/rnaples-frame-10.png differ diff --git a/node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif b/node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif new file mode 100644 index 0000000000000000000000000000000000000000..51725817e2d6fc600f2d102907aebcc971452ba6 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/rnaples-offsets-public.gif differ diff --git a/node_modules/gifwrap/test/fixtures/rosewithtrans.png b/node_modules/gifwrap/test/fixtures/rosewithtrans.png new file mode 100644 index 0000000000000000000000000000000000000000..19fbc3328666ff662c4dc2286ab698774e8a6688 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/rosewithtrans.png differ diff --git a/node_modules/gifwrap/test/fixtures/sculptmap.png b/node_modules/gifwrap/test/fixtures/sculptmap.png new file mode 100644 index 0000000000000000000000000000000000000000..178e669421eea8865fa8a8dfc26dd575a8a90e2a Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/sculptmap.png differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameBWOpaque.gif b/node_modules/gifwrap/test/fixtures/singleFrameBWOpaque.gif new file mode 100644 index 0000000000000000000000000000000000000000..c3f9e4443eed750346c66d10dc6d4d363eb6efc3 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameBWOpaque.gif differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameMonoOpaque.gif b/node_modules/gifwrap/test/fixtures/singleFrameMonoOpaque.gif new file mode 100644 index 0000000000000000000000000000000000000000..8010dc004a1eecf627c90236128f2258778e5dfc Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameMonoOpaque.gif differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameMonoTrans.gif b/node_modules/gifwrap/test/fixtures/singleFrameMonoTrans.gif new file mode 100644 index 0000000000000000000000000000000000000000..70458e1773e24ac8c69af78110358819ec55d056 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameMonoTrans.gif differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameMultiOpaque.gif b/node_modules/gifwrap/test/fixtures/singleFrameMultiOpaque.gif new file mode 100644 index 0000000000000000000000000000000000000000..3e09173e1a1dd9769b5ea8311258dd3503c356af Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameMultiOpaque.gif differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameMultiTrans.gif b/node_modules/gifwrap/test/fixtures/singleFrameMultiTrans.gif new file mode 100644 index 0000000000000000000000000000000000000000..f4c0a976b967e89885e77aa506e0c61c093dd9a9 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameMultiTrans.gif differ diff --git a/node_modules/gifwrap/test/fixtures/singleFrameNoColorTrans.gif b/node_modules/gifwrap/test/fixtures/singleFrameNoColorTrans.gif new file mode 100644 index 0000000000000000000000000000000000000000..5c72d0c54bc45b2ea5799f8429b799d77e569b30 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/singleFrameNoColorTrans.gif differ diff --git a/node_modules/gifwrap/test/fixtures/threeFrameMonoTrans.gif b/node_modules/gifwrap/test/fixtures/threeFrameMonoTrans.gif new file mode 100644 index 0000000000000000000000000000000000000000..396d5f316f79454606aa3d098a29e300d9e1aa10 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/threeFrameMonoTrans.gif differ diff --git a/node_modules/gifwrap/test/fixtures/twoFrameMultiOpaque.gif b/node_modules/gifwrap/test/fixtures/twoFrameMultiOpaque.gif new file mode 100644 index 0000000000000000000000000000000000000000..0d7cf9e34064e4e2db89fb8190237e60e9f5bcf6 Binary files /dev/null and b/node_modules/gifwrap/test/fixtures/twoFrameMultiOpaque.gif differ diff --git a/node_modules/gifwrap/test/lib/bitmaps.js b/node_modules/gifwrap/test/lib/bitmaps.js new file mode 100644 index 0000000000000000000000000000000000000000..fd9f8f9a5d7a092e5a5f9fa62576792f3dca8032 --- /dev/null +++ b/node_modules/gifwrap/test/lib/bitmaps.js @@ -0,0 +1,91 @@ + +exports.COLORS = { + 'R': 0xFF0000ff, // red + 'r': 0xFF00007f, // red half-alpha + 'G': 0x00FF00ff, // green + 'g': 0x00FF007f, // green half-alpha + 'B': 0x0000FFff, // blue + 'b': 0x0000FF7f, // blue half-alpha + '*': 0x000000ff, // black + ' ': 0x00000000, // fully transparent + 'W': 0xFFFFFFff, // white + '_': 0xFFFFFF01, // white transparent + '4': 0x404040ff, // dark grey + '9': 0x909090ff // light grey +}; + +exports.PREMADE = { + + sampleSprite: [ + ' *', + '* ' + ], + + singleFrameMonoOpaque: [ + 'RRR', + 'RRR', + 'RRR' + ], + + singleFrameMonoOpaqueSpriteAt1x1: [ + 'RRR', + 'RR*', + 'R*R' + ], + + singleFrameNoColorTrans: [ + ' ', + ' ', + ' ' + ], + + singleFrameMonoTrans: [ + ' G ', + 'GGG', + ' G ' + ], + + singleFrameBWOpaque: [ + '*WW*', + 'W**W', + '*WW*' + ], + + singleFrameMultiOpaque: [ + 'RGBW', + 'WRGB' + ], + + singleFrameMultiTrans: [ + 'RGB ', + ' RGB', + ' *' + ], + + singleFrameMultiPartialTrans: [ + '_G ', + '__G ', + 'rgb*' + ], + + twoFrameMultiOpaque: [ + ['**RR', + 'GG**', + '**BB'], + ['RR**', + '**GG', + 'BB**'] + ], + + threeFrameMonoTrans: [ + ['* ', + ' ', + ' '], + [' ', + ' * ', + ' '], + [' ', + ' ', + ' *'] + ] +}; diff --git a/node_modules/gifwrap/test/lib/tools.js b/node_modules/gifwrap/test/lib/tools.js new file mode 100644 index 0000000000000000000000000000000000000000..ee7fca98d247367b66d808351a281abde4bdf39a --- /dev/null +++ b/node_modules/gifwrap/test/lib/tools.js @@ -0,0 +1,202 @@ +'use strict'; + +const assert = require('chai').assert; +const Path = require('path'); +const Jimp = require('jimp'); +const Bitmaps = require('./bitmaps'); +const { BitmapImage } = require('../../src/index'); +const { GifFrame } = require('../../src/gifframe'); + +exports.checkBitmap = function (bitmap, width, height, rgbaOrBuf) { + assert.strictEqual(bitmap.width, width, "width"); + assert.strictEqual(bitmap.height, height, "height"); + if (Buffer.isBuffer(rgbaOrBuf)) { + assert.strictEqual(bitmap.data.length, rgbaOrBuf.length, "length"); + for (let i = 0; i < rgbaOrBuf.length; ++i ) { + assert.strictEqual(rgbaOrBuf[i], bitmap.data[i], "at buffer index "+ i); + } + } + else if (typeof rgbaOrBuf === 'number') { + const rgba = rgbaOrBuf + const buf = bitmap.data; + for (let bi = 0; bi < buf.length; bi += 4) { + const found = buf.readUInt32BE(bi); + if (found !== rgba) { + assert.fail(found, rgba, `buffer fill color ${found} != ${rgba}`); + } + } + } + else { + throw new Error("last checkBitmap() param must be a color or a Buffer"); + } +} + +exports.checkFrameDefaults = function (actualInfo, options, frameIndex = 0) { + options = Object.assign({}, options); // don't munge caller + options.xOffset = options.xOffset || 0; + options.yOffset = options.yOffset || 0; + options.delayCentisecs = options.delayCentisecs || 8; + options.interlaced = (options.interlaced === true); + options.disposalMethod = + (options.disposalMethod || GifFrame.DisposeToBackgroundColor); + exports.verifyFrameInfo(actualInfo, options, frameIndex); +}; + +exports.compareToFrameDump = function (actualFrames, expectedDump) { + assert(Array.isArray(actualFrames)); + assert.strictEqual(actualFrames.length, expectedDump.length); + for (let i = 0; i < actualFrames.length; ++i) { + const actualFrame = actualFrames[i]; + const dump = expectedDump[i]; + exports.verifyFrameInfo(actualFrame, { + xOffset: dump[0], + yOffset: dump[1], + bitmap: { + width: dump[2], + height: dump[3] + }, + delayCentisecs: dump[4], + interlaced: dump[5], + disposalMethod: dump[6] + }, i); + } +}; + +exports.dumpFramesAsCode = function (frames) { + let first = true; + process.stdout.write("[\n"); + frames.forEach(f => { + if (!first) { + process.stdout.write(",\n"); + } + process.stdout.write(` [${f.xOffset}, ${f.yOffset}, `+ + `${f.bitmap.width}, ${f.bitmap.height}, `+ + `${f.delayCentisecs}, ${f.interlaced}, ${f.disposalMethod}]`); + first = false; + }); + process.stdout.write("\n]\n"); +}; + +exports.getBitmap = function (bitmapName, transparentRGB) { + const stringPic = Bitmaps.PREMADE[bitmapName]; + if (stringPic === undefined) { + throw new Error(`Bitmap '${bitmapName}' not found`); + } + if (Array.isArray(stringPic[0])) { + throw new Error(`'${bitmapName}' is a bitmap series`); + } + return _stringsToBitmap(stringPic, transparentRGB); +}; + +exports.getFixturePath = function (filename) { + return Path.join(__dirname, "../fixtures", filename); +}; + +exports.getGifPath = function (filenameMinusExtension) { + return exports.getFixturePath(filenameMinusExtension + '.gif'); +}; + +exports.getImagePath = function (filename) { + return exports.getFixturePath(filename); +}; + +exports.getSeries = function (seriesName, transparentRGB) { + const series = Bitmaps.PREMADE[seriesName]; + if (series === undefined) { + throw new Error(`Bitmap series '${seriesName}' not found`); + } + if (!Array.isArray(series[0])) { + throw new Error(`'${seriesName}' is not a bitmap series`); + } + return series.map(stringPic => + (_stringsToBitmap(stringPic, transparentRGB))); +}; + +exports.loadBitmapImage = function (imagePath) { + return new Promise((resolve, reject) => { + new Jimp(imagePath, (err, jimp) => { + if (err) return reject(err); + resolve(new BitmapImage(jimp.bitmap)); + }); + }); +}; + +exports.saveBitmapImage = function (bitmapImage, path) { + let jimp = new Jimp(1, 1, 0); + jimp.bitmap = bitmapImage.bitmap; + return new Promise((resolve, reject) => { + jimp.write(path, (err) => { + if (err) return reject(err); + resolve(); + }); + }); +}; + +exports.verifyFrameInfo = function (actual, expected, frameIndex=0, note='') { + expected = Object.assign({}, expected); // don't munge caller + if (expected.xOffset !== undefined) { + assert.strictEqual(actual.xOffset, expected.xOffset, + `frame ${frameIndex} same x offset${note}`); + } + if (expected.yOffset !== undefined) { + assert.strictEqual(actual.yOffset, expected.yOffset, + `frame ${frameIndex} same y offset${note}`); + } + if (expected.bitmap !== undefined) { + assert.strictEqual(actual.bitmap.width, expected.bitmap.width, + `frame ${frameIndex} same width${note}`); + assert.strictEqual(actual.bitmap.height, expected.bitmap.height, + `frame ${frameIndex} same height${note}`); + } + if (expected.delayCentisecs !== undefined) { + assert.strictEqual(actual.delayCentisecs, expected.delayCentisecs, + `frame ${frameIndex} same delay${note}`); + } + if (expected.disposalMethod !== undefined) { + assert.strictEqual(actual.disposalMethod, expected.disposalMethod, + `frame ${frameIndex} same disposal method${note}`); + } + assert.strictEqual(actual.interlaced, (expected.interlaced === true), + `frame ${frameIndex} same interlacing${note}`); +}; + +function _stringsToBitmap(stringPic, transparentRGB) { + const trans = transparentRGB; // shortens code, leaves parameter clear + const width = stringPic[0].length; + const height = stringPic.length; + const data = new Buffer(width * height * 4); + let offset = 0; + + for (let y = 0; y < height; ++y) { + const row = stringPic[y]; + if (row.length !== width) { + throw new Error("Inconsistent pixel string length"); + } + for (let x = 0; x < width; ++x) { + if (Bitmaps.COLORS[row[x]] !== undefined) { + const color = Bitmaps.COLORS[row[x]]; + const alpha = color & 0xff; + if (alpha !== 0 || trans === undefined) { + data[offset] = (color >> 24) & 0xff; + data[offset + 1] = (color >> 16) & 0xff; + data[offset + 2] = (color >> 8) & 0xff; + data[offset + 3] = color & 0xff; + } + else { + // not concerned about speed + data[offset] = (trans >> 16) & 0xff; + data[offset + 1] = (trans >> 8) & 0xff; + data[offset + 2] = trans & 0xff; + data[offset + 3] = 0; + } + offset += 4; + } + else { + const validChars = Object.keys(Bitmaps.COLORS).join(''); + throw new Error(`Invalid pixel char '${row[x]}'. `+ + `Valid chars are "${validChars}".`); + } + } + } + return { width, height, data }; +} diff --git a/node_modules/gifwrap/test/test_bitmap.js b/node_modules/gifwrap/test/test_bitmap.js new file mode 100644 index 0000000000000000000000000000000000000000..6835f1557c8ee666a7535672482b70d8d95c0eb6 --- /dev/null +++ b/node_modules/gifwrap/test/test_bitmap.js @@ -0,0 +1,157 @@ +'use strict'; + +const assert = require('chai').assert; +const Jimp = require('jimp'); +const Tools = require('./lib/tools'); +const { BitmapImage, GifUtil } = require('../src/index'); + +const SAMPLE_PNG_PATH = Tools.getFixturePath('lenna.png'); +const SAMPLE_JPG_PATH = Tools.getFixturePath('pelagrina.jpg'); + +describe("BitmapImage construction behavior", () => { + + it("constructs an empty uncolored image", (done) => { + + const i = new BitmapImage(10, 5); + Tools.checkBitmap(i.bitmap, 10, 5, 0); + done(); + }); + + it("constructs an empty colored image", (done) => { + + const color = 0x01020304; + const i = new BitmapImage(10, 5, color); + Tools.checkBitmap(i.bitmap, 10, 5, color); + done(); + }); + + it("constructs a buffer-sourced image", (done) => { + + const buf = new Buffer(10 * 5); + const i = new BitmapImage(10, 5, buf); + Tools.checkBitmap(i.bitmap, 10, 5, buf); + done(); + }); + + it("sourced bitmaps are shared", (done) => { + + const b = { width: 5, height: 6, data: new Buffer(5 * 6) }; + const j = new BitmapImage(b); + assert.strictEqual(b, j.bitmap); + done(); + }); + + it("sourced images are copied", (done) => { + + const color = 0x01020304; + const j1 = new BitmapImage(10, 5, color); + const j2 = new BitmapImage(j1); + assert.notStrictEqual(j1.bitmap, j2.bitmap); + assert.deepStrictEqual(j1.bitmap, j2.bitmap); + done(); + }); +}); + +describe("GifFrame bad construction behavior", () => { + + it("won't accept garbage", (done) => { + + assert.throws(() => { + new BitmapImage(); + }, /requires parameters/); + assert.throws(() => { + new BitmapImage(null); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage("string"); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage(() => {}); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage({}); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage(new Buffer(25)); + }, /unrecognized/); + done(); + }); + + it("width requires height", (done) => { + + assert.throws(() => { + new BitmapImage(5); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage(5, new Buffer(5)); + }, /unrecognized/); + assert.throws(() => { + new BitmapImage(5, {}); + }, /unrecognized/); + done(); + }); +}); + +// TBD: test BitmapImage transformation methods + +describe("Jimp compatibility", () => { + + it("works when sourced from Jimp", (done) => { + + new Jimp(SAMPLE_PNG_PATH, (err, j1) => { + + if (err) return done(err); + assert.strictEqual(err, null); + const initialColor = j1.getPixelColor(5, 5); + const i = new BitmapImage(j1.bitmap); + assert.strictEqual(i.getRGBA(5, 5), initialColor); + const newColor = initialColor + 0x01010101; + i.fillRGBA(newColor); + assert.strictEqual(i.getRGBA(5, 5), newColor); + const j2 = GifUtil.shareAsJimp(Jimp, i); + assert.strictEqual(j2.getPixelColor(5, 5), newColor); + done(); + }); + }); + + it("works when sourcing Jimp via sharing", (done) => { + + const initialColor = 0x12344321; + const i1 = new BitmapImage(10, 5, initialColor); + const j = GifUtil.shareAsJimp(Jimp, i1); + assert.strictEqual(j.getPixelColor(3, 3), initialColor); + const newColor = initialColor + 0x01010101; + j.setPixelColor(newColor, 3, 3); + assert.strictEqual(j.getPixelColor(3, 3), newColor); + const i2 = new BitmapImage(j.bitmap); + assert.strictEqual(i2.getRGBA(3,3), newColor); + done(); + }); + + it("works when sourcing Jimp via copying", (done) => { + + const initialColor = 0x12344321; + const i1 = new BitmapImage(10, 5, initialColor); + const j = GifUtil.copyAsJimp(Jimp, i1); + assert.strictEqual(j.getPixelColor(3, 3), initialColor); + const newColor = initialColor + 0x01010101; + j.setPixelColor(newColor, 3, 3); + assert.strictEqual(j.getPixelColor(3, 3), newColor); + const i2 = new BitmapImage(j.bitmap); + assert.strictEqual(i2.getRGBA(3,3), newColor); + done(); + }); + + it("composing with a sprite having transparency", (done) => { + + const i1 = new BitmapImage(Tools.getBitmap('singleFrameMonoOpaque')); + const j1 = GifUtil.shareAsJimp(Jimp, i1); + const i2 = new BitmapImage(Tools.getBitmap('sampleSprite')); + const j2 = GifUtil.shareAsJimp(Jimp, i2); + j1.composite(j2, 1, 1); + const result = new BitmapImage(j1.bitmap); + const expected = new BitmapImage(Tools.getBitmap('singleFrameMonoOpaqueSpriteAt1x1')); + assert.deepStrictEqual(result.bitmap, expected.bitmap); + done(); + }); +}); diff --git a/node_modules/gifwrap/test/test_decoding.js b/node_modules/gifwrap/test/test_decoding.js new file mode 100644 index 0000000000000000000000000000000000000000..9fba8c495c790cb1a847c7a831636734564df479 --- /dev/null +++ b/node_modules/gifwrap/test/test_decoding.js @@ -0,0 +1,252 @@ +'use strict'; + +const assert = require('chai').assert; +const Tools = require('./lib/tools'); +const { Gif, GifFrame, GifCodec, GifUtil, GifError } = + require('../src/index'); + +describe("single frame decoding", () => { + + it("reads an opaque monocolor file", () => { + + const name = 'singleFrameMonoOpaque'; + const bitmap = Tools.getBitmap(name); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: false + }); + }); + }); + + it("reads an opaque multi-color file", () => { + + const name = 'singleFrameMultiOpaque'; + const bitmap = Tools.getBitmap(name); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: false + }); + }); + }); + + it("reads a purely transparent file", () => { + + const name = 'singleFrameNoColorTrans'; + const bitmap = Tools.getBitmap(name, 0); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: true + }); + }); + }); + + it("reads a monochrome file with transparency", () => { + + const name = 'singleFrameMonoTrans'; + const bitmap = Tools.getBitmap(name, 0); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: true + }); + }); + }); + + it("reads a multicolor file with transparency", () => { + + const name = 'singleFrameMultiTrans'; + const bitmap = Tools.getBitmap(name, 0); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: true + }); + }); + }); + + it("reads a multicolor file with custom transparency color", () => { + + const transRGB = 0x123456; + const name = 'singleFrameMultiTrans'; + const bitmap = Tools.getBitmap(name, transRGB); + const decoder = new GifCodec({ transparentRGB: transRGB }); + return GifUtil.read(Tools.getGifPath(name), decoder) + .then(gif => { + + _compareGifToSeries(gif, [bitmap], { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: true + }); + }); + }); +}); + +describe("multiframe decoding", () => { + + it("reads a 2-frame multicolor file without transparency", () => { + + const name = 'twoFrameMultiOpaque'; + const series = Tools.getSeries(name); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, series, { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: false, + delayCentisecs: 50 + }); + }); + }); + + it("reads a 3-frame monocolor file with transparency", () => { + + const name = 'threeFrameMonoTrans'; + const series = Tools.getSeries(name); + return GifUtil.read(Tools.getGifPath(name)) + .then(gif => { + + _compareGifToSeries(gif, series, { + disposalMethod: GifFrame.DisposeToBackgroundColor, + usesTransparency: true, + delayCentisecs: 25 + }); + }); + }); + + it("reads a large multiframe file w/out transparency", () => { + + return GifUtil.read(Tools.getGifPath('nburling-public')) + .then(gif => { + + assert.strictEqual(gif.width, 238); + assert.strictEqual(gif.height, 372); + assert.strictEqual(gif.loops, 0); + assert.strictEqual(gif.usesTransparency, false); + assert(Array.isArray(gif.frames)); + assert.strictEqual(gif.frames.length, 24); + for (let i = 0; i < gif.frames.length; ++i) { + const frame = gif.frames[i]; + assert.strictEqual(frame.bitmap.width, gif.width); + assert.strictEqual(frame.bitmap.height, gif.height); + Tools.checkFrameDefaults(frame, { + xOffset: 0, + yOffset: 0, + disposalMethod: GifFrame.DisposeNothing, + delayCentisecs: 20 + }, i); + } + assert(Buffer.isBuffer(gif.buffer)); + }); + }); + + it("reads a large multiframe file w/ offsets, w/out transparency", () => { + + return GifUtil.read(Tools.getGifPath('rnaples-offsets-public')) + .then(gif => { + + assert.strictEqual(gif.width, 480); + assert.strictEqual(gif.height, 693); + assert.strictEqual(gif.loops, 0); + assert.strictEqual(gif.usesTransparency, true); + const frameDump = [ // generated via Tools.dumpFramesAsCode() + [0, 0, 480, 693, 10, false, 1], + [208, 405, 130, 111, 10, false, 1], + [85, 0, 395, 516, 10, false, 1], + [85, 0, 395, 309, 10, false, 1], + [85, 0, 395, 309, 10, false, 1], + [85, 0, 395, 309, 10, false, 1], + [208, 0, 272, 516, 10, false, 1], + [85, 0, 375, 516, 10, false, 1], + [85, 2, 365, 514, 10, false, 1], + [85, 36, 346, 480, 10, false, 1], + [167, 79, 271, 213, 10, false, 1], + [85, 103, 353, 413, 10, false, 1], + [191, 142, 279, 374, 20, false, 1], + [0, 0, 1, 1, 20, false, 1], + [191, 142, 279, 374, 20, false, 1], + [191, 142, 279, 374, 30, false, 1], + [191, 142, 279, 374, 10, false, 1], + [85, 183, 395, 211, 10, false, 1], + [85, 183, 395, 258, 10, false, 1], + [85, 183, 395, 333, 10, false, 1], + [85, 183, 395, 363, 10, false, 1], + [85, 183, 395, 405, 10, false, 1], + [85, 183, 395, 442, 10, false, 1], + [208, 405, 272, 284, 10, false, 1], + [324, 499, 156, 194, 10, false, 1], + [394, 546, 86, 147, 10, false, 1], + [85, 183, 395, 510, 10, false, 1], + [0, 0, 1, 1, 10, false, 1], + [85, 183, 338, 333, 10, false, 1], + [208, 405, 130, 111, 10, false, 1], + [208, 247, 215, 269, 10, false, 1] + ]; + Tools.compareToFrameDump(gif.frames, frameDump); + assert(Buffer.isBuffer(gif.buffer)); + }); + }); +}); + +describe("partial frame decoding", () => { + + it("renders partial frames properly onto full frames", () => { + let actualBitmapImage; + + return GifUtil.read(Tools.getGifPath('rnaples-offsets-public')) + .then(actualGif => { + actualBitmapImage = actualGif.frames[10]; + return Tools.loadBitmapImage(Tools.getImagePath('rnaples-frame-10.png')); + }) + .then(expectedBitmapImage => { + const expectedBitmap = expectedBitmapImage.bitmap; + Tools.checkBitmap( + actualBitmapImage.bitmap, + expectedBitmap.width, + expectedBitmap.height, + expectedBitmap.data + ); + }); + }); +}); + +function _compareGifToSeries(actualGif, expectedSeries, options) { + + assert.strictEqual(actualGif.width, expectedSeries[0].width); + assert.strictEqual(actualGif.height, expectedSeries[0].height); + if (options.loops === undefined) { + assert.strictEqual(actualGif.loops, 0); + } + else { + assert.strictEqual(actualGif.loops, options.loops); + } + if (options.usesTransparency !== undefined) { + assert.strictEqual(actualGif.usesTransparency, + options.usesTransparency); + } + if (options.optionization !== undefined) { + assert.strictEqual(actualGif.optionization, options.optionization); + } + + assert(Array.isArray(actualGif.frames)); + assert.strictEqual(actualGif.frames.length, expectedSeries.length); + for (let i = 0; i < actualGif.frames.length; ++i) { + const f = actualGif.frames[i]; + Tools.checkFrameDefaults(f, options, i); + assert.deepStrictEqual(f.bitmap, expectedSeries[i], + `frame ${i} same bitmap`); + } + assert(Buffer.isBuffer(actualGif.buffer)); +} diff --git a/node_modules/gifwrap/test/test_encoding.js b/node_modules/gifwrap/test/test_encoding.js new file mode 100644 index 0000000000000000000000000000000000000000..0a60ba595a26f07c41e7f4dd70f10be8528dd89a --- /dev/null +++ b/node_modules/gifwrap/test/test_encoding.js @@ -0,0 +1,307 @@ +'use strict'; + +const assert = require('chai').assert; +const Tools = require('./lib/tools'); +const { Gif, GifFrame, GifCodec, GifUtil, GifError } = require('../src/index'); + +// compare decoded encodings with decodings intead of comparing buffers, because there are many ways to encode the same data + +const defaultCodec = new GifCodec(); + +describe("single-frame encoding", () => { + + it("encodes an opaque monochrome GIF", () => { + + const name = 'singleFrameMonoOpaque'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a transparent GIF", () => { + + const name = 'singleFrameNoColorTrans'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a monochrome GIF with transparency", () => { + + const name = 'singleFrameMonoTrans'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a opaque two-color GIF", () => { + + const name = 'singleFrameBWOpaque'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a opaque multi-color GIF", () => { + + const name = 'singleFrameMultiOpaque'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a 4-color GIF w/ transparency", () => { + + const name = 'singleFrameMultiTrans'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly); // simple code 1st + // .then(() => { + // return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + // }); + }); +}); + +describe("multi-frame encoding", () => { + + it("encodes a 2-frame multi-color opaque GIF", () => { + + const name = 'twoFrameMultiOpaque'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a 3-frame monocolor GIF with transparency", () => { + + const name = 'threeFrameMonoTrans'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a large multiframe file w/out transparency", () => { + + const name = 'nburling-public'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes a large multiframe file w/ offsets, w/out transparency", () => { + + const name = 'rnaples-offsets-public'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly) // simple code 1st + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly); + }); + }); + + it("encodes large multiframe files w/ forced buffer-size scaling (1)", () => { + + const scalingCodec = new GifCodec(); + scalingCodec._testInitialBufferSize = 2048; // big enough for header + const name = 'nburling-public'; + + return _encodeDecodeFile(name, Gif.LocalColorsOnly, scalingCodec) + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly, scalingCodec); + }); + }); + + it("encodes large multiframe files w/ forced buffer-size scaling (2)", () => { + + const scalingCodec = new GifCodec(); + scalingCodec._testInitialBufferSize = 2048; // big enough for header + + const name = 'rnaples-offsets-public'; + return _encodeDecodeFile(name, Gif.LocalColorsOnly, scalingCodec) + .then(() => { + return _encodeDecodeFile(name, Gif.GlobalColorsOnly, scalingCodec); + }); + }); +}); + +describe("encoding GlobalColorsPreferred", () => { + + it("uses a global color table when 256 colors in 1 frame", () => { + + const frames = []; + const options = { colorScope: Gif.GlobalColorsPreferred }; + + frames.push(_get256ColorFrame()); + + return defaultCodec.encodeGif(frames, options) + .then(encodedGif => { + + options.colorScope = Gif.GlobalColorsOnly; + return defaultCodec.encodeGif(frames, options); + }) + .then(encodedGif => { + + assert(true); + }) + }); + + it("uses a global color table when 256 colors in each of 2 frames", () => { + + const frames = []; + const options = { colorScope: Gif.GlobalColorsPreferred }; + + frames.push(_get256ColorFrame()); + frames.push(_get256ColorFrame()); + + return defaultCodec.encodeGif(frames, options) + .then(encodedGif => { + + options.colorScope = Gif.GlobalColorsOnly; + return defaultCodec.encodeGif(frames, options); + }) + .then(encodedGif => { + + assert(true); + }) + }); + + it("uses a global color table when 255 colors + transparency in each of 2 frames", () => { + + const frames = []; + const options = { colorScope: Gif.GlobalColorsPreferred }; + + frames.push(_get256ColorFrame()); + frames[0].bitmap.data[3] = 0; + frames.push(_get256ColorFrame()); + frames[1].bitmap.data[3] = 0; + + return defaultCodec.encodeGif(frames, options) + .then(encodedGif => { + + options.colorScope = Gif.GlobalColorsOnly; + return defaultCodec.encodeGif(frames, options); + }) + .then(encodedGif => { + + assert(true); + }) + }); + + it("uses a local color table when there are 257 opaque colors", () => { + + const frames = []; + const options = { colorScope: Gif.GlobalColorsPreferred }; + + frames.push(_get256ColorFrame()); + // put a 257th opaque color in the second frame + let buf = new Buffer(256 * 4); // defaults to zeroes + buf[0] = 0; buf[1] = 2; buf[2] = 3; buf[3] = 255; + frames.push(new GifFrame(16, 16, buf)); + + return defaultCodec.encodeGif(frames, options) + .then(encodedGif => { + + options.colorScope = Gif.GlobalColorsOnly; + return defaultCodec.encodeGif(frames, options); + }) + .then(encodedGif => { + + assert.fail("should not encode"); + }) + .catch(err => { + + if (!(err instanceof GifError)) { + throw err; + } + assert.strictEqual(err.message, + "Too many color indexes for global color table"); + }); + }); + + it("uses a local color table when there are 256 opaque colors + transparency", () => { + + const frames = []; + const options = { colorScope: Gif.GlobalColorsPreferred }; + + frames.push(_get256ColorFrame()); + frames.push(_get256ColorFrame()); + frames[1].bitmap.data[3] = 0; + + return defaultCodec.encodeGif(frames, options) + .then(encodedGif => { + + options.colorScope = Gif.GlobalColorsOnly; + return defaultCodec.encodeGif(frames, options); + }) + .then(encodedGif => { + + assert.fail("should not encode"); + }) + .catch(err => { + + if (!(err instanceof GifError)) { + throw err; + } + assert.strictEqual(err.message, + "Too many color indexes for global color table"); + }); + }); + +}); + +function _compareGifs(actual, expected, filename, note) { + note = `file '${filename}' (${note})`; + assert.strictEqual(actual.width, expected.width, note); + assert.strictEqual(actual.height, expected.height, note); + assert.strictEqual(actual.loops, expected.loops, note); + assert.strictEqual(actual.usesTransparency, expected.usesTransparency, + note); + + assert(Buffer.isBuffer(actual.buffer), note); + assert(Array.isArray(actual.frames)); + assert.strictEqual(actual.frames.length, expected.frames.length); + note = ` in ${note}`; + for (let i = 0; i < actual.frames.length; ++i) { + const actualFrame = actual.frames[i]; + const expectedFrame = expected.frames[i]; + Tools.verifyFrameInfo(actualFrame, expectedFrame, i, note); + } +} + +function _encodeDecodeFile(filename, colorScope, codec) { + let expectedGif; + codec = codec || defaultCodec; + + return GifUtil.read(Tools.getGifPath(filename), codec) + .then(readGif => { + + expectedGif = readGif; + return codec.encodeGif(readGif.frames, + { loops: readGif.loops, colorScope: colorScope }); + }) + .then(encodedGif => { + + _compareGifs(encodedGif, expectedGif, filename, + `encoded == read (colorScope ${colorScope})`); + return codec.decodeGif(encodedGif.buffer); + }) + .then(decodedGif => { + + _compareGifs(decodedGif, expectedGif, filename, + `decoded == read (colorScope ${colorScope})`); + }) +} + +function _get256ColorFrame() { + let buf = new Buffer(256 * 4); + for (let i = 0; i < 256; ++i) { + const offset = i * 4; + buf[offset + 2] = buf[offset + 1] = buf[offset] = i; + buf[offset + 3] = 255; + } + return new GifFrame(16, 16, buf); +} diff --git a/node_modules/gifwrap/test/test_frame.js b/node_modules/gifwrap/test/test_frame.js new file mode 100644 index 0000000000000000000000000000000000000000..ea29f1c68c5a4c12096e3e3ee9c710089e9016b2 --- /dev/null +++ b/node_modules/gifwrap/test/test_frame.js @@ -0,0 +1,276 @@ +'use strict'; + +const assert = require('chai').assert; +const Jimp = require('jimp'); +const Tools = require('./lib/tools'); +const { BitmapImage, Gif, GifFrame, GifError } = require('../src/index'); + +const SAMPLE_PNG_PATH = Tools.getFixturePath('lenna.png'); +const SAMPLE_JPG_PATH = Tools.getFixturePath('pelagrina.jpg'); + +describe("GifFrame good construction behavior", () => { + + it("constructs an uncolored bitmap", (done) => { + + const f = new GifFrame(10, 5); + Tools.checkBitmap(f.bitmap, 10, 5, 0); + Tools.checkFrameDefaults(f); + done(); + }); + + it("initializes options in an uncolored bitmap", (done) => { + + const f = new GifFrame(10, 5, { delayCentisecs: 100 }); + Tools.checkBitmap(f.bitmap, 10, 5, 0); + Tools.checkFrameDefaults(f, { + delayCentisecs: 100 + }); + done(); + }); + + it("constructs an empty colored bitmap", (done) => { + + const color = 0x01020300; + const f = new GifFrame(10, 5, color); + Tools.checkBitmap(f.bitmap, 10, 5, color); + Tools.checkFrameDefaults(f); + done(); + }); + + it("initializes options in a colored bitmap", (done) => { + + const color = 0x010203ff; + const f = new GifFrame(10, 5, color, { delayCentisecs: 100 }); + Tools.checkBitmap(f.bitmap, 10, 5, color); + Tools.checkFrameDefaults(f, { + delayCentisecs: 100 + }); + done(); + }); + + it("sources from an existing bitmap, sharing", (done) => { + + const color = 0x010203ff; + const j = new BitmapImage(10, 5, color); + const f = new GifFrame(j.bitmap); + assert.strictEqual(f.bitmap, j.bitmap); + Tools.checkFrameDefaults(f); + done(); + }); + + it("sources from an existing bitmap, sharing, with options", (done) => { + + const color = 0x010203ff; + const j = new BitmapImage(10, 5, color); + const f = new GifFrame(j.bitmap, { delayCentisecs: 100 }); + assert.strictEqual(f.bitmap, j.bitmap); + Tools.checkFrameDefaults(f, { + delayCentisecs: 100 + }); + done(); + }); + + it("sources from an existing BitmapImage, copying", (done) => { + + const color = 0x010203ff; + const j = new BitmapImage(10, 5, color); + const f = new GifFrame(j); + assert.notStrictEqual(f.bitmap, j.bitmap); + assert.deepStrictEqual(f.bitmap, j.bitmap); + Tools.checkFrameDefaults(f); + done(); + }); + + it("sources from an existing BitmapImage, copying, with options", (done) => { + + const color = 0x010203ff; + const j = new BitmapImage(10, 5, color); + const f = new GifFrame(j, { delayCentisecs: 100 }); + assert.notStrictEqual(f.bitmap, j.bitmap); + assert.deepStrictEqual(f.bitmap, j.bitmap); + Tools.checkFrameDefaults(f, { + delayCentisecs: 100 + }); + done(); + }); + + it("initializes data params without options", (done) => { + const bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f = new GifFrame(bitmap.width, bitmap.height, bitmap.data); + assert.strictEqual(f.bitmap.width, bitmap.width); + assert.strictEqual(f.bitmap.height, bitmap.height); + assert.strictEqual(f.bitmap.data, bitmap.data); + Tools.checkFrameDefaults(f); + done(); + }); + + it("initializes data params with options", (done) => { + const bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f = new GifFrame(bitmap.width, bitmap.height, bitmap.data, + { delayCentisecs: 200, interlaced: true }); + assert.strictEqual(f.bitmap.width, bitmap.width); + assert.strictEqual(f.bitmap.height, bitmap.height); + assert.strictEqual(f.bitmap.data, bitmap.data); + Tools.checkFrameDefaults(f, { + delayCentisecs: 200, + interlaced: true + }); + done(); + }); + + it("initializes bitmap without options", (done) => { + const bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f = new GifFrame(bitmap); + assert.strictEqual(f.bitmap, bitmap); + Tools.checkFrameDefaults(f); + done(); + }); + + it("initializes bitmap with options", (done) => { + const bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f = new GifFrame(bitmap, + { delayCentisecs: 200, interlaced: true }); + assert.strictEqual(f.bitmap, bitmap); + Tools.checkFrameDefaults(f, { + delayCentisecs: 200, + interlaced: true + }); + done(); + }); + + it("clones an existing frame", (done) => { + + const f1 = new GifFrame(5, 5, { + delayCentisecs: 100, + isInterlace: true + }); + f1.bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f2 = new GifFrame(f1); + Tools.verifyFrameInfo(f2, f1); + assert.notStrictEqual(f2.bitmap, f1.bitmap); + assert.deepStrictEqual(f2.bitmap, f1.bitmap); + done(); + }); +}); + +describe("GifFrame bad construction behavior", () => { + + it("won't accept garbage", (done) => { + + assert.throws(() => { + new GifFrame(); + }, /requires parameters/); + assert.throws(() => { + new GifFrame(null); + }, /unrecognized/); + assert.throws(() => { + new GifFrame(null, { interlaced: true }); + }, /unrecognized/); + assert.throws(() => { + new GifFrame("string"); + }, /unrecognized/); + assert.throws(() => { + new GifFrame("string", { interlaced: true }); + }, /unrecognized/); + assert.throws(() => { + new GifFrame(() => {}); + }, /unrecognized/); + assert.throws(() => { + new GifFrame({}); + }, /unrecognized/); + assert.throws(() => { + new GifFrame({ interlaced: true }); + }, /unrecognized/); + assert.throws(() => { + new GifFrame(new Buffer(25)); + }, /unrecognized/); + done(); + }); + + it("width requires height", (done) => { + + assert.throws(() => { + new GifFrame(5); + }, /unrecognized/); + assert.throws(() => { + new GifFrame(5, { interlaced: true }); + }, /unrecognized/); + assert.throws(() => { + new GifFrame(5, new Buffer(5)); + }, /unrecognized/); + done(); + }); +}); + +describe("GifFrame palette", () => { + + it("is monocolor without transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameMonoOpaque'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, [0xFF0000]); + assert.strictEqual(p.usesTransparency, false); + done(); + }); + + it("includes two colors without transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameBWOpaque'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, [0x000000, 0xffffff]); + assert.strictEqual(p.usesTransparency, false); + done(); + }); + + it("includes multiple colors without transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameMultiOpaque'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, + [0x0000ff, 0x00ff00, 0xff0000, 0xffffff]); + assert.strictEqual(p.usesTransparency, false); + done(); + }); + + it("has only transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameNoColorTrans'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, []); + assert.strictEqual(p.usesTransparency, true); + done(); + }); + + it("is monocolor with transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameMonoTrans'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, [0x00ff00]); + assert.strictEqual(p.usesTransparency, true); + done(); + }); + + it("includes multiple colors with transparency", (done) => { + + const bitmap = Tools.getBitmap('singleFrameMultiPartialTrans'); + const f = new GifFrame(bitmap); + const p = f.getPalette(); + assert.deepStrictEqual(p.colors, + [0x000000, 0x0000ff, 0x00ff00, 0xff0000, 0xffffff]); + assert.strictEqual(p.usesTransparency, true); + done(); + }); +}); + +function _assertDefaultFrameOptions(frame) { + assert.strictEqual(frame.xOffset, 0); + assert.strictEqual(frame.yOffset, 0); + assert.strictEqual(frame.disposalMethod, GifFrame.DisposeToBackgroundColor); + assert.strictEqual(typeof frame.delayCentisecs, 'number'); + assert.strictEqual(frame.interlaced, false); +} diff --git a/node_modules/gifwrap/test/test_properties.js b/node_modules/gifwrap/test/test_properties.js new file mode 100644 index 0000000000000000000000000000000000000000..7080c284b1098be57b8d59612072a1edfaef78ab --- /dev/null +++ b/node_modules/gifwrap/test/test_properties.js @@ -0,0 +1,277 @@ +'use strict'; + +const assert = require('chai').assert; +const Tools = require('./lib/tools'); +const { Gif, GifFrame, GifCodec, GifError, GifUtil } = require('../src/index'); + +const defaultCodec = new GifCodec(); + +describe("Gif width/height", () => { + + it("sets width/height = size of the frames", () => { + + const w = 24, h = 10; + const frames = [ + new GifFrame(w, h), + new GifFrame(w, h, 0xffffffff) + ]; + return defaultCodec.encodeGif(frames) + .then(gif => { + assert.strictEqual(gif.width, w); + assert.strictEqual(gif.height, h); + }); + }); + + it("sets width/height = size of largest frame", () => { + + const w = 24, h = 10; + const frames = [ + new GifFrame(w - 1, h - 1), + new GifFrame(w, h, 0xffffffff) + ]; + return defaultCodec.encodeGif(frames) + .then(gif => { + assert.strictEqual(gif.width, w); + assert.strictEqual(gif.height, h); + }); + }); + + it("sets width/height = largest frame boundary", () => { + + const w = 24, h = 10; + const frames = [ + new GifFrame(w - 1, h - 1, { + xOffset: 1, + yOffset: 1 + }), + new GifFrame(w, h, 0xffffffff) + ]; + return defaultCodec.encodeGif(frames) + .then(gif => { + assert.strictEqual(gif.width, w); + assert.strictEqual(gif.height, h); + }); + }); +}); + +describe("Gif loop count", () => { + + it("decodes an infinite loop", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay0')) + .then(gif => { + + assert.strictEqual(gif.loops, 0); + }); + }); + + it("decodes a single-pass loop", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay1')) + .then(gif => { + + assert.strictEqual(gif.loops, 1); + }); + }); + + it("decodes a three-pass loop", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay3')) + .then(gif => { + + assert.strictEqual(gif.loops, 3); + }); + }); + + it("encodes an infinite loop", () => { + + return _verifyEncodesLoopCount('countConstantDelay3', 0); + }); + + it("encodes a single-pass loop", () => { + + return _verifyEncodesLoopCount('countConstantDelay0', 1); + }); + + it("encodes a three-pass loop", () => { + + return _verifyEncodesLoopCount('countConstantDelay1', 3); + }); +}); + +describe("Gif transparency", () => { + + it("indicates no transparency", () => { + + return GifUtil.read(Tools.getGifPath('twoFrameMultiOpaque')) + .then(readGif => { + + assert.strictEqual(readGif.usesTransparency, false); + return defaultCodec.encodeGif(readGif.frames); + }) + .then(encodedGif => { + + assert.strictEqual(encodedGif.usesTransparency, false); + }) + }); + + it("indicates transparency", () => { + + return GifUtil.read(Tools.getGifPath('threeFrameMonoTrans')) + .then(readGif => { + + assert.strictEqual(readGif.usesTransparency, true); + return defaultCodec.encodeGif(readGif.frames); + }) + .then(encodedGif => { + + assert.strictEqual(encodedGif.usesTransparency, true); + }) + }); +}); + +describe("GifFrame x/y-offsets", () => { + + it("accommodates/encodes offsets", () => { + + return GifUtil.read(Tools.getGifPath('count5x7')) + .then(readGif => { + + const frames = readGif.frames; + assert(frames.length >= 4, "precondition for test"); + assert.strictEqual(readGif.width, 5); + assert.strictEqual(readGif.height, 7); + frames.forEach(frame => { + + _verifyFrameOffsets(frame, 0, 0); + }); + frames[1].xOffset = 1; + frames[1].yOffset = 2; + frames[2].xOffset = 2; + frames[2].yOffset = 1; + return defaultCodec.encodeGif(frames); + }) + .then(encodedGif => { + + assert.strictEqual(encodedGif.width, 7); + assert.strictEqual(encodedGif.height, 9); + return defaultCodec.decodeGif(encodedGif.buffer); + }) + .then(decodedGif => { + + assert.strictEqual(decodedGif.width, 7); + assert.strictEqual(decodedGif.height, 9); + const frames = decodedGif.frames; + _verifyFrameOffsets(frames[0], 0, 0); + _verifyFrameOffsets(frames[1], 1, 2); + _verifyFrameOffsets(frames[2], 2, 1); + _verifyFrameOffsets(frames[3], 0, 0); + }); + }); +}); + +describe("GifFrame delay", () => { + + it("confirms a constant frame-delay GIF", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay0')) + .then(readGif => { + + readGif.frames.forEach(frame => { + + assert.strictEqual(frame.delayCentisecs, 33); + }); + }); + }); + + it("confirms a variable frame-delay GIF", () => { + + return GifUtil.read(Tools.getGifPath('countIncreasingDelay')) + .then(readGif => { + + const frames = readGif.frames; + for (let i = 0; i < frames.length; ++i) { + assert.strictEqual(frames[i].delayCentisecs, (i + 1)*25); + } + }); + }); + + it("encodes varying frame delays", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay0')) + .then(readGif => { + + const frames = readGif.frames; + for (let i = 0; i < frames.length; ++i) { + frames[i].delayCentisecs = (i + 1)*25; + } + return defaultCodec.encodeGif(frames, { loops: readGif.loops }); + }) + .then(encodedGif => { + + return defaultCodec.decodeGif(encodedGif.buffer); + }) + .then(decodedGif => { + + const frames = decodedGif.frames; + for (let i = 0; i < frames.length; ++i) { + assert.strictEqual(frames[i].delayCentisecs, (i + 1)*25); + } + }); + }); +}); + +describe("GifFrame disposal method", () => { + + it("encodes/decodes disposal", () => { + + return GifUtil.read(Tools.getGifPath('countConstantDelay0')) + .then(readGif => { + + const frames = readGif.frames; + assert(frames.length >= 4, "precondition for test"); + frames.forEach(frame => { + + assert.strictEqual(frame.disposalMethod, + GifFrame.DisposeToBackgroundColor); + }); + for (let i = 0; i < 4; ++i) { + frames[i].disposalMethod = i; + } + return defaultCodec.encodeGif(frames, { loops: readGif.loops }); + }) + .then(encodedGif => { + + return defaultCodec.decodeGif(encodedGif.buffer); + }) + .then(decodedGif => { + + const frames = decodedGif.frames; + for (let i = 0; i < 4; ++i) { + assert.strictEqual(frames[i].disposalMethod, i); + } + }); + }); +}); + +function _verifyEncodesLoopCount(sourceFilename, loopCount) { + return GifUtil.read(Tools.getGifPath(sourceFilename)) + .then(readGif => { + + return defaultCodec.encodeGif(readGif.frames, { loops: loopCount }); + }) + .then(encodedGif => { + + assert.strictEqual(encodedGif.loops, loopCount); + return defaultCodec.decodeGif(encodedGif.buffer); + }) + .then(decodedGif => { + + assert.strictEqual(decodedGif.loops, loopCount); + }); +} + +function _verifyFrameOffsets(frame, xOffset, yOffset) { + assert.strictEqual(frame.xOffset, xOffset); + assert.strictEqual(frame.yOffset, yOffset); +} diff --git a/node_modules/gifwrap/test/test_quantize.js b/node_modules/gifwrap/test/test_quantize.js new file mode 100644 index 0000000000000000000000000000000000000000..c0cf31fcf69814f3cb926bd412a731419808c22d --- /dev/null +++ b/node_modules/gifwrap/test/test_quantize.js @@ -0,0 +1,292 @@ +'use strict'; + +const assert = require('chai').assert; +const Jimp = require('jimp'); +const Tools = require('./lib/tools'); +const { BitmapImage, GifUtil } = require('../src/index'); + +describe("graphics color index reduction", () => { + + it("Dekker-quantizes down to 32 colors", () => { + + return _graphicsTest('quantizeDekker', 32); + }); + + it("Dekker-quantizes down to 256 colors", () => { + + return _graphicsTest('quantizeDekker', 256); + }); + + it("Sorokin-quantizes down to 32 colors", () => { + + return _graphicsTest('quantizeSorokin', 32); + }); + + it("Sorokin-quantizes down to 256 colors", () => { + + return _graphicsTest('quantizeSorokin', 256); + }); + + it("Wu-quantizes down to 32 colors", () => { + + return _graphicsTest('quantizeWu', 32); + }); + + it("Wu-quantizes down to 256 colors", () => { + + return _graphicsTest('quantizeWu', 256); + }); +}); + +describe("photo color index reduction", () => { + + it("Dekker-quantizes down to 32 colors", () => { + + return _photoTest('quantizeDekker', 32); + }); + + it("Dekker-quantizes down to 256 colors", () => { + + return _photoTest('quantizeDekker', 256); + }); + + it("Sorokin-quantizes down to 32 colors", () => { + + return _photoTest('quantizeSorokin', 32); + }); + + it("Sorokin-quantizes down to 256 colors", () => { + + return _photoTest('quantizeSorokin', 256); + }); + + it("Wu-quantizes down to 32 colors", () => { + + return _photoTest('quantizeWu', 32); + }); + + it("Wu-quantizes down to 256 colors", () => { + + return _photoTest('quantizeWu', 256); + }); +}); + +describe("dithering", () => { + + it("FloydSteinberg-dither of Dekker-quantized 256 colors", () => { + + return _ditherTest('quantizeDekker', 256, null, 'FloydSteinberg'); + }); + + it("FloydSteinberg-dither of Sorokin-quantized 256 colors", () => { + + return _ditherTest('quantizeSorokin', 256, 'min-pop', 'FloydSteinberg'); + }); + + it("FloydSteinberg-dither of Wu-quantized 256 colors", () => { + + return _ditherTest('quantizeWu', 256, 5, 'FloydSteinberg'); + }); +}); + +describe("reduce colors across a series of images", () => { + + const specialOpaque = 0xffffffff; + const specialTransparent = 0; + + it("Dekker-quantizes an opaque image series down to 256 colors", (done) => { + + _seriesTest('quantizeDekker', specialOpaque); + done(); + }); + + it("Dekker-quantizes an image series with transparency down to 256 colors", (done) => { + + _seriesTest('quantizeDekker', specialTransparent); + done(); + }); + + it("Sorokin-quantizes an opaque image series down to 256 colors", (done) => { + + _seriesTest('quantizeSorokin', specialOpaque); + done(); + }); + + it("Sorokin-quantizes an image series with transparency down to 256 colors", (done) => { + + _seriesTest('quantizeSorokin', specialTransparent); + done(); + }); + + it("Wu-quantizes an opaque image series down to 256 colors", (done) => { + + _seriesTest('quantizeWu', specialOpaque); + done(); + }); + + it("Wu-quantizes an image series with transparency down to 256 colors", (done) => { + + _seriesTest('quantizeWu', specialTransparent); + done(); + }); +}); + +function _ditherTest(method, maxColors, modifier, ditherAlg) { + return _reductionTest("sculptmap.png", false, method, maxColors, modifier, { + ditherAlgorithm: ditherAlg + }); +} + +function _graphicsTest(method, maxColors) { + return _reductionTest("sculptmap.png", false, method, maxColors) + .then(() => { + + return _reductionTest("rosewithtrans.png", true, method, maxColors); + }) +} + +function _hasTransparency(colorSet) { + for (let rgba of colorSet.values()) { + if ((rgba & 0xff) === 0x00) { + return true; + } + } + return false; +} + +function _photoTest(method, maxColors) { + return _reductionTest("hairstreak.jpg", false, method, maxColors); +} + +function _reductionTest(sourceFile, usesTransparency, method, maxColors, modifier, dither) { + const baseFile = sourceFile.substr(0, sourceFile.length - 4); + const suffix = method.substr(8); + let expectedFile = `quantized/${baseFile}${maxColors}_${suffix}`; + if (dither) { + expectedFile += '_' + dither.ditherAlgorithm; + } + expectedFile += '.png'; + const label = `${method}(${maxColors}) - ${baseFile}`; + const writeFile = null; //expectedFile; + let work; + + return new Promise((resolve, reject) => { + new Jimp(Tools.getFixturePath(sourceFile), (err, manyJimp) => { + + if (err) return reject(err); + new Jimp(Tools.getFixturePath(expectedFile), (err, limitedJimp) => { + + if (err) return reject(err); + work = new BitmapImage(manyJimp.bitmap); + + const inputColorSet = work.getRGBASet(); + assert.strictEqual(_hasTransparency(inputColorSet), usesTransparency, label); + assert.isAtLeast(inputColorSet.size, maxColors + 1, label); + + if (method === 'quantizeDekker') { + GifUtil[method](work, maxColors, dither); + } + else { + GifUtil[method](work, maxColors, modifier, dither); + } + + const workBuf = work.bitmap.data; + const limitedBuf = limitedJimp.bitmap.data; + assert.strictEqual(workBuf.length, manyJimp.bitmap.data.length, label); + assert.strictEqual(workBuf.compare(limitedBuf), 0, label); + + const outputColorSet = work.getRGBASet(); + assert.strictEqual(_hasTransparency(outputColorSet), usesTransparency, label); + assert.isAtMost(outputColorSet.size, maxColors, label); + resolve(); + }); + }); + }) + .then(() => { + if (writeFile) { + return _writeJimp(writeFile, work.bitmap); + } + }); +} + +function _seriesTest(method, specialColor) { + const images = []; + const width = 32, height = 32; + const maxColors = 256; + + let image = new BitmapImage(width, height); + let buf = image.bitmap.data; + let bi = 0; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + buf[bi] = x * 8; + buf[bi + 1] = y * 8; + buf[bi + 3] = 255; + bi += 4; + } + } + images.push(image); // 32 * 32 = 1024 colors + + image = new BitmapImage(width, height); + buf = image.bitmap.data; + bi = 0; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + buf[bi] = x * 8 + 4; + buf[bi + 1] = y * 8 + 4; + buf[bi + 3] = 255; + bi += 4; + } + } + images.push(image); // 32 * 32 = 1024 more colors + + image = new BitmapImage(width, height); + buf = image.bitmap.data; + bi = 0; + for (let y = 0; y < height; ++y) { + for (let x = 0; x < width; ++x) { + if (x < width / 2) { + buf.writeUInt32BE(255, bi); + } + else { + buf.writeUInt32BE(specialColor, bi); + } + bi += 4; + } + } + images.push(image); // 1 more color (white), which should be there + + GifUtil[method](images, maxColors); + + const colorSet = new Set(); + images.forEach(image => { + + buf = image.bitmap.data; + for (let bi = 0; bi < buf.length; bi += 4) { + colorSet.add(buf.readUInt32BE(bi, true)); + } + }); + assert.isAtMost(colorSet.size, maxColors); + assert(colorSet.has(specialColor), "has special color"); +} + +function _writeJimp(filename, bitmap) { + + const jimp = new Jimp(1, 1); + jimp.bitmap = bitmap; + + return new Promise((resolve, reject) => { + + jimp.write(filename, (err) => { + if (err) return reject(err); + resolve(); + }); + }).then(() => { + + console.log(`WROTE ${filename}`); + }) + .catch((err) => { + + console.log(`WRITE FAILED ${err.stack}`); + }); +} diff --git a/node_modules/github-from-package/.travis.yml b/node_modules/github-from-package/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..895dbd36234210374d68a0f020b2d6e7abf736fa --- /dev/null +++ b/node_modules/github-from-package/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.6 + - 0.8 diff --git a/node_modules/github-from-package/LICENSE b/node_modules/github-from-package/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/node_modules/github-from-package/LICENSE @@ -0,0 +1,18 @@ +This software is released under the MIT license: + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/github-from-package/example/package.json b/node_modules/github-from-package/example/package.json new file mode 100644 index 0000000000000000000000000000000000000000..03494f486ece7791b05c5025f18ff59e6fbee2a4 --- /dev/null +++ b/node_modules/github-from-package/example/package.json @@ -0,0 +1,8 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : { + "type" : "git", + "url": "git@github.com:substack/beep-boop.git" + } +} diff --git a/node_modules/github-from-package/example/url.js b/node_modules/github-from-package/example/url.js new file mode 100644 index 0000000000000000000000000000000000000000..138fb8a66637d067af30053c20a425815e1fa811 --- /dev/null +++ b/node_modules/github-from-package/example/url.js @@ -0,0 +1,3 @@ +var github = require('../'); +var url = github(require('./package.json')); +console.log(url); diff --git a/node_modules/github-from-package/index.js b/node_modules/github-from-package/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3d1d657b307a2f2225413f803cc1393c40a01465 --- /dev/null +++ b/node_modules/github-from-package/index.js @@ -0,0 +1,17 @@ +module.exports = function (pkg) { + var m; + if (m = match(JSON.stringify(pkg.repository))) { + return m; + } + else if (m = match(JSON.stringify(pkg))) { + return m; + } + return undefined; +}; + +function match (str) { + var m = /\bgithub.com[:\/]([^\/"]+)\/([^\/"]+)/.exec(str); + if (m) { + return 'https://github.com/' + m[1] + '/' + m[2].replace(/\.git$/, ''); + } +} diff --git a/node_modules/github-from-package/package.json b/node_modules/github-from-package/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a3e240fedf0d54d6eac6aa9c058f0734bbc9301c --- /dev/null +++ b/node_modules/github-from-package/package.json @@ -0,0 +1,30 @@ +{ + "name" : "github-from-package", + "version" : "0.0.0", + "description" : "return the github url from a package.json file", + "main" : "index.js", + "devDependencies" : { + "tap" : "~0.3.0", + "tape" : "~0.1.5" + }, + "scripts" : { + "test" : "tap test/*.js" + }, + "repository" : { + "type" : "git", + "url" : "git://github.com/substack/github-from-package.git" + }, + "homepage" : "https://github.com/substack/github-from-package", + "keywords" : [ + "github", + "package.json", + "npm", + "repository" + ], + "author" : { + "name" : "James Halliday", + "email" : "mail@substack.net", + "url" : "http://substack.net" + }, + "license" : "MIT" +} diff --git a/node_modules/github-from-package/readme.markdown b/node_modules/github-from-package/readme.markdown new file mode 100644 index 0000000000000000000000000000000000000000..5ba397da945c63c32182d993d2756eb8ccc63079 --- /dev/null +++ b/node_modules/github-from-package/readme.markdown @@ -0,0 +1,53 @@ +# github-from-package + +return the github url from a package.json file + +[![build status](https://secure.travis-ci.org/substack/github-from-package.png)](http://travis-ci.org/substack/github-from-package) + +# example + +For the `./package.json` file: + +``` json +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : { + "type" : "git", + "url": "git@github.com:substack/beep-boop.git" + } +} +``` + +``` js +var github = require('github-from-package'); +var url = github(require('./package.json')); +console.log(url); +``` + +``` +https://github.com/substack/beep-boop +``` + +# methods + +``` js +var github = require('github-from-package') +``` + +## var url = github(pkg) + +Return the most likely github url from the package.json contents `pkg`. If no +github url can be determined, return `undefined`. + +# install + +With [npm](https://npmjs.org) do: + +``` +npm install github-from-package +``` + +# license + +MIT diff --git a/node_modules/github-from-package/test/a.json b/node_modules/github-from-package/test/a.json new file mode 100644 index 0000000000000000000000000000000000000000..03494f486ece7791b05c5025f18ff59e6fbee2a4 --- /dev/null +++ b/node_modules/github-from-package/test/a.json @@ -0,0 +1,8 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : { + "type" : "git", + "url": "git@github.com:substack/beep-boop.git" + } +} diff --git a/node_modules/github-from-package/test/b.json b/node_modules/github-from-package/test/b.json new file mode 100644 index 0000000000000000000000000000000000000000..02093257bf129c73faf4b6bee04482e45efaa6ff --- /dev/null +++ b/node_modules/github-from-package/test/b.json @@ -0,0 +1,5 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : "git@github.com:substack/beep-boop.git" +} diff --git a/node_modules/github-from-package/test/c.json b/node_modules/github-from-package/test/c.json new file mode 100644 index 0000000000000000000000000000000000000000..65f6ddad5da45a0404420ac7abcd105cc5b2b53b --- /dev/null +++ b/node_modules/github-from-package/test/c.json @@ -0,0 +1,5 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : "https://github.com/substack/beep-boop.git" +} diff --git a/node_modules/github-from-package/test/d.json b/node_modules/github-from-package/test/d.json new file mode 100644 index 0000000000000000000000000000000000000000..c61f3cd3bbfe4a1eb014556e48ef7bab3f9501ff --- /dev/null +++ b/node_modules/github-from-package/test/d.json @@ -0,0 +1,7 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "repository" : { + "url": "https://github.com/substack/beep-boop" + } +} diff --git a/node_modules/github-from-package/test/e.json b/node_modules/github-from-package/test/e.json new file mode 100644 index 0000000000000000000000000000000000000000..770b43846e0ea6542df17126d435a6173043c2dc --- /dev/null +++ b/node_modules/github-from-package/test/e.json @@ -0,0 +1,5 @@ +{ + "name": "beep-boop", + "version": "1.2.3", + "homepage": "https://github.com/substack/beep-boop/issues" +} diff --git a/node_modules/github-from-package/test/url.js b/node_modules/github-from-package/test/url.js new file mode 100644 index 0000000000000000000000000000000000000000..d5a0a667229d04fb9a4fc1c3fd0c29a3d4cefeff --- /dev/null +++ b/node_modules/github-from-package/test/url.js @@ -0,0 +1,19 @@ +var test = require('tape'); +var github = require('../'); +var packages = { + a : require('./a.json'), + b : require('./b.json'), + c : require('./c.json'), + d : require('./d.json'), + e : require('./e.json') +}; + +test(function (t) { + t.plan(5); + var url = 'https://github.com/substack/beep-boop'; + t.equal(url, github(packages.a), 'a.json comparison'); + t.equal(url, github(packages.b), 'b.json comparison'); + t.equal(url, github(packages.c), 'c.json comparison'); + t.equal(url, github(packages.d), 'd.json comparison'); + t.equal(url, github(packages.e), 'e.json comparison'); +}); diff --git a/node_modules/glob-parent/LICENSE b/node_modules/glob-parent/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d701b08324fac71d4da754bbceee539b402b4623 --- /dev/null +++ b/node_modules/glob-parent/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2015, 2019 Elan Shanker, 2021 Blaine Bublitz , Eric Schoffstall and other contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob-parent/README.md b/node_modules/glob-parent/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6ae18a1a089e55a3c97e0c719e6ef9c7ffea982e --- /dev/null +++ b/node_modules/glob-parent/README.md @@ -0,0 +1,134 @@ +

+ + + +

+ +# glob-parent + +[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][ci-image]][ci-url] [![Coveralls Status][coveralls-image]][coveralls-url] + +Extract the non-magic parent path from a glob string. + +## Usage + +```js +var globParent = require('glob-parent'); + +globParent('path/to/*.js'); // 'path/to' +globParent('/root/path/to/*.js'); // '/root/path/to' +globParent('/*.js'); // '/' +globParent('*.js'); // '.' +globParent('**/*.js'); // '.' +globParent('path/{to,from}'); // 'path' +globParent('path/!(to|from)'); // 'path' +globParent('path/?(to|from)'); // 'path' +globParent('path/+(to|from)'); // 'path' +globParent('path/*(to|from)'); // 'path' +globParent('path/@(to|from)'); // 'path' +globParent('path/**/*'); // 'path' + +// if provided a non-glob path, returns the nearest dir +globParent('path/foo/bar.js'); // 'path/foo' +globParent('path/foo/'); // 'path/foo' +globParent('path/foo'); // 'path' (see issue #3 for details) +``` + +## API + +### `globParent(maybeGlobString, [options])` + +Takes a string and returns the part of the path before the glob begins. Be aware of Escaping rules and Limitations below. + +#### options + +```js +{ + // Disables the automatic conversion of slashes for Windows + flipBackslashes: true; +} +``` + +## Escaping + +The following characters have special significance in glob patterns and must be escaped if you want them to be treated as regular path characters: + +- `?` (question mark) unless used as a path segment alone +- `*` (asterisk) +- `|` (pipe) +- `(` (opening parenthesis) +- `)` (closing parenthesis) +- `{` (opening curly brace) +- `}` (closing curly brace) +- `[` (opening bracket) +- `]` (closing bracket) + +**Example** + +```js +globParent('foo/[bar]/'); // 'foo' +globParent('foo/\\[bar]/'); // 'foo/[bar]' +``` + +## Limitations + +### Braces & Brackets + +This library attempts a quick and imperfect method of determining which path +parts have glob magic without fully parsing/lexing the pattern. There are some +advanced use cases that can trip it up, such as nested braces where the outer +pair is escaped and the inner one contains a path separator. If you find +yourself in the unlikely circumstance of being affected by this or need to +ensure higher-fidelity glob handling in your library, it is recommended that you +pre-process your input with [expand-braces] and/or [expand-brackets]. + +### Windows + +Backslashes are not valid path separators for globs. If a path with backslashes +is provided anyway, for simple cases, glob-parent will replace the path +separator for you and return the non-glob parent path (now with +forward-slashes, which are still valid as Windows path separators). + +This cannot be used in conjunction with escape characters. + +```js +// BAD +globParent('C:\\Program Files \\(x86\\)\\*.ext'); // 'C:/Program Files /(x86/)' + +// GOOD +globParent('C:/Program Files\\(x86\\)/*.ext'); // 'C:/Program Files (x86)' +``` + +If you are using escape characters for a pattern without path parts (i.e. +relative to `cwd`), prefix with `./` to avoid confusing glob-parent. + +```js +// BAD +globParent('foo \\[bar]'); // 'foo ' +globParent('foo \\[bar]*'); // 'foo ' + +// GOOD +globParent('./foo \\[bar]'); // 'foo [bar]' +globParent('./foo \\[bar]*'); // '.' +``` + +## License + +ISC + + +[downloads-image]: https://img.shields.io/npm/dm/glob-parent.svg?style=flat-square +[npm-url]: https://www.npmjs.com/package/glob-parent +[npm-image]: https://img.shields.io/npm/v/glob-parent.svg?style=flat-square + +[ci-url]: https://github.com/gulpjs/glob-parent/actions?query=workflow:dev +[ci-image]: https://img.shields.io/github/workflow/status/gulpjs/glob-parent/dev?style=flat-square + +[coveralls-url]: https://coveralls.io/r/gulpjs/glob-parent +[coveralls-image]: https://img.shields.io/coveralls/gulpjs/glob-parent/master.svg?style=flat-square + + + +[expand-braces]: https://github.com/jonschlinkert/expand-braces +[expand-brackets]: https://github.com/jonschlinkert/expand-brackets + diff --git a/node_modules/glob-parent/index.js b/node_modules/glob-parent/index.js new file mode 100644 index 0000000000000000000000000000000000000000..09dde64ba7c12cbfa38474af10db668d6bfd5a70 --- /dev/null +++ b/node_modules/glob-parent/index.js @@ -0,0 +1,75 @@ +'use strict'; + +var isGlob = require('is-glob'); +var pathPosixDirname = require('path').posix.dirname; +var isWin32 = require('os').platform() === 'win32'; + +var slash = '/'; +var backslash = /\\/g; +var escaped = /\\([!*?|[\](){}])/g; + +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ +module.exports = function globParent(str, opts) { + var options = Object.assign({ flipBackslashes: true }, opts); + + // flip windows path separators + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } + + // special case for strings ending in enclosure containing path separator + if (isEnclosure(str)) { + str += slash; + } + + // preserves full path in case of trailing path separator + str += 'a'; + + // remove path parts that are globby + do { + str = pathPosixDirname(str); + } while (isGlobby(str)); + + // remove escape chars and return result + return str.replace(escaped, '$1'); +}; + +function isEnclosure(str) { + var lastChar = str.slice(-1); + + var enclosureStart; + switch (lastChar) { + case '}': + enclosureStart = '{'; + break; + case ']': + enclosureStart = '['; + break; + default: + return false; + } + + var foundIndex = str.indexOf(enclosureStart); + if (foundIndex < 0) { + return false; + } + + return str.slice(foundIndex + 1, -1).includes(slash); +} + +function isGlobby(str) { + if (/\([^()]+$/.test(str)) { + return true; + } + if (str[0] === '{' || str[0] === '[') { + return true; + } + if (/[^\\][{[]/.test(str)) { + return true; + } + return isGlob(str); +} diff --git a/node_modules/glob-parent/package.json b/node_modules/glob-parent/package.json new file mode 100644 index 0000000000000000000000000000000000000000..baeab4217a04fce13604502b17d4fd8cde540b1c --- /dev/null +++ b/node_modules/glob-parent/package.json @@ -0,0 +1,54 @@ +{ + "name": "glob-parent", + "version": "6.0.2", + "description": "Extract the non-magic parent path from a glob string.", + "author": "Gulp Team (https://gulpjs.com/)", + "contributors": [ + "Elan Shanker (https://github.com/es128)", + "Blaine Bublitz " + ], + "repository": "gulpjs/glob-parent", + "license": "ISC", + "engines": { + "node": ">=10.13.0" + }, + "main": "index.js", + "files": [ + "LICENSE", + "index.js" + ], + "scripts": { + "lint": "eslint .", + "pretest": "npm run lint", + "test": "nyc mocha --async-only" + }, + "dependencies": { + "is-glob": "^4.0.3" + }, + "devDependencies": { + "eslint": "^7.0.0", + "eslint-config-gulp": "^5.0.0", + "expect": "^26.0.1", + "mocha": "^7.1.2", + "nyc": "^15.0.1" + }, + "nyc": { + "reporter": [ + "lcov", + "text-summary" + ] + }, + "prettier": { + "singleQuote": true + }, + "keywords": [ + "glob", + "parent", + "strip", + "path", + "dirname", + "directory", + "base", + "wildcard" + ] +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..39e8fe16f665aede689ed7ac7e51eac61825ed7b --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2009-2022 Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62939110a618992a4ae9b044e8a70f1e2ccc7d34 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,399 @@ +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![a fun cartoon logo made of glob characters](logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* `cb` `{Function}` + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* return: `{Array}` filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` `{String}` pattern to search for +* `options` `{Object}` +* `cb` `{Function}` Called when an error occurs, or matches are found + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'FILE'` - Path exists, and is not a directory + * `'DIR'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the specific + thing that matched. It is not deduplicated or resolved to a realpath. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. This option is always coerced to use + forward-slashes as a path separator, because it is not tested + as a glob pattern, so there is no need to escape anything. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) This option is + always coerced to use forward-slashes as a path separator, + because it is not tested as a glob pattern, so there is no need + to escape anything. +* `windowsPathsNoEscape` Use `\\` as a path separator _only_, and + _never_ as an escape character. If set, all `\\` characters + are replaced with `/` in the pattern. Note that this makes it + **impossible** to match against paths containing literal glob + pattern characters, but allows matching with patterns constructed + using `path.join()` and `path.resolve()` on Windows platforms, + mimicking the (buggy!) behavior of Glob v7 and before on + Windows. Please use with caution, and be mindful of [the caveat + below about Windows paths](#windows). (For legacy reasons, + this is also set if `allowWindowsEscape` is set to the exact + value `false`.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of glob patterns to exclude matches. + Note: `ignore` patterns are *always* in `dot:true` mode, regardless + of any other settings. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) +* `absolute` Set to true to always receive absolute paths for matched + files. Unlike `realpath`, this also affects the values returned in + the `match` event. +* `fs` File-system object with Node's `fs` API. By default, the built-in + `fs` module will be used. Set to a volume provided by a library like + `memfs` to avoid using the "real" file-system. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if it +started with a `#` character, or a "negated" pattern if it started +with a `!` character. + +These options were deprecated in version 5, and removed in version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +To automatically coerce all `\` characters to `/` in pattern +strings, **thus making it impossible to escape literal glob +characters**, you may set the `windowsPathsNoEscape` option to +`true`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` + +![](oh-my-glob.gif) diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js new file mode 100644 index 0000000000000000000000000000000000000000..61a4452f097dcd28e7c2ed6ea1a45d643b8b1641 --- /dev/null +++ b/node_modules/glob/common.js @@ -0,0 +1,244 @@ +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var fs = require("fs") +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path").isAbsolute +var Minimatch = minimatch.Minimatch + +function alphasort (a, b) { + return a.localeCompare(b, 'en') +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (self.windowsPathsNoEscape) { + pattern = pattern.replace(/\\/g, '/') + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + self.fs = options.fs || fs + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = path.resolve(cwd) + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + self.nomount = !!options.nomount + + if (process.platform === "win32") { + self.root = self.root.replace(/\\/g, "/") + self.cwd = self.cwd.replace(/\\/g, "/") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + } + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js new file mode 100644 index 0000000000000000000000000000000000000000..2112a957dc501696f443f5620a4e34386a0d1957 --- /dev/null +++ b/node_modules/glob/glob.js @@ -0,0 +1,790 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path').isAbsolute +var globSync = require('./sync.js') +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + self.fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + self.fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + self.fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return self.fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ca0fd916211b51d257af897a46bef305b2d1cb78 --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,55 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me/)", + "name": "glob", + "description": "a little globber", + "version": "8.1.0", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "main": "glob.js", + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "engines": { + "node": ">=12" + }, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^5.0.1", + "once": "^1.3.0" + }, + "devDependencies": { + "memfs": "^3.2.0", + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^16.0.1", + "tick": "0.0.6" + }, + "tap": { + "before": "test/00-setup.js", + "after": "test/zz-cleanup.js", + "statements": 90, + "branches": 90, + "functions": 90, + "lines": 90, + "jobs": 1 + }, + "scripts": { + "prepublish": "npm run benchclean", + "profclean": "rm -f v8.log profile.txt", + "test": "tap", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", + "bench": "bash benchmark.sh", + "prof": "bash prof.sh && cat profile.txt", + "benchclean": "node benchclean.js" + }, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } +} diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js new file mode 100644 index 0000000000000000000000000000000000000000..af4600dd595081284a70874f73b31d318a71dcdb --- /dev/null +++ b/node_modules/glob/sync.js @@ -0,0 +1,486 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path').isAbsolute +var common = require('./common.js') +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert.ok(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert.ok(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, this.fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = this.fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = this.fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/globals/globals.json b/node_modules/globals/globals.json new file mode 100644 index 0000000000000000000000000000000000000000..4e75173f051713d61b2300871ff9a2d72d783a61 --- /dev/null +++ b/node_modules/globals/globals.json @@ -0,0 +1,1998 @@ +{ + "builtin": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "es5": { + "Array": false, + "Boolean": false, + "constructor": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "propertyIsEnumerable": false, + "RangeError": false, + "ReferenceError": false, + "RegExp": false, + "String": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false + }, + "es2015": { + "Array": false, + "ArrayBuffer": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2017": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2020": { + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakSet": false + }, + "es2021": { + "AggregateError": false, + "Array": false, + "ArrayBuffer": false, + "Atomics": false, + "BigInt": false, + "BigInt64Array": false, + "BigUint64Array": false, + "Boolean": false, + "constructor": false, + "DataView": false, + "Date": false, + "decodeURI": false, + "decodeURIComponent": false, + "encodeURI": false, + "encodeURIComponent": false, + "Error": false, + "escape": false, + "eval": false, + "EvalError": false, + "FinalizationRegistry": false, + "Float32Array": false, + "Float64Array": false, + "Function": false, + "globalThis": false, + "hasOwnProperty": false, + "Infinity": false, + "Int16Array": false, + "Int32Array": false, + "Int8Array": false, + "isFinite": false, + "isNaN": false, + "isPrototypeOf": false, + "JSON": false, + "Map": false, + "Math": false, + "NaN": false, + "Number": false, + "Object": false, + "parseFloat": false, + "parseInt": false, + "Promise": false, + "propertyIsEnumerable": false, + "Proxy": false, + "RangeError": false, + "ReferenceError": false, + "Reflect": false, + "RegExp": false, + "Set": false, + "SharedArrayBuffer": false, + "String": false, + "Symbol": false, + "SyntaxError": false, + "toLocaleString": false, + "toString": false, + "TypeError": false, + "Uint16Array": false, + "Uint32Array": false, + "Uint8Array": false, + "Uint8ClampedArray": false, + "undefined": false, + "unescape": false, + "URIError": false, + "valueOf": false, + "WeakMap": false, + "WeakRef": false, + "WeakSet": false + }, + "browser": { + "AbortController": false, + "AbortSignal": false, + "addEventListener": false, + "alert": false, + "AnalyserNode": false, + "Animation": false, + "AnimationEffectReadOnly": false, + "AnimationEffectTiming": false, + "AnimationEffectTimingReadOnly": false, + "AnimationEvent": false, + "AnimationPlaybackEvent": false, + "AnimationTimeline": false, + "applicationCache": false, + "ApplicationCache": false, + "ApplicationCacheErrorEvent": false, + "atob": false, + "Attr": false, + "Audio": false, + "AudioBuffer": false, + "AudioBufferSourceNode": false, + "AudioContext": false, + "AudioDestinationNode": false, + "AudioListener": false, + "AudioNode": false, + "AudioParam": false, + "AudioProcessingEvent": false, + "AudioScheduledSourceNode": false, + "AudioWorkletGlobalScope": false, + "AudioWorkletNode": false, + "AudioWorkletProcessor": false, + "BarProp": false, + "BaseAudioContext": false, + "BatteryManager": false, + "BeforeUnloadEvent": false, + "BiquadFilterNode": false, + "Blob": false, + "BlobEvent": false, + "blur": false, + "BroadcastChannel": false, + "btoa": false, + "BudgetService": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "cancelAnimationFrame": false, + "cancelIdleCallback": false, + "CanvasCaptureMediaStreamTrack": false, + "CanvasGradient": false, + "CanvasPattern": false, + "CanvasRenderingContext2D": false, + "ChannelMergerNode": false, + "ChannelSplitterNode": false, + "CharacterData": false, + "clearInterval": false, + "clearTimeout": false, + "clientInformation": false, + "ClipboardEvent": false, + "ClipboardItem": false, + "close": false, + "closed": false, + "CloseEvent": false, + "Comment": false, + "CompositionEvent": false, + "CompressionStream": false, + "confirm": false, + "console": false, + "ConstantSourceNode": false, + "ConvolverNode": false, + "CountQueuingStrategy": false, + "createImageBitmap": false, + "Credential": false, + "CredentialsContainer": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CSS": false, + "CSSConditionRule": false, + "CSSFontFaceRule": false, + "CSSGroupingRule": false, + "CSSImportRule": false, + "CSSKeyframeRule": false, + "CSSKeyframesRule": false, + "CSSMatrixComponent": false, + "CSSMediaRule": false, + "CSSNamespaceRule": false, + "CSSPageRule": false, + "CSSPerspective": false, + "CSSRotate": false, + "CSSRule": false, + "CSSRuleList": false, + "CSSScale": false, + "CSSSkew": false, + "CSSSkewX": false, + "CSSSkewY": false, + "CSSStyleDeclaration": false, + "CSSStyleRule": false, + "CSSStyleSheet": false, + "CSSSupportsRule": false, + "CSSTransformValue": false, + "CSSTranslate": false, + "CustomElementRegistry": false, + "customElements": false, + "CustomEvent": false, + "DataTransfer": false, + "DataTransferItem": false, + "DataTransferItemList": false, + "DecompressionStream": false, + "defaultstatus": false, + "defaultStatus": false, + "DelayNode": false, + "DeviceMotionEvent": false, + "DeviceOrientationEvent": false, + "devicePixelRatio": false, + "dispatchEvent": false, + "document": false, + "Document": false, + "DocumentFragment": false, + "DocumentType": false, + "DOMError": false, + "DOMException": false, + "DOMImplementation": false, + "DOMMatrix": false, + "DOMMatrixReadOnly": false, + "DOMParser": false, + "DOMPoint": false, + "DOMPointReadOnly": false, + "DOMQuad": false, + "DOMRect": false, + "DOMRectList": false, + "DOMRectReadOnly": false, + "DOMStringList": false, + "DOMStringMap": false, + "DOMTokenList": false, + "DragEvent": false, + "DynamicsCompressorNode": false, + "Element": false, + "ErrorEvent": false, + "event": false, + "Event": false, + "EventSource": false, + "EventTarget": false, + "external": false, + "fetch": false, + "File": false, + "FileList": false, + "FileReader": false, + "find": false, + "focus": false, + "FocusEvent": false, + "FontFace": false, + "FontFaceSetLoadEvent": false, + "FormData": false, + "FormDataEvent": false, + "frameElement": false, + "frames": false, + "GainNode": false, + "Gamepad": false, + "GamepadButton": false, + "GamepadEvent": false, + "getComputedStyle": false, + "getSelection": false, + "HashChangeEvent": false, + "Headers": false, + "history": false, + "History": false, + "HTMLAllCollection": false, + "HTMLAnchorElement": false, + "HTMLAreaElement": false, + "HTMLAudioElement": false, + "HTMLBaseElement": false, + "HTMLBodyElement": false, + "HTMLBRElement": false, + "HTMLButtonElement": false, + "HTMLCanvasElement": false, + "HTMLCollection": false, + "HTMLContentElement": false, + "HTMLDataElement": false, + "HTMLDataListElement": false, + "HTMLDetailsElement": false, + "HTMLDialogElement": false, + "HTMLDirectoryElement": false, + "HTMLDivElement": false, + "HTMLDListElement": false, + "HTMLDocument": false, + "HTMLElement": false, + "HTMLEmbedElement": false, + "HTMLFieldSetElement": false, + "HTMLFontElement": false, + "HTMLFormControlsCollection": false, + "HTMLFormElement": false, + "HTMLFrameElement": false, + "HTMLFrameSetElement": false, + "HTMLHeadElement": false, + "HTMLHeadingElement": false, + "HTMLHRElement": false, + "HTMLHtmlElement": false, + "HTMLIFrameElement": false, + "HTMLImageElement": false, + "HTMLInputElement": false, + "HTMLLabelElement": false, + "HTMLLegendElement": false, + "HTMLLIElement": false, + "HTMLLinkElement": false, + "HTMLMapElement": false, + "HTMLMarqueeElement": false, + "HTMLMediaElement": false, + "HTMLMenuElement": false, + "HTMLMetaElement": false, + "HTMLMeterElement": false, + "HTMLModElement": false, + "HTMLObjectElement": false, + "HTMLOListElement": false, + "HTMLOptGroupElement": false, + "HTMLOptionElement": false, + "HTMLOptionsCollection": false, + "HTMLOutputElement": false, + "HTMLParagraphElement": false, + "HTMLParamElement": false, + "HTMLPictureElement": false, + "HTMLPreElement": false, + "HTMLProgressElement": false, + "HTMLQuoteElement": false, + "HTMLScriptElement": false, + "HTMLSelectElement": false, + "HTMLShadowElement": false, + "HTMLSlotElement": false, + "HTMLSourceElement": false, + "HTMLSpanElement": false, + "HTMLStyleElement": false, + "HTMLTableCaptionElement": false, + "HTMLTableCellElement": false, + "HTMLTableColElement": false, + "HTMLTableElement": false, + "HTMLTableRowElement": false, + "HTMLTableSectionElement": false, + "HTMLTemplateElement": false, + "HTMLTextAreaElement": false, + "HTMLTimeElement": false, + "HTMLTitleElement": false, + "HTMLTrackElement": false, + "HTMLUListElement": false, + "HTMLUnknownElement": false, + "HTMLVideoElement": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "IdleDeadline": false, + "IIRFilterNode": false, + "Image": false, + "ImageBitmap": false, + "ImageBitmapRenderingContext": false, + "ImageCapture": false, + "ImageData": false, + "indexedDB": false, + "innerHeight": false, + "innerWidth": false, + "InputEvent": false, + "IntersectionObserver": false, + "IntersectionObserverEntry": false, + "Intl": false, + "isSecureContext": false, + "KeyboardEvent": false, + "KeyframeEffect": false, + "KeyframeEffectReadOnly": false, + "length": false, + "localStorage": false, + "location": true, + "Location": false, + "locationbar": false, + "matchMedia": false, + "MediaDeviceInfo": false, + "MediaDevices": false, + "MediaElementAudioSourceNode": false, + "MediaEncryptedEvent": false, + "MediaError": false, + "MediaKeyMessageEvent": false, + "MediaKeySession": false, + "MediaKeyStatusMap": false, + "MediaKeySystemAccess": false, + "MediaList": false, + "MediaMetadata": false, + "MediaQueryList": false, + "MediaQueryListEvent": false, + "MediaRecorder": false, + "MediaSettingsRange": false, + "MediaSource": false, + "MediaStream": false, + "MediaStreamAudioDestinationNode": false, + "MediaStreamAudioSourceNode": false, + "MediaStreamConstraints": false, + "MediaStreamEvent": false, + "MediaStreamTrack": false, + "MediaStreamTrackEvent": false, + "menubar": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "MIDIAccess": false, + "MIDIConnectionEvent": false, + "MIDIInput": false, + "MIDIInputMap": false, + "MIDIMessageEvent": false, + "MIDIOutput": false, + "MIDIOutputMap": false, + "MIDIPort": false, + "MimeType": false, + "MimeTypeArray": false, + "MouseEvent": false, + "moveBy": false, + "moveTo": false, + "MutationEvent": false, + "MutationObserver": false, + "MutationRecord": false, + "name": false, + "NamedNodeMap": false, + "NavigationPreloadManager": false, + "navigator": false, + "Navigator": false, + "NavigatorUAData": false, + "NetworkInformation": false, + "Node": false, + "NodeFilter": false, + "NodeIterator": false, + "NodeList": false, + "Notification": false, + "OfflineAudioCompletionEvent": false, + "OfflineAudioContext": false, + "offscreenBuffering": false, + "OffscreenCanvas": true, + "OffscreenCanvasRenderingContext2D": false, + "onabort": true, + "onafterprint": true, + "onanimationend": true, + "onanimationiteration": true, + "onanimationstart": true, + "onappinstalled": true, + "onauxclick": true, + "onbeforeinstallprompt": true, + "onbeforeprint": true, + "onbeforeunload": true, + "onblur": true, + "oncancel": true, + "oncanplay": true, + "oncanplaythrough": true, + "onchange": true, + "onclick": true, + "onclose": true, + "oncontextmenu": true, + "oncuechange": true, + "ondblclick": true, + "ondevicemotion": true, + "ondeviceorientation": true, + "ondeviceorientationabsolute": true, + "ondrag": true, + "ondragend": true, + "ondragenter": true, + "ondragleave": true, + "ondragover": true, + "ondragstart": true, + "ondrop": true, + "ondurationchange": true, + "onemptied": true, + "onended": true, + "onerror": true, + "onfocus": true, + "ongotpointercapture": true, + "onhashchange": true, + "oninput": true, + "oninvalid": true, + "onkeydown": true, + "onkeypress": true, + "onkeyup": true, + "onlanguagechange": true, + "onload": true, + "onloadeddata": true, + "onloadedmetadata": true, + "onloadstart": true, + "onlostpointercapture": true, + "onmessage": true, + "onmessageerror": true, + "onmousedown": true, + "onmouseenter": true, + "onmouseleave": true, + "onmousemove": true, + "onmouseout": true, + "onmouseover": true, + "onmouseup": true, + "onmousewheel": true, + "onoffline": true, + "ononline": true, + "onpagehide": true, + "onpageshow": true, + "onpause": true, + "onplay": true, + "onplaying": true, + "onpointercancel": true, + "onpointerdown": true, + "onpointerenter": true, + "onpointerleave": true, + "onpointermove": true, + "onpointerout": true, + "onpointerover": true, + "onpointerup": true, + "onpopstate": true, + "onprogress": true, + "onratechange": true, + "onrejectionhandled": true, + "onreset": true, + "onresize": true, + "onscroll": true, + "onsearch": true, + "onseeked": true, + "onseeking": true, + "onselect": true, + "onstalled": true, + "onstorage": true, + "onsubmit": true, + "onsuspend": true, + "ontimeupdate": true, + "ontoggle": true, + "ontransitionend": true, + "onunhandledrejection": true, + "onunload": true, + "onvolumechange": true, + "onwaiting": true, + "onwheel": true, + "open": false, + "openDatabase": false, + "opener": false, + "Option": false, + "origin": false, + "OscillatorNode": false, + "outerHeight": false, + "outerWidth": false, + "OverconstrainedError": false, + "PageTransitionEvent": false, + "pageXOffset": false, + "pageYOffset": false, + "PannerNode": false, + "parent": false, + "Path2D": false, + "PaymentAddress": false, + "PaymentRequest": false, + "PaymentRequestUpdateEvent": false, + "PaymentResponse": false, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceLongTaskTiming": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceNavigationTiming": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformancePaintTiming": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "PeriodicWave": false, + "Permissions": false, + "PermissionStatus": false, + "personalbar": false, + "PhotoCapabilities": false, + "Plugin": false, + "PluginArray": false, + "PointerEvent": false, + "PopStateEvent": false, + "postMessage": false, + "Presentation": false, + "PresentationAvailability": false, + "PresentationConnection": false, + "PresentationConnectionAvailableEvent": false, + "PresentationConnectionCloseEvent": false, + "PresentationConnectionList": false, + "PresentationReceiver": false, + "PresentationRequest": false, + "print": false, + "ProcessingInstruction": false, + "ProgressEvent": false, + "PromiseRejectionEvent": false, + "prompt": false, + "PushManager": false, + "PushSubscription": false, + "PushSubscriptionOptions": false, + "queueMicrotask": false, + "RadioNodeList": false, + "Range": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registerProcessor": false, + "RemotePlayback": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "requestAnimationFrame": false, + "requestIdleCallback": false, + "resizeBy": false, + "ResizeObserver": false, + "ResizeObserverEntry": false, + "resizeTo": false, + "Response": false, + "RTCCertificate": false, + "RTCDataChannel": false, + "RTCDataChannelEvent": false, + "RTCDtlsTransport": false, + "RTCIceCandidate": false, + "RTCIceGatherer": false, + "RTCIceTransport": false, + "RTCPeerConnection": false, + "RTCPeerConnectionIceEvent": false, + "RTCRtpContributingSource": false, + "RTCRtpReceiver": false, + "RTCRtpSender": false, + "RTCSctpTransport": false, + "RTCSessionDescription": false, + "RTCStatsReport": false, + "RTCTrackEvent": false, + "screen": false, + "Screen": false, + "screenLeft": false, + "ScreenOrientation": false, + "screenTop": false, + "screenX": false, + "screenY": false, + "ScriptProcessorNode": false, + "scroll": false, + "scrollbars": false, + "scrollBy": false, + "scrollTo": false, + "scrollX": false, + "scrollY": false, + "SecurityPolicyViolationEvent": false, + "Selection": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerRegistration": false, + "sessionStorage": false, + "setInterval": false, + "setTimeout": false, + "ShadowRoot": false, + "SharedWorker": false, + "SourceBuffer": false, + "SourceBufferList": false, + "speechSynthesis": false, + "SpeechSynthesisEvent": false, + "SpeechSynthesisUtterance": false, + "StaticRange": false, + "status": false, + "statusbar": false, + "StereoPannerNode": false, + "stop": false, + "Storage": false, + "StorageEvent": false, + "StorageManager": false, + "structuredClone": false, + "styleMedia": false, + "StyleSheet": false, + "StyleSheetList": false, + "SubmitEvent": false, + "SubtleCrypto": false, + "SVGAElement": false, + "SVGAngle": false, + "SVGAnimatedAngle": false, + "SVGAnimatedBoolean": false, + "SVGAnimatedEnumeration": false, + "SVGAnimatedInteger": false, + "SVGAnimatedLength": false, + "SVGAnimatedLengthList": false, + "SVGAnimatedNumber": false, + "SVGAnimatedNumberList": false, + "SVGAnimatedPreserveAspectRatio": false, + "SVGAnimatedRect": false, + "SVGAnimatedString": false, + "SVGAnimatedTransformList": false, + "SVGAnimateElement": false, + "SVGAnimateMotionElement": false, + "SVGAnimateTransformElement": false, + "SVGAnimationElement": false, + "SVGCircleElement": false, + "SVGClipPathElement": false, + "SVGComponentTransferFunctionElement": false, + "SVGDefsElement": false, + "SVGDescElement": false, + "SVGDiscardElement": false, + "SVGElement": false, + "SVGEllipseElement": false, + "SVGFEBlendElement": false, + "SVGFEColorMatrixElement": false, + "SVGFEComponentTransferElement": false, + "SVGFECompositeElement": false, + "SVGFEConvolveMatrixElement": false, + "SVGFEDiffuseLightingElement": false, + "SVGFEDisplacementMapElement": false, + "SVGFEDistantLightElement": false, + "SVGFEDropShadowElement": false, + "SVGFEFloodElement": false, + "SVGFEFuncAElement": false, + "SVGFEFuncBElement": false, + "SVGFEFuncGElement": false, + "SVGFEFuncRElement": false, + "SVGFEGaussianBlurElement": false, + "SVGFEImageElement": false, + "SVGFEMergeElement": false, + "SVGFEMergeNodeElement": false, + "SVGFEMorphologyElement": false, + "SVGFEOffsetElement": false, + "SVGFEPointLightElement": false, + "SVGFESpecularLightingElement": false, + "SVGFESpotLightElement": false, + "SVGFETileElement": false, + "SVGFETurbulenceElement": false, + "SVGFilterElement": false, + "SVGForeignObjectElement": false, + "SVGGElement": false, + "SVGGeometryElement": false, + "SVGGradientElement": false, + "SVGGraphicsElement": false, + "SVGImageElement": false, + "SVGLength": false, + "SVGLengthList": false, + "SVGLinearGradientElement": false, + "SVGLineElement": false, + "SVGMarkerElement": false, + "SVGMaskElement": false, + "SVGMatrix": false, + "SVGMetadataElement": false, + "SVGMPathElement": false, + "SVGNumber": false, + "SVGNumberList": false, + "SVGPathElement": false, + "SVGPatternElement": false, + "SVGPoint": false, + "SVGPointList": false, + "SVGPolygonElement": false, + "SVGPolylineElement": false, + "SVGPreserveAspectRatio": false, + "SVGRadialGradientElement": false, + "SVGRect": false, + "SVGRectElement": false, + "SVGScriptElement": false, + "SVGSetElement": false, + "SVGStopElement": false, + "SVGStringList": false, + "SVGStyleElement": false, + "SVGSVGElement": false, + "SVGSwitchElement": false, + "SVGSymbolElement": false, + "SVGTextContentElement": false, + "SVGTextElement": false, + "SVGTextPathElement": false, + "SVGTextPositioningElement": false, + "SVGTitleElement": false, + "SVGTransform": false, + "SVGTransformList": false, + "SVGTSpanElement": false, + "SVGUnitTypes": false, + "SVGUseElement": false, + "SVGViewElement": false, + "TaskAttributionTiming": false, + "Text": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TextEvent": false, + "TextMetrics": false, + "TextTrack": false, + "TextTrackCue": false, + "TextTrackCueList": false, + "TextTrackList": false, + "TimeRanges": false, + "ToggleEvent": false, + "toolbar": false, + "top": false, + "Touch": false, + "TouchEvent": false, + "TouchList": false, + "TrackEvent": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "TransitionEvent": false, + "TreeWalker": false, + "UIEvent": false, + "URL": false, + "URLSearchParams": false, + "ValidityState": false, + "visualViewport": false, + "VisualViewport": false, + "VTTCue": false, + "WaveShaperNode": false, + "WebAssembly": false, + "WebGL2RenderingContext": false, + "WebGLActiveInfo": false, + "WebGLBuffer": false, + "WebGLContextEvent": false, + "WebGLFramebuffer": false, + "WebGLProgram": false, + "WebGLQuery": false, + "WebGLRenderbuffer": false, + "WebGLRenderingContext": false, + "WebGLSampler": false, + "WebGLShader": false, + "WebGLShaderPrecisionFormat": false, + "WebGLSync": false, + "WebGLTexture": false, + "WebGLTransformFeedback": false, + "WebGLUniformLocation": false, + "WebGLVertexArrayObject": false, + "WebSocket": false, + "WheelEvent": false, + "window": false, + "Window": false, + "Worker": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLDocument": false, + "XMLHttpRequest": false, + "XMLHttpRequestEventTarget": false, + "XMLHttpRequestUpload": false, + "XMLSerializer": false, + "XPathEvaluator": false, + "XPathExpression": false, + "XPathResult": false, + "XRAnchor": false, + "XRBoundedReferenceSpace": false, + "XRCPUDepthInformation": false, + "XRDepthInformation": false, + "XRFrame": false, + "XRInputSource": false, + "XRInputSourceArray": false, + "XRInputSourceEvent": false, + "XRInputSourcesChangeEvent": false, + "XRPose": false, + "XRReferenceSpace": false, + "XRReferenceSpaceEvent": false, + "XRRenderState": false, + "XRRigidTransform": false, + "XRSession": false, + "XRSessionEvent": false, + "XRSpace": false, + "XRSystem": false, + "XRView": false, + "XRViewerPose": false, + "XRViewport": false, + "XRWebGLBinding": false, + "XRWebGLDepthInformation": false, + "XRWebGLLayer": false, + "XSLTProcessor": false + }, + "worker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "clearInterval": false, + "clearTimeout": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "fetch": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": true, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onlanguagechange": true, + "onmessage": true, + "onoffline": true, + "ononline": true, + "onrejectionhandled": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "removeEventListener": false, + "reportError": false, + "Request": false, + "Response": false, + "self": true, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "node": { + "__dirname": false, + "__filename": false, + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "exports": true, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "module": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "require": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "nodeBuiltin": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "Buffer": false, + "ByteLengthQueuingStrategy": false, + "clearImmediate": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "global": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "process": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setImmediate": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "commonjs": { + "exports": true, + "global": false, + "module": false, + "require": false + }, + "amd": { + "define": false, + "require": false + }, + "mocha": { + "after": false, + "afterEach": false, + "before": false, + "beforeEach": false, + "context": false, + "describe": false, + "it": false, + "mocha": false, + "run": false, + "setup": false, + "specify": false, + "suite": false, + "suiteSetup": false, + "suiteTeardown": false, + "teardown": false, + "test": false, + "xcontext": false, + "xdescribe": false, + "xit": false, + "xspecify": false + }, + "jasmine": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "expectAsync": false, + "fail": false, + "fdescribe": false, + "fit": false, + "it": false, + "jasmine": false, + "pending": false, + "runs": false, + "spyOn": false, + "spyOnAllFunctions": false, + "spyOnProperty": false, + "waits": false, + "waitsFor": false, + "xdescribe": false, + "xit": false + }, + "jest": { + "afterAll": false, + "afterEach": false, + "beforeAll": false, + "beforeEach": false, + "describe": false, + "expect": false, + "fdescribe": false, + "fit": false, + "it": false, + "jest": false, + "pit": false, + "require": false, + "test": false, + "xdescribe": false, + "xit": false, + "xtest": false + }, + "qunit": { + "asyncTest": false, + "deepEqual": false, + "equal": false, + "expect": false, + "module": false, + "notDeepEqual": false, + "notEqual": false, + "notOk": false, + "notPropEqual": false, + "notStrictEqual": false, + "ok": false, + "propEqual": false, + "QUnit": false, + "raises": false, + "start": false, + "stop": false, + "strictEqual": false, + "test": false, + "throws": false + }, + "phantomjs": { + "console": true, + "exports": true, + "phantom": true, + "require": true, + "WebPage": true + }, + "couch": { + "emit": false, + "exports": false, + "getRow": false, + "log": false, + "module": false, + "provides": false, + "require": false, + "respond": false, + "send": false, + "start": false, + "sum": false + }, + "rhino": { + "defineClass": false, + "deserialize": false, + "gc": false, + "help": false, + "importClass": false, + "importPackage": false, + "java": false, + "load": false, + "loadClass": false, + "Packages": false, + "print": false, + "quit": false, + "readFile": false, + "readUrl": false, + "runCommand": false, + "seal": false, + "serialize": false, + "spawn": false, + "sync": false, + "toint32": false, + "version": false + }, + "nashorn": { + "__DIR__": false, + "__FILE__": false, + "__LINE__": false, + "com": false, + "edu": false, + "exit": false, + "java": false, + "Java": false, + "javafx": false, + "JavaImporter": false, + "javax": false, + "JSAdapter": false, + "load": false, + "loadWithNewGlobal": false, + "org": false, + "Packages": false, + "print": false, + "quit": false + }, + "wsh": { + "ActiveXObject": false, + "CollectGarbage": false, + "Debug": false, + "Enumerator": false, + "GetObject": false, + "RuntimeObject": false, + "ScriptEngine": false, + "ScriptEngineBuildVersion": false, + "ScriptEngineMajorVersion": false, + "ScriptEngineMinorVersion": false, + "VBArray": false, + "WScript": false, + "WSH": false + }, + "jquery": { + "$": false, + "jQuery": false + }, + "yui": { + "YAHOO": false, + "YAHOO_config": false, + "YUI": false, + "YUI_config": false + }, + "shelljs": { + "cat": false, + "cd": false, + "chmod": false, + "config": false, + "cp": false, + "dirs": false, + "echo": false, + "env": false, + "error": false, + "exec": false, + "exit": false, + "find": false, + "grep": false, + "ln": false, + "ls": false, + "mkdir": false, + "mv": false, + "popd": false, + "pushd": false, + "pwd": false, + "rm": false, + "sed": false, + "set": false, + "target": false, + "tempdir": false, + "test": false, + "touch": false, + "which": false + }, + "prototypejs": { + "$": false, + "$$": false, + "$A": false, + "$break": false, + "$continue": false, + "$F": false, + "$H": false, + "$R": false, + "$w": false, + "Abstract": false, + "Ajax": false, + "Autocompleter": false, + "Builder": false, + "Class": false, + "Control": false, + "Draggable": false, + "Draggables": false, + "Droppables": false, + "Effect": false, + "Element": false, + "Enumerable": false, + "Event": false, + "Field": false, + "Form": false, + "Hash": false, + "Insertion": false, + "ObjectRange": false, + "PeriodicalExecuter": false, + "Position": false, + "Prototype": false, + "Scriptaculous": false, + "Selector": false, + "Sortable": false, + "SortableObserver": false, + "Sound": false, + "Template": false, + "Toggle": false, + "Try": false + }, + "meteor": { + "$": false, + "Accounts": false, + "AccountsClient": false, + "AccountsCommon": false, + "AccountsServer": false, + "App": false, + "Assets": false, + "Blaze": false, + "check": false, + "Cordova": false, + "DDP": false, + "DDPRateLimiter": false, + "DDPServer": false, + "Deps": false, + "EJSON": false, + "Email": false, + "HTTP": false, + "Log": false, + "Match": false, + "Meteor": false, + "Mongo": false, + "MongoInternals": false, + "Npm": false, + "Package": false, + "Plugin": false, + "process": false, + "Random": false, + "ReactiveDict": false, + "ReactiveVar": false, + "Router": false, + "ServiceConfiguration": false, + "Session": false, + "share": false, + "Spacebars": false, + "Template": false, + "Tinytest": false, + "Tracker": false, + "UI": false, + "Utils": false, + "WebApp": false, + "WebAppInternals": false + }, + "mongo": { + "_isWindows": false, + "_rand": false, + "BulkWriteResult": false, + "cat": false, + "cd": false, + "connect": false, + "db": false, + "getHostName": false, + "getMemInfo": false, + "hostname": false, + "ISODate": false, + "listFiles": false, + "load": false, + "ls": false, + "md5sumFile": false, + "mkdir": false, + "Mongo": false, + "NumberInt": false, + "NumberLong": false, + "ObjectId": false, + "PlanCache": false, + "print": false, + "printjson": false, + "pwd": false, + "quit": false, + "removeFile": false, + "rs": false, + "sh": false, + "UUID": false, + "version": false, + "WriteResult": false + }, + "applescript": { + "$": false, + "Application": false, + "Automation": false, + "console": false, + "delay": false, + "Library": false, + "ObjC": false, + "ObjectSpecifier": false, + "Path": false, + "Progress": false, + "Ref": false + }, + "serviceworker": { + "addEventListener": false, + "applicationCache": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "Cache": false, + "caches": false, + "CacheStorage": false, + "clearInterval": false, + "clearTimeout": false, + "Client": false, + "clients": false, + "Clients": false, + "close": true, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "ErrorEvent": false, + "Event": false, + "ExtendableEvent": false, + "ExtendableMessageEvent": false, + "fetch": false, + "FetchEvent": false, + "File": false, + "FileReaderSync": false, + "FormData": false, + "Headers": false, + "IDBCursor": false, + "IDBCursorWithValue": false, + "IDBDatabase": false, + "IDBFactory": false, + "IDBIndex": false, + "IDBKeyRange": false, + "IDBObjectStore": false, + "IDBOpenDBRequest": false, + "IDBRequest": false, + "IDBTransaction": false, + "IDBVersionChangeEvent": false, + "ImageData": false, + "importScripts": false, + "indexedDB": false, + "location": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "name": false, + "navigator": false, + "Notification": false, + "onclose": true, + "onconnect": true, + "onerror": true, + "onfetch": true, + "oninstall": true, + "onlanguagechange": true, + "onmessage": true, + "onmessageerror": true, + "onnotificationclick": true, + "onnotificationclose": true, + "onoffline": true, + "ononline": true, + "onpush": true, + "onpushsubscriptionchange": true, + "onrejectionhandled": true, + "onsync": true, + "onunhandledrejection": true, + "performance": false, + "Performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceNavigation": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "PerformanceTiming": false, + "postMessage": true, + "Promise": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "registration": false, + "removeEventListener": false, + "Request": false, + "Response": false, + "self": false, + "ServiceWorker": false, + "ServiceWorkerContainer": false, + "ServiceWorkerGlobalScope": false, + "ServiceWorkerMessageEvent": false, + "ServiceWorkerRegistration": false, + "setInterval": false, + "setTimeout": false, + "skipWaiting": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WebSocket": false, + "WindowClient": false, + "Worker": false, + "WorkerGlobalScope": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false, + "XMLHttpRequest": false + }, + "atomtest": { + "advanceClock": false, + "atom": false, + "fakeClearInterval": false, + "fakeClearTimeout": false, + "fakeSetInterval": false, + "fakeSetTimeout": false, + "resetTimeouts": false, + "waitsForPromise": false + }, + "embertest": { + "andThen": false, + "click": false, + "currentPath": false, + "currentRouteName": false, + "currentURL": false, + "fillIn": false, + "find": false, + "findAll": false, + "findWithAssert": false, + "keyEvent": false, + "pauseTest": false, + "resumeTest": false, + "triggerEvent": false, + "visit": false, + "wait": false + }, + "protractor": { + "$": false, + "$$": false, + "browser": false, + "by": false, + "By": false, + "DartObject": false, + "element": false, + "protractor": false + }, + "shared-node-browser": { + "AbortController": false, + "AbortSignal": false, + "atob": false, + "Blob": false, + "BroadcastChannel": false, + "btoa": false, + "ByteLengthQueuingStrategy": false, + "clearInterval": false, + "clearTimeout": false, + "CompressionStream": false, + "console": false, + "CountQueuingStrategy": false, + "crypto": false, + "Crypto": false, + "CryptoKey": false, + "CustomEvent": false, + "DecompressionStream": false, + "DOMException": false, + "Event": false, + "EventTarget": false, + "fetch": false, + "File": false, + "FormData": false, + "Headers": false, + "Intl": false, + "MessageChannel": false, + "MessageEvent": false, + "MessagePort": false, + "performance": false, + "PerformanceEntry": false, + "PerformanceMark": false, + "PerformanceMeasure": false, + "PerformanceObserver": false, + "PerformanceObserverEntryList": false, + "PerformanceResourceTiming": false, + "queueMicrotask": false, + "ReadableByteStreamController": false, + "ReadableStream": false, + "ReadableStreamBYOBReader": false, + "ReadableStreamBYOBRequest": false, + "ReadableStreamDefaultController": false, + "ReadableStreamDefaultReader": false, + "Request": false, + "Response": false, + "setInterval": false, + "setTimeout": false, + "structuredClone": false, + "SubtleCrypto": false, + "TextDecoder": false, + "TextDecoderStream": false, + "TextEncoder": false, + "TextEncoderStream": false, + "TransformStream": false, + "TransformStreamDefaultController": false, + "URL": false, + "URLSearchParams": false, + "WebAssembly": false, + "WritableStream": false, + "WritableStreamDefaultController": false, + "WritableStreamDefaultWriter": false + }, + "webextensions": { + "browser": false, + "chrome": false, + "opr": false + }, + "greasemonkey": { + "cloneInto": false, + "createObjectIn": false, + "exportFunction": false, + "GM": false, + "GM_addElement": false, + "GM_addStyle": false, + "GM_addValueChangeListener": false, + "GM_deleteValue": false, + "GM_download": false, + "GM_getResourceText": false, + "GM_getResourceURL": false, + "GM_getTab": false, + "GM_getTabs": false, + "GM_getValue": false, + "GM_info": false, + "GM_listValues": false, + "GM_log": false, + "GM_notification": false, + "GM_openInTab": false, + "GM_registerMenuCommand": false, + "GM_removeValueChangeListener": false, + "GM_saveTab": false, + "GM_setClipboard": false, + "GM_setValue": false, + "GM_unregisterMenuCommand": false, + "GM_xmlhttpRequest": false, + "unsafeWindow": false + }, + "devtools": { + "$": false, + "$_": false, + "$$": false, + "$0": false, + "$1": false, + "$2": false, + "$3": false, + "$4": false, + "$x": false, + "chrome": false, + "clear": false, + "copy": false, + "debug": false, + "dir": false, + "dirxml": false, + "getEventListeners": false, + "inspect": false, + "keys": false, + "monitor": false, + "monitorEvents": false, + "profile": false, + "profileEnd": false, + "queryObjects": false, + "table": false, + "undebug": false, + "unmonitor": false, + "unmonitorEvents": false, + "values": false + } +} diff --git a/node_modules/globals/index.d.ts b/node_modules/globals/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..edd861f9e56fda9765b26bf7afddedb20a0d585e --- /dev/null +++ b/node_modules/globals/index.d.ts @@ -0,0 +1,2077 @@ +// This file is autogenerated by scripts/generate-types.mjs +// Do NOT modify this file manually + +type GlobalsBuiltin = { + readonly 'AggregateError': false; + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'FinalizationRegistry': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakRef': false; + readonly 'WeakSet': false; +} + +type GlobalsEs5 = { + readonly 'Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'propertyIsEnumerable': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'RegExp': false; + readonly 'String': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; +} + +type GlobalsEs2015 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2017 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2020 = { + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakSet': false; +} + +type GlobalsEs2021 = { + readonly 'AggregateError': false; + readonly 'Array': false; + readonly 'ArrayBuffer': false; + readonly 'Atomics': false; + readonly 'BigInt': false; + readonly 'BigInt64Array': false; + readonly 'BigUint64Array': false; + readonly 'Boolean': false; + readonly 'constructor': false; + readonly 'DataView': false; + readonly 'Date': false; + readonly 'decodeURI': false; + readonly 'decodeURIComponent': false; + readonly 'encodeURI': false; + readonly 'encodeURIComponent': false; + readonly 'Error': false; + readonly 'escape': false; + readonly 'eval': false; + readonly 'EvalError': false; + readonly 'FinalizationRegistry': false; + readonly 'Float32Array': false; + readonly 'Float64Array': false; + readonly 'Function': false; + readonly 'globalThis': false; + readonly 'hasOwnProperty': false; + readonly 'Infinity': false; + readonly 'Int16Array': false; + readonly 'Int32Array': false; + readonly 'Int8Array': false; + readonly 'isFinite': false; + readonly 'isNaN': false; + readonly 'isPrototypeOf': false; + readonly 'JSON': false; + readonly 'Map': false; + readonly 'Math': false; + readonly 'NaN': false; + readonly 'Number': false; + readonly 'Object': false; + readonly 'parseFloat': false; + readonly 'parseInt': false; + readonly 'Promise': false; + readonly 'propertyIsEnumerable': false; + readonly 'Proxy': false; + readonly 'RangeError': false; + readonly 'ReferenceError': false; + readonly 'Reflect': false; + readonly 'RegExp': false; + readonly 'Set': false; + readonly 'SharedArrayBuffer': false; + readonly 'String': false; + readonly 'Symbol': false; + readonly 'SyntaxError': false; + readonly 'toLocaleString': false; + readonly 'toString': false; + readonly 'TypeError': false; + readonly 'Uint16Array': false; + readonly 'Uint32Array': false; + readonly 'Uint8Array': false; + readonly 'Uint8ClampedArray': false; + readonly 'undefined': false; + readonly 'unescape': false; + readonly 'URIError': false; + readonly 'valueOf': false; + readonly 'WeakMap': false; + readonly 'WeakRef': false; + readonly 'WeakSet': false; +} + +type GlobalsBrowser = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'addEventListener': false; + readonly 'alert': false; + readonly 'AnalyserNode': false; + readonly 'Animation': false; + readonly 'AnimationEffectReadOnly': false; + readonly 'AnimationEffectTiming': false; + readonly 'AnimationEffectTimingReadOnly': false; + readonly 'AnimationEvent': false; + readonly 'AnimationPlaybackEvent': false; + readonly 'AnimationTimeline': false; + readonly 'applicationCache': false; + readonly 'ApplicationCache': false; + readonly 'ApplicationCacheErrorEvent': false; + readonly 'atob': false; + readonly 'Attr': false; + readonly 'Audio': false; + readonly 'AudioBuffer': false; + readonly 'AudioBufferSourceNode': false; + readonly 'AudioContext': false; + readonly 'AudioDestinationNode': false; + readonly 'AudioListener': false; + readonly 'AudioNode': false; + readonly 'AudioParam': false; + readonly 'AudioProcessingEvent': false; + readonly 'AudioScheduledSourceNode': false; + readonly 'AudioWorkletGlobalScope': false; + readonly 'AudioWorkletNode': false; + readonly 'AudioWorkletProcessor': false; + readonly 'BarProp': false; + readonly 'BaseAudioContext': false; + readonly 'BatteryManager': false; + readonly 'BeforeUnloadEvent': false; + readonly 'BiquadFilterNode': false; + readonly 'Blob': false; + readonly 'BlobEvent': false; + readonly 'blur': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'BudgetService': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'CacheStorage': false; + readonly 'cancelAnimationFrame': false; + readonly 'cancelIdleCallback': false; + readonly 'CanvasCaptureMediaStreamTrack': false; + readonly 'CanvasGradient': false; + readonly 'CanvasPattern': false; + readonly 'CanvasRenderingContext2D': false; + readonly 'ChannelMergerNode': false; + readonly 'ChannelSplitterNode': false; + readonly 'CharacterData': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'clientInformation': false; + readonly 'ClipboardEvent': false; + readonly 'ClipboardItem': false; + readonly 'close': false; + readonly 'closed': false; + readonly 'CloseEvent': false; + readonly 'Comment': false; + readonly 'CompositionEvent': false; + readonly 'CompressionStream': false; + readonly 'confirm': false; + readonly 'console': false; + readonly 'ConstantSourceNode': false; + readonly 'ConvolverNode': false; + readonly 'CountQueuingStrategy': false; + readonly 'createImageBitmap': false; + readonly 'Credential': false; + readonly 'CredentialsContainer': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CSS': false; + readonly 'CSSConditionRule': false; + readonly 'CSSFontFaceRule': false; + readonly 'CSSGroupingRule': false; + readonly 'CSSImportRule': false; + readonly 'CSSKeyframeRule': false; + readonly 'CSSKeyframesRule': false; + readonly 'CSSMatrixComponent': false; + readonly 'CSSMediaRule': false; + readonly 'CSSNamespaceRule': false; + readonly 'CSSPageRule': false; + readonly 'CSSPerspective': false; + readonly 'CSSRotate': false; + readonly 'CSSRule': false; + readonly 'CSSRuleList': false; + readonly 'CSSScale': false; + readonly 'CSSSkew': false; + readonly 'CSSSkewX': false; + readonly 'CSSSkewY': false; + readonly 'CSSStyleDeclaration': false; + readonly 'CSSStyleRule': false; + readonly 'CSSStyleSheet': false; + readonly 'CSSSupportsRule': false; + readonly 'CSSTransformValue': false; + readonly 'CSSTranslate': false; + readonly 'CustomElementRegistry': false; + readonly 'customElements': false; + readonly 'CustomEvent': false; + readonly 'DataTransfer': false; + readonly 'DataTransferItem': false; + readonly 'DataTransferItemList': false; + readonly 'DecompressionStream': false; + readonly 'defaultstatus': false; + readonly 'defaultStatus': false; + readonly 'DelayNode': false; + readonly 'DeviceMotionEvent': false; + readonly 'DeviceOrientationEvent': false; + readonly 'devicePixelRatio': false; + readonly 'dispatchEvent': false; + readonly 'document': false; + readonly 'Document': false; + readonly 'DocumentFragment': false; + readonly 'DocumentType': false; + readonly 'DOMError': false; + readonly 'DOMException': false; + readonly 'DOMImplementation': false; + readonly 'DOMMatrix': false; + readonly 'DOMMatrixReadOnly': false; + readonly 'DOMParser': false; + readonly 'DOMPoint': false; + readonly 'DOMPointReadOnly': false; + readonly 'DOMQuad': false; + readonly 'DOMRect': false; + readonly 'DOMRectList': false; + readonly 'DOMRectReadOnly': false; + readonly 'DOMStringList': false; + readonly 'DOMStringMap': false; + readonly 'DOMTokenList': false; + readonly 'DragEvent': false; + readonly 'DynamicsCompressorNode': false; + readonly 'Element': false; + readonly 'ErrorEvent': false; + readonly 'event': false; + readonly 'Event': false; + readonly 'EventSource': false; + readonly 'EventTarget': false; + readonly 'external': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FileList': false; + readonly 'FileReader': false; + readonly 'find': false; + readonly 'focus': false; + readonly 'FocusEvent': false; + readonly 'FontFace': false; + readonly 'FontFaceSetLoadEvent': false; + readonly 'FormData': false; + readonly 'FormDataEvent': false; + readonly 'frameElement': false; + readonly 'frames': false; + readonly 'GainNode': false; + readonly 'Gamepad': false; + readonly 'GamepadButton': false; + readonly 'GamepadEvent': false; + readonly 'getComputedStyle': false; + readonly 'getSelection': false; + readonly 'HashChangeEvent': false; + readonly 'Headers': false; + readonly 'history': false; + readonly 'History': false; + readonly 'HTMLAllCollection': false; + readonly 'HTMLAnchorElement': false; + readonly 'HTMLAreaElement': false; + readonly 'HTMLAudioElement': false; + readonly 'HTMLBaseElement': false; + readonly 'HTMLBodyElement': false; + readonly 'HTMLBRElement': false; + readonly 'HTMLButtonElement': false; + readonly 'HTMLCanvasElement': false; + readonly 'HTMLCollection': false; + readonly 'HTMLContentElement': false; + readonly 'HTMLDataElement': false; + readonly 'HTMLDataListElement': false; + readonly 'HTMLDetailsElement': false; + readonly 'HTMLDialogElement': false; + readonly 'HTMLDirectoryElement': false; + readonly 'HTMLDivElement': false; + readonly 'HTMLDListElement': false; + readonly 'HTMLDocument': false; + readonly 'HTMLElement': false; + readonly 'HTMLEmbedElement': false; + readonly 'HTMLFieldSetElement': false; + readonly 'HTMLFontElement': false; + readonly 'HTMLFormControlsCollection': false; + readonly 'HTMLFormElement': false; + readonly 'HTMLFrameElement': false; + readonly 'HTMLFrameSetElement': false; + readonly 'HTMLHeadElement': false; + readonly 'HTMLHeadingElement': false; + readonly 'HTMLHRElement': false; + readonly 'HTMLHtmlElement': false; + readonly 'HTMLIFrameElement': false; + readonly 'HTMLImageElement': false; + readonly 'HTMLInputElement': false; + readonly 'HTMLLabelElement': false; + readonly 'HTMLLegendElement': false; + readonly 'HTMLLIElement': false; + readonly 'HTMLLinkElement': false; + readonly 'HTMLMapElement': false; + readonly 'HTMLMarqueeElement': false; + readonly 'HTMLMediaElement': false; + readonly 'HTMLMenuElement': false; + readonly 'HTMLMetaElement': false; + readonly 'HTMLMeterElement': false; + readonly 'HTMLModElement': false; + readonly 'HTMLObjectElement': false; + readonly 'HTMLOListElement': false; + readonly 'HTMLOptGroupElement': false; + readonly 'HTMLOptionElement': false; + readonly 'HTMLOptionsCollection': false; + readonly 'HTMLOutputElement': false; + readonly 'HTMLParagraphElement': false; + readonly 'HTMLParamElement': false; + readonly 'HTMLPictureElement': false; + readonly 'HTMLPreElement': false; + readonly 'HTMLProgressElement': false; + readonly 'HTMLQuoteElement': false; + readonly 'HTMLScriptElement': false; + readonly 'HTMLSelectElement': false; + readonly 'HTMLShadowElement': false; + readonly 'HTMLSlotElement': false; + readonly 'HTMLSourceElement': false; + readonly 'HTMLSpanElement': false; + readonly 'HTMLStyleElement': false; + readonly 'HTMLTableCaptionElement': false; + readonly 'HTMLTableCellElement': false; + readonly 'HTMLTableColElement': false; + readonly 'HTMLTableElement': false; + readonly 'HTMLTableRowElement': false; + readonly 'HTMLTableSectionElement': false; + readonly 'HTMLTemplateElement': false; + readonly 'HTMLTextAreaElement': false; + readonly 'HTMLTimeElement': false; + readonly 'HTMLTitleElement': false; + readonly 'HTMLTrackElement': false; + readonly 'HTMLUListElement': false; + readonly 'HTMLUnknownElement': false; + readonly 'HTMLVideoElement': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'IdleDeadline': false; + readonly 'IIRFilterNode': false; + readonly 'Image': false; + readonly 'ImageBitmap': false; + readonly 'ImageBitmapRenderingContext': false; + readonly 'ImageCapture': false; + readonly 'ImageData': false; + readonly 'indexedDB': false; + readonly 'innerHeight': false; + readonly 'innerWidth': false; + readonly 'InputEvent': false; + readonly 'IntersectionObserver': false; + readonly 'IntersectionObserverEntry': false; + readonly 'Intl': false; + readonly 'isSecureContext': false; + readonly 'KeyboardEvent': false; + readonly 'KeyframeEffect': false; + readonly 'KeyframeEffectReadOnly': false; + readonly 'length': false; + readonly 'localStorage': false; + readonly 'location': true; + readonly 'Location': false; + readonly 'locationbar': false; + readonly 'matchMedia': false; + readonly 'MediaDeviceInfo': false; + readonly 'MediaDevices': false; + readonly 'MediaElementAudioSourceNode': false; + readonly 'MediaEncryptedEvent': false; + readonly 'MediaError': false; + readonly 'MediaKeyMessageEvent': false; + readonly 'MediaKeySession': false; + readonly 'MediaKeyStatusMap': false; + readonly 'MediaKeySystemAccess': false; + readonly 'MediaList': false; + readonly 'MediaMetadata': false; + readonly 'MediaQueryList': false; + readonly 'MediaQueryListEvent': false; + readonly 'MediaRecorder': false; + readonly 'MediaSettingsRange': false; + readonly 'MediaSource': false; + readonly 'MediaStream': false; + readonly 'MediaStreamAudioDestinationNode': false; + readonly 'MediaStreamAudioSourceNode': false; + readonly 'MediaStreamConstraints': false; + readonly 'MediaStreamEvent': false; + readonly 'MediaStreamTrack': false; + readonly 'MediaStreamTrackEvent': false; + readonly 'menubar': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'MIDIAccess': false; + readonly 'MIDIConnectionEvent': false; + readonly 'MIDIInput': false; + readonly 'MIDIInputMap': false; + readonly 'MIDIMessageEvent': false; + readonly 'MIDIOutput': false; + readonly 'MIDIOutputMap': false; + readonly 'MIDIPort': false; + readonly 'MimeType': false; + readonly 'MimeTypeArray': false; + readonly 'MouseEvent': false; + readonly 'moveBy': false; + readonly 'moveTo': false; + readonly 'MutationEvent': false; + readonly 'MutationObserver': false; + readonly 'MutationRecord': false; + readonly 'name': false; + readonly 'NamedNodeMap': false; + readonly 'NavigationPreloadManager': false; + readonly 'navigator': false; + readonly 'Navigator': false; + readonly 'NavigatorUAData': false; + readonly 'NetworkInformation': false; + readonly 'Node': false; + readonly 'NodeFilter': false; + readonly 'NodeIterator': false; + readonly 'NodeList': false; + readonly 'Notification': false; + readonly 'OfflineAudioCompletionEvent': false; + readonly 'OfflineAudioContext': false; + readonly 'offscreenBuffering': false; + readonly 'OffscreenCanvas': true; + readonly 'OffscreenCanvasRenderingContext2D': false; + readonly 'onabort': true; + readonly 'onafterprint': true; + readonly 'onanimationend': true; + readonly 'onanimationiteration': true; + readonly 'onanimationstart': true; + readonly 'onappinstalled': true; + readonly 'onauxclick': true; + readonly 'onbeforeinstallprompt': true; + readonly 'onbeforeprint': true; + readonly 'onbeforeunload': true; + readonly 'onblur': true; + readonly 'oncancel': true; + readonly 'oncanplay': true; + readonly 'oncanplaythrough': true; + readonly 'onchange': true; + readonly 'onclick': true; + readonly 'onclose': true; + readonly 'oncontextmenu': true; + readonly 'oncuechange': true; + readonly 'ondblclick': true; + readonly 'ondevicemotion': true; + readonly 'ondeviceorientation': true; + readonly 'ondeviceorientationabsolute': true; + readonly 'ondrag': true; + readonly 'ondragend': true; + readonly 'ondragenter': true; + readonly 'ondragleave': true; + readonly 'ondragover': true; + readonly 'ondragstart': true; + readonly 'ondrop': true; + readonly 'ondurationchange': true; + readonly 'onemptied': true; + readonly 'onended': true; + readonly 'onerror': true; + readonly 'onfocus': true; + readonly 'ongotpointercapture': true; + readonly 'onhashchange': true; + readonly 'oninput': true; + readonly 'oninvalid': true; + readonly 'onkeydown': true; + readonly 'onkeypress': true; + readonly 'onkeyup': true; + readonly 'onlanguagechange': true; + readonly 'onload': true; + readonly 'onloadeddata': true; + readonly 'onloadedmetadata': true; + readonly 'onloadstart': true; + readonly 'onlostpointercapture': true; + readonly 'onmessage': true; + readonly 'onmessageerror': true; + readonly 'onmousedown': true; + readonly 'onmouseenter': true; + readonly 'onmouseleave': true; + readonly 'onmousemove': true; + readonly 'onmouseout': true; + readonly 'onmouseover': true; + readonly 'onmouseup': true; + readonly 'onmousewheel': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onpagehide': true; + readonly 'onpageshow': true; + readonly 'onpause': true; + readonly 'onplay': true; + readonly 'onplaying': true; + readonly 'onpointercancel': true; + readonly 'onpointerdown': true; + readonly 'onpointerenter': true; + readonly 'onpointerleave': true; + readonly 'onpointermove': true; + readonly 'onpointerout': true; + readonly 'onpointerover': true; + readonly 'onpointerup': true; + readonly 'onpopstate': true; + readonly 'onprogress': true; + readonly 'onratechange': true; + readonly 'onrejectionhandled': true; + readonly 'onreset': true; + readonly 'onresize': true; + readonly 'onscroll': true; + readonly 'onsearch': true; + readonly 'onseeked': true; + readonly 'onseeking': true; + readonly 'onselect': true; + readonly 'onstalled': true; + readonly 'onstorage': true; + readonly 'onsubmit': true; + readonly 'onsuspend': true; + readonly 'ontimeupdate': true; + readonly 'ontoggle': true; + readonly 'ontransitionend': true; + readonly 'onunhandledrejection': true; + readonly 'onunload': true; + readonly 'onvolumechange': true; + readonly 'onwaiting': true; + readonly 'onwheel': true; + readonly 'open': false; + readonly 'openDatabase': false; + readonly 'opener': false; + readonly 'Option': false; + readonly 'origin': false; + readonly 'OscillatorNode': false; + readonly 'outerHeight': false; + readonly 'outerWidth': false; + readonly 'OverconstrainedError': false; + readonly 'PageTransitionEvent': false; + readonly 'pageXOffset': false; + readonly 'pageYOffset': false; + readonly 'PannerNode': false; + readonly 'parent': false; + readonly 'Path2D': false; + readonly 'PaymentAddress': false; + readonly 'PaymentRequest': false; + readonly 'PaymentRequestUpdateEvent': false; + readonly 'PaymentResponse': false; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceLongTaskTiming': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceNavigationTiming': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformancePaintTiming': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'PeriodicWave': false; + readonly 'Permissions': false; + readonly 'PermissionStatus': false; + readonly 'personalbar': false; + readonly 'PhotoCapabilities': false; + readonly 'Plugin': false; + readonly 'PluginArray': false; + readonly 'PointerEvent': false; + readonly 'PopStateEvent': false; + readonly 'postMessage': false; + readonly 'Presentation': false; + readonly 'PresentationAvailability': false; + readonly 'PresentationConnection': false; + readonly 'PresentationConnectionAvailableEvent': false; + readonly 'PresentationConnectionCloseEvent': false; + readonly 'PresentationConnectionList': false; + readonly 'PresentationReceiver': false; + readonly 'PresentationRequest': false; + readonly 'print': false; + readonly 'ProcessingInstruction': false; + readonly 'ProgressEvent': false; + readonly 'PromiseRejectionEvent': false; + readonly 'prompt': false; + readonly 'PushManager': false; + readonly 'PushSubscription': false; + readonly 'PushSubscriptionOptions': false; + readonly 'queueMicrotask': false; + readonly 'RadioNodeList': false; + readonly 'Range': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'registerProcessor': false; + readonly 'RemotePlayback': false; + readonly 'removeEventListener': false; + readonly 'reportError': false; + readonly 'Request': false; + readonly 'requestAnimationFrame': false; + readonly 'requestIdleCallback': false; + readonly 'resizeBy': false; + readonly 'ResizeObserver': false; + readonly 'ResizeObserverEntry': false; + readonly 'resizeTo': false; + readonly 'Response': false; + readonly 'RTCCertificate': false; + readonly 'RTCDataChannel': false; + readonly 'RTCDataChannelEvent': false; + readonly 'RTCDtlsTransport': false; + readonly 'RTCIceCandidate': false; + readonly 'RTCIceGatherer': false; + readonly 'RTCIceTransport': false; + readonly 'RTCPeerConnection': false; + readonly 'RTCPeerConnectionIceEvent': false; + readonly 'RTCRtpContributingSource': false; + readonly 'RTCRtpReceiver': false; + readonly 'RTCRtpSender': false; + readonly 'RTCSctpTransport': false; + readonly 'RTCSessionDescription': false; + readonly 'RTCStatsReport': false; + readonly 'RTCTrackEvent': false; + readonly 'screen': false; + readonly 'Screen': false; + readonly 'screenLeft': false; + readonly 'ScreenOrientation': false; + readonly 'screenTop': false; + readonly 'screenX': false; + readonly 'screenY': false; + readonly 'ScriptProcessorNode': false; + readonly 'scroll': false; + readonly 'scrollbars': false; + readonly 'scrollBy': false; + readonly 'scrollTo': false; + readonly 'scrollX': false; + readonly 'scrollY': false; + readonly 'SecurityPolicyViolationEvent': false; + readonly 'Selection': false; + readonly 'self': false; + readonly 'ServiceWorker': false; + readonly 'ServiceWorkerContainer': false; + readonly 'ServiceWorkerRegistration': false; + readonly 'sessionStorage': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'ShadowRoot': false; + readonly 'SharedWorker': false; + readonly 'SourceBuffer': false; + readonly 'SourceBufferList': false; + readonly 'speechSynthesis': false; + readonly 'SpeechSynthesisEvent': false; + readonly 'SpeechSynthesisUtterance': false; + readonly 'StaticRange': false; + readonly 'status': false; + readonly 'statusbar': false; + readonly 'StereoPannerNode': false; + readonly 'stop': false; + readonly 'Storage': false; + readonly 'StorageEvent': false; + readonly 'StorageManager': false; + readonly 'structuredClone': false; + readonly 'styleMedia': false; + readonly 'StyleSheet': false; + readonly 'StyleSheetList': false; + readonly 'SubmitEvent': false; + readonly 'SubtleCrypto': false; + readonly 'SVGAElement': false; + readonly 'SVGAngle': false; + readonly 'SVGAnimatedAngle': false; + readonly 'SVGAnimatedBoolean': false; + readonly 'SVGAnimatedEnumeration': false; + readonly 'SVGAnimatedInteger': false; + readonly 'SVGAnimatedLength': false; + readonly 'SVGAnimatedLengthList': false; + readonly 'SVGAnimatedNumber': false; + readonly 'SVGAnimatedNumberList': false; + readonly 'SVGAnimatedPreserveAspectRatio': false; + readonly 'SVGAnimatedRect': false; + readonly 'SVGAnimatedString': false; + readonly 'SVGAnimatedTransformList': false; + readonly 'SVGAnimateElement': false; + readonly 'SVGAnimateMotionElement': false; + readonly 'SVGAnimateTransformElement': false; + readonly 'SVGAnimationElement': false; + readonly 'SVGCircleElement': false; + readonly 'SVGClipPathElement': false; + readonly 'SVGComponentTransferFunctionElement': false; + readonly 'SVGDefsElement': false; + readonly 'SVGDescElement': false; + readonly 'SVGDiscardElement': false; + readonly 'SVGElement': false; + readonly 'SVGEllipseElement': false; + readonly 'SVGFEBlendElement': false; + readonly 'SVGFEColorMatrixElement': false; + readonly 'SVGFEComponentTransferElement': false; + readonly 'SVGFECompositeElement': false; + readonly 'SVGFEConvolveMatrixElement': false; + readonly 'SVGFEDiffuseLightingElement': false; + readonly 'SVGFEDisplacementMapElement': false; + readonly 'SVGFEDistantLightElement': false; + readonly 'SVGFEDropShadowElement': false; + readonly 'SVGFEFloodElement': false; + readonly 'SVGFEFuncAElement': false; + readonly 'SVGFEFuncBElement': false; + readonly 'SVGFEFuncGElement': false; + readonly 'SVGFEFuncRElement': false; + readonly 'SVGFEGaussianBlurElement': false; + readonly 'SVGFEImageElement': false; + readonly 'SVGFEMergeElement': false; + readonly 'SVGFEMergeNodeElement': false; + readonly 'SVGFEMorphologyElement': false; + readonly 'SVGFEOffsetElement': false; + readonly 'SVGFEPointLightElement': false; + readonly 'SVGFESpecularLightingElement': false; + readonly 'SVGFESpotLightElement': false; + readonly 'SVGFETileElement': false; + readonly 'SVGFETurbulenceElement': false; + readonly 'SVGFilterElement': false; + readonly 'SVGForeignObjectElement': false; + readonly 'SVGGElement': false; + readonly 'SVGGeometryElement': false; + readonly 'SVGGradientElement': false; + readonly 'SVGGraphicsElement': false; + readonly 'SVGImageElement': false; + readonly 'SVGLength': false; + readonly 'SVGLengthList': false; + readonly 'SVGLinearGradientElement': false; + readonly 'SVGLineElement': false; + readonly 'SVGMarkerElement': false; + readonly 'SVGMaskElement': false; + readonly 'SVGMatrix': false; + readonly 'SVGMetadataElement': false; + readonly 'SVGMPathElement': false; + readonly 'SVGNumber': false; + readonly 'SVGNumberList': false; + readonly 'SVGPathElement': false; + readonly 'SVGPatternElement': false; + readonly 'SVGPoint': false; + readonly 'SVGPointList': false; + readonly 'SVGPolygonElement': false; + readonly 'SVGPolylineElement': false; + readonly 'SVGPreserveAspectRatio': false; + readonly 'SVGRadialGradientElement': false; + readonly 'SVGRect': false; + readonly 'SVGRectElement': false; + readonly 'SVGScriptElement': false; + readonly 'SVGSetElement': false; + readonly 'SVGStopElement': false; + readonly 'SVGStringList': false; + readonly 'SVGStyleElement': false; + readonly 'SVGSVGElement': false; + readonly 'SVGSwitchElement': false; + readonly 'SVGSymbolElement': false; + readonly 'SVGTextContentElement': false; + readonly 'SVGTextElement': false; + readonly 'SVGTextPathElement': false; + readonly 'SVGTextPositioningElement': false; + readonly 'SVGTitleElement': false; + readonly 'SVGTransform': false; + readonly 'SVGTransformList': false; + readonly 'SVGTSpanElement': false; + readonly 'SVGUnitTypes': false; + readonly 'SVGUseElement': false; + readonly 'SVGViewElement': false; + readonly 'TaskAttributionTiming': false; + readonly 'Text': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TextEvent': false; + readonly 'TextMetrics': false; + readonly 'TextTrack': false; + readonly 'TextTrackCue': false; + readonly 'TextTrackCueList': false; + readonly 'TextTrackList': false; + readonly 'TimeRanges': false; + readonly 'ToggleEvent': false; + readonly 'toolbar': false; + readonly 'top': false; + readonly 'Touch': false; + readonly 'TouchEvent': false; + readonly 'TouchList': false; + readonly 'TrackEvent': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'TransitionEvent': false; + readonly 'TreeWalker': false; + readonly 'UIEvent': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'ValidityState': false; + readonly 'visualViewport': false; + readonly 'VisualViewport': false; + readonly 'VTTCue': false; + readonly 'WaveShaperNode': false; + readonly 'WebAssembly': false; + readonly 'WebGL2RenderingContext': false; + readonly 'WebGLActiveInfo': false; + readonly 'WebGLBuffer': false; + readonly 'WebGLContextEvent': false; + readonly 'WebGLFramebuffer': false; + readonly 'WebGLProgram': false; + readonly 'WebGLQuery': false; + readonly 'WebGLRenderbuffer': false; + readonly 'WebGLRenderingContext': false; + readonly 'WebGLSampler': false; + readonly 'WebGLShader': false; + readonly 'WebGLShaderPrecisionFormat': false; + readonly 'WebGLSync': false; + readonly 'WebGLTexture': false; + readonly 'WebGLTransformFeedback': false; + readonly 'WebGLUniformLocation': false; + readonly 'WebGLVertexArrayObject': false; + readonly 'WebSocket': false; + readonly 'WheelEvent': false; + readonly 'window': false; + readonly 'Window': false; + readonly 'Worker': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLDocument': false; + readonly 'XMLHttpRequest': false; + readonly 'XMLHttpRequestEventTarget': false; + readonly 'XMLHttpRequestUpload': false; + readonly 'XMLSerializer': false; + readonly 'XPathEvaluator': false; + readonly 'XPathExpression': false; + readonly 'XPathResult': false; + readonly 'XRAnchor': false; + readonly 'XRBoundedReferenceSpace': false; + readonly 'XRCPUDepthInformation': false; + readonly 'XRDepthInformation': false; + readonly 'XRFrame': false; + readonly 'XRInputSource': false; + readonly 'XRInputSourceArray': false; + readonly 'XRInputSourceEvent': false; + readonly 'XRInputSourcesChangeEvent': false; + readonly 'XRPose': false; + readonly 'XRReferenceSpace': false; + readonly 'XRReferenceSpaceEvent': false; + readonly 'XRRenderState': false; + readonly 'XRRigidTransform': false; + readonly 'XRSession': false; + readonly 'XRSessionEvent': false; + readonly 'XRSpace': false; + readonly 'XRSystem': false; + readonly 'XRView': false; + readonly 'XRViewerPose': false; + readonly 'XRViewport': false; + readonly 'XRWebGLBinding': false; + readonly 'XRWebGLDepthInformation': false; + readonly 'XRWebGLLayer': false; + readonly 'XSLTProcessor': false; +} + +type GlobalsWorker = { + readonly 'addEventListener': false; + readonly 'applicationCache': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'close': true; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'ErrorEvent': false; + readonly 'Event': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FileReaderSync': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'ImageData': false; + readonly 'importScripts': true; + readonly 'indexedDB': false; + readonly 'location': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'name': false; + readonly 'navigator': false; + readonly 'Notification': false; + readonly 'onclose': true; + readonly 'onconnect': true; + readonly 'onerror': true; + readonly 'onlanguagechange': true; + readonly 'onmessage': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onrejectionhandled': true; + readonly 'onunhandledrejection': true; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'postMessage': true; + readonly 'Promise': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'removeEventListener': false; + readonly 'reportError': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'self': true; + readonly 'ServiceWorkerRegistration': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WebSocket': false; + readonly 'Worker': false; + readonly 'WorkerGlobalScope': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLHttpRequest': false; +} + +type GlobalsNode = { + readonly '__dirname': false; + readonly '__filename': false; + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'Buffer': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearImmediate': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'exports': true; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'global': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'module': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'process': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'require': false; + readonly 'Response': false; + readonly 'setImmediate': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsNodeBuiltin = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'Buffer': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearImmediate': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'global': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'process': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'setImmediate': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsCommonjs = { + readonly 'exports': true; + readonly 'global': false; + readonly 'module': false; + readonly 'require': false; +} + +type GlobalsAmd = { + readonly 'define': false; + readonly 'require': false; +} + +type GlobalsMocha = { + readonly 'after': false; + readonly 'afterEach': false; + readonly 'before': false; + readonly 'beforeEach': false; + readonly 'context': false; + readonly 'describe': false; + readonly 'it': false; + readonly 'mocha': false; + readonly 'run': false; + readonly 'setup': false; + readonly 'specify': false; + readonly 'suite': false; + readonly 'suiteSetup': false; + readonly 'suiteTeardown': false; + readonly 'teardown': false; + readonly 'test': false; + readonly 'xcontext': false; + readonly 'xdescribe': false; + readonly 'xit': false; + readonly 'xspecify': false; +} + +type GlobalsJasmine = { + readonly 'afterAll': false; + readonly 'afterEach': false; + readonly 'beforeAll': false; + readonly 'beforeEach': false; + readonly 'describe': false; + readonly 'expect': false; + readonly 'expectAsync': false; + readonly 'fail': false; + readonly 'fdescribe': false; + readonly 'fit': false; + readonly 'it': false; + readonly 'jasmine': false; + readonly 'pending': false; + readonly 'runs': false; + readonly 'spyOn': false; + readonly 'spyOnAllFunctions': false; + readonly 'spyOnProperty': false; + readonly 'waits': false; + readonly 'waitsFor': false; + readonly 'xdescribe': false; + readonly 'xit': false; +} + +type GlobalsJest = { + readonly 'afterAll': false; + readonly 'afterEach': false; + readonly 'beforeAll': false; + readonly 'beforeEach': false; + readonly 'describe': false; + readonly 'expect': false; + readonly 'fdescribe': false; + readonly 'fit': false; + readonly 'it': false; + readonly 'jest': false; + readonly 'pit': false; + readonly 'require': false; + readonly 'test': false; + readonly 'xdescribe': false; + readonly 'xit': false; + readonly 'xtest': false; +} + +type GlobalsQunit = { + readonly 'asyncTest': false; + readonly 'deepEqual': false; + readonly 'equal': false; + readonly 'expect': false; + readonly 'module': false; + readonly 'notDeepEqual': false; + readonly 'notEqual': false; + readonly 'notOk': false; + readonly 'notPropEqual': false; + readonly 'notStrictEqual': false; + readonly 'ok': false; + readonly 'propEqual': false; + readonly 'QUnit': false; + readonly 'raises': false; + readonly 'start': false; + readonly 'stop': false; + readonly 'strictEqual': false; + readonly 'test': false; + readonly 'throws': false; +} + +type GlobalsPhantomjs = { + readonly 'console': true; + readonly 'exports': true; + readonly 'phantom': true; + readonly 'require': true; + readonly 'WebPage': true; +} + +type GlobalsCouch = { + readonly 'emit': false; + readonly 'exports': false; + readonly 'getRow': false; + readonly 'log': false; + readonly 'module': false; + readonly 'provides': false; + readonly 'require': false; + readonly 'respond': false; + readonly 'send': false; + readonly 'start': false; + readonly 'sum': false; +} + +type GlobalsRhino = { + readonly 'defineClass': false; + readonly 'deserialize': false; + readonly 'gc': false; + readonly 'help': false; + readonly 'importClass': false; + readonly 'importPackage': false; + readonly 'java': false; + readonly 'load': false; + readonly 'loadClass': false; + readonly 'Packages': false; + readonly 'print': false; + readonly 'quit': false; + readonly 'readFile': false; + readonly 'readUrl': false; + readonly 'runCommand': false; + readonly 'seal': false; + readonly 'serialize': false; + readonly 'spawn': false; + readonly 'sync': false; + readonly 'toint32': false; + readonly 'version': false; +} + +type GlobalsNashorn = { + readonly '__DIR__': false; + readonly '__FILE__': false; + readonly '__LINE__': false; + readonly 'com': false; + readonly 'edu': false; + readonly 'exit': false; + readonly 'java': false; + readonly 'Java': false; + readonly 'javafx': false; + readonly 'JavaImporter': false; + readonly 'javax': false; + readonly 'JSAdapter': false; + readonly 'load': false; + readonly 'loadWithNewGlobal': false; + readonly 'org': false; + readonly 'Packages': false; + readonly 'print': false; + readonly 'quit': false; +} + +type GlobalsWsh = { + readonly 'ActiveXObject': false; + readonly 'CollectGarbage': false; + readonly 'Debug': false; + readonly 'Enumerator': false; + readonly 'GetObject': false; + readonly 'RuntimeObject': false; + readonly 'ScriptEngine': false; + readonly 'ScriptEngineBuildVersion': false; + readonly 'ScriptEngineMajorVersion': false; + readonly 'ScriptEngineMinorVersion': false; + readonly 'VBArray': false; + readonly 'WScript': false; + readonly 'WSH': false; +} + +type GlobalsJquery = { + readonly '$': false; + readonly 'jQuery': false; +} + +type GlobalsYui = { + readonly 'YAHOO': false; + readonly 'YAHOO_config': false; + readonly 'YUI': false; + readonly 'YUI_config': false; +} + +type GlobalsShelljs = { + readonly 'cat': false; + readonly 'cd': false; + readonly 'chmod': false; + readonly 'config': false; + readonly 'cp': false; + readonly 'dirs': false; + readonly 'echo': false; + readonly 'env': false; + readonly 'error': false; + readonly 'exec': false; + readonly 'exit': false; + readonly 'find': false; + readonly 'grep': false; + readonly 'ln': false; + readonly 'ls': false; + readonly 'mkdir': false; + readonly 'mv': false; + readonly 'popd': false; + readonly 'pushd': false; + readonly 'pwd': false; + readonly 'rm': false; + readonly 'sed': false; + readonly 'set': false; + readonly 'target': false; + readonly 'tempdir': false; + readonly 'test': false; + readonly 'touch': false; + readonly 'which': false; +} + +type GlobalsPrototypejs = { + readonly '$': false; + readonly '$$': false; + readonly '$A': false; + readonly '$break': false; + readonly '$continue': false; + readonly '$F': false; + readonly '$H': false; + readonly '$R': false; + readonly '$w': false; + readonly 'Abstract': false; + readonly 'Ajax': false; + readonly 'Autocompleter': false; + readonly 'Builder': false; + readonly 'Class': false; + readonly 'Control': false; + readonly 'Draggable': false; + readonly 'Draggables': false; + readonly 'Droppables': false; + readonly 'Effect': false; + readonly 'Element': false; + readonly 'Enumerable': false; + readonly 'Event': false; + readonly 'Field': false; + readonly 'Form': false; + readonly 'Hash': false; + readonly 'Insertion': false; + readonly 'ObjectRange': false; + readonly 'PeriodicalExecuter': false; + readonly 'Position': false; + readonly 'Prototype': false; + readonly 'Scriptaculous': false; + readonly 'Selector': false; + readonly 'Sortable': false; + readonly 'SortableObserver': false; + readonly 'Sound': false; + readonly 'Template': false; + readonly 'Toggle': false; + readonly 'Try': false; +} + +type GlobalsMeteor = { + readonly '$': false; + readonly 'Accounts': false; + readonly 'AccountsClient': false; + readonly 'AccountsCommon': false; + readonly 'AccountsServer': false; + readonly 'App': false; + readonly 'Assets': false; + readonly 'Blaze': false; + readonly 'check': false; + readonly 'Cordova': false; + readonly 'DDP': false; + readonly 'DDPRateLimiter': false; + readonly 'DDPServer': false; + readonly 'Deps': false; + readonly 'EJSON': false; + readonly 'Email': false; + readonly 'HTTP': false; + readonly 'Log': false; + readonly 'Match': false; + readonly 'Meteor': false; + readonly 'Mongo': false; + readonly 'MongoInternals': false; + readonly 'Npm': false; + readonly 'Package': false; + readonly 'Plugin': false; + readonly 'process': false; + readonly 'Random': false; + readonly 'ReactiveDict': false; + readonly 'ReactiveVar': false; + readonly 'Router': false; + readonly 'ServiceConfiguration': false; + readonly 'Session': false; + readonly 'share': false; + readonly 'Spacebars': false; + readonly 'Template': false; + readonly 'Tinytest': false; + readonly 'Tracker': false; + readonly 'UI': false; + readonly 'Utils': false; + readonly 'WebApp': false; + readonly 'WebAppInternals': false; +} + +type GlobalsMongo = { + readonly '_isWindows': false; + readonly '_rand': false; + readonly 'BulkWriteResult': false; + readonly 'cat': false; + readonly 'cd': false; + readonly 'connect': false; + readonly 'db': false; + readonly 'getHostName': false; + readonly 'getMemInfo': false; + readonly 'hostname': false; + readonly 'ISODate': false; + readonly 'listFiles': false; + readonly 'load': false; + readonly 'ls': false; + readonly 'md5sumFile': false; + readonly 'mkdir': false; + readonly 'Mongo': false; + readonly 'NumberInt': false; + readonly 'NumberLong': false; + readonly 'ObjectId': false; + readonly 'PlanCache': false; + readonly 'print': false; + readonly 'printjson': false; + readonly 'pwd': false; + readonly 'quit': false; + readonly 'removeFile': false; + readonly 'rs': false; + readonly 'sh': false; + readonly 'UUID': false; + readonly 'version': false; + readonly 'WriteResult': false; +} + +type GlobalsApplescript = { + readonly '$': false; + readonly 'Application': false; + readonly 'Automation': false; + readonly 'console': false; + readonly 'delay': false; + readonly 'Library': false; + readonly 'ObjC': false; + readonly 'ObjectSpecifier': false; + readonly 'Path': false; + readonly 'Progress': false; + readonly 'Ref': false; +} + +type GlobalsServiceworker = { + readonly 'addEventListener': false; + readonly 'applicationCache': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'Cache': false; + readonly 'caches': false; + readonly 'CacheStorage': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'Client': false; + readonly 'clients': false; + readonly 'Clients': false; + readonly 'close': true; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'ErrorEvent': false; + readonly 'Event': false; + readonly 'ExtendableEvent': false; + readonly 'ExtendableMessageEvent': false; + readonly 'fetch': false; + readonly 'FetchEvent': false; + readonly 'File': false; + readonly 'FileReaderSync': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'IDBCursor': false; + readonly 'IDBCursorWithValue': false; + readonly 'IDBDatabase': false; + readonly 'IDBFactory': false; + readonly 'IDBIndex': false; + readonly 'IDBKeyRange': false; + readonly 'IDBObjectStore': false; + readonly 'IDBOpenDBRequest': false; + readonly 'IDBRequest': false; + readonly 'IDBTransaction': false; + readonly 'IDBVersionChangeEvent': false; + readonly 'ImageData': false; + readonly 'importScripts': false; + readonly 'indexedDB': false; + readonly 'location': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'name': false; + readonly 'navigator': false; + readonly 'Notification': false; + readonly 'onclose': true; + readonly 'onconnect': true; + readonly 'onerror': true; + readonly 'onfetch': true; + readonly 'oninstall': true; + readonly 'onlanguagechange': true; + readonly 'onmessage': true; + readonly 'onmessageerror': true; + readonly 'onnotificationclick': true; + readonly 'onnotificationclose': true; + readonly 'onoffline': true; + readonly 'ononline': true; + readonly 'onpush': true; + readonly 'onpushsubscriptionchange': true; + readonly 'onrejectionhandled': true; + readonly 'onsync': true; + readonly 'onunhandledrejection': true; + readonly 'performance': false; + readonly 'Performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceNavigation': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'PerformanceTiming': false; + readonly 'postMessage': true; + readonly 'Promise': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'registration': false; + readonly 'removeEventListener': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'self': false; + readonly 'ServiceWorker': false; + readonly 'ServiceWorkerContainer': false; + readonly 'ServiceWorkerGlobalScope': false; + readonly 'ServiceWorkerMessageEvent': false; + readonly 'ServiceWorkerRegistration': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'skipWaiting': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WebSocket': false; + readonly 'WindowClient': false; + readonly 'Worker': false; + readonly 'WorkerGlobalScope': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; + readonly 'XMLHttpRequest': false; +} + +type GlobalsAtomtest = { + readonly 'advanceClock': false; + readonly 'atom': false; + readonly 'fakeClearInterval': false; + readonly 'fakeClearTimeout': false; + readonly 'fakeSetInterval': false; + readonly 'fakeSetTimeout': false; + readonly 'resetTimeouts': false; + readonly 'waitsForPromise': false; +} + +type GlobalsEmbertest = { + readonly 'andThen': false; + readonly 'click': false; + readonly 'currentPath': false; + readonly 'currentRouteName': false; + readonly 'currentURL': false; + readonly 'fillIn': false; + readonly 'find': false; + readonly 'findAll': false; + readonly 'findWithAssert': false; + readonly 'keyEvent': false; + readonly 'pauseTest': false; + readonly 'resumeTest': false; + readonly 'triggerEvent': false; + readonly 'visit': false; + readonly 'wait': false; +} + +type GlobalsProtractor = { + readonly '$': false; + readonly '$$': false; + readonly 'browser': false; + readonly 'by': false; + readonly 'By': false; + readonly 'DartObject': false; + readonly 'element': false; + readonly 'protractor': false; +} + +type GlobalsSharednodebrowser = { + readonly 'AbortController': false; + readonly 'AbortSignal': false; + readonly 'atob': false; + readonly 'Blob': false; + readonly 'BroadcastChannel': false; + readonly 'btoa': false; + readonly 'ByteLengthQueuingStrategy': false; + readonly 'clearInterval': false; + readonly 'clearTimeout': false; + readonly 'CompressionStream': false; + readonly 'console': false; + readonly 'CountQueuingStrategy': false; + readonly 'crypto': false; + readonly 'Crypto': false; + readonly 'CryptoKey': false; + readonly 'CustomEvent': false; + readonly 'DecompressionStream': false; + readonly 'DOMException': false; + readonly 'Event': false; + readonly 'EventTarget': false; + readonly 'fetch': false; + readonly 'File': false; + readonly 'FormData': false; + readonly 'Headers': false; + readonly 'Intl': false; + readonly 'MessageChannel': false; + readonly 'MessageEvent': false; + readonly 'MessagePort': false; + readonly 'performance': false; + readonly 'PerformanceEntry': false; + readonly 'PerformanceMark': false; + readonly 'PerformanceMeasure': false; + readonly 'PerformanceObserver': false; + readonly 'PerformanceObserverEntryList': false; + readonly 'PerformanceResourceTiming': false; + readonly 'queueMicrotask': false; + readonly 'ReadableByteStreamController': false; + readonly 'ReadableStream': false; + readonly 'ReadableStreamBYOBReader': false; + readonly 'ReadableStreamBYOBRequest': false; + readonly 'ReadableStreamDefaultController': false; + readonly 'ReadableStreamDefaultReader': false; + readonly 'Request': false; + readonly 'Response': false; + readonly 'setInterval': false; + readonly 'setTimeout': false; + readonly 'structuredClone': false; + readonly 'SubtleCrypto': false; + readonly 'TextDecoder': false; + readonly 'TextDecoderStream': false; + readonly 'TextEncoder': false; + readonly 'TextEncoderStream': false; + readonly 'TransformStream': false; + readonly 'TransformStreamDefaultController': false; + readonly 'URL': false; + readonly 'URLSearchParams': false; + readonly 'WebAssembly': false; + readonly 'WritableStream': false; + readonly 'WritableStreamDefaultController': false; + readonly 'WritableStreamDefaultWriter': false; +} + +type GlobalsWebextensions = { + readonly 'browser': false; + readonly 'chrome': false; + readonly 'opr': false; +} + +type GlobalsGreasemonkey = { + readonly 'cloneInto': false; + readonly 'createObjectIn': false; + readonly 'exportFunction': false; + readonly 'GM': false; + readonly 'GM_addElement': false; + readonly 'GM_addStyle': false; + readonly 'GM_addValueChangeListener': false; + readonly 'GM_deleteValue': false; + readonly 'GM_download': false; + readonly 'GM_getResourceText': false; + readonly 'GM_getResourceURL': false; + readonly 'GM_getTab': false; + readonly 'GM_getTabs': false; + readonly 'GM_getValue': false; + readonly 'GM_info': false; + readonly 'GM_listValues': false; + readonly 'GM_log': false; + readonly 'GM_notification': false; + readonly 'GM_openInTab': false; + readonly 'GM_registerMenuCommand': false; + readonly 'GM_removeValueChangeListener': false; + readonly 'GM_saveTab': false; + readonly 'GM_setClipboard': false; + readonly 'GM_setValue': false; + readonly 'GM_unregisterMenuCommand': false; + readonly 'GM_xmlhttpRequest': false; + readonly 'unsafeWindow': false; +} + +type GlobalsDevtools = { + readonly '$': false; + readonly '$_': false; + readonly '$$': false; + readonly '$0': false; + readonly '$1': false; + readonly '$2': false; + readonly '$3': false; + readonly '$4': false; + readonly '$x': false; + readonly 'chrome': false; + readonly 'clear': false; + readonly 'copy': false; + readonly 'debug': false; + readonly 'dir': false; + readonly 'dirxml': false; + readonly 'getEventListeners': false; + readonly 'inspect': false; + readonly 'keys': false; + readonly 'monitor': false; + readonly 'monitorEvents': false; + readonly 'profile': false; + readonly 'profileEnd': false; + readonly 'queryObjects': false; + readonly 'table': false; + readonly 'undebug': false; + readonly 'unmonitor': false; + readonly 'unmonitorEvents': false; + readonly 'values': false; +} + +type Globals = { + readonly 'builtin': GlobalsBuiltin; + readonly 'es5': GlobalsEs5; + readonly 'es2015': GlobalsEs2015; + readonly 'es2017': GlobalsEs2017; + readonly 'es2020': GlobalsEs2020; + readonly 'es2021': GlobalsEs2021; + readonly 'browser': GlobalsBrowser; + readonly 'worker': GlobalsWorker; + readonly 'node': GlobalsNode; + readonly 'nodeBuiltin': GlobalsNodeBuiltin; + readonly 'commonjs': GlobalsCommonjs; + readonly 'amd': GlobalsAmd; + readonly 'mocha': GlobalsMocha; + readonly 'jasmine': GlobalsJasmine; + readonly 'jest': GlobalsJest; + readonly 'qunit': GlobalsQunit; + readonly 'phantomjs': GlobalsPhantomjs; + readonly 'couch': GlobalsCouch; + readonly 'rhino': GlobalsRhino; + readonly 'nashorn': GlobalsNashorn; + readonly 'wsh': GlobalsWsh; + readonly 'jquery': GlobalsJquery; + readonly 'yui': GlobalsYui; + readonly 'shelljs': GlobalsShelljs; + readonly 'prototypejs': GlobalsPrototypejs; + readonly 'meteor': GlobalsMeteor; + readonly 'mongo': GlobalsMongo; + readonly 'applescript': GlobalsApplescript; + readonly 'serviceworker': GlobalsServiceworker; + readonly 'atomtest': GlobalsAtomtest; + readonly 'embertest': GlobalsEmbertest; + readonly 'protractor': GlobalsProtractor; + readonly 'shared-node-browser': GlobalsSharednodebrowser; + readonly 'webextensions': GlobalsWebextensions; + readonly 'greasemonkey': GlobalsGreasemonkey; + readonly 'devtools': GlobalsDevtools; +} + +declare const globals: Globals; + +export = globals; diff --git a/node_modules/globals/index.js b/node_modules/globals/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a951582e4176e860fdc0c9931723199310ad3d5b --- /dev/null +++ b/node_modules/globals/index.js @@ -0,0 +1,2 @@ +'use strict'; +module.exports = require('./globals.json'); diff --git a/node_modules/globals/license b/node_modules/globals/license new file mode 100644 index 0000000000000000000000000000000000000000..fa7ceba3eb4a9657a9db7f3ffca4e4e97a9019de --- /dev/null +++ b/node_modules/globals/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/globals/package.json b/node_modules/globals/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fca10a52d13024e5551d9b7a3e19966f9a5c6862 --- /dev/null +++ b/node_modules/globals/package.json @@ -0,0 +1,58 @@ +{ + "name": "globals", + "version": "14.0.0", + "description": "Global identifiers from different JavaScript environments", + "license": "MIT", + "repository": "sindresorhus/globals", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "sideEffects": false, + "engines": { + "node": ">=18" + }, + "scripts": { + "test": "xo && ava && tsd", + "prepare": "npm run --silent update-types", + "update-builtin-globals": "node scripts/get-builtin-globals.mjs", + "update-types": "node scripts/generate-types.mjs > index.d.ts" + }, + "files": [ + "index.js", + "index.d.ts", + "globals.json" + ], + "keywords": [ + "globals", + "global", + "identifiers", + "variables", + "vars", + "jshint", + "eslint", + "environments" + ], + "devDependencies": { + "ava": "^2.4.0", + "cheerio": "^1.0.0-rc.12", + "tsd": "^0.30.4", + "type-fest": "^4.10.2", + "xo": "^0.36.1" + }, + "xo": { + "ignores": [ + "get-browser-globals.js" + ], + "rules": { + "node/no-unsupported-features/es-syntax": "off" + } + }, + "tsd": { + "compilerOptions": { + "resolveJsonModule": true + } + } +} diff --git a/node_modules/globals/readme.md b/node_modules/globals/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..29442a85510b95f3134f5e5d62d6db4f7c86fe10 --- /dev/null +++ b/node_modules/globals/readme.md @@ -0,0 +1,44 @@ +# globals + +> Global identifiers from different JavaScript environments + +It's just a [JSON file](globals.json), so use it in any environment. + +This package is used by ESLint. + +**This package [no longer accepts](https://github.com/sindresorhus/globals/issues/82) new environments. If you need it for ESLint, just [create a plugin](http://eslint.org/docs/developer-guide/working-with-plugins#environments-in-plugins).** + +## Install + +```sh +npm install globals +``` + +## Usage + +```js +const globals = require('globals'); + +console.log(globals.browser); +/* +{ + addEventListener: false, + applicationCache: false, + ArrayBuffer: false, + atob: false, + … +} +*/ +``` + +Each global is given a value of `true` or `false`. A value of `true` indicates that the variable may be overwritten. A value of `false` indicates that the variable should be considered read-only. This information is used by static analysis tools to flag incorrect behavior. We assume all variables should be `false` unless we hear otherwise. + +For Node.js this package provides two sets of globals: + +- `globals.nodeBuiltin`: Globals available to all code running in Node.js. + These will usually be available as properties on the `global` object and include `process`, `Buffer`, but not CommonJS arguments like `require`. + See: https://nodejs.org/api/globals.html +- `globals.node`: A combination of the globals from `nodeBuiltin` plus all CommonJS arguments ("CommonJS module scope"). + See: https://nodejs.org/api/modules.html#modules_the_module_scope + +When analyzing code that is known to run outside of a CommonJS wrapper, for example, JavaScript modules, `nodeBuiltin` can find accidental CommonJS references. diff --git a/node_modules/gopd/.eslintrc b/node_modules/gopd/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..e2550c0fb7e8a8b16191ac89b2aaab429948720d --- /dev/null +++ b/node_modules/gopd/.eslintrc @@ -0,0 +1,16 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "func-style": [2, "declaration"], + "id-length": 0, + "multiline-comment-style": 0, + "new-cap": [2, { + "capIsNewExceptions": [ + "GetIntrinsic", + ], + }], + }, +} diff --git a/node_modules/gopd/.github/FUNDING.yml b/node_modules/gopd/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..94a44a8e83ff69f9167af25ae71c238d0f07250e --- /dev/null +++ b/node_modules/gopd/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/gopd +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/gopd/CHANGELOG.md b/node_modules/gopd/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..87f5727fb65c35e7a75fe15464473ffc0455739b --- /dev/null +++ b/node_modules/gopd/CHANGELOG.md @@ -0,0 +1,45 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.2.0](https://github.com/ljharb/gopd/compare/v1.1.0...v1.2.0) - 2024-12-03 + +### Commits + +- [New] add `gOPD` entry point; remove `get-intrinsic` [`5b61232`](https://github.com/ljharb/gopd/commit/5b61232dedea4591a314bcf16101b1961cee024e) + +## [v1.1.0](https://github.com/ljharb/gopd/compare/v1.0.1...v1.1.0) - 2024-11-29 + +### Commits + +- [New] add types [`f585e39`](https://github.com/ljharb/gopd/commit/f585e397886d270e4ba84e53d226e4f9ca2eb0e6) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `tape` [`0b8e4fd`](https://github.com/ljharb/gopd/commit/0b8e4fded64397a7726a9daa144a6cc9a5e2edfa) +- [Dev Deps] update `aud`, `npmignore`, `tape` [`48378b2`](https://github.com/ljharb/gopd/commit/48378b2443f09a4f7efbd0fb6c3ee845a6cabcf3) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`78099ee`](https://github.com/ljharb/gopd/commit/78099eeed41bfdc134c912280483689cc8861c31) +- [Tests] replace `aud` with `npm audit` [`4e0d0ac`](https://github.com/ljharb/gopd/commit/4e0d0ac47619d24a75318a8e1f543ee04b2a2632) +- [meta] add missing `engines.node` [`1443316`](https://github.com/ljharb/gopd/commit/14433165d07835c680155b3dfd62d9217d735eca) +- [Deps] update `get-intrinsic` [`eee5f51`](https://github.com/ljharb/gopd/commit/eee5f51769f3dbaf578b70e2a3199116b01aa670) +- [Deps] update `get-intrinsic` [`550c378`](https://github.com/ljharb/gopd/commit/550c3780e3a9c77b62565712a001b4ed64ea61f5) +- [Dev Deps] add missing peer dep [`8c2ecf8`](https://github.com/ljharb/gopd/commit/8c2ecf848122e4e30abfc5b5086fb48b390dce75) + +## [v1.0.1](https://github.com/ljharb/gopd/compare/v1.0.0...v1.0.1) - 2022-11-01 + +### Commits + +- [Fix] actually export gOPD instead of dP [`4b624bf`](https://github.com/ljharb/gopd/commit/4b624bfbeff788c5e3ff16d9443a83627847234f) + +## v1.0.0 - 2022-11-01 + +### Commits + +- Initial implementation, tests, readme [`0911e01`](https://github.com/ljharb/gopd/commit/0911e012cd642092bd88b732c161c58bf4f20bea) +- Initial commit [`b84e33f`](https://github.com/ljharb/gopd/commit/b84e33f5808a805ac57ff88d4247ad935569acbe) +- [actions] add reusable workflows [`12ae28a`](https://github.com/ljharb/gopd/commit/12ae28ae5f50f86e750215b6e2188901646d0119) +- npm init [`280118b`](https://github.com/ljharb/gopd/commit/280118badb45c80b4483836b5cb5315bddf6e582) +- [meta] add `auto-changelog` [`bb78de5`](https://github.com/ljharb/gopd/commit/bb78de5639a180747fb290c28912beaaf1615709) +- [meta] create FUNDING.yml; add `funding` in package.json [`11c22e6`](https://github.com/ljharb/gopd/commit/11c22e6355bb01f24e7fac4c9bb3055eb5b25002) +- [meta] use `npmignore` to autogenerate an npmignore file [`4f4537a`](https://github.com/ljharb/gopd/commit/4f4537a843b39f698c52f072845092e6fca345bb) +- Only apps should have lockfiles [`c567022`](https://github.com/ljharb/gopd/commit/c567022a18573aa7951cf5399445d9840e23e98b) diff --git a/node_modules/gopd/LICENSE b/node_modules/gopd/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..6abfe1434ebd5c15c245b9f0a7c25e36b581df19 --- /dev/null +++ b/node_modules/gopd/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/gopd/README.md b/node_modules/gopd/README.md new file mode 100644 index 0000000000000000000000000000000000000000..784e56a09695adb47410cb6cf08e96334a9f9c1f --- /dev/null +++ b/node_modules/gopd/README.md @@ -0,0 +1,40 @@ +# gopd [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation. + +## Usage + +```javascript +var gOPD = require('gopd'); +var assert = require('assert'); + +if (gOPD) { + assert.equal(typeof gOPD, 'function', 'descriptors supported'); + // use gOPD like Object.getOwnPropertyDescriptor here +} else { + assert.ok(!gOPD, 'descriptors not supported'); +} +``` + +[package-url]: https://npmjs.org/package/gopd +[npm-version-svg]: https://versionbadg.es/ljharb/gopd.svg +[deps-svg]: https://david-dm.org/ljharb/gopd.svg +[deps-url]: https://david-dm.org/ljharb/gopd +[dev-deps-svg]: https://david-dm.org/ljharb/gopd/dev-status.svg +[dev-deps-url]: https://david-dm.org/ljharb/gopd#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/gopd.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/gopd.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/gopd.svg +[downloads-url]: https://npm-stat.com/charts.html?package=gopd +[codecov-image]: https://codecov.io/gh/ljharb/gopd/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/ljharb/gopd/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/gopd +[actions-url]: https://github.com/ljharb/gopd/actions diff --git a/node_modules/gopd/gOPD.d.ts b/node_modules/gopd/gOPD.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..def48a3ccd01ec119d6d996fb6070d82de1641a5 --- /dev/null +++ b/node_modules/gopd/gOPD.d.ts @@ -0,0 +1 @@ +export = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/gOPD.js b/node_modules/gopd/gOPD.js new file mode 100644 index 0000000000000000000000000000000000000000..cf9616c4a6671026d27790a79dbf26732a5860fb --- /dev/null +++ b/node_modules/gopd/gOPD.js @@ -0,0 +1,4 @@ +'use strict'; + +/** @type {import('./gOPD')} */ +module.exports = Object.getOwnPropertyDescriptor; diff --git a/node_modules/gopd/index.d.ts b/node_modules/gopd/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e228065f3682d916a1474496f002a9c7bf23c2f4 --- /dev/null +++ b/node_modules/gopd/index.d.ts @@ -0,0 +1,5 @@ +declare function gOPD(obj: O, prop: K): PropertyDescriptor | undefined; + +declare const fn: typeof gOPD | undefined | null; + +export = fn; \ No newline at end of file diff --git a/node_modules/gopd/index.js b/node_modules/gopd/index.js new file mode 100644 index 0000000000000000000000000000000000000000..a4081b013e2a7f3406e47ff109bc0c454905b4cf --- /dev/null +++ b/node_modules/gopd/index.js @@ -0,0 +1,15 @@ +'use strict'; + +/** @type {import('.')} */ +var $gOPD = require('./gOPD'); + +if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } +} + +module.exports = $gOPD; diff --git a/node_modules/gopd/package.json b/node_modules/gopd/package.json new file mode 100644 index 0000000000000000000000000000000000000000..01c5ffa632971171f69bd06cf866d4a3be0db124 --- /dev/null +++ b/node_modules/gopd/package.json @@ -0,0 +1,77 @@ +{ + "name": "gopd", + "version": "1.2.0", + "description": "`Object.getOwnPropertyDescriptor`, but accounts for IE's broken implementation.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./gOPD": "./gOPD.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prelint": "tsc -p . && attw -P", + "lint": "eslint --ext=js,mjs .", + "postlint": "evalmd README.md", + "pretest": "npm run lint", + "tests-only": "tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/ljharb/gopd.git" + }, + "keywords": [ + "ecmascript", + "javascript", + "getownpropertydescriptor", + "property", + "descriptor" + ], + "author": "Jordan Harband ", + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/gopd/issues" + }, + "homepage": "https://github.com/ljharb/gopd#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "engines": { + "node": ">= 0.4" + } +} diff --git a/node_modules/gopd/test/index.js b/node_modules/gopd/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6f43453ade2de4499935b80e16d47d7c1406dd2f --- /dev/null +++ b/node_modules/gopd/test/index.js @@ -0,0 +1,36 @@ +'use strict'; + +var test = require('tape'); +var gOPD = require('../'); + +test('gOPD', function (t) { + t.test('supported', { skip: !gOPD }, function (st) { + st.equal(typeof gOPD, 'function', 'is a function'); + + var obj = { x: 1 }; + st.ok('x' in obj, 'property exists'); + + // @ts-expect-error TS can't figure out narrowing from `skip` + var desc = gOPD(obj, 'x'); + st.deepEqual( + desc, + { + configurable: true, + enumerable: true, + value: 1, + writable: true + }, + 'descriptor is as expected' + ); + + st.end(); + }); + + t.test('not supported', { skip: !!gOPD }, function (st) { + st.notOk(gOPD, 'is falsy'); + + st.end(); + }); + + t.end(); +}); diff --git a/node_modules/gopd/tsconfig.json b/node_modules/gopd/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..d9a6668c3ae6be748c78fbd5694053706b3d6942 --- /dev/null +++ b/node_modules/gopd/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "es2021", + }, + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/graceful-fs/LICENSE b/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e906a25acfb5ee2f955bd39101a207e3458463bd --- /dev/null +++ b/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/graceful-fs/README.md b/node_modules/graceful-fs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..82d6e4daf0cdb8543cca8ce644e6b6dfa61b86f8 --- /dev/null +++ b/node_modules/graceful-fs/README.md @@ -0,0 +1,143 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](https://nodejs.org/api/fs.html) + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFile('some-file-or-whatever', (err, data) => { + // Do stuff here. +}) +``` + +## Sync methods + +This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync +methods. If you use sync methods which open file descriptors then you are +responsible for dealing with any errors. + +This is a known limitation, not a bug. + +## Global Patching + +If you want to patch the global fs module (or any other fs-like +module) you can do this: + +```javascript +// Make sure to read the caveat below. +var realFs = require('fs') +var gracefulFs = require('graceful-fs') +gracefulFs.gracefulify(realFs) +``` + +This should only ever be done at the top-level application layer, in +order to delay on EMFILE errors from any fs-using dependencies. You +should **not** do this in a library, because it can cause unexpected +delays in other parts of the program. + +## Changes + +This module is fairly stable at this point, and used by a lot of +things. That being said, because it implements a subtle behavior +change in a core part of the node API, even modest changes can be +extremely breaking, and the versioning is thus biased towards +bumping the major when in doubt. + +The main change between major versions has been switching between +providing a fully-patched `fs` module vs monkey-patching the node core +builtin, and the approach by which a non-monkey-patched `fs` was +created. + +The goal is to trade `EMFILE` errors for slower fs operations. So, if +you try to open a zillion files, rather than crashing, `open` +operations will be queued up and wait for something else to `close`. + +There are advantages to each approach. Monkey-patching the fs means +that no `EMFILE` errors can possibly occur anywhere in your +application, because everything is using the same core `fs` module, +which is patched. However, it can also obviously cause undesirable +side-effects, especially if the module is loaded multiple times. + +Implementing a separate-but-identical patched `fs` module is more +surgical (and doesn't run the risk of patching multiple times), but +also imposes the challenge of keeping in sync with the core module. + +The current approach loads the `fs` module, and then creates a +lookalike object that has all the same methods, except a few that are +patched. It is safe to use in all versions of Node from 0.8 through +7.0. + +### v4 + +* Do not monkey-patch the fs module. This module may now be used as a + drop-in dep, and users can opt into monkey-patching the fs builtin + if their app requires it. + +### v3 + +* Monkey-patch fs, because the eval approach no longer works on recent + node. +* fixed possible type-error throw if rename fails on windows +* verify that we *never* get EMFILE errors +* Ignore ENOSYS from chmod/chown +* clarify that graceful-fs must be used as a drop-in + +### v2.1.0 + +* Use eval rather than monkey-patching fs. +* readdir: Always sort the results +* win32: requeue a file if error has an OK status + +### v2.0 + +* A return to monkey patching +* wrap process.cwd + +### v1.1 + +* wrap readFile +* Wrap fs.writeFile. +* readdir protection +* Don't clobber the fs builtin +* Handle fs.read EAGAIN errors by trying again +* Expose the curOpen counter +* No-op lchown/lchmod if not implemented +* fs.rename patch only for win32 +* Patch fs.rename to handle AV software on Windows +* Close #4 Chown should not fail on einval or eperm if non-root +* Fix isaacs/fstream#1 Only wrap fs one time +* Fix #3 Start at 1024 max files, then back off on EMFILE +* lutimes that doens't blow up on Linux +* A full on-rewrite using a queue instead of just swallowing the EMFILE error +* Wrap Read/Write streams as well + +### 1.0 + +* Update engines for node 0.6 +* Be lstat-graceful on Windows +* first diff --git a/node_modules/graceful-fs/clone.js b/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000000000000000000000000000000000000..dff3cc8c504b4cf14054b5d7bbc64b1696bc9fec --- /dev/null +++ b/node_modules/graceful-fs/clone.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/node_modules/graceful-fs/graceful-fs.js b/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000000000000000000000000000000000000..8d5b89e4fa7fdbaebf58556cc044d2a912bce5de --- /dev/null +++ b/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,448 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} + +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} diff --git a/node_modules/graceful-fs/legacy-streams.js b/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000000000000000000000000000000000000..d617b50fc0832dcce4ba05f7a7200938438ead90 --- /dev/null +++ b/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/node_modules/graceful-fs/package.json b/node_modules/graceful-fs/package.json new file mode 100644 index 0000000000000000000000000000000000000000..87babf0248563c1767d58126c403954bf3e9e024 --- /dev/null +++ b/node_modules/graceful-fs/package.json @@ -0,0 +1,53 @@ +{ + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "4.2.11", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-graceful-fs" + }, + "main": "graceful-fs.js", + "directories": { + "test": "test" + }, + "scripts": { + "preversion": "npm test", + "postversion": "npm publish", + "postpublish": "git push origin --follow-tags", + "test": "nyc --silent node test.js | tap -c -", + "posttest": "nyc report" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^16.3.4" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "tap": { + "reporter": "classic" + } +} diff --git a/node_modules/graceful-fs/polyfills.js b/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000000000000000000000000000000000000..453f1a9e702d1aaf9a34cb8460f30073dc83bcf5 --- /dev/null +++ b/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,355 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/node_modules/graphql/LICENSE b/node_modules/graphql/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7bbf892a0493619a5a9d46ecb8d74b99bc4a2604 --- /dev/null +++ b/node_modules/graphql/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) GraphQL Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/graphql/NotSupportedTSVersion.d.ts b/node_modules/graphql/NotSupportedTSVersion.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af77c305f60eda395e731bf3282ad27aad5e6cc8 --- /dev/null +++ b/node_modules/graphql/NotSupportedTSVersion.d.ts @@ -0,0 +1 @@ +"Package 'graphql' support only TS versions that are >=4.1.0". \ No newline at end of file diff --git a/node_modules/graphql/README.md b/node_modules/graphql/README.md new file mode 100644 index 0000000000000000000000000000000000000000..31f640a8eece55a200d6a96c280311bd160242ef --- /dev/null +++ b/node_modules/graphql/README.md @@ -0,0 +1,203 @@ +[![GraphQLConf 2025 Banner: September 08-10, Amsterdam. Hosted by the GraphQL Foundation](./assets/graphql-conf-2025.png)](https://graphql.org/conf/2025/?utm_source=github&utm_medium=graphql_js&utm_campaign=readme) + +# GraphQL.js + +The JavaScript reference implementation for GraphQL, a query language for APIs created by Facebook. + +[![npm version](https://badge.fury.io/js/graphql.svg)](https://badge.fury.io/js/graphql) +[![Build Status](https://github.com/graphql/graphql-js/workflows/CI/badge.svg?branch=main)](https://github.com/graphql/graphql-js/actions?query=branch%3Amain) +[![Coverage Status](https://codecov.io/gh/graphql/graphql-js/branch/main/graph/badge.svg)](https://codecov.io/gh/graphql/graphql-js) + +See more complete documentation at https://graphql.org/ and +https://graphql.org/graphql-js/. + +Looking for help? Find resources [from the community](https://graphql.org/community/). + +## Getting Started + +A general overview of GraphQL is available in the +[README](https://github.com/graphql/graphql-spec/blob/main/README.md) for the +[Specification for GraphQL](https://github.com/graphql/graphql-spec). That overview +describes a simple set of GraphQL examples that exist as [tests](src/__tests__) +in this repository. A good way to get started with this repository is to walk +through that README and the corresponding tests in parallel. + +### Using GraphQL.js + +Install GraphQL.js from npm + +With npm: + +```sh +npm install --save graphql +``` + +or using yarn: + +```sh +yarn add graphql +``` + +GraphQL.js provides two important capabilities: building a type schema and +serving queries against that type schema. + +First, build a GraphQL type schema which maps to your codebase. + +```js +import { + graphql, + GraphQLSchema, + GraphQLObjectType, + GraphQLString, +} from 'graphql'; + +var schema = new GraphQLSchema({ + query: new GraphQLObjectType({ + name: 'RootQueryType', + fields: { + hello: { + type: GraphQLString, + resolve() { + return 'world'; + }, + }, + }, + }), +}); +``` + +This defines a simple schema, with one type and one field, that resolves +to a fixed value. The `resolve` function can return a value, a promise, +or an array of promises. A more complex example is included in the top-level [tests](src/__tests__) directory. + +Then, serve the result of a query against that type schema. + +```js +var source = '{ hello }'; + +graphql({ schema, source }).then((result) => { + // Prints + // { + // data: { hello: "world" } + // } + console.log(result); +}); +``` + +This runs a query fetching the one field defined. The `graphql` function will +first ensure the query is syntactically and semantically valid before executing +it, reporting errors otherwise. + +```js +var source = '{ BoyHowdy }'; + +graphql({ schema, source }).then((result) => { + // Prints + // { + // errors: [ + // { message: 'Cannot query field BoyHowdy on RootQueryType', + // locations: [ { line: 1, column: 3 } ] } + // ] + // } + console.log(result); +}); +``` + +**Note**: Please don't forget to set `NODE_ENV=production` if you are running a production server. It will disable some checks that can be useful during development but will significantly impact performance. + +## Want to ride the bleeding edge? + +The `npm` branch in this repository is automatically maintained to be the last +commit to `main` to pass all tests, in the same form found on npm. It is +recommended to use builds deployed to npm for many reasons, but if you want to use +the latest not-yet-released version of graphql-js, you can do so by depending +directly on this branch: + +``` +npm install graphql@git://github.com/graphql/graphql-js.git#npm +``` + +### Experimental features + +Each release of GraphQL.js will be accompanied by an experimental release containing support for the `@defer` and `@stream` directive proposal. We are hoping to get community feedback on these releases before the proposal is accepted into the GraphQL specification. You can use this experimental release of GraphQL.js by adding the following to your project's `package.json` file. + +``` +"graphql": "experimental-stream-defer" +``` + +Community feedback on this experimental release is much appreciated and can be provided on the [issue created for this purpose](https://github.com/graphql/graphql-js/issues/2848). + +## Using in a Browser + +GraphQL.js is a general-purpose library and can be used both in a Node server +and in the browser. As an example, the [GraphiQL](https://github.com/graphql/graphiql/) +tool is built with GraphQL.js! + +Building a project using GraphQL.js with [webpack](https://webpack.js.org) or +[rollup](https://github.com/rollup/rollup) should just work and only include +the portions of the library you use. This works because GraphQL.js is distributed +with both CommonJS (`require()`) and ESModule (`import`) files. Ensure that any +custom build configurations look for `.mjs` files! + +## Contributing + +We actively welcome pull requests. Learn how to [contribute](./.github/CONTRIBUTING.md). + +This repository is managed by EasyCLA. Project participants must sign the free ([GraphQL Specification Membership agreement](https://preview-spec-membership.graphql.org) before making a contribution. You only need to do this one time, and it can be signed by [individual contributors](http://individual-spec-membership.graphql.org/) or their [employers](http://corporate-spec-membership.graphql.org/). + +To initiate the signature process please open a PR against this repo. The EasyCLA bot will block the merge if we still need a membership agreement from you. + +You can find [detailed information here](https://github.com/graphql/graphql-wg/tree/main/membership). If you have issues, please email [operations@graphql.org](mailto:operations@graphql.org). + +If your company benefits from GraphQL and you would like to provide essential financial support for the systems and people that power our community, please also consider membership in the [GraphQL Foundation](https://foundation.graphql.org/join). + +## Changelog + +Changes are tracked as [GitHub releases](https://github.com/graphql/graphql-js/releases). + +## License + +GraphQL.js is [MIT-licensed](./LICENSE). + +## Version Support + +GraphQL.JS follows Semantic Versioning (SemVer) for its releases. Our version support policy is as follows: + +- Latest Major Version: We provide full support, including bug fixes and security updates, for the latest major version of GraphQL.JS. +- Previous Major Version: We offer feature support for the previous major version for 12 months after the release of the newest major version. + This means that for 12 months we can backport features for specification changes _if_ they don't cause any breaking changes. We'll continue + supporting the previous major version with bug and security fixes. +- Older Versions: Versions older than the previous major release are considered unsupported. While the code remains available, + we do not actively maintain or provide updates for these versions. + One exception to this rule is when the older version has been released < 1 year ago, in that case we + will treat it like the "Previous Major Version". + +### Long-Term Support (LTS) + +We do not currently offer a Long-Term Support version of GraphQL.JS. Users are encouraged to upgrade to the latest stable version +to receive the most up-to-date features, performance improvements, and security updates. + +### End-of-Life (EOL) Schedule + +We will announce the EOL date for a major version at least 6 months in advance. +After a version reaches its EOL, it will no longer receive updates, even for critical security issues. + +### Upgrade Assistance + +To assist users in upgrading to newer versions: + +- We maintain detailed release notes for each version, highlighting new features, breaking changes, and deprecations. +- [Our documentation](https://www.graphql-js.org/) includes migration guides for moving between major versions. +- The [community forum (Discord channel #graphql-js)](https://discord.graphql.org) is available for users who need additional assistance with upgrades. + +### Security Updates + +We prioritize the security of GraphQL.JS: + +- Critical security updates will be applied to both the current and previous major version. +- For versions that have reached EOL, we strongly recommend upgrading to a supported version to receive security updates. + +### Community Contributions + +We welcome community contributions for all versions of GraphQL.JS. However, our maintainers will primarily focus on reviewing +and merging contributions for supported versions. diff --git a/node_modules/graphql/error/GraphQLError.d.ts b/node_modules/graphql/error/GraphQLError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2116e87d961625d5f6adc815bcd33940c3cbc9ee --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.d.ts @@ -0,0 +1,288 @@ +/** @category Errors */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ASTNode } from '../language/ast'; +import type { SourceLocation } from '../language/location'; +import type { Source } from '../language/source'; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLErrorExtensions { + [attributeName: string]: unknown; +} +/** + * Custom formatted extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLFormattedErrorExtensions { + [attributeName: string]: unknown; +} +/** Options used to construct a GraphQLError. */ +export interface GraphQLErrorOptions { + /** AST node or nodes associated with this error. */ + nodes?: ReadonlyArray | ASTNode | null; + /** Source document used to derive error locations. */ + source?: Maybe; + /** Character offsets in the source document associated with this error. */ + positions?: Maybe>; + /** Response path where this error occurred during execution. */ + path?: Maybe>; + /** Original error that caused this GraphQLError, if one exists. */ + originalError?: Maybe< + Error & { + /** Extension fields associated with this value. */ + readonly extensions?: unknown; + } + >; + /** Extension fields to include in the formatted result. */ + extensions?: Maybe; +} +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ +export declare class GraphQLError extends Error { + /** + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + readonly locations: ReadonlyArray | undefined; + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + readonly path: ReadonlyArray | undefined; + /** An array of GraphQL AST Nodes corresponding to this error. */ + readonly nodes: ReadonlyArray | undefined; + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + readonly source: Source | undefined; + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + readonly positions: ReadonlyArray | undefined; + /** Original error that caused this GraphQLError, if one exists. */ + readonly originalError: Error | undefined; + /** Extension fields to add to the formatted error. */ + readonly extensions: GraphQLErrorExtensions; + /** + * Creates a GraphQLError instance. + * @param message - Human-readable error message. + * @param options - Error metadata such as source locations, response path, original error, and extensions. + * This positional-arguments constructor overload is deprecated. Use the + * `GraphQLError(message, options)` overload instead. + * @example + * ```ts + * // Create an error from AST nodes and response metadata. + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const document = parse('{ greeting }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = new GraphQLError('Cannot query this field.', { + * nodes: fieldNode, + * path: ['greeting'], + * extensions: { code: 'FORBIDDEN' }, + * }); + * + * error.message; // => 'Cannot query this field.' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.extensions; // => { code: 'FORBIDDEN' } + * ``` + * @example + * ```ts + * // This variant derives locations from source positions and preserves the original error. + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError('Resolver failed.', { + * source, + * positions: [2], + * path: ['greeting'], + * originalError, + * }); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * ``` + */ + constructor(message: string, options?: GraphQLErrorOptions); + /** + * Creates a GraphQLError instance using the legacy positional constructor. + * This deprecated overload will be removed in v17. Prefer the + * `GraphQLErrorOptions` object overload, which keeps optional error metadata + * in a single options bag. + * @param message - Human-readable error message. + * @param nodes - AST node or nodes associated with this error. + * @param source - Source document used to derive error locations. + * @param positions - Character offsets in the source document associated with + * this error. + * @param path - Response path where this error occurred during execution. + * @param originalError - Original error that caused this GraphQLError, if one + * exists. + * @param extensions - Extension fields to include in the formatted error. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError( + * 'Resolver failed.', + * undefined, + * source, + * [2], + * ['greeting'], + * originalError, + * { code: 'INTERNAL' }, + * ); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * error.extensions; // => { code: 'INTERNAL' } + * ``` + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor( + message: string, + nodes?: ReadonlyArray | ASTNode | null, + source?: Maybe, + positions?: Maybe>, + path?: Maybe>, + originalError?: Maybe< + Error & { + readonly extensions?: unknown; + } + >, + extensions?: Maybe, + ); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns this error as a human-readable message with source locations. + * @returns The formatted error string. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Cannot query field "name".', { + * source: new Source('{ name }'), + * positions: [2], + * }); + * + * error.toString(); // => 'Cannot query field "name".\n\nGraphQL request:1:3\n1 | { name }\n | ^' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Resolver failed.', { + * path: ['viewer', 'name'], + * extensions: { code: 'INTERNAL' }, + * }); + * + * error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } } + * ``` + */ + toJSON(): GraphQLFormattedError; +} +/** See: https://spec.graphql.org/draft/#sec-Errors */ +export interface GraphQLFormattedError { + /** + * A short, human-readable summary of the problem that **SHOULD NOT** change + * from occurrence to occurrence of the problem, except for purposes of + * localization. + */ + readonly message: string; + /** + * If an error can be associated to a particular point in the requested + * GraphQL document, it should contain a list of locations. + */ + readonly locations?: ReadonlyArray; + /** + * If an error can be associated to a particular field in the GraphQL result, + * it _must_ contain an entry with the key `path` that details the path of + * the response field which experienced the error. This allows clients to + * identify whether a null result is intentional or caused by a runtime error. + */ + readonly path?: ReadonlyArray; + /** + * Reserved for implementors to extend the protocol however they see fit, + * and hence there are no additional restrictions on its contents. + */ + readonly extensions?: GraphQLFormattedErrorExtensions; +} +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. This deprecated helper is retained + * for backwards compatibility; call `error.toString()` instead because + * printError will be removed in v17. + * @param error - The error to format. + * @returns The printed string representation. + * @example + * ```ts + * import { GraphQLError, printError } from 'graphql/error'; + * + * const message = printError(new GraphQLError('Example error')); + * + * message; // => 'Example error' + * ``` + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ +export declare function printError(error: GraphQLError): string; +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. This deprecated + * helper is retained for backwards compatibility; call `error.toJSON()` + * instead because formatError will be removed in v17. + * @param error - The error to format. + * @returns The JSON-serializable formatted error. + * @example + * ```ts + * import { GraphQLError, formatError } from 'graphql/error'; + * + * const formatted = formatError(new GraphQLError('Example error')); + * + * formatted; // => { message: 'Example error' } + * ``` + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ +export declare function formatError(error: GraphQLError): GraphQLFormattedError; diff --git a/node_modules/graphql/error/GraphQLError.js b/node_modules/graphql/error/GraphQLError.js new file mode 100644 index 0000000000000000000000000000000000000000..d7273b2a9ee0b3bca5c7cc5c7ed3cf1cfc70c9ac --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.js @@ -0,0 +1,398 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.GraphQLError = void 0; +exports.formatError = formatError; +exports.printError = printError; + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _location = require('../language/location.js'); + +var _printLocation = require('../language/printLocation.js'); + +/** @category Errors */ +function toNormalizedOptions(args) { + const firstArg = args[0]; + + if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { + return { + nodes: firstArg, + source: args[1], + positions: args[2], + path: args[3], + originalError: args[4], + extensions: args[5], + }; + } + + return firstArg; +} +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ + +class GraphQLError extends Error { + /** + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** An array of GraphQL AST Nodes corresponding to this error. */ + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** Original error that caused this GraphQLError, if one exists. */ + + /** Extension fields to add to the formatted error. */ + + /** + * Creates a GraphQLError instance. + * @param message - Human-readable error message. + * @param options - Error metadata such as source locations, response path, original error, and extensions. + * This positional-arguments constructor overload is deprecated. Use the + * `GraphQLError(message, options)` overload instead. + * @example + * ```ts + * // Create an error from AST nodes and response metadata. + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const document = parse('{ greeting }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = new GraphQLError('Cannot query this field.', { + * nodes: fieldNode, + * path: ['greeting'], + * extensions: { code: 'FORBIDDEN' }, + * }); + * + * error.message; // => 'Cannot query this field.' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.extensions; // => { code: 'FORBIDDEN' } + * ``` + * @example + * ```ts + * // This variant derives locations from source positions and preserves the original error. + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError('Resolver failed.', { + * source, + * positions: [2], + * path: ['greeting'], + * originalError, + * }); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * ``` + */ + + /** + * Creates a GraphQLError instance using the legacy positional constructor. + * This deprecated overload will be removed in v17. Prefer the + * `GraphQLErrorOptions` object overload, which keeps optional error metadata + * in a single options bag. + * @param message - Human-readable error message. + * @param nodes - AST node or nodes associated with this error. + * @param source - Source document used to derive error locations. + * @param positions - Character offsets in the source document associated with + * this error. + * @param path - Response path where this error occurred during execution. + * @param originalError - Original error that caused this GraphQLError, if one + * exists. + * @param extensions - Extension fields to include in the formatted error. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError( + * 'Resolver failed.', + * undefined, + * source, + * [2], + * ['greeting'], + * originalError, + * { code: 'INTERNAL' }, + * ); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * error.extensions; // => { code: 'INTERNAL' } + * ``` + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor(message, ...rawArgs) { + var _this$nodes, _nodeLocations$, _ref; + + const { nodes, source, positions, path, originalError, extensions } = + toNormalizedOptions(rawArgs); + super(message); + this.name = 'GraphQLError'; + this.path = path !== null && path !== void 0 ? path : undefined; + this.originalError = + originalError !== null && originalError !== void 0 + ? originalError + : undefined; // Compute list of blame nodes. + + this.nodes = undefinedIfEmpty( + Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined, + ); + const nodeLocations = undefinedIfEmpty( + (_this$nodes = this.nodes) === null || _this$nodes === void 0 + ? void 0 + : _this$nodes.map((node) => node.loc).filter((loc) => loc != null), + ); // Compute locations in the source for the given nodes/positions. + + this.source = + source !== null && source !== void 0 + ? source + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : (_nodeLocations$ = nodeLocations[0]) === null || + _nodeLocations$ === void 0 + ? void 0 + : _nodeLocations$.source; + this.positions = + positions !== null && positions !== void 0 + ? positions + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => loc.start); + this.locations = + positions && source + ? positions.map((pos) => (0, _location.getLocation)(source, pos)) + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => + (0, _location.getLocation)(loc.source, loc.start), + ); + const originalExtensions = (0, _isObjectLike.isObjectLike)( + originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions, + ) + ? originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions + : undefined; + this.extensions = + (_ref = + extensions !== null && extensions !== void 0 + ? extensions + : originalExtensions) !== null && _ref !== void 0 + ? _ref + : Object.create(null); // Only properties prescribed by the spec should be enumerable. + // Keep the rest as non-enumerable. + + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true, + }, + name: { + enumerable: false, + }, + nodes: { + enumerable: false, + }, + source: { + enumerable: false, + }, + positions: { + enumerable: false, + }, + originalError: { + enumerable: false, + }, + }); // Include (non-enumerable) stack trace. + + /* c8 ignore start */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + + if ( + originalError !== null && + originalError !== void 0 && + originalError.stack + ) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true, + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true, + }); + } + /* c8 ignore stop */ + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLError'; + } + /** + * Returns this error as a human-readable message with source locations. + * @returns The formatted error string. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Cannot query field "name".', { + * source: new Source('{ name }'), + * positions: [2], + * }); + * + * error.toString(); // => 'Cannot query field "name".\n\nGraphQL request:1:3\n1 | { name }\n | ^' + * ``` + */ + + toString() { + let output = this.message; + + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += '\n\n' + (0, _printLocation.printLocation)(node.loc); + } + } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += + '\n\n' + + (0, _printLocation.printSourceLocation)(this.source, location); + } + } + + return output; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Resolver failed.', { + * path: ['viewer', 'name'], + * extensions: { code: 'INTERNAL' }, + * }); + * + * error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } } + * ``` + */ + + toJSON() { + const formattedError = { + message: this.message, + }; + + if (this.locations != null) { + formattedError.locations = this.locations; + } + + if (this.path != null) { + formattedError.path = this.path; + } + + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } + + return formattedError; + } +} + +exports.GraphQLError = GraphQLError; + +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** See: https://spec.graphql.org/draft/#sec-Errors */ + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. This deprecated helper is retained + * for backwards compatibility; call `error.toString()` instead because + * printError will be removed in v17. + * @param error - The error to format. + * @returns The printed string representation. + * @example + * ```ts + * import { GraphQLError, printError } from 'graphql/error'; + * + * const message = printError(new GraphQLError('Example error')); + * + * message; // => 'Example error' + * ``` + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ +function printError(error) { + return error.toString(); +} +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. This deprecated + * helper is retained for backwards compatibility; call `error.toJSON()` + * instead because formatError will be removed in v17. + * @param error - The error to format. + * @returns The JSON-serializable formatted error. + * @example + * ```ts + * import { GraphQLError, formatError } from 'graphql/error'; + * + * const formatted = formatError(new GraphQLError('Example error')); + * + * formatted; // => { message: 'Example error' } + * ``` + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ + +function formatError(error) { + return error.toJSON(); +} diff --git a/node_modules/graphql/error/GraphQLError.mjs b/node_modules/graphql/error/GraphQLError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0c1f79ffca3f3c5b1ed3b6383d899c0482f35e90 --- /dev/null +++ b/node_modules/graphql/error/GraphQLError.mjs @@ -0,0 +1,384 @@ +/** @category Errors */ +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { getLocation } from '../language/location.mjs'; +import { + printLocation, + printSourceLocation, +} from '../language/printLocation.mjs'; + +function toNormalizedOptions(args) { + const firstArg = args[0]; + + if (firstArg == null || 'kind' in firstArg || 'length' in firstArg) { + return { + nodes: firstArg, + source: args[1], + positions: args[2], + path: args[3], + originalError: args[4], + extensions: args[5], + }; + } + + return firstArg; +} +/** + * A GraphQLError describes an Error found during the parse, validate, or + * execute phases of performing a GraphQL operation. In addition to a message + * and stack trace, it also includes information about the locations in a + * GraphQL document and/or execution result that correspond to the Error. + */ + +export class GraphQLError extends Error { + /** + * An array of `{ line, column }` locations within the source GraphQL document + * which correspond to this error. + * + * Errors during validation often contain multiple locations, for example to + * point out two things with the same name. Errors during execution include a + * single location, the field which produced the error. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** + * An array describing the JSON-path into the execution response which + * corresponds to this error. Only included for errors during execution. + * + * Enumerable, and appears in the result of JSON.stringify(). + */ + + /** An array of GraphQL AST Nodes corresponding to this error. */ + + /** + * The source GraphQL document for the first location of this error. + * + * Note that if this Error represents more than one node, the source may not + * represent nodes after the first node. + */ + + /** + * An array of character offsets within the source GraphQL document + * which correspond to this error. + */ + + /** Original error that caused this GraphQLError, if one exists. */ + + /** Extension fields to add to the formatted error. */ + + /** + * Creates a GraphQLError instance. + * @param message - Human-readable error message. + * @param options - Error metadata such as source locations, response path, original error, and extensions. + * This positional-arguments constructor overload is deprecated. Use the + * `GraphQLError(message, options)` overload instead. + * @example + * ```ts + * // Create an error from AST nodes and response metadata. + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const document = parse('{ greeting }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = new GraphQLError('Cannot query this field.', { + * nodes: fieldNode, + * path: ['greeting'], + * extensions: { code: 'FORBIDDEN' }, + * }); + * + * error.message; // => 'Cannot query this field.' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.extensions; // => { code: 'FORBIDDEN' } + * ``` + * @example + * ```ts + * // This variant derives locations from source positions and preserves the original error. + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError('Resolver failed.', { + * source, + * positions: [2], + * path: ['greeting'], + * originalError, + * }); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * ``` + */ + + /** + * Creates a GraphQLError instance using the legacy positional constructor. + * This deprecated overload will be removed in v17. Prefer the + * `GraphQLErrorOptions` object overload, which keeps optional error metadata + * in a single options bag. + * @param message - Human-readable error message. + * @param nodes - AST node or nodes associated with this error. + * @param source - Source document used to derive error locations. + * @param positions - Character offsets in the source document associated with + * this error. + * @param path - Response path where this error occurred during execution. + * @param originalError - Original error that caused this GraphQLError, if one + * exists. + * @param extensions - Extension fields to include in the formatted error. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const source = new Source('{ greeting }'); + * const originalError = new Error('Database unavailable.'); + * const error = new GraphQLError( + * 'Resolver failed.', + * undefined, + * source, + * [2], + * ['greeting'], + * originalError, + * { code: 'INTERNAL' }, + * ); + * + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['greeting'] + * error.originalError; // => originalError + * error.extensions; // => { code: 'INTERNAL' } + * ``` + * @deprecated Please use the `GraphQLErrorOptions` constructor overload instead. + */ + constructor(message, ...rawArgs) { + var _this$nodes, _nodeLocations$, _ref; + + const { nodes, source, positions, path, originalError, extensions } = + toNormalizedOptions(rawArgs); + super(message); + this.name = 'GraphQLError'; + this.path = path !== null && path !== void 0 ? path : undefined; + this.originalError = + originalError !== null && originalError !== void 0 + ? originalError + : undefined; // Compute list of blame nodes. + + this.nodes = undefinedIfEmpty( + Array.isArray(nodes) ? nodes : nodes ? [nodes] : undefined, + ); + const nodeLocations = undefinedIfEmpty( + (_this$nodes = this.nodes) === null || _this$nodes === void 0 + ? void 0 + : _this$nodes.map((node) => node.loc).filter((loc) => loc != null), + ); // Compute locations in the source for the given nodes/positions. + + this.source = + source !== null && source !== void 0 + ? source + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : (_nodeLocations$ = nodeLocations[0]) === null || + _nodeLocations$ === void 0 + ? void 0 + : _nodeLocations$.source; + this.positions = + positions !== null && positions !== void 0 + ? positions + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => loc.start); + this.locations = + positions && source + ? positions.map((pos) => getLocation(source, pos)) + : nodeLocations === null || nodeLocations === void 0 + ? void 0 + : nodeLocations.map((loc) => getLocation(loc.source, loc.start)); + const originalExtensions = isObjectLike( + originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions, + ) + ? originalError === null || originalError === void 0 + ? void 0 + : originalError.extensions + : undefined; + this.extensions = + (_ref = + extensions !== null && extensions !== void 0 + ? extensions + : originalExtensions) !== null && _ref !== void 0 + ? _ref + : Object.create(null); // Only properties prescribed by the spec should be enumerable. + // Keep the rest as non-enumerable. + + Object.defineProperties(this, { + message: { + writable: true, + enumerable: true, + }, + name: { + enumerable: false, + }, + nodes: { + enumerable: false, + }, + source: { + enumerable: false, + }, + positions: { + enumerable: false, + }, + originalError: { + enumerable: false, + }, + }); // Include (non-enumerable) stack trace. + + /* c8 ignore start */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + + if ( + originalError !== null && + originalError !== void 0 && + originalError.stack + ) { + Object.defineProperty(this, 'stack', { + value: originalError.stack, + writable: true, + configurable: true, + }); + } else if (Error.captureStackTrace) { + Error.captureStackTrace(this, GraphQLError); + } else { + Object.defineProperty(this, 'stack', { + value: Error().stack, + writable: true, + configurable: true, + }); + } + /* c8 ignore stop */ + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLError'; + } + /** + * Returns this error as a human-readable message with source locations. + * @returns The formatted error string. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Cannot query field "name".', { + * source: new Source('{ name }'), + * positions: [2], + * }); + * + * error.toString(); // => 'Cannot query field "name".\n\nGraphQL request:1:3\n1 | { name }\n | ^' + * ``` + */ + + toString() { + let output = this.message; + + if (this.nodes) { + for (const node of this.nodes) { + if (node.loc) { + output += '\n\n' + printLocation(node.loc); + } + } + } else if (this.source && this.locations) { + for (const location of this.locations) { + output += '\n\n' + printSourceLocation(this.source, location); + } + } + + return output; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLError } from 'graphql/error'; + * + * const error = new GraphQLError('Resolver failed.', { + * path: ['viewer', 'name'], + * extensions: { code: 'INTERNAL' }, + * }); + * + * error.toJSON(); // => { message: 'Resolver failed.', path: ['viewer', 'name'], extensions: { code: 'INTERNAL' } } + * ``` + */ + + toJSON() { + const formattedError = { + message: this.message, + }; + + if (this.locations != null) { + formattedError.locations = this.locations; + } + + if (this.path != null) { + formattedError.path = this.path; + } + + if (this.extensions != null && Object.keys(this.extensions).length > 0) { + formattedError.extensions = this.extensions; + } + + return formattedError; + } +} + +function undefinedIfEmpty(array) { + return array === undefined || array.length === 0 ? undefined : array; +} +/** See: https://spec.graphql.org/draft/#sec-Errors */ + +/** + * Prints a GraphQLError to a string, representing useful location information + * about the error's position in the source. This deprecated helper is retained + * for backwards compatibility; call `error.toString()` instead because + * printError will be removed in v17. + * @param error - The error to format. + * @returns The printed string representation. + * @example + * ```ts + * import { GraphQLError, printError } from 'graphql/error'; + * + * const message = printError(new GraphQLError('Example error')); + * + * message; // => 'Example error' + * ``` + * @deprecated Please use `error.toString` instead. Will be removed in v17 + */ +export function printError(error) { + return error.toString(); +} +/** + * Given a GraphQLError, format it according to the rules described by the + * Response Format, Errors section of the GraphQL Specification. This deprecated + * helper is retained for backwards compatibility; call `error.toJSON()` + * instead because formatError will be removed in v17. + * @param error - The error to format. + * @returns The JSON-serializable formatted error. + * @example + * ```ts + * import { GraphQLError, formatError } from 'graphql/error'; + * + * const formatted = formatError(new GraphQLError('Example error')); + * + * formatted; // => { message: 'Example error' } + * ``` + * @deprecated Please use `error.toJSON` instead. Will be removed in v17 + */ + +export function formatError(error) { + return error.toJSON(); +} diff --git a/node_modules/graphql/error/index.d.ts b/node_modules/graphql/error/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1fc3a7f4520a87f471339dad4b9081b675c04822 --- /dev/null +++ b/node_modules/graphql/error/index.d.ts @@ -0,0 +1,15 @@ +/** + * Create, format, and locate GraphQL errors. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { GraphQLError, printError, formatError } from './GraphQLError'; +export type { + GraphQLErrorOptions, + GraphQLFormattedError, + GraphQLErrorExtensions, + GraphQLFormattedErrorExtensions, +} from './GraphQLError'; +export { syntaxError } from './syntaxError'; +export { locatedError } from './locatedError'; diff --git a/node_modules/graphql/error/index.js b/node_modules/graphql/error/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c508370ee2e93e481eef1c26c950756b0a5e7d17 --- /dev/null +++ b/node_modules/graphql/error/index.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'GraphQLError', { + enumerable: true, + get: function () { + return _GraphQLError.GraphQLError; + }, +}); +Object.defineProperty(exports, 'formatError', { + enumerable: true, + get: function () { + return _GraphQLError.formatError; + }, +}); +Object.defineProperty(exports, 'locatedError', { + enumerable: true, + get: function () { + return _locatedError.locatedError; + }, +}); +Object.defineProperty(exports, 'printError', { + enumerable: true, + get: function () { + return _GraphQLError.printError; + }, +}); +Object.defineProperty(exports, 'syntaxError', { + enumerable: true, + get: function () { + return _syntaxError.syntaxError; + }, +}); + +var _GraphQLError = require('./GraphQLError.js'); + +var _syntaxError = require('./syntaxError.js'); + +var _locatedError = require('./locatedError.js'); diff --git a/node_modules/graphql/error/index.mjs b/node_modules/graphql/error/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..44550f39b1726b7495d7b460c55e067ee2d20462 --- /dev/null +++ b/node_modules/graphql/error/index.mjs @@ -0,0 +1,9 @@ +/** + * Create, format, and locate GraphQL errors. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { GraphQLError, printError, formatError } from './GraphQLError.mjs'; +export { syntaxError } from './syntaxError.mjs'; +export { locatedError } from './locatedError.mjs'; diff --git a/node_modules/graphql/error/locatedError.d.ts b/node_modules/graphql/error/locatedError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f4d3c65e1962d50c11381cde8132574d6f2459e6 --- /dev/null +++ b/node_modules/graphql/error/locatedError.d.ts @@ -0,0 +1,33 @@ +/** @category Errors */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ASTNode } from '../language/ast'; +import { GraphQLError } from './GraphQLError'; +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + * @param rawOriginalError - The original error value to wrap. + * @param nodes - The AST nodes associated with the error. + * @param path - The response path associated with the error. + * @returns The GraphQL error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { locatedError } from 'graphql/error'; + * + * const document = parse('{ viewer { name } }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = locatedError(new Error('Resolver failed'), fieldNode, [ + * 'viewer', + * ]); + * + * error.message; // => 'Resolver failed' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['viewer'] + * ``` + */ +export declare function locatedError( + rawOriginalError: unknown, + nodes: ASTNode | ReadonlyArray | undefined | null, + path?: Maybe>, +): GraphQLError; diff --git a/node_modules/graphql/error/locatedError.js b/node_modules/graphql/error/locatedError.js new file mode 100644 index 0000000000000000000000000000000000000000..575431b6dbb647784ce73053450f818706a32c90 --- /dev/null +++ b/node_modules/graphql/error/locatedError.js @@ -0,0 +1,61 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.locatedError = locatedError; + +var _toError = require('../jsutils/toError.js'); + +var _GraphQLError = require('./GraphQLError.js'); + +/** @category Errors */ + +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + * @param rawOriginalError - The original error value to wrap. + * @param nodes - The AST nodes associated with the error. + * @param path - The response path associated with the error. + * @returns The GraphQL error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { locatedError } from 'graphql/error'; + * + * const document = parse('{ viewer { name } }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = locatedError(new Error('Resolver failed'), fieldNode, [ + * 'viewer', + * ]); + * + * error.message; // => 'Resolver failed' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['viewer'] + * ``` + */ +function locatedError(rawOriginalError, nodes, path) { + var _nodes; + + const originalError = (0, _toError.toError)(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (isLocatedGraphQLError(originalError)) { + return originalError; + } + + return new _GraphQLError.GraphQLError(originalError.message, { + nodes: + (_nodes = originalError.nodes) !== null && _nodes !== void 0 + ? _nodes + : nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError, + }); +} + +function isLocatedGraphQLError(error) { + return Array.isArray(error.path); +} diff --git a/node_modules/graphql/error/locatedError.mjs b/node_modules/graphql/error/locatedError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..02f833f6220b2a55dfe17e11aaa70b9a60e09a2d --- /dev/null +++ b/node_modules/graphql/error/locatedError.mjs @@ -0,0 +1,52 @@ +/** @category Errors */ +import { toError } from '../jsutils/toError.mjs'; +import { GraphQLError } from './GraphQLError.mjs'; +/** + * Given an arbitrary value, presumably thrown while attempting to execute a + * GraphQL operation, produce a new GraphQLError aware of the location in the + * document responsible for the original Error. + * @param rawOriginalError - The original error value to wrap. + * @param nodes - The AST nodes associated with the error. + * @param path - The response path associated with the error. + * @returns The GraphQL error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { locatedError } from 'graphql/error'; + * + * const document = parse('{ viewer { name } }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * const error = locatedError(new Error('Resolver failed'), fieldNode, [ + * 'viewer', + * ]); + * + * error.message; // => 'Resolver failed' + * error.locations; // => [{ line: 1, column: 3 }] + * error.path; // => ['viewer'] + * ``` + */ + +export function locatedError(rawOriginalError, nodes, path) { + var _nodes; + + const originalError = toError(rawOriginalError); // Note: this uses a brand-check to support GraphQL errors originating from other contexts. + + if (isLocatedGraphQLError(originalError)) { + return originalError; + } + + return new GraphQLError(originalError.message, { + nodes: + (_nodes = originalError.nodes) !== null && _nodes !== void 0 + ? _nodes + : nodes, + source: originalError.source, + positions: originalError.positions, + path, + originalError, + }); +} + +function isLocatedGraphQLError(error) { + return Array.isArray(error.path); +} diff --git a/node_modules/graphql/error/syntaxError.d.ts b/node_modules/graphql/error/syntaxError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8908047e5395547968975d904ce8aa533e802d74 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.d.ts @@ -0,0 +1,26 @@ +/** @category Errors */ +import type { Source } from '../language/source'; +import { GraphQLError } from './GraphQLError'; +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + * @param source - The GraphQL source containing the syntax error. + * @param position - Character offset where the syntax error was encountered. + * @param description - Human-readable description of the syntax error. + * @returns A GraphQLError located at the syntax error position. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { syntaxError } from 'graphql/error'; + * + * const error = syntaxError(new Source('query {'), 7, 'Expected Name'); + * + * error.message; // => 'Syntax Error: Expected Name' + * error.locations; // => [{ line: 1, column: 8 }] + * ``` + */ +export declare function syntaxError( + source: Source, + position: number, + description: string, +): GraphQLError; diff --git a/node_modules/graphql/error/syntaxError.js b/node_modules/graphql/error/syntaxError.js new file mode 100644 index 0000000000000000000000000000000000000000..7326432a63bd319e99bcbf357e21a76b6f4aec0f --- /dev/null +++ b/node_modules/graphql/error/syntaxError.js @@ -0,0 +1,35 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.syntaxError = syntaxError; + +var _GraphQLError = require('./GraphQLError.js'); + +/** @category Errors */ + +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + * @param source - The GraphQL source containing the syntax error. + * @param position - Character offset where the syntax error was encountered. + * @param description - Human-readable description of the syntax error. + * @returns A GraphQLError located at the syntax error position. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { syntaxError } from 'graphql/error'; + * + * const error = syntaxError(new Source('query {'), 7, 'Expected Name'); + * + * error.message; // => 'Syntax Error: Expected Name' + * error.locations; // => [{ line: 1, column: 8 }] + * ``` + */ +function syntaxError(source, position, description) { + return new _GraphQLError.GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position], + }); +} diff --git a/node_modules/graphql/error/syntaxError.mjs b/node_modules/graphql/error/syntaxError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..517cb3f5399a738b3a9b936a4cd32a899b001d02 --- /dev/null +++ b/node_modules/graphql/error/syntaxError.mjs @@ -0,0 +1,27 @@ +/** @category Errors */ +import { GraphQLError } from './GraphQLError.mjs'; +/** + * Produces a GraphQLError representing a syntax error, containing useful + * descriptive information about the syntax error's position in the source. + * @param source - The GraphQL source containing the syntax error. + * @param position - Character offset where the syntax error was encountered. + * @param description - Human-readable description of the syntax error. + * @returns A GraphQLError located at the syntax error position. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * import { syntaxError } from 'graphql/error'; + * + * const error = syntaxError(new Source('query {'), 7, 'Expected Name'); + * + * error.message; // => 'Syntax Error: Expected Name' + * error.locations; // => [{ line: 1, column: 8 }] + * ``` + */ + +export function syntaxError(source, position, description) { + return new GraphQLError(`Syntax Error: ${description}`, { + source, + positions: [position], + }); +} diff --git a/node_modules/graphql/execution/collectFields.d.ts b/node_modules/graphql/execution/collectFields.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..67532c5fc28a1393ebe8da7f3ade72ddc1b07137 --- /dev/null +++ b/node_modules/graphql/execution/collectFields.d.ts @@ -0,0 +1,45 @@ +import type { ObjMap } from '../jsutils/ObjMap'; +import type { + FieldNode, + FragmentDefinitionNode, + SelectionSetNode, +} from '../language/ast'; +import type { GraphQLObjectType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ +export declare function collectFields( + schema: GraphQLSchema, + fragments: ObjMap, + variableValues: { + [variable: string]: unknown; + }, + runtimeType: GraphQLObjectType, + selectionSet: SelectionSetNode, +): Map>; +/** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ +export declare function collectSubfields( + schema: GraphQLSchema, + fragments: ObjMap, + variableValues: { + [variable: string]: unknown; + }, + returnType: GraphQLObjectType, + fieldNodes: ReadonlyArray, +): Map>; diff --git a/node_modules/graphql/execution/collectFields.js b/node_modules/graphql/execution/collectFields.js new file mode 100644 index 0000000000000000000000000000000000000000..3a9fa53f7edde6b72465e9accab3eac05acb877a --- /dev/null +++ b/node_modules/graphql/execution/collectFields.js @@ -0,0 +1,235 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.collectFields = collectFields; +exports.collectSubfields = collectSubfields; + +var _kinds = require('../language/kinds.js'); + +var _definition = require('../type/definition.js'); + +var _directives = require('../type/directives.js'); + +var _typeFromAST = require('../utilities/typeFromAST.js'); + +var _values = require('./values.js'); + +/** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ +function collectFields( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, +) { + const fields = new Map(); + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + new Set(), + ); + return fields; +} +/** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ + +function collectSubfields( + schema, + fragments, + variableValues, + returnType, + fieldNodes, +) { + const subFieldNodes = new Map(); + const visitedFragmentNames = new Set(); + + for (const node of fieldNodes) { + if (node.selectionSet) { + collectFieldsImpl( + schema, + fragments, + variableValues, + returnType, + node.selectionSet, + subFieldNodes, + visitedFragmentNames, + ); + } + } + + return subFieldNodes; +} + +function collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + visitedFragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: { + if (!shouldIncludeNode(variableValues, selection)) { + continue; + } + + const name = getFieldEntryKey(selection); + const fieldList = fields.get(name); + + if (fieldList !== undefined) { + fieldList.push(selection); + } else { + fields.set(name, [selection]); + } + + break; + } + + case _kinds.Kind.INLINE_FRAGMENT: { + if ( + !shouldIncludeNode(variableValues, selection) || + !doesFragmentConditionMatch(schema, selection, runtimeType) + ) { + continue; + } + + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + + case _kinds.Kind.FRAGMENT_SPREAD: { + const fragName = selection.name.value; + + if ( + visitedFragmentNames.has(fragName) || + !shouldIncludeNode(variableValues, selection) + ) { + continue; + } + + visitedFragmentNames.add(fragName); + const fragment = fragments[fragName]; + + if ( + !fragment || + !doesFragmentConditionMatch(schema, fragment, runtimeType) + ) { + continue; + } + + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + } + } +} +/** + * Determines if a field should be included based on the `@include` and `@skip` + * directives, where `@skip` has higher precedence than `@include`. + * + * @internal + */ + +function shouldIncludeNode(variableValues, node) { + const skip = (0, _values.getDirectiveValues)( + _directives.GraphQLSkipDirective, + node, + variableValues, + ); + + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } + + const include = (0, _values.getDirectiveValues)( + _directives.GraphQLIncludeDirective, + node, + variableValues, + ); + + if ( + (include === null || include === void 0 ? void 0 : include.if) === false + ) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + * + * @internal + */ + +function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + const conditionalType = (0, _typeFromAST.typeFromAST)( + schema, + typeConditionNode, + ); + + if (conditionalType === type) { + return true; + } + + if ((0, _definition.isAbstractType)(conditionalType)) { + return schema.isSubType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + * + * @internal + */ + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} diff --git a/node_modules/graphql/execution/collectFields.mjs b/node_modules/graphql/execution/collectFields.mjs new file mode 100644 index 0000000000000000000000000000000000000000..02e24394db5975c778bf52423bd74a54c68f784d --- /dev/null +++ b/node_modules/graphql/execution/collectFields.mjs @@ -0,0 +1,219 @@ +import { Kind } from '../language/kinds.mjs'; +import { isAbstractType } from '../type/definition.mjs'; +import { + GraphQLIncludeDirective, + GraphQLSkipDirective, +} from '../type/directives.mjs'; +import { typeFromAST } from '../utilities/typeFromAST.mjs'; +import { getDirectiveValues } from './values.mjs'; +/** + * Given a selectionSet, collects all of the fields and returns them. + * + * CollectFields requires the "runtime type" of an object. For a field that + * returns an Interface or Union type, the "runtime type" will be the actual + * object type returned by that field. + * + * @internal + */ + +export function collectFields( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, +) { + const fields = new Map(); + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + new Set(), + ); + return fields; +} +/** + * Given an array of field nodes, collects all of the subfields of the passed + * in fields, and returns them at the end. + * + * CollectSubFields requires the "return type" of an object. For a field that + * returns an Interface or Union type, the "return type" will be the actual + * object type returned by that field. + * + * @internal + */ + +export function collectSubfields( + schema, + fragments, + variableValues, + returnType, + fieldNodes, +) { + const subFieldNodes = new Map(); + const visitedFragmentNames = new Set(); + + for (const node of fieldNodes) { + if (node.selectionSet) { + collectFieldsImpl( + schema, + fragments, + variableValues, + returnType, + node.selectionSet, + subFieldNodes, + visitedFragmentNames, + ); + } + } + + return subFieldNodes; +} + +function collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selectionSet, + fields, + visitedFragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case Kind.FIELD: { + if (!shouldIncludeNode(variableValues, selection)) { + continue; + } + + const name = getFieldEntryKey(selection); + const fieldList = fields.get(name); + + if (fieldList !== undefined) { + fieldList.push(selection); + } else { + fields.set(name, [selection]); + } + + break; + } + + case Kind.INLINE_FRAGMENT: { + if ( + !shouldIncludeNode(variableValues, selection) || + !doesFragmentConditionMatch(schema, selection, runtimeType) + ) { + continue; + } + + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + selection.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + + case Kind.FRAGMENT_SPREAD: { + const fragName = selection.name.value; + + if ( + visitedFragmentNames.has(fragName) || + !shouldIncludeNode(variableValues, selection) + ) { + continue; + } + + visitedFragmentNames.add(fragName); + const fragment = fragments[fragName]; + + if ( + !fragment || + !doesFragmentConditionMatch(schema, fragment, runtimeType) + ) { + continue; + } + + collectFieldsImpl( + schema, + fragments, + variableValues, + runtimeType, + fragment.selectionSet, + fields, + visitedFragmentNames, + ); + break; + } + } + } +} +/** + * Determines if a field should be included based on the `@include` and `@skip` + * directives, where `@skip` has higher precedence than `@include`. + * + * @internal + */ + +function shouldIncludeNode(variableValues, node) { + const skip = getDirectiveValues(GraphQLSkipDirective, node, variableValues); + + if ((skip === null || skip === void 0 ? void 0 : skip.if) === true) { + return false; + } + + const include = getDirectiveValues( + GraphQLIncludeDirective, + node, + variableValues, + ); + + if ( + (include === null || include === void 0 ? void 0 : include.if) === false + ) { + return false; + } + + return true; +} +/** + * Determines if a fragment is applicable to the given type. + * + * @internal + */ + +function doesFragmentConditionMatch(schema, fragment, type) { + const typeConditionNode = fragment.typeCondition; + + if (!typeConditionNode) { + return true; + } + + const conditionalType = typeFromAST(schema, typeConditionNode); + + if (conditionalType === type) { + return true; + } + + if (isAbstractType(conditionalType)) { + return schema.isSubType(conditionalType, type); + } + + return false; +} +/** + * Implements the logic to compute the key of a given field's entry + * + * @internal + */ + +function getFieldEntryKey(node) { + return node.alias ? node.alias.value : node.name.value; +} diff --git a/node_modules/graphql/execution/execute.d.ts b/node_modules/graphql/execution/execute.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d48df064a34ec68c3298daf19fdaa119b60c29f1 --- /dev/null +++ b/node_modules/graphql/execution/execute.d.ts @@ -0,0 +1,402 @@ +/** @category Execution */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { Path } from '../jsutils/Path'; +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import type { GraphQLFormattedError } from '../error/GraphQLError'; +import { GraphQLError } from '../error/GraphQLError'; +import type { + DocumentNode, + FieldNode, + FragmentDefinitionNode, + OperationDefinitionNode, +} from '../language/ast'; +import type { + GraphQLField, + GraphQLFieldResolver, + GraphQLObjectType, + GraphQLResolveInfo, + GraphQLTypeResolver, +} from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + * + * @internal + */ +export interface ExecutionContext { + schema: GraphQLSchema; + fragments: ObjMap; + rootValue: unknown; + contextValue: unknown; + operation: OperationDefinitionNode; + variableValues: { + [variable: string]: unknown; + }; + fieldResolver: GraphQLFieldResolver; + typeResolver: GraphQLTypeResolver; + subscribeFieldResolver: GraphQLFieldResolver; + collectedErrors: CollectedErrors; +} +declare class CollectedErrors { + private _errorPositions; + private _errors; + constructor(); + get errors(): ReadonlyArray; + add(error: GraphQLError, path: Path | undefined): void; + private _hasNulledPosition; +} +/** + * Represents the response produced by executing a GraphQL operation. + * @typeParam TData - Shape of the execution data payload. + * @typeParam TExtensions - Shape of the extensions payload. + */ +export interface ExecutionResult< + TData = ObjMap, + TExtensions = ObjMap, +> { + /** Errors raised while parsing, validating, or executing the operation. */ + errors?: ReadonlyArray; + /** Data returned by execution, or null when execution could not produce data. */ + data?: TData | null; + /** Extension fields to include in the formatted result. */ + extensions?: TExtensions; +} +/** + * A JSON-serializable GraphQL execution result. + * @typeParam TData - Shape of the formatted data payload. + * @typeParam TExtensions - Shape of the formatted extensions payload. + */ +export interface FormattedExecutionResult< + TData = ObjMap, + TExtensions = ObjMap, +> { + /** Errors raised while parsing, validating, or executing the operation. */ + errors?: ReadonlyArray; + /** Data returned by execution, or null when execution could not produce data. */ + data?: TData | null; + /** Extension fields to include in the formatted result. */ + extensions?: TExtensions; +} +/** Arguments accepted by execute and executeSync. */ +export interface ExecutionArgs { + /** The schema used for validation or execution. */ + schema: GraphQLSchema; + /** The parsed GraphQL document to execute. */ + document: DocumentNode; + /** Initial root value passed to the operation. */ + rootValue?: unknown; + /** Application context value passed to every resolver. */ + contextValue?: unknown; + /** Runtime variable values keyed by variable name. */ + variableValues?: Maybe<{ + readonly [variable: string]: unknown; + }>; + /** Name of the operation to execute when the document contains multiple operations. */ + operationName?: Maybe; + /** Resolver used when a field does not define its own resolver. */ + fieldResolver?: Maybe>; + /** Resolver used when an abstract type does not define its own resolver. */ + typeResolver?: Maybe>; + /** Resolver used for the root subscription field. */ + subscribeFieldResolver?: Maybe>; + /** Additional execution options. */ + options?: { + /** Set the maximum number of errors allowed for coercing (defaults to 50). */ + maxCoercionErrors?: number; + }; +} +/** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Field errors are collected into the response instead of rejecting the + * returned promise. Only the field that produced the error and its descendants + * are omitted; sibling fields continue to execute. Errors from fields of + * non-null type may propagate to the nearest nullable parent, which can be the + * entire response data. + * @param args - The arguments used to perform the operation. + * @returns A completed execution result, or a promise resolving to one when execution is asynchronous. + * @example + * ```ts + * // Execute an asynchronous operation with variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query ($name: String!) { greeting(name: $name) }'), + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query Viewer { viewer { __typename name } }'), + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * operationName: 'Viewer', + * fieldResolver: (source, _args, contextValue, info) => { + * contextValue.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @example + * ```ts + * // This variant shows how resolver errors become field errors in the result. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * broken: String + * } + * `); + * const document = parse('{ broken }'); + * + * const result = await execute({ + * schema, + * document, + * rootValue: { + * broken: () => { + * throw new Error('Resolver failed.'); + * }, + * }, + * }); + * + * result.data.broken; // => null + * result.errors[0].message; // => 'Resolver failed.' + * ``` + * @example + * ```ts + * // This variant limits how many variable coercion errors are reported. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * + * const result = await execute({ + * schema, + * document, + * variableValues: { + * first: { stars: 'bad' }, + * second: { stars: 'also bad' }, + * }, + * options: { maxCoercionErrors: 1 }, + * }); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +export declare function execute( + args: ExecutionArgs, +): PromiseOrValue; +/** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + * @param args - The arguments used to perform the operation. + * @returns Completed execution output for a synchronous operation. + * @example + * ```ts + * // Execute an operation synchronously when all resolvers are synchronous. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * + * const result = executeSync({ + * schema, + * document, + * rootValue: { + * greeting: 'Hello', + * }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant shows executeSync throwing when a resolver returns a promise. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * executeSync({ + * schema, + * document: parse('{ greeting }'), + * rootValue: { + * greeting: async () => 'Hello', + * }, + * }); // throws an error + * ``` + */ +export declare function executeSync(args: ExecutionArgs): ExecutionResult; +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. This deprecated internal helper will be + * removed in v17; call `assertValidSchema()` and rely on TypeScript checks + * instead. + * + * @deprecated will be removed in v17 in favor of assertValidSchema() and TS checks + * @internal + */ +export declare function assertValidExecutionArguments( + schema: GraphQLSchema, + document: DocumentNode, + rawVariableValues: Maybe<{ + readonly [variable: string]: unknown; + }>, +): void; +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ +export declare function buildExecutionContext( + args: ExecutionArgs, +): ReadonlyArray | ExecutionContext; +/** @internal */ +export declare function buildResolveInfo( + exeContext: ExecutionContext, + fieldDef: GraphQLField, + fieldNodes: ReadonlyArray, + parentType: GraphQLObjectType, + path: Path, +): GraphQLResolveInfo; +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ +export declare const defaultTypeResolver: GraphQLTypeResolver; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ +export declare const defaultFieldResolver: GraphQLFieldResolver< + unknown, + unknown +>; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ +export declare function getFieldDef( + schema: GraphQLSchema, + parentType: GraphQLObjectType, + fieldNode: FieldNode, +): Maybe>; +export {}; diff --git a/node_modules/graphql/execution/execute.js b/node_modules/graphql/execution/execute.js new file mode 100644 index 0000000000000000000000000000000000000000..80535c2c0f91e82227f5ac37b2d2bcbdc96e0409 --- /dev/null +++ b/node_modules/graphql/execution/execute.js @@ -0,0 +1,1295 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.assertValidExecutionArguments = assertValidExecutionArguments; +exports.buildExecutionContext = buildExecutionContext; +exports.buildResolveInfo = buildResolveInfo; +exports.defaultTypeResolver = exports.defaultFieldResolver = void 0; +exports.execute = execute; +exports.executeSync = executeSync; +exports.getFieldDef = getFieldDef; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _isIterableObject = require('../jsutils/isIterableObject.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _isPromise = require('../jsutils/isPromise.js'); + +var _memoize = require('../jsutils/memoize3.js'); + +var _Path = require('../jsutils/Path.js'); + +var _promiseForObject = require('../jsutils/promiseForObject.js'); + +var _promiseReduce = require('../jsutils/promiseReduce.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _locatedError = require('../error/locatedError.js'); + +var _ast = require('../language/ast.js'); + +var _kinds = require('../language/kinds.js'); + +var _definition = require('../type/definition.js'); + +var _introspection = require('../type/introspection.js'); + +var _validate = require('../type/validate.js'); + +var _collectFields = require('./collectFields.js'); + +var _values = require('./values.js'); + +/** @category Execution */ + +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + * + * @internal + */ +const collectSubfields = (0, _memoize.memoize3)( + (exeContext, returnType, fieldNodes) => + (0, _collectFields.collectSubfields)( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + returnType, + fieldNodes, + ), +); +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + * + * @internal + */ + +class CollectedErrors { + constructor() { + this._errorPositions = new Set(); + this._errors = []; + } + + get errors() { + return this._errors; + } + + add(error, path) { + // Do not modify errors list if the execution position for this error or + // any of its ancestors has already been nulled via error propagation. + // This check should be unnecessary for implementations able to implement + // actual cancellation. + if (this._hasNulledPosition(path)) { + return; + } + + this._errorPositions.add(path); + + this._errors.push(error); + } + + _hasNulledPosition(startPath) { + let path = startPath; + + while (path !== undefined) { + if (this._errorPositions.has(path)) { + return true; + } + + path = path.prev; + } + + return this._errorPositions.has(undefined); + } +} +/** + * Represents the response produced by executing a GraphQL operation. + * @typeParam TData - Shape of the execution data payload. + * @typeParam TExtensions - Shape of the extensions payload. + */ + +/** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Field errors are collected into the response instead of rejecting the + * returned promise. Only the field that produced the error and its descendants + * are omitted; sibling fields continue to execute. Errors from fields of + * non-null type may propagate to the nearest nullable parent, which can be the + * entire response data. + * @param args - The arguments used to perform the operation. + * @returns A completed execution result, or a promise resolving to one when execution is asynchronous. + * @example + * ```ts + * // Execute an asynchronous operation with variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query ($name: String!) { greeting(name: $name) }'), + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query Viewer { viewer { __typename name } }'), + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * operationName: 'Viewer', + * fieldResolver: (source, _args, contextValue, info) => { + * contextValue.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @example + * ```ts + * // This variant shows how resolver errors become field errors in the result. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * broken: String + * } + * `); + * const document = parse('{ broken }'); + * + * const result = await execute({ + * schema, + * document, + * rootValue: { + * broken: () => { + * throw new Error('Resolver failed.'); + * }, + * }, + * }); + * + * result.data.broken; // => null + * result.errors[0].message; // => 'Resolver failed.' + * ``` + * @example + * ```ts + * // This variant limits how many variable coercion errors are reported. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * + * const result = await execute({ + * schema, + * document, + * variableValues: { + * first: { stars: 'bad' }, + * second: { stars: 'also bad' }, + * }, + * options: { maxCoercionErrors: 1 }, + * }); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +function execute(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } + + try { + const { operation } = exeContext; + const result = executeOperation(exeContext, operation, rootValue); + + if ((0, _isPromise.isPromise)(result)) { + return result.then( + (data) => buildResponse(data, exeContext.collectedErrors.errors), + (error) => { + exeContext.collectedErrors.add(error, undefined); + return buildResponse(null, exeContext.collectedErrors.errors); + }, + ); + } + + return buildResponse(result, exeContext.collectedErrors.errors); + } catch (error) { + exeContext.collectedErrors.add(error, undefined); + return buildResponse(null, exeContext.collectedErrors.errors); + } +} +/** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + * @param args - The arguments used to perform the operation. + * @returns Completed execution output for a synchronous operation. + * @example + * ```ts + * // Execute an operation synchronously when all resolvers are synchronous. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * + * const result = executeSync({ + * schema, + * document, + * rootValue: { + * greeting: 'Hello', + * }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant shows executeSync throwing when a resolver returns a promise. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * executeSync({ + * schema, + * document: parse('{ greeting }'), + * rootValue: { + * greeting: async () => 'Hello', + * }, + * }); // throws an error + * ``` + */ + +function executeSync(args) { + const result = execute(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} +/** + * Given a completed execution context and data, build the `{ errors, data }` + * response defined by the "Response" section of the GraphQL specification. + * + * @internal + */ + +function buildResponse(data, errors) { + return errors.length === 0 + ? { + data, + } + : { + errors, + data, + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. This deprecated internal helper will be + * removed in v17; call `assertValidSchema()` and rely on TypeScript checks + * instead. + * + * @deprecated will be removed in v17 in favor of assertValidSchema() and TS checks + * @internal + */ + +function assertValidExecutionArguments(schema, document, rawVariableValues) { + document || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || + (0, _isObjectLike.isObjectLike)(rawVariableValues) || + (0, _devAssert.devAssert)( + false, + '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.', + ); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + +function buildExecutionContext(args) { + var _definition$name, _operation$variableDe, _options$maxCoercionE; + + const { + schema, + document, + rootValue, + contextValue, + variableValues: rawVariableValues, + operationName, + fieldResolver, + typeResolver, + subscribeFieldResolver, + options, + } = args; + let operation; + const fragments = Object.create(null); + + for (const definition of document.definitions) { + switch (definition.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [ + new _GraphQLError.GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ]; + } + + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + operation = definition; + } + + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + + default: // ignore non-executable definitions + } + } + + if (!operation) { + if (operationName != null) { + return [ + new _GraphQLError.GraphQLError( + `Unknown operation named "${operationName}".`, + ), + ]; + } + + return [new _GraphQLError.GraphQLError('Must provide an operation.')]; + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const variableDefinitions = + (_operation$variableDe = operation.variableDefinitions) !== null && + _operation$variableDe !== void 0 + ? _operation$variableDe + : []; + const coercedVariableValues = (0, _values.getVariableValues)( + schema, + variableDefinitions, + rawVariableValues !== null && rawVariableValues !== void 0 + ? rawVariableValues + : {}, + { + maxErrors: + (_options$maxCoercionE = + options === null || options === void 0 + ? void 0 + : options.maxCoercionErrors) !== null && + _options$maxCoercionE !== void 0 + ? _options$maxCoercionE + : 50, + }, + ); + + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: + fieldResolver !== null && fieldResolver !== void 0 + ? fieldResolver + : defaultFieldResolver, + typeResolver: + typeResolver !== null && typeResolver !== void 0 + ? typeResolver + : defaultTypeResolver, + subscribeFieldResolver: + subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 + ? subscribeFieldResolver + : defaultFieldResolver, + collectedErrors: new CollectedErrors(), + }; +} +/** + * Implements the "Executing operations" section of the spec. + * + * @internal + */ + +function executeOperation(exeContext, operation, rootValue) { + const rootType = exeContext.schema.getRootType(operation.operation); + + if (rootType == null) { + throw new _GraphQLError.GraphQLError( + `Schema is not configured to execute ${operation.operation} operation.`, + { + nodes: operation, + }, + ); + } + + const rootFields = (0, _collectFields.collectFields)( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + rootType, + operation.selectionSet, + ); + const path = undefined; + + switch (operation.operation) { + case _ast.OperationTypeNode.QUERY: + return executeFields(exeContext, rootType, rootValue, path, rootFields); + + case _ast.OperationTypeNode.MUTATION: + return executeFieldsSerially( + exeContext, + rootType, + rootValue, + path, + rootFields, + ); + + case _ast.OperationTypeNode.SUBSCRIPTION: + // TODO: deprecate `subscribe` and move all logic here + // Temporary solution until we finish merging execute and subscribe together + return executeFields(exeContext, rootType, rootValue, path, rootFields); + } +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that must be executed serially. + * + * @internal + */ + +function executeFieldsSerially( + exeContext, + parentType, + sourceValue, + path, + fields, +) { + return (0, _promiseReduce.promiseReduce)( + fields.entries(), + (results, [responseName, fieldNodes]) => { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result === undefined) { + return results; + } + + if ((0, _isPromise.isPromise)(result)) { + return result.then((resolvedResult) => { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that may be executed in parallel. + * + * @internal + */ + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + const results = Object.create(null); + let containsPromise = false; + + try { + for (const [responseName, fieldNodes] of fields.entries()) { + const fieldPath = (0, _Path.addPath)(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result !== undefined) { + results[responseName] = result; + + if ((0, _isPromise.isPromise)(result)) { + containsPromise = true; + } + } + } + } catch (error) { + if (containsPromise) { + // Ensure that any promises returned by other fields are handled, as they may also reject. + return (0, _promiseForObject.promiseForObject)(results).finally(() => { + throw error; + }); + } + + throw error; + } // If there are no promises, we can just return the object + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + return (0, _promiseForObject.promiseForObject)(results); +} +/** + * Implements the "Executing fields" section of the spec + * In particular, this function figures out the value that the field returns by + * calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. + * + * @internal + */ + +function executeField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); + + if (!fieldDef) { + return; + } + + const returnType = fieldDef.type; + const resolveFn = + (_fieldDef$resolve = fieldDef.resolve) !== null && + _fieldDef$resolve !== void 0 + ? _fieldDef$resolve + : exeContext.fieldResolver; + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = (0, _values.getArgumentValues)( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; + const result = resolveFn(source, args, contextValue, info); + let completed; + + if ((0, _isPromise.isPromise)(result)) { + completed = result.then((resolved) => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + if ((0, _isPromise.isPromise)(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, (rawError) => { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(path), + ); + return handleFieldError(error, returnType, path, exeContext); + }); + } + + return completed; + } catch (rawError) { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(path), + ); + return handleFieldError(error, returnType, path, exeContext); + } +} +/** @internal */ + +function buildResolveInfo(exeContext, fieldDef, fieldNodes, parentType, path) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} + +function handleFieldError(error, returnType, path, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if ((0, _definition.isNonNullType)(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + exeContext.collectedErrors.add(error, path); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Value Completion" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by executing all sub-selections. + * + * @internal + */ + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + if ((0, _definition.isNonNullType)(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); + + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, + ); + } + + return completed; + } // If result value is null or undefined then return null. + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + if ((0, _definition.isListType)(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + if ((0, _definition.isLeafType)(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + if ((0, _definition.isAbstractType)(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is Object, execute and complete all sub-selections. + + if ((0, _definition.isObjectType)(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + /* c8 ignore next 6 */ + // Not reachable, all possible output types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Cannot complete value of unexpected output type: ' + + (0, _inspect.inspect)(returnType), + ); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + * + * @internal + */ + +function completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + if (!(0, _isIterableObject.isIterableObject)(result)) { + throw new _GraphQLError.GraphQLError( + `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`, + ); + } // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = Array.from(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = (0, _Path.addPath)(path, index, undefined); + + try { + let completedItem; + + if ((0, _isPromise.isPromise)(item)) { + completedItem = item.then((resolved) => + completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + resolved, + ), + ); + } else { + completedItem = completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + item, + ); + } + + if ((0, _isPromise.isPromise)(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, (rawError) => { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(itemPath), + ); + return handleFieldError(error, itemType, itemPath, exeContext); + }); + } + + return completedItem; + } catch (rawError) { + const error = (0, _locatedError.locatedError)( + rawError, + fieldNodes, + (0, _Path.pathToArray)(itemPath), + ); + return handleFieldError(error, itemType, itemPath, exeContext); + } + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + * + * @internal + */ + +function completeLeafValue(returnType, result) { + const serializedResult = returnType.serialize(result); + + if (serializedResult == null) { + throw new Error( + `Expected \`${(0, _inspect.inspect)(returnType)}.serialize(${(0, + _inspect.inspect)(result)})\` to ` + + `return non-nullable value, returned: ${(0, _inspect.inspect)( + serializedResult, + )}`, + ); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + * + * @internal + */ + +function completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + var _returnType$resolveTy; + + const resolveTypeFn = + (_returnType$resolveTy = returnType.resolveType) !== null && + _returnType$resolveTy !== void 0 + ? _returnType$resolveTy + : exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + + if ((0, _isPromise.isPromise)(runtimeType)) { + return runtimeType.then((resolvedRuntimeType) => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } + + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); +} + +function ensureValidRuntimeType( + runtimeTypeName, + exeContext, + returnType, + fieldNodes, + info, + result, +) { + if (runtimeTypeName == null) { + throw new _GraphQLError.GraphQLError( + `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.`, + fieldNodes, + ); + } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` + // TODO: remove in 17.0.0 release + + if ((0, _definition.isObjectType)(runtimeTypeName)) { + throw new _GraphQLError.GraphQLError( + 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.', + ); + } + + if (typeof runtimeTypeName !== 'string') { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + + `value ${(0, _inspect.inspect)(result)}, received "${(0, + _inspect.inspect)(runtimeTypeName)}".`, + ); + } + + const runtimeType = exeContext.schema.getType(runtimeTypeName); + + if (runtimeType == null) { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, + { + nodes: fieldNodes, + }, + ); + } + + if (!(0, _definition.isObjectType)(runtimeType)) { + throw new _GraphQLError.GraphQLError( + `Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, + { + nodes: fieldNodes, + }, + ); + } + + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new _GraphQLError.GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, + { + nodes: fieldNodes, + }, + ); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + * + * @internal + */ + +function completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if ((0, _isPromise.isPromise)(isTypeOf)) { + return isTypeOf.then((resolvedIsTypeOf) => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return executeFields( + exeContext, + returnType, + result, + path, + subFieldNodes, + ); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new _GraphQLError.GraphQLError( + `Expected value of type "${returnType.name}" but got: ${(0, + _inspect.inspect)(result)}.`, + { + nodes: fieldNodes, + }, + ); +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + +const defaultTypeResolver = function (value, contextValue, info, abstractType) { + // First, look for `__typename`. + if ( + (0, _isObjectLike.isObjectLike)(value) && + typeof value.__typename === 'string' + ) { + return value.__typename; + } // Otherwise, test each possible type. + + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if ((0, _isPromise.isPromise)(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + if (promisedIsTypeOfResults.length) { + // Explicitly ignore any promise rejections + Promise.allSettled(promisedIsTypeOfResults) + /* c8 ignore next 3 */ + .catch(() => { + // Do nothing + }); + } + + return type.name; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + +exports.defaultTypeResolver = defaultTypeResolver; + +const defaultFieldResolver = function (source, args, contextValue, info) { + // ensure source is a value for which property access is acceptable. + if ((0, _isObjectLike.isObjectLike)(source) || typeof source === 'function') { + const property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ + +exports.defaultFieldResolver = defaultFieldResolver; + +function getFieldDef(schema, parentType, fieldNode) { + const fieldName = fieldNode.name.value; + + if ( + fieldName === _introspection.SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.SchemaMetaFieldDef; + } else if ( + fieldName === _introspection.TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.TypeMetaFieldDef; + } else if (fieldName === _introspection.TypeNameMetaFieldDef.name) { + return _introspection.TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} diff --git a/node_modules/graphql/execution/execute.mjs b/node_modules/graphql/execution/execute.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f386964e5551a07ccb84512e4a1a8d8368a94081 --- /dev/null +++ b/node_modules/graphql/execution/execute.mjs @@ -0,0 +1,1266 @@ +/** @category Execution */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { isIterableObject } from '../jsutils/isIterableObject.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { isPromise } from '../jsutils/isPromise.mjs'; +import { memoize3 } from '../jsutils/memoize3.mjs'; +import { addPath, pathToArray } from '../jsutils/Path.mjs'; +import { promiseForObject } from '../jsutils/promiseForObject.mjs'; +import { promiseReduce } from '../jsutils/promiseReduce.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { locatedError } from '../error/locatedError.mjs'; +import { OperationTypeNode } from '../language/ast.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { + isAbstractType, + isLeafType, + isListType, + isNonNullType, + isObjectType, +} from '../type/definition.mjs'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection.mjs'; +import { assertValidSchema } from '../type/validate.mjs'; +import { + collectFields, + collectSubfields as _collectSubfields, +} from './collectFields.mjs'; +import { getArgumentValues, getVariableValues } from './values.mjs'; +/** + * A memoized collection of relevant subfields with regard to the return + * type. Memoizing ensures the subfields are not repeatedly calculated, which + * saves overhead when resolving lists of values. + * + * @internal + */ + +const collectSubfields = memoize3((exeContext, returnType, fieldNodes) => + _collectSubfields( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + returnType, + fieldNodes, + ), +); +/** + * Terminology + * + * "Definitions" are the generic name for top-level statements in the document. + * Examples of this include: + * 1) Operations (such as a query) + * 2) Fragments + * + * "Operations" are a generic name for requests in the document. + * Examples of this include: + * 1) query, + * 2) mutation + * + * "Selections" are the definitions that can appear legally and at + * single level of the query. These include: + * 1) field references e.g `a` + * 2) fragment "spreads" e.g. `...c` + * 3) inline fragment "spreads" e.g. `...on Type { a }` + */ + +/** + * Data that must be available at all points during query execution. + * + * Namely, schema of the type system that is currently executing, + * and the fragments defined in the query document + * + * @internal + */ + +class CollectedErrors { + constructor() { + this._errorPositions = new Set(); + this._errors = []; + } + + get errors() { + return this._errors; + } + + add(error, path) { + // Do not modify errors list if the execution position for this error or + // any of its ancestors has already been nulled via error propagation. + // This check should be unnecessary for implementations able to implement + // actual cancellation. + if (this._hasNulledPosition(path)) { + return; + } + + this._errorPositions.add(path); + + this._errors.push(error); + } + + _hasNulledPosition(startPath) { + let path = startPath; + + while (path !== undefined) { + if (this._errorPositions.has(path)) { + return true; + } + + path = path.prev; + } + + return this._errorPositions.has(undefined); + } +} +/** + * Represents the response produced by executing a GraphQL operation. + * @typeParam TData - Shape of the execution data payload. + * @typeParam TExtensions - Shape of the extensions payload. + */ + +/** + * Implements the "Executing requests" section of the GraphQL specification. + * + * Returns either a synchronous ExecutionResult (if all encountered resolvers + * are synchronous), or a Promise of an ExecutionResult that will eventually be + * resolved and never rejected. + * + * If the arguments to this function do not result in a legal execution context, + * a GraphQLError will be thrown immediately explaining the invalid input. + * + * Field errors are collected into the response instead of rejecting the + * returned promise. Only the field that produced the error and its descendants + * are omitted; sibling fields continue to execute. Errors from fields of + * non-null type may propagate to the nearest nullable parent, which can be the + * entire response data. + * @param args - The arguments used to perform the operation. + * @returns A completed execution result, or a promise resolving to one when execution is asynchronous. + * @example + * ```ts + * // Execute an asynchronous operation with variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query ($name: String!) { greeting(name: $name) }'), + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await execute({ + * schema, + * document: parse('query Viewer { viewer { __typename name } }'), + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * operationName: 'Viewer', + * fieldResolver: (source, _args, contextValue, info) => { + * contextValue.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @example + * ```ts + * // This variant shows how resolver errors become field errors in the result. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * broken: String + * } + * `); + * const document = parse('{ broken }'); + * + * const result = await execute({ + * schema, + * document, + * rootValue: { + * broken: () => { + * throw new Error('Resolver failed.'); + * }, + * }, + * }); + * + * result.data.broken; // => null + * result.errors[0].message; // => 'Resolver failed.' + * ``` + * @example + * ```ts + * // This variant limits how many variable coercion errors are reported. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { execute } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * + * const result = await execute({ + * schema, + * document, + * variableValues: { + * first: { stars: 'bad' }, + * second: { stars: 'also bad' }, + * }, + * options: { maxCoercionErrors: 1 }, + * }); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +export function execute(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + devAssert( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { schema, document, variableValues, rootValue } = args; // If arguments are missing or incorrect, throw an error. + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } + + try { + const { operation } = exeContext; + const result = executeOperation(exeContext, operation, rootValue); + + if (isPromise(result)) { + return result.then( + (data) => buildResponse(data, exeContext.collectedErrors.errors), + (error) => { + exeContext.collectedErrors.add(error, undefined); + return buildResponse(null, exeContext.collectedErrors.errors); + }, + ); + } + + return buildResponse(result, exeContext.collectedErrors.errors); + } catch (error) { + exeContext.collectedErrors.add(error, undefined); + return buildResponse(null, exeContext.collectedErrors.errors); + } +} +/** + * Also implements the "Executing requests" section of the GraphQL specification. + * However, it guarantees to complete synchronously (or throw an error) assuming + * that all field resolvers are also synchronous. + * @param args - The arguments used to perform the operation. + * @returns Completed execution output for a synchronous operation. + * @example + * ```ts + * // Execute an operation synchronously when all resolvers are synchronous. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * + * const result = executeSync({ + * schema, + * document, + * rootValue: { + * greeting: 'Hello', + * }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant shows executeSync throwing when a resolver returns a promise. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { executeSync } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * executeSync({ + * schema, + * document: parse('{ greeting }'), + * rootValue: { + * greeting: async () => 'Hello', + * }, + * }); // throws an error + * ``` + */ + +export function executeSync(args) { + const result = execute(args); // Assert that the execution was synchronous. + + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} +/** + * Given a completed execution context and data, build the `{ errors, data }` + * response defined by the "Response" section of the GraphQL specification. + * + * @internal + */ + +function buildResponse(data, errors) { + return errors.length === 0 + ? { + data, + } + : { + errors, + data, + }; +} +/** + * Essential assertions before executing to provide developer feedback for + * improper use of the GraphQL library. This deprecated internal helper will be + * removed in v17; call `assertValidSchema()` and rely on TypeScript checks + * instead. + * + * @deprecated will be removed in v17 in favor of assertValidSchema() and TS checks + * @internal + */ + +export function assertValidExecutionArguments( + schema, + document, + rawVariableValues, +) { + document || devAssert(false, 'Must provide document.'); // If the schema used for execution is invalid, throw an error. + + assertValidSchema(schema); // Variables, if provided, must be an object. + + rawVariableValues == null || + isObjectLike(rawVariableValues) || + devAssert( + false, + '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.', + ); +} +/** + * Constructs a ExecutionContext object from the arguments passed to + * execute, which we will pass throughout the other execution methods. + * + * Throws a GraphQLError if a valid execution context cannot be created. + * + * @internal + */ + +export function buildExecutionContext(args) { + var _definition$name, _operation$variableDe, _options$maxCoercionE; + + const { + schema, + document, + rootValue, + contextValue, + variableValues: rawVariableValues, + operationName, + fieldResolver, + typeResolver, + subscribeFieldResolver, + options, + } = args; + let operation; + const fragments = Object.create(null); + + for (const definition of document.definitions) { + switch (definition.kind) { + case Kind.OPERATION_DEFINITION: + if (operationName == null) { + if (operation !== undefined) { + return [ + new GraphQLError( + 'Must provide operation name if query contains multiple operations.', + ), + ]; + } + + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + operation = definition; + } + + break; + + case Kind.FRAGMENT_DEFINITION: + fragments[definition.name.value] = definition; + break; + + default: // ignore non-executable definitions + } + } + + if (!operation) { + if (operationName != null) { + return [new GraphQLError(`Unknown operation named "${operationName}".`)]; + } + + return [new GraphQLError('Must provide an operation.')]; + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const variableDefinitions = + (_operation$variableDe = operation.variableDefinitions) !== null && + _operation$variableDe !== void 0 + ? _operation$variableDe + : []; + const coercedVariableValues = getVariableValues( + schema, + variableDefinitions, + rawVariableValues !== null && rawVariableValues !== void 0 + ? rawVariableValues + : {}, + { + maxErrors: + (_options$maxCoercionE = + options === null || options === void 0 + ? void 0 + : options.maxCoercionErrors) !== null && + _options$maxCoercionE !== void 0 + ? _options$maxCoercionE + : 50, + }, + ); + + if (coercedVariableValues.errors) { + return coercedVariableValues.errors; + } + + return { + schema, + fragments, + rootValue, + contextValue, + operation, + variableValues: coercedVariableValues.coerced, + fieldResolver: + fieldResolver !== null && fieldResolver !== void 0 + ? fieldResolver + : defaultFieldResolver, + typeResolver: + typeResolver !== null && typeResolver !== void 0 + ? typeResolver + : defaultTypeResolver, + subscribeFieldResolver: + subscribeFieldResolver !== null && subscribeFieldResolver !== void 0 + ? subscribeFieldResolver + : defaultFieldResolver, + collectedErrors: new CollectedErrors(), + }; +} +/** + * Implements the "Executing operations" section of the spec. + * + * @internal + */ + +function executeOperation(exeContext, operation, rootValue) { + const rootType = exeContext.schema.getRootType(operation.operation); + + if (rootType == null) { + throw new GraphQLError( + `Schema is not configured to execute ${operation.operation} operation.`, + { + nodes: operation, + }, + ); + } + + const rootFields = collectFields( + exeContext.schema, + exeContext.fragments, + exeContext.variableValues, + rootType, + operation.selectionSet, + ); + const path = undefined; + + switch (operation.operation) { + case OperationTypeNode.QUERY: + return executeFields(exeContext, rootType, rootValue, path, rootFields); + + case OperationTypeNode.MUTATION: + return executeFieldsSerially( + exeContext, + rootType, + rootValue, + path, + rootFields, + ); + + case OperationTypeNode.SUBSCRIPTION: + // TODO: deprecate `subscribe` and move all logic here + // Temporary solution until we finish merging execute and subscribe together + return executeFields(exeContext, rootType, rootValue, path, rootFields); + } +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that must be executed serially. + * + * @internal + */ + +function executeFieldsSerially( + exeContext, + parentType, + sourceValue, + path, + fields, +) { + return promiseReduce( + fields.entries(), + (results, [responseName, fieldNodes]) => { + const fieldPath = addPath(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result === undefined) { + return results; + } + + if (isPromise(result)) { + return result.then((resolvedResult) => { + results[responseName] = resolvedResult; + return results; + }); + } + + results[responseName] = result; + return results; + }, + Object.create(null), + ); +} +/** + * Implements the "Executing selection sets" section of the spec + * for fields that may be executed in parallel. + * + * @internal + */ + +function executeFields(exeContext, parentType, sourceValue, path, fields) { + const results = Object.create(null); + let containsPromise = false; + + try { + for (const [responseName, fieldNodes] of fields.entries()) { + const fieldPath = addPath(path, responseName, parentType.name); + const result = executeField( + exeContext, + parentType, + sourceValue, + fieldNodes, + fieldPath, + ); + + if (result !== undefined) { + results[responseName] = result; + + if (isPromise(result)) { + containsPromise = true; + } + } + } + } catch (error) { + if (containsPromise) { + // Ensure that any promises returned by other fields are handled, as they may also reject. + return promiseForObject(results).finally(() => { + throw error; + }); + } + + throw error; + } // If there are no promises, we can just return the object + + if (!containsPromise) { + return results; + } // Otherwise, results is a map from field name to the result of resolving that + // field, which is possibly a promise. Return a promise that will return this + // same map, but with any promises replaced with the values they resolved to. + + return promiseForObject(results); +} +/** + * Implements the "Executing fields" section of the spec + * In particular, this function figures out the value that the field returns by + * calling its resolve function, then calls completeValue to complete promises, + * serialize scalars, or execute the sub-selection-set for objects. + * + * @internal + */ + +function executeField(exeContext, parentType, source, fieldNodes, path) { + var _fieldDef$resolve; + + const fieldDef = getFieldDef(exeContext.schema, parentType, fieldNodes[0]); + + if (!fieldDef) { + return; + } + + const returnType = fieldDef.type; + const resolveFn = + (_fieldDef$resolve = fieldDef.resolve) !== null && + _fieldDef$resolve !== void 0 + ? _fieldDef$resolve + : exeContext.fieldResolver; + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, + ); // Get the resolve function, regardless of if its result is normal or abrupt (error). + + try { + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + // TODO: find a way to memoize, in case this field is within a List type. + const args = getArgumentValues( + fieldDef, + fieldNodes[0], + exeContext.variableValues, + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; + const result = resolveFn(source, args, contextValue, info); + let completed; + + if (isPromise(result)) { + completed = result.then((resolved) => + completeValue(exeContext, returnType, fieldNodes, info, path, resolved), + ); + } else { + completed = completeValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + + if (isPromise(completed)) { + // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + return completed.then(undefined, (rawError) => { + const error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, path, exeContext); + }); + } + + return completed; + } catch (rawError) { + const error = locatedError(rawError, fieldNodes, pathToArray(path)); + return handleFieldError(error, returnType, path, exeContext); + } +} +/** @internal */ + +export function buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + parentType, + path, +) { + // The resolve function's optional fourth argument is a collection of + // information about the current execution state. + return { + fieldName: fieldDef.name, + fieldNodes, + returnType: fieldDef.type, + parentType, + path, + schema: exeContext.schema, + fragments: exeContext.fragments, + rootValue: exeContext.rootValue, + operation: exeContext.operation, + variableValues: exeContext.variableValues, + }; +} + +function handleFieldError(error, returnType, path, exeContext) { + // If the field type is non-nullable, then it is resolved without any + // protection from errors, however it still properly locates the error. + if (isNonNullType(returnType)) { + throw error; + } // Otherwise, error protection is applied, logging the error and resolving + // a null value for this field if one is encountered. + + exeContext.collectedErrors.add(error, path); + return null; +} +/** + * Implements the instructions for completeValue as defined in the + * "Value Completion" section of the spec. + * + * If the field type is Non-Null, then this recursively completes the value + * for the inner type. It throws a field error if that completion returns null, + * as per the "Nullability" section of the spec. + * + * If the field type is a List, then this recursively completes the value + * for the inner type on each item in the list. + * + * If the field type is a Scalar or Enum, ensures the completed value is a legal + * value of the type by calling the `serialize` method of GraphQL type + * definition. + * + * If the field is an abstract type, determine the runtime type of the value + * and then complete based on that type + * + * Otherwise, the field type expects a sub-selection set, and will complete the + * value by executing all sub-selections. + * + * @internal + */ + +function completeValue(exeContext, returnType, fieldNodes, info, path, result) { + // If result is an Error, throw a located error. + if (result instanceof Error) { + throw result; + } // If field type is NonNull, complete for inner type, and throw field error + // if result is null. + + if (isNonNullType(returnType)) { + const completed = completeValue( + exeContext, + returnType.ofType, + fieldNodes, + info, + path, + result, + ); + + if (completed === null) { + throw new Error( + `Cannot return null for non-nullable field ${info.parentType.name}.${info.fieldName}.`, + ); + } + + return completed; + } // If result value is null or undefined then return null. + + if (result == null) { + return null; + } // If field type is List, complete each item in the list with the inner type + + if (isListType(returnType)) { + return completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is a leaf type, Scalar or Enum, serialize to a valid value, + // returning null if serialization is not possible. + + if (isLeafType(returnType)) { + return completeLeafValue(returnType, result); + } // If field type is an abstract type, Interface or Union, determine the + // runtime Object type and complete for that type. + + if (isAbstractType(returnType)) { + return completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } // If field type is Object, execute and complete all sub-selections. + + if (isObjectType(returnType)) { + return completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, + ); + } + /* c8 ignore next 6 */ + // Not reachable, all possible output types have been considered. + + false || + invariant( + false, + 'Cannot complete value of unexpected output type: ' + inspect(returnType), + ); +} +/** + * Complete a list value by completing each item in the list with the + * inner type + * + * @internal + */ + +function completeListValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + if (!isIterableObject(result)) { + throw new GraphQLError( + `Expected Iterable, but did not find one for field "${info.parentType.name}.${info.fieldName}".`, + ); + } // This is specified as a simple map, however we're optimizing the path + // where the list contains no Promises by avoiding creating another Promise. + + const itemType = returnType.ofType; + let containsPromise = false; + const completedResults = Array.from(result, (item, index) => { + // No need to modify the info object containing the path, + // since from here on it is not ever accessed by resolver functions. + const itemPath = addPath(path, index, undefined); + + try { + let completedItem; + + if (isPromise(item)) { + completedItem = item.then((resolved) => + completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + resolved, + ), + ); + } else { + completedItem = completeValue( + exeContext, + itemType, + fieldNodes, + info, + itemPath, + item, + ); + } + + if (isPromise(completedItem)) { + containsPromise = true; // Note: we don't rely on a `catch` method, but we do expect "thenable" + // to take a second callback for the error case. + + return completedItem.then(undefined, (rawError) => { + const error = locatedError( + rawError, + fieldNodes, + pathToArray(itemPath), + ); + return handleFieldError(error, itemType, itemPath, exeContext); + }); + } + + return completedItem; + } catch (rawError) { + const error = locatedError(rawError, fieldNodes, pathToArray(itemPath)); + return handleFieldError(error, itemType, itemPath, exeContext); + } + }); + return containsPromise ? Promise.all(completedResults) : completedResults; +} +/** + * Complete a Scalar or Enum by serializing to a valid value, returning + * null if serialization is not possible. + * + * @internal + */ + +function completeLeafValue(returnType, result) { + const serializedResult = returnType.serialize(result); + + if (serializedResult == null) { + throw new Error( + `Expected \`${inspect(returnType)}.serialize(${inspect(result)})\` to ` + + `return non-nullable value, returned: ${inspect(serializedResult)}`, + ); + } + + return serializedResult; +} +/** + * Complete a value of an abstract type by determining the runtime object type + * of that value, then complete the value for that type. + * + * @internal + */ + +function completeAbstractValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + var _returnType$resolveTy; + + const resolveTypeFn = + (_returnType$resolveTy = returnType.resolveType) !== null && + _returnType$resolveTy !== void 0 + ? _returnType$resolveTy + : exeContext.typeResolver; + const contextValue = exeContext.contextValue; + const runtimeType = resolveTypeFn(result, contextValue, info, returnType); + + if (isPromise(runtimeType)) { + return runtimeType.then((resolvedRuntimeType) => + completeObjectValue( + exeContext, + ensureValidRuntimeType( + resolvedRuntimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ), + ); + } + + return completeObjectValue( + exeContext, + ensureValidRuntimeType( + runtimeType, + exeContext, + returnType, + fieldNodes, + info, + result, + ), + fieldNodes, + info, + path, + result, + ); +} + +function ensureValidRuntimeType( + runtimeTypeName, + exeContext, + returnType, + fieldNodes, + info, + result, +) { + if (runtimeTypeName == null) { + throw new GraphQLError( + `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.`, + fieldNodes, + ); + } // releases before 16.0.0 supported returning `GraphQLObjectType` from `resolveType` + // TODO: remove in 17.0.0 release + + if (isObjectType(runtimeTypeName)) { + throw new GraphQLError( + 'Support for returning GraphQLObjectType from resolveType was removed in graphql-js@16.0.0 please return type name instead.', + ); + } + + if (typeof runtimeTypeName !== 'string') { + throw new GraphQLError( + `Abstract type "${returnType.name}" must resolve to an Object type at runtime for field "${info.parentType.name}.${info.fieldName}" with ` + + `value ${inspect(result)}, received "${inspect(runtimeTypeName)}".`, + ); + } + + const runtimeType = exeContext.schema.getType(runtimeTypeName); + + if (runtimeType == null) { + throw new GraphQLError( + `Abstract type "${returnType.name}" was resolved to a type "${runtimeTypeName}" that does not exist inside the schema.`, + { + nodes: fieldNodes, + }, + ); + } + + if (!isObjectType(runtimeType)) { + throw new GraphQLError( + `Abstract type "${returnType.name}" was resolved to a non-object type "${runtimeTypeName}".`, + { + nodes: fieldNodes, + }, + ); + } + + if (!exeContext.schema.isSubType(returnType, runtimeType)) { + throw new GraphQLError( + `Runtime Object type "${runtimeType.name}" is not a possible type for "${returnType.name}".`, + { + nodes: fieldNodes, + }, + ); + } + + return runtimeType; +} +/** + * Complete an Object value by executing all sub-selections. + * + * @internal + */ + +function completeObjectValue( + exeContext, + returnType, + fieldNodes, + info, + path, + result, +) { + // Collect sub-fields to execute to complete this value. + const subFieldNodes = collectSubfields(exeContext, returnType, fieldNodes); // If there is an isTypeOf predicate function, call it with the + // current result. If isTypeOf returns false, then raise an error rather + // than continuing execution. + + if (returnType.isTypeOf) { + const isTypeOf = returnType.isTypeOf(result, exeContext.contextValue, info); + + if (isPromise(isTypeOf)) { + return isTypeOf.then((resolvedIsTypeOf) => { + if (!resolvedIsTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + + return executeFields( + exeContext, + returnType, + result, + path, + subFieldNodes, + ); + }); + } + + if (!isTypeOf) { + throw invalidReturnTypeError(returnType, result, fieldNodes); + } + } + + return executeFields(exeContext, returnType, result, path, subFieldNodes); +} + +function invalidReturnTypeError(returnType, result, fieldNodes) { + return new GraphQLError( + `Expected value of type "${returnType.name}" but got: ${inspect(result)}.`, + { + nodes: fieldNodes, + }, + ); +} +/** + * If a resolveType function is not given, then a default resolve behavior is + * used which attempts two strategies: + * + * First, See if the provided value has a `__typename` field defined, if so, use + * that value as name of the resolved type. + * + * Otherwise, test each possible type for the abstract type by calling + * isTypeOf for the object being coerced, returning the first type that matches. + */ + +export const defaultTypeResolver = function ( + value, + contextValue, + info, + abstractType, +) { + // First, look for `__typename`. + if (isObjectLike(value) && typeof value.__typename === 'string') { + return value.__typename; + } // Otherwise, test each possible type. + + const possibleTypes = info.schema.getPossibleTypes(abstractType); + const promisedIsTypeOfResults = []; + + for (let i = 0; i < possibleTypes.length; i++) { + const type = possibleTypes[i]; + + if (type.isTypeOf) { + const isTypeOfResult = type.isTypeOf(value, contextValue, info); + + if (isPromise(isTypeOfResult)) { + promisedIsTypeOfResults[i] = isTypeOfResult; + } else if (isTypeOfResult) { + if (promisedIsTypeOfResults.length) { + // Explicitly ignore any promise rejections + Promise.allSettled(promisedIsTypeOfResults) + /* c8 ignore next 3 */ + .catch(() => { + // Do nothing + }); + } + + return type.name; + } + } + } + + if (promisedIsTypeOfResults.length) { + return Promise.all(promisedIsTypeOfResults).then((isTypeOfResults) => { + for (let i = 0; i < isTypeOfResults.length; i++) { + if (isTypeOfResults[i]) { + return possibleTypes[i].name; + } + } + }); + } +}; +/** + * If a resolve function is not given, then a default resolve behavior is used + * which takes the property of the source object of the same name as the field + * and returns it as the result, or if it's a function, returns the result + * of calling that function while passing along args and context value. + */ + +export const defaultFieldResolver = function ( + source, + args, + contextValue, + info, +) { + // ensure source is a value for which property access is acceptable. + if (isObjectLike(source) || typeof source === 'function') { + const property = source[info.fieldName]; + + if (typeof property === 'function') { + return source[info.fieldName](args, contextValue, info); + } + + return property; + } +}; +/** + * This method looks up the field on the given type definition. + * It has special casing for the three introspection fields, + * __schema, __type and __typename. __typename is special because + * it can always be queried as a field, even in situations where no + * other fields are allowed, like on a Union. __schema and __type + * could get automatically added to the query type, but that would + * require mutating type definitions, which would cause issues. + * + * @internal + */ + +export function getFieldDef(schema, parentType, fieldNode) { + const fieldName = fieldNode.name.value; + + if ( + fieldName === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } else if ( + fieldName === TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return TypeMetaFieldDef; + } else if (fieldName === TypeNameMetaFieldDef.name) { + return TypeNameMetaFieldDef; + } + + return parentType.getFields()[fieldName]; +} diff --git a/node_modules/graphql/execution/index.d.ts b/node_modules/graphql/execution/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d7fcbb8fa0b6473cde2b90b1ee3966ea62b19d96 --- /dev/null +++ b/node_modules/graphql/execution/index.d.ts @@ -0,0 +1,24 @@ +/** + * Execute GraphQL operations and produce GraphQL execution results. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { pathToArray as responsePathAsArray } from '../jsutils/Path'; +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, +} from './execute'; +export type { + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execute'; +export { subscribe, createSourceEventStream } from './subscribe'; +export { + getArgumentValues, + getVariableValues, + getDirectiveValues, +} from './values'; diff --git a/node_modules/graphql/execution/index.js b/node_modules/graphql/execution/index.js new file mode 100644 index 0000000000000000000000000000000000000000..3fef7fadbd6034d454ddd871240ef8f6d326a9b6 --- /dev/null +++ b/node_modules/graphql/execution/index.js @@ -0,0 +1,73 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'createSourceEventStream', { + enumerable: true, + get: function () { + return _subscribe.createSourceEventStream; + }, +}); +Object.defineProperty(exports, 'defaultFieldResolver', { + enumerable: true, + get: function () { + return _execute.defaultFieldResolver; + }, +}); +Object.defineProperty(exports, 'defaultTypeResolver', { + enumerable: true, + get: function () { + return _execute.defaultTypeResolver; + }, +}); +Object.defineProperty(exports, 'execute', { + enumerable: true, + get: function () { + return _execute.execute; + }, +}); +Object.defineProperty(exports, 'executeSync', { + enumerable: true, + get: function () { + return _execute.executeSync; + }, +}); +Object.defineProperty(exports, 'getArgumentValues', { + enumerable: true, + get: function () { + return _values.getArgumentValues; + }, +}); +Object.defineProperty(exports, 'getDirectiveValues', { + enumerable: true, + get: function () { + return _values.getDirectiveValues; + }, +}); +Object.defineProperty(exports, 'getVariableValues', { + enumerable: true, + get: function () { + return _values.getVariableValues; + }, +}); +Object.defineProperty(exports, 'responsePathAsArray', { + enumerable: true, + get: function () { + return _Path.pathToArray; + }, +}); +Object.defineProperty(exports, 'subscribe', { + enumerable: true, + get: function () { + return _subscribe.subscribe; + }, +}); + +var _Path = require('../jsutils/Path.js'); + +var _execute = require('./execute.js'); + +var _subscribe = require('./subscribe.js'); + +var _values = require('./values.js'); diff --git a/node_modules/graphql/execution/index.mjs b/node_modules/graphql/execution/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0e5cae3dd978f93741518384f6d301e18f56acf7 --- /dev/null +++ b/node_modules/graphql/execution/index.mjs @@ -0,0 +1,19 @@ +/** + * Execute GraphQL operations and produce GraphQL execution results. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { pathToArray as responsePathAsArray } from '../jsutils/Path.mjs'; +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, +} from './execute.mjs'; +export { subscribe, createSourceEventStream } from './subscribe.mjs'; +export { + getArgumentValues, + getVariableValues, + getDirectiveValues, +} from './values.mjs'; diff --git a/node_modules/graphql/execution/mapAsyncIterator.d.ts b/node_modules/graphql/execution/mapAsyncIterator.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9430ea7de902ff15c6b9d4d62bf45a46728edf20 --- /dev/null +++ b/node_modules/graphql/execution/mapAsyncIterator.d.ts @@ -0,0 +1,11 @@ +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + * + * @internal + */ +export declare function mapAsyncIterator( + iterable: AsyncGenerator | AsyncIterable, + callback: (value: T) => PromiseOrValue, +): AsyncGenerator; diff --git a/node_modules/graphql/execution/mapAsyncIterator.js b/node_modules/graphql/execution/mapAsyncIterator.js new file mode 100644 index 0000000000000000000000000000000000000000..094515dd4bf4fca9880efbe706918bc72ab1fe40 --- /dev/null +++ b/node_modules/graphql/execution/mapAsyncIterator.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.mapAsyncIterator = mapAsyncIterator; + +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + * + * @internal + */ +function mapAsyncIterator(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); + + async function mapResult(result) { + if (result.done) { + return result; + } + + try { + return { + value: await callback(result.value), + done: false, + }; + } catch (error) { + /* c8 ignore start */ + // FIXME: add test case + if (typeof iterator.return === 'function') { + try { + await iterator.return(); + } catch (_e) { + /* ignore error */ + } + } + + throw error; + /* c8 ignore stop */ + } + } + + return { + async next() { + return mapResult(await iterator.next()); + }, + + async return() { + // If iterator.return() does not exist, then type R must be undefined. + return typeof iterator.return === 'function' + ? mapResult(await iterator.return()) + : { + value: undefined, + done: true, + }; + }, + + async throw(error) { + if (typeof iterator.throw === 'function') { + return mapResult(await iterator.throw(error)); + } + + throw error; + }, + + [Symbol.asyncIterator]() { + return this; + }, + }; +} diff --git a/node_modules/graphql/execution/mapAsyncIterator.mjs b/node_modules/graphql/execution/mapAsyncIterator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b7e574d2d028b24434259459d4363fe169f0b1eb --- /dev/null +++ b/node_modules/graphql/execution/mapAsyncIterator.mjs @@ -0,0 +1,63 @@ +/** + * Given an AsyncIterable and a callback function, return an AsyncIterator + * which produces values mapped via calling the callback function. + * + * @internal + */ +export function mapAsyncIterator(iterable, callback) { + const iterator = iterable[Symbol.asyncIterator](); + + async function mapResult(result) { + if (result.done) { + return result; + } + + try { + return { + value: await callback(result.value), + done: false, + }; + } catch (error) { + /* c8 ignore start */ + // FIXME: add test case + if (typeof iterator.return === 'function') { + try { + await iterator.return(); + } catch (_e) { + /* ignore error */ + } + } + + throw error; + /* c8 ignore stop */ + } + } + + return { + async next() { + return mapResult(await iterator.next()); + }, + + async return() { + // If iterator.return() does not exist, then type R must be undefined. + return typeof iterator.return === 'function' + ? mapResult(await iterator.return()) + : { + value: undefined, + done: true, + }; + }, + + async throw(error) { + if (typeof iterator.throw === 'function') { + return mapResult(await iterator.throw(error)); + } + + throw error; + }, + + [Symbol.asyncIterator]() { + return this; + }, + }; +} diff --git a/node_modules/graphql/execution/subscribe.d.ts b/node_modules/graphql/execution/subscribe.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96abb7326e990e9392d22537315f24c76d233184 --- /dev/null +++ b/node_modules/graphql/execution/subscribe.d.ts @@ -0,0 +1,262 @@ +/** @category Subscriptions */ +import type { Maybe } from '../jsutils/Maybe'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLFieldResolver } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +import type { ExecutionArgs, ExecutionResult } from './execute'; +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise that resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Each payload yielded by the source event stream is executed with the payload + * as the root value. This maps the subscription source stream into the response + * stream described by the GraphQL specification. + * + * Accepts an object with named arguments. + * @param args - The arguments used to perform the operation. + * @returns A source stream mapped to execution results, or an execution result + * containing subscription errors. + * @example + * ```ts + * // Use a same-named rootValue function to provide the source event stream. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant supplies events through a custom subscribeFieldResolver. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* defaultGreetings() { + * yield { greeting: 'Hello' }; + * } + * + * async function* frenchGreetings() { + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting(locale: String): String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse( + * 'subscription Greeting($locale: String) { greeting(locale: $locale) }', + * ), + * rootValue: { + * greeting: (args, contextValue) => { + * const locale = args.locale ?? contextValue.defaultLocale; + * return locale === 'fr' ? frenchGreetings() : defaultGreetings(); + * }, + * }, + * contextValue: { defaultLocale: 'fr' }, + * variableValues: { locale: 'fr' }, + * operationName: 'Greeting', + * subscribeFieldResolver: (rootValue, args, contextValue, info) => { + * args.locale; // => 'fr' + * return rootValue[info.fieldName](args, contextValue); + * }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Bonjour' } } + * ``` + * @example + * ```ts + * // This variant shows the error result when the schema has no subscription root. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * }); + * + * assert('errors' in result); + * + * result.errors[0].message; // => 'Schema is not configured to execute subscription operation.' + * ``` + */ +export declare function subscribe( + args: ExecutionArgs, +): Promise | ExecutionResult>; +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise that resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + * @param args - The arguments used to perform the operation. + * @returns The source event stream, or an execution result containing subscription errors. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { createSourceEventStream } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const stream = await createSourceEventStream({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * Symbol.asyncIterator in stream; // => true + * ``` + */ +export declare function createSourceEventStream( + args: ExecutionArgs, +): Promise | ExecutionResult>; +/** + * Creates the source event stream for a subscription operation using the legacy + * positional argument overload. This deprecated overload will be removed in the + * next major version; use the args object overload instead. + * @param schema - GraphQL schema to use. + * @param document - The parsed GraphQL document containing the subscription + * operation. + * @param rootValue - Initial root value passed to the subscription resolver. + * @param contextValue - Application context value passed to resolvers. + * @param variableValues - Runtime variable values keyed by variable name. + * @param operationName - Name of the subscription operation to execute when + * the document contains multiple operations. + * @param subscribeFieldResolver - Resolver used for the root subscription + * field. + * @returns The source event stream, or an execution result containing + * subscription errors. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { createSourceEventStream } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * const document = parse('subscription { greeting }'); + * + * const stream = await createSourceEventStream(schema, document, { + * greeting: () => greetings(), + * }); + * + * Symbol.asyncIterator in stream; // => true + * ``` + * @deprecated Will be removed in next major version in favor of named arguments. + */ +export declare function createSourceEventStream( + schema: GraphQLSchema, + document: DocumentNode, + rootValue?: unknown, + contextValue?: unknown, + variableValues?: Maybe<{ + readonly [variable: string]: unknown; + }>, + operationName?: Maybe, + subscribeFieldResolver?: Maybe>, +): Promise | ExecutionResult>; diff --git a/node_modules/graphql/execution/subscribe.js b/node_modules/graphql/execution/subscribe.js new file mode 100644 index 0000000000000000000000000000000000000000..5f83fbc6eeafc72cafb4b4c7be1c32e9e6b3b739 --- /dev/null +++ b/node_modules/graphql/execution/subscribe.js @@ -0,0 +1,388 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.createSourceEventStream = createSourceEventStream; +exports.subscribe = subscribe; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _isAsyncIterable = require('../jsutils/isAsyncIterable.js'); + +var _Path = require('../jsutils/Path.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _locatedError = require('../error/locatedError.js'); + +var _collectFields = require('./collectFields.js'); + +var _execute = require('./execute.js'); + +var _mapAsyncIterator = require('./mapAsyncIterator.js'); + +var _values = require('./values.js'); + +/** @category Subscriptions */ + +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise that resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Each payload yielded by the source event stream is executed with the payload + * as the root value. This maps the subscription source stream into the response + * stream described by the GraphQL specification. + * + * Accepts an object with named arguments. + * @param args - The arguments used to perform the operation. + * @returns A source stream mapped to execution results, or an execution result + * containing subscription errors. + * @example + * ```ts + * // Use a same-named rootValue function to provide the source event stream. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant supplies events through a custom subscribeFieldResolver. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* defaultGreetings() { + * yield { greeting: 'Hello' }; + * } + * + * async function* frenchGreetings() { + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting(locale: String): String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse( + * 'subscription Greeting($locale: String) { greeting(locale: $locale) }', + * ), + * rootValue: { + * greeting: (args, contextValue) => { + * const locale = args.locale ?? contextValue.defaultLocale; + * return locale === 'fr' ? frenchGreetings() : defaultGreetings(); + * }, + * }, + * contextValue: { defaultLocale: 'fr' }, + * variableValues: { locale: 'fr' }, + * operationName: 'Greeting', + * subscribeFieldResolver: (rootValue, args, contextValue, info) => { + * args.locale; // => 'fr' + * return rootValue[info.fieldName](args, contextValue); + * }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Bonjour' } } + * ``` + * @example + * ```ts + * // This variant shows the error result when the schema has no subscription root. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * }); + * + * assert('errors' in result); + * + * result.errors[0].message; // => 'Schema is not configured to execute subscription operation.' + * ``` + */ +async function subscribe(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const resultOrStream = await createSourceEventStream(args); + + if (!(0, _isAsyncIterable.isAsyncIterable)(resultOrStream)) { + return resultOrStream; + } + + const mapSourceToResponse = (payload) => + (0, _execute.execute)({ ...args, rootValue: payload }); + + return (0, _mapAsyncIterator.mapAsyncIterator)( + resultOrStream, + mapSourceToResponse, + ); +} + +function toNormalizedArgs(args) { + const firstArg = args[0]; + + if (firstArg && 'document' in firstArg) { + return firstArg; + } + + return { + schema: firstArg, + // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 + document: args[1], + rootValue: args[2], + contextValue: args[3], + variableValues: args[4], + operationName: args[5], + subscribeFieldResolver: args[6], + }; +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise that resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + * @param args - The arguments used to perform the operation. + * @returns The source event stream, or an execution result containing subscription errors. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { createSourceEventStream } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const stream = await createSourceEventStream({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * Symbol.asyncIterator in stream; // => true + * ``` + */ + +/** @internal */ +async function createSourceEventStream(...rawArgs) { + const args = toNormalizedArgs(rawArgs); + const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + // eslint-disable-next-line import/no-deprecated + + (0, _execute.assertValidExecutionArguments)(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = (0, _execute.buildExecutionContext)(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } + + try { + const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + + if (!(0, _isAsyncIterable.isAsyncIterable)(eventStream)) { + throw new Error( + 'Subscription field must return Async Iterable. ' + + `Received: ${(0, _inspect.inspect)(eventStream)}.`, + ); + } + + return eventStream; + } catch (error) { + // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. + // Otherwise treat the error as a system-class error and re-throw it. + if (error instanceof _GraphQLError.GraphQLError) { + return { + errors: [error], + }; + } + + throw error; + } +} + +async function executeSubscription(exeContext) { + const { schema, fragments, operation, variableValues, rootValue } = + exeContext; + const rootType = schema.getSubscriptionType(); + + if (rootType == null) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured to execute subscription operation.', + { + nodes: operation, + }, + ); + } + + const rootFields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + rootType, + operation.selectionSet, + ); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = (0, _execute.getFieldDef)(schema, rootType, fieldNodes[0]); + + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new _GraphQLError.GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + { + nodes: fieldNodes, + }, + ); + } + + const path = (0, _Path.addPath)(undefined, responseName, rootType.name); + const info = (0, _execute.buildResolveInfo)( + exeContext, + fieldDef, + fieldNodes, + rootType, + path, + ); + + try { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = (0, _values.getArgumentValues)( + fieldDef, + fieldNodes[0], + variableValues, + ); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + const resolveFn = + (_fieldDef$subscribe = fieldDef.subscribe) !== null && + _fieldDef$subscribe !== void 0 + ? _fieldDef$subscribe + : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn(rootValue, args, contextValue, info); + + if (eventStream instanceof Error) { + throw eventStream; + } + + return eventStream; + } catch (error) { + throw (0, _locatedError.locatedError)( + error, + fieldNodes, + (0, _Path.pathToArray)(path), + ); + } +} diff --git a/node_modules/graphql/execution/subscribe.mjs b/node_modules/graphql/execution/subscribe.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8cd38fd0d725933b8879a88c0d014944e86a90b4 --- /dev/null +++ b/node_modules/graphql/execution/subscribe.mjs @@ -0,0 +1,366 @@ +/** @category Subscriptions */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { isAsyncIterable } from '../jsutils/isAsyncIterable.mjs'; +import { addPath, pathToArray } from '../jsutils/Path.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { locatedError } from '../error/locatedError.mjs'; +import { collectFields } from './collectFields.mjs'; +import { + // eslint-disable-next-line import/no-deprecated + assertValidExecutionArguments, + buildExecutionContext, + buildResolveInfo, + execute, + getFieldDef, +} from './execute.mjs'; +import { mapAsyncIterator } from './mapAsyncIterator.mjs'; +import { getArgumentValues } from './values.mjs'; +/** + * Implements the "Subscribe" algorithm described in the GraphQL specification. + * + * Returns a Promise that resolves to either an AsyncIterator (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to an AsyncIterator, which + * yields a stream of ExecutionResults representing the response stream. + * + * Each payload yielded by the source event stream is executed with the payload + * as the root value. This maps the subscription source stream into the response + * stream described by the GraphQL specification. + * + * Accepts an object with named arguments. + * @param args - The arguments used to perform the operation. + * @returns A source stream mapped to execution results, or an execution result + * containing subscription errors. + * @example + * ```ts + * // Use a same-named rootValue function to provide the source event stream. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Hello' } } + * ``` + * @example + * ```ts + * // This variant supplies events through a custom subscribeFieldResolver. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * async function* defaultGreetings() { + * yield { greeting: 'Hello' }; + * } + * + * async function* frenchGreetings() { + * yield { greeting: 'Bonjour' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting(locale: String): String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse( + * 'subscription Greeting($locale: String) { greeting(locale: $locale) }', + * ), + * rootValue: { + * greeting: (args, contextValue) => { + * const locale = args.locale ?? contextValue.defaultLocale; + * return locale === 'fr' ? frenchGreetings() : defaultGreetings(); + * }, + * }, + * contextValue: { defaultLocale: 'fr' }, + * variableValues: { locale: 'fr' }, + * operationName: 'Greeting', + * subscribeFieldResolver: (rootValue, args, contextValue, info) => { + * args.locale; // => 'fr' + * return rootValue[info.fieldName](args, contextValue); + * }, + * }); + * + * assert('next' in result); + * + * const firstPayload = await result.next(); + * firstPayload.value; // => { data: { greeting: 'Bonjour' } } + * ``` + * @example + * ```ts + * // This variant shows the error result when the schema has no subscription root. + * import assert from 'node:assert'; + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { subscribe } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * `); + * + * const result = await subscribe({ + * schema, + * document: parse('subscription { greeting }'), + * }); + * + * assert('errors' in result); + * + * result.errors[0].message; // => 'Schema is not configured to execute subscription operation.' + * ``` + */ + +export async function subscribe(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + devAssert( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const resultOrStream = await createSourceEventStream(args); + + if (!isAsyncIterable(resultOrStream)) { + return resultOrStream; + } + + const mapSourceToResponse = (payload) => + execute({ ...args, rootValue: payload }); + + return mapAsyncIterator(resultOrStream, mapSourceToResponse); +} + +function toNormalizedArgs(args) { + const firstArg = args[0]; + + if (firstArg && 'document' in firstArg) { + return firstArg; + } + + return { + schema: firstArg, + // FIXME: when underlying TS bug fixed, see https://github.com/microsoft/TypeScript/issues/31613 + document: args[1], + rootValue: args[2], + contextValue: args[3], + variableValues: args[4], + operationName: args[5], + subscribeFieldResolver: args[6], + }; +} +/** + * Implements the "CreateSourceEventStream" algorithm described in the + * GraphQL specification, resolving the subscription source event stream. + * + * Returns a Promise that resolves to either an AsyncIterable (if successful) + * or an ExecutionResult (error). The promise will be rejected if the schema or + * other arguments to this function are invalid, or if the resolved event stream + * is not an async iterable. + * + * If the client-provided arguments to this function do not result in a + * compliant subscription, a GraphQL Response (ExecutionResult) with + * descriptive errors and no data will be returned. + * + * If the source stream could not be created due to faulty subscription + * resolver logic or underlying systems, the promise will resolve to a single + * ExecutionResult containing `errors` and no `data`. + * + * If the operation succeeded, the promise resolves to the AsyncIterable for the + * event stream returned by the resolver. + * + * A Source Event Stream represents a sequence of events, each of which triggers + * a GraphQL execution for that event. + * + * This may be useful when hosting the stateful subscription service in a + * different process or machine than the stateless GraphQL execution engine, + * or otherwise separating these two steps. For more on this, see the + * "Supporting Subscriptions at Scale" information in the GraphQL specification. + * @param args - The arguments used to perform the operation. + * @returns The source event stream, or an execution result containing subscription errors. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { createSourceEventStream } from 'graphql/execution'; + * + * async function* greetings() { + * yield { greeting: 'Hello' }; + * } + * + * const schema = buildSchema(` + * type Query { + * noop: String + * } + * + * type Subscription { + * greeting: String + * } + * `); + * + * const stream = await createSourceEventStream({ + * schema, + * document: parse('subscription { greeting }'), + * rootValue: { greeting: () => greetings() }, + * }); + * + * Symbol.asyncIterator in stream; // => true + * ``` + */ + +/** @internal */ +export async function createSourceEventStream(...rawArgs) { + const args = toNormalizedArgs(rawArgs); + const { schema, document, variableValues } = args; // If arguments are missing or incorrectly typed, this is an internal + // developer mistake which should throw an early error. + // eslint-disable-next-line import/no-deprecated + + assertValidExecutionArguments(schema, document, variableValues); // If a valid execution context cannot be created due to incorrect arguments, + // a "Response" with only errors is returned. + + const exeContext = buildExecutionContext(args); // Return early errors if execution context failed. + + if (!('schema' in exeContext)) { + return { + errors: exeContext, + }; + } + + try { + const eventStream = await executeSubscription(exeContext); // Assert field returned an event stream, otherwise yield an error. + + if (!isAsyncIterable(eventStream)) { + throw new Error( + 'Subscription field must return Async Iterable. ' + + `Received: ${inspect(eventStream)}.`, + ); + } + + return eventStream; + } catch (error) { + // If it GraphQLError, report it as an ExecutionResult, containing only errors and no data. + // Otherwise treat the error as a system-class error and re-throw it. + if (error instanceof GraphQLError) { + return { + errors: [error], + }; + } + + throw error; + } +} + +async function executeSubscription(exeContext) { + const { schema, fragments, operation, variableValues, rootValue } = + exeContext; + const rootType = schema.getSubscriptionType(); + + if (rootType == null) { + throw new GraphQLError( + 'Schema is not configured to execute subscription operation.', + { + nodes: operation, + }, + ); + } + + const rootFields = collectFields( + schema, + fragments, + variableValues, + rootType, + operation.selectionSet, + ); + const [responseName, fieldNodes] = [...rootFields.entries()][0]; + const fieldDef = getFieldDef(schema, rootType, fieldNodes[0]); + + if (!fieldDef) { + const fieldName = fieldNodes[0].name.value; + throw new GraphQLError( + `The subscription field "${fieldName}" is not defined.`, + { + nodes: fieldNodes, + }, + ); + } + + const path = addPath(undefined, responseName, rootType.name); + const info = buildResolveInfo( + exeContext, + fieldDef, + fieldNodes, + rootType, + path, + ); + + try { + var _fieldDef$subscribe; + + // Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. + // It differs from "ResolveFieldValue" due to providing a different `resolveFn`. + // Build a JS object of arguments from the field.arguments AST, using the + // variables scope to fulfill any variable references. + const args = getArgumentValues(fieldDef, fieldNodes[0], variableValues); // The resolve function's optional third argument is a context value that + // is provided to every resolve function within an execution. It is commonly + // used to represent an authenticated user, or request-specific caches. + + const contextValue = exeContext.contextValue; // Call the `subscribe()` resolver or the default resolver to produce an + // AsyncIterable yielding raw payloads. + + const resolveFn = + (_fieldDef$subscribe = fieldDef.subscribe) !== null && + _fieldDef$subscribe !== void 0 + ? _fieldDef$subscribe + : exeContext.subscribeFieldResolver; + const eventStream = await resolveFn(rootValue, args, contextValue, info); + + if (eventStream instanceof Error) { + throw eventStream; + } + + return eventStream; + } catch (error) { + throw locatedError(error, fieldNodes, pathToArray(path)); + } +} diff --git a/node_modules/graphql/execution/values.d.ts b/node_modules/graphql/execution/values.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a716597fd2f76490234e1e6fdc15e70ded2fb7a0 --- /dev/null +++ b/node_modules/graphql/execution/values.d.ts @@ -0,0 +1,236 @@ +/** @category Values */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import { GraphQLError } from '../error/GraphQLError'; +import type { + DirectiveNode, + FieldNode, + VariableDefinitionNode, +} from '../language/ast'; +import type { GraphQLField } from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +declare type CoercedVariableValues = + | { + errors: ReadonlyArray; + coerced?: never; + } + | { + coerced: { + [variable: string]: unknown; + }; + errors?: never; + }; +/** + * Options used when coercing variable values before execution. + * @internal + */ +export interface GetVariableValuesOptions { + /** + * Maximum number of variable coercion errors before coercion stops. + * @internal + */ + maxErrors?: number; +} +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, GraphQLError values are returned. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param schema - GraphQL schema to use. + * @param varDefNodes - The variable definition AST nodes to coerce. + * @param inputs - The runtime variable values keyed by variable name. + * @param options - Optional variable coercion options, including error limits. + * @returns Coerced variable values, or request errors. + * @example + * ```ts + * // Coerce provided variables and apply operation defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const document = parse(` + * query ($stars: Int!, $limit: Int = 10) { + * reviews(stars: $stars, limit: $limit) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { stars: '5' }, + * ); + * + * result; // => { coerced: { stars: 5, limit: 10 } } + * ``` + * @example + * ```ts + * // This variant uses maxErrors to cap reported coercion errors. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { first: { stars: 'bad' }, second: { stars: 'also bad' } }, + * { maxErrors: 1 }, + * ); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +export declare function getVariableValues( + schema: GraphQLSchema, + varDefNodes: ReadonlyArray, + inputs: { + readonly [variable: string]: unknown; + }, + options?: GetVariableValuesOptions, +): CoercedVariableValues; +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param def - The field or directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced argument values keyed by argument name. + * @example + * ```ts + * // Read literal argument values and defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('{ reviews(stars: 5) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode); // => { stars: 5, limit: 10 } + * ``` + * @example + * ```ts + * // This variant resolves argument values from operation variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('query ($stars: Int!) { reviews(stars: $stars) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 } + * getArgumentValues(fieldDef, fieldNode, {}); // throws an error + * ``` + */ +export declare function getArgumentValues( + def: GraphQLField | GraphQLDirective, + node: FieldNode | DirectiveNode, + variableValues?: Maybe>, +): { + [argument: string]: unknown; +}; +/** + * AST node shape accepted by getDirectiveValues. + * @internal + */ +export interface DirectiveValuesNode { + /** + * Directives attached to the AST node. + * @internal + */ + readonly directives?: ReadonlyArray; +} +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param directiveDef - The directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced directive argument values keyed by argument name. + * @example + * ```ts + * // Read literal directive arguments from a node. + * import { parse } from 'graphql/language'; + * import { GraphQLSkipDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('{ name @skip(if: true) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLSkipDirective, fieldNode); // => { if: true } + * ``` + * @example + * ```ts + * // This variant resolves directive arguments from variables and handles absent directives. + * import { parse } from 'graphql/language'; + * import { GraphQLIncludeDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLIncludeDirective, fieldNode, { + * includeName: false, + * }); // => { if: false } + * getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined + * ``` + */ +export declare function getDirectiveValues( + directiveDef: GraphQLDirective, + node: DirectiveValuesNode, + variableValues?: Maybe>, +): + | undefined + | { + [argument: string]: unknown; + }; +export {}; diff --git a/node_modules/graphql/execution/values.js b/node_modules/graphql/execution/values.js new file mode 100644 index 0000000000000000000000000000000000000000..f1f889a7b12d21d07880fa91b539cf5d851112de --- /dev/null +++ b/node_modules/graphql/execution/values.js @@ -0,0 +1,444 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.getArgumentValues = getArgumentValues; +exports.getDirectiveValues = getDirectiveValues; +exports.getVariableValues = getVariableValues; + +var _inspect = require('../jsutils/inspect.js'); + +var _keyMap = require('../jsutils/keyMap.js'); + +var _printPathArray = require('../jsutils/printPathArray.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _kinds = require('../language/kinds.js'); + +var _printer = require('../language/printer.js'); + +var _definition = require('../type/definition.js'); + +var _coerceInputValue = require('../utilities/coerceInputValue.js'); + +var _typeFromAST = require('../utilities/typeFromAST.js'); + +var _valueFromAST = require('../utilities/valueFromAST.js'); + +/** @category Values */ + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, GraphQLError values are returned. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param schema - GraphQL schema to use. + * @param varDefNodes - The variable definition AST nodes to coerce. + * @param inputs - The runtime variable values keyed by variable name. + * @param options - Optional variable coercion options, including error limits. + * @returns Coerced variable values, or request errors. + * @example + * ```ts + * // Coerce provided variables and apply operation defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const document = parse(` + * query ($stars: Int!, $limit: Int = 10) { + * reviews(stars: $stars, limit: $limit) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { stars: '5' }, + * ); + * + * result; // => { coerced: { stars: 5, limit: 10 } } + * ``` + * @example + * ```ts + * // This variant uses maxErrors to cap reported coercion errors. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { first: { stars: 'bad' }, second: { stars: 'also bad' } }, + * { maxErrors: 1 }, + * ); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors; + + try { + const coerced = coerceVariableValues( + schema, + varDefNodes, + inputs, + (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new _GraphQLError.GraphQLError( + 'Too many errors processing variables, error limit reached. Execution aborted.', + ); + } + + errors.push(error); + }, + ); + + if (errors.length === 0) { + return { + coerced, + }; + } + } catch (error) { + errors.push(error); + } + + return { + errors, + }; +} + +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = Object.create(null); + + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = (0, _typeFromAST.typeFromAST)(schema, varDefNode.type); + + if (!(0, _definition.isInputType)(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = (0, _printer.print)(varDefNode.type); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, + { + nodes: varDefNode.type, + }, + ), + ); + continue; + } + + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = (0, _valueFromAST.valueFromAST)( + varDefNode.defaultValue, + varType, + ); + } else if ((0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, + { + nodes: varDefNode, + }, + ), + ); + } + + continue; + } + + const value = inputs[varName]; + + if (value === null && (0, _definition.isNonNullType)(varType)) { + const varTypeStr = (0, _inspect.inspect)(varType); + onError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, + { + nodes: varDefNode, + }, + ), + ); + continue; + } + + coercedValues[varName] = (0, _coerceInputValue.coerceInputValue)( + value, + varType, + (path, invalidValue, error) => { + let prefix = + `Variable "$${varName}" got invalid value ` + + (0, _inspect.inspect)(invalidValue); + + if (path.length > 0) { + prefix += ` at "${varName}${(0, _printPathArray.printPathArray)( + path, + )}"`; + } + + onError( + new _GraphQLError.GraphQLError(prefix + '; ' + error.message, { + nodes: varDefNode, + originalError: error, + }), + ); + }, + ); + } + + return { ...coercedValues }; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param def - The field or directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced argument values keyed by argument name. + * @example + * ```ts + * // Read literal argument values and defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('{ reviews(stars: 5) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode); // => { stars: 5, limit: 10 } + * ``` + * @example + * ```ts + * // This variant resolves argument values from operation variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('query ($stars: Int!) { reviews(stars: $stars) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 } + * getArgumentValues(fieldDef, fieldNode, {}); // throws an error + * ``` + */ + +function getArgumentValues(def, node, variableValues) { + var _node$arguments; + + const coercedValues = Object.create(null); // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 + ? _node$arguments + : []; + const argNodeMap = (0, _keyMap.keyMap)( + argumentNodes, + (arg) => arg.name.value, + ); + + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, _inspect.inspect)( + argType, + )}" ` + 'was not provided.', + { + nodes: node, + }, + ); + } + + continue; + } + + const valueNode = argumentNode.value; + let isNull = valueNode.kind === _kinds.Kind.NULL; + + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + + if ( + variableValues == null || + !hasOwnProperty(variableValues, variableName) + ) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if ((0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of required type "${(0, _inspect.inspect)( + argType, + )}" ` + + `was provided the variable "$${variableName}" which was not provided a runtime value.`, + { + nodes: valueNode, + }, + ); + } + + continue; + } + + isNull = variableValues[variableName] == null; + } + + if (isNull && (0, _definition.isNonNullType)(argType)) { + throw new _GraphQLError.GraphQLError( + `Argument "${name}" of non-null type "${(0, _inspect.inspect)( + argType, + )}" ` + 'must not be null.', + { + nodes: valueNode, + }, + ); + } + + const coercedValue = (0, _valueFromAST.valueFromAST)( + valueNode, + argType, + variableValues, + ); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new _GraphQLError.GraphQLError( + `Argument "${name}" has invalid value ${(0, _printer.print)( + valueNode, + )}.`, + { + nodes: valueNode, + }, + ); + } + + coercedValues[name] = coercedValue; + } + + return { ...coercedValues }; +} +/** + * AST node shape accepted by getDirectiveValues. + * @internal + */ + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param directiveDef - The directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced directive argument values keyed by argument name. + * @example + * ```ts + * // Read literal directive arguments from a node. + * import { parse } from 'graphql/language'; + * import { GraphQLSkipDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('{ name @skip(if: true) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLSkipDirective, fieldNode); // => { if: true } + * ``` + * @example + * ```ts + * // This variant resolves directive arguments from variables and handles absent directives. + * import { parse } from 'graphql/language'; + * import { GraphQLIncludeDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLIncludeDirective, fieldNode, { + * includeName: false, + * }); // => { if: false } + * getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined + * ``` + */ +function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; + + const directiveNode = + (_node$directives = node.directives) === null || _node$directives === void 0 + ? void 0 + : _node$directives.find( + (directive) => directive.name.value === directiveDef.name, + ); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/execution/values.mjs b/node_modules/graphql/execution/values.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dc8710bad223746a13ed37424cfc89e49d591b34 --- /dev/null +++ b/node_modules/graphql/execution/values.mjs @@ -0,0 +1,406 @@ +/** @category Values */ +import { inspect } from '../jsutils/inspect.mjs'; +import { keyMap } from '../jsutils/keyMap.mjs'; +import { printPathArray } from '../jsutils/printPathArray.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { print } from '../language/printer.mjs'; +import { isInputType, isNonNullType } from '../type/definition.mjs'; +import { coerceInputValue } from '../utilities/coerceInputValue.mjs'; +import { typeFromAST } from '../utilities/typeFromAST.mjs'; +import { valueFromAST } from '../utilities/valueFromAST.mjs'; + +/** + * Prepares an object map of variableValues of the correct type based on the + * provided variable definitions and arbitrary input. If the input cannot be + * parsed to match the variable definitions, GraphQLError values are returned. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param schema - GraphQL schema to use. + * @param varDefNodes - The variable definition AST nodes to coerce. + * @param inputs - The runtime variable values keyed by variable name. + * @param options - Optional variable coercion options, including error limits. + * @returns Coerced variable values, or request errors. + * @example + * ```ts + * // Coerce provided variables and apply operation defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const document = parse(` + * query ($stars: Int!, $limit: Int = 10) { + * reviews(stars: $stars, limit: $limit) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { stars: '5' }, + * ); + * + * result; // => { coerced: { stars: 5, limit: 10 } } + * ``` + * @example + * ```ts + * // This variant uses maxErrors to cap reported coercion errors. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getVariableValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput!): String + * } + * `); + * const document = parse(` + * query ($first: ReviewInput!, $second: ReviewInput!) { + * first: review(input: $first) + * second: review(input: $second) + * } + * `); + * const operation = document.definitions[0]; + * + * const result = getVariableValues( + * schema, + * operation.variableDefinitions, + * { first: { stars: 'bad' }, second: { stars: 'also bad' } }, + * { maxErrors: 1 }, + * ); + * + * result.errors.length; // => 2 + * result.errors[1].message; // matches /error limit reached/ + * ``` + */ +export function getVariableValues(schema, varDefNodes, inputs, options) { + const errors = []; + const maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors; + + try { + const coerced = coerceVariableValues( + schema, + varDefNodes, + inputs, + (error) => { + if (maxErrors != null && errors.length >= maxErrors) { + throw new GraphQLError( + 'Too many errors processing variables, error limit reached. Execution aborted.', + ); + } + + errors.push(error); + }, + ); + + if (errors.length === 0) { + return { + coerced, + }; + } + } catch (error) { + errors.push(error); + } + + return { + errors, + }; +} + +function coerceVariableValues(schema, varDefNodes, inputs, onError) { + const coercedValues = Object.create(null); + + for (const varDefNode of varDefNodes) { + const varName = varDefNode.variable.name.value; + const varType = typeFromAST(schema, varDefNode.type); + + if (!isInputType(varType)) { + // Must use input types for variables. This should be caught during + // validation, however is checked again here for safety. + const varTypeStr = print(varDefNode.type); + onError( + new GraphQLError( + `Variable "$${varName}" expected value of type "${varTypeStr}" which cannot be used as an input type.`, + { + nodes: varDefNode.type, + }, + ), + ); + continue; + } + + if (!hasOwnProperty(inputs, varName)) { + if (varDefNode.defaultValue) { + coercedValues[varName] = valueFromAST(varDefNode.defaultValue, varType); + } else if (isNonNullType(varType)) { + const varTypeStr = inspect(varType); + onError( + new GraphQLError( + `Variable "$${varName}" of required type "${varTypeStr}" was not provided.`, + { + nodes: varDefNode, + }, + ), + ); + } + + continue; + } + + const value = inputs[varName]; + + if (value === null && isNonNullType(varType)) { + const varTypeStr = inspect(varType); + onError( + new GraphQLError( + `Variable "$${varName}" of non-null type "${varTypeStr}" must not be null.`, + { + nodes: varDefNode, + }, + ), + ); + continue; + } + + coercedValues[varName] = coerceInputValue( + value, + varType, + (path, invalidValue, error) => { + let prefix = + `Variable "$${varName}" got invalid value ` + inspect(invalidValue); + + if (path.length > 0) { + prefix += ` at "${varName}${printPathArray(path)}"`; + } + + onError( + new GraphQLError(prefix + '; ' + error.message, { + nodes: varDefNode, + originalError: error, + }), + ); + }, + ); + } + + return { ...coercedValues }; +} +/** + * Prepares an object map of argument values given a list of argument + * definitions and list of argument AST nodes. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param def - The field or directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced argument values keyed by argument name. + * @example + * ```ts + * // Read literal argument values and defaults. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, limit: Int = 10): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('{ reviews(stars: 5) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode); // => { stars: 5, limit: 10 } + * ``` + * @example + * ```ts + * // This variant resolves argument values from operation variables. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { getArgumentValues } from 'graphql/execution'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!): [String] + * } + * `); + * const fieldDef = schema.getQueryType().getFields().reviews; + * const document = parse('query ($stars: Int!) { reviews(stars: $stars) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getArgumentValues(fieldDef, fieldNode, { stars: 5 }); // => { stars: 5 } + * getArgumentValues(fieldDef, fieldNode, {}); // throws an error + * ``` + */ + +export function getArgumentValues(def, node, variableValues) { + var _node$arguments; + + const coercedValues = Object.create(null); // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_node$arguments = node.arguments) !== null && _node$arguments !== void 0 + ? _node$arguments + : []; + const argNodeMap = keyMap(argumentNodes, (arg) => arg.name.value); + + for (const argDef of def.args) { + const name = argDef.name; + const argType = argDef.type; + const argumentNode = argNodeMap[name]; + + if (!argumentNode) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + 'was not provided.', + { + nodes: node, + }, + ); + } + + continue; + } + + const valueNode = argumentNode.value; + let isNull = valueNode.kind === Kind.NULL; + + if (valueNode.kind === Kind.VARIABLE) { + const variableName = valueNode.name.value; + + if ( + variableValues == null || + !hasOwnProperty(variableValues, variableName) + ) { + if (argDef.defaultValue !== undefined) { + coercedValues[name] = argDef.defaultValue; + } else if (isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of required type "${inspect(argType)}" ` + + `was provided the variable "$${variableName}" which was not provided a runtime value.`, + { + nodes: valueNode, + }, + ); + } + + continue; + } + + isNull = variableValues[variableName] == null; + } + + if (isNull && isNonNullType(argType)) { + throw new GraphQLError( + `Argument "${name}" of non-null type "${inspect(argType)}" ` + + 'must not be null.', + { + nodes: valueNode, + }, + ); + } + + const coercedValue = valueFromAST(valueNode, argType, variableValues); + + if (coercedValue === undefined) { + // Note: ValuesOfCorrectTypeRule validation should catch this before + // execution. This is a runtime check to ensure execution does not + // continue with an invalid argument value. + throw new GraphQLError( + `Argument "${name}" has invalid value ${print(valueNode)}.`, + { + nodes: valueNode, + }, + ); + } + + coercedValues[name] = coercedValue; + } + + return { ...coercedValues }; +} +/** + * AST node shape accepted by getDirectiveValues. + * @internal + */ + +/** + * Prepares an object map of argument values given a directive definition + * and a AST node which may contain directives. Optionally also accepts a map + * of variable values. + * + * If the directive does not exist on the node, returns undefined. + * + * Note: Returned value is a plain Object with a prototype, since it is + * exposed to user code. Care should be taken to not pull values from the + * Object prototype. + * @param directiveDef - The directive definition whose arguments should be coerced. + * @param node - The AST node to inspect. + * @param variableValues - The runtime variable values keyed by variable name. + * @returns Coerced directive argument values keyed by argument name. + * @example + * ```ts + * // Read literal directive arguments from a node. + * import { parse } from 'graphql/language'; + * import { GraphQLSkipDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('{ name @skip(if: true) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLSkipDirective, fieldNode); // => { if: true } + * ``` + * @example + * ```ts + * // This variant resolves directive arguments from variables and handles absent directives. + * import { parse } from 'graphql/language'; + * import { GraphQLIncludeDirective } from 'graphql/type'; + * import { getDirectiveValues } from 'graphql/execution'; + * + * const document = parse('query ($includeName: Boolean!) { name @include(if: $includeName) }'); + * const fieldNode = document.definitions[0].selectionSet.selections[0]; + * + * getDirectiveValues(GraphQLIncludeDirective, fieldNode, { + * includeName: false, + * }); // => { if: false } + * getDirectiveValues(GraphQLIncludeDirective, { directives: [] }); // => undefined + * ``` + */ +export function getDirectiveValues(directiveDef, node, variableValues) { + var _node$directives; + + const directiveNode = + (_node$directives = node.directives) === null || _node$directives === void 0 + ? void 0 + : _node$directives.find( + (directive) => directive.name.value === directiveDef.name, + ); + + if (directiveNode) { + return getArgumentValues(directiveDef, directiveNode, variableValues); + } +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/graphql.d.ts b/node_modules/graphql/graphql.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..43e5493613142d7169a30180510a1bcf01b3eae4 --- /dev/null +++ b/node_modules/graphql/graphql.d.ts @@ -0,0 +1,189 @@ +import type { Maybe } from './jsutils/Maybe'; +import type { Source } from './language/source'; +import type { + GraphQLFieldResolver, + GraphQLTypeResolver, +} from './type/definition'; +import type { GraphQLSchema } from './type/schema'; +import type { ExecutionResult } from './execution/execute'; +/** + * Describes the input object accepted by `graphql` and `graphqlSync`. + * + * These arguments describe the full parse, validate, and execute lifecycle for + * a GraphQL request. + * @category Request Pipeline + */ +export interface GraphQLArgs { + /** The GraphQL type system to use when validating and executing a query. */ + schema: GraphQLSchema; + /** + * A GraphQL language-formatted string or source object representing the + * requested operation. + */ + source: string | Source; + /** + * The value provided as the first argument to resolver functions on the top + * level type, such as the query object type. + */ + rootValue?: unknown; + /** + * Application context value passed to every resolver. + * + * Use this for shared request data such as the currently logged in user and + * connections to databases or other services. + */ + contextValue?: unknown; + /** A mapping of variable name to runtime value for variables defined by the operation. */ + variableValues?: Maybe<{ + readonly [variable: string]: unknown; + }>; + /** + * The operation to execute when the source contains multiple possible + * operations. This can be omitted when the source contains only one operation. + */ + operationName?: Maybe; + /** + * A resolver function to use when one is not provided by the schema. + * + * If not provided, the default field resolver is used, which looks for a value + * or method on the source value with the field's name. + */ + fieldResolver?: Maybe>; + /** + * A type resolver function to use when none is provided by the schema. + * + * If not provided, the default type resolver is used, which looks for a + * `__typename` field or alternatively calls the `isTypeOf` method. + */ + typeResolver?: Maybe>; +} +/** + * Parses, validates, and executes a GraphQL document against a schema. + * + * This is the primary entry point for fulfilling GraphQL operations. Use this + * when you want a single-call request lifecycle that returns a promise in all + * cases. + * + * More sophisticated GraphQL servers, such as those which persist queries, may + * wish to separate the validation and execution phases to a static-time tooling + * step and a server runtime step. + * @param args - Request execution arguments, including schema and source. + * @returns A promise that resolves to an execution result or validation errors. + * @example + * ```ts + * // Execute a complete asynchronous request with variables. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await graphql({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await graphql({ + * schema, + * source: '{ viewer { __typename name } }', + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * fieldResolver: (source, _args, context, info) => { + * context.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @category Request Pipeline + */ +export declare function graphql(args: GraphQLArgs): Promise; +/** + * Parses, validates, and executes a GraphQL document synchronously. + * + * This function guarantees that execution completes synchronously, or throws an + * error, assuming that all field resolvers are also synchronous. It throws when + * any resolver returns a promise. + * @param args - Request execution arguments, including schema and source. + * @returns Completed execution output, or request errors if parsing or + * validation fails. + * @example + * ```ts + * // Execute a complete synchronous request with variables. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant uses a synchronous custom field resolver and context. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: '{ greeting }', + * fieldResolver: (_source, _args, contextValue) => { + * return contextValue.defaultGreeting; + * }, + * contextValue: { defaultGreeting: 'Hello' }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @category Request Pipeline + */ +export declare function graphqlSync(args: GraphQLArgs): ExecutionResult; diff --git a/node_modules/graphql/graphql.js b/node_modules/graphql/graphql.js new file mode 100644 index 0000000000000000000000000000000000000000..7078b3aa3067b609b421dea6b0dca68c91542a19 --- /dev/null +++ b/node_modules/graphql/graphql.js @@ -0,0 +1,218 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.graphql = graphql; +exports.graphqlSync = graphqlSync; + +var _devAssert = require('./jsutils/devAssert.js'); + +var _isPromise = require('./jsutils/isPromise.js'); + +var _parser = require('./language/parser.js'); + +var _validate = require('./type/validate.js'); + +var _validate2 = require('./validation/validate.js'); + +var _execute = require('./execution/execute.js'); + +/** + * Parses, validates, and executes a GraphQL document against a schema. + * + * This is the primary entry point for fulfilling GraphQL operations. Use this + * when you want a single-call request lifecycle that returns a promise in all + * cases. + * + * More sophisticated GraphQL servers, such as those which persist queries, may + * wish to separate the validation and execution phases to a static-time tooling + * step and a server runtime step. + * @param args - Request execution arguments, including schema and source. + * @returns A promise that resolves to an execution result or validation errors. + * @example + * ```ts + * // Execute a complete asynchronous request with variables. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await graphql({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await graphql({ + * schema, + * source: '{ viewer { __typename name } }', + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * fieldResolver: (source, _args, context, info) => { + * context.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @category Request Pipeline + */ +function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise((resolve) => resolve(graphqlImpl(args))); +} +/** + * Parses, validates, and executes a GraphQL document synchronously. + * + * This function guarantees that execution completes synchronously, or throws an + * error, assuming that all field resolvers are also synchronous. It throws when + * any resolver returns a promise. + * @param args - Request execution arguments, including schema and source. + * @returns Completed execution output, or request errors if parsing or + * validation fails. + * @example + * ```ts + * // Execute a complete synchronous request with variables. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant uses a synchronous custom field resolver and context. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: '{ greeting }', + * fieldResolver: (_source, _args, contextValue) => { + * return contextValue.defaultGreeting; + * }, + * contextValue: { defaultGreeting: 'Hello' }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @category Request Pipeline + */ + +function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. + + if ((0, _isPromise.isPromise)(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + (0, _devAssert.devAssert)( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; // Validate Schema + + const schemaValidationErrors = (0, _validate.validateSchema)(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors, + }; + } // Parse + + let document; + + try { + document = (0, _parser.parse)(source); + } catch (syntaxError) { + return { + errors: [syntaxError], + }; + } // Validate + + const validationErrors = (0, _validate2.validate)(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors, + }; + } // Execute + + return (0, _execute.execute)({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); +} diff --git a/node_modules/graphql/graphql.mjs b/node_modules/graphql/graphql.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1b418a0c94aa3b89d49da0f13ee56a7f3bbdae2d --- /dev/null +++ b/node_modules/graphql/graphql.mjs @@ -0,0 +1,212 @@ +import { devAssert } from './jsutils/devAssert.mjs'; +import { isPromise } from './jsutils/isPromise.mjs'; +import { parse } from './language/parser.mjs'; +import { validateSchema } from './type/validate.mjs'; +import { validate } from './validation/validate.mjs'; +import { execute } from './execution/execute.mjs'; +/** + * Describes the input object accepted by `graphql` and `graphqlSync`. + * + * These arguments describe the full parse, validate, and execute lifecycle for + * a GraphQL request. + * @category Request Pipeline + */ + +/** + * Parses, validates, and executes a GraphQL document against a schema. + * + * This is the primary entry point for fulfilling GraphQL operations. Use this + * when you want a single-call request lifecycle that returns a promise in all + * cases. + * + * More sophisticated GraphQL servers, such as those which persist queries, may + * wish to separate the validation and execution phases to a static-time tooling + * step and a server runtime step. + * @param args - Request execution arguments, including schema and source. + * @returns A promise that resolves to an execution result or validation errors. + * @example + * ```ts + * // Execute a complete asynchronous request with variables. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = await graphql({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant supplies context plus custom field and type resolvers. + * import { graphql, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * interface Named { + * name: String! + * } + * + * type User implements Named { + * name: String! + * } + * + * type Query { + * viewer: Named + * } + * `); + * + * const result = await graphql({ + * schema, + * source: '{ viewer { __typename name } }', + * rootValue: { viewer: { kind: 'user', name: 'Ada' } }, + * contextValue: { locale: 'en' }, + * fieldResolver: (source, _args, context, info) => { + * context.locale; // => 'en' + * return source[info.fieldName]; + * }, + * typeResolver: (value) => { + * return value.kind === 'user' ? 'User' : undefined; + * }, + * }); + * + * result; // => { data: { viewer: { __typename: 'User', name: 'Ada' } } } + * ``` + * @category Request Pipeline + */ +export function graphql(args) { + // Always return a Promise for a consistent API. + return new Promise((resolve) => resolve(graphqlImpl(args))); +} +/** + * Parses, validates, and executes a GraphQL document synchronously. + * + * This function guarantees that execution completes synchronously, or throws an + * error, assuming that all field resolvers are also synchronous. It throws when + * any resolver returns a promise. + * @param args - Request execution arguments, including schema and source. + * @returns Completed execution output, or request errors if parsing or + * validation fails. + * @example + * ```ts + * // Execute a complete synchronous request with variables. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String!): String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: 'query SayHello($name: String!) { greeting(name: $name) }', + * rootValue: { + * greeting: ({ name }) => `Hello, ${name}!`, + * }, + * variableValues: { name: 'Ada' }, + * operationName: 'SayHello', + * }); + * + * result; // => { data: { greeting: 'Hello, Ada!' } } + * ``` + * @example + * ```ts + * // This variant uses a synchronous custom field resolver and context. + * import { graphqlSync, buildSchema } from 'graphql'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const result = graphqlSync({ + * schema, + * source: '{ greeting }', + * fieldResolver: (_source, _args, contextValue) => { + * return contextValue.defaultGreeting; + * }, + * contextValue: { defaultGreeting: 'Hello' }, + * }); + * + * result; // => { data: { greeting: 'Hello' } } + * ``` + * @category Request Pipeline + */ + +export function graphqlSync(args) { + const result = graphqlImpl(args); // Assert that the execution was synchronous. + + if (isPromise(result)) { + throw new Error('GraphQL execution failed to complete synchronously.'); + } + + return result; +} + +function graphqlImpl(args) { + // Temporary for v15 to v16 migration. Remove in v17 + arguments.length < 2 || + devAssert( + false, + 'graphql@16 dropped long-deprecated support for positional arguments, please pass an object instead.', + ); + const { + schema, + source, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + } = args; // Validate Schema + + const schemaValidationErrors = validateSchema(schema); + + if (schemaValidationErrors.length > 0) { + return { + errors: schemaValidationErrors, + }; + } // Parse + + let document; + + try { + document = parse(source); + } catch (syntaxError) { + return { + errors: [syntaxError], + }; + } // Validate + + const validationErrors = validate(schema, document); + + if (validationErrors.length > 0) { + return { + errors: validationErrors, + }; + } // Execute + + return execute({ + schema, + document, + rootValue, + contextValue, + variableValues, + operationName, + fieldResolver, + typeResolver, + }); +} diff --git a/node_modules/graphql/index.d.ts b/node_modules/graphql/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1921338314d7b85527989f7b050d8fcbf98f7fbc --- /dev/null +++ b/node_modules/graphql/index.d.ts @@ -0,0 +1,423 @@ +/** + * The root `graphql` package re-exports the public GraphQL.js API from its + * submodules and provides the high-level request pipeline helpers defined in + * this module. + * + * You can import public exports from GraphQL.js modules through the root + * `graphql` package or through their module-specific entry point. For example, + * these two references resolve to the same `parse` function: + * + * ```ts + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + * ``` + * + * Use the root package when you want a single import surface, or use submodules + * such as `graphql/language`, `graphql/type`, `graphql/execution`, and + * `graphql/utilities` when you want module-focused imports. This module also + * defines root-only APIs, such as request pipeline helpers and version + * metadata, that do not belong to a narrower submodule. + * @packageDocumentation + */ +export { version, versionInfo } from './version'; +export type { GraphQLArgs } from './graphql'; +export { graphql, graphqlSync } from './graphql'; +export { + resolveObjMapThunk, + resolveReadonlyArrayThunk, + GraphQLSchema, + GraphQLDirective, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + GRAPHQL_MAX_INT, + GRAPHQL_MIN_INT, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, + TypeKind, + DEFAULT_DEPRECATION_REASON, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, + isSchema, + isDirective, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + isSpecifiedScalarType, + isIntrospectionType, + isSpecifiedDirective, + assertSchema, + assertDirective, + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + getNullableType, + getNamedType, + validateSchema, + assertValidSchema, + assertName, + assertEnumValueName, +} from './type/index'; +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + GraphQLNamedInputType, + GraphQLNamedOutputType, + ThunkReadonlyArray, + ThunkObjMap, + GraphQLSchemaConfig, + GraphQLSchemaExtensions, + GraphQLDirectiveConfig, + GraphQLDirectiveExtensions, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLArgumentExtensions, + GraphQLEnumTypeConfig, + GraphQLEnumTypeExtensions, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLEnumValueExtensions, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldExtensions, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldExtensions, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInputObjectTypeExtensions, + GraphQLInterfaceTypeConfig, + GraphQLInterfaceTypeExtensions, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLObjectTypeExtensions, + GraphQLResolveInfo, + ResponsePath, + GraphQLScalarTypeConfig, + GraphQLScalarTypeExtensions, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLUnionTypeExtensions, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './type/index'; +export { + Token, + Source, + Location, + OperationTypeNode, + getLocation, + printLocation, + printSourceLocation, + Lexer, + TokenKind, + parse, + parseValue, + parseConstValue, + parseType, + parseSchemaCoordinate, + print, + visit, + visitInParallel, + getVisitFn, + getEnterLeaveForKind, + BREAK, + Kind, + DirectiveLocation, + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isConstValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, + isSchemaCoordinateNode, +} from './language/index'; +export type { + ParseOptions, + SourceLocation, + TokenKindEnum, + KindEnum, + DirectiveLocationEnum, + ASTVisitor, + ASTVisitFn, + ASTVisitorKeyMap, + ASTNode, + ASTKindToNode, + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + ConstArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + ConstValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ConstListValueNode, + ObjectValueNode, + ConstObjectValueNode, + ObjectFieldNode, + ConstObjectFieldNode, + DirectiveNode, + ConstDirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + DirectiveExtensionNode, + SchemaCoordinateNode, + TypeCoordinateNode, + MemberCoordinateNode, + ArgumentCoordinateNode, + DirectiveCoordinateNode, + DirectiveArgumentCoordinateNode, +} from './language/index'; +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, + responsePathAsArray, + getArgumentValues, + getVariableValues, + getDirectiveValues, + subscribe, + createSourceEventStream, +} from './execution/index'; +export type { + ExecutionArgs, + ExecutionResult, + FormattedExecutionResult, +} from './execution/index'; +export type { SubscriptionArgs } from './subscription/index'; +export { + validate, + ValidationContext, + specifiedRules, + recommendedRules, + ExecutableDefinitionsRule, + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedRequiredArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + ValuesOfCorrectTypeRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, + MaxIntrospectionDepthRule, + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueArgumentDefinitionNamesRule, + UniqueDirectiveNamesRule, + PossibleTypeExtensionsRule, + NoDeprecatedCustomRule, + NoSchemaIntrospectionCustomRule, +} from './validation/index'; +export type { ValidationRule } from './validation/index'; +export { + GraphQLError, + syntaxError, + locatedError, + printError, + formatError, +} from './error/index'; +export type { + GraphQLErrorOptions, + GraphQLFormattedError, + GraphQLErrorExtensions, + GraphQLFormattedErrorExtensions, +} from './error/index'; +export { + getIntrospectionQuery, + getOperationAST, + getOperationRootType, + introspectionFromSchema, + buildClientSchema, + buildASTSchema, + buildSchema, + extendSchema, + lexicographicSortSchema, + printSchema, + printType, + printIntrospectionSchema, + typeFromAST, + valueFromAST, + valueFromASTUntyped, + astFromValue, + TypeInfo, + visitWithTypeInfo, + coerceInputValue, + concatAST, + separateOperations, + stripIgnoredCharacters, + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, + assertValidName, + isValidNameError, + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, + resolveSchemaCoordinate, + resolveASTSchemaCoordinate, +} from './utilities/index'; +export type { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, + BuildSchemaOptions, + BreakingChange, + DangerousChange, + TypedQueryDocumentNode, + ResolvedSchemaElement, +} from './utilities/index'; diff --git a/node_modules/graphql/index.js b/node_modules/graphql/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fef6b6e8a8a39ec4460763ec01e12bab8f11f437 --- /dev/null +++ b/node_modules/graphql/index.js @@ -0,0 +1,1311 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'BREAK', { + enumerable: true, + get: function () { + return _index2.BREAK; + }, +}); +Object.defineProperty(exports, 'BreakingChangeType', { + enumerable: true, + get: function () { + return _index6.BreakingChangeType; + }, +}); +Object.defineProperty(exports, 'DEFAULT_DEPRECATION_REASON', { + enumerable: true, + get: function () { + return _index.DEFAULT_DEPRECATION_REASON; + }, +}); +Object.defineProperty(exports, 'DangerousChangeType', { + enumerable: true, + get: function () { + return _index6.DangerousChangeType; + }, +}); +Object.defineProperty(exports, 'DirectiveLocation', { + enumerable: true, + get: function () { + return _index2.DirectiveLocation; + }, +}); +Object.defineProperty(exports, 'ExecutableDefinitionsRule', { + enumerable: true, + get: function () { + return _index4.ExecutableDefinitionsRule; + }, +}); +Object.defineProperty(exports, 'FieldsOnCorrectTypeRule', { + enumerable: true, + get: function () { + return _index4.FieldsOnCorrectTypeRule; + }, +}); +Object.defineProperty(exports, 'FragmentsOnCompositeTypesRule', { + enumerable: true, + get: function () { + return _index4.FragmentsOnCompositeTypesRule; + }, +}); +Object.defineProperty(exports, 'GRAPHQL_MAX_INT', { + enumerable: true, + get: function () { + return _index.GRAPHQL_MAX_INT; + }, +}); +Object.defineProperty(exports, 'GRAPHQL_MIN_INT', { + enumerable: true, + get: function () { + return _index.GRAPHQL_MIN_INT; + }, +}); +Object.defineProperty(exports, 'GraphQLBoolean', { + enumerable: true, + get: function () { + return _index.GraphQLBoolean; + }, +}); +Object.defineProperty(exports, 'GraphQLDeprecatedDirective', { + enumerable: true, + get: function () { + return _index.GraphQLDeprecatedDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLDirective', { + enumerable: true, + get: function () { + return _index.GraphQLDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLEnumType', { + enumerable: true, + get: function () { + return _index.GraphQLEnumType; + }, +}); +Object.defineProperty(exports, 'GraphQLError', { + enumerable: true, + get: function () { + return _index5.GraphQLError; + }, +}); +Object.defineProperty(exports, 'GraphQLFloat', { + enumerable: true, + get: function () { + return _index.GraphQLFloat; + }, +}); +Object.defineProperty(exports, 'GraphQLID', { + enumerable: true, + get: function () { + return _index.GraphQLID; + }, +}); +Object.defineProperty(exports, 'GraphQLIncludeDirective', { + enumerable: true, + get: function () { + return _index.GraphQLIncludeDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLInputObjectType', { + enumerable: true, + get: function () { + return _index.GraphQLInputObjectType; + }, +}); +Object.defineProperty(exports, 'GraphQLInt', { + enumerable: true, + get: function () { + return _index.GraphQLInt; + }, +}); +Object.defineProperty(exports, 'GraphQLInterfaceType', { + enumerable: true, + get: function () { + return _index.GraphQLInterfaceType; + }, +}); +Object.defineProperty(exports, 'GraphQLList', { + enumerable: true, + get: function () { + return _index.GraphQLList; + }, +}); +Object.defineProperty(exports, 'GraphQLNonNull', { + enumerable: true, + get: function () { + return _index.GraphQLNonNull; + }, +}); +Object.defineProperty(exports, 'GraphQLObjectType', { + enumerable: true, + get: function () { + return _index.GraphQLObjectType; + }, +}); +Object.defineProperty(exports, 'GraphQLOneOfDirective', { + enumerable: true, + get: function () { + return _index.GraphQLOneOfDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLScalarType', { + enumerable: true, + get: function () { + return _index.GraphQLScalarType; + }, +}); +Object.defineProperty(exports, 'GraphQLSchema', { + enumerable: true, + get: function () { + return _index.GraphQLSchema; + }, +}); +Object.defineProperty(exports, 'GraphQLSkipDirective', { + enumerable: true, + get: function () { + return _index.GraphQLSkipDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLSpecifiedByDirective', { + enumerable: true, + get: function () { + return _index.GraphQLSpecifiedByDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLString', { + enumerable: true, + get: function () { + return _index.GraphQLString; + }, +}); +Object.defineProperty(exports, 'GraphQLUnionType', { + enumerable: true, + get: function () { + return _index.GraphQLUnionType; + }, +}); +Object.defineProperty(exports, 'Kind', { + enumerable: true, + get: function () { + return _index2.Kind; + }, +}); +Object.defineProperty(exports, 'KnownArgumentNamesRule', { + enumerable: true, + get: function () { + return _index4.KnownArgumentNamesRule; + }, +}); +Object.defineProperty(exports, 'KnownDirectivesRule', { + enumerable: true, + get: function () { + return _index4.KnownDirectivesRule; + }, +}); +Object.defineProperty(exports, 'KnownFragmentNamesRule', { + enumerable: true, + get: function () { + return _index4.KnownFragmentNamesRule; + }, +}); +Object.defineProperty(exports, 'KnownTypeNamesRule', { + enumerable: true, + get: function () { + return _index4.KnownTypeNamesRule; + }, +}); +Object.defineProperty(exports, 'Lexer', { + enumerable: true, + get: function () { + return _index2.Lexer; + }, +}); +Object.defineProperty(exports, 'Location', { + enumerable: true, + get: function () { + return _index2.Location; + }, +}); +Object.defineProperty(exports, 'LoneAnonymousOperationRule', { + enumerable: true, + get: function () { + return _index4.LoneAnonymousOperationRule; + }, +}); +Object.defineProperty(exports, 'LoneSchemaDefinitionRule', { + enumerable: true, + get: function () { + return _index4.LoneSchemaDefinitionRule; + }, +}); +Object.defineProperty(exports, 'MaxIntrospectionDepthRule', { + enumerable: true, + get: function () { + return _index4.MaxIntrospectionDepthRule; + }, +}); +Object.defineProperty(exports, 'NoDeprecatedCustomRule', { + enumerable: true, + get: function () { + return _index4.NoDeprecatedCustomRule; + }, +}); +Object.defineProperty(exports, 'NoFragmentCyclesRule', { + enumerable: true, + get: function () { + return _index4.NoFragmentCyclesRule; + }, +}); +Object.defineProperty(exports, 'NoSchemaIntrospectionCustomRule', { + enumerable: true, + get: function () { + return _index4.NoSchemaIntrospectionCustomRule; + }, +}); +Object.defineProperty(exports, 'NoUndefinedVariablesRule', { + enumerable: true, + get: function () { + return _index4.NoUndefinedVariablesRule; + }, +}); +Object.defineProperty(exports, 'NoUnusedFragmentsRule', { + enumerable: true, + get: function () { + return _index4.NoUnusedFragmentsRule; + }, +}); +Object.defineProperty(exports, 'NoUnusedVariablesRule', { + enumerable: true, + get: function () { + return _index4.NoUnusedVariablesRule; + }, +}); +Object.defineProperty(exports, 'OperationTypeNode', { + enumerable: true, + get: function () { + return _index2.OperationTypeNode; + }, +}); +Object.defineProperty(exports, 'OverlappingFieldsCanBeMergedRule', { + enumerable: true, + get: function () { + return _index4.OverlappingFieldsCanBeMergedRule; + }, +}); +Object.defineProperty(exports, 'PossibleFragmentSpreadsRule', { + enumerable: true, + get: function () { + return _index4.PossibleFragmentSpreadsRule; + }, +}); +Object.defineProperty(exports, 'PossibleTypeExtensionsRule', { + enumerable: true, + get: function () { + return _index4.PossibleTypeExtensionsRule; + }, +}); +Object.defineProperty(exports, 'ProvidedRequiredArgumentsRule', { + enumerable: true, + get: function () { + return _index4.ProvidedRequiredArgumentsRule; + }, +}); +Object.defineProperty(exports, 'ScalarLeafsRule', { + enumerable: true, + get: function () { + return _index4.ScalarLeafsRule; + }, +}); +Object.defineProperty(exports, 'SchemaMetaFieldDef', { + enumerable: true, + get: function () { + return _index.SchemaMetaFieldDef; + }, +}); +Object.defineProperty(exports, 'SingleFieldSubscriptionsRule', { + enumerable: true, + get: function () { + return _index4.SingleFieldSubscriptionsRule; + }, +}); +Object.defineProperty(exports, 'Source', { + enumerable: true, + get: function () { + return _index2.Source; + }, +}); +Object.defineProperty(exports, 'Token', { + enumerable: true, + get: function () { + return _index2.Token; + }, +}); +Object.defineProperty(exports, 'TokenKind', { + enumerable: true, + get: function () { + return _index2.TokenKind; + }, +}); +Object.defineProperty(exports, 'TypeInfo', { + enumerable: true, + get: function () { + return _index6.TypeInfo; + }, +}); +Object.defineProperty(exports, 'TypeKind', { + enumerable: true, + get: function () { + return _index.TypeKind; + }, +}); +Object.defineProperty(exports, 'TypeMetaFieldDef', { + enumerable: true, + get: function () { + return _index.TypeMetaFieldDef; + }, +}); +Object.defineProperty(exports, 'TypeNameMetaFieldDef', { + enumerable: true, + get: function () { + return _index.TypeNameMetaFieldDef; + }, +}); +Object.defineProperty(exports, 'UniqueArgumentDefinitionNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueArgumentDefinitionNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueArgumentNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueArgumentNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueDirectiveNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueDirectiveNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueDirectivesPerLocationRule', { + enumerable: true, + get: function () { + return _index4.UniqueDirectivesPerLocationRule; + }, +}); +Object.defineProperty(exports, 'UniqueEnumValueNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueEnumValueNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueFieldDefinitionNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueFieldDefinitionNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueFragmentNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueFragmentNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueInputFieldNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueInputFieldNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueOperationNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueOperationNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueOperationTypesRule', { + enumerable: true, + get: function () { + return _index4.UniqueOperationTypesRule; + }, +}); +Object.defineProperty(exports, 'UniqueTypeNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueTypeNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueVariableNamesRule', { + enumerable: true, + get: function () { + return _index4.UniqueVariableNamesRule; + }, +}); +Object.defineProperty(exports, 'ValidationContext', { + enumerable: true, + get: function () { + return _index4.ValidationContext; + }, +}); +Object.defineProperty(exports, 'ValuesOfCorrectTypeRule', { + enumerable: true, + get: function () { + return _index4.ValuesOfCorrectTypeRule; + }, +}); +Object.defineProperty(exports, 'VariablesAreInputTypesRule', { + enumerable: true, + get: function () { + return _index4.VariablesAreInputTypesRule; + }, +}); +Object.defineProperty(exports, 'VariablesInAllowedPositionRule', { + enumerable: true, + get: function () { + return _index4.VariablesInAllowedPositionRule; + }, +}); +Object.defineProperty(exports, '__Directive', { + enumerable: true, + get: function () { + return _index.__Directive; + }, +}); +Object.defineProperty(exports, '__DirectiveLocation', { + enumerable: true, + get: function () { + return _index.__DirectiveLocation; + }, +}); +Object.defineProperty(exports, '__EnumValue', { + enumerable: true, + get: function () { + return _index.__EnumValue; + }, +}); +Object.defineProperty(exports, '__Field', { + enumerable: true, + get: function () { + return _index.__Field; + }, +}); +Object.defineProperty(exports, '__InputValue', { + enumerable: true, + get: function () { + return _index.__InputValue; + }, +}); +Object.defineProperty(exports, '__Schema', { + enumerable: true, + get: function () { + return _index.__Schema; + }, +}); +Object.defineProperty(exports, '__Type', { + enumerable: true, + get: function () { + return _index.__Type; + }, +}); +Object.defineProperty(exports, '__TypeKind', { + enumerable: true, + get: function () { + return _index.__TypeKind; + }, +}); +Object.defineProperty(exports, 'assertAbstractType', { + enumerable: true, + get: function () { + return _index.assertAbstractType; + }, +}); +Object.defineProperty(exports, 'assertCompositeType', { + enumerable: true, + get: function () { + return _index.assertCompositeType; + }, +}); +Object.defineProperty(exports, 'assertDirective', { + enumerable: true, + get: function () { + return _index.assertDirective; + }, +}); +Object.defineProperty(exports, 'assertEnumType', { + enumerable: true, + get: function () { + return _index.assertEnumType; + }, +}); +Object.defineProperty(exports, 'assertEnumValueName', { + enumerable: true, + get: function () { + return _index.assertEnumValueName; + }, +}); +Object.defineProperty(exports, 'assertInputObjectType', { + enumerable: true, + get: function () { + return _index.assertInputObjectType; + }, +}); +Object.defineProperty(exports, 'assertInputType', { + enumerable: true, + get: function () { + return _index.assertInputType; + }, +}); +Object.defineProperty(exports, 'assertInterfaceType', { + enumerable: true, + get: function () { + return _index.assertInterfaceType; + }, +}); +Object.defineProperty(exports, 'assertLeafType', { + enumerable: true, + get: function () { + return _index.assertLeafType; + }, +}); +Object.defineProperty(exports, 'assertListType', { + enumerable: true, + get: function () { + return _index.assertListType; + }, +}); +Object.defineProperty(exports, 'assertName', { + enumerable: true, + get: function () { + return _index.assertName; + }, +}); +Object.defineProperty(exports, 'assertNamedType', { + enumerable: true, + get: function () { + return _index.assertNamedType; + }, +}); +Object.defineProperty(exports, 'assertNonNullType', { + enumerable: true, + get: function () { + return _index.assertNonNullType; + }, +}); +Object.defineProperty(exports, 'assertNullableType', { + enumerable: true, + get: function () { + return _index.assertNullableType; + }, +}); +Object.defineProperty(exports, 'assertObjectType', { + enumerable: true, + get: function () { + return _index.assertObjectType; + }, +}); +Object.defineProperty(exports, 'assertOutputType', { + enumerable: true, + get: function () { + return _index.assertOutputType; + }, +}); +Object.defineProperty(exports, 'assertScalarType', { + enumerable: true, + get: function () { + return _index.assertScalarType; + }, +}); +Object.defineProperty(exports, 'assertSchema', { + enumerable: true, + get: function () { + return _index.assertSchema; + }, +}); +Object.defineProperty(exports, 'assertType', { + enumerable: true, + get: function () { + return _index.assertType; + }, +}); +Object.defineProperty(exports, 'assertUnionType', { + enumerable: true, + get: function () { + return _index.assertUnionType; + }, +}); +Object.defineProperty(exports, 'assertValidName', { + enumerable: true, + get: function () { + return _index6.assertValidName; + }, +}); +Object.defineProperty(exports, 'assertValidSchema', { + enumerable: true, + get: function () { + return _index.assertValidSchema; + }, +}); +Object.defineProperty(exports, 'assertWrappingType', { + enumerable: true, + get: function () { + return _index.assertWrappingType; + }, +}); +Object.defineProperty(exports, 'astFromValue', { + enumerable: true, + get: function () { + return _index6.astFromValue; + }, +}); +Object.defineProperty(exports, 'buildASTSchema', { + enumerable: true, + get: function () { + return _index6.buildASTSchema; + }, +}); +Object.defineProperty(exports, 'buildClientSchema', { + enumerable: true, + get: function () { + return _index6.buildClientSchema; + }, +}); +Object.defineProperty(exports, 'buildSchema', { + enumerable: true, + get: function () { + return _index6.buildSchema; + }, +}); +Object.defineProperty(exports, 'coerceInputValue', { + enumerable: true, + get: function () { + return _index6.coerceInputValue; + }, +}); +Object.defineProperty(exports, 'concatAST', { + enumerable: true, + get: function () { + return _index6.concatAST; + }, +}); +Object.defineProperty(exports, 'createSourceEventStream', { + enumerable: true, + get: function () { + return _index3.createSourceEventStream; + }, +}); +Object.defineProperty(exports, 'defaultFieldResolver', { + enumerable: true, + get: function () { + return _index3.defaultFieldResolver; + }, +}); +Object.defineProperty(exports, 'defaultTypeResolver', { + enumerable: true, + get: function () { + return _index3.defaultTypeResolver; + }, +}); +Object.defineProperty(exports, 'doTypesOverlap', { + enumerable: true, + get: function () { + return _index6.doTypesOverlap; + }, +}); +Object.defineProperty(exports, 'execute', { + enumerable: true, + get: function () { + return _index3.execute; + }, +}); +Object.defineProperty(exports, 'executeSync', { + enumerable: true, + get: function () { + return _index3.executeSync; + }, +}); +Object.defineProperty(exports, 'extendSchema', { + enumerable: true, + get: function () { + return _index6.extendSchema; + }, +}); +Object.defineProperty(exports, 'findBreakingChanges', { + enumerable: true, + get: function () { + return _index6.findBreakingChanges; + }, +}); +Object.defineProperty(exports, 'findDangerousChanges', { + enumerable: true, + get: function () { + return _index6.findDangerousChanges; + }, +}); +Object.defineProperty(exports, 'formatError', { + enumerable: true, + get: function () { + return _index5.formatError; + }, +}); +Object.defineProperty(exports, 'getArgumentValues', { + enumerable: true, + get: function () { + return _index3.getArgumentValues; + }, +}); +Object.defineProperty(exports, 'getDirectiveValues', { + enumerable: true, + get: function () { + return _index3.getDirectiveValues; + }, +}); +Object.defineProperty(exports, 'getEnterLeaveForKind', { + enumerable: true, + get: function () { + return _index2.getEnterLeaveForKind; + }, +}); +Object.defineProperty(exports, 'getIntrospectionQuery', { + enumerable: true, + get: function () { + return _index6.getIntrospectionQuery; + }, +}); +Object.defineProperty(exports, 'getLocation', { + enumerable: true, + get: function () { + return _index2.getLocation; + }, +}); +Object.defineProperty(exports, 'getNamedType', { + enumerable: true, + get: function () { + return _index.getNamedType; + }, +}); +Object.defineProperty(exports, 'getNullableType', { + enumerable: true, + get: function () { + return _index.getNullableType; + }, +}); +Object.defineProperty(exports, 'getOperationAST', { + enumerable: true, + get: function () { + return _index6.getOperationAST; + }, +}); +Object.defineProperty(exports, 'getOperationRootType', { + enumerable: true, + get: function () { + return _index6.getOperationRootType; + }, +}); +Object.defineProperty(exports, 'getVariableValues', { + enumerable: true, + get: function () { + return _index3.getVariableValues; + }, +}); +Object.defineProperty(exports, 'getVisitFn', { + enumerable: true, + get: function () { + return _index2.getVisitFn; + }, +}); +Object.defineProperty(exports, 'graphql', { + enumerable: true, + get: function () { + return _graphql.graphql; + }, +}); +Object.defineProperty(exports, 'graphqlSync', { + enumerable: true, + get: function () { + return _graphql.graphqlSync; + }, +}); +Object.defineProperty(exports, 'introspectionFromSchema', { + enumerable: true, + get: function () { + return _index6.introspectionFromSchema; + }, +}); +Object.defineProperty(exports, 'introspectionTypes', { + enumerable: true, + get: function () { + return _index.introspectionTypes; + }, +}); +Object.defineProperty(exports, 'isAbstractType', { + enumerable: true, + get: function () { + return _index.isAbstractType; + }, +}); +Object.defineProperty(exports, 'isCompositeType', { + enumerable: true, + get: function () { + return _index.isCompositeType; + }, +}); +Object.defineProperty(exports, 'isConstValueNode', { + enumerable: true, + get: function () { + return _index2.isConstValueNode; + }, +}); +Object.defineProperty(exports, 'isDefinitionNode', { + enumerable: true, + get: function () { + return _index2.isDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isDirective', { + enumerable: true, + get: function () { + return _index.isDirective; + }, +}); +Object.defineProperty(exports, 'isEnumType', { + enumerable: true, + get: function () { + return _index.isEnumType; + }, +}); +Object.defineProperty(exports, 'isEqualType', { + enumerable: true, + get: function () { + return _index6.isEqualType; + }, +}); +Object.defineProperty(exports, 'isExecutableDefinitionNode', { + enumerable: true, + get: function () { + return _index2.isExecutableDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isInputObjectType', { + enumerable: true, + get: function () { + return _index.isInputObjectType; + }, +}); +Object.defineProperty(exports, 'isInputType', { + enumerable: true, + get: function () { + return _index.isInputType; + }, +}); +Object.defineProperty(exports, 'isInterfaceType', { + enumerable: true, + get: function () { + return _index.isInterfaceType; + }, +}); +Object.defineProperty(exports, 'isIntrospectionType', { + enumerable: true, + get: function () { + return _index.isIntrospectionType; + }, +}); +Object.defineProperty(exports, 'isLeafType', { + enumerable: true, + get: function () { + return _index.isLeafType; + }, +}); +Object.defineProperty(exports, 'isListType', { + enumerable: true, + get: function () { + return _index.isListType; + }, +}); +Object.defineProperty(exports, 'isNamedType', { + enumerable: true, + get: function () { + return _index.isNamedType; + }, +}); +Object.defineProperty(exports, 'isNonNullType', { + enumerable: true, + get: function () { + return _index.isNonNullType; + }, +}); +Object.defineProperty(exports, 'isNullableType', { + enumerable: true, + get: function () { + return _index.isNullableType; + }, +}); +Object.defineProperty(exports, 'isObjectType', { + enumerable: true, + get: function () { + return _index.isObjectType; + }, +}); +Object.defineProperty(exports, 'isOutputType', { + enumerable: true, + get: function () { + return _index.isOutputType; + }, +}); +Object.defineProperty(exports, 'isRequiredArgument', { + enumerable: true, + get: function () { + return _index.isRequiredArgument; + }, +}); +Object.defineProperty(exports, 'isRequiredInputField', { + enumerable: true, + get: function () { + return _index.isRequiredInputField; + }, +}); +Object.defineProperty(exports, 'isScalarType', { + enumerable: true, + get: function () { + return _index.isScalarType; + }, +}); +Object.defineProperty(exports, 'isSchema', { + enumerable: true, + get: function () { + return _index.isSchema; + }, +}); +Object.defineProperty(exports, 'isSchemaCoordinateNode', { + enumerable: true, + get: function () { + return _index2.isSchemaCoordinateNode; + }, +}); +Object.defineProperty(exports, 'isSelectionNode', { + enumerable: true, + get: function () { + return _index2.isSelectionNode; + }, +}); +Object.defineProperty(exports, 'isSpecifiedDirective', { + enumerable: true, + get: function () { + return _index.isSpecifiedDirective; + }, +}); +Object.defineProperty(exports, 'isSpecifiedScalarType', { + enumerable: true, + get: function () { + return _index.isSpecifiedScalarType; + }, +}); +Object.defineProperty(exports, 'isType', { + enumerable: true, + get: function () { + return _index.isType; + }, +}); +Object.defineProperty(exports, 'isTypeDefinitionNode', { + enumerable: true, + get: function () { + return _index2.isTypeDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isTypeExtensionNode', { + enumerable: true, + get: function () { + return _index2.isTypeExtensionNode; + }, +}); +Object.defineProperty(exports, 'isTypeNode', { + enumerable: true, + get: function () { + return _index2.isTypeNode; + }, +}); +Object.defineProperty(exports, 'isTypeSubTypeOf', { + enumerable: true, + get: function () { + return _index6.isTypeSubTypeOf; + }, +}); +Object.defineProperty(exports, 'isTypeSystemDefinitionNode', { + enumerable: true, + get: function () { + return _index2.isTypeSystemDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isTypeSystemExtensionNode', { + enumerable: true, + get: function () { + return _index2.isTypeSystemExtensionNode; + }, +}); +Object.defineProperty(exports, 'isUnionType', { + enumerable: true, + get: function () { + return _index.isUnionType; + }, +}); +Object.defineProperty(exports, 'isValidNameError', { + enumerable: true, + get: function () { + return _index6.isValidNameError; + }, +}); +Object.defineProperty(exports, 'isValueNode', { + enumerable: true, + get: function () { + return _index2.isValueNode; + }, +}); +Object.defineProperty(exports, 'isWrappingType', { + enumerable: true, + get: function () { + return _index.isWrappingType; + }, +}); +Object.defineProperty(exports, 'lexicographicSortSchema', { + enumerable: true, + get: function () { + return _index6.lexicographicSortSchema; + }, +}); +Object.defineProperty(exports, 'locatedError', { + enumerable: true, + get: function () { + return _index5.locatedError; + }, +}); +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function () { + return _index2.parse; + }, +}); +Object.defineProperty(exports, 'parseConstValue', { + enumerable: true, + get: function () { + return _index2.parseConstValue; + }, +}); +Object.defineProperty(exports, 'parseSchemaCoordinate', { + enumerable: true, + get: function () { + return _index2.parseSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'parseType', { + enumerable: true, + get: function () { + return _index2.parseType; + }, +}); +Object.defineProperty(exports, 'parseValue', { + enumerable: true, + get: function () { + return _index2.parseValue; + }, +}); +Object.defineProperty(exports, 'print', { + enumerable: true, + get: function () { + return _index2.print; + }, +}); +Object.defineProperty(exports, 'printError', { + enumerable: true, + get: function () { + return _index5.printError; + }, +}); +Object.defineProperty(exports, 'printIntrospectionSchema', { + enumerable: true, + get: function () { + return _index6.printIntrospectionSchema; + }, +}); +Object.defineProperty(exports, 'printLocation', { + enumerable: true, + get: function () { + return _index2.printLocation; + }, +}); +Object.defineProperty(exports, 'printSchema', { + enumerable: true, + get: function () { + return _index6.printSchema; + }, +}); +Object.defineProperty(exports, 'printSourceLocation', { + enumerable: true, + get: function () { + return _index2.printSourceLocation; + }, +}); +Object.defineProperty(exports, 'printType', { + enumerable: true, + get: function () { + return _index6.printType; + }, +}); +Object.defineProperty(exports, 'recommendedRules', { + enumerable: true, + get: function () { + return _index4.recommendedRules; + }, +}); +Object.defineProperty(exports, 'resolveASTSchemaCoordinate', { + enumerable: true, + get: function () { + return _index6.resolveASTSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'resolveObjMapThunk', { + enumerable: true, + get: function () { + return _index.resolveObjMapThunk; + }, +}); +Object.defineProperty(exports, 'resolveReadonlyArrayThunk', { + enumerable: true, + get: function () { + return _index.resolveReadonlyArrayThunk; + }, +}); +Object.defineProperty(exports, 'resolveSchemaCoordinate', { + enumerable: true, + get: function () { + return _index6.resolveSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'responsePathAsArray', { + enumerable: true, + get: function () { + return _index3.responsePathAsArray; + }, +}); +Object.defineProperty(exports, 'separateOperations', { + enumerable: true, + get: function () { + return _index6.separateOperations; + }, +}); +Object.defineProperty(exports, 'specifiedDirectives', { + enumerable: true, + get: function () { + return _index.specifiedDirectives; + }, +}); +Object.defineProperty(exports, 'specifiedRules', { + enumerable: true, + get: function () { + return _index4.specifiedRules; + }, +}); +Object.defineProperty(exports, 'specifiedScalarTypes', { + enumerable: true, + get: function () { + return _index.specifiedScalarTypes; + }, +}); +Object.defineProperty(exports, 'stripIgnoredCharacters', { + enumerable: true, + get: function () { + return _index6.stripIgnoredCharacters; + }, +}); +Object.defineProperty(exports, 'subscribe', { + enumerable: true, + get: function () { + return _index3.subscribe; + }, +}); +Object.defineProperty(exports, 'syntaxError', { + enumerable: true, + get: function () { + return _index5.syntaxError; + }, +}); +Object.defineProperty(exports, 'typeFromAST', { + enumerable: true, + get: function () { + return _index6.typeFromAST; + }, +}); +Object.defineProperty(exports, 'validate', { + enumerable: true, + get: function () { + return _index4.validate; + }, +}); +Object.defineProperty(exports, 'validateSchema', { + enumerable: true, + get: function () { + return _index.validateSchema; + }, +}); +Object.defineProperty(exports, 'valueFromAST', { + enumerable: true, + get: function () { + return _index6.valueFromAST; + }, +}); +Object.defineProperty(exports, 'valueFromASTUntyped', { + enumerable: true, + get: function () { + return _index6.valueFromASTUntyped; + }, +}); +Object.defineProperty(exports, 'version', { + enumerable: true, + get: function () { + return _version.version; + }, +}); +Object.defineProperty(exports, 'versionInfo', { + enumerable: true, + get: function () { + return _version.versionInfo; + }, +}); +Object.defineProperty(exports, 'visit', { + enumerable: true, + get: function () { + return _index2.visit; + }, +}); +Object.defineProperty(exports, 'visitInParallel', { + enumerable: true, + get: function () { + return _index2.visitInParallel; + }, +}); +Object.defineProperty(exports, 'visitWithTypeInfo', { + enumerable: true, + get: function () { + return _index6.visitWithTypeInfo; + }, +}); + +var _version = require('./version.js'); + +var _graphql = require('./graphql.js'); + +var _index = require('./type/index.js'); + +var _index2 = require('./language/index.js'); + +var _index3 = require('./execution/index.js'); + +var _index4 = require('./validation/index.js'); + +var _index5 = require('./error/index.js'); + +var _index6 = require('./utilities/index.js'); diff --git a/node_modules/graphql/index.mjs b/node_modules/graphql/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1ead8568acc90714552695ff10405a5e37edb9ab --- /dev/null +++ b/node_modules/graphql/index.mjs @@ -0,0 +1,256 @@ +/** + * The root `graphql` package re-exports the public GraphQL.js API from its + * submodules and provides the high-level request pipeline helpers defined in + * this module. + * + * You can import public exports from GraphQL.js modules through the root + * `graphql` package or through their module-specific entry point. For example, + * these two references resolve to the same `parse` function: + * + * ```ts + * import { parse } from 'graphql'; + * import { parse } from 'graphql/language'; + * ``` + * + * Use the root package when you want a single import surface, or use submodules + * such as `graphql/language`, `graphql/type`, `graphql/execution`, and + * `graphql/utilities` when you want module-focused imports. This module also + * defines root-only APIs, such as request pipeline helpers and version + * metadata, that do not belong to a narrower submodule. + * @packageDocumentation + */ +// Version constants for the GraphQL.js package. +export { version, versionInfo } from './version.mjs'; // Top-level helpers for fulfilling a GraphQL request. + +export { graphql, graphqlSync } from './graphql.mjs'; // Create and operate on GraphQL type definitions and schema. + +export { + resolveObjMapThunk, + resolveReadonlyArrayThunk, // Definitions + GraphQLSchema, + GraphQLDirective, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, // Standard GraphQL Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, // Int boundaries constants + GRAPHQL_MAX_INT, + GRAPHQL_MIN_INT, // Built-in Directives defined by the Spec + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, // "Enum" of Type Kinds + TypeKind, // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, // Predicates + isSchema, + isDirective, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + isSpecifiedScalarType, + isIntrospectionType, + isSpecifiedDirective, // Assertions + assertSchema, + assertDirective, + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, // Un-modifiers + getNullableType, + getNamedType, // Validate GraphQL schema. + validateSchema, + assertValidSchema, // Upholds the spec rules about naming. + assertName, + assertEnumValueName, +} from './type/index.mjs'; +// Parse and operate on GraphQL language source files. +export { + Token, + Source, + Location, + OperationTypeNode, + getLocation, // Print source location. + printLocation, + printSourceLocation, // Lex + Lexer, + TokenKind, // Parse + parse, + parseValue, + parseConstValue, + parseType, + parseSchemaCoordinate, // Print + print, // Visit + visit, + visitInParallel, + getVisitFn, + getEnterLeaveForKind, + BREAK, + Kind, + DirectiveLocation, // Predicates + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isConstValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, + isSchemaCoordinateNode, +} from './language/index.mjs'; +// Execute GraphQL queries. +export { + execute, + executeSync, + defaultFieldResolver, + defaultTypeResolver, + responsePathAsArray, + getArgumentValues, + getVariableValues, + getDirectiveValues, + subscribe, + createSourceEventStream, +} from './execution/index.mjs'; +// Validate GraphQL documents. +export { + validate, + ValidationContext, // All validation rules in the GraphQL Specification. + specifiedRules, + recommendedRules, // Individual validation rules. + ExecutableDefinitionsRule, + FieldsOnCorrectTypeRule, + FragmentsOnCompositeTypesRule, + KnownArgumentNamesRule, + KnownDirectivesRule, + KnownFragmentNamesRule, + KnownTypeNamesRule, + LoneAnonymousOperationRule, + NoFragmentCyclesRule, + NoUndefinedVariablesRule, + NoUnusedFragmentsRule, + NoUnusedVariablesRule, + OverlappingFieldsCanBeMergedRule, + PossibleFragmentSpreadsRule, + ProvidedRequiredArgumentsRule, + ScalarLeafsRule, + SingleFieldSubscriptionsRule, + UniqueArgumentNamesRule, + UniqueDirectivesPerLocationRule, + UniqueFragmentNamesRule, + UniqueInputFieldNamesRule, + UniqueOperationNamesRule, + UniqueVariableNamesRule, + ValuesOfCorrectTypeRule, + VariablesAreInputTypesRule, + VariablesInAllowedPositionRule, + MaxIntrospectionDepthRule, // SDL-specific validation rules + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueArgumentDefinitionNamesRule, + UniqueDirectiveNamesRule, + PossibleTypeExtensionsRule, // Custom validation rules + NoDeprecatedCustomRule, + NoSchemaIntrospectionCustomRule, +} from './validation/index.mjs'; +// Create, format, and print GraphQL errors. +export { + GraphQLError, + syntaxError, + locatedError, + printError, + formatError, +} from './error/index.mjs'; +// Utilities for operating on GraphQL type schema and parsed sources. +export { + // Produce the GraphQL query recommended for a full schema introspection. + // Accepts optional IntrospectionOptions. + getIntrospectionQuery, // Gets the target Operation from a Document. + getOperationAST, // Gets the Type for the target Operation AST. + getOperationRootType, // Convert a GraphQLSchema to an IntrospectionQuery. + introspectionFromSchema, // Build a GraphQLSchema from an introspection result. + buildClientSchema, // Build a GraphQLSchema from a parsed GraphQL Schema language AST. + buildASTSchema, // Build a GraphQLSchema from a GraphQL schema language document. + buildSchema, // Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. + extendSchema, // Sort a GraphQLSchema. + lexicographicSortSchema, // Print a GraphQLSchema to GraphQL Schema language. + printSchema, // Print a GraphQLType to GraphQL Schema language. + printType, // Prints the built-in introspection schema in the Schema Language format. + printIntrospectionSchema, // Create a GraphQLType from a GraphQL language AST. + typeFromAST, // Create a JavaScript value from a GraphQL language AST with a Type. + valueFromAST, // Create a JavaScript value from a GraphQL language AST without a Type. + valueFromASTUntyped, // Create a GraphQL language AST from a JavaScript value. + astFromValue, // A helper to use within recursive-descent visitors which need to be aware of the GraphQL type system. + TypeInfo, + visitWithTypeInfo, // Coerces a JavaScript value to a GraphQL type, or produces errors. + coerceInputValue, // Concatenates multiple AST together. + concatAST, // Separates an AST into an AST per Operation. + separateOperations, // Strips characters that are not significant to the validity or execution of a GraphQL document. + stripIgnoredCharacters, // Comparators for types + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, // Asserts a string is a valid GraphQL name. + assertValidName, // Determine if a string is a valid GraphQL name. + isValidNameError, // Compares two GraphQLSchemas and detects breaking changes. + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, // Schema Coordinates + resolveSchemaCoordinate, + resolveASTSchemaCoordinate, +} from './utilities/index.mjs'; diff --git a/node_modules/graphql/jsutils/Maybe.d.ts b/node_modules/graphql/jsutils/Maybe.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f62b8f1fc7f885a532e7a036c9c2fd656c5d5afd --- /dev/null +++ b/node_modules/graphql/jsutils/Maybe.d.ts @@ -0,0 +1,6 @@ +/** + * Conveniently represents flow's "Maybe" type https://flow.org/en/docs/types/maybe/ + * + * @internal + */ +export declare type Maybe = null | undefined | T; diff --git a/node_modules/graphql/jsutils/Maybe.js b/node_modules/graphql/jsutils/Maybe.js new file mode 100644 index 0000000000000000000000000000000000000000..b92811b00ce45269375f44bfb34fff79dfc55808 --- /dev/null +++ b/node_modules/graphql/jsutils/Maybe.js @@ -0,0 +1,5 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); diff --git a/node_modules/graphql/jsutils/Maybe.mjs b/node_modules/graphql/jsutils/Maybe.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/graphql/jsutils/Maybe.mjs @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/graphql/jsutils/ObjMap.d.ts b/node_modules/graphql/jsutils/ObjMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a49dda8f2ad883f5f1dd3d96f4f61612b078ba0 --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.d.ts @@ -0,0 +1,20 @@ +/** @internal */ +export interface ObjMap { + [key: string]: T; +} +/** @internal */ +export declare type ObjMapLike = + | ObjMap + | { + [key: string]: T; + }; +/** @internal */ +export interface ReadOnlyObjMap { + readonly [key: string]: T; +} +/** @internal */ +export declare type ReadOnlyObjMapLike = + | ReadOnlyObjMap + | { + readonly [key: string]: T; + }; diff --git a/node_modules/graphql/jsutils/ObjMap.js b/node_modules/graphql/jsutils/ObjMap.js new file mode 100644 index 0000000000000000000000000000000000000000..b92811b00ce45269375f44bfb34fff79dfc55808 --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.js @@ -0,0 +1,5 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); diff --git a/node_modules/graphql/jsutils/ObjMap.mjs b/node_modules/graphql/jsutils/ObjMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/graphql/jsutils/ObjMap.mjs @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/graphql/jsutils/Path.d.ts b/node_modules/graphql/jsutils/Path.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..51f5f0307062b7925b8e1617e8f2a68f71fd6a21 --- /dev/null +++ b/node_modules/graphql/jsutils/Path.d.ts @@ -0,0 +1,50 @@ +/** @category Paths */ +import type { Maybe } from './Maybe'; +/** Represents a linked response path from a field back to the root response. */ +export interface Path { + /** The previous segment in the linked response path, or undefined at the root. */ + readonly prev: Path | undefined; + /** The field name or list index for this response path segment. */ + readonly key: string | number; + /** The runtime object type name associated with this path segment, if known. */ + readonly typename: string | undefined; +} +/** + * Given a Path and a key, return a new Path containing the new key. + * + * @internal + */ +export declare function addPath( + prev: Readonly | undefined, + key: string | number, + typename: string | undefined, +): Path; +/** + * Given a Path, return an Array of the path keys. + * @param path - The linked response path to flatten. + * @returns An array of response path keys from root to leaf. + * @example + * ```ts + * import { pathToArray } from 'graphql/jsutils/Path'; + * + * const path = { + * prev: { + * prev: { + * prev: undefined, + * key: 'viewer', + * typename: 'Query', + * }, + * key: 'friends', + * typename: 'User', + * }, + * key: 0, + * typename: undefined, + * }; + * + * pathToArray(path); // => ['viewer', 'friends', 0] + * pathToArray(undefined); // => [] + * ``` + */ +export declare function pathToArray( + path: Maybe>, +): Array; diff --git a/node_modules/graphql/jsutils/Path.js b/node_modules/graphql/jsutils/Path.js new file mode 100644 index 0000000000000000000000000000000000000000..43a334911d528c2886bb473db7cc15dd40814e2a --- /dev/null +++ b/node_modules/graphql/jsutils/Path.js @@ -0,0 +1,62 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.addPath = addPath; +exports.pathToArray = pathToArray; + +/** @category Paths */ + +/** Represents a linked response path from a field back to the root response. */ + +/** + * Given a Path and a key, return a new Path containing the new key. + * + * @internal + */ +function addPath(prev, key, typename) { + return { + prev, + key, + typename, + }; +} +/** + * Given a Path, return an Array of the path keys. + * @param path - The linked response path to flatten. + * @returns An array of response path keys from root to leaf. + * @example + * ```ts + * import { pathToArray } from 'graphql/jsutils/Path'; + * + * const path = { + * prev: { + * prev: { + * prev: undefined, + * key: 'viewer', + * typename: 'Query', + * }, + * key: 'friends', + * typename: 'User', + * }, + * key: 0, + * typename: undefined, + * }; + * + * pathToArray(path); // => ['viewer', 'friends', 0] + * pathToArray(undefined); // => [] + * ``` + */ + +function pathToArray(path) { + const flattened = []; + let curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} diff --git a/node_modules/graphql/jsutils/Path.mjs b/node_modules/graphql/jsutils/Path.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eb782e372de2b5317cb88cfde2d60ebe7cd7f7cd --- /dev/null +++ b/node_modules/graphql/jsutils/Path.mjs @@ -0,0 +1,54 @@ +/** @category Paths */ + +/** Represents a linked response path from a field back to the root response. */ + +/** + * Given a Path and a key, return a new Path containing the new key. + * + * @internal + */ +export function addPath(prev, key, typename) { + return { + prev, + key, + typename, + }; +} +/** + * Given a Path, return an Array of the path keys. + * @param path - The linked response path to flatten. + * @returns An array of response path keys from root to leaf. + * @example + * ```ts + * import { pathToArray } from 'graphql/jsutils/Path'; + * + * const path = { + * prev: { + * prev: { + * prev: undefined, + * key: 'viewer', + * typename: 'Query', + * }, + * key: 'friends', + * typename: 'User', + * }, + * key: 0, + * typename: undefined, + * }; + * + * pathToArray(path); // => ['viewer', 'friends', 0] + * pathToArray(undefined); // => [] + * ``` + */ + +export function pathToArray(path) { + const flattened = []; + let curr = path; + + while (curr) { + flattened.push(curr.key); + curr = curr.prev; + } + + return flattened.reverse(); +} diff --git a/node_modules/graphql/jsutils/PromiseOrValue.d.ts b/node_modules/graphql/jsutils/PromiseOrValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7bad9e2d70d146a81a512e3e7c0fb691f749c560 --- /dev/null +++ b/node_modules/graphql/jsutils/PromiseOrValue.d.ts @@ -0,0 +1,2 @@ +/** @internal */ +export declare type PromiseOrValue = Promise | T; diff --git a/node_modules/graphql/jsutils/PromiseOrValue.js b/node_modules/graphql/jsutils/PromiseOrValue.js new file mode 100644 index 0000000000000000000000000000000000000000..b92811b00ce45269375f44bfb34fff79dfc55808 --- /dev/null +++ b/node_modules/graphql/jsutils/PromiseOrValue.js @@ -0,0 +1,5 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); diff --git a/node_modules/graphql/jsutils/PromiseOrValue.mjs b/node_modules/graphql/jsutils/PromiseOrValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/graphql/jsutils/PromiseOrValue.mjs @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/graphql/jsutils/devAssert.d.ts b/node_modules/graphql/jsutils/devAssert.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e91bd65f03e76496f3cefe85a4de170531494ae3 --- /dev/null +++ b/node_modules/graphql/jsutils/devAssert.d.ts @@ -0,0 +1,2 @@ +/** @internal */ +export declare function devAssert(condition: unknown, message: string): void; diff --git a/node_modules/graphql/jsutils/devAssert.js b/node_modules/graphql/jsutils/devAssert.js new file mode 100644 index 0000000000000000000000000000000000000000..a941f8fc48ed6fdbbf667fb7474b02904e466224 --- /dev/null +++ b/node_modules/graphql/jsutils/devAssert.js @@ -0,0 +1,15 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.devAssert = devAssert; + +/** @internal */ +function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error(message); + } +} diff --git a/node_modules/graphql/jsutils/devAssert.mjs b/node_modules/graphql/jsutils/devAssert.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9d588c60cdd72245ba99345c11bc29e281f40018 --- /dev/null +++ b/node_modules/graphql/jsutils/devAssert.mjs @@ -0,0 +1,8 @@ +/** @internal */ +export function devAssert(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error(message); + } +} diff --git a/node_modules/graphql/jsutils/didYouMean.d.ts b/node_modules/graphql/jsutils/didYouMean.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d5c001d05ebb6b53227e8b43e94bf7a3b231076b --- /dev/null +++ b/node_modules/graphql/jsutils/didYouMean.d.ts @@ -0,0 +1,11 @@ +/** + * Given [A, B, C] return ' Did you mean A, B, or C?'. + * + * @internal + */ +export declare function didYouMean(suggestions: ReadonlyArray): string; +/** @internal */ +export declare function didYouMean( + subMessage: string, + suggestions: ReadonlyArray, +): string; diff --git a/node_modules/graphql/jsutils/didYouMean.js b/node_modules/graphql/jsutils/didYouMean.js new file mode 100644 index 0000000000000000000000000000000000000000..c20633ed61ae72151baf924edbce001239ff9c19 --- /dev/null +++ b/node_modules/graphql/jsutils/didYouMean.js @@ -0,0 +1,41 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.didYouMean = didYouMean; +const MAX_SUGGESTIONS = 5; +/** + * Given [A, B, C] return ' Did you mean A, B, or C?'. + * + * @internal + */ + +/** @internal */ +function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg + ? [firstArg, secondArg] + : [undefined, firstArg]; + let message = ' Did you mean '; + + if (subMessage) { + message += subMessage + ' '; + } + + const suggestions = suggestionsArg.map((x) => `"${x}"`); + + switch (suggestions.length) { + case 0: + return ''; + + case 1: + return message + suggestions[0] + '?'; + + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} diff --git a/node_modules/graphql/jsutils/didYouMean.mjs b/node_modules/graphql/jsutils/didYouMean.mjs new file mode 100644 index 0000000000000000000000000000000000000000..70b83bf779abff2e9254c4cd9134ad90c75f07d4 --- /dev/null +++ b/node_modules/graphql/jsutils/didYouMean.mjs @@ -0,0 +1,35 @@ +const MAX_SUGGESTIONS = 5; +/** + * Given [A, B, C] return ' Did you mean A, B, or C?'. + * + * @internal + */ + +/** @internal */ +export function didYouMean(firstArg, secondArg) { + const [subMessage, suggestionsArg] = secondArg + ? [firstArg, secondArg] + : [undefined, firstArg]; + let message = ' Did you mean '; + + if (subMessage) { + message += subMessage + ' '; + } + + const suggestions = suggestionsArg.map((x) => `"${x}"`); + + switch (suggestions.length) { + case 0: + return ''; + + case 1: + return message + suggestions[0] + '?'; + + case 2: + return message + suggestions[0] + ' or ' + suggestions[1] + '?'; + } + + const selected = suggestions.slice(0, MAX_SUGGESTIONS); + const lastItem = selected.pop(); + return message + selected.join(', ') + ', or ' + lastItem + '?'; +} diff --git a/node_modules/graphql/jsutils/groupBy.d.ts b/node_modules/graphql/jsutils/groupBy.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6edd91a90be90519dac49b39a224a32541cd15d3 --- /dev/null +++ b/node_modules/graphql/jsutils/groupBy.d.ts @@ -0,0 +1,9 @@ +/** + * Groups array items into a Map, given a function to produce grouping key. + * + * @internal + */ +export declare function groupBy( + list: ReadonlyArray, + keyFn: (item: T) => K, +): Map>; diff --git a/node_modules/graphql/jsutils/groupBy.js b/node_modules/graphql/jsutils/groupBy.js new file mode 100644 index 0000000000000000000000000000000000000000..f09a6c7b576d0dfeb189726e3ea56dd5782c1f81 --- /dev/null +++ b/node_modules/graphql/jsutils/groupBy.js @@ -0,0 +1,28 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.groupBy = groupBy; + +/** + * Groups array items into a Map, given a function to produce grouping key. + * + * @internal + */ +function groupBy(list, keyFn) { + const result = new Map(); + + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); + } + } + + return result; +} diff --git a/node_modules/graphql/jsutils/groupBy.mjs b/node_modules/graphql/jsutils/groupBy.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5be24c47a378851f9f91de72192154551e222ac9 --- /dev/null +++ b/node_modules/graphql/jsutils/groupBy.mjs @@ -0,0 +1,21 @@ +/** + * Groups array items into a Map, given a function to produce grouping key. + * + * @internal + */ +export function groupBy(list, keyFn) { + const result = new Map(); + + for (const item of list) { + const key = keyFn(item); + const group = result.get(key); + + if (group === undefined) { + result.set(key, [item]); + } else { + group.push(item); + } + } + + return result; +} diff --git a/node_modules/graphql/jsutils/identityFunc.d.ts b/node_modules/graphql/jsutils/identityFunc.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b6e5e1820bf867fb8d7776301149b815f4c37df8 --- /dev/null +++ b/node_modules/graphql/jsutils/identityFunc.d.ts @@ -0,0 +1,6 @@ +/** + * Returns the first argument it receives. + * + * @internal + */ +export declare function identityFunc(x: T): T; diff --git a/node_modules/graphql/jsutils/identityFunc.js b/node_modules/graphql/jsutils/identityFunc.js new file mode 100644 index 0000000000000000000000000000000000000000..d71cad2b901c92086bb7f957d8f2847f52d7dfc5 --- /dev/null +++ b/node_modules/graphql/jsutils/identityFunc.js @@ -0,0 +1,15 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.identityFunc = identityFunc; + +/** + * Returns the first argument it receives. + * + * @internal + */ +function identityFunc(x) { + return x; +} diff --git a/node_modules/graphql/jsutils/identityFunc.mjs b/node_modules/graphql/jsutils/identityFunc.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f9802981b1c1ed7168f5f679f88b4b18e22420e1 --- /dev/null +++ b/node_modules/graphql/jsutils/identityFunc.mjs @@ -0,0 +1,8 @@ +/** + * Returns the first argument it receives. + * + * @internal + */ +export function identityFunc(x) { + return x; +} diff --git a/node_modules/graphql/jsutils/inspect.d.ts b/node_modules/graphql/jsutils/inspect.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bba898cc2bad3cdb099867c0180255868759dc74 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.d.ts @@ -0,0 +1,6 @@ +/** + * Used to print values in error messages. + * + * @internal + */ +export declare function inspect(value: unknown): string; diff --git a/node_modules/graphql/jsutils/inspect.js b/node_modules/graphql/jsutils/inspect.js new file mode 100644 index 0000000000000000000000000000000000000000..a3f25b5600f2c313e74a818797583da9027a8ce2 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.js @@ -0,0 +1,123 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.inspect = inspect; +const MAX_ARRAY_LENGTH = 10; +const MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + * + * @internal + */ + +function inspect(value) { + return formatValue(value, []); +} + +function formatValue(value, seenValues) { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + + case 'object': + return formatObjectValue(value, seenValues); + + default: + return String(value); + } +} + +function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return 'null'; + } + + if (previouslySeenValues.includes(value)) { + return '[Circular]'; + } + + const seenValues = [...previouslySeenValues, value]; + + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === 'string' + ? jsonValue + : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function isJSONable(value) { + return typeof value.toJSON === 'function'; +} + +function formatObject(object, seenValues) { + const entries = Object.entries(object); + + if (entries.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + const properties = entries.map( + ([key, value]) => key + ': ' + formatValue(value, seenValues), + ); + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + + return '[' + items.join(', ') + ']'; +} + +function getObjectTag(object) { + const tag = Object.prototype.toString + .call(object) + .replace(/^\[object /, '') + .replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + + if (typeof name === 'string' && name !== '') { + return name; + } + } + + return tag; +} diff --git a/node_modules/graphql/jsutils/inspect.mjs b/node_modules/graphql/jsutils/inspect.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8742469c6e9c1862626f8780d5b0464dc1e7cde1 --- /dev/null +++ b/node_modules/graphql/jsutils/inspect.mjs @@ -0,0 +1,117 @@ +const MAX_ARRAY_LENGTH = 10; +const MAX_RECURSIVE_DEPTH = 2; +/** + * Used to print values in error messages. + * + * @internal + */ + +export function inspect(value) { + return formatValue(value, []); +} + +function formatValue(value, seenValues) { + switch (typeof value) { + case 'string': + return JSON.stringify(value); + + case 'function': + return value.name ? `[function ${value.name}]` : '[function]'; + + case 'object': + return formatObjectValue(value, seenValues); + + default: + return String(value); + } +} + +function formatObjectValue(value, previouslySeenValues) { + if (value === null) { + return 'null'; + } + + if (previouslySeenValues.includes(value)) { + return '[Circular]'; + } + + const seenValues = [...previouslySeenValues, value]; + + if (isJSONable(value)) { + const jsonValue = value.toJSON(); // check for infinite recursion + + if (jsonValue !== value) { + return typeof jsonValue === 'string' + ? jsonValue + : formatValue(jsonValue, seenValues); + } + } else if (Array.isArray(value)) { + return formatArray(value, seenValues); + } + + return formatObject(value, seenValues); +} + +function isJSONable(value) { + return typeof value.toJSON === 'function'; +} + +function formatObject(object, seenValues) { + const entries = Object.entries(object); + + if (entries.length === 0) { + return '{}'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[' + getObjectTag(object) + ']'; + } + + const properties = entries.map( + ([key, value]) => key + ': ' + formatValue(value, seenValues), + ); + return '{ ' + properties.join(', ') + ' }'; +} + +function formatArray(array, seenValues) { + if (array.length === 0) { + return '[]'; + } + + if (seenValues.length > MAX_RECURSIVE_DEPTH) { + return '[Array]'; + } + + const len = Math.min(MAX_ARRAY_LENGTH, array.length); + const remaining = array.length - len; + const items = []; + + for (let i = 0; i < len; ++i) { + items.push(formatValue(array[i], seenValues)); + } + + if (remaining === 1) { + items.push('... 1 more item'); + } else if (remaining > 1) { + items.push(`... ${remaining} more items`); + } + + return '[' + items.join(', ') + ']'; +} + +function getObjectTag(object) { + const tag = Object.prototype.toString + .call(object) + .replace(/^\[object /, '') + .replace(/]$/, ''); + + if (tag === 'Object' && typeof object.constructor === 'function') { + const name = object.constructor.name; + + if (typeof name === 'string' && name !== '') { + return name; + } + } + + return tag; +} diff --git a/node_modules/graphql/jsutils/instanceOf.d.ts b/node_modules/graphql/jsutils/instanceOf.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..77e0d4aea111e9afbcb66721580f91d9c8dc5e5f --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.d.ts @@ -0,0 +1,18 @@ +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + * + * @internal + */ +export declare const instanceOf: ( + value: unknown, + constructor: Constructor, +) => boolean; +interface Constructor extends Function { + prototype: { + [Symbol.toStringTag]: string; + }; +} +export {}; diff --git a/node_modules/graphql/jsutils/instanceOf.js b/node_modules/graphql/jsutils/instanceOf.js new file mode 100644 index 0000000000000000000000000000000000000000..dc8e18105d926ed4c26bcba0b8007f6497180e41 --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.js @@ -0,0 +1,67 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.instanceOf = void 0; + +var _inspect = require('./inspect.js'); + +/* c8 ignore next 3 */ +const isProduction = + globalThis.process && // eslint-disable-next-line no-undef + process.env.NODE_ENV === 'production'; +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + * + * @internal + */ + +const instanceOf = + /* c8 ignore next 6 */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + isProduction + ? function instanceOf(value, constructor) { + return value instanceof constructor; + } + : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (typeof value === 'object' && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] + : (_value$constructor = value.constructor) === null || + _value$constructor === void 0 + ? void 0 + : _value$constructor.name; + + if (className === valueClassName) { + const stringifiedValue = (0, _inspect.inspect)(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } + } + + return false; + }; +exports.instanceOf = instanceOf; diff --git a/node_modules/graphql/jsutils/instanceOf.mjs b/node_modules/graphql/jsutils/instanceOf.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1fe4958227fa3242511c2807dee1b36f1a0c8e38 --- /dev/null +++ b/node_modules/graphql/jsutils/instanceOf.mjs @@ -0,0 +1,59 @@ +import { inspect } from './inspect.mjs'; +/* c8 ignore next 3 */ + +const isProduction = + globalThis.process && // eslint-disable-next-line no-undef + process.env.NODE_ENV === 'production'; +/** + * A replacement for instanceof which includes an error warning when multi-realm + * constructors are detected. + * See: https://expressjs.com/en/advanced/best-practice-performance.html#set-node_env-to-production + * See: https://webpack.js.org/guides/production/ + * + * @internal + */ + +export const instanceOf = + /* c8 ignore next 6 */ + // FIXME: https://github.com/graphql/graphql-js/issues/2317 + isProduction + ? function instanceOf(value, constructor) { + return value instanceof constructor; + } + : function instanceOf(value, constructor) { + if (value instanceof constructor) { + return true; + } + + if (typeof value === 'object' && value !== null) { + var _value$constructor; + + // Prefer Symbol.toStringTag since it is immune to minification. + const className = constructor.prototype[Symbol.toStringTag]; + const valueClassName = // We still need to support constructor's name to detect conflicts with older versions of this library. + Symbol.toStringTag in value // @ts-expect-error TS bug see, https://github.com/microsoft/TypeScript/issues/38009 + ? value[Symbol.toStringTag] + : (_value$constructor = value.constructor) === null || + _value$constructor === void 0 + ? void 0 + : _value$constructor.name; + + if (className === valueClassName) { + const stringifiedValue = inspect(value); + throw new Error(`Cannot use ${className} "${stringifiedValue}" from another module or realm. + +Ensure that there is only one instance of "graphql" in the node_modules +directory. If different versions of "graphql" are the dependencies of other +relied on modules, use "resolutions" to ensure only one version is installed. + +https://yarnpkg.com/en/docs/selective-version-resolutions + +Duplicate "graphql" modules cannot be used at the same time since different +versions may have different capabilities and behavior. The data from one +version used in the function from another could produce confusing and +spurious results.`); + } + } + + return false; + }; diff --git a/node_modules/graphql/jsutils/invariant.d.ts b/node_modules/graphql/jsutils/invariant.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a6c4610ad5991c377b6b7002ecf477bddf00f608 --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.d.ts @@ -0,0 +1,5 @@ +/** @internal */ +export declare function invariant( + condition: unknown, + message?: string, +): asserts condition; diff --git a/node_modules/graphql/jsutils/invariant.js b/node_modules/graphql/jsutils/invariant.js new file mode 100644 index 0000000000000000000000000000000000000000..5625907232eba023c747be904d017a7fea78fe4c --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.js @@ -0,0 +1,17 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.invariant = invariant; + +/** @internal */ +function invariant(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error( + message != null ? message : 'Unexpected invariant triggered.', + ); + } +} diff --git a/node_modules/graphql/jsutils/invariant.mjs b/node_modules/graphql/jsutils/invariant.mjs new file mode 100644 index 0000000000000000000000000000000000000000..519b2ecd7afa11ab1498b4a6f8d4e6bcd7af4cc6 --- /dev/null +++ b/node_modules/graphql/jsutils/invariant.mjs @@ -0,0 +1,10 @@ +/** @internal */ +export function invariant(condition, message) { + const booleanCondition = Boolean(condition); + + if (!booleanCondition) { + throw new Error( + message != null ? message : 'Unexpected invariant triggered.', + ); + } +} diff --git a/node_modules/graphql/jsutils/isAsyncIterable.d.ts b/node_modules/graphql/jsutils/isAsyncIterable.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ad237bd0d97ac4aa0c4a48b99ba268e9292abc11 --- /dev/null +++ b/node_modules/graphql/jsutils/isAsyncIterable.d.ts @@ -0,0 +1,9 @@ +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + * + * @internal + */ +export declare function isAsyncIterable( + maybeAsyncIterable: any, +): maybeAsyncIterable is AsyncIterable; diff --git a/node_modules/graphql/jsutils/isAsyncIterable.js b/node_modules/graphql/jsutils/isAsyncIterable.js new file mode 100644 index 0000000000000000000000000000000000000000..1db5a00fe37bc506ecb59833486da9ea20ed9db9 --- /dev/null +++ b/node_modules/graphql/jsutils/isAsyncIterable.js @@ -0,0 +1,20 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isAsyncIterable = isAsyncIterable; + +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + * + * @internal + */ +function isAsyncIterable(maybeAsyncIterable) { + return ( + typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 + ? void 0 + : maybeAsyncIterable[Symbol.asyncIterator]) === 'function' + ); +} diff --git a/node_modules/graphql/jsutils/isAsyncIterable.mjs b/node_modules/graphql/jsutils/isAsyncIterable.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3180c0e533945d7313fa1b17d4b3a443748c8093 --- /dev/null +++ b/node_modules/graphql/jsutils/isAsyncIterable.mjs @@ -0,0 +1,13 @@ +/** + * Returns true if the provided object implements the AsyncIterator protocol via + * implementing a `Symbol.asyncIterator` method. + * + * @internal + */ +export function isAsyncIterable(maybeAsyncIterable) { + return ( + typeof (maybeAsyncIterable === null || maybeAsyncIterable === void 0 + ? void 0 + : maybeAsyncIterable[Symbol.asyncIterator]) === 'function' + ); +} diff --git a/node_modules/graphql/jsutils/isIterableObject.d.ts b/node_modules/graphql/jsutils/isIterableObject.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fd7ae6bf7a593491f457554d79c5e14e59377b79 --- /dev/null +++ b/node_modules/graphql/jsutils/isIterableObject.d.ts @@ -0,0 +1,21 @@ +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @internal + * @example + * ```ts + * isIterableObject([1, 2, 3]); // => true + * isIterableObject(new Map()); // => true + * isIterableObject('ABC'); // => false + * isIterableObject({ key: 'value' }); // => false + * isIterableObject({ length: 1, 0: 'Alpha' }); // => false + * ``` + */ +export declare function isIterableObject( + maybeIterable: any, +): maybeIterable is Iterable; diff --git a/node_modules/graphql/jsutils/isIterableObject.js b/node_modules/graphql/jsutils/isIterableObject.js new file mode 100644 index 0000000000000000000000000000000000000000..b845160bc3b7d744a6c1e31794abb2fedd4a465f --- /dev/null +++ b/node_modules/graphql/jsutils/isIterableObject.js @@ -0,0 +1,33 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isIterableObject = isIterableObject; + +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @internal + * @example + * ```ts + * isIterableObject([1, 2, 3]); // => true + * isIterableObject(new Map()); // => true + * isIterableObject('ABC'); // => false + * isIterableObject({ key: 'value' }); // => false + * isIterableObject({ length: 1, 0: 'Alpha' }); // => false + * ``` + */ +function isIterableObject(maybeIterable) { + return ( + typeof maybeIterable === 'object' && + typeof (maybeIterable === null || maybeIterable === void 0 + ? void 0 + : maybeIterable[Symbol.iterator]) === 'function' + ); +} diff --git a/node_modules/graphql/jsutils/isIterableObject.mjs b/node_modules/graphql/jsutils/isIterableObject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b5ab888f91ae5171b33aa9bad07db76547afdaeb --- /dev/null +++ b/node_modules/graphql/jsutils/isIterableObject.mjs @@ -0,0 +1,26 @@ +/** + * Returns true if the provided object is an Object (i.e. not a string literal) + * and implements the Iterator protocol. + * + * This may be used in place of [Array.isArray()][isArray] to determine if + * an object should be iterated-over e.g. Array, Map, Set, Int8Array, + * TypedArray, etc. but excludes string literals. + * + * @internal + * @example + * ```ts + * isIterableObject([1, 2, 3]); // => true + * isIterableObject(new Map()); // => true + * isIterableObject('ABC'); // => false + * isIterableObject({ key: 'value' }); // => false + * isIterableObject({ length: 1, 0: 'Alpha' }); // => false + * ``` + */ +export function isIterableObject(maybeIterable) { + return ( + typeof maybeIterable === 'object' && + typeof (maybeIterable === null || maybeIterable === void 0 + ? void 0 + : maybeIterable[Symbol.iterator]) === 'function' + ); +} diff --git a/node_modules/graphql/jsutils/isObjectLike.d.ts b/node_modules/graphql/jsutils/isObjectLike.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ef651fa6283364ccd9dde64762fc864911991f04 --- /dev/null +++ b/node_modules/graphql/jsutils/isObjectLike.d.ts @@ -0,0 +1,9 @@ +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + * + * @internal + */ +export declare function isObjectLike(value: unknown): value is { + [key: string]: unknown; +}; diff --git a/node_modules/graphql/jsutils/isObjectLike.js b/node_modules/graphql/jsutils/isObjectLike.js new file mode 100644 index 0000000000000000000000000000000000000000..61c9d7ddbcc438085978cc7c3cecb74bb4200a20 --- /dev/null +++ b/node_modules/graphql/jsutils/isObjectLike.js @@ -0,0 +1,16 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isObjectLike = isObjectLike; + +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + * + * @internal + */ +function isObjectLike(value) { + return typeof value == 'object' && value !== null; +} diff --git a/node_modules/graphql/jsutils/isObjectLike.mjs b/node_modules/graphql/jsutils/isObjectLike.mjs new file mode 100644 index 0000000000000000000000000000000000000000..291b37e51ed7ef66986522e0c2e6fb54a302be2f --- /dev/null +++ b/node_modules/graphql/jsutils/isObjectLike.mjs @@ -0,0 +1,9 @@ +/** + * Return true if `value` is object-like. A value is object-like if it's not + * `null` and has a `typeof` result of "object". + * + * @internal + */ +export function isObjectLike(value) { + return typeof value == 'object' && value !== null; +} diff --git a/node_modules/graphql/jsutils/isPromise.d.ts b/node_modules/graphql/jsutils/isPromise.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28614c165f4f69b5f8a6bbeea03852d9f893e558 --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.d.ts @@ -0,0 +1,7 @@ +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + * + * @internal + */ +export declare function isPromise(value: any): value is Promise; diff --git a/node_modules/graphql/jsutils/isPromise.js b/node_modules/graphql/jsutils/isPromise.js new file mode 100644 index 0000000000000000000000000000000000000000..474b2455e605b9ef8881cb8a72f504e24b07d079 --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isPromise = isPromise; + +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + * + * @internal + */ +function isPromise(value) { + return ( + typeof (value === null || value === void 0 ? void 0 : value.then) === + 'function' + ); +} diff --git a/node_modules/graphql/jsutils/isPromise.mjs b/node_modules/graphql/jsutils/isPromise.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0a3d5a5a4f3bb19d3fa8feec7cc3fd8ab7e41936 --- /dev/null +++ b/node_modules/graphql/jsutils/isPromise.mjs @@ -0,0 +1,12 @@ +/** + * Returns true if the value acts like a Promise, i.e. has a "then" function, + * otherwise returns false. + * + * @internal + */ +export function isPromise(value) { + return ( + typeof (value === null || value === void 0 ? void 0 : value.then) === + 'function' + ); +} diff --git a/node_modules/graphql/jsutils/keyMap.d.ts b/node_modules/graphql/jsutils/keyMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4a79e2f741b2f994932f736d8e6ea743dbc62169 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.d.ts @@ -0,0 +1,25 @@ +import type { ObjMap } from './ObjMap'; +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const entriesByName = keyMap(phoneBook, (entry) => entry.name); + * + * Object.keys(entriesByName); // => ['Jon', 'Jenny'] + * entriesByName['Jenny']; // => { name: 'Jenny', num: '867-5309' } + * ``` + */ +export declare function keyMap( + list: ReadonlyArray, + keyFn: (item: T) => string, +): ObjMap; diff --git a/node_modules/graphql/jsutils/keyMap.js b/node_modules/graphql/jsutils/keyMap.js new file mode 100644 index 0000000000000000000000000000000000000000..63ca9b49baaa7a46ecd263908be1a89de96ee0e1 --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.keyMap = keyMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const entriesByName = keyMap(phoneBook, (entry) => entry.name); + * + * Object.keys(entriesByName); // => ['Jon', 'Jenny'] + * entriesByName['Jenny']; // => { name: 'Jenny', num: '867-5309' } + * ``` + */ +function keyMap(list, keyFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = item; + } + + return result; +} diff --git a/node_modules/graphql/jsutils/keyMap.mjs b/node_modules/graphql/jsutils/keyMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6814c16430046d32d1567c92e79524737c41833c --- /dev/null +++ b/node_modules/graphql/jsutils/keyMap.mjs @@ -0,0 +1,29 @@ +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * for each value in the array. + * + * This provides a convenient lookup for the array items if the key function + * produces unique results. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const entriesByName = keyMap(phoneBook, (entry) => entry.name); + * + * Object.keys(entriesByName); // => ['Jon', 'Jenny'] + * entriesByName['Jenny']; // => { name: 'Jenny', num: '867-5309' } + * ``` + */ +export function keyMap(list, keyFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = item; + } + + return result; +} diff --git a/node_modules/graphql/jsutils/keyValMap.d.ts b/node_modules/graphql/jsutils/keyValMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..25d61d002e460cf4f4cdf108e4fec707a7e3c275 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.d.ts @@ -0,0 +1,26 @@ +import type { ObjMap } from './ObjMap'; +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const phonesByName = keyValMap( + * phoneBook, + * (entry) => entry.name, + * (entry) => entry.num, + * ); + * + * phonesByName; // => { Jon: '555-1234', Jenny: '867-5309' } + * ``` + */ +export declare function keyValMap( + list: ReadonlyArray, + keyFn: (item: T) => string, + valFn: (item: T) => V, +): ObjMap; diff --git a/node_modules/graphql/jsutils/keyValMap.js b/node_modules/graphql/jsutils/keyValMap.js new file mode 100644 index 0000000000000000000000000000000000000000..dba6b3ba25774c09abdb5c27ee51c7e9ecd51fc0 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.js @@ -0,0 +1,36 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.keyValMap = keyValMap; + +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const phonesByName = keyValMap( + * phoneBook, + * (entry) => entry.name, + * (entry) => entry.num, + * ); + * + * phonesByName; // => { Jon: '555-1234', Jenny: '867-5309' } + * ``` + */ +function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + + return result; +} diff --git a/node_modules/graphql/jsutils/keyValMap.mjs b/node_modules/graphql/jsutils/keyValMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d8d56e5fdb7a419e50afadd746aa04ed1c8a4876 --- /dev/null +++ b/node_modules/graphql/jsutils/keyValMap.mjs @@ -0,0 +1,29 @@ +/** + * Creates a keyed JS object from an array, given a function to produce the keys + * and a function to produce the values from each item in the array. + * @internal + * @example + * ```ts + * const phoneBook = [ + * { name: 'Jon', num: '555-1234' }, + * { name: 'Jenny', num: '867-5309' }, + * ]; + * + * const phonesByName = keyValMap( + * phoneBook, + * (entry) => entry.name, + * (entry) => entry.num, + * ); + * + * phonesByName; // => { Jon: '555-1234', Jenny: '867-5309' } + * ``` + */ +export function keyValMap(list, keyFn, valFn) { + const result = Object.create(null); + + for (const item of list) { + result[keyFn(item)] = valFn(item); + } + + return result; +} diff --git a/node_modules/graphql/jsutils/mapValue.d.ts b/node_modules/graphql/jsutils/mapValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..20e61547043162b8d25665f3eb88dd212fd99d14 --- /dev/null +++ b/node_modules/graphql/jsutils/mapValue.d.ts @@ -0,0 +1,11 @@ +import type { ObjMap, ReadOnlyObjMap } from './ObjMap'; +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + * + * @internal + */ +export declare function mapValue( + map: ReadOnlyObjMap, + fn: (value: T, key: string) => V, +): ObjMap; diff --git a/node_modules/graphql/jsutils/mapValue.js b/node_modules/graphql/jsutils/mapValue.js new file mode 100644 index 0000000000000000000000000000000000000000..91718188bcb26fa1131c5a0f70ba8eea99c705aa --- /dev/null +++ b/node_modules/graphql/jsutils/mapValue.js @@ -0,0 +1,22 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.mapValue = mapValue; + +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + * + * @internal + */ +function mapValue(map, fn) { + const result = Object.create(null); + + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + + return result; +} diff --git a/node_modules/graphql/jsutils/mapValue.mjs b/node_modules/graphql/jsutils/mapValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..23090ed0e1a29af512251b49e10d17558ec24ecd --- /dev/null +++ b/node_modules/graphql/jsutils/mapValue.mjs @@ -0,0 +1,15 @@ +/** + * Creates an object map with the same keys as `map` and values generated by + * running each value of `map` thru `fn`. + * + * @internal + */ +export function mapValue(map, fn) { + const result = Object.create(null); + + for (const key of Object.keys(map)) { + result[key] = fn(map[key], key); + } + + return result; +} diff --git a/node_modules/graphql/jsutils/memoize3.d.ts b/node_modules/graphql/jsutils/memoize3.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..37d7760a1e717f2c6a68c33497499201a0d3823c --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.d.ts @@ -0,0 +1,11 @@ +/** + * Memoizes the provided three-argument function. + * + * @internal + */ +export declare function memoize3< + A1 extends object, + A2 extends object, + A3 extends object, + R, +>(fn: (a1: A1, a2: A2, a3: A3) => R): (a1: A1, a2: A2, a3: A3) => R; diff --git a/node_modules/graphql/jsutils/memoize3.js b/node_modules/graphql/jsutils/memoize3.js new file mode 100644 index 0000000000000000000000000000000000000000..4a6bebb544581333eb0039ecd4fbc25ca2b135c8 --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.memoize3 = memoize3; + +/** + * Memoizes the provided three-argument function. + * + * @internal + */ +function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); + } + + let cache1 = cache0.get(a1); + + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + let cache2 = cache1.get(a2); + + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + let fnResult = cache2.get(a3); + + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); + } + + return fnResult; + }; +} diff --git a/node_modules/graphql/jsutils/memoize3.mjs b/node_modules/graphql/jsutils/memoize3.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eb7df6812c82fd280d3b4d2de6a1aaf149d8c65f --- /dev/null +++ b/node_modules/graphql/jsutils/memoize3.mjs @@ -0,0 +1,36 @@ +/** + * Memoizes the provided three-argument function. + * + * @internal + */ +export function memoize3(fn) { + let cache0; + return function memoized(a1, a2, a3) { + if (cache0 === undefined) { + cache0 = new WeakMap(); + } + + let cache1 = cache0.get(a1); + + if (cache1 === undefined) { + cache1 = new WeakMap(); + cache0.set(a1, cache1); + } + + let cache2 = cache1.get(a2); + + if (cache2 === undefined) { + cache2 = new WeakMap(); + cache1.set(a2, cache2); + } + + let fnResult = cache2.get(a3); + + if (fnResult === undefined) { + fnResult = fn(a1, a2, a3); + cache2.set(a3, fnResult); + } + + return fnResult; + }; +} diff --git a/node_modules/graphql/jsutils/naturalCompare.d.ts b/node_modules/graphql/jsutils/naturalCompare.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6bfd4c799216d3c9ef797b2c6854619efa40f7b4 --- /dev/null +++ b/node_modules/graphql/jsutils/naturalCompare.d.ts @@ -0,0 +1,10 @@ +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + * + * @internal + */ +export declare function naturalCompare(aStr: string, bStr: string): number; diff --git a/node_modules/graphql/jsutils/naturalCompare.js b/node_modules/graphql/jsutils/naturalCompare.js new file mode 100644 index 0000000000000000000000000000000000000000..f20e4aff62098efe777509ec547fae8bd2ffaf38 --- /dev/null +++ b/node_modules/graphql/jsutils/naturalCompare.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.naturalCompare = naturalCompare; + +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + * + * @internal + */ +function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + + let bNum = 0; + + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + + if (aChar > bChar) { + return 1; + } + + ++aIndex; + ++bIndex; + } + } + + return aStr.length - bStr.length; +} + +const DIGIT_0 = 48; +const DIGIT_9 = 57; + +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} diff --git a/node_modules/graphql/jsutils/naturalCompare.mjs b/node_modules/graphql/jsutils/naturalCompare.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e7d42702544299ba36911eca8d1b29763952e9d6 --- /dev/null +++ b/node_modules/graphql/jsutils/naturalCompare.mjs @@ -0,0 +1,63 @@ +/** + * Returns a number indicating whether a reference string comes before, or after, + * or is the same as the given string in natural sort order. + * + * See: https://en.wikipedia.org/wiki/Natural_sort_order + * + * + * @internal + */ +export function naturalCompare(aStr, bStr) { + let aIndex = 0; + let bIndex = 0; + + while (aIndex < aStr.length && bIndex < bStr.length) { + let aChar = aStr.charCodeAt(aIndex); + let bChar = bStr.charCodeAt(bIndex); + + if (isDigit(aChar) && isDigit(bChar)) { + let aNum = 0; + + do { + ++aIndex; + aNum = aNum * 10 + aChar - DIGIT_0; + aChar = aStr.charCodeAt(aIndex); + } while (isDigit(aChar) && aNum > 0); + + let bNum = 0; + + do { + ++bIndex; + bNum = bNum * 10 + bChar - DIGIT_0; + bChar = bStr.charCodeAt(bIndex); + } while (isDigit(bChar) && bNum > 0); + + if (aNum < bNum) { + return -1; + } + + if (aNum > bNum) { + return 1; + } + } else { + if (aChar < bChar) { + return -1; + } + + if (aChar > bChar) { + return 1; + } + + ++aIndex; + ++bIndex; + } + } + + return aStr.length - bStr.length; +} +const DIGIT_0 = 48; +const DIGIT_9 = 57; + +function isDigit(code) { + return !isNaN(code) && DIGIT_0 <= code && code <= DIGIT_9; +} diff --git a/node_modules/graphql/jsutils/printPathArray.d.ts b/node_modules/graphql/jsutils/printPathArray.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bd9921c696aa4de2c23f7d4cd40d1c6b852bf46f --- /dev/null +++ b/node_modules/graphql/jsutils/printPathArray.d.ts @@ -0,0 +1,8 @@ +/** + * Build a string describing the path. + * + * @internal + */ +export declare function printPathArray( + path: ReadonlyArray, +): string; diff --git a/node_modules/graphql/jsutils/printPathArray.js b/node_modules/graphql/jsutils/printPathArray.js new file mode 100644 index 0000000000000000000000000000000000000000..328bd872e560a9461843b05e91f96460c9f6e301 --- /dev/null +++ b/node_modules/graphql/jsutils/printPathArray.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.printPathArray = printPathArray; + +/** + * Build a string describing the path. + * + * @internal + */ +function printPathArray(path) { + return path + .map((key) => + typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key, + ) + .join(''); +} diff --git a/node_modules/graphql/jsutils/printPathArray.mjs b/node_modules/graphql/jsutils/printPathArray.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5483a476c7b7241ebee369430c69f5df093b98dc --- /dev/null +++ b/node_modules/graphql/jsutils/printPathArray.mjs @@ -0,0 +1,12 @@ +/** + * Build a string describing the path. + * + * @internal + */ +export function printPathArray(path) { + return path + .map((key) => + typeof key === 'number' ? '[' + key.toString() + ']' : '.' + key, + ) + .join(''); +} diff --git a/node_modules/graphql/jsutils/promiseForObject.d.ts b/node_modules/graphql/jsutils/promiseForObject.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..463c21744321f0f89b4551f77842838db38e9a44 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.d.ts @@ -0,0 +1,13 @@ +import type { ObjMap } from './ObjMap'; +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + * + * @internal + */ +export declare function promiseForObject( + object: ObjMap>, +): Promise>; diff --git a/node_modules/graphql/jsutils/promiseForObject.js b/node_modules/graphql/jsutils/promiseForObject.js new file mode 100644 index 0000000000000000000000000000000000000000..7528b7979451cd1c6d800226eae77ec8dadfcddb --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.promiseForObject = promiseForObject; + +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + * + * @internal + */ +function promiseForObject(object) { + return Promise.all(Object.values(object)).then((resolvedValues) => { + const resolvedObject = Object.create(null); + + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; + } + + return resolvedObject; + }); +} diff --git a/node_modules/graphql/jsutils/promiseForObject.mjs b/node_modules/graphql/jsutils/promiseForObject.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a806a45555e81296affe774c093931ebdceef10d --- /dev/null +++ b/node_modules/graphql/jsutils/promiseForObject.mjs @@ -0,0 +1,20 @@ +/** + * This function transforms a JS object `ObjMap>` into + * a `Promise>` + * + * This is akin to bluebird's `Promise.props`, but implemented only using + * `Promise.all` so it will work with any implementation of ES6 promises. + * + * @internal + */ +export function promiseForObject(object) { + return Promise.all(Object.values(object)).then((resolvedValues) => { + const resolvedObject = Object.create(null); + + for (const [i, key] of Object.keys(object).entries()) { + resolvedObject[key] = resolvedValues[i]; + } + + return resolvedObject; + }); +} diff --git a/node_modules/graphql/jsutils/promiseReduce.d.ts b/node_modules/graphql/jsutils/promiseReduce.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5eaf15e888afad25afbd68d194a8ae6d3d9a6841 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.d.ts @@ -0,0 +1,15 @@ +import type { PromiseOrValue } from './PromiseOrValue'; +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + * + * @internal + */ +export declare function promiseReduce( + values: Iterable, + callbackFn: (accumulator: U, currentValue: T) => PromiseOrValue, + initialValue: PromiseOrValue, +): PromiseOrValue; diff --git a/node_modules/graphql/jsutils/promiseReduce.js b/node_modules/graphql/jsutils/promiseReduce.js new file mode 100644 index 0000000000000000000000000000000000000000..49622f4adc78a7b6d13b0e5be14a460929d35eb0 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.js @@ -0,0 +1,29 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.promiseReduce = promiseReduce; + +var _isPromise = require('./isPromise.js'); + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + * + * @internal + */ +function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + + for (const value of values) { + accumulator = (0, _isPromise.isPromise)(accumulator) + ? accumulator.then((resolved) => callbackFn(resolved, value)) + : callbackFn(accumulator, value); + } + + return accumulator; +} diff --git a/node_modules/graphql/jsutils/promiseReduce.mjs b/node_modules/graphql/jsutils/promiseReduce.mjs new file mode 100644 index 0000000000000000000000000000000000000000..58d4008ca5b386966d420df557afc256fd5dd4b5 --- /dev/null +++ b/node_modules/graphql/jsutils/promiseReduce.mjs @@ -0,0 +1,22 @@ +import { isPromise } from './isPromise.mjs'; + +/** + * Similar to Array.prototype.reduce(), however the reducing callback may return + * a Promise, in which case reduction will continue after each promise resolves. + * + * If the callback does not return a Promise, then this function will also not + * return a Promise. + * + * @internal + */ +export function promiseReduce(values, callbackFn, initialValue) { + let accumulator = initialValue; + + for (const value of values) { + accumulator = isPromise(accumulator) + ? accumulator.then((resolved) => callbackFn(resolved, value)) + : callbackFn(accumulator, value); + } + + return accumulator; +} diff --git a/node_modules/graphql/jsutils/suggestionList.d.ts b/node_modules/graphql/jsutils/suggestionList.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dd1e700c729f8ef511d722648b194eb3af5696c5 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.d.ts @@ -0,0 +1,10 @@ +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + * + * @internal + */ +export declare function suggestionList( + input: string, + options: ReadonlyArray, +): Array; diff --git a/node_modules/graphql/jsutils/suggestionList.js b/node_modules/graphql/jsutils/suggestionList.js new file mode 100644 index 0000000000000000000000000000000000000000..d3d04dd62b271e12591ac35a343e02cb47b4a5b3 --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.js @@ -0,0 +1,143 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.suggestionList = suggestionList; + +var _naturalCompare = require('./naturalCompare.js'); + +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + * + * @internal + */ +function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 + ? distanceDiff + : (0, _naturalCompare.naturalCompare)(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @internal + */ + +class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + ]; + } + + measure(option, threshold) { + if (this._input === option) { + return 0; + } + + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + + const aLength = a.length; + const bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; + } + + const rows = this._rows; + + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = (currentRow[0] = i); + + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min( + upRow[j] + 1, // delete + currentRow[j - 1] + 1, // insert + upRow[j - 1] + cost, // substitute + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; + } + } + + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } +} + +function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + + return array; +} diff --git a/node_modules/graphql/jsutils/suggestionList.mjs b/node_modules/graphql/jsutils/suggestionList.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e11aa6cc3193aaf4b5b66376c83441c34434698d --- /dev/null +++ b/node_modules/graphql/jsutils/suggestionList.mjs @@ -0,0 +1,134 @@ +import { naturalCompare } from './naturalCompare.mjs'; +/** + * Given an invalid input string and a list of valid options, returns a filtered + * list of valid options sorted based on their similarity with the input. + * + * @internal + */ + +export function suggestionList(input, options) { + const optionsByDistance = Object.create(null); + const lexicalDistance = new LexicalDistance(input); + const threshold = Math.floor(input.length * 0.4) + 1; + + for (const option of options) { + const distance = lexicalDistance.measure(option, threshold); + + if (distance !== undefined) { + optionsByDistance[option] = distance; + } + } + + return Object.keys(optionsByDistance).sort((a, b) => { + const distanceDiff = optionsByDistance[a] - optionsByDistance[b]; + return distanceDiff !== 0 ? distanceDiff : naturalCompare(a, b); + }); +} +/** + * Computes the lexical distance between strings A and B. + * + * The "distance" between two strings is given by counting the minimum number + * of edits needed to transform string A into string B. An edit can be an + * insertion, deletion, or substitution of a single character, or a swap of two + * adjacent characters. + * + * Includes a custom alteration from Damerau-Levenshtein to treat case changes + * as a single edit which helps identify mis-cased values with an edit distance + * of 1. + * + * This distance can be useful for detecting typos in input or sorting + * + * @internal + */ + +class LexicalDistance { + constructor(input) { + this._input = input; + this._inputLowerCase = input.toLowerCase(); + this._inputArray = stringToArray(this._inputLowerCase); + this._rows = [ + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + new Array(input.length + 1).fill(0), + ]; + } + + measure(option, threshold) { + if (this._input === option) { + return 0; + } + + const optionLowerCase = option.toLowerCase(); // Any case change counts as a single edit + + if (this._inputLowerCase === optionLowerCase) { + return 1; + } + + let a = stringToArray(optionLowerCase); + let b = this._inputArray; + + if (a.length < b.length) { + const tmp = a; + a = b; + b = tmp; + } + + const aLength = a.length; + const bLength = b.length; + + if (aLength - bLength > threshold) { + return undefined; + } + + const rows = this._rows; + + for (let j = 0; j <= bLength; j++) { + rows[0][j] = j; + } + + for (let i = 1; i <= aLength; i++) { + const upRow = rows[(i - 1) % 3]; + const currentRow = rows[i % 3]; + let smallestCell = (currentRow[0] = i); + + for (let j = 1; j <= bLength; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + let currentCell = Math.min( + upRow[j] + 1, // delete + currentRow[j - 1] + 1, // insert + upRow[j - 1] + cost, // substitute + ); + + if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { + // transposition + const doubleDiagonalCell = rows[(i - 2) % 3][j - 2]; + currentCell = Math.min(currentCell, doubleDiagonalCell + 1); + } + + if (currentCell < smallestCell) { + smallestCell = currentCell; + } + + currentRow[j] = currentCell; + } // Early exit, since distance can't go smaller than smallest element of the previous row. + + if (smallestCell > threshold) { + return undefined; + } + } + + const distance = rows[aLength % 3][bLength]; + return distance <= threshold ? distance : undefined; + } +} + +function stringToArray(str) { + const strLength = str.length; + const array = new Array(strLength); + + for (let i = 0; i < strLength; ++i) { + array[i] = str.charCodeAt(i); + } + + return array; +} diff --git a/node_modules/graphql/jsutils/toError.d.ts b/node_modules/graphql/jsutils/toError.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..58bff7aab8bcd7d35843d750588c0de42aacc535 --- /dev/null +++ b/node_modules/graphql/jsutils/toError.d.ts @@ -0,0 +1,6 @@ +/** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + * + * @internal + */ +export declare function toError(thrownValue: unknown): Error; diff --git a/node_modules/graphql/jsutils/toError.js b/node_modules/graphql/jsutils/toError.js new file mode 100644 index 0000000000000000000000000000000000000000..eee2849524600d58f953d766e2cb10bc57e528e9 --- /dev/null +++ b/node_modules/graphql/jsutils/toError.js @@ -0,0 +1,27 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.toError = toError; + +var _inspect = require('./inspect.js'); + +/** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + * + * @internal + */ +function toError(thrownValue) { + return thrownValue instanceof Error + ? thrownValue + : new NonErrorThrown(thrownValue); +} + +class NonErrorThrown extends Error { + constructor(thrownValue) { + super('Unexpected error value: ' + (0, _inspect.inspect)(thrownValue)); + this.name = 'NonErrorThrown'; + this.thrownValue = thrownValue; + } +} diff --git a/node_modules/graphql/jsutils/toError.mjs b/node_modules/graphql/jsutils/toError.mjs new file mode 100644 index 0000000000000000000000000000000000000000..12e9e32e44f1197d4b106b2ab48fdf8920435a2e --- /dev/null +++ b/node_modules/graphql/jsutils/toError.mjs @@ -0,0 +1,20 @@ +import { inspect } from './inspect.mjs'; +/** + * Sometimes a non-error is thrown, wrap it as an Error instance to ensure a consistent Error interface. + * + * @internal + */ + +export function toError(thrownValue) { + return thrownValue instanceof Error + ? thrownValue + : new NonErrorThrown(thrownValue); +} + +class NonErrorThrown extends Error { + constructor(thrownValue) { + super('Unexpected error value: ' + inspect(thrownValue)); + this.name = 'NonErrorThrown'; + this.thrownValue = thrownValue; + } +} diff --git a/node_modules/graphql/jsutils/toObjMap.d.ts b/node_modules/graphql/jsutils/toObjMap.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..02be316fee70582aafb823c457c67dd29ad2579e --- /dev/null +++ b/node_modules/graphql/jsutils/toObjMap.d.ts @@ -0,0 +1,6 @@ +import type { Maybe } from './Maybe'; +import type { ReadOnlyObjMap, ReadOnlyObjMapLike } from './ObjMap'; +/** @internal */ +export declare function toObjMap( + obj: Maybe>, +): ReadOnlyObjMap; diff --git a/node_modules/graphql/jsutils/toObjMap.js b/node_modules/graphql/jsutils/toObjMap.js new file mode 100644 index 0000000000000000000000000000000000000000..f0244da5bc953e1db173c9359fd37446928d1562 --- /dev/null +++ b/node_modules/graphql/jsutils/toObjMap.js @@ -0,0 +1,25 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.toObjMap = toObjMap; + +/** @internal */ +function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + const map = Object.create(null); + + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + + return map; +} diff --git a/node_modules/graphql/jsutils/toObjMap.mjs b/node_modules/graphql/jsutils/toObjMap.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb9fa4e28086f80a432f705e5b110495603c461f --- /dev/null +++ b/node_modules/graphql/jsutils/toObjMap.mjs @@ -0,0 +1,18 @@ +/** @internal */ +export function toObjMap(obj) { + if (obj == null) { + return Object.create(null); + } + + if (Object.getPrototypeOf(obj) === null) { + return obj; + } + + const map = Object.create(null); + + for (const [key, value] of Object.entries(obj)) { + map[key] = value; + } + + return map; +} diff --git a/node_modules/graphql/language/ast.d.ts b/node_modules/graphql/language/ast.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9987cc83fcdb8a1e786914c86c2c1329f11f12d6 --- /dev/null +++ b/node_modules/graphql/language/ast.d.ts @@ -0,0 +1,949 @@ +/** @category AST */ +import type { Kind } from './kinds'; +import type { Source } from './source'; +import type { TokenKind } from './tokenKind'; +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export declare class Location { + /** The character offset at which this Node begins. */ + readonly start: number; + /** The character offset at which this Node ends. */ + readonly end: number; + /** The Token at which this Node begins. */ + readonly startToken: Token; + /** The Token at which this Node ends. */ + readonly endToken: Token; + /** The Source document the AST represents. */ + readonly source: Source; + /** + * Creates a Location instance. + * @param startToken - The start token. + * @param endToken - The end token. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Location, Source, Token, TokenKind } from 'graphql/language'; + * + * const source = new Source('{ hello }'); + * const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1); + * const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9); + * const location = new Location(startToken, endToken, source); + * + * location.start; // => 0 + * location.end; // => 9 + * location.source.body; // => '{ hello }' + * ``` + */ + constructor(startToken: Token, endToken: Token, source: Source); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns a JSON representation of this location. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * const location = document.loc?.toJSON(); + * + * location; // => { start: 0, end: 9 } + * ``` + */ + toJSON(): { + start: number; + end: number; + }; +} +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ +export declare class Token { + /** The kind of Token. */ + readonly kind: TokenKind; + /** The character offset at which this Node begins. */ + readonly start: number; + /** The character offset at which this Node ends. */ + readonly end: number; + /** The 1-indexed line number on which this Token appears. */ + readonly line: number; + /** The 1-indexed column number at which this Token begins. */ + readonly column: number; + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + readonly value: string; + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + readonly prev: Token | null; + /** Next token in the token stream, including ignored tokens. */ + readonly next: Token | null; + /** + * Creates a Token instance. + * @param kind - Token kind produced by lexical analysis. + * @param start - Character offset where this token begins. + * @param end - Character offset where this token ends. + * @param line - One-indexed line number where this token begins. + * @param column - One-indexed column number where this token begins. + * @param value - Interpreted value for non-punctuation tokens. + * @example + * ```ts + * import { Token, TokenKind } from 'graphql/language'; + * + * const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello'); + * + * token.kind; // => TokenKind.NAME + * token.value; // => 'hello' + * token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 } + * ``` + */ + constructor( + kind: TokenKind, + start: number, + end: number, + line: number, + column: number, + value?: string, + ); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns a JSON representation of this token. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance().toJSON(); + * + * token; // => { kind: '{', value: undefined, line: 1, column: 1 } + * ``` + */ + toJSON(): { + kind: TokenKind; + value?: string; + line: number; + column: number; + }; +} +/** The list of all possible AST node types. */ +export declare type ASTNode = + | NameNode + | DocumentNode + | OperationDefinitionNode + | VariableDefinitionNode + | VariableNode + | SelectionSetNode + | FieldNode + | ArgumentNode + | FragmentSpreadNode + | InlineFragmentNode + | FragmentDefinitionNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode + | ObjectFieldNode + | DirectiveNode + | NamedTypeNode + | ListTypeNode + | NonNullTypeNode + | SchemaDefinitionNode + | OperationTypeDefinitionNode + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | FieldDefinitionNode + | InputValueDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | EnumValueDefinitionNode + | InputObjectTypeDefinitionNode + | DirectiveDefinitionNode + | SchemaExtensionNode + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode + | DirectiveExtensionNode + | TypeCoordinateNode + | MemberCoordinateNode + | ArgumentCoordinateNode + | DirectiveCoordinateNode + | DirectiveArgumentCoordinateNode; +/** Utility type listing all nodes indexed by their kind. */ +export declare type ASTKindToNode = { + [NodeT in ASTNode as NodeT['kind']]: NodeT; +}; +/** @internal */ +export declare const QueryDocumentKeys: { + [NodeT in ASTNode as NodeT['kind']]: ReadonlyArray; +}; +/** @internal */ +export declare function isNode(maybeNode: any): maybeNode is ASTNode; +/** An identifier in a GraphQL document. */ +export interface NameNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.NAME; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: string; +} +/** The root AST node for a parsed GraphQL document. */ +export interface DocumentNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DOCUMENT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Top-level executable and type-system definitions in this document. */ + readonly definitions: ReadonlyArray; + /** The number of lexical tokens parsed for this document, if token counting was enabled. */ + readonly tokenCount?: number | undefined; +} +/** Any top-level definition that may appear in a GraphQL document. */ +export declare type DefinitionNode = + | ExecutableDefinitionNode + | TypeSystemDefinitionNode + | TypeSystemExtensionNode; +/** Any executable definition that may appear in an operation document. */ +export declare type ExecutableDefinitionNode = + | OperationDefinitionNode + | FragmentDefinitionNode; +/** A query, mutation, or subscription operation definition. */ +export interface OperationDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OPERATION_DEFINITION; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The operation selected for execution. */ + readonly operation: OperationTypeNode; + /** Name node identifying this AST node. */ + readonly name?: NameNode; + /** Variable definitions declared by this operation or fragment. */ + readonly variableDefinitions?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Selections made by this operation, field, or fragment. */ + readonly selectionSet: SelectionSetNode; +} +/** + * The operation types supported by GraphQL executable definitions. + * @category Kinds + */ +declare enum OperationTypeNode { + /** A query operation. */ + QUERY = 'query', + /** A mutation operation. */ + MUTATION = 'mutation', + /** A subscription operation. */ + SUBSCRIPTION = 'subscription', +} +export { OperationTypeNode }; +/** A variable declaration in an operation or legacy fragment definition. */ +export interface VariableDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.VARIABLE_DEFINITION; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The variable being defined or referenced. */ + readonly variable: VariableNode; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: TypeNode; + /** Default value used when no explicit value is supplied. */ + readonly defaultValue?: ConstValueNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** A variable reference, such as `$id`. */ +export interface VariableNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.VARIABLE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; +} +/** A set of fields and fragments selected from an object, interface, or union. */ +export interface SelectionSetNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + kind: Kind.SELECTION_SET; + /** The source location for this AST node, if location tracking was enabled. */ + loc?: Location; + /** Fields and fragments contained in this selection set. */ + selections: ReadonlyArray; +} +/** Any selection that may appear inside a selection set. */ +export declare type SelectionNode = + | FieldNode + | FragmentSpreadNode + | InlineFragmentNode; +/** A field selected in an executable GraphQL document. */ +export interface FieldNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.FIELD; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The response-key alias for this field, if one was supplied. */ + readonly alias?: NameNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Arguments supplied to this field, directive, or coordinate. */ + readonly arguments?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Selections made by this operation, field, or fragment. */ + readonly selectionSet?: SelectionSetNode; +} +/** An argument supplied to a field or directive. */ +export interface ArgumentNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ARGUMENT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Parsed value represented by this node. */ + readonly value: ValueNode; +} +/** An argument node whose value is guaranteed to be constant. */ +export interface ConstArgumentNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ARGUMENT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Parsed value represented by this node. */ + readonly value: ConstValueNode; +} +/** A named fragment spread, such as `...userFields`. */ +export interface FragmentSpreadNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.FRAGMENT_SPREAD; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An inline fragment spread with an optional type condition. */ +export interface InlineFragmentNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INLINE_FRAGMENT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The type condition that limits where this fragment applies. */ + readonly typeCondition?: NamedTypeNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Selections made by this operation, field, or fragment. */ + readonly selectionSet: SelectionSetNode; +} +/** A reusable fragment definition declared in an executable document. */ +export interface FragmentDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.FRAGMENT_DEFINITION; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** + * Deprecated variable definitions declared by this legacy fragment + * definition. This legacy fragment variable syntax will be removed in v17. + * Move variable definitions to operations for spec-compliant documents; if + * you need variables or arguments scoped to fragments, v17 has a more + * complete experimental fragment-arguments feature. + * @deprecated variableDefinitions will be removed in v17.0.0 + */ + readonly variableDefinitions?: ReadonlyArray; + /** The type condition that limits where this fragment applies. */ + readonly typeCondition: NamedTypeNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Selections made by this operation, field, or fragment. */ + readonly selectionSet: SelectionSetNode; +} +/** Any value literal that may appear in an executable GraphQL document. */ +export declare type ValueNode = + | VariableNode + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ListValueNode + | ObjectValueNode; +/** Any value literal that is guaranteed not to contain a variable reference. */ +export declare type ConstValueNode = + | IntValueNode + | FloatValueNode + | StringValueNode + | BooleanValueNode + | NullValueNode + | EnumValueNode + | ConstListValueNode + | ConstObjectValueNode; +/** An integer value literal. */ +export interface IntValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: string; +} +/** A floating-point value literal. */ +export interface FloatValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.FLOAT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: string; +} +/** A string value literal. */ +export interface StringValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.STRING; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: string; + /** Whether this string was parsed from block string syntax. */ + readonly block?: boolean; +} +/** A boolean value literal. */ +export interface BooleanValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.BOOLEAN; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: boolean; +} +/** A null value literal. */ +export interface NullValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.NULL; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; +} +/** An enum value literal. */ +export interface EnumValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ENUM; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Parsed value represented by this node. */ + readonly value: string; +} +/** A list value literal. */ +export interface ListValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.LIST; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Values contained in this enum, list, or input-object definition. */ + readonly values: ReadonlyArray; +} +/** A list value literal whose elements are all constant values. */ +export interface ConstListValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.LIST; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Values contained in this enum, list, or input-object definition. */ + readonly values: ReadonlyArray; +} +/** An input object value literal. */ +export interface ObjectValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields: ReadonlyArray; +} +/** An input object value literal whose fields are all constant values. */ +export interface ConstObjectValueNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields: ReadonlyArray; +} +/** A field inside an input object value literal. */ +export interface ObjectFieldNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT_FIELD; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Parsed value represented by this node. */ + readonly value: ValueNode; +} +/** A field inside a constant input object value literal. */ +export interface ConstObjectFieldNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT_FIELD; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Parsed value represented by this node. */ + readonly value: ConstValueNode; +} +/** A directive applied to an executable or type-system location. */ +export interface DirectiveNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Arguments supplied to this field, directive, or coordinate. */ + readonly arguments?: ReadonlyArray; +} +/** A directive whose arguments are all constant values. */ +export interface ConstDirectiveNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Arguments supplied to this field, directive, or coordinate. */ + readonly arguments?: ReadonlyArray; +} +/** Any GraphQL type reference AST node. */ +export declare type TypeNode = NamedTypeNode | ListTypeNode | NonNullTypeNode; +/** A named type reference. */ +export interface NamedTypeNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.NAMED_TYPE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; +} +/** A list type reference. */ +export interface ListTypeNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.LIST_TYPE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: TypeNode; +} +/** A non-null type reference. */ +export interface NonNullTypeNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.NON_NULL_TYPE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: NamedTypeNode | ListTypeNode; +} +/** Any type-system definition that may appear in a schema document. */ +export declare type TypeSystemDefinitionNode = + | SchemaDefinitionNode + | TypeDefinitionNode + | DirectiveDefinitionNode; +/** A schema definition in a type-system document. */ +export interface SchemaDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.SCHEMA_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Root operation types declared by this schema definition or extension. */ + readonly operationTypes: ReadonlyArray; +} +/** A root operation type declaration inside a schema definition or extension. */ +export interface OperationTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OPERATION_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The operation selected for execution. */ + readonly operation: OperationTypeNode; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: NamedTypeNode; +} +/** Any named type definition that may appear in a schema document. */ +export declare type TypeDefinitionNode = + | ScalarTypeDefinitionNode + | ObjectTypeDefinitionNode + | InterfaceTypeDefinitionNode + | UnionTypeDefinitionNode + | EnumTypeDefinitionNode + | InputObjectTypeDefinitionNode; +/** A scalar type definition in a type-system document. */ +export interface ScalarTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.SCALAR_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An object type definition in a type-system document. */ +export interface ObjectTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** A field definition declared by an object or interface type. */ +export interface FieldDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.FIELD_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Arguments supplied to this field, directive, or coordinate. */ + readonly arguments?: ReadonlyArray; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: TypeNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An argument or input-field definition. */ +export interface InputValueDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INPUT_VALUE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: TypeNode; + /** Default value used when no explicit value is supplied. */ + readonly defaultValue?: ConstValueNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An interface type definition in a type-system document. */ +export interface InterfaceTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INTERFACE_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** A union type definition in a type-system document. */ +export interface UnionTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.UNION_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Object types that belong to this union type. */ + readonly types?: ReadonlyArray; +} +/** An enum type definition in a type-system document. */ +export interface EnumTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ENUM_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Values contained in this enum, list, or input-object definition. */ + readonly values?: ReadonlyArray; +} +/** An enum value definition. */ +export interface EnumValueDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ENUM_VALUE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An input object type definition in a type-system document. */ +export interface InputObjectTypeDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INPUT_OBJECT_TYPE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** A directive definition in a type-system document. */ +export interface DirectiveDefinitionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE_DEFINITION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** The optional GraphQL description associated with this definition. */ + readonly description?: StringValueNode; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Arguments supplied to this field, directive, or coordinate. */ + readonly arguments?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Whether this directive may appear more than once at the same location. */ + readonly repeatable: boolean; + /** Locations where this directive may be applied. */ + readonly locations: ReadonlyArray; +} +/** Any type-system extension that may appear in a schema extension document. */ +export declare type TypeSystemExtensionNode = + | SchemaExtensionNode + | TypeExtensionNode + | DirectiveExtensionNode; +/** A schema extension in a type-system document. */ +export interface SchemaExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.SCHEMA_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Root operation types declared by this schema definition or extension. */ + readonly operationTypes?: ReadonlyArray; +} +/** Any named type extension that may appear in a schema extension document. */ +export declare type TypeExtensionNode = + | ScalarTypeExtensionNode + | ObjectTypeExtensionNode + | InterfaceTypeExtensionNode + | UnionTypeExtensionNode + | EnumTypeExtensionNode + | InputObjectTypeExtensionNode; +/** A scalar type extension. */ +export interface ScalarTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.SCALAR_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** An object type extension. */ +export interface ObjectTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.OBJECT_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** An interface type extension. */ +export interface InterfaceTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INTERFACE_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces?: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** A union type extension. */ +export interface UnionTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.UNION_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Object types that belong to this union type. */ + readonly types?: ReadonlyArray; +} +/** An enum type extension. */ +export interface EnumTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ENUM_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Values contained in this enum, list, or input-object definition. */ + readonly values?: ReadonlyArray; +} +/** An input object type extension. */ +export interface InputObjectTypeExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.INPUT_OBJECT_TYPE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields?: ReadonlyArray; +} +/** A directive extension. */ +export interface DirectiveExtensionNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE_EXTENSION; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** Directives available in this schema or applied to this AST node. */ + readonly directives?: ReadonlyArray; +} +/** Any AST node representing a GraphQL schema coordinate. */ +export declare type SchemaCoordinateNode = + | TypeCoordinateNode + | MemberCoordinateNode + | ArgumentCoordinateNode + | DirectiveCoordinateNode + | DirectiveArgumentCoordinateNode; +/** A schema coordinate that refers to a named type. */ +export interface TypeCoordinateNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.TYPE_COORDINATE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; +} +/** A schema coordinate that refers to a member of a named type. */ +export interface MemberCoordinateNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.MEMBER_COORDINATE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** The member name referenced by this schema coordinate. */ + readonly memberName: NameNode; +} +/** A schema coordinate that refers to a field or directive argument. */ +export interface ArgumentCoordinateNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.ARGUMENT_COORDINATE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** The field name referenced by this schema coordinate. */ + readonly fieldName: NameNode; + /** The argument name referenced by this schema coordinate. */ + readonly argumentName: NameNode; +} +/** A schema coordinate that refers to a directive. */ +export interface DirectiveCoordinateNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE_COORDINATE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; +} +/** A schema coordinate that refers to a directive argument. */ +export interface DirectiveArgumentCoordinateNode { + /** The discriminator identifying the concrete AST or introspection kind. */ + readonly kind: Kind.DIRECTIVE_ARGUMENT_COORDINATE; + /** The source location for this AST node, if location tracking was enabled. */ + readonly loc?: Location; + /** Name node identifying this AST node. */ + readonly name: NameNode; + /** The argument name referenced by this schema coordinate. */ + readonly argumentName: NameNode; +} diff --git a/node_modules/graphql/language/ast.js b/node_modules/graphql/language/ast.js new file mode 100644 index 0000000000000000000000000000000000000000..d8264e375f980a928f8ae6238c67f7dcbe00c616 --- /dev/null +++ b/node_modules/graphql/language/ast.js @@ -0,0 +1,301 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.Token = + exports.QueryDocumentKeys = + exports.OperationTypeNode = + exports.Location = + void 0; +exports.isNode = isNode; + +/** @category AST */ + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +class Location { + /** The character offset at which this Node begins. */ + + /** The character offset at which this Node ends. */ + + /** The Token at which this Node begins. */ + + /** The Token at which this Node ends. */ + + /** The Source document the AST represents. */ + + /** + * Creates a Location instance. + * @param startToken - The start token. + * @param endToken - The end token. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Location, Source, Token, TokenKind } from 'graphql/language'; + * + * const source = new Source('{ hello }'); + * const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1); + * const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9); + * const location = new Location(startToken, endToken, source); + * + * location.start; // => 0 + * location.end; // => 9 + * location.source.body; // => '{ hello }' + * ``` + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Location'; + } + /** + * Returns a JSON representation of this location. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * const location = document.loc?.toJSON(); + * + * location; // => { start: 0, end: 9 } + * ``` + */ + + toJSON() { + return { + start: this.start, + end: this.end, + }; + } +} +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + +exports.Location = Location; + +class Token { + /** The kind of Token. */ + + /** The character offset at which this Node begins. */ + + /** The character offset at which this Node ends. */ + + /** The 1-indexed line number on which this Token appears. */ + + /** The 1-indexed column number at which this Token begins. */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + + /** Next token in the token stream, including ignored tokens. */ + + /** + * Creates a Token instance. + * @param kind - Token kind produced by lexical analysis. + * @param start - Character offset where this token begins. + * @param end - Character offset where this token ends. + * @param line - One-indexed line number where this token begins. + * @param column - One-indexed column number where this token begins. + * @param value - Interpreted value for non-punctuation tokens. + * @example + * ```ts + * import { Token, TokenKind } from 'graphql/language'; + * + * const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello'); + * + * token.kind; // => TokenKind.NAME + * token.value; // => 'hello' + * token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 } + * ``` + */ + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Token'; + } + /** + * Returns a JSON representation of this token. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance().toJSON(); + * + * token; // => { kind: '{', value: undefined, line: 1, column: 1 } + * ``` + */ + + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; + } +} +/** The list of all possible AST node types. */ + +exports.Token = Token; + +/** @internal */ +const QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: [ + 'description', + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: [ + 'description', + 'variable', + 'type', + 'defaultValue', + 'directives', + ], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'description', + 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: [ + 'description', + 'name', + 'arguments', + 'directives', + 'locations', + ], + SchemaExtension: ['directives', 'operationTypes'], + DirectiveExtension: ['name', 'directives'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], + TypeCoordinate: ['name'], + MemberCoordinate: ['name', 'memberName'], + ArgumentCoordinate: ['name', 'fieldName', 'argumentName'], + DirectiveCoordinate: ['name'], + DirectiveArgumentCoordinate: ['name', 'argumentName'], +}; +exports.QueryDocumentKeys = QueryDocumentKeys; +const kindValues = new Set(Object.keys(QueryDocumentKeys)); +/** @internal */ + +function isNode(maybeNode) { + const maybeKind = + maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; + return typeof maybeKind === 'string' && kindValues.has(maybeKind); +} +/** An identifier in a GraphQL document. */ + +/** + * The operation types supported by GraphQL executable definitions. + * @category Kinds + */ +var OperationTypeNode; +exports.OperationTypeNode = OperationTypeNode; + +(function (OperationTypeNode) { + OperationTypeNode['QUERY'] = 'query'; + OperationTypeNode['MUTATION'] = 'mutation'; + OperationTypeNode['SUBSCRIPTION'] = 'subscription'; +})(OperationTypeNode || (exports.OperationTypeNode = OperationTypeNode = {})); +/** A variable declaration in an operation or legacy fragment definition. */ diff --git a/node_modules/graphql/language/ast.mjs b/node_modules/graphql/language/ast.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5f5aa1b9d6b5e2997efb902cf95d036668e5ebdb --- /dev/null +++ b/node_modules/graphql/language/ast.mjs @@ -0,0 +1,285 @@ +/** @category AST */ + +/** + * Contains a range of UTF-8 character offsets and token references that + * identify the region of the source from which the AST derived. + */ +export class Location { + /** The character offset at which this Node begins. */ + + /** The character offset at which this Node ends. */ + + /** The Token at which this Node begins. */ + + /** The Token at which this Node ends. */ + + /** The Source document the AST represents. */ + + /** + * Creates a Location instance. + * @param startToken - The start token. + * @param endToken - The end token. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Location, Source, Token, TokenKind } from 'graphql/language'; + * + * const source = new Source('{ hello }'); + * const startToken = new Token(TokenKind.BRACE_L, 0, 1, 1, 1); + * const endToken = new Token(TokenKind.BRACE_R, 8, 9, 1, 9); + * const location = new Location(startToken, endToken, source); + * + * location.start; // => 0 + * location.end; // => 9 + * location.source.body; // => '{ hello }' + * ``` + */ + constructor(startToken, endToken, source) { + this.start = startToken.start; + this.end = endToken.end; + this.startToken = startToken; + this.endToken = endToken; + this.source = source; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Location'; + } + /** + * Returns a JSON representation of this location. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * const location = document.loc?.toJSON(); + * + * location; // => { start: 0, end: 9 } + * ``` + */ + + toJSON() { + return { + start: this.start, + end: this.end, + }; + } +} +/** + * Represents a range of characters represented by a lexical token + * within a Source. + */ + +export class Token { + /** The kind of Token. */ + + /** The character offset at which this Node begins. */ + + /** The character offset at which this Node ends. */ + + /** The 1-indexed line number on which this Token appears. */ + + /** The 1-indexed column number at which this Token begins. */ + + /** + * For non-punctuation tokens, represents the interpreted value of the token. + * + * Note: is undefined for punctuation tokens, but typed as string for + * convenience in the parser. + */ + + /** + * Tokens exist as nodes in a double-linked-list amongst all tokens + * including ignored tokens. is always the first node and + * the last. + */ + + /** Next token in the token stream, including ignored tokens. */ + + /** + * Creates a Token instance. + * @param kind - Token kind produced by lexical analysis. + * @param start - Character offset where this token begins. + * @param end - Character offset where this token ends. + * @param line - One-indexed line number where this token begins. + * @param column - One-indexed column number where this token begins. + * @param value - Interpreted value for non-punctuation tokens. + * @example + * ```ts + * import { Token, TokenKind } from 'graphql/language'; + * + * const token = new Token(TokenKind.NAME, 2, 7, 1, 3, 'hello'); + * + * token.kind; // => TokenKind.NAME + * token.value; // => 'hello' + * token.toJSON(); // => { kind: 'Name', value: 'hello', line: 1, column: 3 } + * ``` + */ + constructor(kind, start, end, line, column, value) { + this.kind = kind; + this.start = start; + this.end = end; + this.line = line; + this.column = column; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + + this.value = value; + this.prev = null; + this.next = null; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Token'; + } + /** + * Returns a JSON representation of this token. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance().toJSON(); + * + * token; // => { kind: '{', value: undefined, line: 1, column: 1 } + * ``` + */ + + toJSON() { + return { + kind: this.kind, + value: this.value, + line: this.line, + column: this.column, + }; + } +} +/** The list of all possible AST node types. */ + +/** @internal */ +export const QueryDocumentKeys = { + Name: [], + Document: ['definitions'], + OperationDefinition: [ + 'description', + 'name', + 'variableDefinitions', + 'directives', + 'selectionSet', + ], + VariableDefinition: [ + 'description', + 'variable', + 'type', + 'defaultValue', + 'directives', + ], + Variable: ['name'], + SelectionSet: ['selections'], + Field: ['alias', 'name', 'arguments', 'directives', 'selectionSet'], + Argument: ['name', 'value'], + FragmentSpread: ['name', 'directives'], + InlineFragment: ['typeCondition', 'directives', 'selectionSet'], + FragmentDefinition: [ + 'description', + 'name', // Note: fragment variable definitions are deprecated and will removed in v17.0.0 + 'variableDefinitions', + 'typeCondition', + 'directives', + 'selectionSet', + ], + IntValue: [], + FloatValue: [], + StringValue: [], + BooleanValue: [], + NullValue: [], + EnumValue: [], + ListValue: ['values'], + ObjectValue: ['fields'], + ObjectField: ['name', 'value'], + Directive: ['name', 'arguments'], + NamedType: ['name'], + ListType: ['type'], + NonNullType: ['type'], + SchemaDefinition: ['description', 'directives', 'operationTypes'], + OperationTypeDefinition: ['type'], + ScalarTypeDefinition: ['description', 'name', 'directives'], + ObjectTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + FieldDefinition: ['description', 'name', 'arguments', 'type', 'directives'], + InputValueDefinition: [ + 'description', + 'name', + 'type', + 'defaultValue', + 'directives', + ], + InterfaceTypeDefinition: [ + 'description', + 'name', + 'interfaces', + 'directives', + 'fields', + ], + UnionTypeDefinition: ['description', 'name', 'directives', 'types'], + EnumTypeDefinition: ['description', 'name', 'directives', 'values'], + EnumValueDefinition: ['description', 'name', 'directives'], + InputObjectTypeDefinition: ['description', 'name', 'directives', 'fields'], + DirectiveDefinition: [ + 'description', + 'name', + 'arguments', + 'directives', + 'locations', + ], + SchemaExtension: ['directives', 'operationTypes'], + DirectiveExtension: ['name', 'directives'], + ScalarTypeExtension: ['name', 'directives'], + ObjectTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + InterfaceTypeExtension: ['name', 'interfaces', 'directives', 'fields'], + UnionTypeExtension: ['name', 'directives', 'types'], + EnumTypeExtension: ['name', 'directives', 'values'], + InputObjectTypeExtension: ['name', 'directives', 'fields'], + TypeCoordinate: ['name'], + MemberCoordinate: ['name', 'memberName'], + ArgumentCoordinate: ['name', 'fieldName', 'argumentName'], + DirectiveCoordinate: ['name'], + DirectiveArgumentCoordinate: ['name', 'argumentName'], +}; +const kindValues = new Set(Object.keys(QueryDocumentKeys)); +/** @internal */ + +export function isNode(maybeNode) { + const maybeKind = + maybeNode === null || maybeNode === void 0 ? void 0 : maybeNode.kind; + return typeof maybeKind === 'string' && kindValues.has(maybeKind); +} +/** An identifier in a GraphQL document. */ + +/** + * The operation types supported by GraphQL executable definitions. + * @category Kinds + */ +var OperationTypeNode; + +(function (OperationTypeNode) { + OperationTypeNode['QUERY'] = 'query'; + OperationTypeNode['MUTATION'] = 'mutation'; + OperationTypeNode['SUBSCRIPTION'] = 'subscription'; +})(OperationTypeNode || (OperationTypeNode = {})); + +export { OperationTypeNode }; +/** A variable declaration in an operation or legacy fragment definition. */ diff --git a/node_modules/graphql/language/blockString.d.ts b/node_modules/graphql/language/blockString.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5cc7416af40090a7b51043c9db05cbb01f6bc677 --- /dev/null +++ b/node_modules/graphql/language/blockString.d.ts @@ -0,0 +1,26 @@ +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +export declare function dedentBlockStringLines( + lines: ReadonlyArray, +): Array; +/** @internal */ +export declare function isPrintableAsBlockString(value: string): boolean; +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ +export declare function printBlockString( + value: string, + options?: { + minimize?: boolean; + }, +): string; diff --git a/node_modules/graphql/language/blockString.js b/node_modules/graphql/language/blockString.js new file mode 100644 index 0000000000000000000000000000000000000000..71f02a50cf4eb52b176224efc5eb4df82a33d981 --- /dev/null +++ b/node_modules/graphql/language/blockString.js @@ -0,0 +1,193 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.dedentBlockStringLines = dedentBlockStringLines; +exports.isPrintableAsBlockString = isPrintableAsBlockString; +exports.printBlockString = printBlockString; + +var _characterClasses = require('./characterClasses.js'); + +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ +function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + + const line = lines[i]; + const indent = leadingWhitespace(line); + + if (indent === line.length) { + continue; // skip empty lines + } + + firstNonEmptyLine = + (_firstNonEmptyLine = firstNonEmptyLine) !== null && + _firstNonEmptyLine !== void 0 + ? _firstNonEmptyLine + : i; + lastNonEmptyLine = i; + + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + + return lines // Remove common indentation from all lines but first. + .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines. + .slice( + (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && + _firstNonEmptyLine2 !== void 0 + ? _firstNonEmptyLine2 + : 0, + lastNonEmptyLine + 1, + ); +} + +function leadingWhitespace(str) { + let i = 0; + + while ( + i < str.length && + (0, _characterClasses.isWhiteSpace)(str.charCodeAt(i)) + ) { + ++i; + } + + return i; +} +/** @internal */ + +function isPrintableAsBlockString(value) { + if (value === '') { + return true; // empty string is printable + } + + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters + + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line + } + + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; + } + } + + if (isEmptyLine) { + return false; // Has trailing empty lines + } + + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent + } + + return true; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + +function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = + lines.length > 1 && + lines + .slice(1) + .every( + (line) => + line.length === 0 || + (0, _characterClasses.isWhiteSpace)(line.charCodeAt(0)), + ); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith('\\'); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = + !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability + (!isSingleLine || + value.length > 70 || + forceTrailingNewline || + forceLeadingNewLine || + hasTrailingTripleQuotes); + let result = ''; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = + isSingleLine && (0, _characterClasses.isWhiteSpace)(value.charCodeAt(0)); + + if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) { + result += '\n'; + } + + result += escapedValue; + + if (printAsMultipleLines || forceTrailingNewline) { + result += '\n'; + } + + return '"""' + result + '"""'; +} diff --git a/node_modules/graphql/language/blockString.mjs b/node_modules/graphql/language/blockString.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ab8727b7fc1a4bbb8a08ce6683263f8c9c9fae81 --- /dev/null +++ b/node_modules/graphql/language/blockString.mjs @@ -0,0 +1,176 @@ +import { isWhiteSpace } from './characterClasses.mjs'; +/** + * Produces the value of a block string from its parsed raw value, similar to + * CoffeeScript's block string, Python's docstring trim or Ruby's strip_heredoc. + * + * This implements the GraphQL spec's BlockStringValue() static algorithm. + * + * @internal + */ + +export function dedentBlockStringLines(lines) { + var _firstNonEmptyLine2; + + let commonIndent = Number.MAX_SAFE_INTEGER; + let firstNonEmptyLine = null; + let lastNonEmptyLine = -1; + + for (let i = 0; i < lines.length; ++i) { + var _firstNonEmptyLine; + + const line = lines[i]; + const indent = leadingWhitespace(line); + + if (indent === line.length) { + continue; // skip empty lines + } + + firstNonEmptyLine = + (_firstNonEmptyLine = firstNonEmptyLine) !== null && + _firstNonEmptyLine !== void 0 + ? _firstNonEmptyLine + : i; + lastNonEmptyLine = i; + + if (i !== 0 && indent < commonIndent) { + commonIndent = indent; + } + } + + return lines // Remove common indentation from all lines but first. + .map((line, i) => (i === 0 ? line : line.slice(commonIndent))) // Remove leading and trailing blank lines. + .slice( + (_firstNonEmptyLine2 = firstNonEmptyLine) !== null && + _firstNonEmptyLine2 !== void 0 + ? _firstNonEmptyLine2 + : 0, + lastNonEmptyLine + 1, + ); +} + +function leadingWhitespace(str) { + let i = 0; + + while (i < str.length && isWhiteSpace(str.charCodeAt(i))) { + ++i; + } + + return i; +} +/** @internal */ + +export function isPrintableAsBlockString(value) { + if (value === '') { + return true; // empty string is printable + } + + let isEmptyLine = true; + let hasIndent = false; + let hasCommonIndent = true; + let seenNonEmptyLine = false; + + for (let i = 0; i < value.length; ++i) { + switch (value.codePointAt(i)) { + case 0x0000: + case 0x0001: + case 0x0002: + case 0x0003: + case 0x0004: + case 0x0005: + case 0x0006: + case 0x0007: + case 0x0008: + case 0x000b: + case 0x000c: + case 0x000e: + case 0x000f: + return false; + // Has non-printable characters + + case 0x000d: + // \r + return false; + // Has \r or \r\n which will be replaced as \n + + case 10: + // \n + if (isEmptyLine && !seenNonEmptyLine) { + return false; // Has leading new line + } + + seenNonEmptyLine = true; + isEmptyLine = true; + hasIndent = false; + break; + + case 9: // \t + + case 32: + // + hasIndent || (hasIndent = isEmptyLine); + break; + + default: + hasCommonIndent && (hasCommonIndent = hasIndent); + isEmptyLine = false; + } + } + + if (isEmptyLine) { + return false; // Has trailing empty lines + } + + if (hasCommonIndent && seenNonEmptyLine) { + return false; // Has internal indent + } + + return true; +} +/** + * Print a block string in the indented block form by adding a leading and + * trailing blank line. However, if a block string starts with whitespace and is + * a single-line, adding a leading blank line would strip that whitespace. + * + * @internal + */ + +export function printBlockString(value, options) { + const escapedValue = value.replace(/"""/g, '\\"""'); // Expand a block string's raw value into independent lines. + + const lines = escapedValue.split(/\r\n|[\n\r]/g); + const isSingleLine = lines.length === 1; // If common indentation is found we can fix some of those cases by adding leading new line + + const forceLeadingNewLine = + lines.length > 1 && + lines + .slice(1) + .every((line) => line.length === 0 || isWhiteSpace(line.charCodeAt(0))); // Trailing triple quotes just looks confusing but doesn't force trailing new line + + const hasTrailingTripleQuotes = escapedValue.endsWith('\\"""'); // Trailing quote (single or double) or slash forces trailing new line + + const hasTrailingQuote = value.endsWith('"') && !hasTrailingTripleQuotes; + const hasTrailingSlash = value.endsWith('\\'); + const forceTrailingNewline = hasTrailingQuote || hasTrailingSlash; + const printAsMultipleLines = + !(options !== null && options !== void 0 && options.minimize) && // add leading and trailing new lines only if it improves readability + (!isSingleLine || + value.length > 70 || + forceTrailingNewline || + forceLeadingNewLine || + hasTrailingTripleQuotes); + let result = ''; // Format a multi-line block quote to account for leading space. + + const skipLeadingNewLine = isSingleLine && isWhiteSpace(value.charCodeAt(0)); + + if ((printAsMultipleLines && !skipLeadingNewLine) || forceLeadingNewLine) { + result += '\n'; + } + + result += escapedValue; + + if (printAsMultipleLines || forceTrailingNewline) { + result += '\n'; + } + + return '"""' + result + '"""'; +} diff --git a/node_modules/graphql/language/characterClasses.d.ts b/node_modules/graphql/language/characterClasses.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1e5da8ae5295d359d3c42dbf15613a58ca18a95f --- /dev/null +++ b/node_modules/graphql/language/characterClasses.d.ts @@ -0,0 +1,47 @@ +/** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ +export declare function isWhiteSpace(code: number): boolean; +/** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ +export declare function isDigit(code: number): boolean; +/** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ +export declare function isLetter(code: number): boolean; +/** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ +export declare function isNameStart(code: number): boolean; +/** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ +export declare function isNameContinue(code: number): boolean; diff --git a/node_modules/graphql/language/characterClasses.js b/node_modules/graphql/language/characterClasses.js new file mode 100644 index 0000000000000000000000000000000000000000..075f740e169468b0e0bee5292f52f5429cdd11e9 --- /dev/null +++ b/node_modules/graphql/language/characterClasses.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isDigit = isDigit; +exports.isLetter = isLetter; +exports.isNameContinue = isNameContinue; +exports.isNameStart = isNameStart; +exports.isWhiteSpace = isWhiteSpace; + +/** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ +function isWhiteSpace(code) { + return code === 0x0009 || code === 0x0020; +} +/** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + +function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; +} +/** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + +function isLetter(code) { + return ( + (code >= 0x0061 && code <= 0x007a) || // A-Z + (code >= 0x0041 && code <= 0x005a) // a-z + ); +} +/** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + +function isNameStart(code) { + return isLetter(code) || code === 0x005f; +} +/** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + +function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; +} diff --git a/node_modules/graphql/language/characterClasses.mjs b/node_modules/graphql/language/characterClasses.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c75777a7e29ab3efb69dde06677f08d258d09449 --- /dev/null +++ b/node_modules/graphql/language/characterClasses.mjs @@ -0,0 +1,64 @@ +/** + * ``` + * WhiteSpace :: + * - "Horizontal Tab (U+0009)" + * - "Space (U+0020)" + * ``` + * @internal + */ +export function isWhiteSpace(code) { + return code === 0x0009 || code === 0x0020; +} +/** + * ``` + * Digit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * ``` + * @internal + */ + +export function isDigit(code) { + return code >= 0x0030 && code <= 0x0039; +} +/** + * ``` + * Letter :: one of + * - `A` `B` `C` `D` `E` `F` `G` `H` `I` `J` `K` `L` `M` + * - `N` `O` `P` `Q` `R` `S` `T` `U` `V` `W` `X` `Y` `Z` + * - `a` `b` `c` `d` `e` `f` `g` `h` `i` `j` `k` `l` `m` + * - `n` `o` `p` `q` `r` `s` `t` `u` `v` `w` `x` `y` `z` + * ``` + * @internal + */ + +export function isLetter(code) { + return ( + (code >= 0x0061 && code <= 0x007a) || // A-Z + (code >= 0x0041 && code <= 0x005a) // a-z + ); +} +/** + * ``` + * NameStart :: + * - Letter + * - `_` + * ``` + * @internal + */ + +export function isNameStart(code) { + return isLetter(code) || code === 0x005f; +} +/** + * ``` + * NameContinue :: + * - Letter + * - Digit + * - `_` + * ``` + * @internal + */ + +export function isNameContinue(code) { + return isLetter(code) || isDigit(code) || code === 0x005f; +} diff --git a/node_modules/graphql/language/directiveLocation.d.ts b/node_modules/graphql/language/directiveLocation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2cfc2d491350e9cd581c59ec4c59ebf1e9c25647 --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.d.ts @@ -0,0 +1,54 @@ +/** @category Kinds */ +/** The set of allowed directive location values. */ +declare enum DirectiveLocation { + /** Directive location for query operations. */ + QUERY = 'QUERY', + /** Directive location for mutation operations. */ + MUTATION = 'MUTATION', + /** Directive location for subscription operations. */ + SUBSCRIPTION = 'SUBSCRIPTION', + /** Directive location for field selections. */ + FIELD = 'FIELD', + /** Directive location for fragment definitions. */ + FRAGMENT_DEFINITION = 'FRAGMENT_DEFINITION', + /** Directive location for fragment spreads. */ + FRAGMENT_SPREAD = 'FRAGMENT_SPREAD', + /** Directive location for inline fragments. */ + INLINE_FRAGMENT = 'INLINE_FRAGMENT', + /** Directive location for variable definitions. */ + VARIABLE_DEFINITION = 'VARIABLE_DEFINITION', + /** Directive location for schema definitions and extensions. */ + SCHEMA = 'SCHEMA', + /** Directive location for scalar type definitions and extensions. */ + SCALAR = 'SCALAR', + /** Directive location for object type definitions and extensions. */ + OBJECT = 'OBJECT', + /** Directive location for field definitions. */ + FIELD_DEFINITION = 'FIELD_DEFINITION', + /** Directive location for argument definitions. */ + ARGUMENT_DEFINITION = 'ARGUMENT_DEFINITION', + /** Directive location for interface type definitions and extensions. */ + INTERFACE = 'INTERFACE', + /** Directive location for union type definitions and extensions. */ + UNION = 'UNION', + /** Directive location for enum type definitions and extensions. */ + ENUM = 'ENUM', + /** Directive location for enum value definitions. */ + ENUM_VALUE = 'ENUM_VALUE', + /** Directive location for input object type definitions and extensions. */ + INPUT_OBJECT = 'INPUT_OBJECT', + /** Directive location for input object field definitions. */ + INPUT_FIELD_DEFINITION = 'INPUT_FIELD_DEFINITION', + /** Directive location for directive definitions and extensions. */ + DIRECTIVE_DEFINITION = 'DIRECTIVE_DEFINITION', +} +export { DirectiveLocation }; +/** + * Deprecated legacy alias for the enum type representing directive location + * values. This alias will be removed in v17. In v17, `DirectiveLocation` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `DirectiveLocation` as both + * the runtime value and the type. + */ +export declare type DirectiveLocationEnum = typeof DirectiveLocation; diff --git a/node_modules/graphql/language/directiveLocation.js b/node_modules/graphql/language/directiveLocation.js new file mode 100644 index 0000000000000000000000000000000000000000..fb790e6e976623618b1a062f1667b7300be3d4c0 --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.js @@ -0,0 +1,43 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.DirectiveLocation = void 0; + +/** @category Kinds */ + +/** The set of allowed directive location values. */ +var DirectiveLocation; +exports.DirectiveLocation = DirectiveLocation; + +(function (DirectiveLocation) { + DirectiveLocation['QUERY'] = 'QUERY'; + DirectiveLocation['MUTATION'] = 'MUTATION'; + DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; + DirectiveLocation['FIELD'] = 'FIELD'; + DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; + DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; + DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; + DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; + DirectiveLocation['SCHEMA'] = 'SCHEMA'; + DirectiveLocation['SCALAR'] = 'SCALAR'; + DirectiveLocation['OBJECT'] = 'OBJECT'; + DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; + DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; + DirectiveLocation['INTERFACE'] = 'INTERFACE'; + DirectiveLocation['UNION'] = 'UNION'; + DirectiveLocation['ENUM'] = 'ENUM'; + DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; + DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; + DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; + DirectiveLocation['DIRECTIVE_DEFINITION'] = 'DIRECTIVE_DEFINITION'; +})(DirectiveLocation || (exports.DirectiveLocation = DirectiveLocation = {})); +/** + * Deprecated legacy alias for the enum type representing directive location + * values. This alias will be removed in v17. In v17, `DirectiveLocation` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `DirectiveLocation` as both + * the runtime value and the type. + */ diff --git a/node_modules/graphql/language/directiveLocation.mjs b/node_modules/graphql/language/directiveLocation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a81d8fa0b13f9a42bdb049c9ca32e3c7552e773d --- /dev/null +++ b/node_modules/graphql/language/directiveLocation.mjs @@ -0,0 +1,37 @@ +/** @category Kinds */ + +/** The set of allowed directive location values. */ +var DirectiveLocation; + +(function (DirectiveLocation) { + DirectiveLocation['QUERY'] = 'QUERY'; + DirectiveLocation['MUTATION'] = 'MUTATION'; + DirectiveLocation['SUBSCRIPTION'] = 'SUBSCRIPTION'; + DirectiveLocation['FIELD'] = 'FIELD'; + DirectiveLocation['FRAGMENT_DEFINITION'] = 'FRAGMENT_DEFINITION'; + DirectiveLocation['FRAGMENT_SPREAD'] = 'FRAGMENT_SPREAD'; + DirectiveLocation['INLINE_FRAGMENT'] = 'INLINE_FRAGMENT'; + DirectiveLocation['VARIABLE_DEFINITION'] = 'VARIABLE_DEFINITION'; + DirectiveLocation['SCHEMA'] = 'SCHEMA'; + DirectiveLocation['SCALAR'] = 'SCALAR'; + DirectiveLocation['OBJECT'] = 'OBJECT'; + DirectiveLocation['FIELD_DEFINITION'] = 'FIELD_DEFINITION'; + DirectiveLocation['ARGUMENT_DEFINITION'] = 'ARGUMENT_DEFINITION'; + DirectiveLocation['INTERFACE'] = 'INTERFACE'; + DirectiveLocation['UNION'] = 'UNION'; + DirectiveLocation['ENUM'] = 'ENUM'; + DirectiveLocation['ENUM_VALUE'] = 'ENUM_VALUE'; + DirectiveLocation['INPUT_OBJECT'] = 'INPUT_OBJECT'; + DirectiveLocation['INPUT_FIELD_DEFINITION'] = 'INPUT_FIELD_DEFINITION'; + DirectiveLocation['DIRECTIVE_DEFINITION'] = 'DIRECTIVE_DEFINITION'; +})(DirectiveLocation || (DirectiveLocation = {})); + +export { DirectiveLocation }; +/** + * Deprecated legacy alias for the enum type representing directive location + * values. This alias will be removed in v17. In v17, `DirectiveLocation` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `DirectiveLocation` as both + * the runtime value and the type. + */ diff --git a/node_modules/graphql/language/index.d.ts b/node_modules/graphql/language/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7164a35360ea64947752dc8981dde88a7b38b03a --- /dev/null +++ b/node_modules/graphql/language/index.d.ts @@ -0,0 +1,117 @@ +/** + * Parse, print, and visit GraphQL language source files and AST nodes. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { Source } from './source'; +export { getLocation } from './location'; +export type { SourceLocation } from './location'; +export { printLocation, printSourceLocation } from './printLocation'; +export { Kind } from './kinds'; +export type { KindEnum } from './kinds'; +export { TokenKind } from './tokenKind'; +export type { TokenKindEnum } from './tokenKind'; +export { Lexer } from './lexer'; +export { + parse, + parseValue, + parseConstValue, + parseType, + parseSchemaCoordinate, +} from './parser'; +export type { ParseOptions } from './parser'; +export { print } from './printer'; +export { + visit, + visitInParallel, + getVisitFn, + getEnterLeaveForKind, + BREAK, +} from './visitor'; +export type { ASTVisitor, ASTVisitFn, ASTVisitorKeyMap } from './visitor'; +export { Location, Token, OperationTypeNode } from './ast'; +export type { + ASTNode, + ASTKindToNode, + NameNode, + DocumentNode, + DefinitionNode, + ExecutableDefinitionNode, + OperationDefinitionNode, + VariableDefinitionNode, + VariableNode, + SelectionSetNode, + SelectionNode, + FieldNode, + ArgumentNode, + ConstArgumentNode, + FragmentSpreadNode, + InlineFragmentNode, + FragmentDefinitionNode, + ValueNode, + ConstValueNode, + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + NullValueNode, + EnumValueNode, + ListValueNode, + ConstListValueNode, + ObjectValueNode, + ConstObjectValueNode, + ObjectFieldNode, + ConstObjectFieldNode, + DirectiveNode, + ConstDirectiveNode, + TypeNode, + NamedTypeNode, + ListTypeNode, + NonNullTypeNode, + TypeSystemDefinitionNode, + SchemaDefinitionNode, + OperationTypeDefinitionNode, + TypeDefinitionNode, + ScalarTypeDefinitionNode, + ObjectTypeDefinitionNode, + FieldDefinitionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + UnionTypeDefinitionNode, + EnumTypeDefinitionNode, + EnumValueDefinitionNode, + InputObjectTypeDefinitionNode, + DirectiveDefinitionNode, + TypeSystemExtensionNode, + SchemaExtensionNode, + TypeExtensionNode, + ScalarTypeExtensionNode, + ObjectTypeExtensionNode, + InterfaceTypeExtensionNode, + UnionTypeExtensionNode, + EnumTypeExtensionNode, + InputObjectTypeExtensionNode, + DirectiveExtensionNode, + SchemaCoordinateNode, + TypeCoordinateNode, + MemberCoordinateNode, + ArgumentCoordinateNode, + DirectiveCoordinateNode, + DirectiveArgumentCoordinateNode, +} from './ast'; +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isConstValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, + isSchemaCoordinateNode, +} from './predicates'; +export { DirectiveLocation } from './directiveLocation'; +export type { DirectiveLocationEnum } from './directiveLocation'; diff --git a/node_modules/graphql/language/index.js b/node_modules/graphql/language/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c31b38aa148ee0ee7daafd1a507a43e31b42e45c --- /dev/null +++ b/node_modules/graphql/language/index.js @@ -0,0 +1,227 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'BREAK', { + enumerable: true, + get: function () { + return _visitor.BREAK; + }, +}); +Object.defineProperty(exports, 'DirectiveLocation', { + enumerable: true, + get: function () { + return _directiveLocation.DirectiveLocation; + }, +}); +Object.defineProperty(exports, 'Kind', { + enumerable: true, + get: function () { + return _kinds.Kind; + }, +}); +Object.defineProperty(exports, 'Lexer', { + enumerable: true, + get: function () { + return _lexer.Lexer; + }, +}); +Object.defineProperty(exports, 'Location', { + enumerable: true, + get: function () { + return _ast.Location; + }, +}); +Object.defineProperty(exports, 'OperationTypeNode', { + enumerable: true, + get: function () { + return _ast.OperationTypeNode; + }, +}); +Object.defineProperty(exports, 'Source', { + enumerable: true, + get: function () { + return _source.Source; + }, +}); +Object.defineProperty(exports, 'Token', { + enumerable: true, + get: function () { + return _ast.Token; + }, +}); +Object.defineProperty(exports, 'TokenKind', { + enumerable: true, + get: function () { + return _tokenKind.TokenKind; + }, +}); +Object.defineProperty(exports, 'getEnterLeaveForKind', { + enumerable: true, + get: function () { + return _visitor.getEnterLeaveForKind; + }, +}); +Object.defineProperty(exports, 'getLocation', { + enumerable: true, + get: function () { + return _location.getLocation; + }, +}); +Object.defineProperty(exports, 'getVisitFn', { + enumerable: true, + get: function () { + return _visitor.getVisitFn; + }, +}); +Object.defineProperty(exports, 'isConstValueNode', { + enumerable: true, + get: function () { + return _predicates.isConstValueNode; + }, +}); +Object.defineProperty(exports, 'isDefinitionNode', { + enumerable: true, + get: function () { + return _predicates.isDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isExecutableDefinitionNode', { + enumerable: true, + get: function () { + return _predicates.isExecutableDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isSchemaCoordinateNode', { + enumerable: true, + get: function () { + return _predicates.isSchemaCoordinateNode; + }, +}); +Object.defineProperty(exports, 'isSelectionNode', { + enumerable: true, + get: function () { + return _predicates.isSelectionNode; + }, +}); +Object.defineProperty(exports, 'isTypeDefinitionNode', { + enumerable: true, + get: function () { + return _predicates.isTypeDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isTypeExtensionNode', { + enumerable: true, + get: function () { + return _predicates.isTypeExtensionNode; + }, +}); +Object.defineProperty(exports, 'isTypeNode', { + enumerable: true, + get: function () { + return _predicates.isTypeNode; + }, +}); +Object.defineProperty(exports, 'isTypeSystemDefinitionNode', { + enumerable: true, + get: function () { + return _predicates.isTypeSystemDefinitionNode; + }, +}); +Object.defineProperty(exports, 'isTypeSystemExtensionNode', { + enumerable: true, + get: function () { + return _predicates.isTypeSystemExtensionNode; + }, +}); +Object.defineProperty(exports, 'isValueNode', { + enumerable: true, + get: function () { + return _predicates.isValueNode; + }, +}); +Object.defineProperty(exports, 'parse', { + enumerable: true, + get: function () { + return _parser.parse; + }, +}); +Object.defineProperty(exports, 'parseConstValue', { + enumerable: true, + get: function () { + return _parser.parseConstValue; + }, +}); +Object.defineProperty(exports, 'parseSchemaCoordinate', { + enumerable: true, + get: function () { + return _parser.parseSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'parseType', { + enumerable: true, + get: function () { + return _parser.parseType; + }, +}); +Object.defineProperty(exports, 'parseValue', { + enumerable: true, + get: function () { + return _parser.parseValue; + }, +}); +Object.defineProperty(exports, 'print', { + enumerable: true, + get: function () { + return _printer.print; + }, +}); +Object.defineProperty(exports, 'printLocation', { + enumerable: true, + get: function () { + return _printLocation.printLocation; + }, +}); +Object.defineProperty(exports, 'printSourceLocation', { + enumerable: true, + get: function () { + return _printLocation.printSourceLocation; + }, +}); +Object.defineProperty(exports, 'visit', { + enumerable: true, + get: function () { + return _visitor.visit; + }, +}); +Object.defineProperty(exports, 'visitInParallel', { + enumerable: true, + get: function () { + return _visitor.visitInParallel; + }, +}); + +var _source = require('./source.js'); + +var _location = require('./location.js'); + +var _printLocation = require('./printLocation.js'); + +var _kinds = require('./kinds.js'); + +var _tokenKind = require('./tokenKind.js'); + +var _lexer = require('./lexer.js'); + +var _parser = require('./parser.js'); + +var _printer = require('./printer.js'); + +var _visitor = require('./visitor.js'); + +var _ast = require('./ast.js'); + +var _predicates = require('./predicates.js'); + +var _directiveLocation = require('./directiveLocation.js'); diff --git a/node_modules/graphql/language/index.mjs b/node_modules/graphql/language/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..183a41f1db907bf1bd2244f03db468a203af6c64 --- /dev/null +++ b/node_modules/graphql/language/index.mjs @@ -0,0 +1,42 @@ +/** + * Parse, print, and visit GraphQL language source files and AST nodes. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { Source } from './source.mjs'; +export { getLocation } from './location.mjs'; +export { printLocation, printSourceLocation } from './printLocation.mjs'; +export { Kind } from './kinds.mjs'; +export { TokenKind } from './tokenKind.mjs'; +export { Lexer } from './lexer.mjs'; +export { + parse, + parseValue, + parseConstValue, + parseType, + parseSchemaCoordinate, +} from './parser.mjs'; +export { print } from './printer.mjs'; +export { + visit, + visitInParallel, + getVisitFn, + getEnterLeaveForKind, + BREAK, +} from './visitor.mjs'; +export { Location, Token, OperationTypeNode } from './ast.mjs'; +export { + isDefinitionNode, + isExecutableDefinitionNode, + isSelectionNode, + isValueNode, + isConstValueNode, + isTypeNode, + isTypeSystemDefinitionNode, + isTypeDefinitionNode, + isTypeSystemExtensionNode, + isTypeExtensionNode, + isSchemaCoordinateNode, +} from './predicates.mjs'; +export { DirectiveLocation } from './directiveLocation.mjs'; diff --git a/node_modules/graphql/language/kinds.d.ts b/node_modules/graphql/language/kinds.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3b512f830055243b35ff1900cdb6ae3f47dfefbe --- /dev/null +++ b/node_modules/graphql/language/kinds.d.ts @@ -0,0 +1,112 @@ +/** @category Kinds */ +/** The set of allowed kind values for AST nodes. */ +declare enum Kind { + /** AST kind for name nodes. */ + NAME = 'Name', + /** AST kind for document nodes. */ + DOCUMENT = 'Document', + /** AST kind for operation definition nodes. */ + OPERATION_DEFINITION = 'OperationDefinition', + /** AST kind for variable definition nodes. */ + VARIABLE_DEFINITION = 'VariableDefinition', + /** AST kind for selection set nodes. */ + SELECTION_SET = 'SelectionSet', + /** AST kind for field selection nodes. */ + FIELD = 'Field', + /** AST kind for argument nodes. */ + ARGUMENT = 'Argument', + /** AST kind for fragment spread nodes. */ + FRAGMENT_SPREAD = 'FragmentSpread', + /** AST kind for inline fragment nodes. */ + INLINE_FRAGMENT = 'InlineFragment', + /** AST kind for fragment definition nodes. */ + FRAGMENT_DEFINITION = 'FragmentDefinition', + /** AST kind for variable reference nodes. */ + VARIABLE = 'Variable', + /** AST kind for integer value nodes. */ + INT = 'IntValue', + /** AST kind for floating-point value nodes. */ + FLOAT = 'FloatValue', + /** AST kind for string value nodes. */ + STRING = 'StringValue', + /** AST kind for boolean value nodes. */ + BOOLEAN = 'BooleanValue', + /** AST kind for null value nodes. */ + NULL = 'NullValue', + /** AST kind for enum value nodes. */ + ENUM = 'EnumValue', + /** AST kind for list value nodes. */ + LIST = 'ListValue', + /** AST kind for object value nodes. */ + OBJECT = 'ObjectValue', + /** AST kind for object field nodes. */ + OBJECT_FIELD = 'ObjectField', + /** AST kind for directive nodes. */ + DIRECTIVE = 'Directive', + /** AST kind for named type reference nodes. */ + NAMED_TYPE = 'NamedType', + /** AST kind for list type reference nodes. */ + LIST_TYPE = 'ListType', + /** AST kind for non-null type reference nodes. */ + NON_NULL_TYPE = 'NonNullType', + /** AST kind for schema definition nodes. */ + SCHEMA_DEFINITION = 'SchemaDefinition', + /** AST kind for operation type definition nodes. */ + OPERATION_TYPE_DEFINITION = 'OperationTypeDefinition', + /** AST kind for scalar type definition nodes. */ + SCALAR_TYPE_DEFINITION = 'ScalarTypeDefinition', + /** AST kind for object type definition nodes. */ + OBJECT_TYPE_DEFINITION = 'ObjectTypeDefinition', + /** AST kind for field definition nodes. */ + FIELD_DEFINITION = 'FieldDefinition', + /** AST kind for input value definition nodes. */ + INPUT_VALUE_DEFINITION = 'InputValueDefinition', + /** AST kind for interface type definition nodes. */ + INTERFACE_TYPE_DEFINITION = 'InterfaceTypeDefinition', + /** AST kind for union type definition nodes. */ + UNION_TYPE_DEFINITION = 'UnionTypeDefinition', + /** AST kind for enum type definition nodes. */ + ENUM_TYPE_DEFINITION = 'EnumTypeDefinition', + /** AST kind for enum value definition nodes. */ + ENUM_VALUE_DEFINITION = 'EnumValueDefinition', + /** AST kind for input object type definition nodes. */ + INPUT_OBJECT_TYPE_DEFINITION = 'InputObjectTypeDefinition', + /** AST kind for directive definition nodes. */ + DIRECTIVE_DEFINITION = 'DirectiveDefinition', + /** AST kind for schema extension nodes. */ + SCHEMA_EXTENSION = 'SchemaExtension', + /** AST kind for directive extension nodes. */ + DIRECTIVE_EXTENSION = 'DirectiveExtension', + /** AST kind for scalar type extension nodes. */ + SCALAR_TYPE_EXTENSION = 'ScalarTypeExtension', + /** AST kind for object type extension nodes. */ + OBJECT_TYPE_EXTENSION = 'ObjectTypeExtension', + /** AST kind for interface type extension nodes. */ + INTERFACE_TYPE_EXTENSION = 'InterfaceTypeExtension', + /** AST kind for union type extension nodes. */ + UNION_TYPE_EXTENSION = 'UnionTypeExtension', + /** AST kind for enum type extension nodes. */ + ENUM_TYPE_EXTENSION = 'EnumTypeExtension', + /** AST kind for input object type extension nodes. */ + INPUT_OBJECT_TYPE_EXTENSION = 'InputObjectTypeExtension', + /** AST kind for type coordinate nodes. */ + TYPE_COORDINATE = 'TypeCoordinate', + /** AST kind for member coordinate nodes. */ + MEMBER_COORDINATE = 'MemberCoordinate', + /** AST kind for argument coordinate nodes. */ + ARGUMENT_COORDINATE = 'ArgumentCoordinate', + /** AST kind for directive coordinate nodes. */ + DIRECTIVE_COORDINATE = 'DirectiveCoordinate', + /** AST kind for directive argument coordinate nodes. */ + DIRECTIVE_ARGUMENT_COORDINATE = 'DirectiveArgumentCoordinate', +} +export { Kind }; +/** + * Deprecated legacy alias for the enum type representing the possible kind + * values of AST nodes. This alias will be removed in v17. In v17, `Kind` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `Kind` as both the runtime + * value and the type. + */ +export declare type KindEnum = typeof Kind; diff --git a/node_modules/graphql/language/kinds.js b/node_modules/graphql/language/kinds.js new file mode 100644 index 0000000000000000000000000000000000000000..7dde38d6e4bb4c4eaac1fc192f481a6aaab449ba --- /dev/null +++ b/node_modules/graphql/language/kinds.js @@ -0,0 +1,72 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.Kind = void 0; + +/** @category Kinds */ + +/** The set of allowed kind values for AST nodes. */ +var Kind; +exports.Kind = Kind; + +(function (Kind) { + Kind['NAME'] = 'Name'; + Kind['DOCUMENT'] = 'Document'; + Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; + Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; + Kind['SELECTION_SET'] = 'SelectionSet'; + Kind['FIELD'] = 'Field'; + Kind['ARGUMENT'] = 'Argument'; + Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; + Kind['INLINE_FRAGMENT'] = 'InlineFragment'; + Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; + Kind['VARIABLE'] = 'Variable'; + Kind['INT'] = 'IntValue'; + Kind['FLOAT'] = 'FloatValue'; + Kind['STRING'] = 'StringValue'; + Kind['BOOLEAN'] = 'BooleanValue'; + Kind['NULL'] = 'NullValue'; + Kind['ENUM'] = 'EnumValue'; + Kind['LIST'] = 'ListValue'; + Kind['OBJECT'] = 'ObjectValue'; + Kind['OBJECT_FIELD'] = 'ObjectField'; + Kind['DIRECTIVE'] = 'Directive'; + Kind['NAMED_TYPE'] = 'NamedType'; + Kind['LIST_TYPE'] = 'ListType'; + Kind['NON_NULL_TYPE'] = 'NonNullType'; + Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; + Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; + Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; + Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; + Kind['FIELD_DEFINITION'] = 'FieldDefinition'; + Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; + Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; + Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; + Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; + Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; + Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; + Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; + Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; + Kind['DIRECTIVE_EXTENSION'] = 'DirectiveExtension'; + Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; + Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; + Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; + Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; + Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; + Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; + Kind['TYPE_COORDINATE'] = 'TypeCoordinate'; + Kind['MEMBER_COORDINATE'] = 'MemberCoordinate'; + Kind['ARGUMENT_COORDINATE'] = 'ArgumentCoordinate'; + Kind['DIRECTIVE_COORDINATE'] = 'DirectiveCoordinate'; + Kind['DIRECTIVE_ARGUMENT_COORDINATE'] = 'DirectiveArgumentCoordinate'; +})(Kind || (exports.Kind = Kind = {})); +/** + * Deprecated legacy alias for the enum type representing the possible kind + * values of AST nodes. This alias will be removed in v17. In v17, `Kind` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `Kind` as both the runtime + * value and the type. + */ diff --git a/node_modules/graphql/language/kinds.mjs b/node_modules/graphql/language/kinds.mjs new file mode 100644 index 0000000000000000000000000000000000000000..49cd345fdb0d9a5631f0cd0341f351ead3bf30c6 --- /dev/null +++ b/node_modules/graphql/language/kinds.mjs @@ -0,0 +1,66 @@ +/** @category Kinds */ + +/** The set of allowed kind values for AST nodes. */ +var Kind; + +(function (Kind) { + Kind['NAME'] = 'Name'; + Kind['DOCUMENT'] = 'Document'; + Kind['OPERATION_DEFINITION'] = 'OperationDefinition'; + Kind['VARIABLE_DEFINITION'] = 'VariableDefinition'; + Kind['SELECTION_SET'] = 'SelectionSet'; + Kind['FIELD'] = 'Field'; + Kind['ARGUMENT'] = 'Argument'; + Kind['FRAGMENT_SPREAD'] = 'FragmentSpread'; + Kind['INLINE_FRAGMENT'] = 'InlineFragment'; + Kind['FRAGMENT_DEFINITION'] = 'FragmentDefinition'; + Kind['VARIABLE'] = 'Variable'; + Kind['INT'] = 'IntValue'; + Kind['FLOAT'] = 'FloatValue'; + Kind['STRING'] = 'StringValue'; + Kind['BOOLEAN'] = 'BooleanValue'; + Kind['NULL'] = 'NullValue'; + Kind['ENUM'] = 'EnumValue'; + Kind['LIST'] = 'ListValue'; + Kind['OBJECT'] = 'ObjectValue'; + Kind['OBJECT_FIELD'] = 'ObjectField'; + Kind['DIRECTIVE'] = 'Directive'; + Kind['NAMED_TYPE'] = 'NamedType'; + Kind['LIST_TYPE'] = 'ListType'; + Kind['NON_NULL_TYPE'] = 'NonNullType'; + Kind['SCHEMA_DEFINITION'] = 'SchemaDefinition'; + Kind['OPERATION_TYPE_DEFINITION'] = 'OperationTypeDefinition'; + Kind['SCALAR_TYPE_DEFINITION'] = 'ScalarTypeDefinition'; + Kind['OBJECT_TYPE_DEFINITION'] = 'ObjectTypeDefinition'; + Kind['FIELD_DEFINITION'] = 'FieldDefinition'; + Kind['INPUT_VALUE_DEFINITION'] = 'InputValueDefinition'; + Kind['INTERFACE_TYPE_DEFINITION'] = 'InterfaceTypeDefinition'; + Kind['UNION_TYPE_DEFINITION'] = 'UnionTypeDefinition'; + Kind['ENUM_TYPE_DEFINITION'] = 'EnumTypeDefinition'; + Kind['ENUM_VALUE_DEFINITION'] = 'EnumValueDefinition'; + Kind['INPUT_OBJECT_TYPE_DEFINITION'] = 'InputObjectTypeDefinition'; + Kind['DIRECTIVE_DEFINITION'] = 'DirectiveDefinition'; + Kind['SCHEMA_EXTENSION'] = 'SchemaExtension'; + Kind['DIRECTIVE_EXTENSION'] = 'DirectiveExtension'; + Kind['SCALAR_TYPE_EXTENSION'] = 'ScalarTypeExtension'; + Kind['OBJECT_TYPE_EXTENSION'] = 'ObjectTypeExtension'; + Kind['INTERFACE_TYPE_EXTENSION'] = 'InterfaceTypeExtension'; + Kind['UNION_TYPE_EXTENSION'] = 'UnionTypeExtension'; + Kind['ENUM_TYPE_EXTENSION'] = 'EnumTypeExtension'; + Kind['INPUT_OBJECT_TYPE_EXTENSION'] = 'InputObjectTypeExtension'; + Kind['TYPE_COORDINATE'] = 'TypeCoordinate'; + Kind['MEMBER_COORDINATE'] = 'MemberCoordinate'; + Kind['ARGUMENT_COORDINATE'] = 'ArgumentCoordinate'; + Kind['DIRECTIVE_COORDINATE'] = 'DirectiveCoordinate'; + Kind['DIRECTIVE_ARGUMENT_COORDINATE'] = 'DirectiveArgumentCoordinate'; +})(Kind || (Kind = {})); + +export { Kind }; +/** + * Deprecated legacy alias for the enum type representing the possible kind + * values of AST nodes. This alias will be removed in v17. In v17, `Kind` is + * exported as the single public symbol for both the runtime object and the + * corresponding TypeScript type. + * @deprecated Will be removed in v17. In v17, use `Kind` as both the runtime + * value and the type. + */ diff --git a/node_modules/graphql/language/lexer.d.ts b/node_modules/graphql/language/lexer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..66da17b386717e11f96bf3e9ea0f1e513de1b492 --- /dev/null +++ b/node_modules/graphql/language/lexer.d.ts @@ -0,0 +1,129 @@ +/** @category Lexing */ +import { Token } from './ast'; +import type { Source } from './source'; +import { TokenKind } from './tokenKind'; +/** + * A Lexer interface which provides common properties and methods required for + * lexing GraphQL source. + * + * @internal + */ +export interface LexerInterface { + source: Source; + lastToken: Token; + token: Token; + line: number; + lineStart: number; + advance: () => Token; + lookahead: () => Token; +} +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export declare class Lexer implements LexerInterface { + /** Source document used to derive error locations. */ + source: Source; + /** Most recent non-ignored token returned by the lexer. */ + lastToken: Token; + /** Current non-ignored token at the lexer cursor. */ + token: Token; + /** The (1-indexed) line containing the current token. */ + line: number; + /** Character offset where the current line starts. */ + lineStart: number; + /** + * Creates a Lexer instance. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Lexer, Source, TokenKind } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * + * lexer.token.kind; // => TokenKind.SOF + * lexer.advance().kind; // => TokenKind.BRACE_L + * lexer.advance().value; // => 'hello' + * lexer.advance().kind; // => TokenKind.BRACE_R + * ``` + */ + constructor(source: Source); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Advances the token stream to the next non-ignored token. + * @returns The next non-ignored token. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance(); + * + * token.kind; // => '{' + * lexer.token; // => token + * ``` + */ + advance(): Token; + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + * @returns The next non-ignored token without advancing the lexer. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.lookahead(); + * + * token.kind; // => '{' + * lexer.token.kind; // => '' + * ``` + */ + lookahead(): Token; +} +/** @internal */ +export declare function isPunctuatorTokenKind(kind: TokenKind): boolean; +/** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + * + * @internal + */ +export declare function printCodePointAt( + lexer: LexerInterface, + location: number, +): string; +/** + * Create a token with line and column location information. + * + * @internal + */ +export declare function createToken( + lexer: LexerInterface, + kind: TokenKind, + start: number, + end: number, + value?: string, +): Token; +/** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + * + * @internal + */ +export declare function readName(lexer: LexerInterface, start: number): Token; diff --git a/node_modules/graphql/language/lexer.js b/node_modules/graphql/language/lexer.js new file mode 100644 index 0000000000000000000000000000000000000000..b8dc402ef84c43ea4dba68c978e56427ef256b47 --- /dev/null +++ b/node_modules/graphql/language/lexer.js @@ -0,0 +1,1074 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.Lexer = void 0; +exports.createToken = createToken; +exports.isPunctuatorTokenKind = isPunctuatorTokenKind; +exports.printCodePointAt = printCodePointAt; +exports.readName = readName; + +var _syntaxError = require('../error/syntaxError.js'); + +var _ast = require('./ast.js'); + +var _blockString = require('./blockString.js'); + +var _characterClasses = require('./characterClasses.js'); + +var _tokenKind = require('./tokenKind.js'); + +/** @category Lexing */ + +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +class Lexer { + /** Source document used to derive error locations. */ + + /** Most recent non-ignored token returned by the lexer. */ + + /** Current non-ignored token at the lexer cursor. */ + + /** The (1-indexed) line containing the current token. */ + + /** Character offset where the current line starts. */ + + /** + * Creates a Lexer instance. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Lexer, Source, TokenKind } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * + * lexer.token.kind; // => TokenKind.SOF + * lexer.advance().kind; // => TokenKind.BRACE_L + * lexer.advance().value; // => 'hello' + * lexer.advance().kind; // => TokenKind.BRACE_R + * ``` + */ + constructor(source) { + const startOfFileToken = new _ast.Token( + _tokenKind.TokenKind.SOF, + 0, + 0, + 0, + 0, + ); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Lexer'; + } + /** + * Advances the token stream to the next non-ignored token. + * @returns The next non-ignored token. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance(); + * + * token.kind; // => '{' + * lexer.token; // => token + * ``` + */ + + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + * @returns The next non-ignored token without advancing the lexer. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.lookahead(); + * + * token.kind; // => '{' + * lexer.token.kind; // => '' + * ``` + */ + + lookahead() { + let token = this.token; + + if (token.kind !== _tokenKind.TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === _tokenKind.TokenKind.COMMENT); + } + + return token; + } +} +/** @internal */ + +exports.Lexer = Lexer; + +function isPunctuatorTokenKind(kind) { + return ( + kind === _tokenKind.TokenKind.BANG || + kind === _tokenKind.TokenKind.DOLLAR || + kind === _tokenKind.TokenKind.AMP || + kind === _tokenKind.TokenKind.PAREN_L || + kind === _tokenKind.TokenKind.PAREN_R || + kind === _tokenKind.TokenKind.DOT || + kind === _tokenKind.TokenKind.SPREAD || + kind === _tokenKind.TokenKind.COLON || + kind === _tokenKind.TokenKind.EQUALS || + kind === _tokenKind.TokenKind.AT || + kind === _tokenKind.TokenKind.BRACKET_L || + kind === _tokenKind.TokenKind.BRACKET_R || + kind === _tokenKind.TokenKind.BRACE_L || + kind === _tokenKind.TokenKind.PIPE || + kind === _tokenKind.TokenKind.BRACE_R + ); +} +/** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + * + * @internal + */ + +function isUnicodeScalarValue(code) { + return ( + (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff) + ); +} +/** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + * + * @internal + */ + +function isSupplementaryCodePoint(body, location) { + return ( + isLeadingSurrogate(body.charCodeAt(location)) && + isTrailingSurrogate(body.charCodeAt(location + 1)) + ); +} + +function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; +} +/** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + * + * @internal + */ + +function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + + if (code === undefined) { + return _tokenKind.TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point + + return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); +} +/** + * Create a token with line and column location information. + * + * @internal + */ + +function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new _ast.Token(kind, start, end, line, col, value); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + * + * @internal + */ + +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter + + switch (code) { + // Ignored :: + // - UnicodeBOM + // - WhiteSpace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // WhiteSpace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // + + case 0x0009: // \t + + case 0x0020: // + + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment + + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + + case 0x0021: + // ! + return createToken( + lexer, + _tokenKind.TokenKind.BANG, + position, + position + 1, + ); + + case 0x0024: + // $ + return createToken( + lexer, + _tokenKind.TokenKind.DOLLAR, + position, + position + 1, + ); + + case 0x0026: + // & + return createToken( + lexer, + _tokenKind.TokenKind.AMP, + position, + position + 1, + ); + + case 0x0028: + // ( + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_L, + position, + position + 1, + ); + + case 0x0029: + // ) + return createToken( + lexer, + _tokenKind.TokenKind.PAREN_R, + position, + position + 1, + ); + + case 0x002e: + // . + if ( + body.charCodeAt(position + 1) === 0x002e && + body.charCodeAt(position + 2) === 0x002e + ) { + return createToken( + lexer, + _tokenKind.TokenKind.SPREAD, + position, + position + 3, + ); + } + + break; + + case 0x003a: + // : + return createToken( + lexer, + _tokenKind.TokenKind.COLON, + position, + position + 1, + ); + + case 0x003d: + // = + return createToken( + lexer, + _tokenKind.TokenKind.EQUALS, + position, + position + 1, + ); + + case 0x0040: + // @ + return createToken( + lexer, + _tokenKind.TokenKind.AT, + position, + position + 1, + ); + + case 0x005b: + // [ + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_L, + position, + position + 1, + ); + + case 0x005d: + // ] + return createToken( + lexer, + _tokenKind.TokenKind.BRACKET_R, + position, + position + 1, + ); + + case 0x007b: + // { + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_L, + position, + position + 1, + ); + + case 0x007c: + // | + return createToken( + lexer, + _tokenKind.TokenKind.PIPE, + position, + position + 1, + ); + + case 0x007d: + // } + return createToken( + lexer, + _tokenKind.TokenKind.BRACE_R, + position, + position + 1, + ); + // StringValue + + case 0x0022: + // " + if ( + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + return readBlockString(lexer, position); + } + + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) + + if ((0, _characterClasses.isDigit)(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name + + if ((0, _characterClasses.isNameStart)(code)) { + return readName(lexer, position); + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + code === 0x0027 + ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' + : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) + ? `Unexpected character: ${printCodePointAt(lexer, position)}.` + : `Invalid character: ${printCodePointAt(lexer, position)}.`, + ); + } + + return createToken(lexer, _tokenKind.TokenKind.EOF, bodyLength, bodyLength); +} +/** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + * + * @internal + */ + +function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } + } + + return createToken( + lexer, + _tokenKind.TokenKind.COMMENT, + start, + position, + body.slice(start + 1, position), + ); +} +/** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + * + * @internal + */ + +function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) + + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) + + if (code === 0x0030) { + code = body.charCodeAt(++position); + + if ((0, _characterClasses.isDigit)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, unexpected digit after 0: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) + + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e + + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - + + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } + + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + if (code === 0x002e || (0, _characterClasses.isNameStart)(code)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + + return createToken( + lexer, + isFloat ? _tokenKind.TokenKind.FLOAT : _tokenKind.TokenKind.INT, + start, + position, + body.slice(start, position), + ); +} +/** + * Returns the new position in the source after reading one or more digits. + * + * @internal + */ + +function readDigits(lexer, start, firstCode) { + if (!(0, _characterClasses.isDigit)(firstCode)) { + throw (0, _syntaxError.syntaxError)( + lexer.source, + start, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + start, + )}.`, + ); + } + + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode + + while ((0, _characterClasses.isDigit)(body.charCodeAt(position))) { + ++position; + } + + return position; +} +/** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + * + * @internal + */ + +function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ''; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") + + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken( + lexer, + _tokenKind.TokenKind.STRING, + start, + position + 1, + value, + ); + } // Escape Sequence (\) + + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = + body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) + : readEscapedUnicodeFixedWidth(lexer, position) + : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + 'Unterminated string.', + ); +} // The string value and lexed size of an escape sequence. + +function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) + + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + + return { + value: String.fromCodePoint(point), + size, + }; + } // Append this hex digit to the code point. + + point = (point << 4) | readHexDigit(code); + + if (point < 0) { + break; + } + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice( + position, + position + size, + )}".`, + ); +} + +function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6, + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. + + if (isLeadingSurrogate(code)) { + // \u + if ( + body.charCodeAt(position + 6) === 0x005c && + body.charCodeAt(position + 7) === 0x0075 + ) { + const trailingCode = read16BitHexCode(body, position + 8); + + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12, + }; + } + } + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`, + ); +} +/** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + * + * @internal + */ + +function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return ( + (readHexDigit(body.charCodeAt(position)) << 12) | + (readHexDigit(body.charCodeAt(position + 1)) << 8) | + (readHexDigit(body.charCodeAt(position + 2)) << 4) | + readHexDigit(body.charCodeAt(position + 3)) + ); +} +/** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + * + * @internal + */ + +function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 + : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 + : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 + : -1; +} +/** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + * + * @internal + */ + +function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + + switch (code) { + case 0x0022: + // " + return { + value: '\u0022', + size: 2, + }; + + case 0x005c: + // \ + return { + value: '\u005c', + size: 2, + }; + + case 0x002f: + // / + return { + value: '\u002f', + size: 2, + }; + + case 0x0062: + // b + return { + value: '\u0008', + size: 2, + }; + + case 0x0066: + // f + return { + value: '\u000c', + size: 2, + }; + + case 0x006e: + // n + return { + value: '\u000a', + size: 2, + }; + + case 0x0072: + // r + return { + value: '\u000d', + size: 2, + }; + + case 0x0074: + // t + return { + value: '\u0009', + size: 2, + }; + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character escape sequence: "${body.slice( + position, + position + 2, + )}".`, + ); +} +/** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + * + * @internal + */ + +function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ''; + const blockLines = []; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") + + if ( + code === 0x0022 && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken( + lexer, + _tokenKind.TokenKind.BLOCK_STRING, + start, + position + 3, // Return a string of the lines joined with U+000A. + (0, _blockString.dedentBlockStringLines)(blockLines).join('\n'), + ); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") + + if ( + code === 0x005c && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 && + body.charCodeAt(position + 3) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash + + position += 4; + continue; + } // LineTerminator + + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + + currentLine = ''; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + 'Unterminated string.', + ); +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + * + * @internal + */ + +function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + + while (position < bodyLength) { + const code = body.charCodeAt(position); + + if ((0, _characterClasses.isNameContinue)(code)) { + ++position; + } else { + break; + } + } + + return createToken( + lexer, + _tokenKind.TokenKind.NAME, + start, + position, + body.slice(start, position), + ); +} diff --git a/node_modules/graphql/language/lexer.mjs b/node_modules/graphql/language/lexer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5c4e9ea49875caf6f6940f6d8de38b849512aa69 --- /dev/null +++ b/node_modules/graphql/language/lexer.mjs @@ -0,0 +1,972 @@ +/** @category Lexing */ +import { syntaxError } from '../error/syntaxError.mjs'; +import { Token } from './ast.mjs'; +import { dedentBlockStringLines } from './blockString.mjs'; +import { isDigit, isNameContinue, isNameStart } from './characterClasses.mjs'; +import { TokenKind } from './tokenKind.mjs'; +/** + * A Lexer interface which provides common properties and methods required for + * lexing GraphQL source. + * + * @internal + */ + +/** + * Given a Source object, creates a Lexer for that source. + * A Lexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + */ +export class Lexer { + /** Source document used to derive error locations. */ + + /** Most recent non-ignored token returned by the lexer. */ + + /** Current non-ignored token at the lexer cursor. */ + + /** The (1-indexed) line containing the current token. */ + + /** Character offset where the current line starts. */ + + /** + * Creates a Lexer instance. + * @param source - Source document used to derive error locations. + * @example + * ```ts + * import { Lexer, Source, TokenKind } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * + * lexer.token.kind; // => TokenKind.SOF + * lexer.advance().kind; // => TokenKind.BRACE_L + * lexer.advance().value; // => 'hello' + * lexer.advance().kind; // => TokenKind.BRACE_R + * ``` + */ + constructor(source) { + const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + this.line = 1; + this.lineStart = 0; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Lexer'; + } + /** + * Advances the token stream to the next non-ignored token. + * @returns The next non-ignored token. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.advance(); + * + * token.kind; // => '{' + * lexer.token; // => token + * ``` + */ + + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the state of Lexer. + * @returns The next non-ignored token without advancing the lexer. + * @example + * ```ts + * import { Lexer, Source } from 'graphql/language'; + * + * const lexer = new Lexer(new Source('{ hello }')); + * const token = lexer.lookahead(); + * + * token.kind; // => '{' + * lexer.token.kind; // => '' + * ``` + */ + + lookahead() { + let token = this.token; + + if (token.kind !== TokenKind.EOF) { + do { + if (token.next) { + token = token.next; + } else { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + } while (token.kind === TokenKind.COMMENT); + } + + return token; + } +} +/** @internal */ + +export function isPunctuatorTokenKind(kind) { + return ( + kind === TokenKind.BANG || + kind === TokenKind.DOLLAR || + kind === TokenKind.AMP || + kind === TokenKind.PAREN_L || + kind === TokenKind.PAREN_R || + kind === TokenKind.DOT || + kind === TokenKind.SPREAD || + kind === TokenKind.COLON || + kind === TokenKind.EQUALS || + kind === TokenKind.AT || + kind === TokenKind.BRACKET_L || + kind === TokenKind.BRACKET_R || + kind === TokenKind.BRACE_L || + kind === TokenKind.PIPE || + kind === TokenKind.BRACE_R + ); +} +/** + * A Unicode scalar value is any Unicode code point except surrogate code + * points. In other words, the inclusive ranges of values 0x0000 to 0xD7FF and + * 0xE000 to 0x10FFFF. + * + * SourceCharacter :: + * - "Any Unicode scalar value" + * + * @internal + */ + +function isUnicodeScalarValue(code) { + return ( + (code >= 0x0000 && code <= 0xd7ff) || (code >= 0xe000 && code <= 0x10ffff) + ); +} +/** + * The GraphQL specification defines source text as a sequence of unicode scalar + * values (which Unicode defines to exclude surrogate code points). However + * JavaScript defines strings as a sequence of UTF-16 code units which may + * include surrogates. A surrogate pair is a valid source character as it + * encodes a supplementary code point (above U+FFFF), but unpaired surrogate + * code points are not valid source characters. + * + * @internal + */ + +function isSupplementaryCodePoint(body, location) { + return ( + isLeadingSurrogate(body.charCodeAt(location)) && + isTrailingSurrogate(body.charCodeAt(location + 1)) + ); +} + +function isLeadingSurrogate(code) { + return code >= 0xd800 && code <= 0xdbff; +} + +function isTrailingSurrogate(code) { + return code >= 0xdc00 && code <= 0xdfff; +} +/** + * Prints the code point (or end of file reference) at a given location in a + * source for use in error messages. + * + * Printable ASCII is printed quoted, while other points are printed in Unicode + * code point form (ie. U+1234). + * + * @internal + */ + +export function printCodePointAt(lexer, location) { + const code = lexer.source.body.codePointAt(location); + + if (code === undefined) { + return TokenKind.EOF; + } else if (code >= 0x0020 && code <= 0x007e) { + // Printable ASCII + const char = String.fromCodePoint(code); + return char === '"' ? "'\"'" : `"${char}"`; + } // Unicode code point + + return 'U+' + code.toString(16).toUpperCase().padStart(4, '0'); +} +/** + * Create a token with line and column location information. + * + * @internal + */ + +export function createToken(lexer, kind, start, end, value) { + const line = lexer.line; + const col = 1 + start - lexer.lineStart; + return new Token(kind, start, end, line, col, value); +} +/** + * Gets the next token from the source starting at the given position. + * + * This skips over whitespace until it finds the next lexable token, then lexes + * punctuators immediately or calls the appropriate helper function for more + * complicated tokens. + * + * @internal + */ + +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // SourceCharacter + + switch (code) { + // Ignored :: + // - UnicodeBOM + // - WhiteSpace + // - LineTerminator + // - Comment + // - Comma + // + // UnicodeBOM :: "Byte Order Mark (U+FEFF)" + // + // WhiteSpace :: + // - "Horizontal Tab (U+0009)" + // - "Space (U+0020)" + // + // Comma :: , + case 0xfeff: // + + case 0x0009: // \t + + case 0x0020: // + + case 0x002c: + // , + ++position; + continue; + // LineTerminator :: + // - "New Line (U+000A)" + // - "Carriage Return (U+000D)" [lookahead != "New Line (U+000A)"] + // - "Carriage Return (U+000D)" "New Line (U+000A)" + + case 0x000a: + // \n + ++position; + ++lexer.line; + lexer.lineStart = position; + continue; + + case 0x000d: + // \r + if (body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + + ++lexer.line; + lexer.lineStart = position; + continue; + // Comment + + case 0x0023: + // # + return readComment(lexer, position); + // Token :: + // - Punctuator + // - Name + // - IntValue + // - FloatValue + // - StringValue + // + // Punctuator :: one of ! $ & ( ) ... : = @ [ ] { | } + + case 0x0021: + // ! + return createToken(lexer, TokenKind.BANG, position, position + 1); + + case 0x0024: + // $ + return createToken(lexer, TokenKind.DOLLAR, position, position + 1); + + case 0x0026: + // & + return createToken(lexer, TokenKind.AMP, position, position + 1); + + case 0x0028: + // ( + return createToken(lexer, TokenKind.PAREN_L, position, position + 1); + + case 0x0029: + // ) + return createToken(lexer, TokenKind.PAREN_R, position, position + 1); + + case 0x002e: + // . + if ( + body.charCodeAt(position + 1) === 0x002e && + body.charCodeAt(position + 2) === 0x002e + ) { + return createToken(lexer, TokenKind.SPREAD, position, position + 3); + } + + break; + + case 0x003a: + // : + return createToken(lexer, TokenKind.COLON, position, position + 1); + + case 0x003d: + // = + return createToken(lexer, TokenKind.EQUALS, position, position + 1); + + case 0x0040: + // @ + return createToken(lexer, TokenKind.AT, position, position + 1); + + case 0x005b: + // [ + return createToken(lexer, TokenKind.BRACKET_L, position, position + 1); + + case 0x005d: + // ] + return createToken(lexer, TokenKind.BRACKET_R, position, position + 1); + + case 0x007b: + // { + return createToken(lexer, TokenKind.BRACE_L, position, position + 1); + + case 0x007c: + // | + return createToken(lexer, TokenKind.PIPE, position, position + 1); + + case 0x007d: + // } + return createToken(lexer, TokenKind.BRACE_R, position, position + 1); + // StringValue + + case 0x0022: + // " + if ( + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + return readBlockString(lexer, position); + } + + return readString(lexer, position); + } // IntValue | FloatValue (Digit | -) + + if (isDigit(code) || code === 0x002d) { + return readNumber(lexer, position, code); + } // Name + + if (isNameStart(code)) { + return readName(lexer, position); + } + + throw syntaxError( + lexer.source, + position, + code === 0x0027 + ? 'Unexpected single quote character (\'), did you mean to use a double quote (")?' + : isUnicodeScalarValue(code) || isSupplementaryCodePoint(body, position) + ? `Unexpected character: ${printCodePointAt(lexer, position)}.` + : `Invalid character: ${printCodePointAt(lexer, position)}.`, + ); + } + + return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength); +} +/** + * Reads a comment token from the source file. + * + * ``` + * Comment :: # CommentChar* [lookahead != CommentChar] + * + * CommentChar :: SourceCharacter but not LineTerminator + * ``` + * + * @internal + */ + +function readComment(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + break; + } + } + + return createToken( + lexer, + TokenKind.COMMENT, + start, + position, + body.slice(start + 1, position), + ); +} +/** + * Reads a number token from the source file, either a FloatValue or an IntValue + * depending on whether a FractionalPart or ExponentPart is encountered. + * + * ``` + * IntValue :: IntegerPart [lookahead != {Digit, `.`, NameStart}] + * + * IntegerPart :: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit Digit* + * + * NegativeSign :: - + * + * NonZeroDigit :: Digit but not `0` + * + * FloatValue :: + * - IntegerPart FractionalPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart FractionalPart [lookahead != {Digit, `.`, NameStart}] + * - IntegerPart ExponentPart [lookahead != {Digit, `.`, NameStart}] + * + * FractionalPart :: . Digit+ + * + * ExponentPart :: ExponentIndicator Sign? Digit+ + * + * ExponentIndicator :: one of `e` `E` + * + * Sign :: one of + - + * ``` + * + * @internal + */ + +function readNumber(lexer, start, firstCode) { + const body = lexer.source.body; + let position = start; + let code = firstCode; + let isFloat = false; // NegativeSign (-) + + if (code === 0x002d) { + code = body.charCodeAt(++position); + } // Zero (0) + + if (code === 0x0030) { + code = body.charCodeAt(++position); + + if (isDigit(code)) { + throw syntaxError( + lexer.source, + position, + `Invalid number, unexpected digit after 0: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } else { + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Full stop (.) + + if (code === 0x002e) { + isFloat = true; + code = body.charCodeAt(++position); + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // E e + + if (code === 0x0045 || code === 0x0065) { + isFloat = true; + code = body.charCodeAt(++position); // + - + + if (code === 0x002b || code === 0x002d) { + code = body.charCodeAt(++position); + } + + position = readDigits(lexer, position, code); + code = body.charCodeAt(position); + } // Numbers cannot be followed by . or NameStart + + if (code === 0x002e || isNameStart(code)) { + throw syntaxError( + lexer.source, + position, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + + return createToken( + lexer, + isFloat ? TokenKind.FLOAT : TokenKind.INT, + start, + position, + body.slice(start, position), + ); +} +/** + * Returns the new position in the source after reading one or more digits. + * + * @internal + */ + +function readDigits(lexer, start, firstCode) { + if (!isDigit(firstCode)) { + throw syntaxError( + lexer.source, + start, + `Invalid number, expected digit but got: ${printCodePointAt( + lexer, + start, + )}.`, + ); + } + + const body = lexer.source.body; + let position = start + 1; // +1 to skip first firstCode + + while (isDigit(body.charCodeAt(position))) { + ++position; + } + + return position; +} +/** + * Reads a single-quote string token from the source file. + * + * ``` + * StringValue :: + * - `""` [lookahead != `"`] + * - `"` StringCharacter+ `"` + * + * StringCharacter :: + * - SourceCharacter but not `"` or `\` or LineTerminator + * - `\u` EscapedUnicode + * - `\` EscapedCharacter + * + * EscapedUnicode :: + * - `{` HexDigit+ `}` + * - HexDigit HexDigit HexDigit HexDigit + * + * EscapedCharacter :: one of `"` `\` `/` `b` `f` `n` `r` `t` + * ``` + * + * @internal + */ + +function readString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + let chunkStart = position; + let value = ''; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Quote (") + + if (code === 0x0022) { + value += body.slice(chunkStart, position); + return createToken(lexer, TokenKind.STRING, start, position + 1, value); + } // Escape Sequence (\) + + if (code === 0x005c) { + value += body.slice(chunkStart, position); + const escape = + body.charCodeAt(position + 1) === 0x0075 // u + ? body.charCodeAt(position + 2) === 0x007b // { + ? readEscapedUnicodeVariableWidth(lexer, position) + : readEscapedUnicodeFixedWidth(lexer, position) + : readEscapedCharacter(lexer, position); + value += escape.value; + position += escape.size; + chunkStart = position; + continue; + } // LineTerminator (\n | \r) + + if (code === 0x000a || code === 0x000d) { + break; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw syntaxError( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } + + throw syntaxError(lexer.source, position, 'Unterminated string.'); +} // The string value and lexed size of an escape sequence. + +function readEscapedUnicodeVariableWidth(lexer, position) { + const body = lexer.source.body; + let point = 0; + let size = 3; // Cannot be larger than 12 chars (\u{00000000}). + + while (size < 12) { + const code = body.charCodeAt(position + size++); // Closing Brace (}) + + if (code === 0x007d) { + // Must be at least 5 chars (\u{0}) and encode a Unicode scalar value. + if (size < 5 || !isUnicodeScalarValue(point)) { + break; + } + + return { + value: String.fromCodePoint(point), + size, + }; + } // Append this hex digit to the code point. + + point = (point << 4) | readHexDigit(code); + + if (point < 0) { + break; + } + } + + throw syntaxError( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice( + position, + position + size, + )}".`, + ); +} + +function readEscapedUnicodeFixedWidth(lexer, position) { + const body = lexer.source.body; + const code = read16BitHexCode(body, position + 2); + + if (isUnicodeScalarValue(code)) { + return { + value: String.fromCodePoint(code), + size: 6, + }; + } // GraphQL allows JSON-style surrogate pair escape sequences, but only when + // a valid pair is formed. + + if (isLeadingSurrogate(code)) { + // \u + if ( + body.charCodeAt(position + 6) === 0x005c && + body.charCodeAt(position + 7) === 0x0075 + ) { + const trailingCode = read16BitHexCode(body, position + 8); + + if (isTrailingSurrogate(trailingCode)) { + // JavaScript defines strings as a sequence of UTF-16 code units and + // encodes Unicode code points above U+FFFF using a surrogate pair of + // code units. Since this is a surrogate pair escape sequence, just + // include both codes into the JavaScript string value. Had JavaScript + // not been internally based on UTF-16, then this surrogate pair would + // be decoded to retrieve the supplementary code point. + return { + value: String.fromCodePoint(code, trailingCode), + size: 12, + }; + } + } + } + + throw syntaxError( + lexer.source, + position, + `Invalid Unicode escape sequence: "${body.slice(position, position + 6)}".`, + ); +} +/** + * Reads four hexadecimal characters and returns the positive integer that 16bit + * hexadecimal string represents. For example, "000f" will return 15, and "dead" + * will return 57005. + * + * Returns a negative number if any char was not a valid hexadecimal digit. + * + * @internal + */ + +function read16BitHexCode(body, position) { + // readHexDigit() returns -1 on error. ORing a negative value with any other + // value always produces a negative value. + return ( + (readHexDigit(body.charCodeAt(position)) << 12) | + (readHexDigit(body.charCodeAt(position + 1)) << 8) | + (readHexDigit(body.charCodeAt(position + 2)) << 4) | + readHexDigit(body.charCodeAt(position + 3)) + ); +} +/** + * Reads a hexadecimal character and returns its positive integer value (0-15). + * + * '0' becomes 0, '9' becomes 9 + * 'A' becomes 10, 'F' becomes 15 + * 'a' becomes 10, 'f' becomes 15 + * + * Returns -1 if the provided character code was not a valid hexadecimal digit. + * + * HexDigit :: one of + * - `0` `1` `2` `3` `4` `5` `6` `7` `8` `9` + * - `A` `B` `C` `D` `E` `F` + * - `a` `b` `c` `d` `e` `f` + * + * @internal + */ + +function readHexDigit(code) { + return code >= 0x0030 && code <= 0x0039 // 0-9 + ? code - 0x0030 + : code >= 0x0041 && code <= 0x0046 // A-F + ? code - 0x0037 + : code >= 0x0061 && code <= 0x0066 // a-f + ? code - 0x0057 + : -1; +} +/** + * | Escaped Character | Code Point | Character Name | + * | ----------------- | ---------- | ---------------------------- | + * | `"` | U+0022 | double quote | + * | `\` | U+005C | reverse solidus (back slash) | + * | `/` | U+002F | solidus (forward slash) | + * | `b` | U+0008 | backspace | + * | `f` | U+000C | form feed | + * | `n` | U+000A | line feed (new line) | + * | `r` | U+000D | carriage return | + * | `t` | U+0009 | horizontal tab | + * + * @internal + */ + +function readEscapedCharacter(lexer, position) { + const body = lexer.source.body; + const code = body.charCodeAt(position + 1); + + switch (code) { + case 0x0022: + // " + return { + value: '\u0022', + size: 2, + }; + + case 0x005c: + // \ + return { + value: '\u005c', + size: 2, + }; + + case 0x002f: + // / + return { + value: '\u002f', + size: 2, + }; + + case 0x0062: + // b + return { + value: '\u0008', + size: 2, + }; + + case 0x0066: + // f + return { + value: '\u000c', + size: 2, + }; + + case 0x006e: + // n + return { + value: '\u000a', + size: 2, + }; + + case 0x0072: + // r + return { + value: '\u000d', + size: 2, + }; + + case 0x0074: + // t + return { + value: '\u0009', + size: 2, + }; + } + + throw syntaxError( + lexer.source, + position, + `Invalid character escape sequence: "${body.slice( + position, + position + 2, + )}".`, + ); +} +/** + * Reads a block string token from the source file. + * + * ``` + * StringValue :: + * - `"""` BlockStringCharacter* `"""` + * + * BlockStringCharacter :: + * - SourceCharacter but not `"""` or `\"""` + * - `\"""` + * ``` + * + * @internal + */ + +function readBlockString(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let lineStart = lexer.lineStart; + let position = start + 3; + let chunkStart = position; + let currentLine = ''; + const blockLines = []; + + while (position < bodyLength) { + const code = body.charCodeAt(position); // Closing Triple-Quote (""") + + if ( + code === 0x0022 && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + const token = createToken( + lexer, + TokenKind.BLOCK_STRING, + start, + position + 3, // Return a string of the lines joined with U+000A. + dedentBlockStringLines(blockLines).join('\n'), + ); + lexer.line += blockLines.length - 1; + lexer.lineStart = lineStart; + return token; + } // Escaped Triple-Quote (\""") + + if ( + code === 0x005c && + body.charCodeAt(position + 1) === 0x0022 && + body.charCodeAt(position + 2) === 0x0022 && + body.charCodeAt(position + 3) === 0x0022 + ) { + currentLine += body.slice(chunkStart, position); + chunkStart = position + 1; // skip only slash + + position += 4; + continue; + } // LineTerminator + + if (code === 0x000a || code === 0x000d) { + currentLine += body.slice(chunkStart, position); + blockLines.push(currentLine); + + if (code === 0x000d && body.charCodeAt(position + 1) === 0x000a) { + position += 2; + } else { + ++position; + } + + currentLine = ''; + chunkStart = position; + lineStart = position; + continue; + } // SourceCharacter + + if (isUnicodeScalarValue(code)) { + ++position; + } else if (isSupplementaryCodePoint(body, position)) { + position += 2; + } else { + throw syntaxError( + lexer.source, + position, + `Invalid character within String: ${printCodePointAt( + lexer, + position, + )}.`, + ); + } + } + + throw syntaxError(lexer.source, position, 'Unterminated string.'); +} +/** + * Reads an alphanumeric + underscore name from the source. + * + * ``` + * Name :: + * - NameStart NameContinue* [lookahead != NameContinue] + * ``` + * + * @internal + */ + +export function readName(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + let position = start + 1; + + while (position < bodyLength) { + const code = body.charCodeAt(position); + + if (isNameContinue(code)) { + ++position; + } else { + break; + } + } + + return createToken( + lexer, + TokenKind.NAME, + start, + position, + body.slice(start, position), + ); +} diff --git a/node_modules/graphql/language/location.d.ts b/node_modules/graphql/language/location.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..76945b9e657c974bf7bf5c5ae8dbb773f27960e6 --- /dev/null +++ b/node_modules/graphql/language/location.d.ts @@ -0,0 +1,29 @@ +/** @category Source */ +import type { Source } from './source'; +/** Represents a location in a Source. */ +export interface SourceLocation { + /** One-indexed line number in the source document. */ + readonly line: number; + /** One-indexed column number in the source document. */ + readonly column: number; +} +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + * @param source - The source document that contains the position. + * @param position - The UTF-8 character offset in the source body. + * @returns The 1-indexed line and column for the given source position. + * @example + * ```ts + * import { Source, getLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const location = getLocation(source, 13); + * + * location; // => { line: 1, column: 14 } + * ``` + */ +export declare function getLocation( + source: Source, + position: number, +): SourceLocation; diff --git a/node_modules/graphql/language/location.js b/node_modules/graphql/language/location.js new file mode 100644 index 0000000000000000000000000000000000000000..efbb7db8db2301cf83539dbd370b687b369719ef --- /dev/null +++ b/node_modules/graphql/language/location.js @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.getLocation = getLocation; + +var _invariant = require('../jsutils/invariant.js'); + +/** @category Source */ +const LineRegExp = /\r\n|[\n\r]/g; +/** Represents a location in a Source. */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + * @param source - The source document that contains the position. + * @param position - The UTF-8 character offset in the source body. + * @returns The 1-indexed line and column for the given source position. + * @example + * ```ts + * import { Source, getLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const location = getLocation(source, 13); + * + * location; // => { line: 1, column: 14 } + * ``` + */ +function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === 'number' || (0, _invariant.invariant)(false); + + if (match.index >= position) { + break; + } + + lastLineStart = match.index + match[0].length; + line += 1; + } + + return { + line, + column: position + 1 - lastLineStart, + }; +} diff --git a/node_modules/graphql/language/location.mjs b/node_modules/graphql/language/location.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d3cc9989fdcd5729e70f838ebad0443dc0c601ac --- /dev/null +++ b/node_modules/graphql/language/location.mjs @@ -0,0 +1,41 @@ +/** @category Source */ +import { invariant } from '../jsutils/invariant.mjs'; +const LineRegExp = /\r\n|[\n\r]/g; +/** Represents a location in a Source. */ + +/** + * Takes a Source and a UTF-8 character offset, and returns the corresponding + * line and column as a SourceLocation. + * @param source - The source document that contains the position. + * @param position - The UTF-8 character offset in the source body. + * @returns The 1-indexed line and column for the given source position. + * @example + * ```ts + * import { Source, getLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const location = getLocation(source, 13); + * + * location; // => { line: 1, column: 14 } + * ``` + */ +export function getLocation(source, position) { + let lastLineStart = 0; + let line = 1; + + for (const match of source.body.matchAll(LineRegExp)) { + typeof match.index === 'number' || invariant(false); + + if (match.index >= position) { + break; + } + + lastLineStart = match.index + match[0].length; + line += 1; + } + + return { + line, + column: position + 1 - lastLineStart, + }; +} diff --git a/node_modules/graphql/language/parser.d.ts b/node_modules/graphql/language/parser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c7639732057238ed5b502d08895590631996335 --- /dev/null +++ b/node_modules/graphql/language/parser.d.ts @@ -0,0 +1,829 @@ +/** @category Parsing */ +import type { Maybe } from '../jsutils/Maybe'; +import type { GraphQLError } from '../error/GraphQLError'; +import type { + ArgumentNode, + ConstArgumentNode, + ConstDirectiveNode, + ConstListValueNode, + ConstObjectFieldNode, + ConstObjectValueNode, + ConstValueNode, + DefinitionNode, + DirectiveDefinitionNode, + DirectiveExtensionNode, + DirectiveNode, + DocumentNode, + EnumTypeDefinitionNode, + EnumTypeExtensionNode, + EnumValueDefinitionNode, + FieldDefinitionNode, + FieldNode, + FragmentDefinitionNode, + FragmentSpreadNode, + InlineFragmentNode, + InputObjectTypeDefinitionNode, + InputObjectTypeExtensionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + InterfaceTypeExtensionNode, + ListValueNode, + NamedTypeNode, + NameNode, + ObjectFieldNode, + ObjectTypeDefinitionNode, + ObjectTypeExtensionNode, + ObjectValueNode, + OperationDefinitionNode, + OperationTypeDefinitionNode, + ScalarTypeDefinitionNode, + ScalarTypeExtensionNode, + SchemaCoordinateNode, + SchemaDefinitionNode, + SchemaExtensionNode, + SelectionNode, + SelectionSetNode, + StringValueNode, + Token, + TypeNode, + TypeSystemExtensionNode, + UnionTypeDefinitionNode, + UnionTypeExtensionNode, + ValueNode, + VariableDefinitionNode, + VariableNode, +} from './ast'; +import { Location, OperationTypeNode } from './ast'; +import type { LexerInterface } from './lexer'; +import { Source } from './source'; +import { TokenKind } from './tokenKind'; +/** Configuration options to control parser behavior */ +export interface ParseOptions { + /** + * By default, the parser creates AST nodes that know the location + * in the source that they correspond to. This configuration flag + * disables that behavior for performance or testing. + */ + noLocation?: boolean; + /** + * Parser CPU and memory usage is linear to the number of tokens in a document + * however in extreme cases it becomes quadratic due to memory exhaustion. + * Parsing happens before validation so even invalid queries can burn lots of + * CPU time and memory. + * To prevent this you can set a maximum number of tokens allowed within a document. + */ + maxTokens?: number | undefined; + /** + * Deprecated option that allows legacy fragment variable definitions to be + * parsed. This legacy fragment variable syntax will be removed in v17. Move + * variable definitions to operations for spec-compliant documents; if you + * need variables or arguments scoped to fragments, v17 has a more complete + * experimental fragment-arguments feature. + * @example + * The syntax is identical to normal, query-defined variables. + * + * ```graphql + * fragment A($var: Boolean = false) on T { + * ... + * } + * ``` + * @deprecated will be removed in the v17.0.0 + * + * If enabled, the parser will understand and parse variable definitions + * contained in a fragment definition. They'll be represented in the + * `variableDefinitions` field of the FragmentDefinitionNode. + */ + allowLegacyFragmentVariables?: boolean; + /** + * EXPERIMENTAL: + * + * If enabled, the parser will parse directives on directive definitions. + * This syntax is not part of the GraphQL specification and may change. + * @example + * ```graphql + * directive @foo @bar on FIELD + * ``` + */ + experimentalDirectivesOnDirectiveDefinitions?: boolean; + /** + * Internal parser hook for GraphQL.js entry points that need to parse a + * restricted grammar with an alternate lexer. + * @internal + */ + lexer?: LexerInterface | undefined; +} +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + * @param source - A GraphQL source string or source object. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL document AST. + * @example + * ```ts + * // Parse a GraphQL document with the default parser options. + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * + * document.kind; // => 'Document' + * ``` + * @example + * ```ts + * // This variant enables parser options and provides an explicit lexer. + * import { Lexer, Source, parse } from 'graphql/language'; + * + * const document = parse('fragment A($var: Boolean) on Query { field }', { + * allowLegacyFragmentVariables: true, + * maxTokens: 20, + * noLocation: true, + * }); + * const directiveDocument = parse('directive @foo @bar on FIELD', { + * experimentalDirectivesOnDirectiveDefinitions: true, + * }); + * const source = new Source('{ hero }'); + * const lexerDocument = parse(source, { lexer: new Lexer(source) }); + * + * document.definitions[0].kind; // => 'FragmentDefinition' + * document.loc; // => undefined + * directiveDocument.definitions[0].kind; // => 'DirectiveDefinition' + * lexerDocument.definitions[0].kind; // => 'OperationDefinition' + * ``` + */ +export declare function parse( + source: string | Source, + options?: ParseOptions | undefined, +): DocumentNode; +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + * @param source - A GraphQL source string or source object containing a value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * + * value.kind; // => 'ListValue' + * ``` + */ +export declare function parseValue( + source: string | Source, + options?: ParseOptions | undefined, +): ValueNode; +/** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + * @param source - A GraphQL source string or source object containing a constant value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL constant value AST. + * @example + * ```ts + * import { parseConstValue } from 'graphql/language'; + * + * const value = parseConstValue('{ enabled: true }'); + * + * value.kind; // => 'ObjectValue' + * parseConstValue('$variable'); // throws an error + * ``` + */ +export declare function parseConstValue( + source: string | Source, + options?: ParseOptions | undefined, +): ConstValueNode; +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + * @param source - A GraphQL source string or source object containing a type reference. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL type AST. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * + * type.kind; // => 'ListType' + * ``` + */ +export declare function parseType( + source: string | Source, + options?: ParseOptions | undefined, +): TypeNode; +/** + * Given a string containing a GraphQL Schema Coordinate (ex. `Type.field`), + * parse the AST for that schema coordinate. + * Throws GraphQLError if a syntax error is encountered. + * + * Consider providing the results to the utility function: + * resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly + * with an unparsed source. + * @param source - A GraphQL source string or source object containing a schema coordinate. + * @returns The parsed GraphQL schema coordinate AST. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * + * coordinate.kind; // => 'MemberCoordinate' + * ``` + */ +export declare function parseSchemaCoordinate( + source: string | Source, +): SchemaCoordinateNode; +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ +export declare class Parser { + protected _options: Omit; + protected _lexer: LexerInterface; + protected _tokenCounter: number; + constructor(source: string | Source, options?: ParseOptions); + get tokenCount(): number; + /** + * Converts a name lex token into a name parse node. + * + * @internal + */ + parseName(): NameNode; + /** + * Document : Definition+ + * + * @internal + */ + parseDocument(): DocumentNode; + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + * + * @internal + */ + parseDefinition(): DefinitionNode; + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + * + * @internal + */ + parseOperationDefinition(): OperationDefinitionNode; + /** + * OperationType : one of query mutation subscription + * + * @internal + */ + parseOperationType(): OperationTypeNode; + /** + * VariableDefinitions : ( VariableDefinition+ ) + * + * @internal + */ + parseVariableDefinitions(): Array; + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + * + * @internal + */ + parseVariableDefinition(): VariableDefinitionNode; + /** + * Variable : $ Name + * + * @internal + */ + parseVariable(): VariableNode; + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + * + * @internal + */ + parseSelectionSet(): SelectionSetNode; + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + * + * @internal + */ + parseSelection(): SelectionNode; + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + * + * @internal + */ + parseField(): FieldNode; + /** + * Arguments[Const] : ( Argument[?Const]+ ) + * + * @internal + */ + parseArguments(isConst: true): Array; + parseArguments(isConst: boolean): Array; + /** + * Argument[Const] : Name : Value[?Const] + * + * @internal + */ + parseArgument(isConst: true): ConstArgumentNode; + parseArgument(isConst?: boolean): ArgumentNode; + parseConstArgument(): ConstArgumentNode; + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + * + * @internal + */ + parseFragment(): FragmentSpreadNode | InlineFragmentNode; + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + * + * @internal + */ + parseFragmentDefinition(): FragmentDefinitionNode; + /** + * FragmentName : Name but not `on` + * + * @internal + */ + parseFragmentName(): NameNode; + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + parseValueLiteral(isConst: true): ConstValueNode; + parseValueLiteral(isConst: boolean): ValueNode; + parseConstValueLiteral(): ConstValueNode; + parseStringLiteral(): StringValueNode; + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + * + * @internal + */ + parseList(isConst: true): ConstListValueNode; + parseList(isConst: boolean): ListValueNode; + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + * + * @internal + */ + parseObject(isConst: true): ConstObjectValueNode; + parseObject(isConst: boolean): ObjectValueNode; + /** + * ObjectField[Const] : Name : Value[?Const] + * + * @internal + */ + parseObjectField(isConst: true): ConstObjectFieldNode; + parseObjectField(isConst: boolean): ObjectFieldNode; + /** + * Directives[Const] : Directive[?Const]+ + * + * @internal + */ + parseDirectives(isConst: true): Array; + parseDirectives(isConst: boolean): Array; + parseConstDirectives(): Array; + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + * + * @internal + */ + parseDirective(isConst: true): ConstDirectiveNode; + parseDirective(isConst: boolean): DirectiveNode; + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + * + * @internal + */ + parseTypeReference(): TypeNode; + /** + * NamedType : Name + * + * @internal + */ + parseNamedType(): NamedTypeNode; + peekDescription(): boolean; + /** + * Description : StringValue + * + * @internal + */ + parseDescription(): undefined | StringValueNode; + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + * + * @internal + */ + parseSchemaDefinition(): SchemaDefinitionNode; + /** + * OperationTypeDefinition : OperationType : NamedType + * + * @internal + */ + parseOperationTypeDefinition(): OperationTypeDefinitionNode; + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + * + * @internal + */ + parseScalarTypeDefinition(): ScalarTypeDefinitionNode; + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + * + * @internal + */ + parseObjectTypeDefinition(): ObjectTypeDefinitionNode; + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + * + * @internal + */ + parseImplementsInterfaces(): Array; + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + * + * @internal + */ + parseFieldsDefinition(): Array; + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + * + * @internal + */ + parseFieldDefinition(): FieldDefinitionNode; + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + * + * @internal + */ + parseArgumentDefs(): Array; + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + * + * @internal + */ + parseInputValueDef(): InputValueDefinitionNode; + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + * + * @internal + */ + parseInterfaceTypeDefinition(): InterfaceTypeDefinitionNode; + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + * + * @internal + */ + parseUnionTypeDefinition(): UnionTypeDefinitionNode; + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + * + * @internal + */ + parseUnionMemberTypes(): Array; + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + * + * @internal + */ + parseEnumTypeDefinition(): EnumTypeDefinitionNode; + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + * + * @internal + */ + parseEnumValuesDefinition(): Array; + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * @internal + */ + parseEnumValueDefinition(): EnumValueDefinitionNode; + /** + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + parseEnumValueName(): NameNode; + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + * + * @internal + */ + parseInputObjectTypeDefinition(): InputObjectTypeDefinitionNode; + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + * + * @internal + */ + parseInputFieldsDefinition(): Array; + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + * - DirectiveDefinitionExtension + * + * @internal + */ + parseTypeSystemExtension(): TypeSystemExtensionNode; + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + * + * @internal + */ + parseSchemaExtension(): SchemaExtensionNode; + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + * + * @internal + */ + parseScalarTypeExtension(): ScalarTypeExtensionNode; + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + * + * @internal + */ + parseObjectTypeExtension(): ObjectTypeExtensionNode; + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + * + * @internal + */ + parseInterfaceTypeExtension(): InterfaceTypeExtensionNode; + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + * + * @internal + */ + parseUnionTypeExtension(): UnionTypeExtensionNode; + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + * + * @internal + */ + parseEnumTypeExtension(): EnumTypeExtensionNode; + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + * + * @internal + */ + parseInputObjectTypeExtension(): InputObjectTypeExtensionNode; + parseDirectiveDefinitionExtension(): DirectiveExtensionNode; + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + * + * @internal + */ + parseDirectiveDefinition(): DirectiveDefinitionNode; + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + * + * @internal + */ + parseDirectiveLocations(): Array; + parseDirectiveLocation(): NameNode; + /** + * SchemaCoordinate : + * - Name + * - Name . Name + * - Name . Name ( Name : ) + * - \@ Name + * - \@ Name ( Name : ) + * @returns Parsed schema coordinate AST. + * @example + * ```ts + * import { Parser, Source } from 'graphql/language'; + * + * const typeCoordinate = new Parser(new Source('User.name')).parseSchemaCoordinate(); + * const directiveCoordinate = new Parser(new Source('@include(if:)')).parseSchemaCoordinate(); + * + * typeCoordinate.name.value; // => 'User' + * typeCoordinate.memberName?.value; // => 'name' + * directiveCoordinate.name.value; // => 'deprecated' + * directiveCoordinate.argumentName?.value; // => 'reason' + * ``` + */ + parseSchemaCoordinate(): SchemaCoordinateNode; + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + * + * @internal + */ + node< + T extends { + loc?: Location; + }, + >(startToken: Token, node: T): T; + /** + * Determines if the next token is of a given kind + * + * @internal + */ + peek(kind: TokenKind): boolean; + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + expectToken(kind: TokenKind): Token; + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + expectOptionalToken(kind: TokenKind): boolean; + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + expectKeyword(value: string): void; + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + expectOptionalKeyword(value: string): boolean; + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + * + * @internal + */ + unexpected(atToken?: Maybe): GraphQLError; + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + any(openKind: TokenKind, parseFn: () => T, closeKind: TokenKind): Array; + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + optionalMany( + openKind: TokenKind, + parseFn: () => T, + closeKind: TokenKind, + ): Array; + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + many( + openKind: TokenKind, + parseFn: () => T, + closeKind: TokenKind, + ): Array; + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + * + * @internal + */ + delimitedMany(delimiterKind: TokenKind, parseFn: () => T): Array; + advanceLexer(): void; +} diff --git a/node_modules/graphql/language/parser.js b/node_modules/graphql/language/parser.js new file mode 100644 index 0000000000000000000000000000000000000000..0634ce0c063d2bdb57e14a966653e1f150692c24 --- /dev/null +++ b/node_modules/graphql/language/parser.js @@ -0,0 +1,1949 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.Parser = void 0; +exports.parse = parse; +exports.parseConstValue = parseConstValue; +exports.parseSchemaCoordinate = parseSchemaCoordinate; +exports.parseType = parseType; +exports.parseValue = parseValue; + +var _syntaxError = require('../error/syntaxError.js'); + +var _ast = require('./ast.js'); + +var _directiveLocation = require('./directiveLocation.js'); + +var _kinds = require('./kinds.js'); + +var _lexer = require('./lexer.js'); + +var _schemaCoordinateLexer = require('./schemaCoordinateLexer.js'); + +var _source = require('./source.js'); + +var _tokenKind = require('./tokenKind.js'); + +/** @category Parsing */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + * @param source - A GraphQL source string or source object. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL document AST. + * @example + * ```ts + * // Parse a GraphQL document with the default parser options. + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * + * document.kind; // => 'Document' + * ``` + * @example + * ```ts + * // This variant enables parser options and provides an explicit lexer. + * import { Lexer, Source, parse } from 'graphql/language'; + * + * const document = parse('fragment A($var: Boolean) on Query { field }', { + * allowLegacyFragmentVariables: true, + * maxTokens: 20, + * noLocation: true, + * }); + * const directiveDocument = parse('directive @foo @bar on FIELD', { + * experimentalDirectivesOnDirectiveDefinitions: true, + * }); + * const source = new Source('{ hero }'); + * const lexerDocument = parse(source, { lexer: new Lexer(source) }); + * + * document.definitions[0].kind; // => 'FragmentDefinition' + * document.loc; // => undefined + * directiveDocument.definitions[0].kind; // => 'DirectiveDefinition' + * lexerDocument.definitions[0].kind; // => 'OperationDefinition' + * ``` + */ +function parse(source, options) { + const parser = new Parser(source, options); + const document = parser.parseDocument(); + Object.defineProperty(document, 'tokenCount', { + enumerable: false, + value: parser.tokenCount, + }); + return document; +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + * @param source - A GraphQL source string or source object containing a value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * + * value.kind; // => 'ListValue' + * ``` + */ + +function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + * @param source - A GraphQL source string or source object containing a constant value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL constant value AST. + * @example + * ```ts + * import { parseConstValue } from 'graphql/language'; + * + * const value = parseConstValue('{ enabled: true }'); + * + * value.kind; // => 'ObjectValue' + * parseConstValue('$variable'); // throws an error + * ``` + */ + +function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + * @param source - A GraphQL source string or source object containing a type reference. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL type AST. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * + * type.kind; // => 'ListType' + * ``` + */ + +function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(_tokenKind.TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return type; +} +/** + * Given a string containing a GraphQL Schema Coordinate (ex. `Type.field`), + * parse the AST for that schema coordinate. + * Throws GraphQLError if a syntax error is encountered. + * + * Consider providing the results to the utility function: + * resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly + * with an unparsed source. + * @param source - A GraphQL source string or source object containing a schema coordinate. + * @returns The parsed GraphQL schema coordinate AST. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * + * coordinate.kind; // => 'MemberCoordinate' + * ``` + */ + +function parseSchemaCoordinate(source) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + const lexer = new _schemaCoordinateLexer.SchemaCoordinateLexer(sourceObj); + const parser = new Parser(source, { + lexer, + }); + parser.expectToken(_tokenKind.TokenKind.SOF); + const coordinate = parser.parseSchemaCoordinate(); + parser.expectToken(_tokenKind.TokenKind.EOF); + return coordinate; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + +class Parser { + constructor(source, options = {}) { + const { lexer, ..._options } = options; + + if (lexer) { + this._lexer = lexer; + } else { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + this._lexer = new _lexer.Lexer(sourceObj); + } + + this._options = _options; + this._tokenCounter = 0; + } + + get tokenCount() { + return this._tokenCounter; + } + /** + * Converts a name lex token into a name parse node. + * + * @internal + */ + + parseName() { + const token = this.expectToken(_tokenKind.TokenKind.NAME); + return this.node(token, { + kind: _kinds.Kind.NAME, + value: token.value, + }); + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + * + * @internal + */ + + parseDocument() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.DOCUMENT, + definitions: this.many( + _tokenKind.TokenKind.SOF, + this.parseDefinition, + _tokenKind.TokenKind.EOF, + ), + }); + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + * + * @internal + */ + + parseDefinition() { + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. + + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription + ? this._lexer.lookahead() + : this._lexer.token; + + if (hasDescription && keywordToken.kind === _tokenKind.TokenKind.BRACE_L) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + 'Unexpected description, descriptions are not supported on shorthand queries.', + ); + } + + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + + case 'scalar': + return this.parseScalarTypeDefinition(); + + case 'type': + return this.parseObjectTypeDefinition(); + + case 'interface': + return this.parseInterfaceTypeDefinition(); + + case 'union': + return this.parseUnionTypeDefinition(); + + case 'enum': + return this.parseEnumTypeDefinition(); + + case 'input': + return this.parseInputObjectTypeDefinition(); + + case 'directive': + return this.parseDirectiveDefinition(); + } + + switch (keywordToken.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + + case 'fragment': + return this.parseFragmentDefinition(); + } + + if (hasDescription) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + 'Unexpected description, only GraphQL definitions support descriptions.', + ); + } + + switch (keywordToken.value) { + case 'extend': + return this.parseTypeSystemExtension(); + } + } + + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + * + * @internal + */ + + parseOperationDefinition() { + const start = this._lexer.token; + + if (this.peek(_tokenKind.TokenKind.BRACE_L)) { + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation: _ast.OperationTypeNode.QUERY, + description: undefined, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + }); + } + + const description = this.parseDescription(); + const operation = this.parseOperationType(); + let name; + + if (this.peek(_tokenKind.TokenKind.NAME)) { + name = this.parseName(); + } + + return this.node(start, { + kind: _kinds.Kind.OPERATION_DEFINITION, + operation, + description, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * OperationType : one of query mutation subscription + * + * @internal + */ + + parseOperationType() { + const operationToken = this.expectToken(_tokenKind.TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return _ast.OperationTypeNode.QUERY; + + case 'mutation': + return _ast.OperationTypeNode.MUTATION; + + case 'subscription': + return _ast.OperationTypeNode.SUBSCRIPTION; + } + + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + * + * @internal + */ + + parseVariableDefinitions() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseVariableDefinition, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + * + * @internal + */ + + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.VARIABLE_DEFINITION, + description: this.parseDescription(), + variable: this.parseVariable(), + type: + (this.expectToken(_tokenKind.TokenKind.COLON), + this.parseTypeReference()), + defaultValue: this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) + ? this.parseConstValueLiteral() + : undefined, + directives: this.parseConstDirectives(), + }); + } + /** + * Variable : $ Name + * + * @internal + */ + + parseVariable() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.DOLLAR); + return this.node(start, { + kind: _kinds.Kind.VARIABLE, + name: this.parseName(), + }); + } + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + * + * @internal + */ + + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.SELECTION_SET, + selections: this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseSelection, + _tokenKind.TokenKind.BRACE_R, + ), + }); + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + * + * @internal + */ + + parseSelection() { + return this.peek(_tokenKind.TokenKind.SPREAD) + ? this.parseFragment() + : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + * + * @internal + */ + + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + + if (this.expectOptionalToken(_tokenKind.TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + + return this.node(start, { + kind: _kinds.Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(_tokenKind.TokenKind.BRACE_L) + ? this.parseSelectionSet() + : undefined, + }); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + * + * @internal + */ + + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + item, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * Argument[Const] : Name : Value[?Const] + * + * @internal + */ + + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst), + }); + } + + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + * + * @internal + */ + + parseFragment() { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword('on'); + + if (!hasTypeCondition && this.peek(_tokenKind.TokenKind.NAME)) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + }); + } + + return this.node(start, { + kind: _kinds.Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + * + * @internal + */ + + parseFragmentDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + + return this.node(start, { + kind: _kinds.Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentName : Name but not `on` + * + * @internal + */ + + parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + + parseValueLiteral(isConst) { + const token = this._lexer.token; + + switch (token.kind) { + case _tokenKind.TokenKind.BRACKET_L: + return this.parseList(isConst); + + case _tokenKind.TokenKind.BRACE_L: + return this.parseObject(isConst); + + case _tokenKind.TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.INT, + value: token.value, + }); + + case _tokenKind.TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.FLOAT, + value: token.value, + }); + + case _tokenKind.TokenKind.STRING: + case _tokenKind.TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + + case _tokenKind.TokenKind.NAME: + this.advanceLexer(); + + switch (token.value) { + case 'true': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: true, + }); + + case 'false': + return this.node(token, { + kind: _kinds.Kind.BOOLEAN, + value: false, + }); + + case 'null': + return this.node(token, { + kind: _kinds.Kind.NULL, + }); + + default: + return this.node(token, { + kind: _kinds.Kind.ENUM, + value: token.value, + }); + } + + case _tokenKind.TokenKind.DOLLAR: + if (isConst) { + this.expectToken(_tokenKind.TokenKind.DOLLAR); + + if (this._lexer.token.kind === _tokenKind.TokenKind.NAME) { + const varName = this._lexer.token.value; + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected variable "$${varName}" in constant value.`, + ); + } else { + throw this.unexpected(token); + } + } + + return this.parseVariable(); + + default: + throw this.unexpected(); + } + } + + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: _kinds.Kind.STRING, + value: token.value, + block: token.kind === _tokenKind.TokenKind.BLOCK_STRING, + }); + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + * + * @internal + */ + + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + + return this.node(this._lexer.token, { + kind: _kinds.Kind.LIST, + values: this.any( + _tokenKind.TokenKind.BRACKET_L, + item, + _tokenKind.TokenKind.BRACKET_R, + ), + }); + } + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + * + * @internal + */ + + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + + return this.node(this._lexer.token, { + kind: _kinds.Kind.OBJECT, + fields: this.any( + _tokenKind.TokenKind.BRACE_L, + item, + _tokenKind.TokenKind.BRACE_R, + ), + }); + } + /** + * ObjectField[Const] : Name : Value[?Const] + * + * @internal + */ + + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + return this.node(start, { + kind: _kinds.Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst), + }); + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + * + * @internal + */ + + parseDirectives(isConst) { + const directives = []; + + while (this.peek(_tokenKind.TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + + return directives; + } + + parseConstDirectives() { + return this.parseDirectives(true); + } + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + * + * @internal + */ + + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(_tokenKind.TokenKind.AT); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + }); + } // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + * + * @internal + */ + + parseTypeReference() { + const start = this._lexer.token; + let type; + + if (this.expectOptionalToken(_tokenKind.TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(_tokenKind.TokenKind.BRACKET_R); + type = this.node(start, { + kind: _kinds.Kind.LIST_TYPE, + type: innerType, + }); + } else { + type = this.parseNamedType(); + } + + if (this.expectOptionalToken(_tokenKind.TokenKind.BANG)) { + return this.node(start, { + kind: _kinds.Kind.NON_NULL_TYPE, + type, + }); + } + + return type; + } + /** + * NamedType : Name + * + * @internal + */ + + parseNamedType() { + return this.node(this._lexer.token, { + kind: _kinds.Kind.NAMED_TYPE, + name: this.parseName(), + }); + } // Implements the parsing rules in the Type Definition section. + + peekDescription() { + return ( + this.peek(_tokenKind.TokenKind.STRING) || + this.peek(_tokenKind.TokenKind.BLOCK_STRING) + ); + } + /** + * Description : StringValue + * + * @internal + */ + + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + * + * @internal + */ + + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.many( + _tokenKind.TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + return this.node(start, { + kind: _kinds.Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes, + }); + } + /** + * OperationTypeDefinition : OperationType : NamedType + * + * @internal + */ + + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: _kinds.Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + }); + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + * + * @internal + */ + + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + }); + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + * + * @internal + */ + + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + * + * @internal + */ + + parseImplementsInterfaces() { + return this.expectOptionalKeyword('implements') + ? this.delimitedMany(_tokenKind.TokenKind.AMP, this.parseNamedType) + : []; + } + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + * + * @internal + */ + + parseFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseFieldDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + * + * @internal + */ + + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + }); + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + * + * @internal + */ + + parseArgumentDefs() { + return this.optionalMany( + _tokenKind.TokenKind.PAREN_L, + this.parseInputValueDef, + _tokenKind.TokenKind.PAREN_R, + ); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + * + * @internal + */ + + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + + if (this.expectOptionalToken(_tokenKind.TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + }); + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + * + * @internal + */ + + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + * + * @internal + */ + + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + }); + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + * + * @internal + */ + + parseUnionMemberTypes() { + return this.expectOptionalToken(_tokenKind.TokenKind.EQUALS) + ? this.delimitedMany(_tokenKind.TokenKind.PIPE, this.parseNamedType) + : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + * + * @internal + */ + + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + }); + } + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + * + * @internal + */ + + parseEnumValuesDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseEnumValueDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * @internal + */ + + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: _kinds.Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + }); + } + /** + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + + parseEnumValueName() { + if ( + this._lexer.token.value === 'true' || + this._lexer.token.value === 'false' || + this._lexer.token.value === 'null' + ) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + this._lexer.token.start, + `${getTokenDesc( + this._lexer.token, + )} is reserved and cannot be used for an enum value.`, + ); + } + + return this.parseName(); + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + * + * @internal + */ + + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + }); + } + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + * + * @internal + */ + + parseInputFieldsDefinition() { + return this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseInputValueDef, + _tokenKind.TokenKind.BRACE_R, + ); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + * - DirectiveDefinitionExtension + * + * @internal + */ + + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + + if (keywordToken.kind === _tokenKind.TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + + case 'scalar': + return this.parseScalarTypeExtension(); + + case 'type': + return this.parseObjectTypeExtension(); + + case 'interface': + return this.parseInterfaceTypeExtension(); + + case 'union': + return this.parseUnionTypeExtension(); + + case 'enum': + return this.parseEnumTypeExtension(); + + case 'input': + return this.parseInputObjectTypeExtension(); + + case 'directive': + if (this._options.experimentalDirectivesOnDirectiveDefinitions) { + return this.parseDirectiveDefinitionExtension(); + } + + break; + } + } + + throw this.unexpected(keywordToken); + } + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + * + * @internal + */ + + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany( + _tokenKind.TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + _tokenKind.TokenKind.BRACE_R, + ); + + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + }); + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + * + * @internal + */ + + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + }); + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + * + * @internal + */ + + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + * + * @internal + */ + + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + * + * @internal + */ + + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + }); + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + * + * @internal + */ + + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + }); + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + * + * @internal + */ + + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + }); + } + + parseDirectiveDefinitionExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_EXTENSION, + name, + directives, + }); + } + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + * + * @internal + */ + + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const directives = this._options + .experimentalDirectivesOnDirectiveDefinitions + ? this.parseConstDirectives() + : []; + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + directives, + repeatable, + locations, + }); + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + * + * @internal + */ + + parseDirectiveLocations() { + return this.delimitedMany( + _tokenKind.TokenKind.PIPE, + this.parseDirectiveLocation, + ); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + * `DIRECTIVE_DEFINITION` + */ + + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + + if ( + Object.prototype.hasOwnProperty.call( + _directiveLocation.DirectiveLocation, + name.value, + ) + ) { + return name; + } + + throw this.unexpected(start); + } // Schema Coordinates + + /** + * SchemaCoordinate : + * - Name + * - Name . Name + * - Name . Name ( Name : ) + * - \@ Name + * - \@ Name ( Name : ) + * @returns Parsed schema coordinate AST. + * @example + * ```ts + * import { Parser, Source } from 'graphql/language'; + * + * const typeCoordinate = new Parser(new Source('User.name')).parseSchemaCoordinate(); + * const directiveCoordinate = new Parser(new Source('@include(if:)')).parseSchemaCoordinate(); + * + * typeCoordinate.name.value; // => 'User' + * typeCoordinate.memberName?.value; // => 'name' + * directiveCoordinate.name.value; // => 'deprecated' + * directiveCoordinate.argumentName?.value; // => 'reason' + * ``` + */ + + parseSchemaCoordinate() { + const start = this._lexer.token; + const ofDirective = this.expectOptionalToken(_tokenKind.TokenKind.AT); + const name = this.parseName(); + let memberName; + + if (!ofDirective && this.expectOptionalToken(_tokenKind.TokenKind.DOT)) { + memberName = this.parseName(); + } + + let argumentName; + + if ( + (ofDirective || memberName) && + this.expectOptionalToken(_tokenKind.TokenKind.PAREN_L) + ) { + argumentName = this.parseName(); + this.expectToken(_tokenKind.TokenKind.COLON); + this.expectToken(_tokenKind.TokenKind.PAREN_R); + } + + if (ofDirective) { + if (argumentName) { + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_ARGUMENT_COORDINATE, + name, + argumentName, + }); + } + + return this.node(start, { + kind: _kinds.Kind.DIRECTIVE_COORDINATE, + name, + }); + } else if (memberName) { + if (argumentName) { + return this.node(start, { + kind: _kinds.Kind.ARGUMENT_COORDINATE, + name, + fieldName: memberName, + argumentName, + }); + } + + return this.node(start, { + kind: _kinds.Kind.MEMBER_COORDINATE, + name, + memberName, + }); + } + + return this.node(start, { + kind: _kinds.Kind.TYPE_COORDINATE, + name, + }); + } // Core parsing utility functions + + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + * + * @internal + */ + + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new _ast.Location( + startToken, + this._lexer.lastToken, + this._lexer.source, + ); + } + + return node; + } + /** + * Determines if the next token is of a given kind + * + * @internal + */ + + peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + + expectToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return token; + } + + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`, + ); + } + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + + expectOptionalToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return true; + } + + return false; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + + expectKeyword(value) { + const token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}.`, + ); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + + expectOptionalKeyword(value) { + const token = this._lexer.token; + + if (token.kind === _tokenKind.TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + * + * @internal + */ + + unexpected(atToken) { + const token = + atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}.`, + ); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + * + * @internal + */ + + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + + return nodes; + } + + advanceLexer() { + const { maxTokens } = this._options; + + const token = this._lexer.advance(); + + if (token.kind !== _tokenKind.TokenKind.EOF) { + ++this._tokenCounter; + + if (maxTokens !== undefined && this._tokenCounter > maxTokens) { + throw (0, _syntaxError.syntaxError)( + this._lexer.source, + token.start, + `Document contains more that ${maxTokens} tokens. Parsing aborted.`, + ); + } + } + } +} +/** + * A helper function to describe a token as a string for debugging. + * + * @internal + */ + +exports.Parser = Parser; + +function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); +} +/** + * A helper function to describe a token kind as a string for debugging. + * + * @internal + */ + +function getTokenKindDesc(kind) { + return (0, _lexer.isPunctuatorTokenKind)(kind) ? `"${kind}"` : kind; +} diff --git a/node_modules/graphql/language/parser.mjs b/node_modules/graphql/language/parser.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a39aa0a05ce62ec9ca3409cd2c26221dffe1707d --- /dev/null +++ b/node_modules/graphql/language/parser.mjs @@ -0,0 +1,1899 @@ +/** @category Parsing */ +import { syntaxError } from '../error/syntaxError.mjs'; +import { Location, OperationTypeNode } from './ast.mjs'; +import { DirectiveLocation } from './directiveLocation.mjs'; +import { Kind } from './kinds.mjs'; +import { isPunctuatorTokenKind, Lexer } from './lexer.mjs'; +import { SchemaCoordinateLexer } from './schemaCoordinateLexer.mjs'; +import { isSource, Source } from './source.mjs'; +import { TokenKind } from './tokenKind.mjs'; +/** Configuration options to control parser behavior */ + +/** + * Given a GraphQL source, parses it into a Document. + * Throws GraphQLError if a syntax error is encountered. + * @param source - A GraphQL source string or source object. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL document AST. + * @example + * ```ts + * // Parse a GraphQL document with the default parser options. + * import { parse } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * + * document.kind; // => 'Document' + * ``` + * @example + * ```ts + * // This variant enables parser options and provides an explicit lexer. + * import { Lexer, Source, parse } from 'graphql/language'; + * + * const document = parse('fragment A($var: Boolean) on Query { field }', { + * allowLegacyFragmentVariables: true, + * maxTokens: 20, + * noLocation: true, + * }); + * const directiveDocument = parse('directive @foo @bar on FIELD', { + * experimentalDirectivesOnDirectiveDefinitions: true, + * }); + * const source = new Source('{ hero }'); + * const lexerDocument = parse(source, { lexer: new Lexer(source) }); + * + * document.definitions[0].kind; // => 'FragmentDefinition' + * document.loc; // => undefined + * directiveDocument.definitions[0].kind; // => 'DirectiveDefinition' + * lexerDocument.definitions[0].kind; // => 'OperationDefinition' + * ``` + */ +export function parse(source, options) { + const parser = new Parser(source, options); + const document = parser.parseDocument(); + Object.defineProperty(document, 'tokenCount', { + enumerable: false, + value: parser.tokenCount, + }); + return document; +} +/** + * Given a string containing a GraphQL value (ex. `[42]`), parse the AST for + * that value. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Values directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: valueFromAST(). + * @param source - A GraphQL source string or source object containing a value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * + * value.kind; // => 'ListValue' + * ``` + */ + +export function parseValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + const value = parser.parseValueLiteral(false); + parser.expectToken(TokenKind.EOF); + return value; +} +/** + * Similar to parseValue(), but raises a parse error if it encounters a + * variable. The return type will be a constant value. + * @param source - A GraphQL source string or source object containing a constant value. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL constant value AST. + * @example + * ```ts + * import { parseConstValue } from 'graphql/language'; + * + * const value = parseConstValue('{ enabled: true }'); + * + * value.kind; // => 'ObjectValue' + * parseConstValue('$variable'); // throws an error + * ``` + */ + +export function parseConstValue(source, options) { + const parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + const value = parser.parseConstValueLiteral(); + parser.expectToken(TokenKind.EOF); + return value; +} +/** + * Given a string containing a GraphQL Type (ex. `[Int!]`), parse the AST for + * that type. + * Throws GraphQLError if a syntax error is encountered. + * + * This is useful within tools that operate upon GraphQL Types directly and + * in isolation of complete GraphQL documents. + * + * Consider providing the results to the utility function: typeFromAST(). + * @param source - A GraphQL source string or source object containing a type reference. + * @param options - Optional parser configuration. + * @returns The parsed GraphQL type AST. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * + * type.kind; // => 'ListType' + * ``` + */ + +export function parseType(source, options) { + const parser = new Parser(source, options); + parser.expectToken(TokenKind.SOF); + const type = parser.parseTypeReference(); + parser.expectToken(TokenKind.EOF); + return type; +} +/** + * Given a string containing a GraphQL Schema Coordinate (ex. `Type.field`), + * parse the AST for that schema coordinate. + * Throws GraphQLError if a syntax error is encountered. + * + * Consider providing the results to the utility function: + * resolveASTSchemaCoordinate(). Or calling resolveSchemaCoordinate() directly + * with an unparsed source. + * @param source - A GraphQL source string or source object containing a schema coordinate. + * @returns The parsed GraphQL schema coordinate AST. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * + * coordinate.kind; // => 'MemberCoordinate' + * ``` + */ + +export function parseSchemaCoordinate(source) { + const sourceObj = isSource(source) ? source : new Source(source); + const lexer = new SchemaCoordinateLexer(sourceObj); + const parser = new Parser(source, { + lexer, + }); + parser.expectToken(TokenKind.SOF); + const coordinate = parser.parseSchemaCoordinate(); + parser.expectToken(TokenKind.EOF); + return coordinate; +} +/** + * This class is exported only to assist people in implementing their own parsers + * without duplicating too much code and should be used only as last resort for cases + * such as experimental syntax or if certain features could not be contributed upstream. + * + * It is still part of the internal API and is versioned, so any changes to it are never + * considered breaking changes. If you still need to support multiple versions of the + * library, please use the `versionInfo` variable for version detection. + * + * @internal + */ + +export class Parser { + constructor(source, options = {}) { + const { lexer, ..._options } = options; + + if (lexer) { + this._lexer = lexer; + } else { + const sourceObj = isSource(source) ? source : new Source(source); + this._lexer = new Lexer(sourceObj); + } + + this._options = _options; + this._tokenCounter = 0; + } + + get tokenCount() { + return this._tokenCounter; + } + /** + * Converts a name lex token into a name parse node. + * + * @internal + */ + + parseName() { + const token = this.expectToken(TokenKind.NAME); + return this.node(token, { + kind: Kind.NAME, + value: token.value, + }); + } // Implements the parsing rules in the Document section. + + /** + * Document : Definition+ + * + * @internal + */ + + parseDocument() { + return this.node(this._lexer.token, { + kind: Kind.DOCUMENT, + definitions: this.many( + TokenKind.SOF, + this.parseDefinition, + TokenKind.EOF, + ), + }); + } + /** + * Definition : + * - ExecutableDefinition + * - TypeSystemDefinition + * - TypeSystemExtension + * + * ExecutableDefinition : + * - OperationDefinition + * - FragmentDefinition + * + * TypeSystemDefinition : + * - SchemaDefinition + * - TypeDefinition + * - DirectiveDefinition + * + * TypeDefinition : + * - ScalarTypeDefinition + * - ObjectTypeDefinition + * - InterfaceTypeDefinition + * - UnionTypeDefinition + * - EnumTypeDefinition + * - InputObjectTypeDefinition + * + * @internal + */ + + parseDefinition() { + if (this.peek(TokenKind.BRACE_L)) { + return this.parseOperationDefinition(); + } // Many definitions begin with a description and require a lookahead. + + const hasDescription = this.peekDescription(); + const keywordToken = hasDescription + ? this._lexer.lookahead() + : this._lexer.token; + + if (hasDescription && keywordToken.kind === TokenKind.BRACE_L) { + throw syntaxError( + this._lexer.source, + this._lexer.token.start, + 'Unexpected description, descriptions are not supported on shorthand queries.', + ); + } + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaDefinition(); + + case 'scalar': + return this.parseScalarTypeDefinition(); + + case 'type': + return this.parseObjectTypeDefinition(); + + case 'interface': + return this.parseInterfaceTypeDefinition(); + + case 'union': + return this.parseUnionTypeDefinition(); + + case 'enum': + return this.parseEnumTypeDefinition(); + + case 'input': + return this.parseInputObjectTypeDefinition(); + + case 'directive': + return this.parseDirectiveDefinition(); + } + + switch (keywordToken.value) { + case 'query': + case 'mutation': + case 'subscription': + return this.parseOperationDefinition(); + + case 'fragment': + return this.parseFragmentDefinition(); + } + + if (hasDescription) { + throw syntaxError( + this._lexer.source, + this._lexer.token.start, + 'Unexpected description, only GraphQL definitions support descriptions.', + ); + } + + switch (keywordToken.value) { + case 'extend': + return this.parseTypeSystemExtension(); + } + } + + throw this.unexpected(keywordToken); + } // Implements the parsing rules in the Operations section. + + /** + * OperationDefinition : + * - SelectionSet + * - OperationType Name? VariableDefinitions? Directives? SelectionSet + * + * @internal + */ + + parseOperationDefinition() { + const start = this._lexer.token; + + if (this.peek(TokenKind.BRACE_L)) { + return this.node(start, { + kind: Kind.OPERATION_DEFINITION, + operation: OperationTypeNode.QUERY, + description: undefined, + name: undefined, + variableDefinitions: [], + directives: [], + selectionSet: this.parseSelectionSet(), + }); + } + + const description = this.parseDescription(); + const operation = this.parseOperationType(); + let name; + + if (this.peek(TokenKind.NAME)) { + name = this.parseName(); + } + + return this.node(start, { + kind: Kind.OPERATION_DEFINITION, + operation, + description, + name, + variableDefinitions: this.parseVariableDefinitions(), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * OperationType : one of query mutation subscription + * + * @internal + */ + + parseOperationType() { + const operationToken = this.expectToken(TokenKind.NAME); + + switch (operationToken.value) { + case 'query': + return OperationTypeNode.QUERY; + + case 'mutation': + return OperationTypeNode.MUTATION; + + case 'subscription': + return OperationTypeNode.SUBSCRIPTION; + } + + throw this.unexpected(operationToken); + } + /** + * VariableDefinitions : ( VariableDefinition+ ) + * + * @internal + */ + + parseVariableDefinitions() { + return this.optionalMany( + TokenKind.PAREN_L, + this.parseVariableDefinition, + TokenKind.PAREN_R, + ); + } + /** + * VariableDefinition : Variable : Type DefaultValue? Directives[Const]? + * + * @internal + */ + + parseVariableDefinition() { + return this.node(this._lexer.token, { + kind: Kind.VARIABLE_DEFINITION, + description: this.parseDescription(), + variable: this.parseVariable(), + type: (this.expectToken(TokenKind.COLON), this.parseTypeReference()), + defaultValue: this.expectOptionalToken(TokenKind.EQUALS) + ? this.parseConstValueLiteral() + : undefined, + directives: this.parseConstDirectives(), + }); + } + /** + * Variable : $ Name + * + * @internal + */ + + parseVariable() { + const start = this._lexer.token; + this.expectToken(TokenKind.DOLLAR); + return this.node(start, { + kind: Kind.VARIABLE, + name: this.parseName(), + }); + } + /** + * ``` + * SelectionSet : { Selection+ } + * ``` + * + * @internal + */ + + parseSelectionSet() { + return this.node(this._lexer.token, { + kind: Kind.SELECTION_SET, + selections: this.many( + TokenKind.BRACE_L, + this.parseSelection, + TokenKind.BRACE_R, + ), + }); + } + /** + * Selection : + * - Field + * - FragmentSpread + * - InlineFragment + * + * @internal + */ + + parseSelection() { + return this.peek(TokenKind.SPREAD) + ? this.parseFragment() + : this.parseField(); + } + /** + * Field : Alias? Name Arguments? Directives? SelectionSet? + * + * Alias : Name : + * + * @internal + */ + + parseField() { + const start = this._lexer.token; + const nameOrAlias = this.parseName(); + let alias; + let name; + + if (this.expectOptionalToken(TokenKind.COLON)) { + alias = nameOrAlias; + name = this.parseName(); + } else { + name = nameOrAlias; + } + + return this.node(start, { + kind: Kind.FIELD, + alias, + name, + arguments: this.parseArguments(false), + directives: this.parseDirectives(false), + selectionSet: this.peek(TokenKind.BRACE_L) + ? this.parseSelectionSet() + : undefined, + }); + } + /** + * Arguments[Const] : ( Argument[?Const]+ ) + * + * @internal + */ + + parseArguments(isConst) { + const item = isConst ? this.parseConstArgument : this.parseArgument; + return this.optionalMany(TokenKind.PAREN_L, item, TokenKind.PAREN_R); + } + /** + * Argument[Const] : Name : Value[?Const] + * + * @internal + */ + + parseArgument(isConst = false) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(TokenKind.COLON); + return this.node(start, { + kind: Kind.ARGUMENT, + name, + value: this.parseValueLiteral(isConst), + }); + } + + parseConstArgument() { + return this.parseArgument(true); + } // Implements the parsing rules in the Fragments section. + + /** + * Corresponds to both FragmentSpread and InlineFragment in the spec. + * + * FragmentSpread : ... FragmentName Directives? + * + * InlineFragment : ... TypeCondition? Directives? SelectionSet + * + * @internal + */ + + parseFragment() { + const start = this._lexer.token; + this.expectToken(TokenKind.SPREAD); + const hasTypeCondition = this.expectOptionalKeyword('on'); + + if (!hasTypeCondition && this.peek(TokenKind.NAME)) { + return this.node(start, { + kind: Kind.FRAGMENT_SPREAD, + name: this.parseFragmentName(), + directives: this.parseDirectives(false), + }); + } + + return this.node(start, { + kind: Kind.INLINE_FRAGMENT, + typeCondition: hasTypeCondition ? this.parseNamedType() : undefined, + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentDefinition : + * - fragment FragmentName on TypeCondition Directives? SelectionSet + * + * TypeCondition : NamedType + * + * @internal + */ + + parseFragmentDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('fragment'); // Legacy support for defining variables within fragments changes + // the grammar of FragmentDefinition: + // - fragment FragmentName VariableDefinitions? on TypeCondition Directives? SelectionSet + + if (this._options.allowLegacyFragmentVariables === true) { + return this.node(start, { + kind: Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + variableDefinitions: this.parseVariableDefinitions(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + + return this.node(start, { + kind: Kind.FRAGMENT_DEFINITION, + description, + name: this.parseFragmentName(), + typeCondition: (this.expectKeyword('on'), this.parseNamedType()), + directives: this.parseDirectives(false), + selectionSet: this.parseSelectionSet(), + }); + } + /** + * FragmentName : Name but not `on` + * + * @internal + */ + + parseFragmentName() { + if (this._lexer.token.value === 'on') { + throw this.unexpected(); + } + + return this.parseName(); + } // Implements the parsing rules in the Values section. + + /** + * Value[Const] : + * - [~Const] Variable + * - IntValue + * - FloatValue + * - StringValue + * - BooleanValue + * - NullValue + * - EnumValue + * - ListValue[?Const] + * - ObjectValue[?Const] + * + * BooleanValue : one of `true` `false` + * + * NullValue : `null` + * + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + + parseValueLiteral(isConst) { + const token = this._lexer.token; + + switch (token.kind) { + case TokenKind.BRACKET_L: + return this.parseList(isConst); + + case TokenKind.BRACE_L: + return this.parseObject(isConst); + + case TokenKind.INT: + this.advanceLexer(); + return this.node(token, { + kind: Kind.INT, + value: token.value, + }); + + case TokenKind.FLOAT: + this.advanceLexer(); + return this.node(token, { + kind: Kind.FLOAT, + value: token.value, + }); + + case TokenKind.STRING: + case TokenKind.BLOCK_STRING: + return this.parseStringLiteral(); + + case TokenKind.NAME: + this.advanceLexer(); + + switch (token.value) { + case 'true': + return this.node(token, { + kind: Kind.BOOLEAN, + value: true, + }); + + case 'false': + return this.node(token, { + kind: Kind.BOOLEAN, + value: false, + }); + + case 'null': + return this.node(token, { + kind: Kind.NULL, + }); + + default: + return this.node(token, { + kind: Kind.ENUM, + value: token.value, + }); + } + + case TokenKind.DOLLAR: + if (isConst) { + this.expectToken(TokenKind.DOLLAR); + + if (this._lexer.token.kind === TokenKind.NAME) { + const varName = this._lexer.token.value; + throw syntaxError( + this._lexer.source, + token.start, + `Unexpected variable "$${varName}" in constant value.`, + ); + } else { + throw this.unexpected(token); + } + } + + return this.parseVariable(); + + default: + throw this.unexpected(); + } + } + + parseConstValueLiteral() { + return this.parseValueLiteral(true); + } + + parseStringLiteral() { + const token = this._lexer.token; + this.advanceLexer(); + return this.node(token, { + kind: Kind.STRING, + value: token.value, + block: token.kind === TokenKind.BLOCK_STRING, + }); + } + /** + * ListValue[Const] : + * - [ ] + * - [ Value[?Const]+ ] + * + * @internal + */ + + parseList(isConst) { + const item = () => this.parseValueLiteral(isConst); + + return this.node(this._lexer.token, { + kind: Kind.LIST, + values: this.any(TokenKind.BRACKET_L, item, TokenKind.BRACKET_R), + }); + } + /** + * ``` + * ObjectValue[Const] : + * - { } + * - { ObjectField[?Const]+ } + * ``` + * + * @internal + */ + + parseObject(isConst) { + const item = () => this.parseObjectField(isConst); + + return this.node(this._lexer.token, { + kind: Kind.OBJECT, + fields: this.any(TokenKind.BRACE_L, item, TokenKind.BRACE_R), + }); + } + /** + * ObjectField[Const] : Name : Value[?Const] + * + * @internal + */ + + parseObjectField(isConst) { + const start = this._lexer.token; + const name = this.parseName(); + this.expectToken(TokenKind.COLON); + return this.node(start, { + kind: Kind.OBJECT_FIELD, + name, + value: this.parseValueLiteral(isConst), + }); + } // Implements the parsing rules in the Directives section. + + /** + * Directives[Const] : Directive[?Const]+ + * + * @internal + */ + + parseDirectives(isConst) { + const directives = []; + + while (this.peek(TokenKind.AT)) { + directives.push(this.parseDirective(isConst)); + } + + return directives; + } + + parseConstDirectives() { + return this.parseDirectives(true); + } + /** + * ``` + * Directive[Const] : @ Name Arguments[?Const]? + * ``` + * + * @internal + */ + + parseDirective(isConst) { + const start = this._lexer.token; + this.expectToken(TokenKind.AT); + return this.node(start, { + kind: Kind.DIRECTIVE, + name: this.parseName(), + arguments: this.parseArguments(isConst), + }); + } // Implements the parsing rules in the Types section. + + /** + * Type : + * - NamedType + * - ListType + * - NonNullType + * + * @internal + */ + + parseTypeReference() { + const start = this._lexer.token; + let type; + + if (this.expectOptionalToken(TokenKind.BRACKET_L)) { + const innerType = this.parseTypeReference(); + this.expectToken(TokenKind.BRACKET_R); + type = this.node(start, { + kind: Kind.LIST_TYPE, + type: innerType, + }); + } else { + type = this.parseNamedType(); + } + + if (this.expectOptionalToken(TokenKind.BANG)) { + return this.node(start, { + kind: Kind.NON_NULL_TYPE, + type, + }); + } + + return type; + } + /** + * NamedType : Name + * + * @internal + */ + + parseNamedType() { + return this.node(this._lexer.token, { + kind: Kind.NAMED_TYPE, + name: this.parseName(), + }); + } // Implements the parsing rules in the Type Definition section. + + peekDescription() { + return this.peek(TokenKind.STRING) || this.peek(TokenKind.BLOCK_STRING); + } + /** + * Description : StringValue + * + * @internal + */ + + parseDescription() { + if (this.peekDescription()) { + return this.parseStringLiteral(); + } + } + /** + * ``` + * SchemaDefinition : Description? schema Directives[Const]? { OperationTypeDefinition+ } + * ``` + * + * @internal + */ + + parseSchemaDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.many( + TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + return this.node(start, { + kind: Kind.SCHEMA_DEFINITION, + description, + directives, + operationTypes, + }); + } + /** + * OperationTypeDefinition : OperationType : NamedType + * + * @internal + */ + + parseOperationTypeDefinition() { + const start = this._lexer.token; + const operation = this.parseOperationType(); + this.expectToken(TokenKind.COLON); + const type = this.parseNamedType(); + return this.node(start, { + kind: Kind.OPERATION_TYPE_DEFINITION, + operation, + type, + }); + } + /** + * ScalarTypeDefinition : Description? scalar Name Directives[Const]? + * + * @internal + */ + + parseScalarTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: Kind.SCALAR_TYPE_DEFINITION, + description, + name, + directives, + }); + } + /** + * ObjectTypeDefinition : + * Description? + * type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition? + * + * @internal + */ + + parseObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: Kind.OBJECT_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * ImplementsInterfaces : + * - implements `&`? NamedType + * - ImplementsInterfaces & NamedType + * + * @internal + */ + + parseImplementsInterfaces() { + return this.expectOptionalKeyword('implements') + ? this.delimitedMany(TokenKind.AMP, this.parseNamedType) + : []; + } + /** + * ``` + * FieldsDefinition : { FieldDefinition+ } + * ``` + * + * @internal + */ + + parseFieldsDefinition() { + return this.optionalMany( + TokenKind.BRACE_L, + this.parseFieldDefinition, + TokenKind.BRACE_R, + ); + } + /** + * FieldDefinition : + * - Description? Name ArgumentsDefinition? : Type Directives[Const]? + * + * @internal + */ + + parseFieldDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + this.expectToken(TokenKind.COLON); + const type = this.parseTypeReference(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: Kind.FIELD_DEFINITION, + description, + name, + arguments: args, + type, + directives, + }); + } + /** + * ArgumentsDefinition : ( InputValueDefinition+ ) + * + * @internal + */ + + parseArgumentDefs() { + return this.optionalMany( + TokenKind.PAREN_L, + this.parseInputValueDef, + TokenKind.PAREN_R, + ); + } + /** + * InputValueDefinition : + * - Description? Name : Type DefaultValue? Directives[Const]? + * + * @internal + */ + + parseInputValueDef() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseName(); + this.expectToken(TokenKind.COLON); + const type = this.parseTypeReference(); + let defaultValue; + + if (this.expectOptionalToken(TokenKind.EQUALS)) { + defaultValue = this.parseConstValueLiteral(); + } + + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: Kind.INPUT_VALUE_DEFINITION, + description, + name, + type, + defaultValue, + directives, + }); + } + /** + * InterfaceTypeDefinition : + * - Description? interface Name Directives[Const]? FieldsDefinition? + * + * @internal + */ + + parseInterfaceTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + return this.node(start, { + kind: Kind.INTERFACE_TYPE_DEFINITION, + description, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeDefinition : + * - Description? union Name Directives[Const]? UnionMemberTypes? + * + * @internal + */ + + parseUnionTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + return this.node(start, { + kind: Kind.UNION_TYPE_DEFINITION, + description, + name, + directives, + types, + }); + } + /** + * UnionMemberTypes : + * - = `|`? NamedType + * - UnionMemberTypes | NamedType + * + * @internal + */ + + parseUnionMemberTypes() { + return this.expectOptionalToken(TokenKind.EQUALS) + ? this.delimitedMany(TokenKind.PIPE, this.parseNamedType) + : []; + } + /** + * EnumTypeDefinition : + * - Description? enum Name Directives[Const]? EnumValuesDefinition? + * + * @internal + */ + + parseEnumTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + return this.node(start, { + kind: Kind.ENUM_TYPE_DEFINITION, + description, + name, + directives, + values, + }); + } + /** + * ``` + * EnumValuesDefinition : { EnumValueDefinition+ } + * ``` + * + * @internal + */ + + parseEnumValuesDefinition() { + return this.optionalMany( + TokenKind.BRACE_L, + this.parseEnumValueDefinition, + TokenKind.BRACE_R, + ); + } + /** + * EnumValueDefinition : Description? EnumValue Directives[Const]? + * + * @internal + */ + + parseEnumValueDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + const name = this.parseEnumValueName(); + const directives = this.parseConstDirectives(); + return this.node(start, { + kind: Kind.ENUM_VALUE_DEFINITION, + description, + name, + directives, + }); + } + /** + * EnumValue : Name but not `true`, `false` or `null` + * + * @internal + */ + + parseEnumValueName() { + if ( + this._lexer.token.value === 'true' || + this._lexer.token.value === 'false' || + this._lexer.token.value === 'null' + ) { + throw syntaxError( + this._lexer.source, + this._lexer.token.start, + `${getTokenDesc( + this._lexer.token, + )} is reserved and cannot be used for an enum value.`, + ); + } + + return this.parseName(); + } + /** + * InputObjectTypeDefinition : + * - Description? input Name Directives[Const]? InputFieldsDefinition? + * + * @internal + */ + + parseInputObjectTypeDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + return this.node(start, { + kind: Kind.INPUT_OBJECT_TYPE_DEFINITION, + description, + name, + directives, + fields, + }); + } + /** + * ``` + * InputFieldsDefinition : { InputValueDefinition+ } + * ``` + * + * @internal + */ + + parseInputFieldsDefinition() { + return this.optionalMany( + TokenKind.BRACE_L, + this.parseInputValueDef, + TokenKind.BRACE_R, + ); + } + /** + * TypeSystemExtension : + * - SchemaExtension + * - TypeExtension + * + * TypeExtension : + * - ScalarTypeExtension + * - ObjectTypeExtension + * - InterfaceTypeExtension + * - UnionTypeExtension + * - EnumTypeExtension + * - InputObjectTypeDefinition + * - DirectiveDefinitionExtension + * + * @internal + */ + + parseTypeSystemExtension() { + const keywordToken = this._lexer.lookahead(); + + if (keywordToken.kind === TokenKind.NAME) { + switch (keywordToken.value) { + case 'schema': + return this.parseSchemaExtension(); + + case 'scalar': + return this.parseScalarTypeExtension(); + + case 'type': + return this.parseObjectTypeExtension(); + + case 'interface': + return this.parseInterfaceTypeExtension(); + + case 'union': + return this.parseUnionTypeExtension(); + + case 'enum': + return this.parseEnumTypeExtension(); + + case 'input': + return this.parseInputObjectTypeExtension(); + + case 'directive': + if (this._options.experimentalDirectivesOnDirectiveDefinitions) { + return this.parseDirectiveDefinitionExtension(); + } + + break; + } + } + + throw this.unexpected(keywordToken); + } + /** + * ``` + * SchemaExtension : + * - extend schema Directives[Const]? { OperationTypeDefinition+ } + * - extend schema Directives[Const] + * ``` + * + * @internal + */ + + parseSchemaExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('schema'); + const directives = this.parseConstDirectives(); + const operationTypes = this.optionalMany( + TokenKind.BRACE_L, + this.parseOperationTypeDefinition, + TokenKind.BRACE_R, + ); + + if (directives.length === 0 && operationTypes.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.SCHEMA_EXTENSION, + directives, + operationTypes, + }); + } + /** + * ScalarTypeExtension : + * - extend scalar Name Directives[Const] + * + * @internal + */ + + parseScalarTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('scalar'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.SCALAR_TYPE_EXTENSION, + name, + directives, + }); + } + /** + * ObjectTypeExtension : + * - extend type Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend type Name ImplementsInterfaces? Directives[Const] + * - extend type Name ImplementsInterfaces + * + * @internal + */ + + parseObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('type'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.OBJECT_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * InterfaceTypeExtension : + * - extend interface Name ImplementsInterfaces? Directives[Const]? FieldsDefinition + * - extend interface Name ImplementsInterfaces? Directives[Const] + * - extend interface Name ImplementsInterfaces + * + * @internal + */ + + parseInterfaceTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('interface'); + const name = this.parseName(); + const interfaces = this.parseImplementsInterfaces(); + const directives = this.parseConstDirectives(); + const fields = this.parseFieldsDefinition(); + + if ( + interfaces.length === 0 && + directives.length === 0 && + fields.length === 0 + ) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.INTERFACE_TYPE_EXTENSION, + name, + interfaces, + directives, + fields, + }); + } + /** + * UnionTypeExtension : + * - extend union Name Directives[Const]? UnionMemberTypes + * - extend union Name Directives[Const] + * + * @internal + */ + + parseUnionTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('union'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const types = this.parseUnionMemberTypes(); + + if (directives.length === 0 && types.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.UNION_TYPE_EXTENSION, + name, + directives, + types, + }); + } + /** + * EnumTypeExtension : + * - extend enum Name Directives[Const]? EnumValuesDefinition + * - extend enum Name Directives[Const] + * + * @internal + */ + + parseEnumTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('enum'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const values = this.parseEnumValuesDefinition(); + + if (directives.length === 0 && values.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.ENUM_TYPE_EXTENSION, + name, + directives, + values, + }); + } + /** + * InputObjectTypeExtension : + * - extend input Name Directives[Const]? InputFieldsDefinition + * - extend input Name Directives[Const] + * + * @internal + */ + + parseInputObjectTypeExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('input'); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + const fields = this.parseInputFieldsDefinition(); + + if (directives.length === 0 && fields.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.INPUT_OBJECT_TYPE_EXTENSION, + name, + directives, + fields, + }); + } + + parseDirectiveDefinitionExtension() { + const start = this._lexer.token; + this.expectKeyword('extend'); + this.expectKeyword('directive'); + this.expectToken(TokenKind.AT); + const name = this.parseName(); + const directives = this.parseConstDirectives(); + + if (directives.length === 0) { + throw this.unexpected(); + } + + return this.node(start, { + kind: Kind.DIRECTIVE_EXTENSION, + name, + directives, + }); + } + /** + * ``` + * DirectiveDefinition : + * - Description? directive @ Name ArgumentsDefinition? `repeatable`? on DirectiveLocations + * ``` + * + * @internal + */ + + parseDirectiveDefinition() { + const start = this._lexer.token; + const description = this.parseDescription(); + this.expectKeyword('directive'); + this.expectToken(TokenKind.AT); + const name = this.parseName(); + const args = this.parseArgumentDefs(); + const directives = this._options + .experimentalDirectivesOnDirectiveDefinitions + ? this.parseConstDirectives() + : []; + const repeatable = this.expectOptionalKeyword('repeatable'); + this.expectKeyword('on'); + const locations = this.parseDirectiveLocations(); + return this.node(start, { + kind: Kind.DIRECTIVE_DEFINITION, + description, + name, + arguments: args, + directives, + repeatable, + locations, + }); + } + /** + * DirectiveLocations : + * - `|`? DirectiveLocation + * - DirectiveLocations | DirectiveLocation + * + * @internal + */ + + parseDirectiveLocations() { + return this.delimitedMany(TokenKind.PIPE, this.parseDirectiveLocation); + } + /* + * DirectiveLocation : + * - ExecutableDirectiveLocation + * - TypeSystemDirectiveLocation + * + * ExecutableDirectiveLocation : one of + * `QUERY` + * `MUTATION` + * `SUBSCRIPTION` + * `FIELD` + * `FRAGMENT_DEFINITION` + * `FRAGMENT_SPREAD` + * `INLINE_FRAGMENT` + * + * TypeSystemDirectiveLocation : one of + * `SCHEMA` + * `SCALAR` + * `OBJECT` + * `FIELD_DEFINITION` + * `ARGUMENT_DEFINITION` + * `INTERFACE` + * `UNION` + * `ENUM` + * `ENUM_VALUE` + * `INPUT_OBJECT` + * `INPUT_FIELD_DEFINITION` + * `DIRECTIVE_DEFINITION` + */ + + parseDirectiveLocation() { + const start = this._lexer.token; + const name = this.parseName(); + + if (Object.prototype.hasOwnProperty.call(DirectiveLocation, name.value)) { + return name; + } + + throw this.unexpected(start); + } // Schema Coordinates + + /** + * SchemaCoordinate : + * - Name + * - Name . Name + * - Name . Name ( Name : ) + * - \@ Name + * - \@ Name ( Name : ) + * @returns Parsed schema coordinate AST. + * @example + * ```ts + * import { Parser, Source } from 'graphql/language'; + * + * const typeCoordinate = new Parser(new Source('User.name')).parseSchemaCoordinate(); + * const directiveCoordinate = new Parser(new Source('@include(if:)')).parseSchemaCoordinate(); + * + * typeCoordinate.name.value; // => 'User' + * typeCoordinate.memberName?.value; // => 'name' + * directiveCoordinate.name.value; // => 'deprecated' + * directiveCoordinate.argumentName?.value; // => 'reason' + * ``` + */ + + parseSchemaCoordinate() { + const start = this._lexer.token; + const ofDirective = this.expectOptionalToken(TokenKind.AT); + const name = this.parseName(); + let memberName; + + if (!ofDirective && this.expectOptionalToken(TokenKind.DOT)) { + memberName = this.parseName(); + } + + let argumentName; + + if ( + (ofDirective || memberName) && + this.expectOptionalToken(TokenKind.PAREN_L) + ) { + argumentName = this.parseName(); + this.expectToken(TokenKind.COLON); + this.expectToken(TokenKind.PAREN_R); + } + + if (ofDirective) { + if (argumentName) { + return this.node(start, { + kind: Kind.DIRECTIVE_ARGUMENT_COORDINATE, + name, + argumentName, + }); + } + + return this.node(start, { + kind: Kind.DIRECTIVE_COORDINATE, + name, + }); + } else if (memberName) { + if (argumentName) { + return this.node(start, { + kind: Kind.ARGUMENT_COORDINATE, + name, + fieldName: memberName, + argumentName, + }); + } + + return this.node(start, { + kind: Kind.MEMBER_COORDINATE, + name, + memberName, + }); + } + + return this.node(start, { + kind: Kind.TYPE_COORDINATE, + name, + }); + } // Core parsing utility functions + + /** + * Returns a node that, if configured to do so, sets a "loc" field as a + * location object, used to identify the place in the source that created a + * given parsed object. + * + * @internal + */ + + node(startToken, node) { + if (this._options.noLocation !== true) { + node.loc = new Location( + startToken, + this._lexer.lastToken, + this._lexer.source, + ); + } + + return node; + } + /** + * Determines if the next token is of a given kind + * + * @internal + */ + + peek(kind) { + return this._lexer.token.kind === kind; + } + /** + * If the next token is of the given kind, return that token after advancing the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + + expectToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return token; + } + + throw syntaxError( + this._lexer.source, + token.start, + `Expected ${getTokenKindDesc(kind)}, found ${getTokenDesc(token)}.`, + ); + } + /** + * If the next token is of the given kind, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + + expectOptionalToken(kind) { + const token = this._lexer.token; + + if (token.kind === kind) { + this.advanceLexer(); + return true; + } + + return false; + } + /** + * If the next token is a given keyword, advance the lexer. + * Otherwise, do not change the parser state and throw an error. + * + * @internal + */ + + expectKeyword(value) { + const token = this._lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + this.advanceLexer(); + } else { + throw syntaxError( + this._lexer.source, + token.start, + `Expected "${value}", found ${getTokenDesc(token)}.`, + ); + } + } + /** + * If the next token is a given keyword, return "true" after advancing the lexer. + * Otherwise, do not change the parser state and return "false". + * + * @internal + */ + + expectOptionalKeyword(value) { + const token = this._lexer.token; + + if (token.kind === TokenKind.NAME && token.value === value) { + this.advanceLexer(); + return true; + } + + return false; + } + /** + * Helper function for creating an error when an unexpected lexed token is encountered. + * + * @internal + */ + + unexpected(atToken) { + const token = + atToken !== null && atToken !== void 0 ? atToken : this._lexer.token; + return syntaxError( + this._lexer.source, + token.start, + `Unexpected ${getTokenDesc(token)}.`, + ); + } + /** + * Returns a possibly empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + any(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + + while (!this.expectOptionalToken(closeKind)) { + nodes.push(parseFn.call(this)); + } + + return nodes; + } + /** + * Returns a list of parse nodes, determined by the parseFn. + * It can be empty only if open token is missing otherwise it will always return non-empty list + * that begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + optionalMany(openKind, parseFn, closeKind) { + if (this.expectOptionalToken(openKind)) { + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + + return []; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list begins with a lex token of openKind and ends with a lex token of closeKind. + * Advances the parser to the next lex token after the closing token. + * + * @internal + */ + + many(openKind, parseFn, closeKind) { + this.expectToken(openKind); + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (!this.expectOptionalToken(closeKind)); + + return nodes; + } + /** + * Returns a non-empty list of parse nodes, determined by the parseFn. + * This list may begin with a lex token of delimiterKind followed by items separated by lex tokens of tokenKind. + * Advances the parser to the next lex token after last item in the list. + * + * @internal + */ + + delimitedMany(delimiterKind, parseFn) { + this.expectOptionalToken(delimiterKind); + const nodes = []; + + do { + nodes.push(parseFn.call(this)); + } while (this.expectOptionalToken(delimiterKind)); + + return nodes; + } + + advanceLexer() { + const { maxTokens } = this._options; + + const token = this._lexer.advance(); + + if (token.kind !== TokenKind.EOF) { + ++this._tokenCounter; + + if (maxTokens !== undefined && this._tokenCounter > maxTokens) { + throw syntaxError( + this._lexer.source, + token.start, + `Document contains more that ${maxTokens} tokens. Parsing aborted.`, + ); + } + } + } +} +/** + * A helper function to describe a token as a string for debugging. + * + * @internal + */ + +function getTokenDesc(token) { + const value = token.value; + return getTokenKindDesc(token.kind) + (value != null ? ` "${value}"` : ''); +} +/** + * A helper function to describe a token kind as a string for debugging. + * + * @internal + */ + +function getTokenKindDesc(kind) { + return isPunctuatorTokenKind(kind) ? `"${kind}"` : kind; +} diff --git a/node_modules/graphql/language/predicates.d.ts b/node_modules/graphql/language/predicates.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e9480216c875514d6903d383cb82c1db9670b1ff --- /dev/null +++ b/node_modules/graphql/language/predicates.d.ts @@ -0,0 +1,206 @@ +/** @category AST Predicates */ +import type { + ASTNode, + ConstValueNode, + DefinitionNode, + ExecutableDefinitionNode, + SchemaCoordinateNode, + SelectionNode, + TypeDefinitionNode, + TypeExtensionNode, + TypeNode, + TypeSystemDefinitionNode, + TypeSystemExtensionNode, + ValueNode, +} from './ast'; +/** + * Returns true when the AST node is a definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a definition node. + * @example + * ```ts + * import { parse, isDefinitionNode } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * + * isDefinitionNode(document.definitions[0]); // => true + * isDefinitionNode(document); // => false + * ``` + */ +export declare function isDefinitionNode(node: ASTNode): node is DefinitionNode; +/** + * Returns true when the AST node is an executable definition node. + * @param node - The AST node to test. + * @returns True when the AST node is an executable definition node. + * @example + * ```ts + * import { parse, isExecutableDefinitionNode } from 'graphql/language'; + * + * const query = parse('{ hello }'); + * const schema = parse('type Query { hello: String }'); + * + * isExecutableDefinitionNode(query.definitions[0]); // => true + * isExecutableDefinitionNode(schema.definitions[0]); // => false + * ``` + */ +export declare function isExecutableDefinitionNode( + node: ASTNode, +): node is ExecutableDefinitionNode; +/** + * Returns true when the AST node is a selection node. + * @param node - The AST node to test. + * @returns True when the AST node is a selection node. + * @example + * ```ts + * import { Kind, isSelectionNode } from 'graphql/language'; + * + * const field = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'hello' } }; + * const document = { kind: Kind.DOCUMENT, definitions: [] }; + * + * isSelectionNode(field); // => true + * isSelectionNode(document); // => false + * ``` + */ +export declare function isSelectionNode(node: ASTNode): node is SelectionNode; +/** + * Returns true when the AST node is a value node. + * @param node - The AST node to test. + * @returns True when the AST node is a value node. + * @example + * ```ts + * import { parseType, parseValue, isValueNode } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * const type = parseType('[String!]'); + * + * isValueNode(value); // => true + * isValueNode(type); // => false + * ``` + */ +export declare function isValueNode(node: ASTNode): node is ValueNode; +/** + * Returns true when the AST node is a constant value node. + * @param node - The AST node to test. + * @returns True when the AST node is a constant value node. + * @example + * ```ts + * import { parseConstValue, parseValue, isConstValueNode } from 'graphql/language'; + * + * const value = parseConstValue('[42]'); + * const variable = parseValue('$id'); + * + * isConstValueNode(value); // => true + * isConstValueNode(variable); // => false + * ``` + */ +export declare function isConstValueNode(node: ASTNode): node is ConstValueNode; +/** + * Returns true when the AST node is a type node. + * @param node - The AST node to test. + * @returns True when the AST node is a type node. + * @example + * ```ts + * import { parseType, parseValue, isTypeNode } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * const value = parseValue('[42]'); + * + * isTypeNode(type); // => true + * isTypeNode(value); // => false + * ``` + */ +export declare function isTypeNode(node: ASTNode): node is TypeNode; +/** + * Returns true when the AST node is a type system definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system definition node. + * @example + * ```ts + * import { parse, isTypeSystemDefinitionNode } from 'graphql/language'; + * + * const schema = parse('type Query { hello: String }'); + * const query = parse('{ hello }'); + * + * isTypeSystemDefinitionNode(schema.definitions[0]); // => true + * isTypeSystemDefinitionNode(query.definitions[0]); // => false + * ``` + */ +export declare function isTypeSystemDefinitionNode( + node: ASTNode, +): node is TypeSystemDefinitionNode; +/** + * Returns true when the AST node is a type definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type definition node. + * @example + * ```ts + * import { parse, isTypeDefinitionNode } from 'graphql/language'; + * + * const typeDefinition = parse('type Query { hello: String }'); + * const directiveDefinition = parse('directive @cache on FIELD'); + * + * isTypeDefinitionNode(typeDefinition.definitions[0]); // => true + * isTypeDefinitionNode(directiveDefinition.definitions[0]); // => false + * ``` + */ +export declare function isTypeDefinitionNode( + node: ASTNode, +): node is TypeDefinitionNode; +/** + * Returns true when the AST node is a type system extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system extension node. + * @example + * ```ts + * import { parse, isTypeSystemExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const definition = parse('type Query { hello: String }'); + * + * isTypeSystemExtensionNode(extension.definitions[0]); // => true + * isTypeSystemExtensionNode(definition.definitions[0]); // => false + * ``` + */ +export declare function isTypeSystemExtensionNode( + node: ASTNode, +): node is TypeSystemExtensionNode; +/** + * Returns true when the AST node is a type extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type extension node. + * @example + * ```ts + * import { parse, isTypeExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const schemaExtension = parse('extend schema { query: Query }'); + * + * isTypeExtensionNode(extension.definitions[0]); // => true + * isTypeExtensionNode(schemaExtension.definitions[0]); // => false + * ``` + */ +export declare function isTypeExtensionNode( + node: ASTNode, +): node is TypeExtensionNode; +/** + * Returns true when the AST node is a schema coordinate node. + * @param node - The AST node to test. + * @returns True when the AST node is a schema coordinate node. + * @example + * ```ts + * import { + * parse, + * parseSchemaCoordinate, + * isSchemaCoordinateNode, + * } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * const document = parse('{ hero }'); + * + * isSchemaCoordinateNode(coordinate); // => true + * isSchemaCoordinateNode(document); // => false + * ``` + */ +export declare function isSchemaCoordinateNode( + node: ASTNode, +): node is SchemaCoordinateNode; diff --git a/node_modules/graphql/language/predicates.js b/node_modules/graphql/language/predicates.js new file mode 100644 index 0000000000000000000000000000000000000000..adb1f1e06a2d5e590692716812bf124e53703967 --- /dev/null +++ b/node_modules/graphql/language/predicates.js @@ -0,0 +1,292 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.isConstValueNode = isConstValueNode; +exports.isDefinitionNode = isDefinitionNode; +exports.isExecutableDefinitionNode = isExecutableDefinitionNode; +exports.isSchemaCoordinateNode = isSchemaCoordinateNode; +exports.isSelectionNode = isSelectionNode; +exports.isTypeDefinitionNode = isTypeDefinitionNode; +exports.isTypeExtensionNode = isTypeExtensionNode; +exports.isTypeNode = isTypeNode; +exports.isTypeSystemDefinitionNode = isTypeSystemDefinitionNode; +exports.isTypeSystemExtensionNode = isTypeSystemExtensionNode; +exports.isValueNode = isValueNode; + +var _kinds = require('./kinds.js'); + +/** @category AST Predicates */ + +/** + * Returns true when the AST node is a definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a definition node. + * @example + * ```ts + * import { parse, isDefinitionNode } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * + * isDefinitionNode(document.definitions[0]); // => true + * isDefinitionNode(document); // => false + * ``` + */ +function isDefinitionNode(node) { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} +/** + * Returns true when the AST node is an executable definition node. + * @param node - The AST node to test. + * @returns True when the AST node is an executable definition node. + * @example + * ```ts + * import { parse, isExecutableDefinitionNode } from 'graphql/language'; + * + * const query = parse('{ hello }'); + * const schema = parse('type Query { hello: String }'); + * + * isExecutableDefinitionNode(query.definitions[0]); // => true + * isExecutableDefinitionNode(schema.definitions[0]); // => false + * ``` + */ + +function isExecutableDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.OPERATION_DEFINITION || + node.kind === _kinds.Kind.FRAGMENT_DEFINITION + ); +} +/** + * Returns true when the AST node is a selection node. + * @param node - The AST node to test. + * @returns True when the AST node is a selection node. + * @example + * ```ts + * import { Kind, isSelectionNode } from 'graphql/language'; + * + * const field = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'hello' } }; + * const document = { kind: Kind.DOCUMENT, definitions: [] }; + * + * isSelectionNode(field); // => true + * isSelectionNode(document); // => false + * ``` + */ + +function isSelectionNode(node) { + return ( + node.kind === _kinds.Kind.FIELD || + node.kind === _kinds.Kind.FRAGMENT_SPREAD || + node.kind === _kinds.Kind.INLINE_FRAGMENT + ); +} +/** + * Returns true when the AST node is a value node. + * @param node - The AST node to test. + * @returns True when the AST node is a value node. + * @example + * ```ts + * import { parseType, parseValue, isValueNode } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * const type = parseType('[String!]'); + * + * isValueNode(value); // => true + * isValueNode(type); // => false + * ``` + */ + +function isValueNode(node) { + return ( + node.kind === _kinds.Kind.VARIABLE || + node.kind === _kinds.Kind.INT || + node.kind === _kinds.Kind.FLOAT || + node.kind === _kinds.Kind.STRING || + node.kind === _kinds.Kind.BOOLEAN || + node.kind === _kinds.Kind.NULL || + node.kind === _kinds.Kind.ENUM || + node.kind === _kinds.Kind.LIST || + node.kind === _kinds.Kind.OBJECT + ); +} +/** + * Returns true when the AST node is a constant value node. + * @param node - The AST node to test. + * @returns True when the AST node is a constant value node. + * @example + * ```ts + * import { parseConstValue, parseValue, isConstValueNode } from 'graphql/language'; + * + * const value = parseConstValue('[42]'); + * const variable = parseValue('$id'); + * + * isConstValueNode(value); // => true + * isConstValueNode(variable); // => false + * ``` + */ + +function isConstValueNode(node) { + return ( + isValueNode(node) && + (node.kind === _kinds.Kind.LIST + ? node.values.some(isConstValueNode) + : node.kind === _kinds.Kind.OBJECT + ? node.fields.some((field) => isConstValueNode(field.value)) + : node.kind !== _kinds.Kind.VARIABLE) + ); +} +/** + * Returns true when the AST node is a type node. + * @param node - The AST node to test. + * @returns True when the AST node is a type node. + * @example + * ```ts + * import { parseType, parseValue, isTypeNode } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * const value = parseValue('[42]'); + * + * isTypeNode(type); // => true + * isTypeNode(value); // => false + * ``` + */ + +function isTypeNode(node) { + return ( + node.kind === _kinds.Kind.NAMED_TYPE || + node.kind === _kinds.Kind.LIST_TYPE || + node.kind === _kinds.Kind.NON_NULL_TYPE + ); +} +/** + * Returns true when the AST node is a type system definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system definition node. + * @example + * ```ts + * import { parse, isTypeSystemDefinitionNode } from 'graphql/language'; + * + * const schema = parse('type Query { hello: String }'); + * const query = parse('{ hello }'); + * + * isTypeSystemDefinitionNode(schema.definitions[0]); // => true + * isTypeSystemDefinitionNode(query.definitions[0]); // => false + * ``` + */ + +function isTypeSystemDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === _kinds.Kind.DIRECTIVE_DEFINITION + ); +} +/** + * Returns true when the AST node is a type definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type definition node. + * @example + * ```ts + * import { parse, isTypeDefinitionNode } from 'graphql/language'; + * + * const typeDefinition = parse('type Query { hello: String }'); + * const directiveDefinition = parse('directive @cache on FIELD'); + * + * isTypeDefinitionNode(typeDefinition.definitions[0]); // => true + * isTypeDefinitionNode(directiveDefinition.definitions[0]); // => false + * ``` + */ + +function isTypeDefinitionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_DEFINITION || + node.kind === _kinds.Kind.OBJECT_TYPE_DEFINITION || + node.kind === _kinds.Kind.INTERFACE_TYPE_DEFINITION || + node.kind === _kinds.Kind.UNION_TYPE_DEFINITION || + node.kind === _kinds.Kind.ENUM_TYPE_DEFINITION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} +/** + * Returns true when the AST node is a type system extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system extension node. + * @example + * ```ts + * import { parse, isTypeSystemExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const definition = parse('type Query { hello: String }'); + * + * isTypeSystemExtensionNode(extension.definitions[0]); // => true + * isTypeSystemExtensionNode(definition.definitions[0]); // => false + * ``` + */ + +function isTypeSystemExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCHEMA_EXTENSION || + node.kind === _kinds.Kind.DIRECTIVE_EXTENSION || + isTypeExtensionNode(node) + ); +} +/** + * Returns true when the AST node is a type extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type extension node. + * @example + * ```ts + * import { parse, isTypeExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const schemaExtension = parse('extend schema { query: Query }'); + * + * isTypeExtensionNode(extension.definitions[0]); // => true + * isTypeExtensionNode(schemaExtension.definitions[0]); // => false + * ``` + */ + +function isTypeExtensionNode(node) { + return ( + node.kind === _kinds.Kind.SCALAR_TYPE_EXTENSION || + node.kind === _kinds.Kind.OBJECT_TYPE_EXTENSION || + node.kind === _kinds.Kind.INTERFACE_TYPE_EXTENSION || + node.kind === _kinds.Kind.UNION_TYPE_EXTENSION || + node.kind === _kinds.Kind.ENUM_TYPE_EXTENSION || + node.kind === _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} +/** + * Returns true when the AST node is a schema coordinate node. + * @param node - The AST node to test. + * @returns True when the AST node is a schema coordinate node. + * @example + * ```ts + * import { + * parse, + * parseSchemaCoordinate, + * isSchemaCoordinateNode, + * } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * const document = parse('{ hero }'); + * + * isSchemaCoordinateNode(coordinate); // => true + * isSchemaCoordinateNode(document); // => false + * ``` + */ + +function isSchemaCoordinateNode(node) { + return ( + node.kind === _kinds.Kind.TYPE_COORDINATE || + node.kind === _kinds.Kind.MEMBER_COORDINATE || + node.kind === _kinds.Kind.ARGUMENT_COORDINATE || + node.kind === _kinds.Kind.DIRECTIVE_COORDINATE || + node.kind === _kinds.Kind.DIRECTIVE_ARGUMENT_COORDINATE + ); +} diff --git a/node_modules/graphql/language/predicates.mjs b/node_modules/graphql/language/predicates.mjs new file mode 100644 index 0000000000000000000000000000000000000000..811b16ff9db34aae2792c58ff28bc2938ab1c0f5 --- /dev/null +++ b/node_modules/graphql/language/predicates.mjs @@ -0,0 +1,274 @@ +/** @category AST Predicates */ +import { Kind } from './kinds.mjs'; +/** + * Returns true when the AST node is a definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a definition node. + * @example + * ```ts + * import { parse, isDefinitionNode } from 'graphql/language'; + * + * const document = parse('{ hello }'); + * + * isDefinitionNode(document.definitions[0]); // => true + * isDefinitionNode(document); // => false + * ``` + */ + +export function isDefinitionNode(node) { + return ( + isExecutableDefinitionNode(node) || + isTypeSystemDefinitionNode(node) || + isTypeSystemExtensionNode(node) + ); +} +/** + * Returns true when the AST node is an executable definition node. + * @param node - The AST node to test. + * @returns True when the AST node is an executable definition node. + * @example + * ```ts + * import { parse, isExecutableDefinitionNode } from 'graphql/language'; + * + * const query = parse('{ hello }'); + * const schema = parse('type Query { hello: String }'); + * + * isExecutableDefinitionNode(query.definitions[0]); // => true + * isExecutableDefinitionNode(schema.definitions[0]); // => false + * ``` + */ + +export function isExecutableDefinitionNode(node) { + return ( + node.kind === Kind.OPERATION_DEFINITION || + node.kind === Kind.FRAGMENT_DEFINITION + ); +} +/** + * Returns true when the AST node is a selection node. + * @param node - The AST node to test. + * @returns True when the AST node is a selection node. + * @example + * ```ts + * import { Kind, isSelectionNode } from 'graphql/language'; + * + * const field = { kind: Kind.FIELD, name: { kind: Kind.NAME, value: 'hello' } }; + * const document = { kind: Kind.DOCUMENT, definitions: [] }; + * + * isSelectionNode(field); // => true + * isSelectionNode(document); // => false + * ``` + */ + +export function isSelectionNode(node) { + return ( + node.kind === Kind.FIELD || + node.kind === Kind.FRAGMENT_SPREAD || + node.kind === Kind.INLINE_FRAGMENT + ); +} +/** + * Returns true when the AST node is a value node. + * @param node - The AST node to test. + * @returns True when the AST node is a value node. + * @example + * ```ts + * import { parseType, parseValue, isValueNode } from 'graphql/language'; + * + * const value = parseValue('[42]'); + * const type = parseType('[String!]'); + * + * isValueNode(value); // => true + * isValueNode(type); // => false + * ``` + */ + +export function isValueNode(node) { + return ( + node.kind === Kind.VARIABLE || + node.kind === Kind.INT || + node.kind === Kind.FLOAT || + node.kind === Kind.STRING || + node.kind === Kind.BOOLEAN || + node.kind === Kind.NULL || + node.kind === Kind.ENUM || + node.kind === Kind.LIST || + node.kind === Kind.OBJECT + ); +} +/** + * Returns true when the AST node is a constant value node. + * @param node - The AST node to test. + * @returns True when the AST node is a constant value node. + * @example + * ```ts + * import { parseConstValue, parseValue, isConstValueNode } from 'graphql/language'; + * + * const value = parseConstValue('[42]'); + * const variable = parseValue('$id'); + * + * isConstValueNode(value); // => true + * isConstValueNode(variable); // => false + * ``` + */ + +export function isConstValueNode(node) { + return ( + isValueNode(node) && + (node.kind === Kind.LIST + ? node.values.some(isConstValueNode) + : node.kind === Kind.OBJECT + ? node.fields.some((field) => isConstValueNode(field.value)) + : node.kind !== Kind.VARIABLE) + ); +} +/** + * Returns true when the AST node is a type node. + * @param node - The AST node to test. + * @returns True when the AST node is a type node. + * @example + * ```ts + * import { parseType, parseValue, isTypeNode } from 'graphql/language'; + * + * const type = parseType('[String!]'); + * const value = parseValue('[42]'); + * + * isTypeNode(type); // => true + * isTypeNode(value); // => false + * ``` + */ + +export function isTypeNode(node) { + return ( + node.kind === Kind.NAMED_TYPE || + node.kind === Kind.LIST_TYPE || + node.kind === Kind.NON_NULL_TYPE + ); +} +/** + * Returns true when the AST node is a type system definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system definition node. + * @example + * ```ts + * import { parse, isTypeSystemDefinitionNode } from 'graphql/language'; + * + * const schema = parse('type Query { hello: String }'); + * const query = parse('{ hello }'); + * + * isTypeSystemDefinitionNode(schema.definitions[0]); // => true + * isTypeSystemDefinitionNode(query.definitions[0]); // => false + * ``` + */ + +export function isTypeSystemDefinitionNode(node) { + return ( + node.kind === Kind.SCHEMA_DEFINITION || + isTypeDefinitionNode(node) || + node.kind === Kind.DIRECTIVE_DEFINITION + ); +} +/** + * Returns true when the AST node is a type definition node. + * @param node - The AST node to test. + * @returns True when the AST node is a type definition node. + * @example + * ```ts + * import { parse, isTypeDefinitionNode } from 'graphql/language'; + * + * const typeDefinition = parse('type Query { hello: String }'); + * const directiveDefinition = parse('directive @cache on FIELD'); + * + * isTypeDefinitionNode(typeDefinition.definitions[0]); // => true + * isTypeDefinitionNode(directiveDefinition.definitions[0]); // => false + * ``` + */ + +export function isTypeDefinitionNode(node) { + return ( + node.kind === Kind.SCALAR_TYPE_DEFINITION || + node.kind === Kind.OBJECT_TYPE_DEFINITION || + node.kind === Kind.INTERFACE_TYPE_DEFINITION || + node.kind === Kind.UNION_TYPE_DEFINITION || + node.kind === Kind.ENUM_TYPE_DEFINITION || + node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ); +} +/** + * Returns true when the AST node is a type system extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type system extension node. + * @example + * ```ts + * import { parse, isTypeSystemExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const definition = parse('type Query { hello: String }'); + * + * isTypeSystemExtensionNode(extension.definitions[0]); // => true + * isTypeSystemExtensionNode(definition.definitions[0]); // => false + * ``` + */ + +export function isTypeSystemExtensionNode(node) { + return ( + node.kind === Kind.SCHEMA_EXTENSION || + node.kind === Kind.DIRECTIVE_EXTENSION || + isTypeExtensionNode(node) + ); +} +/** + * Returns true when the AST node is a type extension node. + * @param node - The AST node to test. + * @returns True when the AST node is a type extension node. + * @example + * ```ts + * import { parse, isTypeExtensionNode } from 'graphql/language'; + * + * const extension = parse('extend type Query { hello: String }'); + * const schemaExtension = parse('extend schema { query: Query }'); + * + * isTypeExtensionNode(extension.definitions[0]); // => true + * isTypeExtensionNode(schemaExtension.definitions[0]); // => false + * ``` + */ + +export function isTypeExtensionNode(node) { + return ( + node.kind === Kind.SCALAR_TYPE_EXTENSION || + node.kind === Kind.OBJECT_TYPE_EXTENSION || + node.kind === Kind.INTERFACE_TYPE_EXTENSION || + node.kind === Kind.UNION_TYPE_EXTENSION || + node.kind === Kind.ENUM_TYPE_EXTENSION || + node.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION + ); +} +/** + * Returns true when the AST node is a schema coordinate node. + * @param node - The AST node to test. + * @returns True when the AST node is a schema coordinate node. + * @example + * ```ts + * import { + * parse, + * parseSchemaCoordinate, + * isSchemaCoordinateNode, + * } from 'graphql/language'; + * + * const coordinate = parseSchemaCoordinate('Query.hero'); + * const document = parse('{ hero }'); + * + * isSchemaCoordinateNode(coordinate); // => true + * isSchemaCoordinateNode(document); // => false + * ``` + */ + +export function isSchemaCoordinateNode(node) { + return ( + node.kind === Kind.TYPE_COORDINATE || + node.kind === Kind.MEMBER_COORDINATE || + node.kind === Kind.ARGUMENT_COORDINATE || + node.kind === Kind.DIRECTIVE_COORDINATE || + node.kind === Kind.DIRECTIVE_ARGUMENT_COORDINATE + ); +} diff --git a/node_modules/graphql/language/printLocation.d.ts b/node_modules/graphql/language/printLocation.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f490d9875d7dd0b0ea5204f2b8eb73274f5262fe --- /dev/null +++ b/node_modules/graphql/language/printLocation.d.ts @@ -0,0 +1,42 @@ +/** @category Source */ +import type { Location } from './ast'; +import type { SourceLocation } from './location'; +import type { Source } from './source'; +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param location - The AST location to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { parse, printLocation } from 'graphql/language'; + * + * const document = parse('type Query { hello: String }'); + * const location = document.definitions[0].loc; + * + * if (location) { + * const printed = printLocation(location); + * + * printed; // => 'GraphQL request:1:1\n1 | type Query { hello: String }\n | ^' + * } + * ``` + */ +export declare function printLocation(location: Location): string; +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param source - The source document that contains the location. + * @param sourceLocation - The 1-indexed line and column to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { Source, printSourceLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const printed = printSourceLocation(source, { line: 1, column: 14 }); + * + * printed; // => 'GraphQL request:1:14\n1 | type Query { hello: String }\n | ^' + * ``` + */ +export declare function printSourceLocation( + source: Source, + sourceLocation: SourceLocation, +): string; diff --git a/node_modules/graphql/language/printLocation.js b/node_modules/graphql/language/printLocation.js new file mode 100644 index 0000000000000000000000000000000000000000..bfb05619ce05a004a6860332b8477e27be52bded --- /dev/null +++ b/node_modules/graphql/language/printLocation.js @@ -0,0 +1,103 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.printLocation = printLocation; +exports.printSourceLocation = printSourceLocation; + +var _location = require('./location.js'); + +/** @category Source */ + +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param location - The AST location to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { parse, printLocation } from 'graphql/language'; + * + * const document = parse('type Query { hello: String }'); + * const location = document.definitions[0].loc; + * + * if (location) { + * const printed = printLocation(location); + * + * printed; // => 'GraphQL request:1:1\n1 | type Query { hello: String }\n | ^' + * } + * ``` + */ +function printLocation(location) { + return printSourceLocation( + location.source, + (0, _location.getLocation)(location.source, location.start), + ); +} +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param source - The source document that contains the location. + * @param sourceLocation - The 1-indexed line and column to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { Source, printSourceLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const printed = printSourceLocation(source, { line: 1, column: 14 }); + * + * printed; // => 'GraphQL request:1:14\n1 | type Query { hello: String }\n | ^' + * ``` + */ + +function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = ''.padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return ( + locationStr + + printPrefixedLines([ + [`${lineNum} |`, subLines[0]], + ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]), + ['|', '^'.padStart(subLineColumnNum)], + ['|', subLines[subLineIndex + 1]], + ]) + ); + } + + return ( + locationStr + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], + [`${lineNum} |`, locationLine], + ['|', '^'.padStart(columnNum)], + [`${lineNum + 1} |`, lines[lineIndex + 1]], + ]) + ); +} + +function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines + .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')) + .join('\n'); +} diff --git a/node_modules/graphql/language/printLocation.mjs b/node_modules/graphql/language/printLocation.mjs new file mode 100644 index 0000000000000000000000000000000000000000..423c92c4faf6762e7a2430c3a9acd91fe5050df9 --- /dev/null +++ b/node_modules/graphql/language/printLocation.mjs @@ -0,0 +1,94 @@ +/** @category Source */ +import { getLocation } from './location.mjs'; + +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param location - The AST location to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { parse, printLocation } from 'graphql/language'; + * + * const document = parse('type Query { hello: String }'); + * const location = document.definitions[0].loc; + * + * if (location) { + * const printed = printLocation(location); + * + * printed; // => 'GraphQL request:1:1\n1 | type Query { hello: String }\n | ^' + * } + * ``` + */ +export function printLocation(location) { + return printSourceLocation( + location.source, + getLocation(location.source, location.start), + ); +} +/** + * Render a helpful description of the location in the GraphQL Source document. + * @param source - The source document that contains the location. + * @param sourceLocation - The 1-indexed line and column to print. + * @returns A formatted source excerpt with line and column information. + * @example + * ```ts + * import { Source, printSourceLocation } from 'graphql/language'; + * + * const source = new Source('type Query { hello: String }'); + * const printed = printSourceLocation(source, { line: 1, column: 14 }); + * + * printed; // => 'GraphQL request:1:14\n1 | type Query { hello: String }\n | ^' + * ``` + */ + +export function printSourceLocation(source, sourceLocation) { + const firstLineColumnOffset = source.locationOffset.column - 1; + const body = ''.padStart(firstLineColumnOffset) + source.body; + const lineIndex = sourceLocation.line - 1; + const lineOffset = source.locationOffset.line - 1; + const lineNum = sourceLocation.line + lineOffset; + const columnOffset = sourceLocation.line === 1 ? firstLineColumnOffset : 0; + const columnNum = sourceLocation.column + columnOffset; + const locationStr = `${source.name}:${lineNum}:${columnNum}\n`; + const lines = body.split(/\r\n|[\n\r]/g); + const locationLine = lines[lineIndex]; // Special case for minified documents + + if (locationLine.length > 120) { + const subLineIndex = Math.floor(columnNum / 80); + const subLineColumnNum = columnNum % 80; + const subLines = []; + + for (let i = 0; i < locationLine.length; i += 80) { + subLines.push(locationLine.slice(i, i + 80)); + } + + return ( + locationStr + + printPrefixedLines([ + [`${lineNum} |`, subLines[0]], + ...subLines.slice(1, subLineIndex + 1).map((subLine) => ['|', subLine]), + ['|', '^'.padStart(subLineColumnNum)], + ['|', subLines[subLineIndex + 1]], + ]) + ); + } + + return ( + locationStr + + printPrefixedLines([ + // Lines specified like this: ["prefix", "string"], + [`${lineNum - 1} |`, lines[lineIndex - 1]], + [`${lineNum} |`, locationLine], + ['|', '^'.padStart(columnNum)], + [`${lineNum + 1} |`, lines[lineIndex + 1]], + ]) + ); +} + +function printPrefixedLines(lines) { + const existingLines = lines.filter(([_, line]) => line !== undefined); + const padLen = Math.max(...existingLines.map(([prefix]) => prefix.length)); + return existingLines + .map(([prefix, line]) => prefix.padStart(padLen) + (line ? ' ' + line : '')) + .join('\n'); +} diff --git a/node_modules/graphql/language/printString.d.ts b/node_modules/graphql/language/printString.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ac7833c0efd4c14bf7b8a541b5baf304c3b13b42 --- /dev/null +++ b/node_modules/graphql/language/printString.d.ts @@ -0,0 +1,7 @@ +/** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + * + * @internal + */ +export declare function printString(str: string): string; diff --git a/node_modules/graphql/language/printString.js b/node_modules/graphql/language/printString.js new file mode 100644 index 0000000000000000000000000000000000000000..d5632dbcf53d2c564a25594bb5c7ac426684c293 --- /dev/null +++ b/node_modules/graphql/language/printString.js @@ -0,0 +1,187 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.printString = printString; + +/** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + * + * @internal + */ +function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; +} +/** @internal */ +// eslint-disable-next-line no-control-regex + +const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + +function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; +} // prettier-ignore + +const escapeSequences = [ + '\\u0000', + '\\u0001', + '\\u0002', + '\\u0003', + '\\u0004', + '\\u0005', + '\\u0006', + '\\u0007', + '\\b', + '\\t', + '\\n', + '\\u000B', + '\\f', + '\\r', + '\\u000E', + '\\u000F', + '\\u0010', + '\\u0011', + '\\u0012', + '\\u0013', + '\\u0014', + '\\u0015', + '\\u0016', + '\\u0017', + '\\u0018', + '\\u0019', + '\\u001A', + '\\u001B', + '\\u001C', + '\\u001D', + '\\u001E', + '\\u001F', + '', + '', + '\\"', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 2F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 3F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 4F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\\\', + '', + '', + '', // 5F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 6F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\u007F', + '\\u0080', + '\\u0081', + '\\u0082', + '\\u0083', + '\\u0084', + '\\u0085', + '\\u0086', + '\\u0087', + '\\u0088', + '\\u0089', + '\\u008A', + '\\u008B', + '\\u008C', + '\\u008D', + '\\u008E', + '\\u008F', + '\\u0090', + '\\u0091', + '\\u0092', + '\\u0093', + '\\u0094', + '\\u0095', + '\\u0096', + '\\u0097', + '\\u0098', + '\\u0099', + '\\u009A', + '\\u009B', + '\\u009C', + '\\u009D', + '\\u009E', + '\\u009F', +]; diff --git a/node_modules/graphql/language/printString.mjs b/node_modules/graphql/language/printString.mjs new file mode 100644 index 0000000000000000000000000000000000000000..eec92c9476b60e8c4dea533e742e88eedfddfb1d --- /dev/null +++ b/node_modules/graphql/language/printString.mjs @@ -0,0 +1,180 @@ +/** + * Prints a string as a GraphQL StringValue literal. Replaces control characters + * and excluded characters (" U+0022 and \\ U+005C) with escape sequences. + * + * @internal + */ +export function printString(str) { + return `"${str.replace(escapedRegExp, escapedReplacer)}"`; +} +/** @internal */ +// eslint-disable-next-line no-control-regex + +const escapedRegExp = /[\x00-\x1f\x22\x5c\x7f-\x9f]/g; + +function escapedReplacer(str) { + return escapeSequences[str.charCodeAt(0)]; +} // prettier-ignore + +const escapeSequences = [ + '\\u0000', + '\\u0001', + '\\u0002', + '\\u0003', + '\\u0004', + '\\u0005', + '\\u0006', + '\\u0007', + '\\b', + '\\t', + '\\n', + '\\u000B', + '\\f', + '\\r', + '\\u000E', + '\\u000F', + '\\u0010', + '\\u0011', + '\\u0012', + '\\u0013', + '\\u0014', + '\\u0015', + '\\u0016', + '\\u0017', + '\\u0018', + '\\u0019', + '\\u001A', + '\\u001B', + '\\u001C', + '\\u001D', + '\\u001E', + '\\u001F', + '', + '', + '\\"', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 2F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 3F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 4F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\\\', + '', + '', + '', // 5F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', // 6F + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '', + '\\u007F', + '\\u0080', + '\\u0081', + '\\u0082', + '\\u0083', + '\\u0084', + '\\u0085', + '\\u0086', + '\\u0087', + '\\u0088', + '\\u0089', + '\\u008A', + '\\u008B', + '\\u008C', + '\\u008D', + '\\u008E', + '\\u008F', + '\\u0090', + '\\u0091', + '\\u0092', + '\\u0093', + '\\u0094', + '\\u0095', + '\\u0096', + '\\u0097', + '\\u0098', + '\\u0099', + '\\u009A', + '\\u009B', + '\\u009C', + '\\u009D', + '\\u009E', + '\\u009F', +]; diff --git a/node_modules/graphql/language/printer.d.ts b/node_modules/graphql/language/printer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2957940e832635ee6e2b89935e72ba856bc35d92 --- /dev/null +++ b/node_modules/graphql/language/printer.d.ts @@ -0,0 +1,18 @@ +/** @category Printing */ +import type { ASTNode } from './ast'; +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + * @param ast - The GraphQL AST node to print. + * @returns A stable string representation of the AST. + * @example + * ```ts + * import { parse, print } from 'graphql'; + * + * const ast = parse('{ hero { name } }'); + * const text = print(ast); + * + * text; // => '{\n hero {\n name\n }\n}' + * ``` + */ +export declare function print(ast: ASTNode): string; diff --git a/node_modules/graphql/language/printer.js b/node_modules/graphql/language/printer.js new file mode 100644 index 0000000000000000000000000000000000000000..310e7343601e287d34d03225f1f3bad35786b860 --- /dev/null +++ b/node_modules/graphql/language/printer.js @@ -0,0 +1,411 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.print = print; + +var _blockString = require('./blockString.js'); + +var _printString = require('./printString.js'); + +var _visitor = require('./visitor.js'); + +/** @category Printing */ + +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + * @param ast - The GraphQL AST node to print. + * @returns A stable string representation of the AST. + * @example + * ```ts + * import { parse, print } from 'graphql'; + * + * const ast = parse('{ hero { name } }'); + * const text = print(ast); + * + * text; // => '{\n hero {\n name\n }\n}' + * ``` + */ +function print(ast) { + return (0, _visitor.visit)(ast, printDocASTReducer); +} + +const MAX_LINE_LENGTH = 80; +const printDocASTReducer = { + Name: { + leave: (node) => node.value, + }, + Variable: { + leave: (node) => '$' + node.name, + }, + // Document + Document: { + leave: (node) => join(node.definitions, '\n\n'), + }, + OperationDefinition: { + leave(node) { + const varDefs = hasMultilineItems(node.variableDefinitions) + ? wrap('(\n', join(node.variableDefinitions, '\n'), '\n)') + : wrap('(', join(node.variableDefinitions, ', '), ')'); + const prefix = + wrap('', node.description, '\n') + + join( + [ + node.operation, + join([node.name, varDefs]), + join(node.directives, ' '), + ], + ' ', + ); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; + }, + }, + VariableDefinition: { + leave: ({ variable, type, defaultValue, directives, description }) => + wrap('', description, '\n') + + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + }, + SelectionSet: { + leave: ({ selections }) => block(selections), + }, + Field: { + leave({ alias, name, arguments: args, directives, selectionSet }) { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + }, + Argument: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Fragments + FragmentSpread: { + leave: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + }, + InlineFragment: { + leave: ({ typeCondition, directives, selectionSet }) => + join( + [ + '...', + wrap('on ', typeCondition), + join(directives, ' '), + selectionSet, + ], + ' ', + ), + }, + FragmentDefinition: { + leave: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + description, + }) => + wrap('', description, '\n') + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + }, + // Value + IntValue: { + leave: ({ value }) => value, + }, + FloatValue: { + leave: ({ value }) => value, + }, + StringValue: { + leave: ({ value, block: isBlockString }) => + isBlockString + ? (0, _blockString.printBlockString)(value) + : (0, _printString.printString)(value), + }, + BooleanValue: { + leave: ({ value }) => (value ? 'true' : 'false'), + }, + NullValue: { + leave: () => 'null', + }, + EnumValue: { + leave: ({ value }) => value, + }, + ListValue: { + leave: ({ values }) => '[' + join(values, ', ') + ']', + }, + ObjectValue: { + leave: ({ fields }) => '{' + join(fields, ', ') + '}', + }, + ObjectField: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Directive + Directive: { + leave: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + }, + // Type + NamedType: { + leave: ({ name }) => name, + }, + ListType: { + leave: ({ type }) => '[' + type + ']', + }, + NonNullType: { + leave: ({ type }) => type + '!', + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ description, directives, operationTypes }) => + wrap('', description, '\n') + + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + }, + OperationTypeDefinition: { + leave: ({ operation, type }) => operation + ': ' + type, + }, + ScalarTypeDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + + join(['scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + FieldDefinition: { + leave: ({ description, name, arguments: args, type, directives }) => + wrap('', description, '\n') + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + }, + InputValueDefinition: { + leave: ({ description, name, type, defaultValue, directives }) => + wrap('', description, '\n') + + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + }, + InterfaceTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeDefinition: { + leave: ({ description, name, directives, types }) => + wrap('', description, '\n') + + join( + ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], + ' ', + ), + }, + EnumTypeDefinition: { + leave: ({ description, name, directives, values }) => + wrap('', description, '\n') + + join(['enum', name, join(directives, ' '), block(values)], ' '), + }, + EnumValueDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + join([name, join(directives, ' ')], ' '), + }, + InputObjectTypeDefinition: { + leave: ({ description, name, directives, fields }) => + wrap('', description, '\n') + + join(['input', name, join(directives, ' '), block(fields)], ' '), + }, + DirectiveDefinition: { + leave: ({ + description, + name, + arguments: args, + directives, + repeatable, + locations, + }) => + wrap('', description, '\n') + + 'directive @' + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + wrap(' ', join(directives, ' ')) + + (repeatable ? ' repeatable' : '') + + ' on ' + + join(locations, ' | '), + }, + SchemaExtension: { + leave: ({ directives, operationTypes }) => + join( + ['extend schema', join(directives, ' '), block(operationTypes)], + ' ', + ), + }, + ScalarTypeExtension: { + leave: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + InterfaceTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeExtension: { + leave: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + wrap('= ', join(types, ' | ')), + ], + ' ', + ), + }, + EnumTypeExtension: { + leave: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + }, + InputObjectTypeExtension: { + leave: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), + }, + DirectiveExtension: { + leave: ({ name, directives }) => + join(['extend directive @' + name, join(directives, ' ')], ' '), + }, + // Schema Coordinates + TypeCoordinate: { + leave: ({ name }) => name, + }, + MemberCoordinate: { + leave: ({ name, memberName }) => join([name, wrap('.', memberName)]), + }, + ArgumentCoordinate: { + leave: ({ name, fieldName, argumentName }) => + join([name, wrap('.', fieldName), wrap('(', argumentName, ':)')]), + }, + DirectiveCoordinate: { + leave: ({ name }) => join(['@', name]), + }, + DirectiveArgumentCoordinate: { + leave: ({ name, argumentName }) => + join(['@', name, wrap('(', argumentName, ':)')]), + }, +}; +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + * + * @internal + */ + +function join(maybeArray, separator = '') { + var _maybeArray$filter$jo; + + return (_maybeArray$filter$jo = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.filter((x) => x).join(separator)) !== null && + _maybeArray$filter$jo !== void 0 + ? _maybeArray$filter$jo + : ''; +} +/** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + * + * @internal + */ + +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + * + * @internal + */ + +function wrap(start, maybeString, end = '') { + return maybeString != null && maybeString !== '' + ? start + maybeString + end + : ''; +} + +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} + +function hasMultilineItems(maybeArray) { + var _maybeArray$some; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + return (_maybeArray$some = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.some((str) => str.includes('\n'))) !== null && + _maybeArray$some !== void 0 + ? _maybeArray$some + : false; +} diff --git a/node_modules/graphql/language/printer.mjs b/node_modules/graphql/language/printer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1b246547a5945af63f0f6e046a36211a382436b1 --- /dev/null +++ b/node_modules/graphql/language/printer.mjs @@ -0,0 +1,398 @@ +/** @category Printing */ +import { printBlockString } from './blockString.mjs'; +import { printString } from './printString.mjs'; +import { visit } from './visitor.mjs'; +/** + * Converts an AST into a string, using one set of reasonable + * formatting rules. + * @param ast - The GraphQL AST node to print. + * @returns A stable string representation of the AST. + * @example + * ```ts + * import { parse, print } from 'graphql'; + * + * const ast = parse('{ hero { name } }'); + * const text = print(ast); + * + * text; // => '{\n hero {\n name\n }\n}' + * ``` + */ + +export function print(ast) { + return visit(ast, printDocASTReducer); +} +const MAX_LINE_LENGTH = 80; +const printDocASTReducer = { + Name: { + leave: (node) => node.value, + }, + Variable: { + leave: (node) => '$' + node.name, + }, + // Document + Document: { + leave: (node) => join(node.definitions, '\n\n'), + }, + OperationDefinition: { + leave(node) { + const varDefs = hasMultilineItems(node.variableDefinitions) + ? wrap('(\n', join(node.variableDefinitions, '\n'), '\n)') + : wrap('(', join(node.variableDefinitions, ', '), ')'); + const prefix = + wrap('', node.description, '\n') + + join( + [ + node.operation, + join([node.name, varDefs]), + join(node.directives, ' '), + ], + ' ', + ); // Anonymous queries with no directives or variable definitions can use + // the query short form. + + return (prefix === 'query' ? '' : prefix + ' ') + node.selectionSet; + }, + }, + VariableDefinition: { + leave: ({ variable, type, defaultValue, directives, description }) => + wrap('', description, '\n') + + variable + + ': ' + + type + + wrap(' = ', defaultValue) + + wrap(' ', join(directives, ' ')), + }, + SelectionSet: { + leave: ({ selections }) => block(selections), + }, + Field: { + leave({ alias, name, arguments: args, directives, selectionSet }) { + const prefix = wrap('', alias, ': ') + name; + let argsLine = prefix + wrap('(', join(args, ', '), ')'); + + if (argsLine.length > MAX_LINE_LENGTH) { + argsLine = prefix + wrap('(\n', indent(join(args, '\n')), '\n)'); + } + + return join([argsLine, join(directives, ' '), selectionSet], ' '); + }, + }, + Argument: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Fragments + FragmentSpread: { + leave: ({ name, directives }) => + '...' + name + wrap(' ', join(directives, ' ')), + }, + InlineFragment: { + leave: ({ typeCondition, directives, selectionSet }) => + join( + [ + '...', + wrap('on ', typeCondition), + join(directives, ' '), + selectionSet, + ], + ' ', + ), + }, + FragmentDefinition: { + leave: ({ + name, + typeCondition, + variableDefinitions, + directives, + selectionSet, + description, + }) => + wrap('', description, '\n') + // Note: fragment variable definitions are experimental and may be changed + // or removed in the future. + `fragment ${name}${wrap('(', join(variableDefinitions, ', '), ')')} ` + + `on ${typeCondition} ${wrap('', join(directives, ' '), ' ')}` + + selectionSet, + }, + // Value + IntValue: { + leave: ({ value }) => value, + }, + FloatValue: { + leave: ({ value }) => value, + }, + StringValue: { + leave: ({ value, block: isBlockString }) => + isBlockString ? printBlockString(value) : printString(value), + }, + BooleanValue: { + leave: ({ value }) => (value ? 'true' : 'false'), + }, + NullValue: { + leave: () => 'null', + }, + EnumValue: { + leave: ({ value }) => value, + }, + ListValue: { + leave: ({ values }) => '[' + join(values, ', ') + ']', + }, + ObjectValue: { + leave: ({ fields }) => '{' + join(fields, ', ') + '}', + }, + ObjectField: { + leave: ({ name, value }) => name + ': ' + value, + }, + // Directive + Directive: { + leave: ({ name, arguments: args }) => + '@' + name + wrap('(', join(args, ', '), ')'), + }, + // Type + NamedType: { + leave: ({ name }) => name, + }, + ListType: { + leave: ({ type }) => '[' + type + ']', + }, + NonNullType: { + leave: ({ type }) => type + '!', + }, + // Type System Definitions + SchemaDefinition: { + leave: ({ description, directives, operationTypes }) => + wrap('', description, '\n') + + join(['schema', join(directives, ' '), block(operationTypes)], ' '), + }, + OperationTypeDefinition: { + leave: ({ operation, type }) => operation + ': ' + type, + }, + ScalarTypeDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + + join(['scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + FieldDefinition: { + leave: ({ description, name, arguments: args, type, directives }) => + wrap('', description, '\n') + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + ': ' + + type + + wrap(' ', join(directives, ' ')), + }, + InputValueDefinition: { + leave: ({ description, name, type, defaultValue, directives }) => + wrap('', description, '\n') + + join( + [name + ': ' + type, wrap('= ', defaultValue), join(directives, ' ')], + ' ', + ), + }, + InterfaceTypeDefinition: { + leave: ({ description, name, interfaces, directives, fields }) => + wrap('', description, '\n') + + join( + [ + 'interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeDefinition: { + leave: ({ description, name, directives, types }) => + wrap('', description, '\n') + + join( + ['union', name, join(directives, ' '), wrap('= ', join(types, ' | '))], + ' ', + ), + }, + EnumTypeDefinition: { + leave: ({ description, name, directives, values }) => + wrap('', description, '\n') + + join(['enum', name, join(directives, ' '), block(values)], ' '), + }, + EnumValueDefinition: { + leave: ({ description, name, directives }) => + wrap('', description, '\n') + join([name, join(directives, ' ')], ' '), + }, + InputObjectTypeDefinition: { + leave: ({ description, name, directives, fields }) => + wrap('', description, '\n') + + join(['input', name, join(directives, ' '), block(fields)], ' '), + }, + DirectiveDefinition: { + leave: ({ + description, + name, + arguments: args, + directives, + repeatable, + locations, + }) => + wrap('', description, '\n') + + 'directive @' + + name + + (hasMultilineItems(args) + ? wrap('(\n', indent(join(args, '\n')), '\n)') + : wrap('(', join(args, ', '), ')')) + + wrap(' ', join(directives, ' ')) + + (repeatable ? ' repeatable' : '') + + ' on ' + + join(locations, ' | '), + }, + SchemaExtension: { + leave: ({ directives, operationTypes }) => + join( + ['extend schema', join(directives, ' '), block(operationTypes)], + ' ', + ), + }, + ScalarTypeExtension: { + leave: ({ name, directives }) => + join(['extend scalar', name, join(directives, ' ')], ' '), + }, + ObjectTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend type', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + InterfaceTypeExtension: { + leave: ({ name, interfaces, directives, fields }) => + join( + [ + 'extend interface', + name, + wrap('implements ', join(interfaces, ' & ')), + join(directives, ' '), + block(fields), + ], + ' ', + ), + }, + UnionTypeExtension: { + leave: ({ name, directives, types }) => + join( + [ + 'extend union', + name, + join(directives, ' '), + wrap('= ', join(types, ' | ')), + ], + ' ', + ), + }, + EnumTypeExtension: { + leave: ({ name, directives, values }) => + join(['extend enum', name, join(directives, ' '), block(values)], ' '), + }, + InputObjectTypeExtension: { + leave: ({ name, directives, fields }) => + join(['extend input', name, join(directives, ' '), block(fields)], ' '), + }, + DirectiveExtension: { + leave: ({ name, directives }) => + join(['extend directive @' + name, join(directives, ' ')], ' '), + }, + // Schema Coordinates + TypeCoordinate: { + leave: ({ name }) => name, + }, + MemberCoordinate: { + leave: ({ name, memberName }) => join([name, wrap('.', memberName)]), + }, + ArgumentCoordinate: { + leave: ({ name, fieldName, argumentName }) => + join([name, wrap('.', fieldName), wrap('(', argumentName, ':)')]), + }, + DirectiveCoordinate: { + leave: ({ name }) => join(['@', name]), + }, + DirectiveArgumentCoordinate: { + leave: ({ name, argumentName }) => + join(['@', name, wrap('(', argumentName, ':)')]), + }, +}; +/** + * Given maybeArray, print an empty string if it is null or empty, otherwise + * print all items together separated by separator if provided + * + * @internal + */ + +function join(maybeArray, separator = '') { + var _maybeArray$filter$jo; + + return (_maybeArray$filter$jo = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.filter((x) => x).join(separator)) !== null && + _maybeArray$filter$jo !== void 0 + ? _maybeArray$filter$jo + : ''; +} +/** + * Given array, print each item on its own line, wrapped in an indented `{ }` block. + * + * @internal + */ + +function block(array) { + return wrap('{\n', indent(join(array, '\n')), '\n}'); +} +/** + * If maybeString is not null or empty, then wrap with start and end, otherwise print an empty string. + * + * @internal + */ + +function wrap(start, maybeString, end = '') { + return maybeString != null && maybeString !== '' + ? start + maybeString + end + : ''; +} + +function indent(str) { + return wrap(' ', str.replace(/\n/g, '\n ')); +} + +function hasMultilineItems(maybeArray) { + var _maybeArray$some; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + return (_maybeArray$some = + maybeArray === null || maybeArray === void 0 + ? void 0 + : maybeArray.some((str) => str.includes('\n'))) !== null && + _maybeArray$some !== void 0 + ? _maybeArray$some + : false; +} diff --git a/node_modules/graphql/language/schemaCoordinateLexer.d.ts b/node_modules/graphql/language/schemaCoordinateLexer.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae37abcc39c0c49eb6a03638279e6b22135dfc2d --- /dev/null +++ b/node_modules/graphql/language/schemaCoordinateLexer.d.ts @@ -0,0 +1,45 @@ +import { Token } from './ast'; +import type { LexerInterface } from './lexer'; +import type { Source } from './source'; +/** + * Given a Source schema coordinate, creates a Lexer for that source. + * A SchemaCoordinateLexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + * + * @internal + */ +export declare class SchemaCoordinateLexer implements LexerInterface { + source: Source; + /** The previously focused non-ignored token. */ + lastToken: Token; + /** The currently focused non-ignored token. */ + token: Token; + /** + * The (1-indexed) line containing the current token. + * Since a schema coordinate may not contain newline, this value is always 1. + */ + line: 1; + /** + * The character offset at which the current line begins. + * Since a schema coordinate may not contain newline, this value is always 0. + */ + lineStart: 0; + constructor(source: Source); + get [Symbol.toStringTag](): string; + /** + * Advances the token stream to the next non-ignored token. + * + * @internal + */ + advance(): Token; + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the current Lexer token. + * + * @internal + */ + lookahead(): Token; +} diff --git a/node_modules/graphql/language/schemaCoordinateLexer.js b/node_modules/graphql/language/schemaCoordinateLexer.js new file mode 100644 index 0000000000000000000000000000000000000000..3164a4472bf066f4ec78ec79a47165487a6a2a22 --- /dev/null +++ b/node_modules/graphql/language/schemaCoordinateLexer.js @@ -0,0 +1,175 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.SchemaCoordinateLexer = void 0; + +var _syntaxError = require('../error/syntaxError.js'); + +var _ast = require('./ast.js'); + +var _characterClasses = require('./characterClasses.js'); + +var _lexer = require('./lexer.js'); + +var _tokenKind = require('./tokenKind.js'); + +/** + * Given a Source schema coordinate, creates a Lexer for that source. + * A SchemaCoordinateLexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + * + * @internal + */ +class SchemaCoordinateLexer { + /** The previously focused non-ignored token. */ + + /** The currently focused non-ignored token. */ + + /** + * The (1-indexed) line containing the current token. + * Since a schema coordinate may not contain newline, this value is always 1. + */ + line = 1; + /** + * The character offset at which the current line begins. + * Since a schema coordinate may not contain newline, this value is always 0. + */ + + lineStart = 0; + + constructor(source) { + const startOfFileToken = new _ast.Token( + _tokenKind.TokenKind.SOF, + 0, + 0, + 0, + 0, + ); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + } + + get [Symbol.toStringTag]() { + return 'SchemaCoordinateLexer'; + } + /** + * Advances the token stream to the next non-ignored token. + * + * @internal + */ + + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the current Lexer token. + * + * @internal + */ + + lookahead() { + let token = this.token; + + if (token.kind !== _tokenKind.TokenKind.EOF) { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + + return token; + } +} +/** + * Gets the next token from the source starting at the given position. + * + * @internal + */ + +exports.SchemaCoordinateLexer = SchemaCoordinateLexer; + +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + const position = start; + + if (position < bodyLength) { + const code = body.charCodeAt(position); + + switch (code) { + case 0x002e: + // . + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.DOT, + position, + position + 1, + ); + + case 0x0028: + // ( + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.PAREN_L, + position, + position + 1, + ); + + case 0x0029: + // ) + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.PAREN_R, + position, + position + 1, + ); + + case 0x003a: + // : + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.COLON, + position, + position + 1, + ); + + case 0x0040: + // @ + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.AT, + position, + position + 1, + ); + } // Name + + if ((0, _characterClasses.isNameStart)(code)) { + return (0, _lexer.readName)(lexer, position); + } + + throw (0, _syntaxError.syntaxError)( + lexer.source, + position, + `Invalid character: ${(0, _lexer.printCodePointAt)(lexer, position)}.`, + ); + } + + return (0, _lexer.createToken)( + lexer, + _tokenKind.TokenKind.EOF, + bodyLength, + bodyLength, + ); +} diff --git a/node_modules/graphql/language/schemaCoordinateLexer.mjs b/node_modules/graphql/language/schemaCoordinateLexer.mjs new file mode 100644 index 0000000000000000000000000000000000000000..55f9bb0ba7b8bbd7c5db8023c51a6abd8923652e --- /dev/null +++ b/node_modules/graphql/language/schemaCoordinateLexer.mjs @@ -0,0 +1,126 @@ +import { syntaxError } from '../error/syntaxError.mjs'; +import { Token } from './ast.mjs'; +import { isNameStart } from './characterClasses.mjs'; +import { createToken, printCodePointAt, readName } from './lexer.mjs'; +import { TokenKind } from './tokenKind.mjs'; +/** + * Given a Source schema coordinate, creates a Lexer for that source. + * A SchemaCoordinateLexer is a stateful stream generator in that every time + * it is advanced, it returns the next token in the Source. Assuming the + * source lexes, the final Token emitted by the lexer will be of kind + * EOF, after which the lexer will repeatedly return the same EOF token + * whenever called. + * + * @internal + */ + +export class SchemaCoordinateLexer { + /** The previously focused non-ignored token. */ + + /** The currently focused non-ignored token. */ + + /** + * The (1-indexed) line containing the current token. + * Since a schema coordinate may not contain newline, this value is always 1. + */ + line = 1; + /** + * The character offset at which the current line begins. + * Since a schema coordinate may not contain newline, this value is always 0. + */ + + lineStart = 0; + + constructor(source) { + const startOfFileToken = new Token(TokenKind.SOF, 0, 0, 0, 0); + this.source = source; + this.lastToken = startOfFileToken; + this.token = startOfFileToken; + } + + get [Symbol.toStringTag]() { + return 'SchemaCoordinateLexer'; + } + /** + * Advances the token stream to the next non-ignored token. + * + * @internal + */ + + advance() { + this.lastToken = this.token; + const token = (this.token = this.lookahead()); + return token; + } + /** + * Looks ahead and returns the next non-ignored token, but does not change + * the current Lexer token. + * + * @internal + */ + + lookahead() { + let token = this.token; + + if (token.kind !== TokenKind.EOF) { + // Read the next token and form a link in the token linked-list. + const nextToken = readNextToken(this, token.end); // @ts-expect-error next is only mutable during parsing. + + token.next = nextToken; // @ts-expect-error prev is only mutable during parsing. + + nextToken.prev = token; + token = nextToken; + } + + return token; + } +} +/** + * Gets the next token from the source starting at the given position. + * + * @internal + */ + +function readNextToken(lexer, start) { + const body = lexer.source.body; + const bodyLength = body.length; + const position = start; + + if (position < bodyLength) { + const code = body.charCodeAt(position); + + switch (code) { + case 0x002e: + // . + return createToken(lexer, TokenKind.DOT, position, position + 1); + + case 0x0028: + // ( + return createToken(lexer, TokenKind.PAREN_L, position, position + 1); + + case 0x0029: + // ) + return createToken(lexer, TokenKind.PAREN_R, position, position + 1); + + case 0x003a: + // : + return createToken(lexer, TokenKind.COLON, position, position + 1); + + case 0x0040: + // @ + return createToken(lexer, TokenKind.AT, position, position + 1); + } // Name + + if (isNameStart(code)) { + return readName(lexer, position); + } + + throw syntaxError( + lexer.source, + position, + `Invalid character: ${printCodePointAt(lexer, position)}.`, + ); + } + + return createToken(lexer, TokenKind.EOF, bodyLength, bodyLength); +} diff --git a/node_modules/graphql/language/source.d.ts b/node_modules/graphql/language/source.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01b93d792fe4edb1c3ca4848106d64bacc0ccc2d --- /dev/null +++ b/node_modules/graphql/language/source.d.ts @@ -0,0 +1,53 @@ +/** @category Source */ +interface Location { + line: number; + column: number; +} +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +export declare class Source { + /** The GraphQL source text. */ + body: string; + /** Name used in diagnostics for this source, such as a file path or request name. */ + name: string; + /** One-indexed line and column where this source begins. */ + locationOffset: Location; + /** + * Creates a Source instance. + * @param body - The GraphQL source text. + * @param name - Name used in diagnostics for this source. + * @param locationOffset - One-indexed line and column where this source begins. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * + * const source = new Source( + * 'type Query { greeting: String }', + * 'schema.graphql', + * { line: 10, column: 1 }, + * ); + * + * source.body; // => 'type Query { greeting: String }' + * source.name; // => 'schema.graphql' + * source.locationOffset; // => { line: 10, column: 1 } + * ``` + */ + constructor(body: string, name?: string, locationOffset?: Location); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; +} +/** + * Test if the given value is a Source object. + * + * @internal + */ +export declare function isSource(source: unknown): source is Source; +export {}; diff --git a/node_modules/graphql/language/source.js b/node_modules/graphql/language/source.js new file mode 100644 index 0000000000000000000000000000000000000000..76e231d661a2e13bfe86b983a0a11b2ce9ae25c5 --- /dev/null +++ b/node_modules/graphql/language/source.js @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.Source = void 0; +exports.isSource = isSource; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _instanceOf = require('../jsutils/instanceOf.js'); + +/** @category Source */ + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +class Source { + /** The GraphQL source text. */ + + /** Name used in diagnostics for this source, such as a file path or request name. */ + + /** One-indexed line and column where this source begins. */ + + /** + * Creates a Source instance. + * @param body - The GraphQL source text. + * @param name - Name used in diagnostics for this source. + * @param locationOffset - One-indexed line and column where this source begins. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * + * const source = new Source( + * 'type Query { greeting: String }', + * 'schema.graphql', + * { line: 10, column: 1 }, + * ); + * + * source.body; // => 'type Query { greeting: String }' + * source.name; // => 'schema.graphql' + * source.locationOffset; // => { line: 10, column: 1 } + * ``` + */ + constructor( + body, + name = 'GraphQL request', + locationOffset = { + line: 1, + column: 1, + }, + ) { + typeof body === 'string' || + (0, _devAssert.devAssert)( + false, + `Body must be a string. Received: ${(0, _inspect.inspect)(body)}.`, + ); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || + (0, _devAssert.devAssert)( + false, + 'line in locationOffset is 1-indexed and must be positive.', + ); + this.locationOffset.column > 0 || + (0, _devAssert.devAssert)( + false, + 'column in locationOffset is 1-indexed and must be positive.', + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Source'; + } +} +/** + * Test if the given value is a Source object. + * + * @internal + */ + +exports.Source = Source; + +function isSource(source) { + return (0, _instanceOf.instanceOf)(source, Source); +} diff --git a/node_modules/graphql/language/source.mjs b/node_modules/graphql/language/source.mjs new file mode 100644 index 0000000000000000000000000000000000000000..584e0ff6116ad7d070171e828c859ff898892c44 --- /dev/null +++ b/node_modules/graphql/language/source.mjs @@ -0,0 +1,81 @@ +/** @category Source */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { instanceOf } from '../jsutils/instanceOf.mjs'; + +/** + * A representation of source input to GraphQL. The `name` and `locationOffset` parameters are + * optional, but they are useful for clients who store GraphQL documents in source files. + * For example, if the GraphQL input starts at line 40 in a file named `Foo.graphql`, it might + * be useful for `name` to be `"Foo.graphql"` and location to be `{ line: 40, column: 1 }`. + * The `line` and `column` properties in `locationOffset` are 1-indexed. + */ +export class Source { + /** The GraphQL source text. */ + + /** Name used in diagnostics for this source, such as a file path or request name. */ + + /** One-indexed line and column where this source begins. */ + + /** + * Creates a Source instance. + * @param body - The GraphQL source text. + * @param name - Name used in diagnostics for this source. + * @param locationOffset - One-indexed line and column where this source begins. + * @example + * ```ts + * import { Source } from 'graphql/language'; + * + * const source = new Source( + * 'type Query { greeting: String }', + * 'schema.graphql', + * { line: 10, column: 1 }, + * ); + * + * source.body; // => 'type Query { greeting: String }' + * source.name; // => 'schema.graphql' + * source.locationOffset; // => { line: 10, column: 1 } + * ``` + */ + constructor( + body, + name = 'GraphQL request', + locationOffset = { + line: 1, + column: 1, + }, + ) { + typeof body === 'string' || + devAssert(false, `Body must be a string. Received: ${inspect(body)}.`); + this.body = body; + this.name = name; + this.locationOffset = locationOffset; + this.locationOffset.line > 0 || + devAssert( + false, + 'line in locationOffset is 1-indexed and must be positive.', + ); + this.locationOffset.column > 0 || + devAssert( + false, + 'column in locationOffset is 1-indexed and must be positive.', + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'Source'; + } +} +/** + * Test if the given value is a Source object. + * + * @internal + */ + +export function isSource(source) { + return instanceOf(source, Source); +} diff --git a/node_modules/graphql/language/tokenKind.d.ts b/node_modules/graphql/language/tokenKind.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..28d8e473db28220106e0dc4490faabbe4eadc772 --- /dev/null +++ b/node_modules/graphql/language/tokenKind.d.ts @@ -0,0 +1,63 @@ +/** @category Lexing */ +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +declare enum TokenKind { + /** Start-of-file token. */ + SOF = '', + /** End-of-file token. */ + EOF = '', + /** The `!` punctuation token. */ + BANG = '!', + /** The `$` punctuation token. */ + DOLLAR = '$', + /** The `&` punctuation token. */ + AMP = '&', + /** The `(` punctuation token. */ + PAREN_L = '(', + /** The `)` punctuation token. */ + PAREN_R = ')', + /** The `.` punctuation token. */ + DOT = '.', + /** The `...` spread punctuation token. */ + SPREAD = '...', + /** The `:` punctuation token. */ + COLON = ':', + /** The `=` punctuation token. */ + EQUALS = '=', + /** The `@` punctuation token. */ + AT = '@', + /** The `[` punctuation token. */ + BRACKET_L = '[', + /** The `]` punctuation token. */ + BRACKET_R = ']', + /** The `{` punctuation token. */ + BRACE_L = '{', + /** The `|` punctuation token. */ + PIPE = '|', + /** The `}` punctuation token. */ + BRACE_R = '}', + /** A GraphQL name token or name AST node. */ + NAME = 'Name', + /** An integer value token or AST node. */ + INT = 'Int', + /** A floating-point value token or AST node. */ + FLOAT = 'Float', + /** A string value token or AST node. */ + STRING = 'String', + /** A block string value token. */ + BLOCK_STRING = 'BlockString', + /** A comment token. */ + COMMENT = 'Comment', +} +export { TokenKind }; +/** + * Deprecated legacy alias for the enum type representing token kind values. + * This alias will be removed in v17. In v17, `TokenKind` is exported as the + * single public symbol for both the runtime object and the corresponding + * TypeScript type. + * @deprecated Will be removed in v17. In v17, use `TokenKind` as both the + * runtime value and the type. + */ +export declare type TokenKindEnum = typeof TokenKind; diff --git a/node_modules/graphql/language/tokenKind.js b/node_modules/graphql/language/tokenKind.js new file mode 100644 index 0000000000000000000000000000000000000000..e9b1aa32f412d7ef3cb9a9a7990a2c790f4ee0da --- /dev/null +++ b/node_modules/graphql/language/tokenKind.js @@ -0,0 +1,49 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.TokenKind = void 0; + +/** @category Lexing */ + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind; +exports.TokenKind = TokenKind; + +(function (TokenKind) { + TokenKind['SOF'] = ''; + TokenKind['EOF'] = ''; + TokenKind['BANG'] = '!'; + TokenKind['DOLLAR'] = '$'; + TokenKind['AMP'] = '&'; + TokenKind['PAREN_L'] = '('; + TokenKind['PAREN_R'] = ')'; + TokenKind['DOT'] = '.'; + TokenKind['SPREAD'] = '...'; + TokenKind['COLON'] = ':'; + TokenKind['EQUALS'] = '='; + TokenKind['AT'] = '@'; + TokenKind['BRACKET_L'] = '['; + TokenKind['BRACKET_R'] = ']'; + TokenKind['BRACE_L'] = '{'; + TokenKind['PIPE'] = '|'; + TokenKind['BRACE_R'] = '}'; + TokenKind['NAME'] = 'Name'; + TokenKind['INT'] = 'Int'; + TokenKind['FLOAT'] = 'Float'; + TokenKind['STRING'] = 'String'; + TokenKind['BLOCK_STRING'] = 'BlockString'; + TokenKind['COMMENT'] = 'Comment'; +})(TokenKind || (exports.TokenKind = TokenKind = {})); +/** + * Deprecated legacy alias for the enum type representing token kind values. + * This alias will be removed in v17. In v17, `TokenKind` is exported as the + * single public symbol for both the runtime object and the corresponding + * TypeScript type. + * @deprecated Will be removed in v17. In v17, use `TokenKind` as both the + * runtime value and the type. + */ diff --git a/node_modules/graphql/language/tokenKind.mjs b/node_modules/graphql/language/tokenKind.mjs new file mode 100644 index 0000000000000000000000000000000000000000..95a62e4b1473159e37b9816d5ec672ed26bb710a --- /dev/null +++ b/node_modules/graphql/language/tokenKind.mjs @@ -0,0 +1,43 @@ +/** @category Lexing */ + +/** + * An exported enum describing the different kinds of tokens that the + * lexer emits. + */ +var TokenKind; + +(function (TokenKind) { + TokenKind['SOF'] = ''; + TokenKind['EOF'] = ''; + TokenKind['BANG'] = '!'; + TokenKind['DOLLAR'] = '$'; + TokenKind['AMP'] = '&'; + TokenKind['PAREN_L'] = '('; + TokenKind['PAREN_R'] = ')'; + TokenKind['DOT'] = '.'; + TokenKind['SPREAD'] = '...'; + TokenKind['COLON'] = ':'; + TokenKind['EQUALS'] = '='; + TokenKind['AT'] = '@'; + TokenKind['BRACKET_L'] = '['; + TokenKind['BRACKET_R'] = ']'; + TokenKind['BRACE_L'] = '{'; + TokenKind['PIPE'] = '|'; + TokenKind['BRACE_R'] = '}'; + TokenKind['NAME'] = 'Name'; + TokenKind['INT'] = 'Int'; + TokenKind['FLOAT'] = 'Float'; + TokenKind['STRING'] = 'String'; + TokenKind['BLOCK_STRING'] = 'BlockString'; + TokenKind['COMMENT'] = 'Comment'; +})(TokenKind || (TokenKind = {})); + +export { TokenKind }; +/** + * Deprecated legacy alias for the enum type representing token kind values. + * This alias will be removed in v17. In v17, `TokenKind` is exported as the + * single public symbol for both the runtime object and the corresponding + * TypeScript type. + * @deprecated Will be removed in v17. In v17, use `TokenKind` as both the + * runtime value and the type. + */ diff --git a/node_modules/graphql/language/visitor.d.ts b/node_modules/graphql/language/visitor.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..80719df68c9fcf44473daaa0250fd6c3e9f87711 --- /dev/null +++ b/node_modules/graphql/language/visitor.d.ts @@ -0,0 +1,322 @@ +/** @category Visiting */ +import type { ASTNode } from './ast'; +import { Kind } from './kinds'; +/** A visitor defines the callbacks called during AST traversal. */ +export declare type ASTVisitor = EnterLeaveVisitor | KindVisitor; +declare type KindVisitor = { + readonly [NodeT in ASTNode as NodeT['kind']]?: + | ASTVisitFn + | EnterLeaveVisitor; +}; +interface EnterLeaveVisitor { + readonly enter?: ASTVisitFn; + readonly leave?: ASTVisitFn; +} +/** + * A visitor is composed of visit functions called for each node during traversal. + * @typeParam TVisitedNode - AST node type handled by this visitor function. + */ +export declare type ASTVisitFn = ( + /** Current node being visited. */ + node: TVisitedNode, + /** Index or key for this node within the parent node or array. */ + key: string | number | undefined, + /** Parent immediately above this node, which may be an array. */ + parent: ASTNode | ReadonlyArray | undefined, + /** Key path from the root node to this node. */ + path: ReadonlyArray, + /** + * All nodes and arrays visited before reaching this node's parent. + * These correspond to array indices in `path`. + * Note: ancestors includes arrays that contain the visited node's parent. + */ + ancestors: ReadonlyArray>, +) => any; +/** + * A reducer is composed of reducer functions that convert AST nodes into another form. + * + * @internal + */ +export declare type ASTReducer = { + readonly [NodeT in ASTNode as NodeT['kind']]?: { + readonly enter?: ASTVisitFn; + readonly leave: ASTReducerFn; + }; +}; +declare type ASTReducerFn = ( + /** + * Current node being visited. + * @internal + */ + node: { + [K in keyof TReducedNode]: ReducedField; + }, + /** + * Index or key for this node within the parent node or array. + * @internal + */ + key: string | number | undefined, + /** + * Parent immediately above this node, which may be an array. + * @internal + */ + parent: ASTNode | ReadonlyArray | undefined, + /** + * Key path from the root node to this node. + * @internal + */ + path: ReadonlyArray, + /** + * All nodes and arrays visited before reaching this node's parent. + * These correspond to array indices in `path`. + * Note: ancestors includes arrays that contain the visited node's parent. + * @internal + */ + ancestors: ReadonlyArray>, +) => R; +declare type ReducedField = T extends null | undefined + ? T + : T extends ReadonlyArray + ? ReadonlyArray + : R; +/** + * Deprecated visitor key map type retained for compatibility. Inline this + * mapped type at use sites because ASTVisitorKeyMap will be removed in v17. + * @deprecated Please inline it. Will be removed in v17 + */ +export declare type ASTVisitorKeyMap = { + [NodeT in ASTNode as NodeT['kind']]?: ReadonlyArray; +}; +/** A value that can be returned from a visitor function to stop traversal. */ +export declare const BREAK: unknown; +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * @param root - The AST node at which to start traversal. + * @param visitor - The visitor or reducer functions to call while traversing. + * @param visitorKeys - Optional map of child keys to visit for each AST node kind. + * @returns The original AST, an edited AST, or a reduced value depending on the visitor. + * @typeParam N - The root AST node type returned when visiting without reducing. + * @example + * ```ts + * // Return values control traversal: undefined makes no change, false skips + * // a subtree, BREAK stops traversal, null removes a node, and any other + * // value replaces the current node. + * import { Kind, parse, print, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const editedAST = visit(document, { + * Field: (node) => { + * if (node.name.value === 'hero') { + * return { + * ...node, + * name: { kind: Kind.NAME, value: 'human' }, + * }; + * } + * }, + * }); + * + * print(editedAST); // => '{\n human {\n name\n }\n}' + * ``` + * @example + * ```ts + * // A named visitor function runs when entering nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const fieldNames = []; + * + * visit(document, { + * Field: (node) => { + * fieldNames.push(node.name.value); + * }, + * }); + * + * fieldNames; // => ['hero', 'name'] + * ``` + * @example + * ```ts + * // A named visitor object can provide separate enter and leave handlers for + * // nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit(document, { + * Field: { + * enter: (node) => { + * events.push(`enter:${node.name.value}`); + * }, + * leave: (node) => { + * events.push(`leave:${node.name.value}`); + * }, + * }, + * }); + * + * events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero'] + * ``` + * @example + * ```ts + * // Generic enter and leave handlers run for every node. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * let enterCount = 0; + * let leaveCount = 0; + * + * visit(document, { + * enter: (node) => { + * enterCount += 1; + * }, + * leave: (node) => { + * leaveCount += 1; + * }, + * }); + * + * enterCount; // => leaveCount + * enterCount > 0; // => true + * ``` + */ +export declare function visit( + root: N, + visitor: ASTVisitor, + visitorKeys?: ASTVisitorKeyMap, +): N; +/** + * Traverses an AST with reducer callbacks and returns the reduced value. + * @param root - The AST node where traversal starts. + * @param visitor - Reducer callbacks to invoke during traversal. + * @param visitorKeys - Optional mapping of child keys for each AST node kind. + * @returns The value produced by the reducer visitor. + * @typeParam R - The value produced by reducer visitor callbacks. + * @example + * ```ts + * // A reducer visitor returns values from leave handlers to build a reduced + * // result instead of returning an edited AST. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const printed = visit(document, { + * Name: { + * leave: (node) => { + * return node.value; + * }, + * }, + * Field: { + * leave: (node) => { + * return node.selectionSet == null + * ? node.name + * : `${node.name} { ${node.selectionSet} }`; + * }, + * }, + * SelectionSet: { + * leave: (node) => { + * return node.selections.join(' '); + * }, + * }, + * OperationDefinition: { + * leave: (node) => { + * return node.selectionSet; + * }, + * }, + * Document: { + * leave: (node) => { + * return node.definitions.join('\n'); + * }, + * }, + * }); + * + * printed; // => 'hero { name }' + * ``` + */ +export declare function visit( + root: ASTNode, + visitor: ASTReducer, + visitorKeys?: ASTVisitorKeyMap, +): R; +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + * @param visitors - The visitors to merge into one parallel visitor. + * @returns A visitor that delegates traversal to each provided visitor. + * @example + * ```ts + * import { parse, visit, visitInParallel } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit( + * document, + * visitInParallel([ + * { Field: (node) => { events.push(`field:${node.name.value}`); } }, + * { Name: (node) => { events.push(`name:${node.value}`); } }, + * ]), + * ); + * + * events; // => ['field:hero', 'name:hero', 'field:name', 'name:name'] + * ``` + */ +export declare function visitInParallel( + visitors: ReadonlyArray, +): ASTVisitor; +/** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve handlers for. + * @returns The enter and leave handlers that apply for the given node kind. + * @example + * ```ts + * import { Kind, getEnterLeaveForKind } from 'graphql/language'; + * + * const handlers = getEnterLeaveForKind({ Field: () => {} }, Kind.FIELD); + * + * typeof handlers.enter; // => 'function' + * handlers.leave; // => undefined + * ``` + */ +export declare function getEnterLeaveForKind( + visitor: ASTVisitor, + kind: Kind, +): EnterLeaveVisitor; +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. This deprecated compatibility + * helper delegates to `getEnterLeaveForKind`; call `getEnterLeaveForKind` + * directly because getVisitFn will be removed in v17. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve a handler for. + * @param isLeaving - Whether to resolve the leave handler instead of the enter handler. + * @returns The visit function that applies for the given node kind and traversal phase, if one exists. + * @example + * ```ts + * import { Kind, getVisitFn } from 'graphql/language'; + * + * const enter = getVisitFn({ Field: () => {} }, Kind.FIELD, false); + * const leave = getVisitFn({ Field: () => {} }, Kind.FIELD, true); + * + * typeof enter; // => 'function' + * leave; // => undefined + * ``` + * @category Visiting + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ +export declare function getVisitFn( + visitor: ASTVisitor, + kind: Kind, + isLeaving: boolean, +): ASTVisitFn | undefined; +export {}; diff --git a/node_modules/graphql/language/visitor.js b/node_modules/graphql/language/visitor.js new file mode 100644 index 0000000000000000000000000000000000000000..3ec77d2310e9e8c97d18432b69194d8ad8d3c25f --- /dev/null +++ b/node_modules/graphql/language/visitor.js @@ -0,0 +1,446 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.BREAK = void 0; +exports.getEnterLeaveForKind = getEnterLeaveForKind; +exports.getVisitFn = getVisitFn; +exports.visit = visit; +exports.visitInParallel = visitInParallel; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _ast = require('./ast.js'); + +var _kinds = require('./kinds.js'); + +/** @category Visiting */ + +/** A value that can be returned from a visitor function to stop traversal. */ +const BREAK = Object.freeze({}); +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * @param root - The AST node at which to start traversal. + * @param visitor - The visitor or reducer functions to call while traversing. + * @param visitorKeys - Optional map of child keys to visit for each AST node kind. + * @returns The original AST, an edited AST, or a reduced value depending on the visitor. + * @typeParam N - The root AST node type returned when visiting without reducing. + * @example + * ```ts + * // Return values control traversal: undefined makes no change, false skips + * // a subtree, BREAK stops traversal, null removes a node, and any other + * // value replaces the current node. + * import { Kind, parse, print, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const editedAST = visit(document, { + * Field: (node) => { + * if (node.name.value === 'hero') { + * return { + * ...node, + * name: { kind: Kind.NAME, value: 'human' }, + * }; + * } + * }, + * }); + * + * print(editedAST); // => '{\n human {\n name\n }\n}' + * ``` + * @example + * ```ts + * // A named visitor function runs when entering nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const fieldNames = []; + * + * visit(document, { + * Field: (node) => { + * fieldNames.push(node.name.value); + * }, + * }); + * + * fieldNames; // => ['hero', 'name'] + * ``` + * @example + * ```ts + * // A named visitor object can provide separate enter and leave handlers for + * // nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit(document, { + * Field: { + * enter: (node) => { + * events.push(`enter:${node.name.value}`); + * }, + * leave: (node) => { + * events.push(`leave:${node.name.value}`); + * }, + * }, + * }); + * + * events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero'] + * ``` + * @example + * ```ts + * // Generic enter and leave handlers run for every node. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * let enterCount = 0; + * let leaveCount = 0; + * + * visit(document, { + * enter: (node) => { + * enterCount += 1; + * }, + * leave: (node) => { + * leaveCount += 1; + * }, + * }); + * + * enterCount; // => leaveCount + * enterCount > 0; // => true + * ``` + */ + +exports.BREAK = BREAK; + +/** @internal */ +function visit(root, visitor, visitorKeys = _ast.QueryDocumentKeys) { + const enterLeaveMap = new Map(); + + for (const kind of Object.values(_kinds.Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); + } + /* eslint-disable no-undef-init */ + + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = { ...node }; + + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; + + if (node === null || node === undefined) { + continue; + } + + path.push(key); + } + + let result; + + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; + + (0, _ast.isNode)(node) || + (0, _devAssert.devAssert)( + false, + `Invalid AST Node: ${(0, _inspect.inspect)(node)}.`, + ); + const visitFn = isLeaving + ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get === void 0 + ? void 0 + : _enterLeaveMap$get.leave + : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get2 === void 0 + ? void 0 + : _enterLeaveMap$get2.enter; + result = + visitFn === null || visitFn === void 0 + ? void 0 + : visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if ((0, _ast.isNode)(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + var _node$kind; + + stack = { + inArray, + index, + keys, + edits, + prev: stack, + }; + inArray = Array.isArray(node); + keys = inArray + ? node + : (_node$kind = visitorKeys[node.kind]) !== null && + _node$kind !== void 0 + ? _node$kind + : []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; + } + + return root; +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + * @param visitors - The visitors to merge into one parallel visitor. + * @returns A visitor that delegates traversal to each provided visitor. + * @example + * ```ts + * import { parse, visit, visitInParallel } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit( + * document, + * visitInParallel([ + * { Field: (node) => { events.push(`field:${node.name.value}`); } }, + * { Name: (node) => { events.push(`name:${node.value}`); } }, + * ]), + * ); + * + * events; // => ['field:hero', 'name:hero', 'field:name', 'name:name'] + * ``` + */ + +function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + + for (const kind of Object.values(_kinds.Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + + for (let i = 0; i < visitors.length; ++i) { + const { enter, leave } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; + } + + if (!hasVisitor) { + continue; + } + + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + + const result = + (_enterList$i = enterList[i]) === null || _enterList$i === void 0 + ? void 0 + : _enterList$i.apply(visitors[i], args); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + }, + + leave(...args) { + const node = args[0]; + + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; + + const result = + (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 + ? void 0 + : _leaveList$i.apply(visitors[i], args); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; + mergedVisitor[kind] = mergedEnterLeave; + } + + return mergedVisitor; +} +/** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve handlers for. + * @returns The enter and leave handlers that apply for the given node kind. + * @example + * ```ts + * import { Kind, getEnterLeaveForKind } from 'graphql/language'; + * + * const handlers = getEnterLeaveForKind({ Field: () => {} }, Kind.FIELD); + * + * typeof handlers.enter; // => 'function' + * handlers.leave; // => undefined + * ``` + */ + +function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; + + if (typeof kindVisitor === 'object') { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === 'function') { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined, + }; + } // { enter() {}, leave() {} } + + return { + enter: visitor.enter, + leave: visitor.leave, + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. This deprecated compatibility + * helper delegates to `getEnterLeaveForKind`; call `getEnterLeaveForKind` + * directly because getVisitFn will be removed in v17. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve a handler for. + * @param isLeaving - Whether to resolve the leave handler instead of the enter handler. + * @returns The visit function that applies for the given node kind and traversal phase, if one exists. + * @example + * ```ts + * import { Kind, getVisitFn } from 'graphql/language'; + * + * const enter = getVisitFn({ Field: () => {} }, Kind.FIELD, false); + * const leave = getVisitFn({ Field: () => {} }, Kind.FIELD, true); + * + * typeof enter; // => 'function' + * leave; // => undefined + * ``` + * @category Visiting + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ + +/* c8 ignore next 8 */ + +function getVisitFn(visitor, kind, isLeaving) { + const { enter, leave } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; +} diff --git a/node_modules/graphql/language/visitor.mjs b/node_modules/graphql/language/visitor.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cccae9043df3e6e20fd8f3660e39559a762f7480 --- /dev/null +++ b/node_modules/graphql/language/visitor.mjs @@ -0,0 +1,426 @@ +/** @category Visiting */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { isNode, QueryDocumentKeys } from './ast.mjs'; +import { Kind } from './kinds.mjs'; +/** A visitor defines the callbacks called during AST traversal. */ + +/** A value that can be returned from a visitor function to stop traversal. */ +export const BREAK = Object.freeze({}); +/** + * visit() will walk through an AST using a depth-first traversal, calling + * the visitor's enter function at each node in the traversal, and calling the + * leave function after visiting that node and all of its child nodes. + * + * By returning different values from the enter and leave functions, the + * behavior of the visitor can be altered, including skipping over a sub-tree of + * the AST (by returning false), editing the AST by returning a value or null + * to remove the value, or to stop the whole traversal by returning BREAK. + * + * When using visit() to edit an AST, the original AST will not be modified, and + * a new version of the AST with the changes applied will be returned from the + * visit function. + * @param root - The AST node at which to start traversal. + * @param visitor - The visitor or reducer functions to call while traversing. + * @param visitorKeys - Optional map of child keys to visit for each AST node kind. + * @returns The original AST, an edited AST, or a reduced value depending on the visitor. + * @typeParam N - The root AST node type returned when visiting without reducing. + * @example + * ```ts + * // Return values control traversal: undefined makes no change, false skips + * // a subtree, BREAK stops traversal, null removes a node, and any other + * // value replaces the current node. + * import { Kind, parse, print, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const editedAST = visit(document, { + * Field: (node) => { + * if (node.name.value === 'hero') { + * return { + * ...node, + * name: { kind: Kind.NAME, value: 'human' }, + * }; + * } + * }, + * }); + * + * print(editedAST); // => '{\n human {\n name\n }\n}' + * ``` + * @example + * ```ts + * // A named visitor function runs when entering nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const fieldNames = []; + * + * visit(document, { + * Field: (node) => { + * fieldNames.push(node.name.value); + * }, + * }); + * + * fieldNames; // => ['hero', 'name'] + * ``` + * @example + * ```ts + * // A named visitor object can provide separate enter and leave handlers for + * // nodes of that kind. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit(document, { + * Field: { + * enter: (node) => { + * events.push(`enter:${node.name.value}`); + * }, + * leave: (node) => { + * events.push(`leave:${node.name.value}`); + * }, + * }, + * }); + * + * events; // => ['enter:hero', 'enter:name', 'leave:name', 'leave:hero'] + * ``` + * @example + * ```ts + * // Generic enter and leave handlers run for every node. + * import { parse, visit } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * let enterCount = 0; + * let leaveCount = 0; + * + * visit(document, { + * enter: (node) => { + * enterCount += 1; + * }, + * leave: (node) => { + * leaveCount += 1; + * }, + * }); + * + * enterCount; // => leaveCount + * enterCount > 0; // => true + * ``` + */ + +/** @internal */ +export function visit(root, visitor, visitorKeys = QueryDocumentKeys) { + const enterLeaveMap = new Map(); + + for (const kind of Object.values(Kind)) { + enterLeaveMap.set(kind, getEnterLeaveForKind(visitor, kind)); + } + /* eslint-disable no-undef-init */ + + let stack = undefined; + let inArray = Array.isArray(root); + let keys = [root]; + let index = -1; + let edits = []; + let node = root; + let key = undefined; + let parent = undefined; + const path = []; + const ancestors = []; + /* eslint-enable no-undef-init */ + + do { + index++; + const isLeaving = index === keys.length; + const isEdited = isLeaving && edits.length !== 0; + + if (isLeaving) { + key = ancestors.length === 0 ? undefined : path[path.length - 1]; + node = parent; + parent = ancestors.pop(); + + if (isEdited) { + if (inArray) { + node = node.slice(); + let editOffset = 0; + + for (const [editKey, editValue] of edits) { + const arrayKey = editKey - editOffset; + + if (editValue === null) { + node.splice(arrayKey, 1); + editOffset++; + } else { + node[arrayKey] = editValue; + } + } + } else { + node = { ...node }; + + for (const [editKey, editValue] of edits) { + node[editKey] = editValue; + } + } + } + + index = stack.index; + keys = stack.keys; + edits = stack.edits; + inArray = stack.inArray; + stack = stack.prev; + } else if (parent) { + key = inArray ? index : keys[index]; + node = parent[key]; + + if (node === null || node === undefined) { + continue; + } + + path.push(key); + } + + let result; + + if (!Array.isArray(node)) { + var _enterLeaveMap$get, _enterLeaveMap$get2; + + isNode(node) || devAssert(false, `Invalid AST Node: ${inspect(node)}.`); + const visitFn = isLeaving + ? (_enterLeaveMap$get = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get === void 0 + ? void 0 + : _enterLeaveMap$get.leave + : (_enterLeaveMap$get2 = enterLeaveMap.get(node.kind)) === null || + _enterLeaveMap$get2 === void 0 + ? void 0 + : _enterLeaveMap$get2.enter; + result = + visitFn === null || visitFn === void 0 + ? void 0 + : visitFn.call(visitor, node, key, parent, path, ancestors); + + if (result === BREAK) { + break; + } + + if (result === false) { + if (!isLeaving) { + path.pop(); + continue; + } + } else if (result !== undefined) { + edits.push([key, result]); + + if (!isLeaving) { + if (isNode(result)) { + node = result; + } else { + path.pop(); + continue; + } + } + } + } + + if (result === undefined && isEdited) { + edits.push([key, node]); + } + + if (isLeaving) { + path.pop(); + } else { + var _node$kind; + + stack = { + inArray, + index, + keys, + edits, + prev: stack, + }; + inArray = Array.isArray(node); + keys = inArray + ? node + : (_node$kind = visitorKeys[node.kind]) !== null && + _node$kind !== void 0 + ? _node$kind + : []; + index = -1; + edits = []; + + if (parent) { + ancestors.push(parent); + } + + parent = node; + } + } while (stack !== undefined); + + if (edits.length !== 0) { + // New root + return edits[edits.length - 1][1]; + } + + return root; +} +/** + * Creates a new visitor instance which delegates to many visitors to run in + * parallel. Each visitor will be visited for each node before moving on. + * + * If a prior visitor edits a node, no following visitors will see that node. + * @param visitors - The visitors to merge into one parallel visitor. + * @returns A visitor that delegates traversal to each provided visitor. + * @example + * ```ts + * import { parse, visit, visitInParallel } from 'graphql/language'; + * + * const document = parse('{ hero { name } }'); + * const events = []; + * + * visit( + * document, + * visitInParallel([ + * { Field: (node) => { events.push(`field:${node.name.value}`); } }, + * { Name: (node) => { events.push(`name:${node.value}`); } }, + * ]), + * ); + * + * events; // => ['field:hero', 'name:hero', 'field:name', 'name:name'] + * ``` + */ + +export function visitInParallel(visitors) { + const skipping = new Array(visitors.length).fill(null); + const mergedVisitor = Object.create(null); + + for (const kind of Object.values(Kind)) { + let hasVisitor = false; + const enterList = new Array(visitors.length).fill(undefined); + const leaveList = new Array(visitors.length).fill(undefined); + + for (let i = 0; i < visitors.length; ++i) { + const { enter, leave } = getEnterLeaveForKind(visitors[i], kind); + hasVisitor || (hasVisitor = enter != null || leave != null); + enterList[i] = enter; + leaveList[i] = leave; + } + + if (!hasVisitor) { + continue; + } + + const mergedEnterLeave = { + enter(...args) { + const node = args[0]; + + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _enterList$i; + + const result = + (_enterList$i = enterList[i]) === null || _enterList$i === void 0 + ? void 0 + : _enterList$i.apply(visitors[i], args); + + if (result === false) { + skipping[i] = node; + } else if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined) { + return result; + } + } + } + }, + + leave(...args) { + const node = args[0]; + + for (let i = 0; i < visitors.length; i++) { + if (skipping[i] === null) { + var _leaveList$i; + + const result = + (_leaveList$i = leaveList[i]) === null || _leaveList$i === void 0 + ? void 0 + : _leaveList$i.apply(visitors[i], args); + + if (result === BREAK) { + skipping[i] = BREAK; + } else if (result !== undefined && result !== false) { + return result; + } + } else if (skipping[i] === node) { + skipping[i] = null; + } + } + }, + }; + mergedVisitor[kind] = mergedEnterLeave; + } + + return mergedVisitor; +} +/** + * Given a visitor instance and a node kind, return EnterLeaveVisitor for that kind. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve handlers for. + * @returns The enter and leave handlers that apply for the given node kind. + * @example + * ```ts + * import { Kind, getEnterLeaveForKind } from 'graphql/language'; + * + * const handlers = getEnterLeaveForKind({ Field: () => {} }, Kind.FIELD); + * + * typeof handlers.enter; // => 'function' + * handlers.leave; // => undefined + * ``` + */ + +export function getEnterLeaveForKind(visitor, kind) { + const kindVisitor = visitor[kind]; + + if (typeof kindVisitor === 'object') { + // { Kind: { enter() {}, leave() {} } } + return kindVisitor; + } else if (typeof kindVisitor === 'function') { + // { Kind() {} } + return { + enter: kindVisitor, + leave: undefined, + }; + } // { enter() {}, leave() {} } + + return { + enter: visitor.enter, + leave: visitor.leave, + }; +} +/** + * Given a visitor instance, if it is leaving or not, and a node kind, return + * the function the visitor runtime should call. This deprecated compatibility + * helper delegates to `getEnterLeaveForKind`; call `getEnterLeaveForKind` + * directly because getVisitFn will be removed in v17. + * @param visitor - The visitor object to inspect. + * @param kind - The AST node kind to resolve a handler for. + * @param isLeaving - Whether to resolve the leave handler instead of the enter handler. + * @returns The visit function that applies for the given node kind and traversal phase, if one exists. + * @example + * ```ts + * import { Kind, getVisitFn } from 'graphql/language'; + * + * const enter = getVisitFn({ Field: () => {} }, Kind.FIELD, false); + * const leave = getVisitFn({ Field: () => {} }, Kind.FIELD, true); + * + * typeof enter; // => 'function' + * leave; // => undefined + * ``` + * @category Visiting + * @deprecated Please use `getEnterLeaveForKind` instead. Will be removed in v17 + */ + +/* c8 ignore next 8 */ + +export function getVisitFn(visitor, kind, isLeaving) { + const { enter, leave } = getEnterLeaveForKind(visitor, kind); + return isLeaving ? leave : enter; +} diff --git a/node_modules/graphql/package.json b/node_modules/graphql/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4960ba1a81187ae363a449c6cd85231b03bbcdbd --- /dev/null +++ b/node_modules/graphql/package.json @@ -0,0 +1,39 @@ +{ + "name": "graphql", + "version": "16.14.2", + "description": "A Query Language and Runtime which can target any service.", + "license": "MIT", + "main": "index", + "module": "index.mjs", + "typesVersions": { + ">=4.1.0": { + "*": [ + "*" + ] + }, + "*": { + "*": [ + "NotSupportedTSVersion.d.ts" + ] + } + }, + "sideEffects": false, + "homepage": "https://github.com/graphql/graphql-js", + "bugs": { + "url": "https://github.com/graphql/graphql-js/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/graphql/graphql-js.git" + }, + "keywords": [ + "graphql", + "graphql-js" + ], + "engines": { + "node": "^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0" + }, + "publishConfig": { + "tag": "latest" + } +} diff --git a/node_modules/graphql/subscription/index.d.ts b/node_modules/graphql/subscription/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d11cf67eb331c6f9ef8ba38459c99e9117a3e4b6 --- /dev/null +++ b/node_modules/graphql/subscription/index.d.ts @@ -0,0 +1,25 @@ +/** + * NOTE: the `graphql/subscription` module has been deprecated with its + * exported functions integrated into the `graphql/execution` module, to + * better conform with the terminology of the GraphQL specification. + * + * For backwards compatibility, the `graphql/subscription` module + * currently re-exports the moved functions from the `graphql/execution` + * module. In v17, the `graphql/subscription` module will be dropped entirely. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + * @category Subscriptions + */ +import type { ExecutionArgs } from '../execution/execute'; +/** + * Deprecated legacy alias for ExecutionArgs retained by the subscription + * module. Use `ExecutionArgs` directly instead because SubscriptionArgs will be + * removed in v17. + * + * ExecutionArgs has been broadened to include all properties within SubscriptionArgs. + * The SubscriptionArgs type is retained for backwards compatibility. + * @deprecated use ExecutionArgs instead. Will be removed in v17 + */ +export interface SubscriptionArgs extends ExecutionArgs {} +export { subscribe, createSourceEventStream } from '../execution/subscribe'; diff --git a/node_modules/graphql/subscription/index.js b/node_modules/graphql/subscription/index.js new file mode 100644 index 0000000000000000000000000000000000000000..7d39b2db34544cf934aa67fa22cc1c005edd7571 --- /dev/null +++ b/node_modules/graphql/subscription/index.js @@ -0,0 +1,19 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'createSourceEventStream', { + enumerable: true, + get: function () { + return _subscribe.createSourceEventStream; + }, +}); +Object.defineProperty(exports, 'subscribe', { + enumerable: true, + get: function () { + return _subscribe.subscribe; + }, +}); + +var _subscribe = require('../execution/subscribe.js'); diff --git a/node_modules/graphql/subscription/index.mjs b/node_modules/graphql/subscription/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4a83ca1728b1bb34ffc8c4ec5d7df006f3449353 --- /dev/null +++ b/node_modules/graphql/subscription/index.mjs @@ -0,0 +1,25 @@ +/** + * NOTE: the `graphql/subscription` module has been deprecated with its + * exported functions integrated into the `graphql/execution` module, to + * better conform with the terminology of the GraphQL specification. + * + * For backwards compatibility, the `graphql/subscription` module + * currently re-exports the moved functions from the `graphql/execution` + * module. In v17, the `graphql/subscription` module will be dropped entirely. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + * @category Subscriptions + */ + +/** + * Deprecated legacy alias for ExecutionArgs retained by the subscription + * module. Use `ExecutionArgs` directly instead because SubscriptionArgs will be + * removed in v17. + * + * ExecutionArgs has been broadened to include all properties within SubscriptionArgs. + * The SubscriptionArgs type is retained for backwards compatibility. + * @deprecated use ExecutionArgs instead. Will be removed in v17 + */ +// eslint-disable-next-line @typescript-eslint/no-empty-interface +export { subscribe, createSourceEventStream } from '../execution/subscribe.mjs'; diff --git a/node_modules/graphql/type/assertName.d.ts b/node_modules/graphql/type/assertName.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..18f01a3610cceb3784647df47658c1d3bb40cd8a --- /dev/null +++ b/node_modules/graphql/type/assertName.d.ts @@ -0,0 +1,27 @@ +/** @category Names */ +/** + * Upholds the spec rules about naming. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertName } from 'graphql/type'; + * + * assertName('User'); // => 'User' + * assertName('123User'); // throws an error + * ``` + */ +export declare function assertName(name: string): string; +/** + * Upholds the spec rules about naming enum values. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertEnumValueName } from 'graphql/type'; + * + * assertEnumValueName('ACTIVE'); // => 'ACTIVE' + * assertEnumValueName('true'); // throws an error + * ``` + */ +export declare function assertEnumValueName(name: string): string; diff --git a/node_modules/graphql/type/assertName.js b/node_modules/graphql/type/assertName.js new file mode 100644 index 0000000000000000000000000000000000000000..985641233c3f73f35abe60bead2fac3b85f38ee0 --- /dev/null +++ b/node_modules/graphql/type/assertName.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.assertEnumValueName = assertEnumValueName; +exports.assertName = assertName; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _characterClasses = require('../language/characterClasses.js'); + +/** @category Names */ + +/** + * Upholds the spec rules about naming. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertName } from 'graphql/type'; + * + * assertName('User'); // => 'User' + * assertName('123User'); // throws an error + * ``` + */ +function assertName(name) { + name != null || (0, _devAssert.devAssert)(false, 'Must provide name.'); + typeof name === 'string' || + (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + + if (name.length === 0) { + throw new _GraphQLError.GraphQLError( + 'Expected name to be a non-empty string.', + ); + } + + for (let i = 1; i < name.length; ++i) { + if (!(0, _characterClasses.isNameContinue)(name.charCodeAt(i))) { + throw new _GraphQLError.GraphQLError( + `Names must only contain [_a-zA-Z0-9] but "${name}" does not.`, + ); + } + } + + if (!(0, _characterClasses.isNameStart)(name.charCodeAt(0))) { + throw new _GraphQLError.GraphQLError( + `Names must start with [_a-zA-Z] but "${name}" does not.`, + ); + } + + return name; +} +/** + * Upholds the spec rules about naming enum values. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertEnumValueName } from 'graphql/type'; + * + * assertEnumValueName('ACTIVE'); // => 'ACTIVE' + * assertEnumValueName('true'); // throws an error + * ``` + */ + +function assertEnumValueName(name) { + if (name === 'true' || name === 'false' || name === 'null') { + throw new _GraphQLError.GraphQLError( + `Enum values cannot be named: ${name}`, + ); + } + + return assertName(name); +} diff --git a/node_modules/graphql/type/assertName.mjs b/node_modules/graphql/type/assertName.mjs new file mode 100644 index 0000000000000000000000000000000000000000..697ec8ea797ef1f405627dd471fa5f1699a1a4b2 --- /dev/null +++ b/node_modules/graphql/type/assertName.mjs @@ -0,0 +1,61 @@ +/** @category Names */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { isNameContinue, isNameStart } from '../language/characterClasses.mjs'; +/** + * Upholds the spec rules about naming. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertName } from 'graphql/type'; + * + * assertName('User'); // => 'User' + * assertName('123User'); // throws an error + * ``` + */ + +export function assertName(name) { + name != null || devAssert(false, 'Must provide name.'); + typeof name === 'string' || devAssert(false, 'Expected name to be a string.'); + + if (name.length === 0) { + throw new GraphQLError('Expected name to be a non-empty string.'); + } + + for (let i = 1; i < name.length; ++i) { + if (!isNameContinue(name.charCodeAt(i))) { + throw new GraphQLError( + `Names must only contain [_a-zA-Z0-9] but "${name}" does not.`, + ); + } + } + + if (!isNameStart(name.charCodeAt(0))) { + throw new GraphQLError( + `Names must start with [_a-zA-Z] but "${name}" does not.`, + ); + } + + return name; +} +/** + * Upholds the spec rules about naming enum values. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertEnumValueName } from 'graphql/type'; + * + * assertEnumValueName('ACTIVE'); // => 'ACTIVE' + * assertEnumValueName('true'); // throws an error + * ``` + */ + +export function assertEnumValueName(name) { + if (name === 'true' || name === 'false' || name === 'null') { + throw new GraphQLError(`Enum values cannot be named: ${name}`); + } + + return assertName(name); +} diff --git a/node_modules/graphql/type/definition.d.ts b/node_modules/graphql/type/definition.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1fe39df6bea268d7ae1f63bc1f06d3bd45a154c --- /dev/null +++ b/node_modules/graphql/type/definition.d.ts @@ -0,0 +1,3387 @@ +/** @category Types */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { Path } from '../jsutils/Path'; +import type { PromiseOrValue } from '../jsutils/PromiseOrValue'; +import type { + EnumTypeDefinitionNode, + EnumTypeExtensionNode, + EnumValueDefinitionNode, + FieldDefinitionNode, + FieldNode, + FragmentDefinitionNode, + InputObjectTypeDefinitionNode, + InputObjectTypeExtensionNode, + InputValueDefinitionNode, + InterfaceTypeDefinitionNode, + InterfaceTypeExtensionNode, + ObjectTypeDefinitionNode, + ObjectTypeExtensionNode, + OperationDefinitionNode, + ScalarTypeDefinitionNode, + ScalarTypeExtensionNode, + UnionTypeDefinitionNode, + UnionTypeExtensionNode, + ValueNode, +} from '../language/ast'; +import type { GraphQLSchema } from './schema'; +/** These are all of the possible kinds of types. */ +export declare type GraphQLType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + >; +/** + * Returns true when the value is any GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is any GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * isType(GraphQLString); // => true + * isType(new GraphQLList(GraphQLString)); // => true + * isType(schema.getType('Query')); // => true + * isType('String'); // => false + * ``` + */ +export declare function isType(type: unknown): type is GraphQLType; +/** + * Returns the value as a GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const queryType = assertType(schema.getType('Query')); + * + * queryType.toString(); // => 'Query' + * assertType('Query'); // throws an error + * ``` + */ +export declare function assertType(type: unknown): GraphQLType; +/** + * There are predicates for each kind of GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * isScalarType(schema.getType('DateTime')); // => true + * isScalarType(schema.getType('Query')); // => false + * ``` + */ +export declare function isScalarType(type: unknown): type is GraphQLScalarType; +/** + * Returns the value as a GraphQLScalarType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * const dateTimeType = assertScalarType(schema.getType('DateTime')); + * + * dateTimeType.name; // => 'DateTime' + * assertScalarType(schema.getType('Query')); // throws an error + * ``` + */ +export declare function assertScalarType(type: unknown): GraphQLScalarType; +/** + * Returns true when the value is a GraphQLObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * isObjectType(schema.getType('User')); // => true + * isObjectType(schema.getType('ReviewInput')); // => false + * ``` + */ +export declare function isObjectType(type: unknown): type is GraphQLObjectType; +/** + * Returns the value as a GraphQLObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * const userType = assertObjectType(schema.getType('User')); + * + * Object.keys(userType.getFields()); // => ['name'] + * assertObjectType(schema.getType('ReviewInput')); // throws an error + * ``` + */ +export declare function assertObjectType(type: unknown): GraphQLObjectType; +/** + * Returns true when the value is a GraphQLInterfaceType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * isInterfaceType(schema.getType('Node')); // => true + * isInterfaceType(schema.getType('User')); // => false + * ``` + */ +export declare function isInterfaceType( + type: unknown, +): type is GraphQLInterfaceType; +/** + * Returns the value as a GraphQLInterfaceType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertInterfaceType(schema.getType('Node')); + * + * nodeType.name; // => 'Node' + * assertInterfaceType(schema.getType('User')); // throws an error + * ``` + */ +export declare function assertInterfaceType( + type: unknown, +): GraphQLInterfaceType; +/** + * Returns true when the value is a GraphQLUnionType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * isUnionType(schema.getType('Media')); // => true + * isUnionType(schema.getType('Photo')); // => false + * ``` + */ +export declare function isUnionType(type: unknown): type is GraphQLUnionType; +/** + * Returns the value as a GraphQLUnionType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const mediaType = assertUnionType(schema.getType('Media')); + * + * mediaType.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * assertUnionType(schema.getType('Photo')); // throws an error + * ``` + */ +export declare function assertUnionType(type: unknown): GraphQLUnionType; +/** + * Returns true when the value is a GraphQLEnumType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * isEnumType(schema.getType('Episode')); // => true + * isEnumType(schema.getType('Query')); // => false + * ``` + */ +export declare function isEnumType(type: unknown): type is GraphQLEnumType; +/** + * Returns the value as a GraphQLEnumType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * const episodeType = assertEnumType(schema.getType('Episode')); + * + * episodeType.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE'] + * assertEnumType(schema.getType('Query')); // throws an error + * ``` + */ +export declare function assertEnumType(type: unknown): GraphQLEnumType; +/** + * Returns true when the value is a GraphQLInputObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputObjectType(schema.getType('ReviewInput')); // => true + * isInputObjectType(schema.getType('Review')); // => false + * ``` + */ +export declare function isInputObjectType( + type: unknown, +): type is GraphQLInputObjectType; +/** + * Returns the value as a GraphQLInputObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputObjectType(schema.getType('ReviewInput')); + * + * Object.keys(inputType.getFields()); // => ['stars'] + * assertInputObjectType(schema.getType('Review')); // throws an error + * ``` + */ +export declare function assertInputObjectType( + type: unknown, +): GraphQLInputObjectType; +/** + * Returns true when the value is a GraphQLList. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLList. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isListType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * tags: [String!]! + * } + * `); + * + * const tagsField = schema.getQueryType()?.getFields().tags; + * + * isListType(new GraphQLList(GraphQLString)); // => true + * isListType(GraphQLString); // => false + * isListType(tagsField?.type); // => false + * ``` + */ +export declare function isListType( + type: GraphQLInputType, +): type is GraphQLList; +/** + * Returns true when the output type is a GraphQLList. + * @param type - The GraphQL output type to inspect. + * @returns True when the output type is a list type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { getNullableType, isListType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * tags: [String!]! + * } + * `); + * + * const tagsField = schema.getQueryType()?.getFields().tags; + * const nullableTagsType = getNullableType(tagsField?.type); + * + * isListType(nullableTagsType); // => true + * ``` + */ +export declare function isListType( + type: GraphQLOutputType, +): type is GraphQLList; +/** + * Returns true when the value is a GraphQLList. + * @param type - The value to inspect. + * @returns True when the value is a list type. + * @example + * ```ts + * import { isListType } from 'graphql/type'; + * + * isListType('[String]'); // => false + * isListType(null); // => false + * ``` + */ +export declare function isListType( + type: unknown, +): type is GraphQLList; +/** + * Returns the value as a GraphQLList, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLList. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; + * + * const listType = assertListType(new GraphQLList(GraphQLString)); + * + * listType.ofType; // => GraphQLString + * assertListType(GraphQLString); // throws an error + * ``` + */ +export declare function assertListType(type: unknown): GraphQLList; +/** + * Returns true when the value is a GraphQLNonNull. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLNonNull. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String! + * nickname: String + * } + * `); + * + * const fields = schema.getQueryType()?.getFields(); + * + * isNonNullType(new GraphQLNonNull(GraphQLString)); // => true + * isNonNullType(fields?.name.type); // => true + * isNonNullType(fields?.nickname.type); // => false + * ``` + */ +export declare function isNonNullType( + type: GraphQLInputType, +): type is GraphQLNonNull; +/** + * Returns true when the output type is a GraphQLNonNull. + * @param type - The GraphQL output type to inspect. + * @returns True when the output type is a non-null type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isNonNullType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String! + * nickname: String + * } + * `); + * + * const fields = schema.getQueryType()?.getFields(); + * + * isNonNullType(fields?.name.type); // => true + * isNonNullType(fields?.nickname.type); // => false + * ``` + */ +export declare function isNonNullType( + type: GraphQLOutputType, +): type is GraphQLNonNull; +/** + * Returns true when the value is a GraphQLNonNull. + * @param type - The value to inspect. + * @returns True when the value is a non-null type. + * @example + * ```ts + * import { isNonNullType } from 'graphql/type'; + * + * isNonNullType('String!'); // => false + * isNonNullType(null); // => false + * ``` + */ +export declare function isNonNullType( + type: unknown, +): type is GraphQLNonNull; +/** + * Returns the value as a GraphQLNonNull, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLNonNull. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; + * + * const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); + * + * nonNullType.ofType; // => GraphQLString + * assertNonNullType(GraphQLString); // throws an error + * ``` + */ +export declare function assertNonNullType( + type: unknown, +): GraphQLNonNull; +/** These types may be used as input types for arguments and directives. */ +export declare type GraphQLInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + >; +/** + * Returns true when the value can be used as a GraphQL input type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputType(schema.getType('ReviewInput')); // => true + * isInputType(schema.getType('Review')); // => false + * ``` + */ +export declare function isInputType(type: unknown): type is GraphQLInputType; +/** + * Returns the value as a GraphQL input type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputType(schema.getType('ReviewInput')); + * + * inputType.toString(); // => 'ReviewInput' + * assertInputType(schema.getType('Review')); // throws an error + * ``` + */ +export declare function assertInputType(type: unknown): GraphQLInputType; +/** These types may be used as output types as the result of fields. */ +export declare type GraphQLOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + >; +/** + * Returns true when the value can be used as a GraphQL output type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isOutputType(schema.getType('Review')); // => true + * isOutputType(schema.getType('ReviewInput')); // => false + * ``` + */ +export declare function isOutputType(type: unknown): type is GraphQLOutputType; +/** + * Returns the value as a GraphQL output type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const outputType = assertOutputType(schema.getType('Review')); + * + * outputType.toString(); // => 'Review' + * assertOutputType(schema.getType('ReviewInput')); // throws an error + * ``` + */ +export declare function assertOutputType(type: unknown): GraphQLOutputType; +/** These types may describe types which may be leaf values. */ +export declare type GraphQLLeafType = GraphQLScalarType | GraphQLEnumType; +/** + * Returns true when the value is a GraphQL scalar or enum type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL scalar or enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * isLeafType(schema.getType('Episode')); // => true + * isLeafType(schema.getType('String')); // => true + * isLeafType(schema.getType('Review')); // => false + * ``` + */ +export declare function isLeafType(type: unknown): type is GraphQLLeafType; +/** + * Returns the value as a GraphQL leaf type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL leaf type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * const episodeType = assertLeafType(schema.getType('Episode')); + * + * episodeType.toString(); // => 'Episode' + * assertLeafType(schema.getType('Review')); // throws an error + * ``` + */ +export declare function assertLeafType(type: unknown): GraphQLLeafType; +/** These types may describe the parent context of a selection set. */ +export declare type GraphQLCompositeType = + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; +/** + * Returns true when the value is a GraphQL object, interface, or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL object, interface, or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isCompositeType(schema.getType('User')); // => true + * isCompositeType(schema.getType('Node')); // => true + * isCompositeType(schema.getType('SearchResult')); // => true + * isCompositeType(schema.getType('String')); // => false + * ``` + */ +export declare function isCompositeType( + type: unknown, +): type is GraphQLCompositeType; +/** + * Returns the value as a GraphQL composite type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL composite type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const userType = assertCompositeType(schema.getType('User')); + * + * userType.toString(); // => 'User' + * assertCompositeType(schema.getType('String')); // throws an error + * ``` + */ +export declare function assertCompositeType( + type: unknown, +): GraphQLCompositeType; +/** These types may describe the parent context of a selection set. */ +export declare type GraphQLAbstractType = + | GraphQLInterfaceType + | GraphQLUnionType; +/** + * Returns true when the value is a GraphQL interface or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL interface or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isAbstractType(schema.getType('Node')); // => true + * isAbstractType(schema.getType('SearchResult')); // => true + * isAbstractType(schema.getType('User')); // => false + * ``` + */ +export declare function isAbstractType( + type: unknown, +): type is GraphQLAbstractType; +/** + * Returns the value as a GraphQL abstract type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertAbstractType(schema.getType('Node')); + * + * nodeType.toString(); // => 'Node' + * assertAbstractType(schema.getType('User')); // throws an error + * ``` + */ +export declare function assertAbstractType(type: unknown): GraphQLAbstractType; +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * @typeParam T - The GraphQL type wrapped by this list type. + * @example + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ +export declare class GraphQLList { + /** The type wrapped by this list or non-null type. */ + readonly ofType: T; + /** + * Creates a GraphQLList instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.ofType; // => GraphQLString + * String(stringList); // => '[String]' + * ``` + */ + constructor(ofType: T); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * const requiredStringList = new GraphQLList(new GraphQLNonNull(GraphQLString)); + * + * stringList.toString(); // => '[String]' + * requiredStringList.toString(); // => '[String!]' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.toJSON(); // => '[String]' + * JSON.stringify({ type: stringList }); // => '{"type":"[String]"}' + * ``` + */ + toJSON(): string; +} +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * @typeParam T - The nullable GraphQL type wrapped by this non-null type. + * @example + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * + * Note: the enforcement of non-nullability occurs within the executor. + */ +export declare class GraphQLNonNull { + /** The type wrapped by this list or non-null type. */ + readonly ofType: T; + /** + * Creates a GraphQLNonNull instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.ofType; // => GraphQLString + * String(requiredString); // => 'String!' + * ``` + */ + constructor(ofType: T); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * const requiredStringList = new GraphQLNonNull( + * new GraphQLList(GraphQLString), + * ); + * + * requiredString.toString(); // => 'String!' + * requiredStringList.toString(); // => '[String]!' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.toJSON(); // => 'String!' + * JSON.stringify({ type: requiredString }); // => '{"type":"String!"}' + * ``` + */ + toJSON(): string; +} +/** These types wrap and modify other types */ +export declare type GraphQLWrappingType = + | GraphQLList + | GraphQLNonNull; +/** + * Returns true when the value is a GraphQL list or non-null wrapper type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL list or non-null wrapper type. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * isWrappingType, + * } from 'graphql/type'; + * + * isWrappingType(new GraphQLList(GraphQLString)); // => true + * isWrappingType(new GraphQLNonNull(GraphQLString)); // => true + * isWrappingType(GraphQLString); // => false + * ``` + */ +export declare function isWrappingType( + type: unknown, +): type is GraphQLWrappingType; +/** + * Returns the value as a GraphQL wrapping type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL wrapping type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; + * + * const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); + * + * wrappingType.toString(); // => '[String]' + * assertWrappingType(GraphQLString); // throws an error + * ``` + */ +export declare function assertWrappingType(type: unknown): GraphQLWrappingType; +/** These types can all accept null as a value. */ +export declare type GraphQLNullableType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; +/** + * Returns true when the value is a GraphQL type that can accept null. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL type that can accept null. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; + * + * isNullableType(GraphQLString); // => true + * isNullableType(new GraphQLNonNull(GraphQLString)); // => false + * isNullableType(null); // => false + * ``` + */ +export declare function isNullableType( + type: unknown, +): type is GraphQLNullableType; +/** + * Returns the value as a nullable GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a nullable GraphQL type. + * @example + * ```ts + * import { + * GraphQLNonNull, + * GraphQLString, + * assertNullableType, + * } from 'graphql/type'; + * + * const nullableType = assertNullableType(GraphQLString); + * + * nullableType; // => GraphQLString + * assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error + * ``` + */ +export declare function assertNullableType(type: unknown): GraphQLNullableType; +/** + * Returns the nullable type. + * @param type - The GraphQL type to inspect. + * @returns The nullable type after removing one non-null wrapper, if present. + * @example + * ```ts + * import { getNullableType } from 'graphql/type'; + * + * getNullableType(null); // => undefined + * getNullableType(undefined); // => undefined + * ``` + */ +export declare function getNullableType(type: undefined | null): void; +/** + * Returns the nullable type after removing one non-null wrapper. + * @param type - A nullable type or non-null wrapper. + * @returns The nullable type after removing one non-null wrapper, if present. + * @typeParam T - The nullable GraphQL type returned after removing one non-null wrapper. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * getNullableType, + * } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * const stringList = new GraphQLList(GraphQLString); + * + * getNullableType(requiredString); // => GraphQLString + * getNullableType(stringList); // => stringList + * ``` + */ +export declare function getNullableType( + type: T | GraphQLNonNull, +): T; +/** + * Returns the nullable type after removing one non-null wrapper. + * @param type - The GraphQL type to inspect. + * @returns The nullable type after removing one non-null wrapper, if present. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * getNullableType, + * } from 'graphql/type'; + * + * const requiredStringList = new GraphQLNonNull( + * new GraphQLList(GraphQLString), + * ); + * + * getNullableType(requiredStringList).toString(); // => '[String]' + * getNullableType(GraphQLString); // => GraphQLString + * ``` + */ +export declare function getNullableType( + type: Maybe, +): GraphQLNullableType | undefined; +/** These named types do not include modifiers like List or NonNull. */ +export declare type GraphQLNamedType = + | GraphQLNamedInputType + | GraphQLNamedOutputType; +/** A named GraphQL type that can be used as an input type. */ +export declare type GraphQLNamedInputType = + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType; +/** A named GraphQL type that can be used as an output type. */ +export declare type GraphQLNamedOutputType = + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType; +/** + * Returns true when the value is a GraphQL named type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; + * + * isNamedType(GraphQLString); // => true + * isNamedType(new GraphQLList(GraphQLString)); // => false + * isNamedType(null); // => false + * ``` + */ +export declare function isNamedType(type: unknown): type is GraphQLNamedType; +/** + * Returns the value as a GraphQL named type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; + * + * const namedType = assertNamedType(GraphQLString); + * + * namedType.name; // => 'String' + * assertNamedType(new GraphQLList(GraphQLString)); // throws an error + * ``` + */ +export declare function assertNamedType(type: unknown): GraphQLNamedType; +/** + * Returns the named type. + * @param type - The GraphQL type to inspect. + * @returns The named type after unwrapping all list and non-null wrappers. + * @example + * ```ts + * import { getNamedType } from 'graphql/type'; + * + * getNamedType(null); // => undefined + * getNamedType(undefined); // => undefined + * ``` + */ +export declare function getNamedType(type: undefined | null): void; +/** + * Returns the named input type after unwrapping all list and non-null wrappers. + * @param type - The GraphQL input type to inspect. + * @returns The named input type after unwrapping all wrappers. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { getNamedType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * review(input: [ReviewInput!]!): Boolean + * } + * `); + * + * const inputArg = schema.getQueryType()?.getFields().review.args[0]; + * + * getNamedType(inputArg?.type).toString(); // => 'ReviewInput' + * ``` + */ +export declare function getNamedType( + type: GraphQLInputType, +): GraphQLNamedInputType; +/** + * Returns the named output type after unwrapping all list and non-null wrappers. + * @param type - The GraphQL output type to inspect. + * @returns The named output type after unwrapping all wrappers. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { getNamedType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * users: [User!]! + * } + * `); + * + * const usersField = schema.getQueryType()?.getFields().users; + * + * getNamedType(usersField?.type).toString(); // => 'User' + * ``` + */ +export declare function getNamedType( + type: GraphQLOutputType, +): GraphQLNamedOutputType; +/** + * Returns the named type after unwrapping all list and non-null wrappers. + * @param type - The GraphQL type to inspect. + * @returns The named type after unwrapping all wrappers. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * getNamedType, + * } from 'graphql/type'; + * + * const nestedType = new GraphQLNonNull( + * new GraphQLList(new GraphQLNonNull(GraphQLString)), + * ); + * + * getNamedType(nestedType); // => GraphQLString + * ``` + */ +export declare function getNamedType(type: GraphQLType): GraphQLNamedType; +/** + * Returns the named type after unwrapping all list and non-null wrappers. + * @param type - The GraphQL type to inspect. + * @returns The named type after unwrapping all wrappers, or undefined for nullish input. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLString, + * getNamedType, + * } from 'graphql/type'; + * + * getNamedType(new GraphQLList(GraphQLString)); // => GraphQLString + * getNamedType(undefined); // => undefined + * ``` + */ +export declare function getNamedType( + type: Maybe, +): GraphQLNamedType | undefined; +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + * @typeParam T - The element type returned by the thunk or array. + */ +export declare type ThunkReadonlyArray = + | (() => ReadonlyArray) + | ReadonlyArray; +/** + * A thunk that resolves to an object map. + * @typeParam T - Value type stored in the object map. + */ +export declare type ThunkObjMap = (() => ObjMap) | ObjMap; +/** + * Resolves a thunked readonly array. + * @param thunk - The thunk or value to resolve. + * @returns The resolved readonly array. + * @typeParam T - The element type resolved from the thunk or array. + * @example + * ```ts + * import { GraphQLString, resolveReadonlyArrayThunk } from 'graphql/type'; + * + * const lazyFields = resolveReadonlyArrayThunk(() => [GraphQLString]); + * const fields = resolveReadonlyArrayThunk([GraphQLString]); + * + * lazyFields; // => [GraphQLString] + * fields; // => [GraphQLString] + * ``` + */ +export declare function resolveReadonlyArrayThunk( + thunk: ThunkReadonlyArray, +): ReadonlyArray; +/** + * Resolves a thunked object map. + * @param thunk - The thunk or value to resolve. + * @returns The resolved object map. + * @typeParam T - The object-map value type resolved from the thunk or map. + * @example + * ```ts + * import { GraphQLString, resolveObjMapThunk } from 'graphql/type'; + * + * const lazyFields = resolveObjMapThunk(() => ({ name: GraphQLString })); + * const fields = resolveObjMapThunk({ name: GraphQLString }); + * + * lazyFields.name; // => GraphQLString + * fields.name; // => GraphQLString + * ``` + */ +export declare function resolveObjMapThunk(thunk: ThunkObjMap): ObjMap; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLScalarTypeExtensions { + [attributeName: string]: unknown; +} +/** + * Scalar Type Definition + * + * Scalar types define the leaf values of a GraphQL response and the input + * values accepted by arguments and input object fields. A scalar type has a + * name and coercion functions that validate and convert runtime values and + * GraphQL literals. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. Prefer validating inputs before + * execution so clients receive input diagnostics before result coercion fails. + * @typeParam TInternal - The internal runtime representation accepted by this scalar. + * @typeParam TExternal - The serialized representation exposed in GraphQL results. + * @example + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize: (value) => { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ +export declare class GraphQLScalarType< + TInternal = unknown, + TExternal = TInternal, +> { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** URL identifying the behavior specified for this custom scalar. */ + specifiedByURL: Maybe; + /** Function that converts internal values to externally visible scalar values. */ + serialize: GraphQLScalarSerializer; + /** Function that converts variable input into this scalar's internal value. */ + parseValue: GraphQLScalarValueParser; + /** Function that converts AST input literals into this scalar's internal value. */ + parseLiteral: GraphQLScalarLiteralParser; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + /** + * Creates a GraphQLScalarType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { GraphQLScalarType } from 'graphql/type'; + * + * const document = parse(` + * "Odd integer values." + * scalar Odd @specifiedBy(url: "https://example.com/odd") + * + * extend scalar Odd @specifiedBy(url: "https://example.com/odd-v2") + * `); + * + * const Odd = new GraphQLScalarType({ + * name: 'Odd', + * description: 'Odd integer values.', + * specifiedByURL: 'https://example.com/odd', + * serialize: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only serialize odd numbers.'); + * } + * return value; + * }, + * parseValue: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only parse odd numbers.'); + * } + * return value; + * }, + * parseLiteral: (ast) => { + * if (ast.kind !== Kind.INT) { + * throw new TypeError('Odd can only parse integer literals.'); + * } + * const value = Number(ast.value); + * if (value % 2 === 0) { + * throw new TypeError('Odd can only parse odd integer literals.'); + * } + * return value; + * }, + * extensions: { numeric: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Odd.description; // => 'Odd integer values.' + * Odd.specifiedByURL; // => 'https://example.com/odd' + * Odd.serialize(3); // => 3 + * Odd.parseValue(5); // => 5 + * Odd.extensions; // => { numeric: true } + * ``` + */ + constructor(config: Readonly>); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const Url = new GraphQLScalarType({ + * name: 'Url', + * description: 'An absolute URL string.', + * specifiedByURL: 'https://url.spec.whatwg.org/', + * }); + * + * const config = Url.toConfig(); + * const UrlCopy = new GraphQLScalarType(config); + * + * config.name; // => 'Url' + * config.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * UrlCopy.name; // => Url.name + * ``` + */ + toConfig(): GraphQLScalarTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this scalar type. + * @returns The schema coordinate for this scalar type. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toString(); // => 'DateTime' + * String(DateTime); // => 'DateTime' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toJSON(); // => 'DateTime' + * JSON.stringify({ type: DateTime }); // => '{"type":"DateTime"}' + * ``` + */ + toJSON(): string; +} +/** + * Serializes a runtime value as a scalar output value. + * @typeParam TExternal - The serialized representation returned for GraphQL results. + */ +export declare type GraphQLScalarSerializer = ( + outputValue: unknown, +) => TExternal; +/** + * Parses a runtime input value as a scalar input value. + * @typeParam TInternal - The internal runtime representation produced from variable input. + */ +export declare type GraphQLScalarValueParser = ( + inputValue: unknown, +) => TInternal; +/** + * Parses a GraphQL value literal as a scalar input value. + * @typeParam TInternal - The internal runtime representation produced from literal input. + */ +export declare type GraphQLScalarLiteralParser = ( + valueNode: ValueNode, + variables?: Maybe>, +) => TInternal; +/** + * Configuration used to construct a GraphQLScalarType. + * @typeParam TInternal - The internal runtime representation accepted by this scalar. + * @typeParam TExternal - The serialized representation exposed in GraphQL results. + */ +export interface GraphQLScalarTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** URL identifying the behavior specified for this custom scalar. */ + specifiedByURL?: Maybe; + /** Serializes an internal value to include in a response. */ + serialize?: GraphQLScalarSerializer; + /** Parses an externally provided value to use as an input. */ + parseValue?: GraphQLScalarValueParser; + /** Parses an externally provided literal value to use as an input. */ + parseLiteral?: GraphQLScalarLiteralParser; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +interface GraphQLScalarTypeNormalizedConfig + extends GraphQLScalarTypeConfig { + serialize: GraphQLScalarSerializer; + parseValue: GraphQLScalarValueParser; + parseLiteral: GraphQLScalarLiteralParser; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + * We've provided these template arguments because this is an open type and + * you may find them useful. + * @typeParam _TSource - Reserved source type parameter for extension typing. + * @typeParam _TContext - Reserved context type parameter for extension typing. + */ +export interface GraphQLObjectTypeExtensions<_TSource = any, _TContext = any> { + [attributeName: string]: unknown; +} +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @example + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve: (obj) => { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * @example + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ +export declare class GraphQLObjectType { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Predicate used to determine whether a runtime value belongs to this object type. */ + isTypeOf: Maybe>; + /** Custom extension fields reserved for users. */ + extensions: Readonly>; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + private _fields; + private _interfaces; + /** + * Creates a GraphQLObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Configure an object type with interfaces, fields, arguments, and metadata. + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInterfaceType, + * GraphQLNonNull, + * GraphQLObjectType, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * type User implements Node { + * id: ID! + * name(format: String = "short"): String + * } + * + * extend type User { + * displayName: String + * } + * `); + * const definition = document.definitions[0]; + * const nameField = definition.fields[1]; + * const formatArg = nameField.arguments[0]; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const User = new GraphQLObjectType({ + * name: 'User', + * description: 'A registered user.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * name: { + * description: 'The formatted user name.', + * type: GraphQLString, + * args: { + * format: { + * description: 'Controls the name format.', + * type: GraphQLString, + * defaultValue: 'short', + * deprecationReason: 'Use locale instead.', + * extensions: { public: true }, + * astNode: formatArg, + * }, + * }, + * resolve: (user, { format }) => { + * return format === 'long' ? user.fullName : user.name; + * }, + * deprecationReason: 'Use displayName.', + * extensions: { cacheSeconds: 60 }, + * astNode: nameField, + * }, + * }, + * isTypeOf: (value) => { + * return typeof value === 'object' && value != null && 'id' in value; + * }, + * extensions: { entity: 'User' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * User.name; // => 'User' + * User.getInterfaces(); // => [Node] + * Object.keys(User.getFields()); // => ['id', 'name'] + * User.getFields().name.args[0].defaultValue; // => 'short' + * User.extensions; // => { entity: 'User' } + * ``` + * @example + * ```ts + * // This variant configures a subscription field with subscribe and resolve functions. + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { + * greeting: { + * type: GraphQLString, + * subscribe: async function* () { + * yield { greeting: 'Hello!' }; + * }, + * resolve: (event) => { + * return event.greeting; + * }, + * }, + * }, + * }); + * + * typeof Subscription.getFields().greeting.subscribe; // => 'function' + * ``` + */ + constructor(config: Readonly>); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * const fields = User.getFields(); + * + * Object.keys(fields); // => ['id', 'name'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + getFields(): GraphQLFieldMap; + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.getInterfaces().map((type) => type.name); // => ['Node'] + * ``` + */ + getInterfaces(): ReadonlyArray; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = User.toConfig(); + * const UserCopy = new GraphQLObjectType(config); + * + * config.fields.name.type; // => GraphQLString + * UserCopy.getFields().name.type; // => GraphQLString + * ``` + */ + toConfig(): GraphQLObjectTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this object type. + * @returns The schema coordinate for this object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.toString(); // => 'User' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { name: { type: GraphQLString } }, + * }); + * + * User.toJSON(); // => 'User' + * JSON.stringify({ type: User }); // => '{"type":"User"}' + * ``` + */ + toJSON(): string; +} +/** @internal */ +export declare function defineArguments( + config: GraphQLFieldConfigArgumentMap, +): ReadonlyArray; +/** @internal */ +export declare function argsToArgsConfig( + args: ReadonlyArray, +): GraphQLFieldConfigArgumentMap; +/** + * Configuration used to construct a GraphQLObjectType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export interface GraphQLObjectTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Interfaces implemented by this object or interface type. */ + interfaces?: ThunkReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + fields: ThunkObjMap>; + /** Predicate used to determine whether a runtime value belongs to this object type. */ + isTypeOf?: Maybe>; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +interface GraphQLObjectTypeNormalizedConfig + extends GraphQLObjectTypeConfig { + interfaces: ReadonlyArray; + fields: GraphQLFieldConfigMap; + extensions: Readonly>; + extensionASTNodes: ReadonlyArray; +} +/** + * Resolves the concrete object type for an abstract GraphQL type. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export declare type GraphQLTypeResolver = ( + value: TSource, + context: TContext, + info: GraphQLResolveInfo, + abstractType: GraphQLAbstractType, +) => PromiseOrValue; +/** + * Checks whether a runtime value belongs to a GraphQL object type. + * @typeParam TSource - Source object type tested against this object type. + * @typeParam TContext - Context object type passed to resolvers. + */ +export declare type GraphQLIsTypeOfFn = ( + source: TSource, + context: TContext, + info: GraphQLResolveInfo, +) => PromiseOrValue; +/** + * Resolves the runtime value for a GraphQL field. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @typeParam TArgs - Argument object type passed to resolvers. + * @typeParam TResult - Result value type. + */ +export declare type GraphQLFieldResolver< + TSource, + TContext, + TArgs = any, + TResult = unknown, +> = ( + source: TSource, + args: TArgs, + context: TContext, + info: GraphQLResolveInfo, +) => TResult; +/** Information about the currently executing GraphQL field. */ +export interface GraphQLResolveInfo { + /** The field name referenced by this schema coordinate. */ + readonly fieldName: string; + /** AST field nodes that contributed to the current field execution. */ + readonly fieldNodes: ReadonlyArray; + /** GraphQL output type declared for the current field. */ + readonly returnType: GraphQLOutputType; + /** Object type that owns the current field. */ + readonly parentType: GraphQLObjectType; + /** Response path where this error occurred during execution. */ + readonly path: Path; + /** The schema used for validation or execution. */ + readonly schema: GraphQLSchema; + /** Fragment definitions in the operation document keyed by fragment name. */ + readonly fragments: ObjMap; + /** Initial root value passed to the operation. */ + readonly rootValue: unknown; + /** The operation selected for execution. */ + readonly operation: OperationDefinitionNode; + /** Runtime variable values keyed by variable name. */ + readonly variableValues: { + [variable: string]: unknown; + }; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + * We've provided these template arguments because this is an open type and + * you may find them useful. + * @typeParam _TSource - Reserved source type parameter for extension typing. + * @typeParam _TContext - Reserved context type parameter for extension typing. + * @typeParam _TArgs - Reserved argument type parameter for extension typing. + */ +export interface GraphQLFieldExtensions<_TSource, _TContext, _TArgs = any> { + [attributeName: string]: unknown; +} +/** + * Configuration used to define a GraphQL field. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @typeParam TArgs - Argument object type passed to resolvers. + */ +export interface GraphQLFieldConfig { + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLOutputType; + /** Arguments accepted by this field or directive. */ + args?: GraphQLFieldConfigArgumentMap; + /** Resolver function used to produce this field value. */ + resolve?: GraphQLFieldResolver; + /** Resolver function used to create a subscription event stream for this field. */ + subscribe?: GraphQLFieldResolver; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason?: Maybe; + /** Custom extension fields reserved for users. */ + extensions?: Maybe< + Readonly> + >; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; +} +/** A map of argument names to argument configuration objects. */ +export declare type GraphQLFieldConfigArgumentMap = + ObjMap; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLArgumentExtensions { + [attributeName: string]: unknown; +} +/** Configuration used to define a GraphQL argument. */ +export interface GraphQLArgumentConfig { + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLInputType; + /** Default value used when no explicit value is supplied. */ + defaultValue?: unknown; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason?: Maybe; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; +} +/** + * A map of field names to field configuration objects. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export declare type GraphQLFieldConfigMap = ObjMap< + GraphQLFieldConfig +>; +/** + * A resolved GraphQL field definition. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @typeParam TArgs - Argument object type passed to resolvers. + */ +export interface GraphQLField { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLOutputType; + /** Arguments accepted by this field or directive. */ + args: ReadonlyArray; + /** Resolver function used to produce this field value. */ + resolve?: GraphQLFieldResolver; + /** Resolver function used to create a subscription event stream for this field. */ + subscribe?: GraphQLFieldResolver; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly>; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; +} +/** A resolved GraphQL argument definition. */ +export interface GraphQLArgument { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLInputType; + /** Default value used when no explicit value is supplied. */ + defaultValue: unknown; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; +} +/** + * Returns true when the argument is non-null and has no default value. + * @param arg - The argument definition to inspect. + * @returns True when the argument is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredArgument, + * } from 'graphql/type'; + * + * const requiredArgument = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalArgument = { name: 'name', type: GraphQLString }; + * const argumentWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredArgument(requiredArgument); // => true + * isRequiredArgument(optionalArgument); // => false + * isRequiredArgument(argumentWithDefault); // => false + * ``` + */ +export declare function isRequiredArgument(arg: GraphQLArgument): boolean; +/** + * A map of field names to resolved field definitions. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export declare type GraphQLFieldMap = ObjMap< + GraphQLField +>; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInterfaceTypeExtensions { + [attributeName: string]: unknown; +} +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * @example + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ +export declare class GraphQLInterfaceType { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Function that resolves the concrete object type for this abstract type. */ + resolveType: Maybe>; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + private _fields; + private _interfaces; + /** + * Creates a GraphQLInterfaceType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const document = parse(` + * interface Node { + * id: ID! + * } + * + * interface Resource implements Node { + * id: ID! + * } + * + * extend interface Resource { + * url: String + * } + * `); + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const Resource = new GraphQLInterfaceType({ + * name: 'Resource', + * description: 'An addressable resource.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'url' in value + * ? 'WebPage' + * : null; + * }, + * extensions: { abstract: true }, + * astNode: document.definitions[1], + * extensionASTNodes: [ document.definitions[2] ], + * }); + * + * Resource.name; // => 'Resource' + * Resource.getInterfaces(); // => [Node] + * Object.keys(Resource.getFields()); // => ['id'] + * Resource.extensions; // => { abstract: true } + * ``` + */ + constructor(config: Readonly>); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const fields = Node.getFields(); + * + * Object.keys(fields); // => ['id'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + getFields(): GraphQLFieldMap; + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * image: Image + * } + * `); + * + * const Image = assertInterfaceType(schema.getType('Image')); + * + * Image.getInterfaces().map((type) => type.name); // => ['Resource'] + * ``` + */ + getInterfaces(): ReadonlyArray; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const config = Node.toConfig(); + * const NodeCopy = new GraphQLInterfaceType(config); + * + * String(config.fields.id.type); // => 'ID!' + * String(NodeCopy.getFields().id.type); // => 'ID!' + * ``` + */ + toConfig(): GraphQLInterfaceTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this interface type. + * @returns The schema coordinate for this interface type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * + * Node.toString(); // => 'Node' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInterfaceType, GraphQLString } from 'graphql/type'; + * + * const Named = new GraphQLInterfaceType({ + * name: 'Named', + * fields: { name: { type: GraphQLString } }, + * }); + * + * Named.toJSON(); // => 'Named' + * JSON.stringify({ type: Named }); // => '{"type":"Named"}' + * ``` + */ + toJSON(): string; +} +/** + * Configuration used to construct a GraphQLInterfaceType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export interface GraphQLInterfaceTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Interfaces implemented by this object or interface type. */ + interfaces?: ThunkReadonlyArray; + /** Fields declared by this object, interface, input object, or literal. */ + fields: ThunkObjMap>; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe>; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +/** @internal */ +export interface GraphQLInterfaceTypeNormalizedConfig + extends GraphQLInterfaceTypeConfig { + interfaces: ReadonlyArray; + fields: GraphQLFieldConfigMap; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLUnionTypeExtensions { + [attributeName: string]: unknown; +} +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * @example + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [DogType, CatType], + * resolveType: (value) => { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ +export declare class GraphQLUnionType { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Function that resolves the concrete object type for this abstract type. */ + resolveType: Maybe>; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + private _types; + /** + * Creates a GraphQLUnionType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const document = parse(` + * union Media = Photo | Video + * + * extend union Media = Audio + * `); + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * + * const Media = new GraphQLUnionType({ + * name: 'Media', + * description: 'Media that can appear in a search result.', + * types: [Photo, Video], + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'duration' in value + * ? 'Video' + * : 'Photo'; + * }, + * extensions: { searchable: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Media.description; // => 'Media that can appear in a search result.' + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * Media.extensions; // => { searchable: true } + * ``` + */ + constructor(config: Readonly>); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the object types included in this union. + * @returns The union member object types. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const Media = assertUnionType(schema.getType('Media')); + * + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + getTypes(): ReadonlyArray; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * const Media = new GraphQLUnionType({ + * name: 'Media', + * types: [Photo, Video], + * }); + * + * const config = Media.toConfig(); + * const MediaCopy = new GraphQLUnionType(config); + * + * MediaCopy.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + toConfig(): GraphQLUnionTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this union type. + * @returns The schema coordinate for this union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * union SearchResult = Photo + * + * type Query { + * search: [SearchResult] + * } + * `); + * + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * SearchResult.toString(); // => 'SearchResult' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const SearchResult = new GraphQLUnionType({ + * name: 'SearchResult', + * types: [Photo], + * }); + * + * SearchResult.toJSON(); // => 'SearchResult' + * JSON.stringify({ type: SearchResult }); // => '{"type":"SearchResult"}' + * ``` + */ + toJSON(): string; +} +/** + * Configuration used to construct a GraphQLUnionType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ +export interface GraphQLUnionTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Object types that belong to this union type. */ + types: ThunkReadonlyArray; + /** + * Optionally provide a custom type resolver function. If one is not provided, + * the default implementation will call `isTypeOf` on each implementing + * Object type. + */ + resolveType?: Maybe>; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +interface GraphQLUnionTypeNormalizedConfig + extends GraphQLUnionTypeConfig { + types: ReadonlyArray; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLEnumTypeExtensions { + [attributeName: string]: unknown; +} +/** + * Enum Type Definition + * + * Enum types define leaf values whose serialized form is one of a fixed set + * of GraphQL enum names. Internally, enum values can map to any runtime value, + * often integers. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGBType.getValue('GREEN')?.value; // => 1 + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export declare class GraphQLEnumType { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + private _values; + private _valueLookup; + private _nameLookup; + /** + * Creates a GraphQLEnumType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const document = parse(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * extend enum Episode { + * FORCE_AWAKENS + * } + * `); + * const definition = document.definitions[0]; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * description: 'A Star Wars film episode.', + * values: { + * NEW_HOPE: { + * value: 4, + * description: 'Released in 1977.', + * extensions: { trilogy: 'original' }, + * astNode: definition.values[0], + * }, + * EMPIRE: { value: 5, astNode: definition.values[1] }, + * JEDI: { + * value: 6, + * deprecationReason: 'Use RETURN_OF_THE_JEDI.', + * astNode: definition.values[2], + * }, + * }, + * extensions: { catalog: 'films' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Episode.description; // => 'A Star Wars film episode.' + * Episode.serialize(5); // => 'EMPIRE' + * Episode.parseValue('JEDI'); // => 6 + * Episode.getValue('JEDI').deprecationReason; // => 'Use RETURN_OF_THE_JEDI.' + * Episode.extensions; // => { catalog: 'films' } + * ``` + */ + constructor(config: Readonly); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the values defined by this enum type. + * @returns Enum value definitions in schema order. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE', 'JEDI'] + * ``` + */ + getValues(): ReadonlyArray; + /** + * Returns the enum value definition for a value name. + * @param name - The GraphQL name to look up. + * @returns The matching enum value definition, if it exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValue('EMPIRE')?.name; // => 'EMPIRE' + * Episode.getValue('JEDI'); // => undefined + * ``` + */ + getValue(name: string): Maybe; + /** + * Serializes a runtime enum value as a GraphQL enum name. + * @param outputValue - Runtime enum value to serialize. + * @returns The GraphQL enum name for the runtime value. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.serialize(1); // => 'GREEN' + * RGB.serialize(3); // throws an error + * ``` + */ + serialize(outputValue: unknown): Maybe; + /** + * Parses a GraphQL enum name from variable input. + * @param inputValue - Runtime input value to parse. + * @returns The internal enum value represented by the input name. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseValue('BLUE'); // => 2 + * RGB.parseValue('PURPLE'); // throws an error + * RGB.parseValue(2); // throws an error + * ``` + */ + parseValue(inputValue: unknown): Maybe; + /** + * Parses a GraphQL enum name from an AST value literal. + * @param valueNode - AST value literal to parse. + * @param _variables - Runtime variable values; ignored because enum literals cannot contain variables. + * @returns The internal enum value represented by the literal. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseLiteral(parseValue('RED')); // => 0 + * RGB.parseLiteral(parseValue('"RED"')); // throws an error + * ``` + */ + parseLiteral( + valueNode: ValueNode, + _variables: Maybe>, + ): Maybe; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * const config = RGB.toConfig(); + * const RGBCopy = new GraphQLEnumType(config); + * + * config.values.GREEN.value; // => 1 + * RGBCopy.serialize(2); // => 'BLUE' + * ``` + */ + toConfig(): GraphQLEnumTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this enum type. + * @returns The schema coordinate for this enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.toString(); // => 'Episode' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * values: { + * NEW_HOPE: {}, + * }, + * }); + * + * Episode.toJSON(); // => 'Episode' + * JSON.stringify({ type: Episode }); // => '{"type":"Episode"}' + * ``` + */ + toJSON(): string; +} +/** Configuration used to construct a GraphQLEnumType. */ +export interface GraphQLEnumTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Values contained in this enum, list, or input-object definition. */ + values: ThunkObjMap; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +interface GraphQLEnumTypeNormalizedConfig extends GraphQLEnumTypeConfig { + values: ObjMap; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** A map of enum value names to enum value configuration objects. */ +export declare type GraphQLEnumValueConfigMap = ObjMap; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLEnumValueExtensions { + [attributeName: string]: unknown; +} +/** Configuration used to define a GraphQL enum value. */ +export interface GraphQLEnumValueConfig { + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Parsed value represented by this node. */ + value?: any; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason?: Maybe; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; +} +/** A resolved GraphQL enum value definition. */ +export interface GraphQLEnumValue { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Parsed value represented by this node. */ + value: any; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInputObjectTypeExtensions { + [attributeName: string]: unknown; +} +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * @example + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ +export declare class GraphQLInputObjectType { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + /** Whether this input object uses the experimental OneOf input object semantics. */ + isOneOf: boolean; + private _fields; + /** + * Creates a GraphQLInputObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * input ReviewInput { + * stars: Int! + * commentary: String + * } + * + * extend input ReviewInput { + * body: String + * } + * `); + * const definition = document.definitions[0]; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * description: 'Input collected when reviewing a product.', + * fields: { + * stars: { + * description: 'Star rating from one to five.', + * type: new GraphQLNonNull(GraphQLInt), + * extensions: { min: 1, max: 5 }, + * astNode: definition.fields[0], + * }, + * commentary: { + * type: GraphQLString, + * defaultValue: '', + * deprecationReason: 'Use body.', + * astNode: definition.fields[1], + * }, + * }, + * extensions: { form: 'review' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * isOneOf: false, + * }); + * const SearchBy = new GraphQLInputObjectType({ + * name: 'SearchBy', + * fields: { + * id: { type: GraphQLID }, + * slug: { type: GraphQLString }, + * }, + * isOneOf: true, + * }); + * + * const fields = ReviewInput.getFields(); + * + * ReviewInput.description; // => 'Input collected when reviewing a product.' + * String(fields.stars.type); // => 'Int!' + * fields.stars.extensions; // => { min: 1, max: 5 } + * fields.commentary.defaultValue; // => '' + * fields.commentary.deprecationReason; // => 'Use body.' + * ReviewInput.isOneOf; // => false + * SearchBy.isOneOf; // => true + * ``` + */ + constructor(config: Readonly); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * commentary: String = "" + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * const fields = ReviewInput.getFields(); + * + * Object.keys(fields); // => ['stars', 'commentary'] + * fields.commentary.defaultValue; // => '' + * ``` + */ + getFields(): GraphQLInputFieldMap; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * }, + * }); + * + * const config = ReviewInput.toConfig(); + * const ReviewInputCopy = new GraphQLInputObjectType(config); + * + * String(config.fields.stars.type); // => 'Int!' + * String(ReviewInputCopy.getFields().stars.type); // => 'Int!' + * ``` + */ + toConfig(): GraphQLInputObjectTypeNormalizedConfig; + /** + * Returns the schema coordinate identifying this input object type. + * @returns The schema coordinate for this input object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * + * ReviewInput.toString(); // => 'ReviewInput' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInputObjectType, GraphQLString } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * commentary: { type: GraphQLString }, + * }, + * }); + * + * ReviewInput.toJSON(); // => 'ReviewInput' + * JSON.stringify({ type: ReviewInput }); // => '{"type":"ReviewInput"}' + * ``` + */ + toJSON(): string; +} +/** Configuration used to construct a GraphQLInputObjectType. */ +export interface GraphQLInputObjectTypeConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Fields declared by this object, interface, input object, or literal. */ + fields: ThunkObjMap; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; + /** Whether this input object uses the experimental OneOf input object semantics. */ + isOneOf?: boolean; +} +interface GraphQLInputObjectTypeNormalizedConfig + extends GraphQLInputObjectTypeConfig { + fields: GraphQLInputFieldConfigMap; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLInputFieldExtensions { + [attributeName: string]: unknown; +} +/** Configuration used to define a GraphQL input field. */ +export interface GraphQLInputFieldConfig { + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLInputType; + /** Default value used when no explicit value is supplied. */ + defaultValue?: unknown; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason?: Maybe; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; +} +/** A map of input field names to input field configuration objects. */ +export declare type GraphQLInputFieldConfigMap = + ObjMap; +/** A resolved GraphQL input field definition. */ +export interface GraphQLInputField { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + type: GraphQLInputType; + /** Default value used when no explicit value is supplied. */ + defaultValue: unknown; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; +} +/** + * Returns true when the input field is non-null and has no default value. + * @param field - The input field definition to inspect. + * @returns True when the input field is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredInputField, + * } from 'graphql/type'; + * + * const requiredField = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalField = { name: 'name', type: GraphQLString }; + * const fieldWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredInputField(requiredField); // => true + * isRequiredInputField(optionalField); // => false + * isRequiredInputField(fieldWithDefault); // => false + * ``` + */ +export declare function isRequiredInputField(field: GraphQLInputField): boolean; +/** A map of input field names to resolved input field definitions. */ +export declare type GraphQLInputFieldMap = ObjMap; +export {}; diff --git a/node_modules/graphql/type/definition.js b/node_modules/graphql/type/definition.js new file mode 100644 index 0000000000000000000000000000000000000000..05a170ab7fc4fb249381894877932376e0fdb9ec --- /dev/null +++ b/node_modules/graphql/type/definition.js @@ -0,0 +1,3515 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.GraphQLUnionType = + exports.GraphQLScalarType = + exports.GraphQLObjectType = + exports.GraphQLNonNull = + exports.GraphQLList = + exports.GraphQLInterfaceType = + exports.GraphQLInputObjectType = + exports.GraphQLEnumType = + void 0; +exports.argsToArgsConfig = argsToArgsConfig; +exports.assertAbstractType = assertAbstractType; +exports.assertCompositeType = assertCompositeType; +exports.assertEnumType = assertEnumType; +exports.assertInputObjectType = assertInputObjectType; +exports.assertInputType = assertInputType; +exports.assertInterfaceType = assertInterfaceType; +exports.assertLeafType = assertLeafType; +exports.assertListType = assertListType; +exports.assertNamedType = assertNamedType; +exports.assertNonNullType = assertNonNullType; +exports.assertNullableType = assertNullableType; +exports.assertObjectType = assertObjectType; +exports.assertOutputType = assertOutputType; +exports.assertScalarType = assertScalarType; +exports.assertType = assertType; +exports.assertUnionType = assertUnionType; +exports.assertWrappingType = assertWrappingType; +exports.defineArguments = defineArguments; +exports.getNamedType = getNamedType; +exports.getNullableType = getNullableType; +exports.isAbstractType = isAbstractType; +exports.isCompositeType = isCompositeType; +exports.isEnumType = isEnumType; +exports.isInputObjectType = isInputObjectType; +exports.isInputType = isInputType; +exports.isInterfaceType = isInterfaceType; +exports.isLeafType = isLeafType; +exports.isListType = isListType; +exports.isNamedType = isNamedType; +exports.isNonNullType = isNonNullType; +exports.isNullableType = isNullableType; +exports.isObjectType = isObjectType; +exports.isOutputType = isOutputType; +exports.isRequiredArgument = isRequiredArgument; +exports.isRequiredInputField = isRequiredInputField; +exports.isScalarType = isScalarType; +exports.isType = isType; +exports.isUnionType = isUnionType; +exports.isWrappingType = isWrappingType; +exports.resolveObjMapThunk = resolveObjMapThunk; +exports.resolveReadonlyArrayThunk = resolveReadonlyArrayThunk; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _didYouMean = require('../jsutils/didYouMean.js'); + +var _identityFunc = require('../jsutils/identityFunc.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _instanceOf = require('../jsutils/instanceOf.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _keyMap = require('../jsutils/keyMap.js'); + +var _keyValMap = require('../jsutils/keyValMap.js'); + +var _mapValue = require('../jsutils/mapValue.js'); + +var _suggestionList = require('../jsutils/suggestionList.js'); + +var _toObjMap = require('../jsutils/toObjMap.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _kinds = require('../language/kinds.js'); + +var _printer = require('../language/printer.js'); + +var _valueFromASTUntyped = require('../utilities/valueFromASTUntyped.js'); + +var _assertName = require('./assertName.js'); + +/** @category Types */ + +/** + * Returns true when the value is any GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is any GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * isType(GraphQLString); // => true + * isType(new GraphQLList(GraphQLString)); // => true + * isType(schema.getType('Query')); // => true + * isType('String'); // => false + * ``` + */ +function isType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} +/** + * Returns the value as a GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const queryType = assertType(schema.getType('Query')); + * + * queryType.toString(); // => 'Query' + * assertType('Query'); // throws an error + * ``` + */ + +function assertType(type) { + if (!isType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL type.`, + ); + } + + return type; +} +/** + * There are predicates for each kind of GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * isScalarType(schema.getType('DateTime')); // => true + * isScalarType(schema.getType('Query')); // => false + * ``` + */ + +function isScalarType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLScalarType); +} +/** + * Returns the value as a GraphQLScalarType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * const dateTimeType = assertScalarType(schema.getType('DateTime')); + * + * dateTimeType.name; // => 'DateTime' + * assertScalarType(schema.getType('Query')); // throws an error + * ``` + */ + +function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Scalar type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * isObjectType(schema.getType('User')); // => true + * isObjectType(schema.getType('ReviewInput')); // => false + * ``` + */ + +function isObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLObjectType); +} +/** + * Returns the value as a GraphQLObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * const userType = assertObjectType(schema.getType('User')); + * + * Object.keys(userType.getFields()); // => ['name'] + * assertObjectType(schema.getType('ReviewInput')); // throws an error + * ``` + */ + +function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Object type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLInterfaceType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * isInterfaceType(schema.getType('Node')); // => true + * isInterfaceType(schema.getType('User')); // => false + * ``` + */ + +function isInterfaceType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInterfaceType); +} +/** + * Returns the value as a GraphQLInterfaceType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertInterfaceType(schema.getType('Node')); + * + * nodeType.name; // => 'Node' + * assertInterfaceType(schema.getType('User')); // throws an error + * ``` + */ + +function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Interface type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLUnionType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * isUnionType(schema.getType('Media')); // => true + * isUnionType(schema.getType('Photo')); // => false + * ``` + */ + +function isUnionType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLUnionType); +} +/** + * Returns the value as a GraphQLUnionType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const mediaType = assertUnionType(schema.getType('Media')); + * + * mediaType.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * assertUnionType(schema.getType('Photo')); // throws an error + * ``` + */ + +function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Union type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLEnumType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * isEnumType(schema.getType('Episode')); // => true + * isEnumType(schema.getType('Query')); // => false + * ``` + */ + +function isEnumType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLEnumType); +} +/** + * Returns the value as a GraphQLEnumType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * const episodeType = assertEnumType(schema.getType('Episode')); + * + * episodeType.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE'] + * assertEnumType(schema.getType('Query')); // throws an error + * ``` + */ + +function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Enum type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLInputObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputObjectType(schema.getType('ReviewInput')); // => true + * isInputObjectType(schema.getType('Review')); // => false + * ``` + */ + +function isInputObjectType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLInputObjectType); +} +/** + * Returns the value as a GraphQLInputObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputObjectType(schema.getType('ReviewInput')); + * + * Object.keys(inputType.getFields()); // => ['stars'] + * assertInputObjectType(schema.getType('Review')); // throws an error + * ``` + */ + +function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + type, + )} to be a GraphQL Input Object type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLList. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLList. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isListType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * tags: [String!]! + * } + * `); + * + * const tagsField = schema.getQueryType()?.getFields().tags; + * + * isListType(new GraphQLList(GraphQLString)); // => true + * isListType(GraphQLString); // => false + * isListType(tagsField?.type); // => false + * ``` + */ + +/** @internal */ +function isListType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLList); +} +/** + * Returns the value as a GraphQLList, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLList. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; + * + * const listType = assertListType(new GraphQLList(GraphQLString)); + * + * listType.ofType; // => GraphQLString + * assertListType(GraphQLString); // throws an error + * ``` + */ + +function assertListType(type) { + if (!isListType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL List type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLNonNull. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLNonNull. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String! + * nickname: String + * } + * `); + * + * const fields = schema.getQueryType()?.getFields(); + * + * isNonNullType(new GraphQLNonNull(GraphQLString)); // => true + * isNonNullType(fields?.name.type); // => true + * isNonNullType(fields?.nickname.type); // => false + * ``` + */ + +/** @internal */ +function isNonNullType(type) { + return (0, _instanceOf.instanceOf)(type, GraphQLNonNull); +} +/** + * Returns the value as a GraphQLNonNull, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLNonNull. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; + * + * const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); + * + * nonNullType.ofType; // => GraphQLString + * assertNonNullType(GraphQLString); // throws an error + * ``` + */ + +function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL Non-Null type.`, + ); + } + + return type; +} +/** These types may be used as input types for arguments and directives. */ + +/** + * Returns true when the value can be used as a GraphQL input type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputType(schema.getType('ReviewInput')); // => true + * isInputType(schema.getType('Review')); // => false + * ``` + */ +function isInputType(type) { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} +/** + * Returns the value as a GraphQL input type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputType(schema.getType('ReviewInput')); + * + * inputType.toString(); // => 'ReviewInput' + * assertInputType(schema.getType('Review')); // throws an error + * ``` + */ + +function assertInputType(type) { + if (!isInputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL input type.`, + ); + } + + return type; +} +/** These types may be used as output types as the result of fields. */ + +/** + * Returns true when the value can be used as a GraphQL output type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isOutputType(schema.getType('Review')); // => true + * isOutputType(schema.getType('ReviewInput')); // => false + * ``` + */ +function isOutputType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} +/** + * Returns the value as a GraphQL output type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const outputType = assertOutputType(schema.getType('Review')); + * + * outputType.toString(); // => 'Review' + * assertOutputType(schema.getType('ReviewInput')); // throws an error + * ``` + */ + +function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL output type.`, + ); + } + + return type; +} +/** These types may describe types which may be leaf values. */ + +/** + * Returns true when the value is a GraphQL scalar or enum type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL scalar or enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * isLeafType(schema.getType('Episode')); // => true + * isLeafType(schema.getType('String')); // => true + * isLeafType(schema.getType('Review')); // => false + * ``` + */ +function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +/** + * Returns the value as a GraphQL leaf type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL leaf type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * const episodeType = assertLeafType(schema.getType('Episode')); + * + * episodeType.toString(); // => 'Episode' + * assertLeafType(schema.getType('Review')); // throws an error + * ``` + */ + +function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL leaf type.`, + ); + } + + return type; +} +/** These types may describe the parent context of a selection set. */ + +/** + * Returns true when the value is a GraphQL object, interface, or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL object, interface, or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isCompositeType(schema.getType('User')); // => true + * isCompositeType(schema.getType('Node')); // => true + * isCompositeType(schema.getType('SearchResult')); // => true + * isCompositeType(schema.getType('String')); // => false + * ``` + */ +function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +/** + * Returns the value as a GraphQL composite type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL composite type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const userType = assertCompositeType(schema.getType('User')); + * + * userType.toString(); // => 'User' + * assertCompositeType(schema.getType('String')); // throws an error + * ``` + */ + +function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL composite type.`, + ); + } + + return type; +} +/** These types may describe the parent context of a selection set. */ + +/** + * Returns true when the value is a GraphQL interface or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL interface or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isAbstractType(schema.getType('Node')); // => true + * isAbstractType(schema.getType('SearchResult')); // => true + * isAbstractType(schema.getType('User')); // => false + * ``` + */ +function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +/** + * Returns the value as a GraphQL abstract type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertAbstractType(schema.getType('Node')); + * + * nodeType.toString(); // => 'Node' + * assertAbstractType(schema.getType('User')); // throws an error + * ``` + */ + +function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL abstract type.`, + ); + } + + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * @typeParam T - The GraphQL type wrapped by this list type. + * @example + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ + +class GraphQLList { + /** The type wrapped by this list or non-null type. */ + + /** + * Creates a GraphQLList instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.ofType; // => GraphQLString + * String(stringList); // => '[String]' + * ``` + */ + constructor(ofType) { + isType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)(ofType)} to be a GraphQL type.`, + ); + this.ofType = ofType; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLList'; + } + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * const requiredStringList = new GraphQLList(new GraphQLNonNull(GraphQLString)); + * + * stringList.toString(); // => '[String]' + * requiredStringList.toString(); // => '[String!]' + * ``` + */ + + toString() { + return '[' + String(this.ofType) + ']'; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.toJSON(); // => '[String]' + * JSON.stringify({ type: stringList }); // => '{"type":"[String]"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * @typeParam T - The nullable GraphQL type wrapped by this non-null type. + * @example + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +exports.GraphQLList = GraphQLList; + +class GraphQLNonNull { + /** The type wrapped by this list or non-null type. */ + + /** + * Creates a GraphQLNonNull instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.ofType; // => GraphQLString + * String(requiredString); // => 'String!' + * ``` + */ + constructor(ofType) { + isNullableType(ofType) || + (0, _devAssert.devAssert)( + false, + `Expected ${(0, _inspect.inspect)( + ofType, + )} to be a GraphQL nullable type.`, + ); + this.ofType = ofType; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLNonNull'; + } + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * const requiredStringList = new GraphQLNonNull( + * new GraphQLList(GraphQLString), + * ); + * + * requiredString.toString(); // => 'String!' + * requiredStringList.toString(); // => '[String]!' + * ``` + */ + + toString() { + return String(this.ofType) + '!'; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.toJSON(); // => 'String!' + * JSON.stringify({ type: requiredString }); // => '{"type":"String!"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** These types wrap and modify other types */ + +exports.GraphQLNonNull = GraphQLNonNull; + +/** + * Returns true when the value is a GraphQL list or non-null wrapper type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL list or non-null wrapper type. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * isWrappingType, + * } from 'graphql/type'; + * + * isWrappingType(new GraphQLList(GraphQLString)); // => true + * isWrappingType(new GraphQLNonNull(GraphQLString)); // => true + * isWrappingType(GraphQLString); // => false + * ``` + */ +function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +/** + * Returns the value as a GraphQL wrapping type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL wrapping type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; + * + * const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); + * + * wrappingType.toString(); // => '[String]' + * assertWrappingType(GraphQLString); // throws an error + * ``` + */ + +function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL wrapping type.`, + ); + } + + return type; +} +/** These types can all accept null as a value. */ + +/** + * Returns true when the value is a GraphQL type that can accept null. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL type that can accept null. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; + * + * isNullableType(GraphQLString); // => true + * isNullableType(new GraphQLNonNull(GraphQLString)); // => false + * isNullableType(null); // => false + * ``` + */ +function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +/** + * Returns the value as a nullable GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a nullable GraphQL type. + * @example + * ```ts + * import { + * GraphQLNonNull, + * GraphQLString, + * assertNullableType, + * } from 'graphql/type'; + * + * const nullableType = assertNullableType(GraphQLString); + * + * nullableType; // => GraphQLString + * assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error + * ``` + */ + +function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL nullable type.`, + ); + } + + return type; +} +/** + * Returns the nullable type. + * @param type - The GraphQL type to inspect. + * @returns The nullable type after removing one non-null wrapper, if present. + * @example + * ```ts + * import { getNullableType } from 'graphql/type'; + * + * getNullableType(null); // => undefined + * getNullableType(undefined); // => undefined + * ``` + */ + +/** @internal */ +function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** These named types do not include modifiers like List or NonNull. */ + +/** + * Returns true when the value is a GraphQL named type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; + * + * isNamedType(GraphQLString); // => true + * isNamedType(new GraphQLList(GraphQLString)); // => false + * isNamedType(null); // => false + * ``` + */ +function isNamedType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} +/** + * Returns the value as a GraphQL named type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; + * + * const namedType = assertNamedType(GraphQLString); + * + * namedType.name; // => 'String' + * assertNamedType(new GraphQLList(GraphQLString)); // throws an error + * ``` + */ + +function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(type)} to be a GraphQL named type.`, + ); + } + + return type; +} +/** + * Returns the named type. + * @param type - The GraphQL type to inspect. + * @returns The named type after unwrapping all list and non-null wrappers. + * @example + * ```ts + * import { getNamedType } from 'graphql/type'; + * + * getNamedType(null); // => undefined + * getNamedType(undefined); // => undefined + * ``` + */ + +/** @internal */ +function getNamedType(type) { + if (type) { + let unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + * @typeParam T - The element type returned by the thunk or array. + */ + +/** + * Resolves a thunked readonly array. + * @param thunk - The thunk or value to resolve. + * @returns The resolved readonly array. + * @typeParam T - The element type resolved from the thunk or array. + * @example + * ```ts + * import { GraphQLString, resolveReadonlyArrayThunk } from 'graphql/type'; + * + * const lazyFields = resolveReadonlyArrayThunk(() => [GraphQLString]); + * const fields = resolveReadonlyArrayThunk([GraphQLString]); + * + * lazyFields; // => [GraphQLString] + * fields; // => [GraphQLString] + * ``` + */ +function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Resolves a thunked object map. + * @param thunk - The thunk or value to resolve. + * @returns The resolved object map. + * @typeParam T - The object-map value type resolved from the thunk or map. + * @example + * ```ts + * import { GraphQLString, resolveObjMapThunk } from 'graphql/type'; + * + * const lazyFields = resolveObjMapThunk(() => ({ name: GraphQLString })); + * const fields = resolveObjMapThunk({ name: GraphQLString }); + * + * lazyFields.name; // => GraphQLString + * fields.name; // => GraphQLString + * ``` + */ + +function resolveObjMapThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Scalar Type Definition + * + * Scalar types define the leaf values of a GraphQL response and the input + * values accepted by arguments and input object fields. A scalar type has a + * name and coercion functions that validate and convert runtime values and + * GraphQL literals. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. Prefer validating inputs before + * execution so clients receive input diagnostics before result coercion fails. + * @typeParam TInternal - The internal runtime representation accepted by this scalar. + * @typeParam TExternal - The serialized representation exposed in GraphQL results. + * @example + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize: (value) => { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ +class GraphQLScalarType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** URL identifying the behavior specified for this custom scalar. */ + + /** Function that converts internal values to externally visible scalar values. */ + + /** Function that converts variable input into this scalar's internal value. */ + + /** Function that converts AST input literals into this scalar's internal value. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLScalarType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { GraphQLScalarType } from 'graphql/type'; + * + * const document = parse(` + * "Odd integer values." + * scalar Odd @specifiedBy(url: "https://example.com/odd") + * + * extend scalar Odd @specifiedBy(url: "https://example.com/odd-v2") + * `); + * + * const Odd = new GraphQLScalarType({ + * name: 'Odd', + * description: 'Odd integer values.', + * specifiedByURL: 'https://example.com/odd', + * serialize: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only serialize odd numbers.'); + * } + * return value; + * }, + * parseValue: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only parse odd numbers.'); + * } + * return value; + * }, + * parseLiteral: (ast) => { + * if (ast.kind !== Kind.INT) { + * throw new TypeError('Odd can only parse integer literals.'); + * } + * const value = Number(ast.value); + * if (value % 2 === 0) { + * throw new TypeError('Odd can only parse odd integer literals.'); + * } + * return value; + * }, + * extensions: { numeric: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Odd.description; // => 'Odd integer values.' + * Odd.specifiedByURL; // => 'https://example.com/odd' + * Odd.serialize(3); // => 3 + * Odd.parseValue(5); // => 5 + * Odd.extensions; // => { numeric: true } + * ``` + */ + constructor(config) { + var _config$parseValue, + _config$serialize, + _config$parseLiteral, + _config$extensionASTN; + + const parseValue = + (_config$parseValue = config.parseValue) !== null && + _config$parseValue !== void 0 + ? _config$parseValue + : _identityFunc.identityFunc; + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = + (_config$serialize = config.serialize) !== null && + _config$serialize !== void 0 + ? _config$serialize + : _identityFunc.identityFunc; + this.parseValue = parseValue; + this.parseLiteral = + (_config$parseLiteral = config.parseLiteral) !== null && + _config$parseLiteral !== void 0 + ? _config$parseLiteral + : (node, variables) => + parseValue( + (0, _valueFromASTUntyped.valueFromASTUntyped)(node, variables), + ); + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + config.specifiedByURL == null || + typeof config.specifiedByURL === 'string' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "specifiedByURL" as a string, ` + + `but got: ${(0, _inspect.inspect)(config.specifiedByURL)}.`, + ); + config.serialize == null || + typeof config.serialize === 'function' || + (0, _devAssert.devAssert)( + false, + `${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.`, + ); + + if (config.parseLiteral) { + (typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function') || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide both "parseValue" and "parseLiteral" functions.`, + ); + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLScalarType'; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const Url = new GraphQLScalarType({ + * name: 'Url', + * description: 'An absolute URL string.', + * specifiedByURL: 'https://url.spec.whatwg.org/', + * }); + * + * const config = Url.toConfig(); + * const UrlCopy = new GraphQLScalarType(config); + * + * config.name; // => 'Url' + * config.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * UrlCopy.name; // => Url.name + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this scalar type. + * @returns The schema coordinate for this scalar type. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toString(); // => 'DateTime' + * String(DateTime); // => 'DateTime' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toJSON(); // => 'DateTime' + * JSON.stringify({ type: DateTime }); // => '{"type":"DateTime"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Serializes a runtime value as a scalar output value. + * @typeParam TExternal - The serialized representation returned for GraphQL results. + */ + +exports.GraphQLScalarType = GraphQLScalarType; + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @example + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve: (obj) => { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * @example + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ +class GraphQLObjectType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Predicate used to determine whether a runtime value belongs to this object type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Configure an object type with interfaces, fields, arguments, and metadata. + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInterfaceType, + * GraphQLNonNull, + * GraphQLObjectType, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * type User implements Node { + * id: ID! + * name(format: String = "short"): String + * } + * + * extend type User { + * displayName: String + * } + * `); + * const definition = document.definitions[0]; + * const nameField = definition.fields[1]; + * const formatArg = nameField.arguments[0]; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const User = new GraphQLObjectType({ + * name: 'User', + * description: 'A registered user.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * name: { + * description: 'The formatted user name.', + * type: GraphQLString, + * args: { + * format: { + * description: 'Controls the name format.', + * type: GraphQLString, + * defaultValue: 'short', + * deprecationReason: 'Use locale instead.', + * extensions: { public: true }, + * astNode: formatArg, + * }, + * }, + * resolve: (user, { format }) => { + * return format === 'long' ? user.fullName : user.name; + * }, + * deprecationReason: 'Use displayName.', + * extensions: { cacheSeconds: 60 }, + * astNode: nameField, + * }, + * }, + * isTypeOf: (value) => { + * return typeof value === 'object' && value != null && 'id' in value; + * }, + * extensions: { entity: 'User' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * User.name; // => 'User' + * User.getInterfaces(); // => [Node] + * Object.keys(User.getFields()); // => ['id', 'name'] + * User.getFields().name.args[0].defaultValue; // => 'short' + * User.extensions; // => { entity: 'User' } + * ``` + * @example + * ```ts + * // This variant configures a subscription field with subscribe and resolve functions. + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { + * greeting: { + * type: GraphQLString, + * subscribe: async function* () { + * yield { greeting: 'Hello!' }; + * }, + * resolve: (event) => { + * return event.greeting; + * }, + * }, + * }, + * }); + * + * typeof Subscription.getFields().greeting.subscribe; // => 'function' + * ``` + */ + constructor(config) { + var _config$extensionASTN2; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN2 = config.extensionASTNodes) !== null && + _config$extensionASTN2 !== void 0 + ? _config$extensionASTN2 + : []; + + this._fields = () => defineFieldMap(config); + + this._interfaces = () => defineInterfaces(config); + + config.isTypeOf == null || + typeof config.isTypeOf === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.isTypeOf)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLObjectType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * const fields = User.getFields(); + * + * Object.keys(fields); // => ['id', 'name'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.getInterfaces().map((type) => type.name); // => ['Node'] + * ``` + */ + + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = User.toConfig(); + * const UserCopy = new GraphQLObjectType(config); + * + * config.fields.name.type; // => GraphQLString + * UserCopy.getFields().name.type; // => GraphQLString + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this object type. + * @returns The schema coordinate for this object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.toString(); // => 'User' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { name: { type: GraphQLString } }, + * }); + * + * User.toJSON(); // => 'User' + * JSON.stringify({ type: User }); // => '{"type":"User"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +exports.GraphQLObjectType = GraphQLObjectType; + +function defineInterfaces(config) { + var _config$interfaces; + + const interfaces = resolveReadonlyArrayThunk( + (_config$interfaces = config.interfaces) !== null && + _config$interfaces !== void 0 + ? _config$interfaces + : [], + ); + Array.isArray(interfaces) || + (0, _devAssert.devAssert)( + false, + `${config.name} interfaces must be an Array or a function which returns an Array.`, + ); + return interfaces; +} + +function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + + isPlainObj(fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field config must be an object.`, + ); + fieldConfig.resolve == null || + typeof fieldConfig.resolve === 'function' || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${(0, _inspect.inspect)(fieldConfig.resolve)}.`, + ); + const argsConfig = + (_fieldConfig$args = fieldConfig.args) !== null && + _fieldConfig$args !== void 0 + ? _fieldConfig$args + : {}; + isPlainObj(argsConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} args must be an object with argument names as keys.`, + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} +/** @internal */ + +function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: (0, _assertName.assertName)(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(argConfig.extensions), + astNode: argConfig.astNode, + })); +} + +function isPlainObj(obj) { + return (0, _isObjectLike.isObjectLike)(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig(fields) { + return (0, _mapValue.mapValue)(fields, (field) => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); +} +/** @internal */ + +function argsToArgsConfig(args) { + return (0, _keyValMap.keyValMap)( + args, + (arg) => arg.name, + (arg) => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode, + }), + ); +} +/** + * Configuration used to construct a GraphQLObjectType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Returns true when the argument is non-null and has no default value. + * @param arg - The argument definition to inspect. + * @returns True when the argument is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredArgument, + * } from 'graphql/type'; + * + * const requiredArgument = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalArgument = { name: 'name', type: GraphQLString }; + * const argumentWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredArgument(requiredArgument); // => true + * isRequiredArgument(optionalArgument); // => false + * isRequiredArgument(argumentWithDefault); // => false + * ``` + */ +function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} +/** + * A map of field names to resolved field definitions. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * @example + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ +class GraphQLInterfaceType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Function that resolves the concrete object type for this abstract type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLInterfaceType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const document = parse(` + * interface Node { + * id: ID! + * } + * + * interface Resource implements Node { + * id: ID! + * } + * + * extend interface Resource { + * url: String + * } + * `); + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const Resource = new GraphQLInterfaceType({ + * name: 'Resource', + * description: 'An addressable resource.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'url' in value + * ? 'WebPage' + * : null; + * }, + * extensions: { abstract: true }, + * astNode: document.definitions[1], + * extensionASTNodes: [ document.definitions[2] ], + * }); + * + * Resource.name; // => 'Resource' + * Resource.getInterfaces(); // => [Node] + * Object.keys(Resource.getFields()); // => ['id'] + * Resource.extensions; // => { abstract: true } + * ``` + */ + constructor(config) { + var _config$extensionASTN3; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN3 = config.extensionASTNodes) !== null && + _config$extensionASTN3 !== void 0 + ? _config$extensionASTN3 + : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLInterfaceType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const fields = Node.getFields(); + * + * Object.keys(fields); // => ['id'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * image: Image + * } + * `); + * + * const Image = assertInterfaceType(schema.getType('Image')); + * + * Image.getInterfaces().map((type) => type.name); // => ['Resource'] + * ``` + */ + + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const config = Node.toConfig(); + * const NodeCopy = new GraphQLInterfaceType(config); + * + * String(config.fields.id.type); // => 'ID!' + * String(NodeCopy.getFields().id.type); // => 'ID!' + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this interface type. + * @returns The schema coordinate for this interface type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * + * Node.toString(); // => 'Node' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInterfaceType, GraphQLString } from 'graphql/type'; + * + * const Named = new GraphQLInterfaceType({ + * name: 'Named', + * fields: { name: { type: GraphQLString } }, + * }); + * + * Named.toJSON(); // => 'Named' + * JSON.stringify({ type: Named }); // => '{"type":"Named"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Configuration used to construct a GraphQLInterfaceType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +exports.GraphQLInterfaceType = GraphQLInterfaceType; + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * @example + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [DogType, CatType], + * resolveType: (value) => { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ +class GraphQLUnionType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Function that resolves the concrete object type for this abstract type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLUnionType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const document = parse(` + * union Media = Photo | Video + * + * extend union Media = Audio + * `); + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * + * const Media = new GraphQLUnionType({ + * name: 'Media', + * description: 'Media that can appear in a search result.', + * types: [Photo, Video], + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'duration' in value + * ? 'Video' + * : 'Photo'; + * }, + * extensions: { searchable: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Media.description; // => 'Media that can appear in a search result.' + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * Media.extensions; // => { searchable: true } + * ``` + */ + constructor(config) { + var _config$extensionASTN4; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN4 = config.extensionASTNodes) !== null && + _config$extensionASTN4 !== void 0 + ? _config$extensionASTN4 + : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + (0, _devAssert.devAssert)( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${(0, _inspect.inspect)(config.resolveType)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLUnionType'; + } + /** + * Returns the object types included in this union. + * @returns The union member object types. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const Media = assertUnionType(schema.getType('Media')); + * + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + + getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * const Media = new GraphQLUnionType({ + * name: 'Media', + * types: [Photo, Video], + * }); + * + * const config = Media.toConfig(); + * const MediaCopy = new GraphQLUnionType(config); + * + * MediaCopy.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this union type. + * @returns The schema coordinate for this union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * union SearchResult = Photo + * + * type Query { + * search: [SearchResult] + * } + * `); + * + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * SearchResult.toString(); // => 'SearchResult' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const SearchResult = new GraphQLUnionType({ + * name: 'SearchResult', + * types: [Photo], + * }); + * + * SearchResult.toJSON(); // => 'SearchResult' + * JSON.stringify({ type: SearchResult }); // => '{"type":"SearchResult"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +exports.GraphQLUnionType = GraphQLUnionType; + +function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || + (0, _devAssert.devAssert)( + false, + `Must provide Array of types or a function which returns such an array for Union ${config.name}.`, + ); + return types; +} +/** + * Configuration used to construct a GraphQLUnionType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Enum Type Definition + * + * Enum types define leaf values whose serialized form is one of a fixed set + * of GraphQL enum names. Internally, enum values can map to any runtime value, + * often integers. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGBType.getValue('GREEN')?.value; // => 1 + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +class GraphQLEnumType { + /* */ + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLEnumType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const document = parse(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * extend enum Episode { + * FORCE_AWAKENS + * } + * `); + * const definition = document.definitions[0]; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * description: 'A Star Wars film episode.', + * values: { + * NEW_HOPE: { + * value: 4, + * description: 'Released in 1977.', + * extensions: { trilogy: 'original' }, + * astNode: definition.values[0], + * }, + * EMPIRE: { value: 5, astNode: definition.values[1] }, + * JEDI: { + * value: 6, + * deprecationReason: 'Use RETURN_OF_THE_JEDI.', + * astNode: definition.values[2], + * }, + * }, + * extensions: { catalog: 'films' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Episode.description; // => 'A Star Wars film episode.' + * Episode.serialize(5); // => 'EMPIRE' + * Episode.parseValue('JEDI'); // => 6 + * Episode.getValue('JEDI').deprecationReason; // => 'Use RETURN_OF_THE_JEDI.' + * Episode.extensions; // => { catalog: 'films' } + * ``` + */ + constructor(config) { + var _config$extensionASTN5; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN5 = config.extensionASTNodes) !== null && + _config$extensionASTN5 !== void 0 + ? _config$extensionASTN5 + : []; + this._values = + typeof config.values === 'function' + ? config.values + : defineEnumValues(this.name, config.values); + this._valueLookup = null; + this._nameLookup = null; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLEnumType'; + } + /** + * Returns the values defined by this enum type. + * @returns Enum value definitions in schema order. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE', 'JEDI'] + * ``` + */ + + getValues() { + if (typeof this._values === 'function') { + this._values = defineEnumValues(this.name, this._values()); + } + + return this._values; + } + /** + * Returns the enum value definition for a value name. + * @param name - The GraphQL name to look up. + * @returns The matching enum value definition, if it exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValue('EMPIRE')?.name; // => 'EMPIRE' + * Episode.getValue('JEDI'); // => undefined + * ``` + */ + + getValue(name) { + if (this._nameLookup === null) { + this._nameLookup = (0, _keyMap.keyMap)( + this.getValues(), + (value) => value.name, + ); + } + + return this._nameLookup[name]; + } + /** + * Serializes a runtime enum value as a GraphQL enum name. + * @param outputValue - Runtime enum value to serialize. + * @returns The GraphQL enum name for the runtime value. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.serialize(1); // => 'GREEN' + * RGB.serialize(3); // throws an error + * ``` + */ + + serialize(outputValue) { + if (this._valueLookup === null) { + this._valueLookup = new Map( + this.getValues().map((enumValue) => [enumValue.value, enumValue]), + ); + } + + const enumValue = this._valueLookup.get(outputValue); + + if (enumValue === undefined) { + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent value: ${(0, _inspect.inspect)( + outputValue, + )}`, + ); + } + + return enumValue.name; + } + /** + * Parses a GraphQL enum name from variable input. + * @param inputValue - Runtime input value to parse. + * @returns The internal enum value represented by the input name. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseValue('BLUE'); // => 2 + * RGB.parseValue('PURPLE'); // throws an error + * RGB.parseValue(2); // throws an error + * ``` + */ + + parseValue(inputValue) /* T */ + { + if (typeof inputValue !== 'string') { + const valueStr = (0, _inspect.inspect)(inputValue); + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + ); + } + + const enumValue = this.getValue(inputValue); + + if (enumValue == null) { + throw new _GraphQLError.GraphQLError( + `Value "${inputValue}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, inputValue), + ); + } + + return enumValue.value; + } + /** + * Parses a GraphQL enum name from an AST value literal. + * @param valueNode - AST value literal to parse. + * @param _variables - Runtime variable values; ignored because enum literals cannot contain variables. + * @returns The internal enum value represented by the literal. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseLiteral(parseValue('RED')); // => 0 + * RGB.parseLiteral(parseValue('"RED"')); // throws an error + * ``` + */ + + parseLiteral(valueNode, _variables) /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== _kinds.Kind.ENUM) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError( + `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + }, + ); + } + + const enumValue = this.getValue(valueNode.value); + + if (enumValue == null) { + const valueStr = (0, _printer.print)(valueNode); + throw new _GraphQLError.GraphQLError( + `Value "${valueStr}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + }, + ); + } + + return enumValue.value; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * const config = RGB.toConfig(); + * const RGBCopy = new GraphQLEnumType(config); + * + * config.values.GREEN.value; // => 1 + * RGBCopy.serialize(2); // => 'BLUE' + * ``` + */ + + toConfig() { + const values = (0, _keyValMap.keyValMap)( + this.getValues(), + (value) => value.name, + (value) => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode, + }), + ); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this enum type. + * @returns The schema coordinate for this enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.toString(); // => 'Episode' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * values: { + * NEW_HOPE: {}, + * }, + * }); + * + * Episode.toJSON(); // => 'Episode' + * JSON.stringify({ type: Episode }); // => '{"type":"Episode"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +exports.GraphQLEnumType = GraphQLEnumType; + +function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = (0, _suggestionList.suggestionList)( + unknownValueStr, + allNames, + ); + return (0, _didYouMean.didYouMean)('the enum value', suggestedValues); +} + +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || + (0, _devAssert.devAssert)( + false, + `${typeName} values must be an object with value names as keys.`, + ); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || + (0, _devAssert.devAssert)( + false, + `${typeName}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${(0, _inspect.inspect)( + valueConfig, + )}.`, + ); + return { + name: (0, _assertName.assertEnumValueName)(valueName), + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(valueConfig.extensions), + astNode: valueConfig.astNode, + }; + }); +} +/** Configuration used to construct a GraphQLEnumType. */ + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * @example + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ +class GraphQLInputObjectType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** Whether this input object uses the experimental OneOf input object semantics. */ + + /** + * Creates a GraphQLInputObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * input ReviewInput { + * stars: Int! + * commentary: String + * } + * + * extend input ReviewInput { + * body: String + * } + * `); + * const definition = document.definitions[0]; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * description: 'Input collected when reviewing a product.', + * fields: { + * stars: { + * description: 'Star rating from one to five.', + * type: new GraphQLNonNull(GraphQLInt), + * extensions: { min: 1, max: 5 }, + * astNode: definition.fields[0], + * }, + * commentary: { + * type: GraphQLString, + * defaultValue: '', + * deprecationReason: 'Use body.', + * astNode: definition.fields[1], + * }, + * }, + * extensions: { form: 'review' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * isOneOf: false, + * }); + * const SearchBy = new GraphQLInputObjectType({ + * name: 'SearchBy', + * fields: { + * id: { type: GraphQLID }, + * slug: { type: GraphQLString }, + * }, + * isOneOf: true, + * }); + * + * const fields = ReviewInput.getFields(); + * + * ReviewInput.description; // => 'Input collected when reviewing a product.' + * String(fields.stars.type); // => 'Int!' + * fields.stars.extensions; // => { min: 1, max: 5 } + * fields.commentary.defaultValue; // => '' + * fields.commentary.deprecationReason; // => 'Use body.' + * ReviewInput.isOneOf; // => false + * SearchBy.isOneOf; // => true + * ``` + */ + constructor(config) { + var _config$extensionASTN6, _config$isOneOf; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN6 = config.extensionASTNodes) !== null && + _config$extensionASTN6 !== void 0 + ? _config$extensionASTN6 + : []; + this.isOneOf = + (_config$isOneOf = config.isOneOf) !== null && _config$isOneOf !== void 0 + ? _config$isOneOf + : false; + this._fields = defineInputFieldMap.bind(undefined, config); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLInputObjectType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * commentary: String = "" + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * const fields = ReviewInput.getFields(); + * + * Object.keys(fields); // => ['stars', 'commentary'] + * fields.commentary.defaultValue; // => '' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * }, + * }); + * + * const config = ReviewInput.toConfig(); + * const ReviewInputCopy = new GraphQLInputObjectType(config); + * + * String(config.fields.stars.type); // => 'Int!' + * String(ReviewInputCopy.getFields().stars.type); // => 'Int!' + * ``` + */ + + toConfig() { + const fields = (0, _mapValue.mapValue)(this.getFields(), (field) => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + isOneOf: this.isOneOf, + }; + } + /** + * Returns the schema coordinate identifying this input object type. + * @returns The schema coordinate for this input object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * + * ReviewInput.toString(); // => 'ReviewInput' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInputObjectType, GraphQLString } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * commentary: { type: GraphQLString }, + * }, + * }); + * + * ReviewInput.toJSON(); // => 'ReviewInput' + * JSON.stringify({ type: ReviewInput }); // => '{"type":"ReviewInput"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +exports.GraphQLInputObjectType = GraphQLInputObjectType; + +function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + (0, _devAssert.devAssert)( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return (0, _mapValue.mapValue)(fieldMap, (fieldConfig, fieldName) => { + !('resolve' in fieldConfig) || + (0, _devAssert.devAssert)( + false, + `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`, + ); + return { + name: (0, _assertName.assertName)(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: (0, _toObjMap.toObjMap)(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} +/** Configuration used to construct a GraphQLInputObjectType. */ + +/** + * Returns true when the input field is non-null and has no default value. + * @param field - The input field definition to inspect. + * @returns True when the input field is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredInputField, + * } from 'graphql/type'; + * + * const requiredField = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalField = { name: 'name', type: GraphQLString }; + * const fieldWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredInputField(requiredField); // => true + * isRequiredInputField(optionalField); // => false + * isRequiredInputField(fieldWithDefault); // => false + * ``` + */ +function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} +/** A map of input field names to resolved input field definitions. */ diff --git a/node_modules/graphql/type/definition.mjs b/node_modules/graphql/type/definition.mjs new file mode 100644 index 0000000000000000000000000000000000000000..335f0bb945c347899749b4a86b6bb15ecdadcdcd --- /dev/null +++ b/node_modules/graphql/type/definition.mjs @@ -0,0 +1,3378 @@ +/** @category Types */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { didYouMean } from '../jsutils/didYouMean.mjs'; +import { identityFunc } from '../jsutils/identityFunc.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { instanceOf } from '../jsutils/instanceOf.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { keyMap } from '../jsutils/keyMap.mjs'; +import { keyValMap } from '../jsutils/keyValMap.mjs'; +import { mapValue } from '../jsutils/mapValue.mjs'; +import { suggestionList } from '../jsutils/suggestionList.mjs'; +import { toObjMap } from '../jsutils/toObjMap.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { print } from '../language/printer.mjs'; +import { valueFromASTUntyped } from '../utilities/valueFromASTUntyped.mjs'; +import { assertEnumValueName, assertName } from './assertName.mjs'; + +/** + * Returns true when the value is any GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is any GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * isType(GraphQLString); // => true + * isType(new GraphQLList(GraphQLString)); // => true + * isType(schema.getType('Query')); // => true + * isType('String'); // => false + * ``` + */ +export function isType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) || + isListType(type) || + isNonNullType(type) + ); +} +/** + * Returns the value as a GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const queryType = assertType(schema.getType('Query')); + * + * queryType.toString(); // => 'Query' + * assertType('Query'); // throws an error + * ``` + */ + +export function assertType(type) { + if (!isType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL type.`); + } + + return type; +} +/** + * There are predicates for each kind of GraphQL type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * isScalarType(schema.getType('DateTime')); // => true + * isScalarType(schema.getType('Query')); // => false + * ``` + */ + +export function isScalarType(type) { + return instanceOf(type, GraphQLScalarType); +} +/** + * Returns the value as a GraphQLScalarType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLScalarType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertScalarType } from 'graphql/type'; + * + * const schema = buildSchema(` + * scalar DateTime + * + * type Query { + * createdAt: DateTime + * } + * `); + * + * const dateTimeType = assertScalarType(schema.getType('DateTime')); + * + * dateTimeType.name; // => 'DateTime' + * assertScalarType(schema.getType('Query')); // throws an error + * ``` + */ + +export function assertScalarType(type) { + if (!isScalarType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Scalar type.`); + } + + return type; +} +/** + * Returns true when the value is a GraphQLObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * isObjectType(schema.getType('User')); // => true + * isObjectType(schema.getType('ReviewInput')); // => false + * ``` + */ + +export function isObjectType(type) { + return instanceOf(type, GraphQLObjectType); +} +/** + * Returns the value as a GraphQLObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type User { + * name: String + * } + * + * type Query { + * user: User + * } + * `); + * + * const userType = assertObjectType(schema.getType('User')); + * + * Object.keys(userType.getFields()); // => ['name'] + * assertObjectType(schema.getType('ReviewInput')); // throws an error + * ``` + */ + +export function assertObjectType(type) { + if (!isObjectType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Object type.`); + } + + return type; +} +/** + * Returns true when the value is a GraphQLInterfaceType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * isInterfaceType(schema.getType('Node')); // => true + * isInterfaceType(schema.getType('User')); // => false + * ``` + */ + +export function isInterfaceType(type) { + return instanceOf(type, GraphQLInterfaceType); +} +/** + * Returns the value as a GraphQLInterfaceType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInterfaceType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertInterfaceType(schema.getType('Node')); + * + * nodeType.name; // => 'Node' + * assertInterfaceType(schema.getType('User')); // throws an error + * ``` + */ + +export function assertInterfaceType(type) { + if (!isInterfaceType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL Interface type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLUnionType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * isUnionType(schema.getType('Media')); // => true + * isUnionType(schema.getType('Photo')); // => false + * ``` + */ + +export function isUnionType(type) { + return instanceOf(type, GraphQLUnionType); +} +/** + * Returns the value as a GraphQLUnionType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLUnionType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const mediaType = assertUnionType(schema.getType('Media')); + * + * mediaType.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * assertUnionType(schema.getType('Photo')); // throws an error + * ``` + */ + +export function assertUnionType(type) { + if (!isUnionType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Union type.`); + } + + return type; +} +/** + * Returns true when the value is a GraphQLEnumType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * isEnumType(schema.getType('Episode')); // => true + * isEnumType(schema.getType('Query')); // => false + * ``` + */ + +export function isEnumType(type) { + return instanceOf(type, GraphQLEnumType); +} +/** + * Returns the value as a GraphQLEnumType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLEnumType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * favoriteEpisode: Episode + * } + * `); + * + * const episodeType = assertEnumType(schema.getType('Episode')); + * + * episodeType.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE'] + * assertEnumType(schema.getType('Query')); // throws an error + * ``` + */ + +export function assertEnumType(type) { + if (!isEnumType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Enum type.`); + } + + return type; +} +/** + * Returns true when the value is a GraphQLInputObjectType. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputObjectType(schema.getType('ReviewInput')); // => true + * isInputObjectType(schema.getType('Review')); // => false + * ``` + */ + +export function isInputObjectType(type) { + return instanceOf(type, GraphQLInputObjectType); +} +/** + * Returns the value as a GraphQLInputObjectType, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLInputObjectType. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputObjectType(schema.getType('ReviewInput')); + * + * Object.keys(inputType.getFields()); // => ['stars'] + * assertInputObjectType(schema.getType('Review')); // throws an error + * ``` + */ + +export function assertInputObjectType(type) { + if (!isInputObjectType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL Input Object type.`, + ); + } + + return type; +} +/** + * Returns true when the value is a GraphQLList. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLList. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLList, GraphQLString, isListType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * tags: [String!]! + * } + * `); + * + * const tagsField = schema.getQueryType()?.getFields().tags; + * + * isListType(new GraphQLList(GraphQLString)); // => true + * isListType(GraphQLString); // => false + * isListType(tagsField?.type); // => false + * ``` + */ + +/** @internal */ +export function isListType(type) { + return instanceOf(type, GraphQLList); +} +/** + * Returns the value as a GraphQLList, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLList. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertListType } from 'graphql/type'; + * + * const listType = assertListType(new GraphQLList(GraphQLString)); + * + * listType.ofType; // => GraphQLString + * assertListType(GraphQLString); // throws an error + * ``` + */ + +export function assertListType(type) { + if (!isListType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL List type.`); + } + + return type; +} +/** + * Returns true when the value is a GraphQLNonNull. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQLNonNull. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLNonNull, GraphQLString, isNonNullType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * name: String! + * nickname: String + * } + * `); + * + * const fields = schema.getQueryType()?.getFields(); + * + * isNonNullType(new GraphQLNonNull(GraphQLString)); // => true + * isNonNullType(fields?.name.type); // => true + * isNonNullType(fields?.nickname.type); // => false + * ``` + */ + +/** @internal */ +export function isNonNullType(type) { + return instanceOf(type, GraphQLNonNull); +} +/** + * Returns the value as a GraphQLNonNull, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQLNonNull. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, assertNonNullType } from 'graphql/type'; + * + * const nonNullType = assertNonNullType(new GraphQLNonNull(GraphQLString)); + * + * nonNullType.ofType; // => GraphQLString + * assertNonNullType(GraphQLString); // throws an error + * ``` + */ + +export function assertNonNullType(type) { + if (!isNonNullType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL Non-Null type.`); + } + + return type; +} +/** These types may be used as input types for arguments and directives. */ + +/** + * Returns true when the value can be used as a GraphQL input type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isInputType(schema.getType('ReviewInput')); // => true + * isInputType(schema.getType('Review')); // => false + * ``` + */ +export function isInputType(type) { + return ( + isScalarType(type) || + isEnumType(type) || + isInputObjectType(type) || + (isWrappingType(type) && isInputType(type.ofType)) + ); +} +/** + * Returns the value as a GraphQL input type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL input type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const inputType = assertInputType(schema.getType('ReviewInput')); + * + * inputType.toString(); // => 'ReviewInput' + * assertInputType(schema.getType('Review')); // throws an error + * ``` + */ + +export function assertInputType(type) { + if (!isInputType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL input type.`); + } + + return type; +} +/** These types may be used as output types as the result of fields. */ + +/** + * Returns true when the value can be used as a GraphQL output type. + * @param type - The GraphQL type to inspect. + * @returns True when the value can be used as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * isOutputType(schema.getType('Review')); // => true + * isOutputType(schema.getType('ReviewInput')); // => false + * ``` + */ +export function isOutputType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + (isWrappingType(type) && isOutputType(type.ofType)) + ); +} +/** + * Returns the value as a GraphQL output type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL output type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertOutputType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * review(input: ReviewInput): Review + * } + * `); + * + * const outputType = assertOutputType(schema.getType('Review')); + * + * outputType.toString(); // => 'Review' + * assertOutputType(schema.getType('ReviewInput')); // throws an error + * ``` + */ + +export function assertOutputType(type) { + if (!isOutputType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL output type.`); + } + + return type; +} +/** These types may describe types which may be leaf values. */ + +/** + * Returns true when the value is a GraphQL scalar or enum type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL scalar or enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * isLeafType(schema.getType('Episode')); // => true + * isLeafType(schema.getType('String')); // => true + * isLeafType(schema.getType('Review')); // => false + * ``` + */ +export function isLeafType(type) { + return isScalarType(type) || isEnumType(type); +} +/** + * Returns the value as a GraphQL leaf type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL leaf type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertLeafType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Review { + * stars: Int! + * } + * + * type Query { + * episode: Episode + * review: Review + * } + * `); + * + * const episodeType = assertLeafType(schema.getType('Episode')); + * + * episodeType.toString(); // => 'Episode' + * assertLeafType(schema.getType('Review')); // throws an error + * ``` + */ + +export function assertLeafType(type) { + if (!isLeafType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL leaf type.`); + } + + return type; +} +/** These types may describe the parent context of a selection set. */ + +/** + * Returns true when the value is a GraphQL object, interface, or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL object, interface, or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isCompositeType(schema.getType('User')); // => true + * isCompositeType(schema.getType('Node')); // => true + * isCompositeType(schema.getType('SearchResult')); // => true + * isCompositeType(schema.getType('String')); // => false + * ``` + */ +export function isCompositeType(type) { + return isObjectType(type) || isInterfaceType(type) || isUnionType(type); +} +/** + * Returns the value as a GraphQL composite type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL composite type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertCompositeType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const userType = assertCompositeType(schema.getType('User')); + * + * userType.toString(); // => 'User' + * assertCompositeType(schema.getType('String')); // throws an error + * ``` + */ + +export function assertCompositeType(type) { + if (!isCompositeType(type)) { + throw new Error( + `Expected ${inspect(type)} to be a GraphQL composite type.`, + ); + } + + return type; +} +/** These types may describe the parent context of a selection set. */ + +/** + * Returns true when the value is a GraphQL interface or union type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL interface or union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { isAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * union SearchResult = User + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * isAbstractType(schema.getType('Node')); // => true + * isAbstractType(schema.getType('SearchResult')); // => true + * isAbstractType(schema.getType('User')); // => false + * ``` + */ +export function isAbstractType(type) { + return isInterfaceType(type) || isUnionType(type); +} +/** + * Returns the value as a GraphQL abstract type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertAbstractType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const nodeType = assertAbstractType(schema.getType('Node')); + * + * nodeType.toString(); // => 'Node' + * assertAbstractType(schema.getType('User')); // throws an error + * ``` + */ + +export function assertAbstractType(type) { + if (!isAbstractType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL abstract type.`); + } + + return type; +} +/** + * List Type Wrapper + * + * A list is a wrapping type which points to another type. + * Lists are often created within the context of defining the fields of + * an object type. + * @typeParam T - The GraphQL type wrapped by this list type. + * @example + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * parents: { type: new GraphQLList(PersonType) }, + * children: { type: new GraphQLList(PersonType) }, + * }) + * }) + * ``` + */ + +export class GraphQLList { + /** The type wrapped by this list or non-null type. */ + + /** + * Creates a GraphQLList instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.ofType; // => GraphQLString + * String(stringList); // => '[String]' + * ``` + */ + constructor(ofType) { + isType(ofType) || + devAssert(false, `Expected ${inspect(ofType)} to be a GraphQL type.`); + this.ofType = ofType; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLList'; + } + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * const requiredStringList = new GraphQLList(new GraphQLNonNull(GraphQLString)); + * + * stringList.toString(); // => '[String]' + * requiredStringList.toString(); // => '[String!]' + * ``` + */ + + toString() { + return '[' + String(this.ofType) + ']'; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLList, GraphQLString } from 'graphql/type'; + * + * const stringList = new GraphQLList(GraphQLString); + * + * stringList.toJSON(); // => '[String]' + * JSON.stringify({ type: stringList }); // => '{"type":"[String]"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Non-Null Type Wrapper + * + * A non-null is a wrapping type which points to another type. + * Non-null types enforce that their values are never null and can ensure + * an error is raised if this ever occurs during a request. It is useful for + * fields which you can make a strong guarantee on non-nullability, for example + * usually the id field of a database row will never be null. + * @typeParam T - The nullable GraphQL type wrapped by this non-null type. + * @example + * ```ts + * const RowType = new GraphQLObjectType({ + * name: 'Row', + * fields: () => ({ + * id: { type: new GraphQLNonNull(GraphQLString) }, + * }) + * }) + * ``` + * + * Note: the enforcement of non-nullability occurs within the executor. + */ + +export class GraphQLNonNull { + /** The type wrapped by this list or non-null type. */ + + /** + * Creates a GraphQLNonNull instance. + * @param ofType - The type to wrap. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.ofType; // => GraphQLString + * String(requiredString); // => 'String!' + * ``` + */ + constructor(ofType) { + isNullableType(ofType) || + devAssert( + false, + `Expected ${inspect(ofType)} to be a GraphQL nullable type.`, + ); + this.ofType = ofType; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLNonNull'; + } + /** + * Returns this wrapping type as a GraphQL type-reference string. + * @returns The GraphQL type-reference string. + * @example + * ```ts + * import { GraphQLList, GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * const requiredStringList = new GraphQLNonNull( + * new GraphQLList(GraphQLString), + * ); + * + * requiredString.toString(); // => 'String!' + * requiredStringList.toString(); // => '[String]!' + * ``` + */ + + toString() { + return String(this.ofType) + '!'; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString } from 'graphql/type'; + * + * const requiredString = new GraphQLNonNull(GraphQLString); + * + * requiredString.toJSON(); // => 'String!' + * JSON.stringify({ type: requiredString }); // => '{"type":"String!"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** These types wrap and modify other types */ + +/** + * Returns true when the value is a GraphQL list or non-null wrapper type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL list or non-null wrapper type. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * isWrappingType, + * } from 'graphql/type'; + * + * isWrappingType(new GraphQLList(GraphQLString)); // => true + * isWrappingType(new GraphQLNonNull(GraphQLString)); // => true + * isWrappingType(GraphQLString); // => false + * ``` + */ +export function isWrappingType(type) { + return isListType(type) || isNonNullType(type); +} +/** + * Returns the value as a GraphQL wrapping type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL wrapping type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertWrappingType } from 'graphql/type'; + * + * const wrappingType = assertWrappingType(new GraphQLList(GraphQLString)); + * + * wrappingType.toString(); // => '[String]' + * assertWrappingType(GraphQLString); // throws an error + * ``` + */ + +export function assertWrappingType(type) { + if (!isWrappingType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL wrapping type.`); + } + + return type; +} +/** These types can all accept null as a value. */ + +/** + * Returns true when the value is a GraphQL type that can accept null. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL type that can accept null. + * @example + * ```ts + * import { GraphQLNonNull, GraphQLString, isNullableType } from 'graphql/type'; + * + * isNullableType(GraphQLString); // => true + * isNullableType(new GraphQLNonNull(GraphQLString)); // => false + * isNullableType(null); // => false + * ``` + */ +export function isNullableType(type) { + return isType(type) && !isNonNullType(type); +} +/** + * Returns the value as a nullable GraphQL type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a nullable GraphQL type. + * @example + * ```ts + * import { + * GraphQLNonNull, + * GraphQLString, + * assertNullableType, + * } from 'graphql/type'; + * + * const nullableType = assertNullableType(GraphQLString); + * + * nullableType; // => GraphQLString + * assertNullableType(new GraphQLNonNull(GraphQLString)); // throws an error + * ``` + */ + +export function assertNullableType(type) { + if (!isNullableType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL nullable type.`); + } + + return type; +} +/** + * Returns the nullable type. + * @param type - The GraphQL type to inspect. + * @returns The nullable type after removing one non-null wrapper, if present. + * @example + * ```ts + * import { getNullableType } from 'graphql/type'; + * + * getNullableType(null); // => undefined + * getNullableType(undefined); // => undefined + * ``` + */ + +/** @internal */ +export function getNullableType(type) { + if (type) { + return isNonNullType(type) ? type.ofType : type; + } +} +/** These named types do not include modifiers like List or NonNull. */ + +/** + * Returns true when the value is a GraphQL named type. + * @param type - The GraphQL type to inspect. + * @returns True when the value is a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, isNamedType } from 'graphql/type'; + * + * isNamedType(GraphQLString); // => true + * isNamedType(new GraphQLList(GraphQLString)); // => false + * isNamedType(null); // => false + * ``` + */ +export function isNamedType(type) { + return ( + isScalarType(type) || + isObjectType(type) || + isInterfaceType(type) || + isUnionType(type) || + isEnumType(type) || + isInputObjectType(type) + ); +} +/** + * Returns the value as a GraphQL named type, or throws if it is not one. + * @param type - The GraphQL type to inspect. + * @returns The value typed as a GraphQL named type. + * @example + * ```ts + * import { GraphQLList, GraphQLString, assertNamedType } from 'graphql/type'; + * + * const namedType = assertNamedType(GraphQLString); + * + * namedType.name; // => 'String' + * assertNamedType(new GraphQLList(GraphQLString)); // throws an error + * ``` + */ + +export function assertNamedType(type) { + if (!isNamedType(type)) { + throw new Error(`Expected ${inspect(type)} to be a GraphQL named type.`); + } + + return type; +} +/** + * Returns the named type. + * @param type - The GraphQL type to inspect. + * @returns The named type after unwrapping all list and non-null wrappers. + * @example + * ```ts + * import { getNamedType } from 'graphql/type'; + * + * getNamedType(null); // => undefined + * getNamedType(undefined); // => undefined + * ``` + */ + +/** @internal */ +export function getNamedType(type) { + if (type) { + let unwrappedType = type; + + while (isWrappingType(unwrappedType)) { + unwrappedType = unwrappedType.ofType; + } + + return unwrappedType; + } +} +/** + * Used while defining GraphQL types to allow for circular references in + * otherwise immutable type definitions. + * @typeParam T - The element type returned by the thunk or array. + */ + +/** + * Resolves a thunked readonly array. + * @param thunk - The thunk or value to resolve. + * @returns The resolved readonly array. + * @typeParam T - The element type resolved from the thunk or array. + * @example + * ```ts + * import { GraphQLString, resolveReadonlyArrayThunk } from 'graphql/type'; + * + * const lazyFields = resolveReadonlyArrayThunk(() => [GraphQLString]); + * const fields = resolveReadonlyArrayThunk([GraphQLString]); + * + * lazyFields; // => [GraphQLString] + * fields; // => [GraphQLString] + * ``` + */ +export function resolveReadonlyArrayThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Resolves a thunked object map. + * @param thunk - The thunk or value to resolve. + * @returns The resolved object map. + * @typeParam T - The object-map value type resolved from the thunk or map. + * @example + * ```ts + * import { GraphQLString, resolveObjMapThunk } from 'graphql/type'; + * + * const lazyFields = resolveObjMapThunk(() => ({ name: GraphQLString })); + * const fields = resolveObjMapThunk({ name: GraphQLString }); + * + * lazyFields.name; // => GraphQLString + * fields.name; // => GraphQLString + * ``` + */ + +export function resolveObjMapThunk(thunk) { + return typeof thunk === 'function' ? thunk() : thunk; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Scalar Type Definition + * + * Scalar types define the leaf values of a GraphQL response and the input + * values accepted by arguments and input object fields. A scalar type has a + * name and coercion functions that validate and convert runtime values and + * GraphQL literals. + * + * If a type's serialize function returns `null` or does not return a value + * (i.e. it returns `undefined`) then an error will be raised and a `null` + * value will be returned in the response. Prefer validating inputs before + * execution so clients receive input diagnostics before result coercion fails. + * @typeParam TInternal - The internal runtime representation accepted by this scalar. + * @typeParam TExternal - The serialized representation exposed in GraphQL results. + * @example + * ```ts + * const OddType = new GraphQLScalarType({ + * name: 'Odd', + * serialize: (value) => { + * if (!Number.isFinite(value)) { + * throw new Error( + * `Scalar "Odd" cannot represent "${value}" since it is not a finite number.`, + * ); + * } + * + * if (value % 2 === 0) { + * throw new Error(`Scalar "Odd" cannot represent "${value}" since it is even.`); + * } + * return value; + * } + * }); + * ``` + */ +export class GraphQLScalarType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** URL identifying the behavior specified for this custom scalar. */ + + /** Function that converts internal values to externally visible scalar values. */ + + /** Function that converts variable input into this scalar's internal value. */ + + /** Function that converts AST input literals into this scalar's internal value. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLScalarType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { GraphQLScalarType } from 'graphql/type'; + * + * const document = parse(` + * "Odd integer values." + * scalar Odd @specifiedBy(url: "https://example.com/odd") + * + * extend scalar Odd @specifiedBy(url: "https://example.com/odd-v2") + * `); + * + * const Odd = new GraphQLScalarType({ + * name: 'Odd', + * description: 'Odd integer values.', + * specifiedByURL: 'https://example.com/odd', + * serialize: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only serialize odd numbers.'); + * } + * return value; + * }, + * parseValue: (value) => { + * if (typeof value !== 'number' || value % 2 === 0) { + * throw new TypeError('Odd can only parse odd numbers.'); + * } + * return value; + * }, + * parseLiteral: (ast) => { + * if (ast.kind !== Kind.INT) { + * throw new TypeError('Odd can only parse integer literals.'); + * } + * const value = Number(ast.value); + * if (value % 2 === 0) { + * throw new TypeError('Odd can only parse odd integer literals.'); + * } + * return value; + * }, + * extensions: { numeric: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Odd.description; // => 'Odd integer values.' + * Odd.specifiedByURL; // => 'https://example.com/odd' + * Odd.serialize(3); // => 3 + * Odd.parseValue(5); // => 5 + * Odd.extensions; // => { numeric: true } + * ``` + */ + constructor(config) { + var _config$parseValue, + _config$serialize, + _config$parseLiteral, + _config$extensionASTN; + + const parseValue = + (_config$parseValue = config.parseValue) !== null && + _config$parseValue !== void 0 + ? _config$parseValue + : identityFunc; + this.name = assertName(config.name); + this.description = config.description; + this.specifiedByURL = config.specifiedByURL; + this.serialize = + (_config$serialize = config.serialize) !== null && + _config$serialize !== void 0 + ? _config$serialize + : identityFunc; + this.parseValue = parseValue; + this.parseLiteral = + (_config$parseLiteral = config.parseLiteral) !== null && + _config$parseLiteral !== void 0 + ? _config$parseLiteral + : (node, variables) => parseValue(valueFromASTUntyped(node, variables)); + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + config.specifiedByURL == null || + typeof config.specifiedByURL === 'string' || + devAssert( + false, + `${this.name} must provide "specifiedByURL" as a string, ` + + `but got: ${inspect(config.specifiedByURL)}.`, + ); + config.serialize == null || + typeof config.serialize === 'function' || + devAssert( + false, + `${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.`, + ); + + if (config.parseLiteral) { + (typeof config.parseValue === 'function' && + typeof config.parseLiteral === 'function') || + devAssert( + false, + `${this.name} must provide both "parseValue" and "parseLiteral" functions.`, + ); + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLScalarType'; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const Url = new GraphQLScalarType({ + * name: 'Url', + * description: 'An absolute URL string.', + * specifiedByURL: 'https://url.spec.whatwg.org/', + * }); + * + * const config = Url.toConfig(); + * const UrlCopy = new GraphQLScalarType(config); + * + * config.name; // => 'Url' + * config.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * UrlCopy.name; // => Url.name + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + specifiedByURL: this.specifiedByURL, + serialize: this.serialize, + parseValue: this.parseValue, + parseLiteral: this.parseLiteral, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this scalar type. + * @returns The schema coordinate for this scalar type. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toString(); // => 'DateTime' + * String(DateTime); // => 'DateTime' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLScalarType } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ name: 'DateTime' }); + * + * DateTime.toJSON(); // => 'DateTime' + * JSON.stringify({ type: DateTime }); // => '{"type":"DateTime"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Serializes a runtime value as a scalar output value. + * @typeParam TExternal - The serialized representation returned for GraphQL results. + */ + +/** + * Object Type Definition + * + * Almost all of the GraphQL types you define will be object types. Object types + * have a name, but most importantly describe their fields. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + * @example + * ```ts + * const AddressType = new GraphQLObjectType({ + * name: 'Address', + * fields: { + * street: { type: GraphQLString }, + * number: { type: GraphQLInt }, + * formatted: { + * type: GraphQLString, + * resolve: (obj) => { + * return obj.number + ' ' + obj.street + * } + * } + * } + * }); + * ``` + * @example + * When two types need to refer to each other, or a type needs to refer to + * itself in a field, you can use a function expression (aka a closure or a + * thunk) to supply the fields lazily. + * + * ```ts + * const PersonType = new GraphQLObjectType({ + * name: 'Person', + * fields: () => ({ + * name: { type: GraphQLString }, + * bestFriend: { type: PersonType }, + * }) + * }); + * ``` + */ +export class GraphQLObjectType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Predicate used to determine whether a runtime value belongs to this object type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Configure an object type with interfaces, fields, arguments, and metadata. + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInterfaceType, + * GraphQLNonNull, + * GraphQLObjectType, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * type User implements Node { + * id: ID! + * name(format: String = "short"): String + * } + * + * extend type User { + * displayName: String + * } + * `); + * const definition = document.definitions[0]; + * const nameField = definition.fields[1]; + * const formatArg = nameField.arguments[0]; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const User = new GraphQLObjectType({ + * name: 'User', + * description: 'A registered user.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * name: { + * description: 'The formatted user name.', + * type: GraphQLString, + * args: { + * format: { + * description: 'Controls the name format.', + * type: GraphQLString, + * defaultValue: 'short', + * deprecationReason: 'Use locale instead.', + * extensions: { public: true }, + * astNode: formatArg, + * }, + * }, + * resolve: (user, { format }) => { + * return format === 'long' ? user.fullName : user.name; + * }, + * deprecationReason: 'Use displayName.', + * extensions: { cacheSeconds: 60 }, + * astNode: nameField, + * }, + * }, + * isTypeOf: (value) => { + * return typeof value === 'object' && value != null && 'id' in value; + * }, + * extensions: { entity: 'User' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * User.name; // => 'User' + * User.getInterfaces(); // => [Node] + * Object.keys(User.getFields()); // => ['id', 'name'] + * User.getFields().name.args[0].defaultValue; // => 'short' + * User.extensions; // => { entity: 'User' } + * ``` + * @example + * ```ts + * // This variant configures a subscription field with subscribe and resolve functions. + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { + * greeting: { + * type: GraphQLString, + * subscribe: async function* () { + * yield { greeting: 'Hello!' }; + * }, + * resolve: (event) => { + * return event.greeting; + * }, + * }, + * }, + * }); + * + * typeof Subscription.getFields().greeting.subscribe; // => 'function' + * ``` + */ + constructor(config) { + var _config$extensionASTN2; + + this.name = assertName(config.name); + this.description = config.description; + this.isTypeOf = config.isTypeOf; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN2 = config.extensionASTNodes) !== null && + _config$extensionASTN2 !== void 0 + ? _config$extensionASTN2 + : []; + + this._fields = () => defineFieldMap(config); + + this._interfaces = () => defineInterfaces(config); + + config.isTypeOf == null || + typeof config.isTypeOf === 'function' || + devAssert( + false, + `${this.name} must provide "isTypeOf" as a function, ` + + `but got: ${inspect(config.isTypeOf)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLObjectType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * const fields = User.getFields(); + * + * Object.keys(fields); // => ['id', 'name'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.getInterfaces().map((type) => type.name); // => ['Node'] + * ``` + */ + + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = User.toConfig(); + * const UserCopy = new GraphQLObjectType(config); + * + * config.fields.name.type; // => GraphQLString + * UserCopy.getFields().name.type; // => GraphQLString + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + isTypeOf: this.isTypeOf, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this object type. + * @returns The schema coordinate for this object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const User = assertObjectType(schema.getType('User')); + * + * User.toString(); // => 'User' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString } from 'graphql/type'; + * + * const User = new GraphQLObjectType({ + * name: 'User', + * fields: { name: { type: GraphQLString } }, + * }); + * + * User.toJSON(); // => 'User' + * JSON.stringify({ type: User }); // => '{"type":"User"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +function defineInterfaces(config) { + var _config$interfaces; + + const interfaces = resolveReadonlyArrayThunk( + (_config$interfaces = config.interfaces) !== null && + _config$interfaces !== void 0 + ? _config$interfaces + : [], + ); + Array.isArray(interfaces) || + devAssert( + false, + `${config.name} interfaces must be an Array or a function which returns an Array.`, + ); + return interfaces; +} + +function defineFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + devAssert( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return mapValue(fieldMap, (fieldConfig, fieldName) => { + var _fieldConfig$args; + + isPlainObj(fieldConfig) || + devAssert( + false, + `${config.name}.${fieldName} field config must be an object.`, + ); + fieldConfig.resolve == null || + typeof fieldConfig.resolve === 'function' || + devAssert( + false, + `${config.name}.${fieldName} field resolver must be a function if ` + + `provided, but got: ${inspect(fieldConfig.resolve)}.`, + ); + const argsConfig = + (_fieldConfig$args = fieldConfig.args) !== null && + _fieldConfig$args !== void 0 + ? _fieldConfig$args + : {}; + isPlainObj(argsConfig) || + devAssert( + false, + `${config.name}.${fieldName} args must be an object with argument names as keys.`, + ); + return { + name: assertName(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + args: defineArguments(argsConfig), + resolve: fieldConfig.resolve, + subscribe: fieldConfig.subscribe, + deprecationReason: fieldConfig.deprecationReason, + extensions: toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} +/** @internal */ + +export function defineArguments(config) { + return Object.entries(config).map(([argName, argConfig]) => ({ + name: assertName(argName), + description: argConfig.description, + type: argConfig.type, + defaultValue: argConfig.defaultValue, + deprecationReason: argConfig.deprecationReason, + extensions: toObjMap(argConfig.extensions), + astNode: argConfig.astNode, + })); +} + +function isPlainObj(obj) { + return isObjectLike(obj) && !Array.isArray(obj); +} + +function fieldsToFieldsConfig(fields) { + return mapValue(fields, (field) => ({ + description: field.description, + type: field.type, + args: argsToArgsConfig(field.args), + resolve: field.resolve, + subscribe: field.subscribe, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); +} +/** @internal */ + +export function argsToArgsConfig(args) { + return keyValMap( + args, + (arg) => arg.name, + (arg) => ({ + description: arg.description, + type: arg.type, + defaultValue: arg.defaultValue, + deprecationReason: arg.deprecationReason, + extensions: arg.extensions, + astNode: arg.astNode, + }), + ); +} +/** + * Configuration used to construct a GraphQLObjectType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Returns true when the argument is non-null and has no default value. + * @param arg - The argument definition to inspect. + * @returns True when the argument is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredArgument, + * } from 'graphql/type'; + * + * const requiredArgument = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalArgument = { name: 'name', type: GraphQLString }; + * const argumentWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredArgument(requiredArgument); // => true + * isRequiredArgument(optionalArgument); // => false + * isRequiredArgument(argumentWithDefault); // => false + * ``` + */ +export function isRequiredArgument(arg) { + return isNonNullType(arg.type) && arg.defaultValue === undefined; +} +/** + * A map of field names to resolved field definitions. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Interface Type Definition + * + * When a field can return one of a heterogeneous set of types, a Interface type + * is used to describe what types are possible, what fields are in common across + * all types, as well as a function to determine which type is actually used + * when the field is resolved. + * @example + * ```ts + * const EntityType = new GraphQLInterfaceType({ + * name: 'Entity', + * fields: { + * name: { type: GraphQLString } + * } + * }); + * ``` + */ +export class GraphQLInterfaceType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Function that resolves the concrete object type for this abstract type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLInterfaceType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const document = parse(` + * interface Node { + * id: ID! + * } + * + * interface Resource implements Node { + * id: ID! + * } + * + * extend interface Resource { + * url: String + * } + * `); + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const Resource = new GraphQLInterfaceType({ + * name: 'Resource', + * description: 'An addressable resource.', + * interfaces: [Node], + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'url' in value + * ? 'WebPage' + * : null; + * }, + * extensions: { abstract: true }, + * astNode: document.definitions[1], + * extensionASTNodes: [ document.definitions[2] ], + * }); + * + * Resource.name; // => 'Resource' + * Resource.getInterfaces(); // => [Node] + * Object.keys(Resource.getFields()); // => ['id'] + * Resource.extensions; // => { abstract: true } + * ``` + */ + constructor(config) { + var _config$extensionASTN3; + + this.name = assertName(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN3 = config.extensionASTNodes) !== null && + _config$extensionASTN3 !== void 0 + ? _config$extensionASTN3 + : []; + this._fields = defineFieldMap.bind(undefined, config); + this._interfaces = defineInterfaces.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + devAssert( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLInterfaceType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const fields = Node.getFields(); + * + * Object.keys(fields); // => ['id'] + * String(fields.id.type); // => 'ID!' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns the interfaces implemented by this type. + * @returns The implemented interfaces. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * image: Image + * } + * `); + * + * const Image = assertInterfaceType(schema.getType('Image')); + * + * Image.getInterfaces().map((type) => type.name); // => ['Resource'] + * ``` + */ + + getInterfaces() { + if (typeof this._interfaces === 'function') { + this._interfaces = this._interfaces(); + } + + return this._interfaces; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLID, GraphQLInterfaceType, GraphQLNonNull } from 'graphql/type'; + * + * const Node = new GraphQLInterfaceType({ + * name: 'Node', + * fields: { + * id: { type: new GraphQLNonNull(GraphQLID) }, + * }, + * }); + * + * const config = Node.toConfig(); + * const NodeCopy = new GraphQLInterfaceType(config); + * + * String(config.fields.id.type); // => 'ID!' + * String(NodeCopy.getFields().id.type); // => 'ID!' + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + interfaces: this.getInterfaces(), + fields: fieldsToFieldsConfig(this.getFields()), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this interface type. + * @returns The schema coordinate for this interface type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * + * Node.toString(); // => 'Node' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInterfaceType, GraphQLString } from 'graphql/type'; + * + * const Named = new GraphQLInterfaceType({ + * name: 'Named', + * fields: { name: { type: GraphQLString } }, + * }); + * + * Named.toJSON(); // => 'Named' + * JSON.stringify({ type: Named }); // => '{"type":"Named"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** + * Configuration used to construct a GraphQLInterfaceType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Union Type Definition + * + * When a field can return one of a heterogeneous set of types, a Union type + * is used to describe what types are possible as well as providing a function + * to determine which type is actually used when the field is resolved. + * @example + * ```ts + * const PetType = new GraphQLUnionType({ + * name: 'Pet', + * types: [DogType, CatType], + * resolveType: (value) => { + * if (value instanceof Dog) { + * return DogType; + * } + * if (value instanceof Cat) { + * return CatType; + * } + * } + * }); + * ``` + */ +export class GraphQLUnionType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Function that resolves the concrete object type for this abstract type. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLUnionType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const document = parse(` + * union Media = Photo | Video + * + * extend union Media = Audio + * `); + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * + * const Media = new GraphQLUnionType({ + * name: 'Media', + * description: 'Media that can appear in a search result.', + * types: [Photo, Video], + * resolveType: (value) => { + * return typeof value === 'object' && value != null && 'duration' in value + * ? 'Video' + * : 'Photo'; + * }, + * extensions: { searchable: true }, + * astNode: document.definitions[0], + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Media.description; // => 'Media that can appear in a search result.' + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * Media.extensions; // => { searchable: true } + * ``` + */ + constructor(config) { + var _config$extensionASTN4; + + this.name = assertName(config.name); + this.description = config.description; + this.resolveType = config.resolveType; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN4 = config.extensionASTNodes) !== null && + _config$extensionASTN4 !== void 0 + ? _config$extensionASTN4 + : []; + this._types = defineTypes.bind(undefined, config); + config.resolveType == null || + typeof config.resolveType === 'function' || + devAssert( + false, + `${this.name} must provide "resolveType" as a function, ` + + `but got: ${inspect(config.resolveType)}.`, + ); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLUnionType'; + } + /** + * Returns the object types included in this union. + * @returns The union member object types. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * + * type Query { + * media: [Media] + * } + * `); + * + * const Media = assertUnionType(schema.getType('Media')); + * + * Media.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + + getTypes() { + if (typeof this._types === 'function') { + this._types = this._types(); + } + + return this._types; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const Video = new GraphQLObjectType({ + * name: 'Video', + * fields: { url: { type: GraphQLString } }, + * }); + * const Media = new GraphQLUnionType({ + * name: 'Media', + * types: [Photo, Video], + * }); + * + * const config = Media.toConfig(); + * const MediaCopy = new GraphQLUnionType(config); + * + * MediaCopy.getTypes().map((type) => type.name); // => ['Photo', 'Video'] + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + types: this.getTypes(), + resolveType: this.resolveType, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this union type. + * @returns The schema coordinate for this union type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * union SearchResult = Photo + * + * type Query { + * search: [SearchResult] + * } + * `); + * + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * SearchResult.toString(); // => 'SearchResult' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLObjectType, GraphQLString, GraphQLUnionType } from 'graphql/type'; + * + * const Photo = new GraphQLObjectType({ + * name: 'Photo', + * fields: { url: { type: GraphQLString } }, + * }); + * const SearchResult = new GraphQLUnionType({ + * name: 'SearchResult', + * types: [Photo], + * }); + * + * SearchResult.toJSON(); // => 'SearchResult' + * JSON.stringify({ type: SearchResult }); // => '{"type":"SearchResult"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +function defineTypes(config) { + const types = resolveReadonlyArrayThunk(config.types); + Array.isArray(types) || + devAssert( + false, + `Must provide Array of types or a function which returns such an array for Union ${config.name}.`, + ); + return types; +} +/** + * Configuration used to construct a GraphQLUnionType. + * @typeParam TSource - Source object type passed to resolvers. + * @typeParam TContext - Context object type passed to resolvers. + */ + +/** + * Enum Type Definition + * + * Enum types define leaf values whose serialized form is one of a fixed set + * of GraphQL enum names. Internally, enum values can map to any runtime value, + * often integers. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGBType = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGBType.getValue('GREEN')?.value; // => 1 + * ``` + * + * Note: If a value is not provided in a definition, the name of the enum value + * will be used as its internal value. + */ +export class GraphQLEnumType { + /* */ + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLEnumType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const document = parse(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * extend enum Episode { + * FORCE_AWAKENS + * } + * `); + * const definition = document.definitions[0]; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * description: 'A Star Wars film episode.', + * values: { + * NEW_HOPE: { + * value: 4, + * description: 'Released in 1977.', + * extensions: { trilogy: 'original' }, + * astNode: definition.values[0], + * }, + * EMPIRE: { value: 5, astNode: definition.values[1] }, + * JEDI: { + * value: 6, + * deprecationReason: 'Use RETURN_OF_THE_JEDI.', + * astNode: definition.values[2], + * }, + * }, + * extensions: { catalog: 'films' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * Episode.description; // => 'A Star Wars film episode.' + * Episode.serialize(5); // => 'EMPIRE' + * Episode.parseValue('JEDI'); // => 6 + * Episode.getValue('JEDI').deprecationReason; // => 'Use RETURN_OF_THE_JEDI.' + * Episode.extensions; // => { catalog: 'films' } + * ``` + */ + constructor(config) { + var _config$extensionASTN5; + + this.name = assertName(config.name); + this.description = config.description; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN5 = config.extensionASTNodes) !== null && + _config$extensionASTN5 !== void 0 + ? _config$extensionASTN5 + : []; + this._values = + typeof config.values === 'function' + ? config.values + : defineEnumValues(this.name, config.values); + this._valueLookup = null; + this._nameLookup = null; + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLEnumType'; + } + /** + * Returns the values defined by this enum type. + * @returns Enum value definitions in schema order. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * JEDI + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValues().map((value) => value.name); // => ['NEW_HOPE', 'EMPIRE', 'JEDI'] + * ``` + */ + + getValues() { + if (typeof this._values === 'function') { + this._values = defineEnumValues(this.name, this._values()); + } + + return this._values; + } + /** + * Returns the enum value definition for a value name. + * @param name - The GraphQL name to look up. + * @returns The matching enum value definition, if it exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.getValue('EMPIRE')?.name; // => 'EMPIRE' + * Episode.getValue('JEDI'); // => undefined + * ``` + */ + + getValue(name) { + if (this._nameLookup === null) { + this._nameLookup = keyMap(this.getValues(), (value) => value.name); + } + + return this._nameLookup[name]; + } + /** + * Serializes a runtime enum value as a GraphQL enum name. + * @param outputValue - Runtime enum value to serialize. + * @returns The GraphQL enum name for the runtime value. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.serialize(1); // => 'GREEN' + * RGB.serialize(3); // throws an error + * ``` + */ + + serialize(outputValue) { + if (this._valueLookup === null) { + this._valueLookup = new Map( + this.getValues().map((enumValue) => [enumValue.value, enumValue]), + ); + } + + const enumValue = this._valueLookup.get(outputValue); + + if (enumValue === undefined) { + throw new GraphQLError( + `Enum "${this.name}" cannot represent value: ${inspect(outputValue)}`, + ); + } + + return enumValue.name; + } + /** + * Parses a GraphQL enum name from variable input. + * @param inputValue - Runtime input value to parse. + * @returns The internal enum value represented by the input name. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseValue('BLUE'); // => 2 + * RGB.parseValue('PURPLE'); // throws an error + * RGB.parseValue(2); // throws an error + * ``` + */ + + parseValue(inputValue) /* T */ + { + if (typeof inputValue !== 'string') { + const valueStr = inspect(inputValue); + throw new GraphQLError( + `Enum "${this.name}" cannot represent non-string value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + ); + } + + const enumValue = this.getValue(inputValue); + + if (enumValue == null) { + throw new GraphQLError( + `Value "${inputValue}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, inputValue), + ); + } + + return enumValue.value; + } + /** + * Parses a GraphQL enum name from an AST value literal. + * @param valueNode - AST value literal to parse. + * @param _variables - Runtime variable values; ignored because enum literals cannot contain variables. + * @returns The internal enum value represented by the literal. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * RGB.parseLiteral(parseValue('RED')); // => 0 + * RGB.parseLiteral(parseValue('"RED"')); // throws an error + * ``` + */ + + parseLiteral(valueNode, _variables) /* T */ + { + // Note: variables will be resolved to a value before calling this function. + if (valueNode.kind !== Kind.ENUM) { + const valueStr = print(valueNode); + throw new GraphQLError( + `Enum "${this.name}" cannot represent non-enum value: ${valueStr}.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + }, + ); + } + + const enumValue = this.getValue(valueNode.value); + + if (enumValue == null) { + const valueStr = print(valueNode); + throw new GraphQLError( + `Value "${valueStr}" does not exist in "${this.name}" enum.` + + didYouMeanEnumValue(this, valueStr), + { + nodes: valueNode, + }, + ); + } + + return enumValue.value; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const RGB = new GraphQLEnumType({ + * name: 'RGB', + * values: { + * RED: { value: 0 }, + * GREEN: { value: 1 }, + * BLUE: { value: 2 }, + * }, + * }); + * + * const config = RGB.toConfig(); + * const RGBCopy = new GraphQLEnumType(config); + * + * config.values.GREEN.value; // => 1 + * RGBCopy.serialize(2); // => 'BLUE' + * ``` + */ + + toConfig() { + const values = keyValMap( + this.getValues(), + (value) => value.name, + (value) => ({ + description: value.description, + value: value.value, + deprecationReason: value.deprecationReason, + extensions: value.extensions, + astNode: value.astNode, + }), + ); + return { + name: this.name, + description: this.description, + values, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this enum type. + * @returns The schema coordinate for this enum type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertEnumType } from 'graphql/type'; + * + * const schema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const Episode = assertEnumType(schema.getType('Episode')); + * + * Episode.toString(); // => 'Episode' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLEnumType } from 'graphql/type'; + * + * const Episode = new GraphQLEnumType({ + * name: 'Episode', + * values: { + * NEW_HOPE: {}, + * }, + * }); + * + * Episode.toJSON(); // => 'Episode' + * JSON.stringify({ type: Episode }); // => '{"type":"Episode"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +function didYouMeanEnumValue(enumType, unknownValueStr) { + const allNames = enumType.getValues().map((value) => value.name); + const suggestedValues = suggestionList(unknownValueStr, allNames); + return didYouMean('the enum value', suggestedValues); +} + +function defineEnumValues(typeName, valueMap) { + isPlainObj(valueMap) || + devAssert( + false, + `${typeName} values must be an object with value names as keys.`, + ); + return Object.entries(valueMap).map(([valueName, valueConfig]) => { + isPlainObj(valueConfig) || + devAssert( + false, + `${typeName}.${valueName} must refer to an object with a "value" key ` + + `representing an internal value but got: ${inspect(valueConfig)}.`, + ); + return { + name: assertEnumValueName(valueName), + description: valueConfig.description, + value: valueConfig.value !== undefined ? valueConfig.value : valueName, + deprecationReason: valueConfig.deprecationReason, + extensions: toObjMap(valueConfig.extensions), + astNode: valueConfig.astNode, + }; + }); +} +/** Configuration used to construct a GraphQLEnumType. */ + +/** + * Input Object Type Definition + * + * An input object defines a structured collection of fields which may be + * supplied to a field argument. + * + * Using `NonNull` will ensure that a value must be provided by the query + * @example + * ```ts + * const GeoPoint = new GraphQLInputObjectType({ + * name: 'GeoPoint', + * fields: { + * lat: { type: new GraphQLNonNull(GraphQLFloat) }, + * lon: { type: new GraphQLNonNull(GraphQLFloat) }, + * alt: { type: GraphQLFloat, defaultValue: 0 }, + * } + * }); + * ``` + */ +export class GraphQLInputObjectType { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** Whether this input object uses the experimental OneOf input object semantics. */ + + /** + * Creates a GraphQLInputObjectType instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { + * GraphQLID, + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * + * const document = parse(` + * input ReviewInput { + * stars: Int! + * commentary: String + * } + * + * extend input ReviewInput { + * body: String + * } + * `); + * const definition = document.definitions[0]; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * description: 'Input collected when reviewing a product.', + * fields: { + * stars: { + * description: 'Star rating from one to five.', + * type: new GraphQLNonNull(GraphQLInt), + * extensions: { min: 1, max: 5 }, + * astNode: definition.fields[0], + * }, + * commentary: { + * type: GraphQLString, + * defaultValue: '', + * deprecationReason: 'Use body.', + * astNode: definition.fields[1], + * }, + * }, + * extensions: { form: 'review' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * isOneOf: false, + * }); + * const SearchBy = new GraphQLInputObjectType({ + * name: 'SearchBy', + * fields: { + * id: { type: GraphQLID }, + * slug: { type: GraphQLString }, + * }, + * isOneOf: true, + * }); + * + * const fields = ReviewInput.getFields(); + * + * ReviewInput.description; // => 'Input collected when reviewing a product.' + * String(fields.stars.type); // => 'Int!' + * fields.stars.extensions; // => { min: 1, max: 5 } + * fields.commentary.defaultValue; // => '' + * fields.commentary.deprecationReason; // => 'Use body.' + * ReviewInput.isOneOf; // => false + * SearchBy.isOneOf; // => true + * ``` + */ + constructor(config) { + var _config$extensionASTN6, _config$isOneOf; + + this.name = assertName(config.name); + this.description = config.description; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN6 = config.extensionASTNodes) !== null && + _config$extensionASTN6 !== void 0 + ? _config$extensionASTN6 + : []; + this.isOneOf = + (_config$isOneOf = config.isOneOf) !== null && _config$isOneOf !== void 0 + ? _config$isOneOf + : false; + this._fields = defineInputFieldMap.bind(undefined, config); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLInputObjectType'; + } + /** + * Returns the fields defined by this type. + * @returns The fields keyed by field name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * commentary: String = "" + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * const fields = ReviewInput.getFields(); + * + * Object.keys(fields); // => ['stars', 'commentary'] + * fields.commentary.defaultValue; // => '' + * ``` + */ + + getFields() { + if (typeof this._fields === 'function') { + this._fields = this._fields(); + } + + return this._fields; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * }, + * }); + * + * const config = ReviewInput.toConfig(); + * const ReviewInputCopy = new GraphQLInputObjectType(config); + * + * String(config.fields.stars.type); // => 'Int!' + * String(ReviewInputCopy.getFields().stars.type); // => 'Int!' + * ``` + */ + + toConfig() { + const fields = mapValue(this.getFields(), (field) => ({ + description: field.description, + type: field.type, + defaultValue: field.defaultValue, + deprecationReason: field.deprecationReason, + extensions: field.extensions, + astNode: field.astNode, + })); + return { + name: this.name, + description: this.description, + fields, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + isOneOf: this.isOneOf, + }; + } + /** + * Returns the schema coordinate identifying this input object type. + * @returns The schema coordinate for this input object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInputObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * input ReviewInput { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewInput): [String] + * } + * `); + * + * const ReviewInput = assertInputObjectType(schema.getType('ReviewInput')); + * + * ReviewInput.toString(); // => 'ReviewInput' + * ``` + */ + + toString() { + return this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { GraphQLInputObjectType, GraphQLString } from 'graphql/type'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * commentary: { type: GraphQLString }, + * }, + * }); + * + * ReviewInput.toJSON(); // => 'ReviewInput' + * JSON.stringify({ type: ReviewInput }); // => '{"type":"ReviewInput"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} + +function defineInputFieldMap(config) { + const fieldMap = resolveObjMapThunk(config.fields); + isPlainObj(fieldMap) || + devAssert( + false, + `${config.name} fields must be an object with field names as keys or a function which returns such an object.`, + ); + return mapValue(fieldMap, (fieldConfig, fieldName) => { + !('resolve' in fieldConfig) || + devAssert( + false, + `${config.name}.${fieldName} field has a resolve property, but Input Types cannot define resolvers.`, + ); + return { + name: assertName(fieldName), + description: fieldConfig.description, + type: fieldConfig.type, + defaultValue: fieldConfig.defaultValue, + deprecationReason: fieldConfig.deprecationReason, + extensions: toObjMap(fieldConfig.extensions), + astNode: fieldConfig.astNode, + }; + }); +} +/** Configuration used to construct a GraphQLInputObjectType. */ + +/** + * Returns true when the input field is non-null and has no default value. + * @param field - The input field definition to inspect. + * @returns True when the input field is non-null and has no default value. + * @example + * ```ts + * import { + * GraphQLInt, + * GraphQLNonNull, + * GraphQLString, + * isRequiredInputField, + * } from 'graphql/type'; + * + * const requiredField = { name: 'id', type: new GraphQLNonNull(GraphQLInt) }; + * const optionalField = { name: 'name', type: GraphQLString }; + * const fieldWithDefault = { + * name: 'limit', + * type: new GraphQLNonNull(GraphQLInt), + * defaultValue: 10, + * }; + * + * isRequiredInputField(requiredField); // => true + * isRequiredInputField(optionalField); // => false + * isRequiredInputField(fieldWithDefault); // => false + * ``` + */ +export function isRequiredInputField(field) { + return isNonNullType(field.type) && field.defaultValue === undefined; +} +/** A map of input field names to resolved input field definitions. */ diff --git a/node_modules/graphql/type/directives.d.ts b/node_modules/graphql/type/directives.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a44412aa2dc08e7d70121108e7b17ba194aa6a5a --- /dev/null +++ b/node_modules/graphql/type/directives.d.ts @@ -0,0 +1,273 @@ +/** @category Directives */ +import type { Maybe } from '../jsutils/Maybe'; +import type { + DirectiveDefinitionNode, + DirectiveExtensionNode, +} from '../language/ast'; +import { DirectiveLocation } from '../language/directiveLocation'; +import type { + GraphQLArgument, + GraphQLFieldConfigArgumentMap, +} from './definition'; +/** + * Test if the given value is a GraphQL directive. + * @param directive - Value to inspect. + * @returns True when the value is a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString, isDirective } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isDirective(upper); // => true + * isDirective(GraphQLString); // => false + * ``` + */ +export declare function isDirective( + directive: unknown, +): directive is GraphQLDirective; +/** + * Returns the value as a GraphQLDirective, or throws if it is not a directive. + * @param directive - Value to inspect. + * @returns The value typed as a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { assertDirective, GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * assertDirective(upper); // => upper + * assertDirective(GraphQLString); // throws an error + * ``` + */ +export declare function assertDirective(directive: unknown): GraphQLDirective; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLDirectiveExtensions { + [attributeName: string]: unknown; +} +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export declare class GraphQLDirective { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Locations where this directive may be applied. */ + locations: ReadonlyArray; + /** Arguments accepted by this field or directive. */ + args: ReadonlyArray; + /** Whether this directive may appear more than once at the same location. */ + isRepeatable: boolean; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + /** + * Creates a GraphQLDirective instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const document = parse(` + * directive @cacheControl(maxAge: Int) repeatable on FIELD_DEFINITION + * extend directive @cacheControl(maxAge: Int) on FIELD_DEFINITION + * `); + * const definition = document.definitions[0]; + * + * const cacheControl = new GraphQLDirective({ + * name: 'cacheControl', + * description: 'Controls HTTP cache hints for a field.', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * inheritMaxAge: { + * description: 'Inherit the parent cache hint.', + * type: new GraphQLNonNull(GraphQLBoolean), + * defaultValue: false, + * deprecationReason: 'Use maxAge instead.', + * extensions: { scope: 'cache' }, + * }, + * maxAge: { + * type: GraphQLInt, + * astNode: definition.arguments[0], + * }, + * }, + * isRepeatable: true, + * deprecationReason: 'Use @cache instead.', + * extensions: { scope: 'cache' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * cacheControl.name; // => 'cacheControl' + * cacheControl.description; // => 'Controls HTTP cache hints for a field.' + * cacheControl.args[0].name; // => 'inheritMaxAge' + * cacheControl.args[0].defaultValue; // => false + * cacheControl.isRepeatable; // => true + * cacheControl.extensions; // => { scope: 'cache' } + * ``` + */ + constructor(config: Readonly); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = tag.toConfig(); + * const tagCopy = new GraphQLDirective(config); + * + * config.args.name.type; // => GraphQLString + * tagCopy.args[0].name; // => 'name' + * ``` + */ + toConfig(): GraphQLDirectiveNormalizedConfig; + /** + * Returns the schema coordinate identifying this directive. + * @returns The directive schema coordinate. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toString(); // => '@tag' + * ``` + */ + toString(): string; + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toJSON(); // => '@tag' + * JSON.stringify({ directive: tag }); // => '{"directive":"@tag"}' + * ``` + */ + toJSON(): string; +} +/** Configuration used to construct a GraphQLDirective. */ +export interface GraphQLDirectiveConfig { + /** The GraphQL name for this schema element. */ + name: string; + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Locations where this directive may be applied. */ + locations: ReadonlyArray; + /** Arguments accepted by this field or directive. */ + args?: Maybe; + /** Whether this directive may appear more than once at the same location. */ + isRepeatable?: Maybe; + /** Reason this element is deprecated, if one was provided. */ + deprecationReason?: Maybe; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +interface GraphQLDirectiveNormalizedConfig extends GraphQLDirectiveConfig { + args: GraphQLFieldConfigArgumentMap; + isRepeatable: boolean; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; +} +/** Used to conditionally include fields or fragments. */ +export declare const GraphQLIncludeDirective: GraphQLDirective; +/** Used to conditionally skip (exclude) fields or fragments. */ +export declare const GraphQLSkipDirective: GraphQLDirective; +/** Constant string used for default reason for a deprecation. */ +export declare const DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + * + * The optional `reason` argument defaults to `DEFAULT_DEPRECATION_REASON`. + */ +export declare const GraphQLDeprecatedDirective: GraphQLDirective; +/** Used to provide a URL for specifying the behavior of custom scalar definitions. */ +export declare const GraphQLSpecifiedByDirective: GraphQLDirective; +/** Used to indicate an Input Object is a OneOf Input Object. */ +export declare const GraphQLOneOfDirective: GraphQLDirective; +/** Full list of stable directives specified by GraphQL.js. */ +export declare const specifiedDirectives: ReadonlyArray; +/** + * Returns true when the directive is one of the directives specified by GraphQL. + * @param directive - Directive to inspect. + * @returns True when the directive is specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLDirective, + * GraphQLIncludeDirective, + * isSpecifiedDirective, + * } from 'graphql/type'; + * import { DirectiveLocation } from 'graphql/language'; + * + * const customDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isSpecifiedDirective(GraphQLIncludeDirective); // => true + * isSpecifiedDirective(customDirective); // => false + * ``` + */ +export declare function isSpecifiedDirective( + directive: GraphQLDirective, +): boolean; +export {}; diff --git a/node_modules/graphql/type/directives.js b/node_modules/graphql/type/directives.js new file mode 100644 index 0000000000000000000000000000000000000000..fa1bfadf9c9e3d5b87f46f1b2502a9eaf3b0e032 --- /dev/null +++ b/node_modules/graphql/type/directives.js @@ -0,0 +1,424 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.GraphQLSpecifiedByDirective = + exports.GraphQLSkipDirective = + exports.GraphQLOneOfDirective = + exports.GraphQLIncludeDirective = + exports.GraphQLDirective = + exports.GraphQLDeprecatedDirective = + exports.DEFAULT_DEPRECATION_REASON = + void 0; +exports.assertDirective = assertDirective; +exports.isDirective = isDirective; +exports.isSpecifiedDirective = isSpecifiedDirective; +exports.specifiedDirectives = void 0; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _instanceOf = require('../jsutils/instanceOf.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _toObjMap = require('../jsutils/toObjMap.js'); + +var _directiveLocation = require('../language/directiveLocation.js'); + +var _assertName = require('./assertName.js'); + +var _definition = require('./definition.js'); + +var _scalars = require('./scalars.js'); + +/** @category Directives */ + +/** + * Test if the given value is a GraphQL directive. + * @param directive - Value to inspect. + * @returns True when the value is a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString, isDirective } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isDirective(upper); // => true + * isDirective(GraphQLString); // => false + * ``` + */ +function isDirective(directive) { + return (0, _instanceOf.instanceOf)(directive, GraphQLDirective); +} +/** + * Returns the value as a GraphQLDirective, or throws if it is not a directive. + * @param directive - Value to inspect. + * @returns The value typed as a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { assertDirective, GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * assertDirective(upper); // => upper + * assertDirective(GraphQLString); // throws an error + * ``` + */ + +function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(directive)} to be a GraphQL directive.`, + ); + } + + return directive; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +class GraphQLDirective { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Locations where this directive may be applied. */ + + /** Arguments accepted by this field or directive. */ + + /** Whether this directive may appear more than once at the same location. */ + + /** Reason this element is deprecated, if one was provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLDirective instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const document = parse(` + * directive @cacheControl(maxAge: Int) repeatable on FIELD_DEFINITION + * extend directive @cacheControl(maxAge: Int) on FIELD_DEFINITION + * `); + * const definition = document.definitions[0]; + * + * const cacheControl = new GraphQLDirective({ + * name: 'cacheControl', + * description: 'Controls HTTP cache hints for a field.', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * inheritMaxAge: { + * description: 'Inherit the parent cache hint.', + * type: new GraphQLNonNull(GraphQLBoolean), + * defaultValue: false, + * deprecationReason: 'Use maxAge instead.', + * extensions: { scope: 'cache' }, + * }, + * maxAge: { + * type: GraphQLInt, + * astNode: definition.arguments[0], + * }, + * }, + * isRepeatable: true, + * deprecationReason: 'Use @cache instead.', + * extensions: { scope: 'cache' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * cacheControl.name; // => 'cacheControl' + * cacheControl.description; // => 'Controls HTTP cache hints for a field.' + * cacheControl.args[0].name; // => 'inheritMaxAge' + * cacheControl.args[0].defaultValue; // => false + * cacheControl.isRepeatable; // => true + * cacheControl.extensions; // => { scope: 'cache' } + * ``` + */ + constructor(config) { + var _config$isRepeatable, _config$extensionASTN, _config$args; + + this.name = (0, _assertName.assertName)(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = + (_config$isRepeatable = config.isRepeatable) !== null && + _config$isRepeatable !== void 0 + ? _config$isRepeatable + : false; + this.deprecationReason = config.deprecationReason; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + Array.isArray(config.locations) || + (0, _devAssert.devAssert)( + false, + `@${config.name} locations must be an Array.`, + ); + const args = + (_config$args = config.args) !== null && _config$args !== void 0 + ? _config$args + : {}; + ((0, _isObjectLike.isObjectLike)(args) && !Array.isArray(args)) || + (0, _devAssert.devAssert)( + false, + `@${config.name} args must be an object with argument names as keys.`, + ); + this.args = (0, _definition.defineArguments)(args); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLDirective'; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = tag.toConfig(); + * const tagCopy = new GraphQLDirective(config); + * + * config.args.name.type; // => GraphQLString + * tagCopy.args[0].name; // => 'name' + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: (0, _definition.argsToArgsConfig)(this.args), + isRepeatable: this.isRepeatable, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this directive. + * @returns The directive schema coordinate. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toString(); // => '@tag' + * ``` + */ + + toString() { + return '@' + this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toJSON(); // => '@tag' + * JSON.stringify({ directive: tag }); // => '{"directive":"@tag"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** Configuration used to construct a GraphQLDirective. */ + +exports.GraphQLDirective = GraphQLDirective; + +/** Used to conditionally include fields or fragments. */ +const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); +/** Used to conditionally skip (exclude) fields or fragments. */ + +exports.GraphQLIncludeDirective = GraphQLIncludeDirective; +const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD, + _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); +/** Constant string used for default reason for a deprecation. */ + +exports.GraphQLSkipDirective = GraphQLSkipDirective; +const DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + * + * The optional `reason` argument defaults to `DEFAULT_DEPRECATION_REASON`. + */ + +exports.DEFAULT_DEPRECATION_REASON = DEFAULT_DEPRECATION_REASON; +const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [ + _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + _directiveLocation.DirectiveLocation.ENUM_VALUE, + _directiveLocation.DirectiveLocation.DIRECTIVE_DEFINITION, + ], + args: { + reason: { + type: _scalars.GraphQLString, + description: + '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/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, +}); +/** Used to provide a URL for specifying the behavior of custom scalar definitions. */ + +exports.GraphQLDeprecatedDirective = GraphQLDeprecatedDirective; +const GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behavior of this scalar.', + locations: [_directiveLocation.DirectiveLocation.SCALAR], + args: { + url: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The URL that specifies the behavior of this scalar.', + }, + }, +}); +/** Used to indicate an Input Object is a OneOf Input Object. */ + +exports.GraphQLSpecifiedByDirective = GraphQLSpecifiedByDirective; +const GraphQLOneOfDirective = new GraphQLDirective({ + name: 'oneOf', + description: + 'Indicates exactly one field must be supplied and this field must not be `null`.', + locations: [_directiveLocation.DirectiveLocation.INPUT_OBJECT], + args: {}, +}); +/** Full list of stable directives specified by GraphQL.js. */ + +exports.GraphQLOneOfDirective = GraphQLOneOfDirective; +const specifiedDirectives = Object.freeze([ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, +]); +/** + * Returns true when the directive is one of the directives specified by GraphQL. + * @param directive - Directive to inspect. + * @returns True when the directive is specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLDirective, + * GraphQLIncludeDirective, + * isSpecifiedDirective, + * } from 'graphql/type'; + * import { DirectiveLocation } from 'graphql/language'; + * + * const customDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isSpecifiedDirective(GraphQLIncludeDirective); // => true + * isSpecifiedDirective(customDirective); // => false + * ``` + */ + +exports.specifiedDirectives = specifiedDirectives; + +function isSpecifiedDirective(directive) { + return specifiedDirectives.some(({ name }) => name === directive.name); +} diff --git a/node_modules/graphql/type/directives.mjs b/node_modules/graphql/type/directives.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c9a1fb5d09edded7905f5880fbec715159324df4 --- /dev/null +++ b/node_modules/graphql/type/directives.mjs @@ -0,0 +1,388 @@ +/** @category Directives */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { instanceOf } from '../jsutils/instanceOf.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { toObjMap } from '../jsutils/toObjMap.mjs'; +import { DirectiveLocation } from '../language/directiveLocation.mjs'; +import { assertName } from './assertName.mjs'; +import { + argsToArgsConfig, + defineArguments, + GraphQLNonNull, +} from './definition.mjs'; +import { GraphQLBoolean, GraphQLString } from './scalars.mjs'; +/** + * Test if the given value is a GraphQL directive. + * @param directive - Value to inspect. + * @returns True when the value is a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString, isDirective } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isDirective(upper); // => true + * isDirective(GraphQLString); // => false + * ``` + */ + +export function isDirective(directive) { + return instanceOf(directive, GraphQLDirective); +} +/** + * Returns the value as a GraphQLDirective, or throws if it is not a directive. + * @param directive - Value to inspect. + * @returns The value typed as a GraphQLDirective. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { assertDirective, GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const upper = new GraphQLDirective({ + * name: 'upper', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * assertDirective(upper); // => upper + * assertDirective(GraphQLString); // throws an error + * ``` + */ + +export function assertDirective(directive) { + if (!isDirective(directive)) { + throw new Error( + `Expected ${inspect(directive)} to be a GraphQL directive.`, + ); + } + + return directive; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Directives are used by the GraphQL runtime as a way of modifying execution + * behavior. Type system creators will usually not create these directly. + */ +export class GraphQLDirective { + /** The GraphQL name for this schema element. */ + + /** Human-readable description for this schema element, if provided. */ + + /** Locations where this directive may be applied. */ + + /** Arguments accepted by this field or directive. */ + + /** Whether this directive may appear more than once at the same location. */ + + /** Reason this element is deprecated, if one was provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Creates a GraphQLDirective instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLInt, + * GraphQLNonNull, + * } from 'graphql/type'; + * + * const document = parse(` + * directive @cacheControl(maxAge: Int) repeatable on FIELD_DEFINITION + * extend directive @cacheControl(maxAge: Int) on FIELD_DEFINITION + * `); + * const definition = document.definitions[0]; + * + * const cacheControl = new GraphQLDirective({ + * name: 'cacheControl', + * description: 'Controls HTTP cache hints for a field.', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * inheritMaxAge: { + * description: 'Inherit the parent cache hint.', + * type: new GraphQLNonNull(GraphQLBoolean), + * defaultValue: false, + * deprecationReason: 'Use maxAge instead.', + * extensions: { scope: 'cache' }, + * }, + * maxAge: { + * type: GraphQLInt, + * astNode: definition.arguments[0], + * }, + * }, + * isRepeatable: true, + * deprecationReason: 'Use @cache instead.', + * extensions: { scope: 'cache' }, + * astNode: definition, + * extensionASTNodes: [ document.definitions[1] ], + * }); + * + * cacheControl.name; // => 'cacheControl' + * cacheControl.description; // => 'Controls HTTP cache hints for a field.' + * cacheControl.args[0].name; // => 'inheritMaxAge' + * cacheControl.args[0].defaultValue; // => false + * cacheControl.isRepeatable; // => true + * cacheControl.extensions; // => { scope: 'cache' } + * ``` + */ + constructor(config) { + var _config$isRepeatable, _config$extensionASTN, _config$args; + + this.name = assertName(config.name); + this.description = config.description; + this.locations = config.locations; + this.isRepeatable = + (_config$isRepeatable = config.isRepeatable) !== null && + _config$isRepeatable !== void 0 + ? _config$isRepeatable + : false; + this.deprecationReason = config.deprecationReason; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + Array.isArray(config.locations) || + devAssert(false, `@${config.name} locations must be an Array.`); + const args = + (_config$args = config.args) !== null && _config$args !== void 0 + ? _config$args + : {}; + (isObjectLike(args) && !Array.isArray(args)) || + devAssert( + false, + `@${config.name} args must be an object with argument names as keys.`, + ); + this.args = defineArguments(args); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLDirective'; + } + /** + * Returns a normalized configuration object for this object. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective, GraphQLString } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const config = tag.toConfig(); + * const tagCopy = new GraphQLDirective(config); + * + * config.args.name.type; // => GraphQLString + * tagCopy.args[0].name; // => 'name' + * ``` + */ + + toConfig() { + return { + name: this.name, + description: this.description, + locations: this.locations, + args: argsToArgsConfig(this.args), + isRepeatable: this.isRepeatable, + deprecationReason: this.deprecationReason, + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + }; + } + /** + * Returns the schema coordinate identifying this directive. + * @returns The directive schema coordinate. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toString(); // => '@tag' + * ``` + */ + + toString() { + return '@' + this.name; + } + /** + * Returns the JSON representation used when this object is serialized. + * @returns The JSON-serializable representation. + * @example + * ```ts + * import { DirectiveLocation } from 'graphql/language'; + * import { GraphQLDirective } from 'graphql/type'; + * + * const tag = new GraphQLDirective({ + * name: 'tag', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * tag.toJSON(); // => '@tag' + * JSON.stringify({ directive: tag }); // => '{"directive":"@tag"}' + * ``` + */ + + toJSON() { + return this.toString(); + } +} +/** Configuration used to construct a GraphQLDirective. */ + +/** Used to conditionally include fields or fragments. */ +export const GraphQLIncludeDirective = new GraphQLDirective({ + name: 'include', + description: + 'Directs the executor to include this field or fragment only when the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Included when true.', + }, + }, +}); +/** Used to conditionally skip (exclude) fields or fragments. */ + +export const GraphQLSkipDirective = new GraphQLDirective({ + name: 'skip', + description: + 'Directs the executor to skip this field or fragment when the `if` argument is true.', + locations: [ + DirectiveLocation.FIELD, + DirectiveLocation.FRAGMENT_SPREAD, + DirectiveLocation.INLINE_FRAGMENT, + ], + args: { + if: { + type: new GraphQLNonNull(GraphQLBoolean), + description: 'Skipped when true.', + }, + }, +}); +/** Constant string used for default reason for a deprecation. */ + +export const DEFAULT_DEPRECATION_REASON = 'No longer supported'; +/** + * Used to declare element of a GraphQL schema as deprecated. + * + * The optional `reason` argument defaults to `DEFAULT_DEPRECATION_REASON`. + */ + +export const GraphQLDeprecatedDirective = new GraphQLDirective({ + name: 'deprecated', + description: 'Marks an element of a GraphQL schema as no longer supported.', + locations: [ + DirectiveLocation.FIELD_DEFINITION, + DirectiveLocation.ARGUMENT_DEFINITION, + DirectiveLocation.INPUT_FIELD_DEFINITION, + DirectiveLocation.ENUM_VALUE, + DirectiveLocation.DIRECTIVE_DEFINITION, + ], + args: { + reason: { + type: GraphQLString, + description: + '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/).', + defaultValue: DEFAULT_DEPRECATION_REASON, + }, + }, +}); +/** Used to provide a URL for specifying the behavior of custom scalar definitions. */ + +export const GraphQLSpecifiedByDirective = new GraphQLDirective({ + name: 'specifiedBy', + description: 'Exposes a URL that specifies the behavior of this scalar.', + locations: [DirectiveLocation.SCALAR], + args: { + url: { + type: new GraphQLNonNull(GraphQLString), + description: 'The URL that specifies the behavior of this scalar.', + }, + }, +}); +/** Used to indicate an Input Object is a OneOf Input Object. */ + +export const GraphQLOneOfDirective = new GraphQLDirective({ + name: 'oneOf', + description: + 'Indicates exactly one field must be supplied and this field must not be `null`.', + locations: [DirectiveLocation.INPUT_OBJECT], + args: {}, +}); +/** Full list of stable directives specified by GraphQL.js. */ + +export const specifiedDirectives = Object.freeze([ + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, +]); +/** + * Returns true when the directive is one of the directives specified by GraphQL. + * @param directive - Directive to inspect. + * @returns True when the directive is specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLDirective, + * GraphQLIncludeDirective, + * isSpecifiedDirective, + * } from 'graphql/type'; + * import { DirectiveLocation } from 'graphql/language'; + * + * const customDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * }); + * + * isSpecifiedDirective(GraphQLIncludeDirective); // => true + * isSpecifiedDirective(customDirective); // => false + * ``` + */ + +export function isSpecifiedDirective(directive) { + return specifiedDirectives.some(({ name }) => name === directive.name); +} diff --git a/node_modules/graphql/type/index.d.ts b/node_modules/graphql/type/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..84fcdd37220e851a347c9880293b60c204048794 --- /dev/null +++ b/node_modules/graphql/type/index.d.ts @@ -0,0 +1,157 @@ +/** + * Create and inspect GraphQL type definitions and schemas. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export type { Path as ResponsePath } from '../jsutils/Path'; +export { isSchema, assertSchema, GraphQLSchema } from './schema'; +export type { GraphQLSchemaConfig, GraphQLSchemaExtensions } from './schema'; +export { + resolveObjMapThunk, + resolveReadonlyArrayThunk, + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, + getNullableType, + getNamedType, + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLList, + GraphQLNonNull, +} from './definition'; +export type { + GraphQLType, + GraphQLInputType, + GraphQLOutputType, + GraphQLLeafType, + GraphQLCompositeType, + GraphQLAbstractType, + GraphQLWrappingType, + GraphQLNullableType, + GraphQLNamedType, + GraphQLNamedInputType, + GraphQLNamedOutputType, + ThunkReadonlyArray, + ThunkObjMap, + GraphQLArgument, + GraphQLArgumentConfig, + GraphQLArgumentExtensions, + GraphQLEnumTypeConfig, + GraphQLEnumTypeExtensions, + GraphQLEnumValue, + GraphQLEnumValueConfig, + GraphQLEnumValueConfigMap, + GraphQLEnumValueExtensions, + GraphQLField, + GraphQLFieldConfig, + GraphQLFieldConfigArgumentMap, + GraphQLFieldConfigMap, + GraphQLFieldExtensions, + GraphQLFieldMap, + GraphQLFieldResolver, + GraphQLInputField, + GraphQLInputFieldConfig, + GraphQLInputFieldConfigMap, + GraphQLInputFieldExtensions, + GraphQLInputFieldMap, + GraphQLInputObjectTypeConfig, + GraphQLInputObjectTypeExtensions, + GraphQLInterfaceTypeConfig, + GraphQLInterfaceTypeExtensions, + GraphQLIsTypeOfFn, + GraphQLObjectTypeConfig, + GraphQLObjectTypeExtensions, + GraphQLResolveInfo, + GraphQLScalarTypeConfig, + GraphQLScalarTypeExtensions, + GraphQLTypeResolver, + GraphQLUnionTypeConfig, + GraphQLUnionTypeExtensions, + GraphQLScalarSerializer, + GraphQLScalarValueParser, + GraphQLScalarLiteralParser, +} from './definition'; +export { + isDirective, + assertDirective, + GraphQLDirective, + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, + DEFAULT_DEPRECATION_REASON, +} from './directives'; +export type { + GraphQLDirectiveConfig, + GraphQLDirectiveExtensions, +} from './directives'; +export { + isSpecifiedScalarType, + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, + GRAPHQL_MAX_INT, + GRAPHQL_MIN_INT, +} from './scalars'; +export { + isIntrospectionType, + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, + TypeKind, + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection'; +export { validateSchema, assertValidSchema } from './validate'; +export { assertName, assertEnumValueName } from './assertName'; diff --git a/node_modules/graphql/type/index.js b/node_modules/graphql/type/index.js new file mode 100644 index 0000000000000000000000000000000000000000..076ccb00444fad49904c29a9df01c38b999ce86a --- /dev/null +++ b/node_modules/graphql/type/index.js @@ -0,0 +1,553 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'DEFAULT_DEPRECATION_REASON', { + enumerable: true, + get: function () { + return _directives.DEFAULT_DEPRECATION_REASON; + }, +}); +Object.defineProperty(exports, 'GRAPHQL_MAX_INT', { + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MAX_INT; + }, +}); +Object.defineProperty(exports, 'GRAPHQL_MIN_INT', { + enumerable: true, + get: function () { + return _scalars.GRAPHQL_MIN_INT; + }, +}); +Object.defineProperty(exports, 'GraphQLBoolean', { + enumerable: true, + get: function () { + return _scalars.GraphQLBoolean; + }, +}); +Object.defineProperty(exports, 'GraphQLDeprecatedDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLDeprecatedDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLEnumType', { + enumerable: true, + get: function () { + return _definition.GraphQLEnumType; + }, +}); +Object.defineProperty(exports, 'GraphQLFloat', { + enumerable: true, + get: function () { + return _scalars.GraphQLFloat; + }, +}); +Object.defineProperty(exports, 'GraphQLID', { + enumerable: true, + get: function () { + return _scalars.GraphQLID; + }, +}); +Object.defineProperty(exports, 'GraphQLIncludeDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLIncludeDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLInputObjectType', { + enumerable: true, + get: function () { + return _definition.GraphQLInputObjectType; + }, +}); +Object.defineProperty(exports, 'GraphQLInt', { + enumerable: true, + get: function () { + return _scalars.GraphQLInt; + }, +}); +Object.defineProperty(exports, 'GraphQLInterfaceType', { + enumerable: true, + get: function () { + return _definition.GraphQLInterfaceType; + }, +}); +Object.defineProperty(exports, 'GraphQLList', { + enumerable: true, + get: function () { + return _definition.GraphQLList; + }, +}); +Object.defineProperty(exports, 'GraphQLNonNull', { + enumerable: true, + get: function () { + return _definition.GraphQLNonNull; + }, +}); +Object.defineProperty(exports, 'GraphQLObjectType', { + enumerable: true, + get: function () { + return _definition.GraphQLObjectType; + }, +}); +Object.defineProperty(exports, 'GraphQLOneOfDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLOneOfDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLScalarType', { + enumerable: true, + get: function () { + return _definition.GraphQLScalarType; + }, +}); +Object.defineProperty(exports, 'GraphQLSchema', { + enumerable: true, + get: function () { + return _schema.GraphQLSchema; + }, +}); +Object.defineProperty(exports, 'GraphQLSkipDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLSkipDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLSpecifiedByDirective', { + enumerable: true, + get: function () { + return _directives.GraphQLSpecifiedByDirective; + }, +}); +Object.defineProperty(exports, 'GraphQLString', { + enumerable: true, + get: function () { + return _scalars.GraphQLString; + }, +}); +Object.defineProperty(exports, 'GraphQLUnionType', { + enumerable: true, + get: function () { + return _definition.GraphQLUnionType; + }, +}); +Object.defineProperty(exports, 'SchemaMetaFieldDef', { + enumerable: true, + get: function () { + return _introspection.SchemaMetaFieldDef; + }, +}); +Object.defineProperty(exports, 'TypeKind', { + enumerable: true, + get: function () { + return _introspection.TypeKind; + }, +}); +Object.defineProperty(exports, 'TypeMetaFieldDef', { + enumerable: true, + get: function () { + return _introspection.TypeMetaFieldDef; + }, +}); +Object.defineProperty(exports, 'TypeNameMetaFieldDef', { + enumerable: true, + get: function () { + return _introspection.TypeNameMetaFieldDef; + }, +}); +Object.defineProperty(exports, '__Directive', { + enumerable: true, + get: function () { + return _introspection.__Directive; + }, +}); +Object.defineProperty(exports, '__DirectiveLocation', { + enumerable: true, + get: function () { + return _introspection.__DirectiveLocation; + }, +}); +Object.defineProperty(exports, '__EnumValue', { + enumerable: true, + get: function () { + return _introspection.__EnumValue; + }, +}); +Object.defineProperty(exports, '__Field', { + enumerable: true, + get: function () { + return _introspection.__Field; + }, +}); +Object.defineProperty(exports, '__InputValue', { + enumerable: true, + get: function () { + return _introspection.__InputValue; + }, +}); +Object.defineProperty(exports, '__Schema', { + enumerable: true, + get: function () { + return _introspection.__Schema; + }, +}); +Object.defineProperty(exports, '__Type', { + enumerable: true, + get: function () { + return _introspection.__Type; + }, +}); +Object.defineProperty(exports, '__TypeKind', { + enumerable: true, + get: function () { + return _introspection.__TypeKind; + }, +}); +Object.defineProperty(exports, 'assertAbstractType', { + enumerable: true, + get: function () { + return _definition.assertAbstractType; + }, +}); +Object.defineProperty(exports, 'assertCompositeType', { + enumerable: true, + get: function () { + return _definition.assertCompositeType; + }, +}); +Object.defineProperty(exports, 'assertDirective', { + enumerable: true, + get: function () { + return _directives.assertDirective; + }, +}); +Object.defineProperty(exports, 'assertEnumType', { + enumerable: true, + get: function () { + return _definition.assertEnumType; + }, +}); +Object.defineProperty(exports, 'assertEnumValueName', { + enumerable: true, + get: function () { + return _assertName.assertEnumValueName; + }, +}); +Object.defineProperty(exports, 'assertInputObjectType', { + enumerable: true, + get: function () { + return _definition.assertInputObjectType; + }, +}); +Object.defineProperty(exports, 'assertInputType', { + enumerable: true, + get: function () { + return _definition.assertInputType; + }, +}); +Object.defineProperty(exports, 'assertInterfaceType', { + enumerable: true, + get: function () { + return _definition.assertInterfaceType; + }, +}); +Object.defineProperty(exports, 'assertLeafType', { + enumerable: true, + get: function () { + return _definition.assertLeafType; + }, +}); +Object.defineProperty(exports, 'assertListType', { + enumerable: true, + get: function () { + return _definition.assertListType; + }, +}); +Object.defineProperty(exports, 'assertName', { + enumerable: true, + get: function () { + return _assertName.assertName; + }, +}); +Object.defineProperty(exports, 'assertNamedType', { + enumerable: true, + get: function () { + return _definition.assertNamedType; + }, +}); +Object.defineProperty(exports, 'assertNonNullType', { + enumerable: true, + get: function () { + return _definition.assertNonNullType; + }, +}); +Object.defineProperty(exports, 'assertNullableType', { + enumerable: true, + get: function () { + return _definition.assertNullableType; + }, +}); +Object.defineProperty(exports, 'assertObjectType', { + enumerable: true, + get: function () { + return _definition.assertObjectType; + }, +}); +Object.defineProperty(exports, 'assertOutputType', { + enumerable: true, + get: function () { + return _definition.assertOutputType; + }, +}); +Object.defineProperty(exports, 'assertScalarType', { + enumerable: true, + get: function () { + return _definition.assertScalarType; + }, +}); +Object.defineProperty(exports, 'assertSchema', { + enumerable: true, + get: function () { + return _schema.assertSchema; + }, +}); +Object.defineProperty(exports, 'assertType', { + enumerable: true, + get: function () { + return _definition.assertType; + }, +}); +Object.defineProperty(exports, 'assertUnionType', { + enumerable: true, + get: function () { + return _definition.assertUnionType; + }, +}); +Object.defineProperty(exports, 'assertValidSchema', { + enumerable: true, + get: function () { + return _validate.assertValidSchema; + }, +}); +Object.defineProperty(exports, 'assertWrappingType', { + enumerable: true, + get: function () { + return _definition.assertWrappingType; + }, +}); +Object.defineProperty(exports, 'getNamedType', { + enumerable: true, + get: function () { + return _definition.getNamedType; + }, +}); +Object.defineProperty(exports, 'getNullableType', { + enumerable: true, + get: function () { + return _definition.getNullableType; + }, +}); +Object.defineProperty(exports, 'introspectionTypes', { + enumerable: true, + get: function () { + return _introspection.introspectionTypes; + }, +}); +Object.defineProperty(exports, 'isAbstractType', { + enumerable: true, + get: function () { + return _definition.isAbstractType; + }, +}); +Object.defineProperty(exports, 'isCompositeType', { + enumerable: true, + get: function () { + return _definition.isCompositeType; + }, +}); +Object.defineProperty(exports, 'isDirective', { + enumerable: true, + get: function () { + return _directives.isDirective; + }, +}); +Object.defineProperty(exports, 'isEnumType', { + enumerable: true, + get: function () { + return _definition.isEnumType; + }, +}); +Object.defineProperty(exports, 'isInputObjectType', { + enumerable: true, + get: function () { + return _definition.isInputObjectType; + }, +}); +Object.defineProperty(exports, 'isInputType', { + enumerable: true, + get: function () { + return _definition.isInputType; + }, +}); +Object.defineProperty(exports, 'isInterfaceType', { + enumerable: true, + get: function () { + return _definition.isInterfaceType; + }, +}); +Object.defineProperty(exports, 'isIntrospectionType', { + enumerable: true, + get: function () { + return _introspection.isIntrospectionType; + }, +}); +Object.defineProperty(exports, 'isLeafType', { + enumerable: true, + get: function () { + return _definition.isLeafType; + }, +}); +Object.defineProperty(exports, 'isListType', { + enumerable: true, + get: function () { + return _definition.isListType; + }, +}); +Object.defineProperty(exports, 'isNamedType', { + enumerable: true, + get: function () { + return _definition.isNamedType; + }, +}); +Object.defineProperty(exports, 'isNonNullType', { + enumerable: true, + get: function () { + return _definition.isNonNullType; + }, +}); +Object.defineProperty(exports, 'isNullableType', { + enumerable: true, + get: function () { + return _definition.isNullableType; + }, +}); +Object.defineProperty(exports, 'isObjectType', { + enumerable: true, + get: function () { + return _definition.isObjectType; + }, +}); +Object.defineProperty(exports, 'isOutputType', { + enumerable: true, + get: function () { + return _definition.isOutputType; + }, +}); +Object.defineProperty(exports, 'isRequiredArgument', { + enumerable: true, + get: function () { + return _definition.isRequiredArgument; + }, +}); +Object.defineProperty(exports, 'isRequiredInputField', { + enumerable: true, + get: function () { + return _definition.isRequiredInputField; + }, +}); +Object.defineProperty(exports, 'isScalarType', { + enumerable: true, + get: function () { + return _definition.isScalarType; + }, +}); +Object.defineProperty(exports, 'isSchema', { + enumerable: true, + get: function () { + return _schema.isSchema; + }, +}); +Object.defineProperty(exports, 'isSpecifiedDirective', { + enumerable: true, + get: function () { + return _directives.isSpecifiedDirective; + }, +}); +Object.defineProperty(exports, 'isSpecifiedScalarType', { + enumerable: true, + get: function () { + return _scalars.isSpecifiedScalarType; + }, +}); +Object.defineProperty(exports, 'isType', { + enumerable: true, + get: function () { + return _definition.isType; + }, +}); +Object.defineProperty(exports, 'isUnionType', { + enumerable: true, + get: function () { + return _definition.isUnionType; + }, +}); +Object.defineProperty(exports, 'isWrappingType', { + enumerable: true, + get: function () { + return _definition.isWrappingType; + }, +}); +Object.defineProperty(exports, 'resolveObjMapThunk', { + enumerable: true, + get: function () { + return _definition.resolveObjMapThunk; + }, +}); +Object.defineProperty(exports, 'resolveReadonlyArrayThunk', { + enumerable: true, + get: function () { + return _definition.resolveReadonlyArrayThunk; + }, +}); +Object.defineProperty(exports, 'specifiedDirectives', { + enumerable: true, + get: function () { + return _directives.specifiedDirectives; + }, +}); +Object.defineProperty(exports, 'specifiedScalarTypes', { + enumerable: true, + get: function () { + return _scalars.specifiedScalarTypes; + }, +}); +Object.defineProperty(exports, 'validateSchema', { + enumerable: true, + get: function () { + return _validate.validateSchema; + }, +}); + +var _schema = require('./schema.js'); + +var _definition = require('./definition.js'); + +var _directives = require('./directives.js'); + +var _scalars = require('./scalars.js'); + +var _introspection = require('./introspection.js'); + +var _validate = require('./validate.js'); + +var _assertName = require('./assertName.js'); diff --git a/node_modules/graphql/type/index.mjs b/node_modules/graphql/type/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..156f262c9666835e2810427ead189dca3fbe9d0e --- /dev/null +++ b/node_modules/graphql/type/index.mjs @@ -0,0 +1,110 @@ +/** + * Create and inspect GraphQL type definitions and schemas. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { + // Predicate + isSchema, // Assertion + assertSchema, // GraphQL Schema definition + GraphQLSchema, +} from './schema.mjs'; +export { + resolveObjMapThunk, + resolveReadonlyArrayThunk, // Predicates + isType, + isScalarType, + isObjectType, + isInterfaceType, + isUnionType, + isEnumType, + isInputObjectType, + isListType, + isNonNullType, + isInputType, + isOutputType, + isLeafType, + isCompositeType, + isAbstractType, + isWrappingType, + isNullableType, + isNamedType, + isRequiredArgument, + isRequiredInputField, // Assertions + assertType, + assertScalarType, + assertObjectType, + assertInterfaceType, + assertUnionType, + assertEnumType, + assertInputObjectType, + assertListType, + assertNonNullType, + assertInputType, + assertOutputType, + assertLeafType, + assertCompositeType, + assertAbstractType, + assertWrappingType, + assertNullableType, + assertNamedType, // Un-modifiers + getNullableType, + getNamedType, // Definitions + GraphQLScalarType, + GraphQLObjectType, + GraphQLInterfaceType, + GraphQLUnionType, + GraphQLEnumType, + GraphQLInputObjectType, // Type Wrappers + GraphQLList, + GraphQLNonNull, +} from './definition.mjs'; +export { + // Predicate + isDirective, // Assertion + assertDirective, // Directives Definition + GraphQLDirective, // Built-in Directives defined by the Spec + isSpecifiedDirective, + specifiedDirectives, + GraphQLIncludeDirective, + GraphQLSkipDirective, + GraphQLDeprecatedDirective, + GraphQLSpecifiedByDirective, + GraphQLOneOfDirective, // Constant Deprecation Reason + DEFAULT_DEPRECATION_REASON, +} from './directives.mjs'; +// Common built-in scalar instances. +export { + // Predicate + isSpecifiedScalarType, // Standard GraphQL Scalars + specifiedScalarTypes, + GraphQLInt, + GraphQLFloat, + GraphQLString, + GraphQLBoolean, + GraphQLID, // Int boundaries constants + GRAPHQL_MAX_INT, + GRAPHQL_MIN_INT, +} from './scalars.mjs'; +export { + // Predicate + isIntrospectionType, // GraphQL Types for introspection. + introspectionTypes, + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, // "Enum" of Type Kinds + TypeKind, // Meta-field definitions. + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from './introspection.mjs'; // Validate GraphQL schema. + +export { validateSchema, assertValidSchema } from './validate.mjs'; // Upholds the spec rules about naming. + +export { assertName, assertEnumValueName } from './assertName.mjs'; diff --git a/node_modules/graphql/type/introspection.d.ts b/node_modules/graphql/type/introspection.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2155a12fffe0da2b4f08df5adca7cc3d5b95f105 --- /dev/null +++ b/node_modules/graphql/type/introspection.d.ts @@ -0,0 +1,66 @@ +/** @category Introspection */ +import type { GraphQLField, GraphQLNamedType } from './definition'; +import { GraphQLEnumType, GraphQLObjectType } from './definition'; +/** The introspection type describing a GraphQL schema. */ +export declare const __Schema: GraphQLObjectType; +/** The introspection type describing a GraphQL directive. */ +export declare const __Directive: GraphQLObjectType; +/** The introspection enum describing directive locations. */ +export declare const __DirectiveLocation: GraphQLEnumType; +/** The introspection type describing GraphQL types. */ +export declare const __Type: GraphQLObjectType; +/** The introspection type describing object and interface fields. */ +export declare const __Field: GraphQLObjectType; +/** The introspection type describing arguments and input fields. */ +export declare const __InputValue: GraphQLObjectType; +/** The introspection type describing enum values. */ +export declare const __EnumValue: GraphQLObjectType; +/** + * The introspection enum describing the different kinds of GraphQL types. + * @category Introspection + */ +declare enum TypeKind { + /** A scalar type. */ + SCALAR = 'SCALAR', + /** An object type. */ + OBJECT = 'OBJECT', + /** An interface type. */ + INTERFACE = 'INTERFACE', + /** A union type. */ + UNION = 'UNION', + /** An enum type. */ + ENUM = 'ENUM', + /** An input object type. */ + INPUT_OBJECT = 'INPUT_OBJECT', + /** A list wrapper type. */ + LIST = 'LIST', + /** A non-null wrapper type. */ + NON_NULL = 'NON_NULL', +} +export { TypeKind }; +/** The introspection enum describing GraphQL type kinds. */ +export declare const __TypeKind: GraphQLEnumType; +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ +export declare const SchemaMetaFieldDef: GraphQLField; +/** The `__type` meta field definition used by introspection. */ +export declare const TypeMetaFieldDef: GraphQLField; +/** The `__typename` meta field definition used by execution and introspection. */ +export declare const TypeNameMetaFieldDef: GraphQLField; +/** All introspection types defined by the GraphQL specification. */ +export declare const introspectionTypes: ReadonlyArray; +/** + * Returns true when the type is one of the built-in introspection types. + * @param type - The GraphQL type to inspect. + * @returns True when the type is one of the built-in introspection types. + * @example + * ```ts + * import { GraphQLString, isIntrospectionType, __Type } from 'graphql/type'; + * + * isIntrospectionType(__Type); // => true + * isIntrospectionType(GraphQLString); // => false + * ``` + */ +export declare function isIntrospectionType(type: GraphQLNamedType): boolean; diff --git a/node_modules/graphql/type/introspection.js b/node_modules/graphql/type/introspection.js new file mode 100644 index 0000000000000000000000000000000000000000..b67faa1fe134c0e1d4966c277ef1cffc2a6557d3 --- /dev/null +++ b/node_modules/graphql/type/introspection.js @@ -0,0 +1,681 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.introspectionTypes = + exports.__TypeKind = + exports.__Type = + exports.__Schema = + exports.__InputValue = + exports.__Field = + exports.__EnumValue = + exports.__DirectiveLocation = + exports.__Directive = + exports.TypeNameMetaFieldDef = + exports.TypeMetaFieldDef = + exports.TypeKind = + exports.SchemaMetaFieldDef = + void 0; +exports.isIntrospectionType = isIntrospectionType; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _directiveLocation = require('../language/directiveLocation.js'); + +var _printer = require('../language/printer.js'); + +var _astFromValue = require('../utilities/astFromValue.js'); + +var _definition = require('./definition.js'); + +var _scalars = require('./scalars.js'); + +/** @category Introspection */ + +/** The introspection type describing a GraphQL schema. */ +const __Schema = new _definition.GraphQLObjectType({ + name: '__Schema', + description: + '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.', + fields: () => ({ + description: { + type: _scalars.GraphQLString, + resolve: (schema) => schema.description, + }, + types: { + description: 'A list of all types supported by this server.', + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + ), + + resolve(schema) { + return Object.values(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new _definition.GraphQLNonNull(__Type), + resolve: (schema) => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Directive), + ), + ), + args: { + includeDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + defaultValue: false, + }, + }, + resolve: (schema, { includeDeprecated }) => + includeDeprecated + ? schema.getDirectives() + : schema + .getDirectives() + .filter((directive) => directive.deprecationReason == null), + }, + }), +}); +/** The introspection type describing a GraphQL directive. */ + +exports.__Schema = __Schema; + +const __Directive = new _definition.GraphQLObjectType({ + name: '__Directive', + description: + "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.", + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (directive) => directive.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (directive) => directive.description, + }, + isRepeatable: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (directive) => directive.isRepeatable, + }, + locations: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__DirectiveLocation), + ), + ), + resolve: (directive) => directive.locations, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (directive) => directive.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (directive) => directive.deprecationReason, + }, + }), +}); +/** The introspection enum describing directive locations. */ + +exports.__Directive = __Directive; + +const __DirectiveLocation = new _definition.GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: _directiveLocation.DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: _directiveLocation.DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: _directiveLocation.DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: _directiveLocation.DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: _directiveLocation.DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: _directiveLocation.DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: _directiveLocation.DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: _directiveLocation.DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: _directiveLocation.DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: _directiveLocation.DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: _directiveLocation.DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: _directiveLocation.DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: _directiveLocation.DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, + DIRECTIVE_DEFINITION: { + value: _directiveLocation.DirectiveLocation.DIRECTIVE_DEFINITION, + description: 'Location adjacent to a directive definition.', + }, + }, +}); +/** The introspection type describing GraphQL types. */ + +exports.__DirectiveLocation = __DirectiveLocation; + +const __Type = new _definition.GraphQLObjectType({ + name: '__Type', + description: + '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.', + fields: () => ({ + kind: { + type: new _definition.GraphQLNonNull(__TypeKind), + + resolve(type) { + if ((0, _definition.isScalarType)(type)) { + return TypeKind.SCALAR; + } + + if ((0, _definition.isObjectType)(type)) { + return TypeKind.OBJECT; + } + + if ((0, _definition.isInterfaceType)(type)) { + return TypeKind.INTERFACE; + } + + if ((0, _definition.isUnionType)(type)) { + return TypeKind.UNION; + } + + if ((0, _definition.isEnumType)(type)) { + return TypeKind.ENUM; + } + + if ((0, _definition.isInputObjectType)(type)) { + return TypeKind.INPUT_OBJECT; + } + + if ((0, _definition.isListType)(type)) { + return TypeKind.LIST; + } + + if ((0, _definition.isNonNullType)(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || + (0, _invariant.invariant)( + false, + `Unexpected type: "${(0, _inspect.inspect)(type)}".`, + ); + }, + }, + name: { + type: _scalars.GraphQLString, + resolve: (type) => ('name' in type ? type.name : undefined), + }, + description: { + type: _scalars.GraphQLString, + resolve: ( + type, // FIXME: add test case + ) => + /* c8 ignore next */ + 'description' in type ? type.description : undefined, + }, + specifiedByURL: { + type: _scalars.GraphQLString, + resolve: (obj) => + 'specifiedByURL' in obj ? obj.specifiedByURL : undefined, + }, + fields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__Field), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const fields = Object.values(type.getFields()); + return includeDeprecated + ? fields + : fields.filter((field) => field.deprecationReason == null); + } + }, + }, + interfaces: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + + resolve(type) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: new _definition.GraphQLList(new _definition.GraphQLNonNull(__Type)), + + resolve(type, _args, _context, { schema }) { + if ((0, _definition.isAbstractType)(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__EnumValue), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ((0, _definition.isEnumType)(type)) { + const values = type.getValues(); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + inputFields: { + type: new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if ((0, _definition.isInputObjectType)(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + ofType: { + type: __Type, + resolve: (type) => ('ofType' in type ? type.ofType : undefined), + }, + isOneOf: { + type: _scalars.GraphQLBoolean, + resolve: (type) => { + if ((0, _definition.isInputObjectType)(type)) { + return type.isOneOf; + } + }, + }, + }), +}); +/** The introspection type describing object and interface fields. */ + +exports.__Type = __Type; + +const __Field = new _definition.GraphQLObjectType({ + name: '__Field', + description: + '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.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (field) => field.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (field) => field.description, + }, + args: { + type: new _definition.GraphQLNonNull( + new _definition.GraphQLList( + new _definition.GraphQLNonNull(__InputValue), + ), + ), + args: { + includeDeprecated: { + type: _scalars.GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (field) => field.type, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (field) => field.deprecationReason, + }, + }), +}); +/** The introspection type describing arguments and input fields. */ + +exports.__Field = __Field; + +const __InputValue = new _definition.GraphQLObjectType({ + name: '__InputValue', + description: + '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.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (inputValue) => inputValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (inputValue) => inputValue.description, + }, + type: { + type: new _definition.GraphQLNonNull(__Type), + resolve: (inputValue) => inputValue.type, + }, + defaultValue: { + type: _scalars.GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this input value.', + + resolve(inputValue) { + const { type, defaultValue } = inputValue; + const valueAST = (0, _astFromValue.astFromValue)(defaultValue, type); + return valueAST ? (0, _printer.print)(valueAST) : null; + }, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (obj) => obj.deprecationReason, + }, + }), +}); +/** The introspection type describing enum values. */ + +exports.__InputValue = __InputValue; + +const __EnumValue = new _definition.GraphQLObjectType({ + name: '__EnumValue', + description: + '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.', + fields: () => ({ + name: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + resolve: (enumValue) => enumValue.name, + }, + description: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.description, + }, + isDeprecated: { + type: new _definition.GraphQLNonNull(_scalars.GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null, + }, + deprecationReason: { + type: _scalars.GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason, + }, + }), +}); +/** + * The introspection enum describing the different kinds of GraphQL types. + * @category Introspection + */ + +exports.__EnumValue = __EnumValue; +var TypeKind; +exports.TypeKind = TypeKind; + +(function (TypeKind) { + TypeKind['SCALAR'] = 'SCALAR'; + TypeKind['OBJECT'] = 'OBJECT'; + TypeKind['INTERFACE'] = 'INTERFACE'; + TypeKind['UNION'] = 'UNION'; + TypeKind['ENUM'] = 'ENUM'; + TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; + TypeKind['LIST'] = 'LIST'; + TypeKind['NON_NULL'] = 'NON_NULL'; +})(TypeKind || (exports.TypeKind = TypeKind = {})); + +/** The introspection enum describing GraphQL type kinds. */ +const __TypeKind = new _definition.GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. `inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, + }, +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +exports.__TypeKind = __TypeKind; +const SchemaMetaFieldDef = { + name: '__schema', + type: new _definition.GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { schema }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** The `__type` meta field definition used by introspection. */ + +exports.SchemaMetaFieldDef = SchemaMetaFieldDef; +const TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [ + { + name: 'name', + description: undefined, + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }, + ], + resolve: (_source, { name }, _context, { schema }) => schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** The `__typename` meta field definition used by execution and introspection. */ + +exports.TypeMetaFieldDef = TypeMetaFieldDef; +const TypeNameMetaFieldDef = { + name: '__typename', + type: new _definition.GraphQLNonNull(_scalars.GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { parentType }) => parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** All introspection types defined by the GraphQL specification. */ + +exports.TypeNameMetaFieldDef = TypeNameMetaFieldDef; +const introspectionTypes = Object.freeze([ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]); +/** + * Returns true when the type is one of the built-in introspection types. + * @param type - The GraphQL type to inspect. + * @returns True when the type is one of the built-in introspection types. + * @example + * ```ts + * import { GraphQLString, isIntrospectionType, __Type } from 'graphql/type'; + * + * isIntrospectionType(__Type); // => true + * isIntrospectionType(GraphQLString); // => false + * ``` + */ + +exports.introspectionTypes = introspectionTypes; + +function isIntrospectionType(type) { + return introspectionTypes.some(({ name }) => type.name === name); +} diff --git a/node_modules/graphql/type/introspection.mjs b/node_modules/graphql/type/introspection.mjs new file mode 100644 index 0000000000000000000000000000000000000000..819611ec25a5b7685ee570213000b0c1e5300d0a --- /dev/null +++ b/node_modules/graphql/type/introspection.mjs @@ -0,0 +1,623 @@ +/** @category Introspection */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { DirectiveLocation } from '../language/directiveLocation.mjs'; +import { print } from '../language/printer.mjs'; +import { astFromValue } from '../utilities/astFromValue.mjs'; +import { + GraphQLEnumType, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + isAbstractType, + isEnumType, + isInputObjectType, + isInterfaceType, + isListType, + isNonNullType, + isObjectType, + isScalarType, + isUnionType, +} from './definition.mjs'; +import { GraphQLBoolean, GraphQLString } from './scalars.mjs'; + +/** The introspection type describing a GraphQL schema. */ +export const __Schema = new GraphQLObjectType({ + name: '__Schema', + description: + '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.', + fields: () => ({ + description: { + type: GraphQLString, + resolve: (schema) => schema.description, + }, + types: { + description: 'A list of all types supported by this server.', + type: new GraphQLNonNull(new GraphQLList(new GraphQLNonNull(__Type))), + + resolve(schema) { + return Object.values(schema.getTypeMap()); + }, + }, + queryType: { + description: 'The type that query operations will be rooted at.', + type: new GraphQLNonNull(__Type), + resolve: (schema) => schema.getQueryType(), + }, + mutationType: { + description: + 'If this server supports mutation, the type that mutation operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getMutationType(), + }, + subscriptionType: { + description: + 'If this server support subscription, the type that subscription operations will be rooted at.', + type: __Type, + resolve: (schema) => schema.getSubscriptionType(), + }, + directives: { + description: 'A list of all directives supported by this server.', + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__Directive)), + ), + args: { + includeDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + defaultValue: false, + }, + }, + resolve: (schema, { includeDeprecated }) => + includeDeprecated + ? schema.getDirectives() + : schema + .getDirectives() + .filter((directive) => directive.deprecationReason == null), + }, + }), +}); +/** The introspection type describing a GraphQL directive. */ + +export const __Directive = new GraphQLObjectType({ + name: '__Directive', + description: + "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.", + fields: () => ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (directive) => directive.name, + }, + description: { + type: GraphQLString, + resolve: (directive) => directive.description, + }, + isRepeatable: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (directive) => directive.isRepeatable, + }, + locations: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__DirectiveLocation)), + ), + resolve: (directive) => directive.locations, + }, + args: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__InputValue)), + ), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (directive) => directive.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (directive) => directive.deprecationReason, + }, + }), +}); +/** The introspection enum describing directive locations. */ + +export const __DirectiveLocation = new GraphQLEnumType({ + name: '__DirectiveLocation', + description: + 'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.', + values: { + QUERY: { + value: DirectiveLocation.QUERY, + description: 'Location adjacent to a query operation.', + }, + MUTATION: { + value: DirectiveLocation.MUTATION, + description: 'Location adjacent to a mutation operation.', + }, + SUBSCRIPTION: { + value: DirectiveLocation.SUBSCRIPTION, + description: 'Location adjacent to a subscription operation.', + }, + FIELD: { + value: DirectiveLocation.FIELD, + description: 'Location adjacent to a field.', + }, + FRAGMENT_DEFINITION: { + value: DirectiveLocation.FRAGMENT_DEFINITION, + description: 'Location adjacent to a fragment definition.', + }, + FRAGMENT_SPREAD: { + value: DirectiveLocation.FRAGMENT_SPREAD, + description: 'Location adjacent to a fragment spread.', + }, + INLINE_FRAGMENT: { + value: DirectiveLocation.INLINE_FRAGMENT, + description: 'Location adjacent to an inline fragment.', + }, + VARIABLE_DEFINITION: { + value: DirectiveLocation.VARIABLE_DEFINITION, + description: 'Location adjacent to a variable definition.', + }, + SCHEMA: { + value: DirectiveLocation.SCHEMA, + description: 'Location adjacent to a schema definition.', + }, + SCALAR: { + value: DirectiveLocation.SCALAR, + description: 'Location adjacent to a scalar definition.', + }, + OBJECT: { + value: DirectiveLocation.OBJECT, + description: 'Location adjacent to an object type definition.', + }, + FIELD_DEFINITION: { + value: DirectiveLocation.FIELD_DEFINITION, + description: 'Location adjacent to a field definition.', + }, + ARGUMENT_DEFINITION: { + value: DirectiveLocation.ARGUMENT_DEFINITION, + description: 'Location adjacent to an argument definition.', + }, + INTERFACE: { + value: DirectiveLocation.INTERFACE, + description: 'Location adjacent to an interface definition.', + }, + UNION: { + value: DirectiveLocation.UNION, + description: 'Location adjacent to a union definition.', + }, + ENUM: { + value: DirectiveLocation.ENUM, + description: 'Location adjacent to an enum definition.', + }, + ENUM_VALUE: { + value: DirectiveLocation.ENUM_VALUE, + description: 'Location adjacent to an enum value definition.', + }, + INPUT_OBJECT: { + value: DirectiveLocation.INPUT_OBJECT, + description: 'Location adjacent to an input object type definition.', + }, + INPUT_FIELD_DEFINITION: { + value: DirectiveLocation.INPUT_FIELD_DEFINITION, + description: 'Location adjacent to an input object field definition.', + }, + DIRECTIVE_DEFINITION: { + value: DirectiveLocation.DIRECTIVE_DEFINITION, + description: 'Location adjacent to a directive definition.', + }, + }, +}); +/** The introspection type describing GraphQL types. */ + +export const __Type = new GraphQLObjectType({ + name: '__Type', + description: + '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.', + fields: () => ({ + kind: { + type: new GraphQLNonNull(__TypeKind), + + resolve(type) { + if (isScalarType(type)) { + return TypeKind.SCALAR; + } + + if (isObjectType(type)) { + return TypeKind.OBJECT; + } + + if (isInterfaceType(type)) { + return TypeKind.INTERFACE; + } + + if (isUnionType(type)) { + return TypeKind.UNION; + } + + if (isEnumType(type)) { + return TypeKind.ENUM; + } + + if (isInputObjectType(type)) { + return TypeKind.INPUT_OBJECT; + } + + if (isListType(type)) { + return TypeKind.LIST; + } + + if (isNonNullType(type)) { + return TypeKind.NON_NULL; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered) + + false || invariant(false, `Unexpected type: "${inspect(type)}".`); + }, + }, + name: { + type: GraphQLString, + resolve: (type) => ('name' in type ? type.name : undefined), + }, + description: { + type: GraphQLString, + resolve: ( + type, // FIXME: add test case + ) => + /* c8 ignore next */ + 'description' in type ? type.description : undefined, + }, + specifiedByURL: { + type: GraphQLString, + resolve: (obj) => + 'specifiedByURL' in obj ? obj.specifiedByURL : undefined, + }, + fields: { + type: new GraphQLList(new GraphQLNonNull(__Field)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if (isObjectType(type) || isInterfaceType(type)) { + const fields = Object.values(type.getFields()); + return includeDeprecated + ? fields + : fields.filter((field) => field.deprecationReason == null); + } + }, + }, + interfaces: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + + resolve(type) { + if (isObjectType(type) || isInterfaceType(type)) { + return type.getInterfaces(); + } + }, + }, + possibleTypes: { + type: new GraphQLList(new GraphQLNonNull(__Type)), + + resolve(type, _args, _context, { schema }) { + if (isAbstractType(type)) { + return schema.getPossibleTypes(type); + } + }, + }, + enumValues: { + type: new GraphQLList(new GraphQLNonNull(__EnumValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if (isEnumType(type)) { + const values = type.getValues(); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + inputFields: { + type: new GraphQLList(new GraphQLNonNull(__InputValue)), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(type, { includeDeprecated }) { + if (isInputObjectType(type)) { + const values = Object.values(type.getFields()); + return includeDeprecated + ? values + : values.filter((field) => field.deprecationReason == null); + } + }, + }, + ofType: { + type: __Type, + resolve: (type) => ('ofType' in type ? type.ofType : undefined), + }, + isOneOf: { + type: GraphQLBoolean, + resolve: (type) => { + if (isInputObjectType(type)) { + return type.isOneOf; + } + }, + }, + }), +}); +/** The introspection type describing object and interface fields. */ + +export const __Field = new GraphQLObjectType({ + name: '__Field', + description: + '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.', + fields: () => ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (field) => field.name, + }, + description: { + type: GraphQLString, + resolve: (field) => field.description, + }, + args: { + type: new GraphQLNonNull( + new GraphQLList(new GraphQLNonNull(__InputValue)), + ), + args: { + includeDeprecated: { + type: GraphQLBoolean, + defaultValue: false, + }, + }, + + resolve(field, { includeDeprecated }) { + return includeDeprecated + ? field.args + : field.args.filter((arg) => arg.deprecationReason == null); + }, + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: (field) => field.type, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (field) => field.deprecationReason, + }, + }), +}); +/** The introspection type describing arguments and input fields. */ + +export const __InputValue = new GraphQLObjectType({ + name: '__InputValue', + description: + '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.', + fields: () => ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (inputValue) => inputValue.name, + }, + description: { + type: GraphQLString, + resolve: (inputValue) => inputValue.description, + }, + type: { + type: new GraphQLNonNull(__Type), + resolve: (inputValue) => inputValue.type, + }, + defaultValue: { + type: GraphQLString, + description: + 'A GraphQL-formatted string representing the default value for this input value.', + + resolve(inputValue) { + const { type, defaultValue } = inputValue; + const valueAST = astFromValue(defaultValue, type); + return valueAST ? print(valueAST) : null; + }, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (field) => field.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (obj) => obj.deprecationReason, + }, + }), +}); +/** The introspection type describing enum values. */ + +export const __EnumValue = new GraphQLObjectType({ + name: '__EnumValue', + description: + '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.', + fields: () => ({ + name: { + type: new GraphQLNonNull(GraphQLString), + resolve: (enumValue) => enumValue.name, + }, + description: { + type: GraphQLString, + resolve: (enumValue) => enumValue.description, + }, + isDeprecated: { + type: new GraphQLNonNull(GraphQLBoolean), + resolve: (enumValue) => enumValue.deprecationReason != null, + }, + deprecationReason: { + type: GraphQLString, + resolve: (enumValue) => enumValue.deprecationReason, + }, + }), +}); +/** + * The introspection enum describing the different kinds of GraphQL types. + * @category Introspection + */ + +var TypeKind; + +(function (TypeKind) { + TypeKind['SCALAR'] = 'SCALAR'; + TypeKind['OBJECT'] = 'OBJECT'; + TypeKind['INTERFACE'] = 'INTERFACE'; + TypeKind['UNION'] = 'UNION'; + TypeKind['ENUM'] = 'ENUM'; + TypeKind['INPUT_OBJECT'] = 'INPUT_OBJECT'; + TypeKind['LIST'] = 'LIST'; + TypeKind['NON_NULL'] = 'NON_NULL'; +})(TypeKind || (TypeKind = {})); + +export { TypeKind }; +/** The introspection enum describing GraphQL type kinds. */ + +export const __TypeKind = new GraphQLEnumType({ + name: '__TypeKind', + description: 'An enum describing what kind of type a given `__Type` is.', + values: { + SCALAR: { + value: TypeKind.SCALAR, + description: 'Indicates this type is a scalar.', + }, + OBJECT: { + value: TypeKind.OBJECT, + description: + 'Indicates this type is an object. `fields` and `interfaces` are valid fields.', + }, + INTERFACE: { + value: TypeKind.INTERFACE, + description: + 'Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.', + }, + UNION: { + value: TypeKind.UNION, + description: + 'Indicates this type is a union. `possibleTypes` is a valid field.', + }, + ENUM: { + value: TypeKind.ENUM, + description: + 'Indicates this type is an enum. `enumValues` is a valid field.', + }, + INPUT_OBJECT: { + value: TypeKind.INPUT_OBJECT, + description: + 'Indicates this type is an input object. `inputFields` is a valid field.', + }, + LIST: { + value: TypeKind.LIST, + description: 'Indicates this type is a list. `ofType` is a valid field.', + }, + NON_NULL: { + value: TypeKind.NON_NULL, + description: + 'Indicates this type is a non-null. `ofType` is a valid field.', + }, + }, +}); +/** + * Note that these are GraphQLField and not GraphQLFieldConfig, + * so the format for args is different. + */ + +export const SchemaMetaFieldDef = { + name: '__schema', + type: new GraphQLNonNull(__Schema), + description: 'Access the current type schema of this server.', + args: [], + resolve: (_source, _args, _context, { schema }) => schema, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** The `__type` meta field definition used by introspection. */ + +export const TypeMetaFieldDef = { + name: '__type', + type: __Type, + description: 'Request the type information of a single type.', + args: [ + { + name: 'name', + description: undefined, + type: new GraphQLNonNull(GraphQLString), + defaultValue: undefined, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, + }, + ], + resolve: (_source, { name }, _context, { schema }) => schema.getType(name), + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** The `__typename` meta field definition used by execution and introspection. */ + +export const TypeNameMetaFieldDef = { + name: '__typename', + type: new GraphQLNonNull(GraphQLString), + description: 'The name of the current Object type at runtime.', + args: [], + resolve: (_source, _args, _context, { parentType }) => parentType.name, + deprecationReason: undefined, + extensions: Object.create(null), + astNode: undefined, +}; +/** All introspection types defined by the GraphQL specification. */ + +export const introspectionTypes = Object.freeze([ + __Schema, + __Directive, + __DirectiveLocation, + __Type, + __Field, + __InputValue, + __EnumValue, + __TypeKind, +]); +/** + * Returns true when the type is one of the built-in introspection types. + * @param type - The GraphQL type to inspect. + * @returns True when the type is one of the built-in introspection types. + * @example + * ```ts + * import { GraphQLString, isIntrospectionType, __Type } from 'graphql/type'; + * + * isIntrospectionType(__Type); // => true + * isIntrospectionType(GraphQLString); // => false + * ``` + */ + +export function isIntrospectionType(type) { + return introspectionTypes.some(({ name }) => type.name === name); +} diff --git a/node_modules/graphql/type/scalars.d.ts b/node_modules/graphql/type/scalars.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4549077c57c0814d86e2df42c5af661c4f07848e --- /dev/null +++ b/node_modules/graphql/type/scalars.d.ts @@ -0,0 +1,46 @@ +/** @category Scalars */ +import type { GraphQLNamedType } from './definition'; +import { GraphQLScalarType } from './definition'; +/** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + */ +export declare const GRAPHQL_MAX_INT = 2147483647; +/** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + */ +export declare const GRAPHQL_MIN_INT = -2147483648; +/** The built-in `Int` scalar type. */ +export declare const GraphQLInt: GraphQLScalarType; +/** The built-in `Float` scalar type. */ +export declare const GraphQLFloat: GraphQLScalarType; +/** The built-in `String` scalar type. */ +export declare const GraphQLString: GraphQLScalarType; +/** The built-in `Boolean` scalar type. */ +export declare const GraphQLBoolean: GraphQLScalarType; +/** The built-in `ID` scalar type. */ +export declare const GraphQLID: GraphQLScalarType; +/** All built-in scalar types defined by the GraphQL specification. */ +export declare const specifiedScalarTypes: ReadonlyArray; +/** + * Returns true when the scalar type is one of the scalars specified by GraphQL. + * @param type - The GraphQL type to inspect. + * @returns True when the scalar type is one of the scalars specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLScalarType, + * GraphQLString, + * isSpecifiedScalarType, + * } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ + * name: 'DateTime', + * }); + * + * isSpecifiedScalarType(GraphQLString); // => true + * isSpecifiedScalarType(DateTime); // => false + * ``` + */ +export declare function isSpecifiedScalarType(type: GraphQLNamedType): boolean; diff --git a/node_modules/graphql/type/scalars.js b/node_modules/graphql/type/scalars.js new file mode 100644 index 0000000000000000000000000000000000000000..31be4f2bcae407239189fdb3587506b8c0235622 --- /dev/null +++ b/node_modules/graphql/type/scalars.js @@ -0,0 +1,404 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.GraphQLString = + exports.GraphQLInt = + exports.GraphQLID = + exports.GraphQLFloat = + exports.GraphQLBoolean = + exports.GRAPHQL_MIN_INT = + exports.GRAPHQL_MAX_INT = + void 0; +exports.isSpecifiedScalarType = isSpecifiedScalarType; +exports.specifiedScalarTypes = void 0; + +var _inspect = require('../jsutils/inspect.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _kinds = require('../language/kinds.js'); + +var _printer = require('../language/printer.js'); + +var _definition = require('./definition.js'); + +/** @category Scalars */ + +/** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + */ +const GRAPHQL_MAX_INT = 2147483647; +/** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + */ + +exports.GRAPHQL_MAX_INT = GRAPHQL_MAX_INT; +const GRAPHQL_MIN_INT = -2147483648; +/** The built-in `Int` scalar type. */ + +exports.GRAPHQL_MIN_INT = GRAPHQL_MIN_INT; +const GraphQLInt = new _definition.GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isInteger(num)) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); + } + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + 'Int cannot represent non 32-bit signed integer value: ' + + (0, _inspect.inspect)(coercedValue), + ); + } + + return num; + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${inputValue}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non-integer value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + const num = parseInt(valueNode.value, 10); + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new _GraphQLError.GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, + { + nodes: valueNode, + }, + ); + } + + return num; + }, +}); +/** The built-in `Float` scalar type. */ + +exports.GraphQLInt = GraphQLInt; +const GraphQLFloat = new _definition.GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isFinite(num)) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); + } + + return num; + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.FLOAT && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + `Float cannot represent non numeric value: ${(0, _printer.print)( + valueNode, + )}`, + valueNode, + ); + } + + return parseFloat(valueNode.value); + }, +}); +/** The built-in `String` scalar type. */ + +exports.GraphQLFloat = GraphQLFloat; +const GraphQLString = new _definition.GraphQLScalarType({ + name: 'String', + description: + '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.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + + if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { + return coercedValue.toString(); + } + + throw new _GraphQLError.GraphQLError( + `String cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'string') { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.STRING) { + throw new _GraphQLError.GraphQLError( + `String cannot represent a non string value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** The built-in `Boolean` scalar type. */ + +exports.GraphQLString = GraphQLString; +const GraphQLBoolean = new _definition.GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( + coercedValue, + )}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _inspect.inspect)( + inputValue, + )}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== _kinds.Kind.BOOLEAN) { + throw new _GraphQLError.GraphQLError( + `Boolean cannot represent a non boolean value: ${(0, _printer.print)( + valueNode, + )}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** The built-in `ID` scalar type. */ + +exports.GraphQLBoolean = GraphQLBoolean; +const GraphQLID = new _definition.GraphQLScalarType({ + name: 'ID', + description: + '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.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (Number.isInteger(coercedValue)) { + return String(coercedValue); + } + + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)(outputValue)}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + + if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { + return inputValue.toString(); + } + + throw new _GraphQLError.GraphQLError( + `ID cannot represent value: ${(0, _inspect.inspect)(inputValue)}`, + ); + }, + + parseLiteral(valueNode) { + if ( + valueNode.kind !== _kinds.Kind.STRING && + valueNode.kind !== _kinds.Kind.INT + ) { + throw new _GraphQLError.GraphQLError( + 'ID cannot represent a non-string and non-integer value: ' + + (0, _printer.print)(valueNode), + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** All built-in scalar types defined by the GraphQL specification. */ + +exports.GraphQLID = GraphQLID; +const specifiedScalarTypes = Object.freeze([ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]); +/** + * Returns true when the scalar type is one of the scalars specified by GraphQL. + * @param type - The GraphQL type to inspect. + * @returns True when the scalar type is one of the scalars specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLScalarType, + * GraphQLString, + * isSpecifiedScalarType, + * } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ + * name: 'DateTime', + * }); + * + * isSpecifiedScalarType(GraphQLString); // => true + * isSpecifiedScalarType(DateTime); // => false + * ``` + */ + +exports.specifiedScalarTypes = specifiedScalarTypes; + +function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ name }) => type.name === name); +} // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +function serializeObject(outputValue) { + if ((0, _isObjectLike.isObjectLike)(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + + if (!(0, _isObjectLike.isObjectLike)(valueOfResult)) { + return valueOfResult; + } + } + + if (typeof outputValue.toJSON === 'function') { + return outputValue.toJSON(); + } + } + + return outputValue; +} diff --git a/node_modules/graphql/type/scalars.mjs b/node_modules/graphql/type/scalars.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a686c8e67585a1aa2c91be69b9b069cced08362e --- /dev/null +++ b/node_modules/graphql/type/scalars.mjs @@ -0,0 +1,343 @@ +/** @category Scalars */ +import { inspect } from '../jsutils/inspect.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { print } from '../language/printer.mjs'; +import { GraphQLScalarType } from './definition.mjs'; +/** + * Maximum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe up-to 2^53 - 1 + */ + +export const GRAPHQL_MAX_INT = 2147483647; +/** + * Minimum possible Int value as per GraphQL Spec (32-bit signed integer). + * n.b. This differs from JavaScript's numbers that are IEEE 754 doubles safe starting at -(2^53 - 1) + */ + +export const GRAPHQL_MIN_INT = -2147483648; +/** The built-in `Int` scalar type. */ + +export const GraphQLInt = new GraphQLScalarType({ + name: 'Int', + description: + 'The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isInteger(num)) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${inspect(coercedValue)}`, + ); + } + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new GraphQLError( + 'Int cannot represent non 32-bit signed integer value: ' + + inspect(coercedValue), + ); + } + + return num; + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isInteger(inputValue)) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${inspect(inputValue)}`, + ); + } + + if (inputValue > GRAPHQL_MAX_INT || inputValue < GRAPHQL_MIN_INT) { + throw new GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${inputValue}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.INT) { + throw new GraphQLError( + `Int cannot represent non-integer value: ${print(valueNode)}`, + { + nodes: valueNode, + }, + ); + } + + const num = parseInt(valueNode.value, 10); + + if (num > GRAPHQL_MAX_INT || num < GRAPHQL_MIN_INT) { + throw new GraphQLError( + `Int cannot represent non 32-bit signed integer value: ${valueNode.value}`, + { + nodes: valueNode, + }, + ); + } + + return num; + }, +}); +/** The built-in `Float` scalar type. */ + +export const GraphQLFloat = new GraphQLScalarType({ + name: 'Float', + description: + 'The `Float` scalar type represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point).', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 1 : 0; + } + + let num = coercedValue; + + if (typeof coercedValue === 'string' && coercedValue !== '') { + num = Number(coercedValue); + } + + if (typeof num !== 'number' || !Number.isFinite(num)) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${inspect(coercedValue)}`, + ); + } + + return num; + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'number' || !Number.isFinite(inputValue)) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${inspect(inputValue)}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.FLOAT && valueNode.kind !== Kind.INT) { + throw new GraphQLError( + `Float cannot represent non numeric value: ${print(valueNode)}`, + valueNode, + ); + } + + return parseFloat(valueNode.value); + }, +}); +/** The built-in `String` scalar type. */ + +export const GraphQLString = new GraphQLScalarType({ + name: 'String', + description: + '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.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); // Serialize string, boolean and number values to a string, but do not + // attempt to coerce object, function, symbol, or other types as strings. + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (typeof coercedValue === 'boolean') { + return coercedValue ? 'true' : 'false'; + } + + if (typeof coercedValue === 'number' && Number.isFinite(coercedValue)) { + return coercedValue.toString(); + } + + throw new GraphQLError( + `String cannot represent value: ${inspect(outputValue)}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'string') { + throw new GraphQLError( + `String cannot represent a non string value: ${inspect(inputValue)}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING) { + throw new GraphQLError( + `String cannot represent a non string value: ${print(valueNode)}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** The built-in `Boolean` scalar type. */ + +export const GraphQLBoolean = new GraphQLScalarType({ + name: 'Boolean', + description: 'The `Boolean` scalar type represents `true` or `false`.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'boolean') { + return coercedValue; + } + + if (Number.isFinite(coercedValue)) { + return coercedValue !== 0; + } + + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${inspect(coercedValue)}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue !== 'boolean') { + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${inspect(inputValue)}`, + ); + } + + return inputValue; + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.BOOLEAN) { + throw new GraphQLError( + `Boolean cannot represent a non boolean value: ${print(valueNode)}`, + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** The built-in `ID` scalar type. */ + +export const GraphQLID = new GraphQLScalarType({ + name: 'ID', + description: + '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.', + + serialize(outputValue) { + const coercedValue = serializeObject(outputValue); + + if (typeof coercedValue === 'string') { + return coercedValue; + } + + if (Number.isInteger(coercedValue)) { + return String(coercedValue); + } + + throw new GraphQLError( + `ID cannot represent value: ${inspect(outputValue)}`, + ); + }, + + parseValue(inputValue) { + if (typeof inputValue === 'string') { + return inputValue; + } + + if (typeof inputValue === 'number' && Number.isInteger(inputValue)) { + return inputValue.toString(); + } + + throw new GraphQLError(`ID cannot represent value: ${inspect(inputValue)}`); + }, + + parseLiteral(valueNode) { + if (valueNode.kind !== Kind.STRING && valueNode.kind !== Kind.INT) { + throw new GraphQLError( + 'ID cannot represent a non-string and non-integer value: ' + + print(valueNode), + { + nodes: valueNode, + }, + ); + } + + return valueNode.value; + }, +}); +/** All built-in scalar types defined by the GraphQL specification. */ + +export const specifiedScalarTypes = Object.freeze([ + GraphQLString, + GraphQLInt, + GraphQLFloat, + GraphQLBoolean, + GraphQLID, +]); +/** + * Returns true when the scalar type is one of the scalars specified by GraphQL. + * @param type - The GraphQL type to inspect. + * @returns True when the scalar type is one of the scalars specified by GraphQL. + * @example + * ```ts + * import { + * GraphQLScalarType, + * GraphQLString, + * isSpecifiedScalarType, + * } from 'graphql/type'; + * + * const DateTime = new GraphQLScalarType({ + * name: 'DateTime', + * }); + * + * isSpecifiedScalarType(GraphQLString); // => true + * isSpecifiedScalarType(DateTime); // => false + * ``` + */ + +export function isSpecifiedScalarType(type) { + return specifiedScalarTypes.some(({ name }) => type.name === name); +} // Support serializing objects with custom valueOf() or toJSON() functions - +// a common way to represent a complex value which can be represented as +// a string (ex: MongoDB id objects). + +function serializeObject(outputValue) { + if (isObjectLike(outputValue)) { + if (typeof outputValue.valueOf === 'function') { + const valueOfResult = outputValue.valueOf(); + + if (!isObjectLike(valueOfResult)) { + return valueOfResult; + } + } + + if (typeof outputValue.toJSON === 'function') { + return outputValue.toJSON(); + } + } + + return outputValue; +} diff --git a/node_modules/graphql/type/schema.d.ts b/node_modules/graphql/type/schema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..21d7e425c90a53fd238dc9f8c2de1a7018d193e8 --- /dev/null +++ b/node_modules/graphql/type/schema.d.ts @@ -0,0 +1,632 @@ +/** @category Schema */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { GraphQLError } from '../error/GraphQLError'; +import type { + SchemaDefinitionNode, + SchemaExtensionNode, +} from '../language/ast'; +import { OperationTypeNode } from '../language/ast'; +import type { + GraphQLAbstractType, + GraphQLInterfaceType, + GraphQLNamedType, + GraphQLObjectType, +} from './definition'; +import type { GraphQLDirective } from './directives'; +/** + * Test if the given value is a GraphQL schema. + * @param schema - Value to inspect. + * @returns True when the value is a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLString, isSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * isSchema(schema); // => true + * isSchema(GraphQLString); // => false + * ``` + */ +export declare function isSchema(schema: unknown): schema is GraphQLSchema; +/** + * Returns the value as a GraphQLSchema, or throws if it is not a schema. + * @param schema - GraphQL schema to use. + * @returns The value typed as a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertSchema, GraphQLString } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * assertSchema(schema); // => schema + * assertSchema(GraphQLString); // throws an error + * ``` + */ +export declare function assertSchema(schema: unknown): GraphQLSchema; +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ +export interface GraphQLSchemaExtensions { + [attributeName: string]: unknown; +} +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * @example + * ```ts + * const MyAppQueryRootType = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppMutationRootType = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { + * setGreeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }); + * ``` + * @example + * When the schema is constructed, by default only the types that are reachable + * by traversing the root types are included, other types must be explicitly + * referenced. + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface }, + * }, + * }), + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }); + * ``` + * @example + * If an array of `directives` are provided to GraphQLSchema, that will be the + * exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to + * these specified directives, you must explicitly declare them. + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * directives: specifiedDirectives.concat([myCustomDirective]), + * }); + * ``` + */ +export declare class GraphQLSchema { + /** Human-readable description for this schema element, if provided. */ + description: Maybe; + /** Custom extension fields reserved for users. */ + extensions: Readonly; + /** AST node from which this schema element was built, if available. */ + astNode: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes: ReadonlyArray; + /** + * Cached schema validation errors, if validation has already run. + * @internal + */ + __validationErrors: Maybe>; + private _queryType; + private _mutationType; + private _subscriptionType; + private _directives; + private _typeMap; + private _subTypeMap; + private _implementationsMap; + /** + * Creates a GraphQLSchema instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Create a schema with the required query root. + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { + * type: GraphQLString, + * resolve: () => 'Hello', + * }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * description: 'The application schema.', + * query: Query, + * }); + * + * schema.getQueryType(); // => Query + * schema.description; // => 'The application schema.' + * ``` + * @example + * ```ts + * // This variant configures every schema option, including directives and extensions. + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { greeting: { type: GraphQLString } }, + * }); + * const Mutation = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { setGreeting: { type: GraphQLString } }, + * }); + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { greetingChanged: { type: GraphQLString } }, + * }); + * const AuditEvent = new GraphQLObjectType({ + * name: 'AuditEvent', + * fields: { message: { type: GraphQLString } }, + * }); + * const authDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { required: { type: GraphQLBoolean } }, + * }); + * const schemaDocument = parse(` + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * + * extend schema @auth + * `); + * + * const schema = new GraphQLSchema({ + * description: 'Operations exposed by the application.', + * query: Query, + * mutation: Mutation, + * subscription: Subscription, + * types: [AuditEvent], + * directives: [authDirective], + * extensions: { owner: 'platform' }, + * astNode: schemaDocument.definitions[0], + * extensionASTNodes: [ schemaDocument.definitions[1] ], + * assumeValid: true, + * }); + * + * schema.getMutationType(); // => Mutation + * schema.getSubscriptionType(); // => Subscription + * schema.getType('AuditEvent'); // => AuditEvent + * schema.getDirective('auth'); // => authDirective + * schema.extensions; // => { owner: 'platform' } + * ``` + */ + constructor(config: Readonly); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the root object type for query operations. + * @returns The query root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * schema.getQueryType()?.name; // => 'Query' + * ``` + */ + getQueryType(): Maybe; + /** + * Returns the root object type for mutation operations. + * @returns The mutation root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getMutationType()?.name; // => 'Mutation' + * ``` + */ + getMutationType(): Maybe; + /** + * Returns the root object type for subscription operations. + * @returns The subscription root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Subscription { + * greetings: String + * } + * `); + * + * schema.getSubscriptionType()?.name; // => 'Subscription' + * ``` + */ + getSubscriptionType(): Maybe; + /** + * Returns the root object type for the requested operation kind. + * @param operation - Operation kind to resolve. + * @returns The root object type for the operation kind, if this schema defines one. + * @example + * ```ts + * import { OperationTypeNode } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getRootType(OperationTypeNode.QUERY)?.name; // => 'Query' + * schema.getRootType(OperationTypeNode.MUTATION)?.name; // => 'Mutation' + * schema.getRootType(OperationTypeNode.SUBSCRIPTION); // => undefined + * ``` + */ + getRootType(operation: OperationTypeNode): Maybe; + /** + * Returns all named types known to this schema. + * @returns A map of schema types keyed by type name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const typeMap = schema.getTypeMap(); + * + * typeMap.User.name; // => 'User' + * typeMap.Query.name; // => 'Query' + * typeMap.String.name; // => 'String' + * ``` + */ + getTypeMap(): TypeMap; + /** + * Returns the named type with the provided name. + * @param name - The GraphQL name to look up. + * @returns The named schema type, if one exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * schema.getType('User')?.toString(); // => 'User' + * schema.getType('Missing'); // => undefined + * ``` + */ + getType(name: string): GraphQLNamedType | undefined; + /** + * Returns object types that may be returned for an abstract type. + * @param abstractType - Interface or union type to inspect. + * @returns Object types that may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Organization implements Node { + * id: ID! + * } + * + * union SearchResult = User | Organization + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * schema.getPossibleTypes(Node).map((type) => type.name); // => ['User', 'Organization'] + * schema.getPossibleTypes(SearchResult).map((type) => type.name); // => ['User', 'Organization'] + * ``` + */ + getPossibleTypes( + abstractType: GraphQLAbstractType, + ): ReadonlyArray; + /** + * Returns objects and interfaces that implement an interface type. + * @param interfaceType - Interface type to inspect. + * @returns Object and interface implementations of the interface. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * resource: Resource + * } + * `); + * + * const Resource = assertInterfaceType(schema.getType('Resource')); + * const implementations = schema.getImplementations(Resource); + * + * implementations.interfaces.map((type) => type.name); // => ['Image'] + * implementations.objects.map((type) => type.name); // => ['Photo'] + * ``` + */ + getImplementations(interfaceType: GraphQLInterfaceType): { + objects: ReadonlyArray; + interfaces: ReadonlyArray; + }; + /** + * Returns whether one type is a possible runtime subtype of an abstract type. + * @param abstractType - Interface or union type to inspect. + * @param maybeSubType - Object or interface type to test as a possible subtype. + * @returns True when the subtype may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Review { + * body: String + * } + * + * type Query { + * node: Node + * review: Review + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * const Review = assertObjectType(schema.getType('Review')); + * + * schema.isSubType(Node, User); // => true + * schema.isSubType(Node, Review); // => false + * ``` + */ + isSubType( + abstractType: GraphQLAbstractType, + maybeSubType: GraphQLObjectType | GraphQLInterfaceType, + ): boolean; + /** + * Returns directives available in this schema. + * @returns Directives available in this schema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirectives().map((directive) => directive.name); // => ['include', 'skip', 'deprecated', 'specifiedBy', 'oneOf', 'upper'] + * ``` + */ + getDirectives(): ReadonlyArray; + /** + * Returns the current directive definition. + * @param name - The GraphQL name to look up. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirective('upper')?.name; // => 'upper' + * schema.getDirective('missing'); // => undefined + * ``` + */ + getDirective(name: string): Maybe; + /** + * Returns a normalized configuration object for this object. + * + * The returned config preserves the original `assumeValid` flag so the schema + * can be recreated with the same validation behavior. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const config = schema.toConfig(); + * const schemaCopy = new GraphQLSchema(config); + * + * config.query?.name; // => 'Query' + * schemaCopy.getQueryType()?.name; // => 'Query' + * ``` + */ + toConfig(): GraphQLSchemaNormalizedConfig; +} +declare type TypeMap = ObjMap; +/** @internal */ +export interface GraphQLSchemaValidationOptions { + /** + * When building a schema from a GraphQL service's introspection result, it + * might be safe to assume the schema is valid. Set to true to assume the + * produced schema is valid. + * + * Default: false + */ + assumeValid?: boolean; +} +/** Configuration used to construct a GraphQLSchema. */ +export interface GraphQLSchemaConfig extends GraphQLSchemaValidationOptions { + /** Human-readable description for this schema element, if provided. */ + description?: Maybe; + /** Root object type for query operations. */ + query?: Maybe; + /** Root object type for mutation operations. */ + mutation?: Maybe; + /** Root object type for subscription operations. */ + subscription?: Maybe; + /** Object types that belong to this union type. */ + types?: Maybe>; + /** Directives available in this schema or applied to this AST node. */ + directives?: Maybe>; + /** Custom extension fields reserved for users. */ + extensions?: Maybe>; + /** AST node from which this schema element was built, if available. */ + astNode?: Maybe; + /** AST extension nodes applied to this schema element. */ + extensionASTNodes?: Maybe>; +} +/** @internal */ +export interface GraphQLSchemaNormalizedConfig extends GraphQLSchemaConfig { + description: Maybe; + types: ReadonlyArray; + directives: ReadonlyArray; + extensions: Readonly; + extensionASTNodes: ReadonlyArray; + assumeValid: boolean; +} +export {}; diff --git a/node_modules/graphql/type/schema.js b/node_modules/graphql/type/schema.js new file mode 100644 index 0000000000000000000000000000000000000000..01bed94ac3aff678e1bdce94567e050c508b2b4b --- /dev/null +++ b/node_modules/graphql/type/schema.js @@ -0,0 +1,860 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.GraphQLSchema = void 0; +exports.assertSchema = assertSchema; +exports.isSchema = isSchema; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _instanceOf = require('../jsutils/instanceOf.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _toObjMap = require('../jsutils/toObjMap.js'); + +var _ast = require('../language/ast.js'); + +var _definition = require('./definition.js'); + +var _directives = require('./directives.js'); + +var _introspection = require('./introspection.js'); + +/** @category Schema */ + +/** + * Test if the given value is a GraphQL schema. + * @param schema - Value to inspect. + * @returns True when the value is a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLString, isSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * isSchema(schema); // => true + * isSchema(GraphQLString); // => false + * ``` + */ +function isSchema(schema) { + return (0, _instanceOf.instanceOf)(schema, GraphQLSchema); +} +/** + * Returns the value as a GraphQLSchema, or throws if it is not a schema. + * @param schema - GraphQL schema to use. + * @returns The value typed as a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertSchema, GraphQLString } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * assertSchema(schema); // => schema + * assertSchema(GraphQLString); // throws an error + * ``` + */ + +function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error( + `Expected ${(0, _inspect.inspect)(schema)} to be a GraphQL schema.`, + ); + } + + return schema; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * @example + * ```ts + * const MyAppQueryRootType = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppMutationRootType = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { + * setGreeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }); + * ``` + * @example + * When the schema is constructed, by default only the types that are reachable + * by traversing the root types are included, other types must be explicitly + * referenced. + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface }, + * }, + * }), + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }); + * ``` + * @example + * If an array of `directives` are provided to GraphQLSchema, that will be the + * exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to + * these specified directives, you must explicitly declare them. + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * directives: specifiedDirectives.concat([myCustomDirective]), + * }); + * ``` + */ +class GraphQLSchema { + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Cached schema validation errors, if validation has already run. + * @internal + */ + + /** + * Creates a GraphQLSchema instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Create a schema with the required query root. + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { + * type: GraphQLString, + * resolve: () => 'Hello', + * }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * description: 'The application schema.', + * query: Query, + * }); + * + * schema.getQueryType(); // => Query + * schema.description; // => 'The application schema.' + * ``` + * @example + * ```ts + * // This variant configures every schema option, including directives and extensions. + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { greeting: { type: GraphQLString } }, + * }); + * const Mutation = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { setGreeting: { type: GraphQLString } }, + * }); + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { greetingChanged: { type: GraphQLString } }, + * }); + * const AuditEvent = new GraphQLObjectType({ + * name: 'AuditEvent', + * fields: { message: { type: GraphQLString } }, + * }); + * const authDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { required: { type: GraphQLBoolean } }, + * }); + * const schemaDocument = parse(` + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * + * extend schema @auth + * `); + * + * const schema = new GraphQLSchema({ + * description: 'Operations exposed by the application.', + * query: Query, + * mutation: Mutation, + * subscription: Subscription, + * types: [AuditEvent], + * directives: [authDirective], + * extensions: { owner: 'platform' }, + * astNode: schemaDocument.definitions[0], + * extensionASTNodes: [ schemaDocument.definitions[1] ], + * assumeValid: true, + * }); + * + * schema.getMutationType(); // => Mutation + * schema.getSubscriptionType(); // => Subscription + * schema.getType('AuditEvent'); // => AuditEvent + * schema.getDirective('auth'); // => authDirective + * schema.extensions; // => { owner: 'platform' } + * ``` + */ + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + (0, _isObjectLike.isObjectLike)(config) || + (0, _devAssert.devAssert)(false, 'Must provide configuration object.'); + !config.types || + Array.isArray(config.types) || + (0, _devAssert.devAssert)( + false, + `"types" must be Array if provided but got: ${(0, _inspect.inspect)( + config.types, + )}.`, + ); + !config.directives || + Array.isArray(config.directives) || + (0, _devAssert.devAssert)( + false, + '"directives" must be Array if provided but got: ' + + `${(0, _inspect.inspect)(config.directives)}.`, + ); + this.description = config.description; + this.extensions = (0, _toObjMap.toObjMap)(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = + (_config$directives = config.directives) !== null && + _config$directives !== void 0 + ? _config$directives + : _directives.specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if ((0, _directives.isDirective)(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + + collectReferencedTypes(_introspection.__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + + const typeName = namedType.name; + typeName || + (0, _devAssert.devAssert)( + false, + 'One of the provided types for building the Schema is missing a name.', + ); + + if (this._typeMap[typeName] !== undefined) { + throw new Error( + `Schema must contain uniquely named types but contains multiple types named "${typeName}".`, + ); + } + + this._typeMap[typeName] = namedType; + + if ((0, _definition.isInterfaceType)(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if ((0, _definition.isObjectType)(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if ((0, _definition.isInterfaceType)(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.objects.push(namedType); + } + } + } + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLSchema'; + } + /** + * Returns the root object type for query operations. + * @returns The query root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * schema.getQueryType()?.name; // => 'Query' + * ``` + */ + + getQueryType() { + return this._queryType; + } + /** + * Returns the root object type for mutation operations. + * @returns The mutation root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getMutationType()?.name; // => 'Mutation' + * ``` + */ + + getMutationType() { + return this._mutationType; + } + /** + * Returns the root object type for subscription operations. + * @returns The subscription root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Subscription { + * greetings: String + * } + * `); + * + * schema.getSubscriptionType()?.name; // => 'Subscription' + * ``` + */ + + getSubscriptionType() { + return this._subscriptionType; + } + /** + * Returns the root object type for the requested operation kind. + * @param operation - Operation kind to resolve. + * @returns The root object type for the operation kind, if this schema defines one. + * @example + * ```ts + * import { OperationTypeNode } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getRootType(OperationTypeNode.QUERY)?.name; // => 'Query' + * schema.getRootType(OperationTypeNode.MUTATION)?.name; // => 'Mutation' + * schema.getRootType(OperationTypeNode.SUBSCRIPTION); // => undefined + * ``` + */ + + getRootType(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return this.getQueryType(); + + case _ast.OperationTypeNode.MUTATION: + return this.getMutationType(); + + case _ast.OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + /** + * Returns all named types known to this schema. + * @returns A map of schema types keyed by type name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const typeMap = schema.getTypeMap(); + * + * typeMap.User.name; // => 'User' + * typeMap.Query.name; // => 'Query' + * typeMap.String.name; // => 'String' + * ``` + */ + + getTypeMap() { + return this._typeMap; + } + /** + * Returns the named type with the provided name. + * @param name - The GraphQL name to look up. + * @returns The named schema type, if one exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * schema.getType('User')?.toString(); // => 'User' + * schema.getType('Missing'); // => undefined + * ``` + */ + + getType(name) { + return this.getTypeMap()[name]; + } + /** + * Returns object types that may be returned for an abstract type. + * @param abstractType - Interface or union type to inspect. + * @returns Object types that may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Organization implements Node { + * id: ID! + * } + * + * union SearchResult = User | Organization + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * schema.getPossibleTypes(Node).map((type) => type.name); // => ['User', 'Organization'] + * schema.getPossibleTypes(SearchResult).map((type) => type.name); // => ['User', 'Organization'] + * ``` + */ + + getPossibleTypes(abstractType) { + return (0, _definition.isUnionType)(abstractType) + ? abstractType.getTypes() + : this.getImplementations(abstractType).objects; + } + /** + * Returns objects and interfaces that implement an interface type. + * @param interfaceType - Interface type to inspect. + * @returns Object and interface implementations of the interface. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * resource: Resource + * } + * `); + * + * const Resource = assertInterfaceType(schema.getType('Resource')); + * const implementations = schema.getImplementations(Resource); + * + * implementations.interfaces.map((type) => type.name); // => ['Image'] + * implementations.objects.map((type) => type.name); // => ['Photo'] + * ``` + */ + + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 + ? implementations + : { + objects: [], + interfaces: [], + }; + } + /** + * Returns whether one type is a possible runtime subtype of an abstract type. + * @param abstractType - Interface or union type to inspect. + * @param maybeSubType - Object or interface type to test as a possible subtype. + * @returns True when the subtype may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Review { + * body: String + * } + * + * type Query { + * node: Node + * review: Review + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * const Review = assertObjectType(schema.getType('Review')); + * + * schema.isSubType(Node, User); // => true + * schema.isSubType(Node, Review); // => false + * ``` + */ + + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + + if (map === undefined) { + map = Object.create(null); + + if ((0, _definition.isUnionType)(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + + for (const type of implementations.objects) { + map[type.name] = true; + } + + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + + return map[maybeSubType.name] !== undefined; + } + /** + * Returns directives available in this schema. + * @returns Directives available in this schema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirectives().map((directive) => directive.name); // => ['include', 'skip', 'deprecated', 'specifiedBy', 'oneOf', 'upper'] + * ``` + */ + + getDirectives() { + return this._directives; + } + /** + * Returns the current directive definition. + * @param name - The GraphQL name to look up. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirective('upper')?.name; // => 'upper' + * schema.getDirective('missing'); // => undefined + * ``` + */ + + getDirective(name) { + return this.getDirectives().find((directive) => directive.name === name); + } + /** + * Returns a normalized configuration object for this object. + * + * The returned config preserves the original `assumeValid` flag so the schema + * can be recreated with the same validation behavior. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const config = schema.toConfig(); + * const schemaCopy = new GraphQLSchema(config); + * + * config.query?.name; // => 'Query' + * schemaCopy.getQueryType()?.name; // => 'Query' + * ``` + */ + + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined, + }; + } +} + +exports.GraphQLSchema = GraphQLSchema; + +function collectReferencedTypes(type, typeSet) { + const namedType = (0, _definition.getNamedType)(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + + if ((0, _definition.isUnionType)(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if ( + (0, _definition.isObjectType)(namedType) || + (0, _definition.isInterfaceType)(namedType) + ) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if ((0, _definition.isInputObjectType)(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + + return typeSet; +} diff --git a/node_modules/graphql/type/schema.mjs b/node_modules/graphql/type/schema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..74b53fa60ce82394057368e499111c5697220d1a --- /dev/null +++ b/node_modules/graphql/type/schema.mjs @@ -0,0 +1,839 @@ +/** @category Schema */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { instanceOf } from '../jsutils/instanceOf.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { toObjMap } from '../jsutils/toObjMap.mjs'; +import { OperationTypeNode } from '../language/ast.mjs'; +import { + getNamedType, + isInputObjectType, + isInterfaceType, + isObjectType, + isUnionType, +} from './definition.mjs'; +import { isDirective, specifiedDirectives } from './directives.mjs'; +import { __Schema } from './introspection.mjs'; +/** + * Test if the given value is a GraphQL schema. + * @param schema - Value to inspect. + * @returns True when the value is a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLString, isSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * isSchema(schema); // => true + * isSchema(GraphQLString); // => false + * ``` + */ + +export function isSchema(schema) { + return instanceOf(schema, GraphQLSchema); +} +/** + * Returns the value as a GraphQLSchema, or throws if it is not a schema. + * @param schema - GraphQL schema to use. + * @returns The value typed as a GraphQLSchema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertSchema, GraphQLString } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * assertSchema(schema); // => schema + * assertSchema(GraphQLString); // throws an error + * ``` + */ + +export function assertSchema(schema) { + if (!isSchema(schema)) { + throw new Error(`Expected ${inspect(schema)} to be a GraphQL schema.`); + } + + return schema; +} +/** + * Custom extensions + * @remarks + * Use a unique identifier name for your extension, for example the name of + * your library or project. Do not use a shortened identifier as this increases + * the risk of conflicts. We recommend you add at most one extension field, + * an object which can contain all the values you need. + */ + +/** + * Schema Definition + * + * A Schema is created by supplying the root types of each type of operation, + * query and mutation (optional). A schema definition is then supplied to the + * validator and executor. + * @example + * ```ts + * const MyAppQueryRootType = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppMutationRootType = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { + * setGreeting: { type: GraphQLString }, + * }, + * }); + * + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * mutation: MyAppMutationRootType, + * }); + * ``` + * @example + * When the schema is constructed, by default only the types that are reachable + * by traversing the root types are included, other types must be explicitly + * referenced. + * + * ```ts + * const characterInterface = new GraphQLInterfaceType({ + * name: 'Character', + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const humanType = new GraphQLObjectType({ + * name: 'Human', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const droidType = new GraphQLObjectType({ + * name: 'Droid', + * interfaces: [characterInterface], + * fields: { + * name: { type: GraphQLString }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * hero: { type: characterInterface }, + * }, + * }), + * // Since this schema references only the `Character` interface it's + * // necessary to explicitly list the types that implement it if + * // you want them to be included in the final schema. + * types: [humanType, droidType], + * }); + * ``` + * @example + * If an array of `directives` are provided to GraphQLSchema, that will be the + * exact list of directives represented and allowed. If `directives` is not + * provided then a default set of the specified directives (e.g. `@include` and + * `@skip`) will be used. If you wish to provide *additional* directives to + * these specified directives, you must explicitly declare them. + * + * ```ts + * const MyAppSchema = new GraphQLSchema({ + * query: MyAppQueryRootType, + * directives: specifiedDirectives.concat([myCustomDirective]), + * }); + * ``` + */ +export class GraphQLSchema { + /** Human-readable description for this schema element, if provided. */ + + /** Custom extension fields reserved for users. */ + + /** AST node from which this schema element was built, if available. */ + + /** AST extension nodes applied to this schema element. */ + + /** + * Cached schema validation errors, if validation has already run. + * @internal + */ + + /** + * Creates a GraphQLSchema instance. + * @param config - Configuration describing this object. + * @example + * ```ts + * // Create a schema with the required query root. + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { + * greeting: { + * type: GraphQLString, + * resolve: () => 'Hello', + * }, + * }, + * }); + * + * const schema = new GraphQLSchema({ + * description: 'The application schema.', + * query: Query, + * }); + * + * schema.getQueryType(); // => Query + * schema.description; // => 'The application schema.' + * ``` + * @example + * ```ts + * // This variant configures every schema option, including directives and extensions. + * import { DirectiveLocation, parse } from 'graphql/language'; + * import { + * GraphQLBoolean, + * GraphQLDirective, + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * } from 'graphql/type'; + * + * const Query = new GraphQLObjectType({ + * name: 'Query', + * fields: { greeting: { type: GraphQLString } }, + * }); + * const Mutation = new GraphQLObjectType({ + * name: 'Mutation', + * fields: { setGreeting: { type: GraphQLString } }, + * }); + * const Subscription = new GraphQLObjectType({ + * name: 'Subscription', + * fields: { greetingChanged: { type: GraphQLString } }, + * }); + * const AuditEvent = new GraphQLObjectType({ + * name: 'AuditEvent', + * fields: { message: { type: GraphQLString } }, + * }); + * const authDirective = new GraphQLDirective({ + * name: 'auth', + * locations: [DirectiveLocation.FIELD_DEFINITION], + * args: { required: { type: GraphQLBoolean } }, + * }); + * const schemaDocument = parse(` + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * + * extend schema @auth + * `); + * + * const schema = new GraphQLSchema({ + * description: 'Operations exposed by the application.', + * query: Query, + * mutation: Mutation, + * subscription: Subscription, + * types: [AuditEvent], + * directives: [authDirective], + * extensions: { owner: 'platform' }, + * astNode: schemaDocument.definitions[0], + * extensionASTNodes: [ schemaDocument.definitions[1] ], + * assumeValid: true, + * }); + * + * schema.getMutationType(); // => Mutation + * schema.getSubscriptionType(); // => Subscription + * schema.getType('AuditEvent'); // => AuditEvent + * schema.getDirective('auth'); // => authDirective + * schema.extensions; // => { owner: 'platform' } + * ``` + */ + constructor(config) { + var _config$extensionASTN, _config$directives; + + // If this schema was built from a source known to be valid, then it may be + // marked with assumeValid to avoid an additional type system validation. + this.__validationErrors = config.assumeValid === true ? [] : undefined; // Check for common mistakes during construction to produce early errors. + + isObjectLike(config) || + devAssert(false, 'Must provide configuration object.'); + !config.types || + Array.isArray(config.types) || + devAssert( + false, + `"types" must be Array if provided but got: ${inspect(config.types)}.`, + ); + !config.directives || + Array.isArray(config.directives) || + devAssert( + false, + '"directives" must be Array if provided but got: ' + + `${inspect(config.directives)}.`, + ); + this.description = config.description; + this.extensions = toObjMap(config.extensions); + this.astNode = config.astNode; + this.extensionASTNodes = + (_config$extensionASTN = config.extensionASTNodes) !== null && + _config$extensionASTN !== void 0 + ? _config$extensionASTN + : []; + this._queryType = config.query; + this._mutationType = config.mutation; + this._subscriptionType = config.subscription; // Provide specified directives (e.g. @include and @skip) by default. + + this._directives = + (_config$directives = config.directives) !== null && + _config$directives !== void 0 + ? _config$directives + : specifiedDirectives; // To preserve order of user-provided types, we add first to add them to + // the set of "collected" types, so `collectReferencedTypes` ignore them. + + const allReferencedTypes = new Set(config.types); + + if (config.types != null) { + for (const type of config.types) { + // When we ready to process this type, we remove it from "collected" types + // and then add it together with all dependent types in the correct position. + allReferencedTypes.delete(type); + collectReferencedTypes(type, allReferencedTypes); + } + } + + if (this._queryType != null) { + collectReferencedTypes(this._queryType, allReferencedTypes); + } + + if (this._mutationType != null) { + collectReferencedTypes(this._mutationType, allReferencedTypes); + } + + if (this._subscriptionType != null) { + collectReferencedTypes(this._subscriptionType, allReferencedTypes); + } + + for (const directive of this._directives) { + // Directives are not validated until validateSchema() is called. + if (isDirective(directive)) { + for (const arg of directive.args) { + collectReferencedTypes(arg.type, allReferencedTypes); + } + } + } + + collectReferencedTypes(__Schema, allReferencedTypes); // Storing the resulting map for reference by the schema. + + this._typeMap = Object.create(null); + this._subTypeMap = Object.create(null); // Keep track of all implementations by interface name. + + this._implementationsMap = Object.create(null); + + for (const namedType of allReferencedTypes) { + if (namedType == null) { + continue; + } + + const typeName = namedType.name; + typeName || + devAssert( + false, + 'One of the provided types for building the Schema is missing a name.', + ); + + if (this._typeMap[typeName] !== undefined) { + throw new Error( + `Schema must contain uniquely named types but contains multiple types named "${typeName}".`, + ); + } + + this._typeMap[typeName] = namedType; + + if (isInterfaceType(namedType)) { + // Store implementations by interface. + for (const iface of namedType.getInterfaces()) { + if (isInterfaceType(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.interfaces.push(namedType); + } + } + } else if (isObjectType(namedType)) { + // Store implementations by objects. + for (const iface of namedType.getInterfaces()) { + if (isInterfaceType(iface)) { + let implementations = this._implementationsMap[iface.name]; + + if (implementations === undefined) { + implementations = this._implementationsMap[iface.name] = { + objects: [], + interfaces: [], + }; + } + + implementations.objects.push(namedType); + } + } + } + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'GraphQLSchema'; + } + /** + * Returns the root object type for query operations. + * @returns The query root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * schema.getQueryType()?.name; // => 'Query' + * ``` + */ + + getQueryType() { + return this._queryType; + } + /** + * Returns the root object type for mutation operations. + * @returns The mutation root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getMutationType()?.name; // => 'Mutation' + * ``` + */ + + getMutationType() { + return this._mutationType; + } + /** + * Returns the root object type for subscription operations. + * @returns The subscription root type, if this schema defines one. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Subscription { + * greetings: String + * } + * `); + * + * schema.getSubscriptionType()?.name; // => 'Subscription' + * ``` + */ + + getSubscriptionType() { + return this._subscriptionType; + } + /** + * Returns the root object type for the requested operation kind. + * @param operation - Operation kind to resolve. + * @returns The root object type for the operation kind, if this schema defines one. + * @example + * ```ts + * import { OperationTypeNode } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * + * type Mutation { + * setGreeting(value: String!): String + * } + * `); + * + * schema.getRootType(OperationTypeNode.QUERY)?.name; // => 'Query' + * schema.getRootType(OperationTypeNode.MUTATION)?.name; // => 'Mutation' + * schema.getRootType(OperationTypeNode.SUBSCRIPTION); // => undefined + * ``` + */ + + getRootType(operation) { + switch (operation) { + case OperationTypeNode.QUERY: + return this.getQueryType(); + + case OperationTypeNode.MUTATION: + return this.getMutationType(); + + case OperationTypeNode.SUBSCRIPTION: + return this.getSubscriptionType(); + } + } + /** + * Returns all named types known to this schema. + * @returns A map of schema types keyed by type name. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const typeMap = schema.getTypeMap(); + * + * typeMap.User.name; // => 'User' + * typeMap.Query.name; // => 'Query' + * typeMap.String.name; // => 'String' + * ``` + */ + + getTypeMap() { + return this._typeMap; + } + /** + * Returns the named type with the provided name. + * @param name - The GraphQL name to look up. + * @returns The named schema type, if one exists. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * schema.getType('User')?.toString(); // => 'User' + * schema.getType('Missing'); // => undefined + * ``` + */ + + getType(name) { + return this.getTypeMap()[name]; + } + /** + * Returns object types that may be returned for an abstract type. + * @param abstractType - Interface or union type to inspect. + * @returns Object types that may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertUnionType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Organization implements Node { + * id: ID! + * } + * + * union SearchResult = User | Organization + * + * type Query { + * node: Node + * search: [SearchResult] + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const SearchResult = assertUnionType(schema.getType('SearchResult')); + * + * schema.getPossibleTypes(Node).map((type) => type.name); // => ['User', 'Organization'] + * schema.getPossibleTypes(SearchResult).map((type) => type.name); // => ['User', 'Organization'] + * ``` + */ + + getPossibleTypes(abstractType) { + return isUnionType(abstractType) + ? abstractType.getTypes() + : this.getImplementations(abstractType).objects; + } + /** + * Returns objects and interfaces that implement an interface type. + * @param interfaceType - Interface type to inspect. + * @returns Object and interface implementations of the interface. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Resource { + * url: String! + * } + * + * interface Image implements Resource { + * url: String! + * width: Int + * } + * + * type Photo implements Resource & Image { + * url: String! + * width: Int + * } + * + * type Query { + * resource: Resource + * } + * `); + * + * const Resource = assertInterfaceType(schema.getType('Resource')); + * const implementations = schema.getImplementations(Resource); + * + * implementations.interfaces.map((type) => type.name); // => ['Image'] + * implementations.objects.map((type) => type.name); // => ['Photo'] + * ``` + */ + + getImplementations(interfaceType) { + const implementations = this._implementationsMap[interfaceType.name]; + return implementations !== null && implementations !== void 0 + ? implementations + : { + objects: [], + interfaces: [], + }; + } + /** + * Returns whether one type is a possible runtime subtype of an abstract type. + * @param abstractType - Interface or union type to inspect. + * @param maybeSubType - Object or interface type to test as a possible subtype. + * @returns True when the subtype may satisfy the abstract type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertInterfaceType, assertObjectType } from 'graphql/type'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Review { + * body: String + * } + * + * type Query { + * node: Node + * review: Review + * } + * `); + * + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * const Review = assertObjectType(schema.getType('Review')); + * + * schema.isSubType(Node, User); // => true + * schema.isSubType(Node, Review); // => false + * ``` + */ + + isSubType(abstractType, maybeSubType) { + let map = this._subTypeMap[abstractType.name]; + + if (map === undefined) { + map = Object.create(null); + + if (isUnionType(abstractType)) { + for (const type of abstractType.getTypes()) { + map[type.name] = true; + } + } else { + const implementations = this.getImplementations(abstractType); + + for (const type of implementations.objects) { + map[type.name] = true; + } + + for (const type of implementations.interfaces) { + map[type.name] = true; + } + } + + this._subTypeMap[abstractType.name] = map; + } + + return map[maybeSubType.name] !== undefined; + } + /** + * Returns directives available in this schema. + * @returns Directives available in this schema. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirectives().map((directive) => directive.name); // => ['include', 'skip', 'deprecated', 'specifiedBy', 'oneOf', 'upper'] + * ``` + */ + + getDirectives() { + return this._directives; + } + /** + * Returns the current directive definition. + * @param name - The GraphQL name to look up. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * schema.getDirective('upper')?.name; // => 'upper' + * schema.getDirective('missing'); // => undefined + * ``` + */ + + getDirective(name) { + return this.getDirectives().find((directive) => directive.name === name); + } + /** + * Returns a normalized configuration object for this object. + * + * The returned config preserves the original `assumeValid` flag so the schema + * can be recreated with the same validation behavior. + * @returns A configuration object that can be used to recreate this object. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { GraphQLSchema } from 'graphql/type'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const config = schema.toConfig(); + * const schemaCopy = new GraphQLSchema(config); + * + * config.query?.name; // => 'Query' + * schemaCopy.getQueryType()?.name; // => 'Query' + * ``` + */ + + toConfig() { + return { + description: this.description, + query: this.getQueryType(), + mutation: this.getMutationType(), + subscription: this.getSubscriptionType(), + types: Object.values(this.getTypeMap()), + directives: this.getDirectives(), + extensions: this.extensions, + astNode: this.astNode, + extensionASTNodes: this.extensionASTNodes, + assumeValid: this.__validationErrors !== undefined, + }; + } +} + +function collectReferencedTypes(type, typeSet) { + const namedType = getNamedType(type); + + if (!typeSet.has(namedType)) { + typeSet.add(namedType); + + if (isUnionType(namedType)) { + for (const memberType of namedType.getTypes()) { + collectReferencedTypes(memberType, typeSet); + } + } else if (isObjectType(namedType) || isInterfaceType(namedType)) { + for (const interfaceType of namedType.getInterfaces()) { + collectReferencedTypes(interfaceType, typeSet); + } + + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + + for (const arg of field.args) { + collectReferencedTypes(arg.type, typeSet); + } + } + } else if (isInputObjectType(namedType)) { + for (const field of Object.values(namedType.getFields())) { + collectReferencedTypes(field.type, typeSet); + } + } + } + + return typeSet; +} diff --git a/node_modules/graphql/type/validate.d.ts b/node_modules/graphql/type/validate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fda009a0fe700021ed5a0bb64ccb376407086e33 --- /dev/null +++ b/node_modules/graphql/type/validate.d.ts @@ -0,0 +1,48 @@ +/** @category Validation */ +import { GraphQLError } from '../error/GraphQLError'; +import type { GraphQLSchema } from './schema'; +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + * @param schema - GraphQL schema to use. + * @returns Schema validation errors, or an empty array when the schema is valid. + * @example + * ```ts + * import { validateSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * const errors = validateSchema(schema); + * + * errors; // => [] + * ``` + */ +export declare function validateSchema( + schema: GraphQLSchema, +): ReadonlyArray; +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + * @param schema - GraphQL schema to use. + * @example + * ```ts + * import { assertValidSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * assertValidSchema(schema); // does not throw + * ``` + */ +export declare function assertValidSchema(schema: GraphQLSchema): void; diff --git a/node_modules/graphql/type/validate.js b/node_modules/graphql/type/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..9ddcc4d986fc8028dcab922de0ccecc703bf7f81 --- /dev/null +++ b/node_modules/graphql/type/validate.js @@ -0,0 +1,738 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.assertValidSchema = assertValidSchema; +exports.validateSchema = validateSchema; + +var _inspect = require('../jsutils/inspect.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _ast = require('../language/ast.js'); + +var _typeComparators = require('../utilities/typeComparators.js'); + +var _definition = require('./definition.js'); + +var _directives = require('./directives.js'); + +var _introspection = require('./introspection.js'); + +var _schema = require('./schema.js'); + +/** @category Validation */ + +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + * @param schema - GraphQL schema to use. + * @returns Schema validation errors, or an empty array when the schema is valid. + * @example + * ```ts + * import { validateSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * const errors = validateSchema(schema); + * + * errors; // => [] + * ``` + */ +function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + (0, _schema.assertSchema)(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + * @param schema - GraphQL schema to use. + * @example + * ```ts + * import { assertValidSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * assertValidSchema(schema); // does not throw + * ``` + */ + +function assertValidSchema(schema) { + const errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + + this._errors.push( + new _GraphQLError.GraphQLError(message, { + nodes: _nodes, + }), + ); + } + + getErrors() { + return this._errors; + } +} + +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!(0, _definition.isObjectType)(queryType)) { + var _getOperationTypeNode; + + context.reportError( + `Query root type must be Object type, it cannot be ${(0, + _inspect.inspect)(queryType)}.`, + (_getOperationTypeNode = getOperationTypeNode( + schema, + _ast.OperationTypeNode.QUERY, + )) !== null && _getOperationTypeNode !== void 0 + ? _getOperationTypeNode + : queryType.astNode, + ); + } + + const mutationType = schema.getMutationType(); + + if (mutationType && !(0, _definition.isObjectType)(mutationType)) { + var _getOperationTypeNode2; + + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${(0, _inspect.inspect)(mutationType)}.`, + (_getOperationTypeNode2 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.MUTATION, + )) !== null && _getOperationTypeNode2 !== void 0 + ? _getOperationTypeNode2 + : mutationType.astNode, + ); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !(0, _definition.isObjectType)(subscriptionType)) { + var _getOperationTypeNode3; + + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${(0, _inspect.inspect)(subscriptionType)}.`, + (_getOperationTypeNode3 = getOperationTypeNode( + schema, + _ast.OperationTypeNode.SUBSCRIPTION, + )) !== null && _getOperationTypeNode3 !== void 0 + ? _getOperationTypeNode3 + : subscriptionType.astNode, + ); + } +} + +function getOperationTypeNode(schema, operation) { + var _flatMap$find; + + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes] + .flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (schemaNode) => { + var _schemaNode$operation; + + return ( + /* c8 ignore next */ + (_schemaNode$operation = + schemaNode === null || schemaNode === void 0 + ? void 0 + : schemaNode.operationTypes) !== null && + _schemaNode$operation !== void 0 + ? _schemaNode$operation + : [] + ); + }, + ) + .find((operationNode) => operationNode.operation === operation)) === null || + _flatMap$find === void 0 + ? void 0 + : _flatMap$find.type; +} + +function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!(0, _directives.isDirective)(directive)) { + context.reportError( + `Expected directive but got: ${(0, _inspect.inspect)(directive)}.`, + directive === null || directive === void 0 ? void 0 : directive.astNode, + ); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); + + if (directive.locations.length === 0) { + context.reportError( + `Directive @${directive.name} must include 1 or more locations.`, + directive.astNode, + ); + } // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!(0, _definition.isInputType)(arg.type)) { + context.reportError( + `The type of @${directive.name}(${arg.name}:) must be Input Type ` + + `but got: ${(0, _inspect.inspect)(arg.type)}.`, + arg.astNode, + ); + } + + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode; + + context.reportError( + `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 + ? void 0 + : _arg$astNode.type, + ], + ); + } + } + } +} + +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith('__')) { + context.reportError( + `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, + node.astNode, + ); + } +} + +function validateTypes(context) { + const validateInputObjectCircularRefs = + createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!(0, _definition.isNamedType)(type)) { + context.reportError( + `Expected GraphQL named type but got: ${(0, _inspect.inspect)(type)}.`, + type.astNode, + ); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!(0, _introspection.isIntrospectionType)(type)) { + validateName(context, type); + } + + if ((0, _definition.isObjectType)(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isInterfaceType)(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if ((0, _definition.isUnionType)(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if ((0, _definition.isEnumType)(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if ((0, _definition.isInputObjectType)(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError(`Type ${type.name} must define one or more fields.`, [ + type.astNode, + ...type.extensionASTNodes, + ]); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!(0, _definition.isOutputType)(field.type)) { + var _field$astNode; + + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode = field.astNode) === null || _field$astNode === void 0 + ? void 0 + : _field$astNode.type, + ); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(arg.type)) { + var _arg$astNode2; + + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${(0, _inspect.inspect)(arg.type)}.`, + (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 + ? void 0 + : _arg$astNode2.type, + ); + } + + if ( + (0, _definition.isRequiredArgument)(arg) && + arg.deprecationReason != null + ) { + var _arg$astNode3; + + context.reportError( + `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 + ? void 0 + : _arg$astNode3.type, + ], + ); + } + } + } +} + +function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + + for (const iface of type.getInterfaces()) { + if (!(0, _definition.isInterfaceType)(iface)) { + context.reportError( + `Type ${(0, _inspect.inspect)( + type, + )} must only implement Interface types, ` + + `it cannot implement ${(0, _inspect.inspect)(iface)}.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (type === iface) { + context.reportError( + `Type ${type.name} cannot implement itself because it would create a circular reference.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError( + `Type ${type.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, + [ifaceField.astNode, type.astNode, ...type.extensionASTNodes], + ); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if ( + !(0, _typeComparators.isTypeSubTypeOf)( + context.schema, + typeField.type, + ifaceField.type, + ) + ) { + var _ifaceField$astNode, _typeField$astNode; + + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${(0, _inspect.inspect)(ifaceField.type)} but ${ + type.name + }.${fieldName} ` + + `is type ${(0, _inspect.inspect)(typeField.type)}.`, + [ + (_ifaceField$astNode = ifaceField.astNode) === null || + _ifaceField$astNode === void 0 + ? void 0 + : _ifaceField$astNode.type, + (_typeField$astNode = typeField.astNode) === null || + _typeField$astNode === void 0 + ? void 0 + : _typeField$astNode.type, + ], + ); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find((arg) => arg.name === argName); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, + [ifaceArg.astNode, typeField.astNode], + ); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if (!(0, _typeComparators.isEqualType)(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${(0, _inspect.inspect)(ifaceArg.type)} but ` + + `${type.name}.${fieldName}(${argName}:) is type ` + + `${(0, _inspect.inspect)(typeArg.type)}.`, + [ + (_ifaceArg$astNode = ifaceArg.astNode) === null || + _ifaceArg$astNode === void 0 + ? void 0 + : _ifaceArg$astNode.type, + (_typeArg$astNode = typeArg.astNode) === null || + _typeArg$astNode === void 0 + ? void 0 + : _typeArg$astNode.type, + ], + ); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find((arg) => arg.name === argName); + + if (!ifaceArg && (0, _definition.isRequiredArgument)(typeArg)) { + context.reportError( + `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, + [typeArg.astNode, ifaceField.astNode], + ); + } + } + } +} + +function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError( + transitive === type + ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` + : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, + [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface), + ], + ); + } + } +} + +function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + [union.astNode, ...union.extensionASTNodes], + ); + } + + const includedTypeNames = Object.create(null); + + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!(0, _definition.isObjectType)(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${(0, _inspect.inspect)(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + [enumType.astNode, ...enumType.extensionASTNodes], + ); + } + + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } +} + +function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + [inputObj.astNode, ...inputObj.extensionASTNodes], + ); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!(0, _definition.isInputType)(field.type)) { + var _field$astNode2; + + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${(0, _inspect.inspect)(field.type)}.`, + (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 + ? void 0 + : _field$astNode2.type, + ); + } + + if ( + (0, _definition.isRequiredInputField)(field) && + field.deprecationReason != null + ) { + var _field$astNode3; + + context.reportError( + `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(field.astNode), + (_field$astNode3 = field.astNode) === null || + _field$astNode3 === void 0 + ? void 0 + : _field$astNode3.type, + ], + ); + } + + if (inputObj.isOneOf) { + validateOneOfInputObjectField(inputObj, field, context); + } + } +} + +function validateOneOfInputObjectField(type, field, context) { + if ((0, _definition.isNonNullType)(field.type)) { + var _field$astNode4; + + context.reportError( + `OneOf input field ${type.name}.${field.name} must be nullable.`, + (_field$astNode4 = field.astNode) === null || _field$astNode4 === void 0 + ? void 0 + : _field$astNode4.type, + ); + } + + if (field.defaultValue !== undefined) { + context.reportError( + `OneOf input field ${type.name}.${field.name} cannot have a default value.`, + field.astNode, + ); + } +} + +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + + for (const field of fields) { + if ( + (0, _definition.isNonNullType)(field.type) && + (0, _definition.isInputObjectType)(field.type.ofType) + ) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.'); + context.reportError( + `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, + cyclePath.map((fieldObj) => fieldObj.astNode), + ); + } + + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +function getAllImplementsInterfaceNodes(type, iface) { + const { astNode, extensionASTNodes } = type; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((typeNode) => { + var _typeNode$interfaces; + + return ( + /* c8 ignore next */ + (_typeNode$interfaces = typeNode.interfaces) !== null && + _typeNode$interfaces !== void 0 + ? _typeNode$interfaces + : [] + ); + }) + .filter((ifaceNode) => ifaceNode.name.value === iface.name); +} + +function getUnionMemberTypeNodes(union, typeName) { + const { astNode, extensionASTNodes } = union; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((unionNode) => { + var _unionNode$types; + + return ( + /* c8 ignore next */ + (_unionNode$types = unionNode.types) !== null && + _unionNode$types !== void 0 + ? _unionNode$types + : [] + ); + }) + .filter((typeNode) => typeNode.name.value === typeName); +} + +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + + return definitionNode === null || definitionNode === void 0 + ? void 0 + : (_definitionNode$direc = definitionNode.directives) === null || + _definitionNode$direc === void 0 + ? void 0 + : _definitionNode$direc.find( + (node) => + node.name.value === _directives.GraphQLDeprecatedDirective.name, + ); +} diff --git a/node_modules/graphql/type/validate.mjs b/node_modules/graphql/type/validate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..686d984ffeaf8ae81cbdbfc7319d4fa2e3f3b3c0 --- /dev/null +++ b/node_modules/graphql/type/validate.mjs @@ -0,0 +1,712 @@ +/** @category Validation */ +import { inspect } from '../jsutils/inspect.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { OperationTypeNode } from '../language/ast.mjs'; +import { isEqualType, isTypeSubTypeOf } from '../utilities/typeComparators.mjs'; +import { + isEnumType, + isInputObjectType, + isInputType, + isInterfaceType, + isNamedType, + isNonNullType, + isObjectType, + isOutputType, + isRequiredArgument, + isRequiredInputField, + isUnionType, +} from './definition.mjs'; +import { GraphQLDeprecatedDirective, isDirective } from './directives.mjs'; +import { isIntrospectionType } from './introspection.mjs'; +import { assertSchema } from './schema.mjs'; +/** + * Implements the "Type Validation" sub-sections of the specification's + * "Type System" section. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the Schema is valid. + * @param schema - GraphQL schema to use. + * @returns Schema validation errors, or an empty array when the schema is valid. + * @example + * ```ts + * import { validateSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * const errors = validateSchema(schema); + * + * errors; // => [] + * ``` + */ + +export function validateSchema(schema) { + // First check to ensure the provided value is in fact a GraphQLSchema. + assertSchema(schema); // If this Schema has already been validated, return the previous results. + + if (schema.__validationErrors) { + return schema.__validationErrors; + } // Validate the schema, producing a list of errors. + + const context = new SchemaValidationContext(schema); + validateRootTypes(context); + validateDirectives(context); + validateTypes(context); // Persist the results of validation before returning to ensure validation + // does not run multiple times for this schema. + + const errors = context.getErrors(); + schema.__validationErrors = errors; + return errors; +} +/** + * Utility function which asserts a schema is valid by throwing an error if + * it is invalid. + * @param schema - GraphQL schema to use. + * @example + * ```ts + * import { assertValidSchema } from 'graphql/type'; + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * assertValidSchema(schema); // does not throw + * ``` + */ + +export function assertValidSchema(schema) { + const errors = validateSchema(schema); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} + +class SchemaValidationContext { + constructor(schema) { + this._errors = []; + this.schema = schema; + } + + reportError(message, nodes) { + const _nodes = Array.isArray(nodes) ? nodes.filter(Boolean) : nodes; + + this._errors.push( + new GraphQLError(message, { + nodes: _nodes, + }), + ); + } + + getErrors() { + return this._errors; + } +} + +function validateRootTypes(context) { + const schema = context.schema; + const queryType = schema.getQueryType(); + + if (!queryType) { + context.reportError('Query root type must be provided.', schema.astNode); + } else if (!isObjectType(queryType)) { + var _getOperationTypeNode; + + context.reportError( + `Query root type must be Object type, it cannot be ${inspect( + queryType, + )}.`, + (_getOperationTypeNode = getOperationTypeNode( + schema, + OperationTypeNode.QUERY, + )) !== null && _getOperationTypeNode !== void 0 + ? _getOperationTypeNode + : queryType.astNode, + ); + } + + const mutationType = schema.getMutationType(); + + if (mutationType && !isObjectType(mutationType)) { + var _getOperationTypeNode2; + + context.reportError( + 'Mutation root type must be Object type if provided, it cannot be ' + + `${inspect(mutationType)}.`, + (_getOperationTypeNode2 = getOperationTypeNode( + schema, + OperationTypeNode.MUTATION, + )) !== null && _getOperationTypeNode2 !== void 0 + ? _getOperationTypeNode2 + : mutationType.astNode, + ); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && !isObjectType(subscriptionType)) { + var _getOperationTypeNode3; + + context.reportError( + 'Subscription root type must be Object type if provided, it cannot be ' + + `${inspect(subscriptionType)}.`, + (_getOperationTypeNode3 = getOperationTypeNode( + schema, + OperationTypeNode.SUBSCRIPTION, + )) !== null && _getOperationTypeNode3 !== void 0 + ? _getOperationTypeNode3 + : subscriptionType.astNode, + ); + } +} + +function getOperationTypeNode(schema, operation) { + var _flatMap$find; + + return (_flatMap$find = [schema.astNode, ...schema.extensionASTNodes] + .flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (schemaNode) => { + var _schemaNode$operation; + + return ( + /* c8 ignore next */ + (_schemaNode$operation = + schemaNode === null || schemaNode === void 0 + ? void 0 + : schemaNode.operationTypes) !== null && + _schemaNode$operation !== void 0 + ? _schemaNode$operation + : [] + ); + }, + ) + .find((operationNode) => operationNode.operation === operation)) === null || + _flatMap$find === void 0 + ? void 0 + : _flatMap$find.type; +} + +function validateDirectives(context) { + for (const directive of context.schema.getDirectives()) { + // Ensure all directives are in fact GraphQL directives. + if (!isDirective(directive)) { + context.reportError( + `Expected directive but got: ${inspect(directive)}.`, + directive === null || directive === void 0 ? void 0 : directive.astNode, + ); + continue; + } // Ensure they are named correctly. + + validateName(context, directive); + + if (directive.locations.length === 0) { + context.reportError( + `Directive @${directive.name} must include 1 or more locations.`, + directive.astNode, + ); + } // Ensure the arguments are valid. + + for (const arg of directive.args) { + // Ensure they are named correctly. + validateName(context, arg); // Ensure the type is an input type. + + if (!isInputType(arg.type)) { + context.reportError( + `The type of @${directive.name}(${arg.name}:) must be Input Type ` + + `but got: ${inspect(arg.type)}.`, + arg.astNode, + ); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + var _arg$astNode; + + context.reportError( + `Required argument @${directive.name}(${arg.name}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode = arg.astNode) === null || _arg$astNode === void 0 + ? void 0 + : _arg$astNode.type, + ], + ); + } + } + } +} + +function validateName(context, node) { + // Ensure names are valid, however introspection types opt out. + if (node.name.startsWith('__')) { + context.reportError( + `Name "${node.name}" must not begin with "__", which is reserved by GraphQL introspection.`, + node.astNode, + ); + } +} + +function validateTypes(context) { + const validateInputObjectCircularRefs = + createInputObjectCircularRefsValidator(context); + const typeMap = context.schema.getTypeMap(); + + for (const type of Object.values(typeMap)) { + // Ensure all provided types are in fact GraphQL type. + if (!isNamedType(type)) { + context.reportError( + `Expected GraphQL named type but got: ${inspect(type)}.`, + type.astNode, + ); + continue; + } // Ensure it is named correctly (excluding introspection types). + + if (!isIntrospectionType(type)) { + validateName(context, type); + } + + if (isObjectType(type)) { + // Ensure fields are valid + validateFields(context, type); // Ensure objects implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if (isInterfaceType(type)) { + // Ensure fields are valid. + validateFields(context, type); // Ensure interfaces implement the interfaces they claim to. + + validateInterfaces(context, type); + } else if (isUnionType(type)) { + // Ensure Unions include valid member types. + validateUnionMembers(context, type); + } else if (isEnumType(type)) { + // Ensure Enums have valid values. + validateEnumValues(context, type); + } else if (isInputObjectType(type)) { + // Ensure Input Object fields are valid. + validateInputFields(context, type); // Ensure Input Objects do not contain non-nullable circular references + + validateInputObjectCircularRefs(type); + } + } +} + +function validateFields(context, type) { + const fields = Object.values(type.getFields()); // Objects and Interfaces both must define one or more fields. + + if (fields.length === 0) { + context.reportError(`Type ${type.name} must define one or more fields.`, [ + type.astNode, + ...type.extensionASTNodes, + ]); + } + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an output type + + if (!isOutputType(field.type)) { + var _field$astNode; + + context.reportError( + `The type of ${type.name}.${field.name} must be Output Type ` + + `but got: ${inspect(field.type)}.`, + (_field$astNode = field.astNode) === null || _field$astNode === void 0 + ? void 0 + : _field$astNode.type, + ); + } // Ensure the arguments are valid + + for (const arg of field.args) { + const argName = arg.name; // Ensure they are named correctly. + + validateName(context, arg); // Ensure the type is an input type + + if (!isInputType(arg.type)) { + var _arg$astNode2; + + context.reportError( + `The type of ${type.name}.${field.name}(${argName}:) must be Input ` + + `Type but got: ${inspect(arg.type)}.`, + (_arg$astNode2 = arg.astNode) === null || _arg$astNode2 === void 0 + ? void 0 + : _arg$astNode2.type, + ); + } + + if (isRequiredArgument(arg) && arg.deprecationReason != null) { + var _arg$astNode3; + + context.reportError( + `Required argument ${type.name}.${field.name}(${argName}:) cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(arg.astNode), + (_arg$astNode3 = arg.astNode) === null || _arg$astNode3 === void 0 + ? void 0 + : _arg$astNode3.type, + ], + ); + } + } + } +} + +function validateInterfaces(context, type) { + const ifaceTypeNames = Object.create(null); + + for (const iface of type.getInterfaces()) { + if (!isInterfaceType(iface)) { + context.reportError( + `Type ${inspect(type)} must only implement Interface types, ` + + `it cannot implement ${inspect(iface)}.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (type === iface) { + context.reportError( + `Type ${type.name} cannot implement itself because it would create a circular reference.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + if (ifaceTypeNames[iface.name]) { + context.reportError( + `Type ${type.name} can only implement ${iface.name} once.`, + getAllImplementsInterfaceNodes(type, iface), + ); + continue; + } + + ifaceTypeNames[iface.name] = true; + validateTypeImplementsAncestors(context, type, iface); + validateTypeImplementsInterface(context, type, iface); + } +} + +function validateTypeImplementsInterface(context, type, iface) { + const typeFieldMap = type.getFields(); // Assert each interface field is implemented. + + for (const ifaceField of Object.values(iface.getFields())) { + const fieldName = ifaceField.name; + const typeField = typeFieldMap[fieldName]; // Assert interface field exists on type. + + if (!typeField) { + context.reportError( + `Interface field ${iface.name}.${fieldName} expected but ${type.name} does not provide it.`, + [ifaceField.astNode, type.astNode, ...type.extensionASTNodes], + ); + continue; + } // Assert interface field type is satisfied by type field type, by being + // a valid subtype. (covariant) + + if (!isTypeSubTypeOf(context.schema, typeField.type, ifaceField.type)) { + var _ifaceField$astNode, _typeField$astNode; + + context.reportError( + `Interface field ${iface.name}.${fieldName} expects type ` + + `${inspect(ifaceField.type)} but ${type.name}.${fieldName} ` + + `is type ${inspect(typeField.type)}.`, + [ + (_ifaceField$astNode = ifaceField.astNode) === null || + _ifaceField$astNode === void 0 + ? void 0 + : _ifaceField$astNode.type, + (_typeField$astNode = typeField.astNode) === null || + _typeField$astNode === void 0 + ? void 0 + : _typeField$astNode.type, + ], + ); + } // Assert each interface field arg is implemented. + + for (const ifaceArg of ifaceField.args) { + const argName = ifaceArg.name; + const typeArg = typeField.args.find((arg) => arg.name === argName); // Assert interface field arg exists on object field. + + if (!typeArg) { + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) expected but ${type.name}.${fieldName} does not provide it.`, + [ifaceArg.astNode, typeField.astNode], + ); + continue; + } // Assert interface field arg type matches object field arg type. + // (invariant) + // TODO: change to contravariant? + + if (!isEqualType(ifaceArg.type, typeArg.type)) { + var _ifaceArg$astNode, _typeArg$astNode; + + context.reportError( + `Interface field argument ${iface.name}.${fieldName}(${argName}:) ` + + `expects type ${inspect(ifaceArg.type)} but ` + + `${type.name}.${fieldName}(${argName}:) is type ` + + `${inspect(typeArg.type)}.`, + [ + (_ifaceArg$astNode = ifaceArg.astNode) === null || + _ifaceArg$astNode === void 0 + ? void 0 + : _ifaceArg$astNode.type, + (_typeArg$astNode = typeArg.astNode) === null || + _typeArg$astNode === void 0 + ? void 0 + : _typeArg$astNode.type, + ], + ); + } // TODO: validate default values? + } // Assert additional arguments must not be required. + + for (const typeArg of typeField.args) { + const argName = typeArg.name; + const ifaceArg = ifaceField.args.find((arg) => arg.name === argName); + + if (!ifaceArg && isRequiredArgument(typeArg)) { + context.reportError( + `Object field ${type.name}.${fieldName} includes required argument ${argName} that is missing from the Interface field ${iface.name}.${fieldName}.`, + [typeArg.astNode, ifaceField.astNode], + ); + } + } + } +} + +function validateTypeImplementsAncestors(context, type, iface) { + const ifaceInterfaces = type.getInterfaces(); + + for (const transitive of iface.getInterfaces()) { + if (!ifaceInterfaces.includes(transitive)) { + context.reportError( + transitive === type + ? `Type ${type.name} cannot implement ${iface.name} because it would create a circular reference.` + : `Type ${type.name} must implement ${transitive.name} because it is implemented by ${iface.name}.`, + [ + ...getAllImplementsInterfaceNodes(iface, transitive), + ...getAllImplementsInterfaceNodes(type, iface), + ], + ); + } + } +} + +function validateUnionMembers(context, union) { + const memberTypes = union.getTypes(); + + if (memberTypes.length === 0) { + context.reportError( + `Union type ${union.name} must define one or more member types.`, + [union.astNode, ...union.extensionASTNodes], + ); + } + + const includedTypeNames = Object.create(null); + + for (const memberType of memberTypes) { + if (includedTypeNames[memberType.name]) { + context.reportError( + `Union type ${union.name} can only include type ${memberType.name} once.`, + getUnionMemberTypeNodes(union, memberType.name), + ); + continue; + } + + includedTypeNames[memberType.name] = true; + + if (!isObjectType(memberType)) { + context.reportError( + `Union type ${union.name} can only include Object types, ` + + `it cannot include ${inspect(memberType)}.`, + getUnionMemberTypeNodes(union, String(memberType)), + ); + } + } +} + +function validateEnumValues(context, enumType) { + const enumValues = enumType.getValues(); + + if (enumValues.length === 0) { + context.reportError( + `Enum type ${enumType.name} must define one or more values.`, + [enumType.astNode, ...enumType.extensionASTNodes], + ); + } + + for (const enumValue of enumValues) { + // Ensure valid name. + validateName(context, enumValue); + } +} + +function validateInputFields(context, inputObj) { + const fields = Object.values(inputObj.getFields()); + + if (fields.length === 0) { + context.reportError( + `Input Object type ${inputObj.name} must define one or more fields.`, + [inputObj.astNode, ...inputObj.extensionASTNodes], + ); + } // Ensure the arguments are valid + + for (const field of fields) { + // Ensure they are named correctly. + validateName(context, field); // Ensure the type is an input type + + if (!isInputType(field.type)) { + var _field$astNode2; + + context.reportError( + `The type of ${inputObj.name}.${field.name} must be Input Type ` + + `but got: ${inspect(field.type)}.`, + (_field$astNode2 = field.astNode) === null || _field$astNode2 === void 0 + ? void 0 + : _field$astNode2.type, + ); + } + + if (isRequiredInputField(field) && field.deprecationReason != null) { + var _field$astNode3; + + context.reportError( + `Required input field ${inputObj.name}.${field.name} cannot be deprecated.`, + [ + getDeprecatedDirectiveNode(field.astNode), + (_field$astNode3 = field.astNode) === null || + _field$astNode3 === void 0 + ? void 0 + : _field$astNode3.type, + ], + ); + } + + if (inputObj.isOneOf) { + validateOneOfInputObjectField(inputObj, field, context); + } + } +} + +function validateOneOfInputObjectField(type, field, context) { + if (isNonNullType(field.type)) { + var _field$astNode4; + + context.reportError( + `OneOf input field ${type.name}.${field.name} must be nullable.`, + (_field$astNode4 = field.astNode) === null || _field$astNode4 === void 0 + ? void 0 + : _field$astNode4.type, + ); + } + + if (field.defaultValue !== undefined) { + context.reportError( + `OneOf input field ${type.name}.${field.name} cannot have a default value.`, + field.astNode, + ); + } +} + +function createInputObjectCircularRefsValidator(context) { + // Modified copy of algorithm from 'src/validation/rules/NoFragmentCycles.js'. + // Tracks already visited types to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedTypes = Object.create(null); // Array of types nodes used to produce meaningful errors + + const fieldPath = []; // Position in the type path + + const fieldPathIndexByTypeName = Object.create(null); + return detectCycleRecursive; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(inputObj) { + if (visitedTypes[inputObj.name]) { + return; + } + + visitedTypes[inputObj.name] = true; + fieldPathIndexByTypeName[inputObj.name] = fieldPath.length; + const fields = Object.values(inputObj.getFields()); + + for (const field of fields) { + if (isNonNullType(field.type) && isInputObjectType(field.type.ofType)) { + const fieldType = field.type.ofType; + const cycleIndex = fieldPathIndexByTypeName[fieldType.name]; + fieldPath.push(field); + + if (cycleIndex === undefined) { + detectCycleRecursive(fieldType); + } else { + const cyclePath = fieldPath.slice(cycleIndex); + const pathStr = cyclePath.map((fieldObj) => fieldObj.name).join('.'); + context.reportError( + `Cannot reference Input Object "${fieldType.name}" within itself through a series of non-null fields: "${pathStr}".`, + cyclePath.map((fieldObj) => fieldObj.astNode), + ); + } + + fieldPath.pop(); + } + } + + fieldPathIndexByTypeName[inputObj.name] = undefined; + } +} + +function getAllImplementsInterfaceNodes(type, iface) { + const { astNode, extensionASTNodes } = type; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((typeNode) => { + var _typeNode$interfaces; + + return ( + /* c8 ignore next */ + (_typeNode$interfaces = typeNode.interfaces) !== null && + _typeNode$interfaces !== void 0 + ? _typeNode$interfaces + : [] + ); + }) + .filter((ifaceNode) => ifaceNode.name.value === iface.name); +} + +function getUnionMemberTypeNodes(union, typeName) { + const { astNode, extensionASTNodes } = union; + const nodes = + astNode != null ? [astNode, ...extensionASTNodes] : extensionASTNodes; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + return nodes + .flatMap((unionNode) => { + var _unionNode$types; + + return ( + /* c8 ignore next */ + (_unionNode$types = unionNode.types) !== null && + _unionNode$types !== void 0 + ? _unionNode$types + : [] + ); + }) + .filter((typeNode) => typeNode.name.value === typeName); +} + +function getDeprecatedDirectiveNode(definitionNode) { + var _definitionNode$direc; + + return definitionNode === null || definitionNode === void 0 + ? void 0 + : (_definitionNode$direc = definitionNode.directives) === null || + _definitionNode$direc === void 0 + ? void 0 + : _definitionNode$direc.find( + (node) => node.name.value === GraphQLDeprecatedDirective.name, + ); +} diff --git a/node_modules/graphql/utilities/TypeInfo.d.ts b/node_modules/graphql/utilities/TypeInfo.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..725b2301c09f235c118e4ab8079cf4f601a2562b --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.d.ts @@ -0,0 +1,507 @@ +/** @category Type Info */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ASTNode, FieldNode } from '../language/ast'; +import type { ASTVisitor } from '../language/visitor'; +import type { + GraphQLArgument, + GraphQLCompositeType, + GraphQLEnumValue, + GraphQLField, + GraphQLInputType, + GraphQLOutputType, + GraphQLType, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +export declare class TypeInfo { + private _schema; + private _typeStack; + private _parentTypeStack; + private _inputTypeStack; + private _fieldDefStack; + private _defaultValueStack; + private _directive; + private _argument; + private _enumValue; + private _getFieldDef; + /** + * Creates a TypeInfo instance. + * @param schema - Schema used for type lookups. + * @param initialType - Optional type to use at the start of traversal. + * @param getFieldDefFn - Optional field definition lookup override. + * @example + * ```ts + * // Track field types during a visitWithTypeInfo traversal. + * import { parse, visit } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const seenTypes = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * seenTypes.push(String(typeInfo.getType())); + * }, + * }), + * ); + * + * seenTypes; // => ['String'] + * ``` + * @example + * ```ts + * // This variant starts from an initial type and supplies a field definition resolver. + * import { Kind } from 'graphql/language'; + * import { GraphQLString } from 'graphql/type'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema, schema.getQueryType(), () => ({ + * name: 'virtualGreeting', + * description: undefined, + * type: GraphQLString, + * args: [], + * resolve: undefined, + * subscribe: undefined, + * deprecationReason: undefined, + * extensions: Object.create(null), + * astNode: undefined, + * })); + * + * typeInfo.enter({ + * kind: Kind.SELECTION_SET, + * selections: [], + * }); + * typeInfo.enter({ + * kind: Kind.FIELD, + * name: { kind: Kind.NAME, value: 'ignored' }, + * }); + * + * typeInfo.getFieldDef()?.name; // => 'virtualGreeting' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + constructor( + schema: GraphQLSchema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType?: Maybe, + /** + * Deprecated field definition lookup override. Use TypeInfo's built-in + * field definition lookup instead because this hook will be removed in v17. + * @deprecated will be removed in 17.0.0 + */ + getFieldDefFn?: GetFieldDefFn, + ); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fieldTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fieldTypes[node.name.value] = String(typeInfo.getType()); + * }, + * }), + * ); + * + * fieldTypes; // => { viewer: 'User', name: 'String' } + * ``` + */ + getType(): Maybe; + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * parentTypes[node.name.value] = String(typeInfo.getParentType()); + * }, + * }), + * ); + * + * parentTypes; // => { viewer: 'Query', name: 'User' } + * ``` + */ + getParentType(): Maybe; + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, sort: Sort = NEWEST): [String] + * } + * + * enum Sort { + * NEWEST + * OLDEST + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const inputTypes = {}; + * + * visit( + * parse('{ reviews(stars: 5, sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: (node) => { + * inputTypes[node.name.value] = String(typeInfo.getInputType()); + * }, + * }), + * ); + * + * inputTypes; // => { stars: 'Int!', sort: 'Sort' } + * ``` + */ + getInputType(): Maybe; + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentInputTypes = {}; + * + * visit( + * parse('{ reviews(filter: { stars: 5 }) }'), + * visitWithTypeInfo(typeInfo, { + * ObjectField: (node) => { + * parentInputTypes[node.name.value] = String(typeInfo.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypes; // => { stars: 'ReviewFilter' } + * ``` + */ + getParentInputType(): Maybe; + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let fieldName; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = typeInfo.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + getFieldDef(): Maybe>; + /** + * Returns the default value for the current input position. + * @returns The current default value, if one is available. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let defaultLimit; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * defaultLimit = typeInfo.getDefaultValue(); + * }, + * }), + * ); + * + * defaultLimit; // => 10 + * ``` + */ + getDefaultValue(): Maybe; + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let directiveName; + * + * visit( + * parse('{ greeting @include(if: true) }'), + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = typeInfo.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + getDirective(): Maybe; + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let argumentName; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = typeInfo.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + getArgument(): Maybe; + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort = NEWEST): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let enumValueName; + * + * visit( + * parse('{ reviews(sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = typeInfo.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + getEnumValue(): Maybe; + /** + * Updates this TypeInfo instance for an entered AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * + * field.kind; // => Kind.FIELD + * typeInfo.getParentType()?.name; // => 'Query' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + enter(node: ASTNode): void; + /** + * Updates this TypeInfo instance for a left AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * String(typeInfo.getType()); // => 'String' + * + * typeInfo.leave(field); + * typeInfo.getType(); // => undefined + * ``` + */ + leave(node: ASTNode): void; +} +declare type GetFieldDefFn = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +) => Maybe>; +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + * @param typeInfo - TypeInfo instance to update during traversal. + * @param visitor - Visitor callbacks to wrap with TypeInfo updates. + * @returns A visitor that keeps TypeInfo in sync while delegating callbacks. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fields = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fields.push({ + * name: node.name.value, + * parentType: String(typeInfo.getParentType()), + * type: String(typeInfo.getType()), + * }); + * }, + * }), + * ); + * + * fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] + * ``` + */ +export declare function visitWithTypeInfo( + typeInfo: TypeInfo, + visitor: ASTVisitor, +): ASTVisitor; +export {}; diff --git a/node_modules/graphql/utilities/TypeInfo.js b/node_modules/graphql/utilities/TypeInfo.js new file mode 100644 index 0000000000000000000000000000000000000000..88e60c845e03295f116fab81ca9ed71b76a45d25 --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.js @@ -0,0 +1,861 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.TypeInfo = void 0; +exports.visitWithTypeInfo = visitWithTypeInfo; + +var _ast = require('../language/ast.js'); + +var _kinds = require('../language/kinds.js'); + +var _visitor = require('../language/visitor.js'); + +var _definition = require('../type/definition.js'); + +var _introspection = require('../type/introspection.js'); + +var _typeFromAST = require('./typeFromAST.js'); + +/** @category Type Info */ + +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ +class TypeInfo { + /** + * Creates a TypeInfo instance. + * @param schema - Schema used for type lookups. + * @param initialType - Optional type to use at the start of traversal. + * @param getFieldDefFn - Optional field definition lookup override. + * @example + * ```ts + * // Track field types during a visitWithTypeInfo traversal. + * import { parse, visit } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const seenTypes = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * seenTypes.push(String(typeInfo.getType())); + * }, + * }), + * ); + * + * seenTypes; // => ['String'] + * ``` + * @example + * ```ts + * // This variant starts from an initial type and supplies a field definition resolver. + * import { Kind } from 'graphql/language'; + * import { GraphQLString } from 'graphql/type'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema, schema.getQueryType(), () => ({ + * name: 'virtualGreeting', + * description: undefined, + * type: GraphQLString, + * args: [], + * resolve: undefined, + * subscribe: undefined, + * deprecationReason: undefined, + * extensions: Object.create(null), + * astNode: undefined, + * })); + * + * typeInfo.enter({ + * kind: Kind.SELECTION_SET, + * selections: [], + * }); + * typeInfo.enter({ + * kind: Kind.FIELD, + * name: { kind: Kind.NAME, value: 'ignored' }, + * }); + * + * typeInfo.getFieldDef()?.name; // => 'virtualGreeting' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + constructor( + schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType, + /** + * Deprecated field definition lookup override. Use TypeInfo's built-in + * field definition lookup instead because this hook will be removed in v17. + * @deprecated will be removed in 17.0.0 + */ + getFieldDefFn, + ) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = + getFieldDefFn !== null && getFieldDefFn !== void 0 + ? getFieldDefFn + : getFieldDef; + + if (initialType) { + if ((0, _definition.isInputType)(initialType)) { + this._inputTypeStack.push(initialType); + } + + if ((0, _definition.isCompositeType)(initialType)) { + this._parentTypeStack.push(initialType); + } + + if ((0, _definition.isOutputType)(initialType)) { + this._typeStack.push(initialType); + } + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'TypeInfo'; + } + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fieldTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fieldTypes[node.name.value] = String(typeInfo.getType()); + * }, + * }), + * ); + * + * fieldTypes; // => { viewer: 'User', name: 'String' } + * ``` + */ + + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * parentTypes[node.name.value] = String(typeInfo.getParentType()); + * }, + * }), + * ); + * + * parentTypes; // => { viewer: 'Query', name: 'User' } + * ``` + */ + + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, sort: Sort = NEWEST): [String] + * } + * + * enum Sort { + * NEWEST + * OLDEST + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const inputTypes = {}; + * + * visit( + * parse('{ reviews(stars: 5, sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: (node) => { + * inputTypes[node.name.value] = String(typeInfo.getInputType()); + * }, + * }), + * ); + * + * inputTypes; // => { stars: 'Int!', sort: 'Sort' } + * ``` + */ + + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentInputTypes = {}; + * + * visit( + * parse('{ reviews(filter: { stars: 5 }) }'), + * visitWithTypeInfo(typeInfo, { + * ObjectField: (node) => { + * parentInputTypes[node.name.value] = String(typeInfo.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypes; // => { stars: 'ReviewFilter' } + * ``` + */ + + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let fieldName; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = typeInfo.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + /** + * Returns the default value for the current input position. + * @returns The current default value, if one is available. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let defaultLimit; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * defaultLimit = typeInfo.getDefaultValue(); + * }, + * }), + * ); + * + * defaultLimit; // => 10 + * ``` + */ + + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let directiveName; + * + * visit( + * parse('{ greeting @include(if: true) }'), + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = typeInfo.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + + getDirective() { + return this._directive; + } + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let argumentName; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = typeInfo.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + + getArgument() { + return this._argument; + } + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort = NEWEST): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let enumValueName; + * + * visit( + * parse('{ reviews(sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = typeInfo.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + + getEnumValue() { + return this._enumValue; + } + /** + * Updates this TypeInfo instance for an entered AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * + * field.kind; // => Kind.FIELD + * typeInfo.getParentType()?.name; // => 'Query' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: { + const namedType = (0, _definition.getNamedType)(this.getType()); + + this._parentTypeStack.push( + (0, _definition.isCompositeType)(namedType) ? namedType : undefined, + ); + + break; + } + + case _kinds.Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push( + (0, _definition.isOutputType)(fieldType) ? fieldType : undefined, + ); + + break; + } + + case _kinds.Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case _kinds.Kind.OPERATION_DEFINITION: { + const rootType = schema.getRootType(node.operation); + + this._typeStack.push( + (0, _definition.isObjectType)(rootType) ? rootType : undefined, + ); + + break; + } + + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST + ? (0, _typeFromAST.typeFromAST)(schema, typeConditionAST) + : (0, _definition.getNamedType)(this.getType()); + + this._typeStack.push( + (0, _definition.isOutputType)(outputType) ? outputType : undefined, + ); + + break; + } + + case _kinds.Kind.VARIABLE_DEFINITION: { + const inputType = (0, _typeFromAST.typeFromAST)(schema, node.type); + + this._inputTypeStack.push( + (0, _definition.isInputType)(inputType) ? inputType : undefined, + ); + + break; + } + + case _kinds.Kind.ARGUMENT: { + var _this$getDirective; + + let argDef; + let argType; + const fieldOrDirective = + (_this$getDirective = this.getDirective()) !== null && + _this$getDirective !== void 0 + ? _this$getDirective + : this.getFieldDef(); + + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find( + (arg) => arg.name === node.name.value, + ); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push( + (0, _definition.isInputType)(argType) ? argType : undefined, + ); + + break; + } + + case _kinds.Kind.LIST: { + const listType = (0, _definition.getNullableType)(this.getInputType()); + const itemType = (0, _definition.isListType)(listType) + ? listType.ofType + : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push( + (0, _definition.isInputType)(itemType) ? itemType : undefined, + ); + + break; + } + + case _kinds.Kind.OBJECT_FIELD: { + const objectType = (0, _definition.getNamedType)(this.getInputType()); + let inputFieldType; + let inputField; + + if ((0, _definition.isInputObjectType)(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined, + ); + + this._inputTypeStack.push( + (0, _definition.isInputType)(inputFieldType) + ? inputFieldType + : undefined, + ); + + break; + } + + case _kinds.Kind.ENUM: { + const enumType = (0, _definition.getNamedType)(this.getInputType()); + let enumValue; + + if ((0, _definition.isEnumType)(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + + default: // Ignore other nodes + } + } + /** + * Updates this TypeInfo instance for a left AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * String(typeInfo.getType()); // => 'String' + * + * typeInfo.leave(field); + * typeInfo.getType(); // => undefined + * ``` + */ + + leave(node) { + switch (node.kind) { + case _kinds.Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case _kinds.Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case _kinds.Kind.DIRECTIVE: + this._directive = null; + break; + + case _kinds.Kind.OPERATION_DEFINITION: + case _kinds.Kind.INLINE_FRAGMENT: + case _kinds.Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case _kinds.Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.LIST: + case _kinds.Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case _kinds.Kind.ENUM: + this._enumValue = null; + break; + + default: // Ignore other nodes + } + } +} + +exports.TypeInfo = TypeInfo; + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + * + * @internal + */ +function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + + if ( + name === _introspection.SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.SchemaMetaFieldDef; + } + + if ( + name === _introspection.TypeMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return _introspection.TypeMetaFieldDef; + } + + if ( + name === _introspection.TypeNameMetaFieldDef.name && + (0, _definition.isCompositeType)(parentType) + ) { + return _introspection.TypeNameMetaFieldDef; + } + + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + return parentType.getFields()[name]; + } +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + * @param typeInfo - TypeInfo instance to update during traversal. + * @param visitor - Visitor callbacks to wrap with TypeInfo updates. + * @returns A visitor that keeps TypeInfo in sync while delegating callbacks. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fields = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fields.push({ + * name: node.name.value, + * parentType: String(typeInfo.getParentType()), + * type: String(typeInfo.getType()), + * }); + * }, + * }), + * ); + * + * fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] + * ``` + */ + +function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).enter; + + if (fn) { + const result = fn.apply(visitor, args); + + if (result !== undefined) { + typeInfo.leave(node); + + if ((0, _ast.isNode)(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + + leave(...args) { + const node = args[0]; + const fn = (0, _visitor.getEnterLeaveForKind)(visitor, node.kind).leave; + let result; + + if (fn) { + result = fn.apply(visitor, args); + } + + typeInfo.leave(node); + return result; + }, + }; +} diff --git a/node_modules/graphql/utilities/TypeInfo.mjs b/node_modules/graphql/utilities/TypeInfo.mjs new file mode 100644 index 0000000000000000000000000000000000000000..112ae418ee5ba1ec769fca2e517659a86ea5757a --- /dev/null +++ b/node_modules/graphql/utilities/TypeInfo.mjs @@ -0,0 +1,837 @@ +/** @category Type Info */ +import { isNode } from '../language/ast.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { getEnterLeaveForKind } from '../language/visitor.mjs'; +import { + getNamedType, + getNullableType, + isCompositeType, + isEnumType, + isInputObjectType, + isInputType, + isInterfaceType, + isListType, + isObjectType, + isOutputType, +} from '../type/definition.mjs'; +import { + SchemaMetaFieldDef, + TypeMetaFieldDef, + TypeNameMetaFieldDef, +} from '../type/introspection.mjs'; +import { typeFromAST } from './typeFromAST.mjs'; +/** + * TypeInfo is a utility class which, given a GraphQL schema, can keep track + * of the current field and type definitions at any point in a GraphQL document + * AST during a recursive descent by calling `enter(node)` and `leave(node)`. + */ + +export class TypeInfo { + /** + * Creates a TypeInfo instance. + * @param schema - Schema used for type lookups. + * @param initialType - Optional type to use at the start of traversal. + * @param getFieldDefFn - Optional field definition lookup override. + * @example + * ```ts + * // Track field types during a visitWithTypeInfo traversal. + * import { parse, visit } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const seenTypes = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * seenTypes.push(String(typeInfo.getType())); + * }, + * }), + * ); + * + * seenTypes; // => ['String'] + * ``` + * @example + * ```ts + * // This variant starts from an initial type and supplies a field definition resolver. + * import { Kind } from 'graphql/language'; + * import { GraphQLString } from 'graphql/type'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema, schema.getQueryType(), () => ({ + * name: 'virtualGreeting', + * description: undefined, + * type: GraphQLString, + * args: [], + * resolve: undefined, + * subscribe: undefined, + * deprecationReason: undefined, + * extensions: Object.create(null), + * astNode: undefined, + * })); + * + * typeInfo.enter({ + * kind: Kind.SELECTION_SET, + * selections: [], + * }); + * typeInfo.enter({ + * kind: Kind.FIELD, + * name: { kind: Kind.NAME, value: 'ignored' }, + * }); + * + * typeInfo.getFieldDef()?.name; // => 'virtualGreeting' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + constructor( + schema, + /** + * Initial type may be provided in rare cases to facilitate traversals + * beginning somewhere other than documents. + */ + initialType, + /** + * Deprecated field definition lookup override. Use TypeInfo's built-in + * field definition lookup instead because this hook will be removed in v17. + * @deprecated will be removed in 17.0.0 + */ + getFieldDefFn, + ) { + this._schema = schema; + this._typeStack = []; + this._parentTypeStack = []; + this._inputTypeStack = []; + this._fieldDefStack = []; + this._defaultValueStack = []; + this._directive = null; + this._argument = null; + this._enumValue = null; + this._getFieldDef = + getFieldDefFn !== null && getFieldDefFn !== void 0 + ? getFieldDefFn + : getFieldDef; + + if (initialType) { + if (isInputType(initialType)) { + this._inputTypeStack.push(initialType); + } + + if (isCompositeType(initialType)) { + this._parentTypeStack.push(initialType); + } + + if (isOutputType(initialType)) { + this._typeStack.push(initialType); + } + } + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'TypeInfo'; + } + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fieldTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fieldTypes[node.name.value] = String(typeInfo.getType()); + * }, + * }), + * ); + * + * fieldTypes; // => { viewer: 'User', name: 'String' } + * ``` + */ + + getType() { + if (this._typeStack.length > 0) { + return this._typeStack[this._typeStack.length - 1]; + } + } + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentTypes = {}; + * + * visit( + * parse('{ viewer { name } }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * parentTypes[node.name.value] = String(typeInfo.getParentType()); + * }, + * }), + * ); + * + * parentTypes; // => { viewer: 'Query', name: 'User' } + * ``` + */ + + getParentType() { + if (this._parentTypeStack.length > 0) { + return this._parentTypeStack[this._parentTypeStack.length - 1]; + } + } + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(stars: Int!, sort: Sort = NEWEST): [String] + * } + * + * enum Sort { + * NEWEST + * OLDEST + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const inputTypes = {}; + * + * visit( + * parse('{ reviews(stars: 5, sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: (node) => { + * inputTypes[node.name.value] = String(typeInfo.getInputType()); + * }, + * }), + * ); + * + * inputTypes; // => { stars: 'Int!', sort: 'Sort' } + * ``` + */ + + getInputType() { + if (this._inputTypeStack.length > 0) { + return this._inputTypeStack[this._inputTypeStack.length - 1]; + } + } + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int! + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const parentInputTypes = {}; + * + * visit( + * parse('{ reviews(filter: { stars: 5 }) }'), + * visitWithTypeInfo(typeInfo, { + * ObjectField: (node) => { + * parentInputTypes[node.name.value] = String(typeInfo.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypes; // => { stars: 'ReviewFilter' } + * ``` + */ + + getParentInputType() { + if (this._inputTypeStack.length > 1) { + return this._inputTypeStack[this._inputTypeStack.length - 2]; + } + } + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let fieldName; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = typeInfo.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + + getFieldDef() { + if (this._fieldDefStack.length > 0) { + return this._fieldDefStack[this._fieldDefStack.length - 1]; + } + } + /** + * Returns the default value for the current input position. + * @returns The current default value, if one is available. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let defaultLimit; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * defaultLimit = typeInfo.getDefaultValue(); + * }, + * }), + * ); + * + * defaultLimit; // => 10 + * ``` + */ + + getDefaultValue() { + if (this._defaultValueStack.length > 0) { + return this._defaultValueStack[this._defaultValueStack.length - 1]; + } + } + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let directiveName; + * + * visit( + * parse('{ greeting @include(if: true) }'), + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = typeInfo.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + + getDirective() { + return this._directive; + } + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int = 10): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let argumentName; + * + * visit( + * parse('{ reviews(limit: 5) }'), + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = typeInfo.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + + getArgument() { + return this._argument; + } + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort = NEWEST): [String] + * } + * `); + * const typeInfo = new TypeInfo(schema); + * let enumValueName; + * + * visit( + * parse('{ reviews(sort: OLDEST) }'), + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = typeInfo.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + + getEnumValue() { + return this._enumValue; + } + /** + * Updates this TypeInfo instance for an entered AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { Kind, parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * + * field.kind; // => Kind.FIELD + * typeInfo.getParentType()?.name; // => 'Query' + * String(typeInfo.getType()); // => 'String' + * ``` + */ + + enter(node) { + const schema = this._schema; // Note: many of the types below are explicitly typed as "unknown" to drop + // any assumptions of a valid schema to ensure runtime types are properly + // checked before continuing since TypeInfo is used as part of validation + // which occurs before guarantees of schema and document validity. + + switch (node.kind) { + case Kind.SELECTION_SET: { + const namedType = getNamedType(this.getType()); + + this._parentTypeStack.push( + isCompositeType(namedType) ? namedType : undefined, + ); + + break; + } + + case Kind.FIELD: { + const parentType = this.getParentType(); + let fieldDef; + let fieldType; + + if (parentType) { + fieldDef = this._getFieldDef(schema, parentType, node); + + if (fieldDef) { + fieldType = fieldDef.type; + } + } + + this._fieldDefStack.push(fieldDef); + + this._typeStack.push(isOutputType(fieldType) ? fieldType : undefined); + + break; + } + + case Kind.DIRECTIVE: + this._directive = schema.getDirective(node.name.value); + break; + + case Kind.OPERATION_DEFINITION: { + const rootType = schema.getRootType(node.operation); + + this._typeStack.push(isObjectType(rootType) ? rootType : undefined); + + break; + } + + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: { + const typeConditionAST = node.typeCondition; + const outputType = typeConditionAST + ? typeFromAST(schema, typeConditionAST) + : getNamedType(this.getType()); + + this._typeStack.push(isOutputType(outputType) ? outputType : undefined); + + break; + } + + case Kind.VARIABLE_DEFINITION: { + const inputType = typeFromAST(schema, node.type); + + this._inputTypeStack.push( + isInputType(inputType) ? inputType : undefined, + ); + + break; + } + + case Kind.ARGUMENT: { + var _this$getDirective; + + let argDef; + let argType; + const fieldOrDirective = + (_this$getDirective = this.getDirective()) !== null && + _this$getDirective !== void 0 + ? _this$getDirective + : this.getFieldDef(); + + if (fieldOrDirective) { + argDef = fieldOrDirective.args.find( + (arg) => arg.name === node.name.value, + ); + + if (argDef) { + argType = argDef.type; + } + } + + this._argument = argDef; + + this._defaultValueStack.push(argDef ? argDef.defaultValue : undefined); + + this._inputTypeStack.push(isInputType(argType) ? argType : undefined); + + break; + } + + case Kind.LIST: { + const listType = getNullableType(this.getInputType()); + const itemType = isListType(listType) ? listType.ofType : listType; // List positions never have a default value. + + this._defaultValueStack.push(undefined); + + this._inputTypeStack.push(isInputType(itemType) ? itemType : undefined); + + break; + } + + case Kind.OBJECT_FIELD: { + const objectType = getNamedType(this.getInputType()); + let inputFieldType; + let inputField; + + if (isInputObjectType(objectType)) { + inputField = objectType.getFields()[node.name.value]; + + if (inputField) { + inputFieldType = inputField.type; + } + } + + this._defaultValueStack.push( + inputField ? inputField.defaultValue : undefined, + ); + + this._inputTypeStack.push( + isInputType(inputFieldType) ? inputFieldType : undefined, + ); + + break; + } + + case Kind.ENUM: { + const enumType = getNamedType(this.getInputType()); + let enumValue; + + if (isEnumType(enumType)) { + enumValue = enumType.getValue(node.value); + } + + this._enumValue = enumValue; + break; + } + + default: // Ignore other nodes + } + } + /** + * Updates this TypeInfo instance for a left AST node. + * @param node - AST node being entered. + * @returns Nothing. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const operation = document.definitions[0]; + * const selectionSet = operation.selectionSet; + * const field = selectionSet.selections[0]; + * const typeInfo = new TypeInfo(schema); + * + * typeInfo.enter(operation); + * typeInfo.enter(selectionSet); + * typeInfo.enter(field); + * String(typeInfo.getType()); // => 'String' + * + * typeInfo.leave(field); + * typeInfo.getType(); // => undefined + * ``` + */ + + leave(node) { + switch (node.kind) { + case Kind.SELECTION_SET: + this._parentTypeStack.pop(); + + break; + + case Kind.FIELD: + this._fieldDefStack.pop(); + + this._typeStack.pop(); + + break; + + case Kind.DIRECTIVE: + this._directive = null; + break; + + case Kind.OPERATION_DEFINITION: + case Kind.INLINE_FRAGMENT: + case Kind.FRAGMENT_DEFINITION: + this._typeStack.pop(); + + break; + + case Kind.VARIABLE_DEFINITION: + this._inputTypeStack.pop(); + + break; + + case Kind.ARGUMENT: + this._argument = null; + + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.LIST: + case Kind.OBJECT_FIELD: + this._defaultValueStack.pop(); + + this._inputTypeStack.pop(); + + break; + + case Kind.ENUM: + this._enumValue = null; + break; + + default: // Ignore other nodes + } + } +} + +/** + * Not exactly the same as the executor's definition of getFieldDef, in this + * statically evaluated environment we do not always have an Object type, + * and need to handle Interface and Union types. + * + * @internal + */ +function getFieldDef(schema, parentType, fieldNode) { + const name = fieldNode.name.value; + + if ( + name === SchemaMetaFieldDef.name && + schema.getQueryType() === parentType + ) { + return SchemaMetaFieldDef; + } + + if (name === TypeMetaFieldDef.name && schema.getQueryType() === parentType) { + return TypeMetaFieldDef; + } + + if (name === TypeNameMetaFieldDef.name && isCompositeType(parentType)) { + return TypeNameMetaFieldDef; + } + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + return parentType.getFields()[name]; + } +} +/** + * Creates a new visitor instance which maintains a provided TypeInfo instance + * along with visiting visitor. + * @param typeInfo - TypeInfo instance to update during traversal. + * @param visitor - Visitor callbacks to wrap with TypeInfo updates. + * @returns A visitor that keeps TypeInfo in sync while delegating callbacks. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const typeInfo = new TypeInfo(schema); + * const fields = []; + * + * visit( + * parse('{ greeting }'), + * visitWithTypeInfo(typeInfo, { + * Field: (node) => { + * fields.push({ + * name: node.name.value, + * parentType: String(typeInfo.getParentType()), + * type: String(typeInfo.getType()), + * }); + * }, + * }), + * ); + * + * fields; // => [{ name: 'greeting', parentType: 'Query', type: 'String' }] + * ``` + */ + +export function visitWithTypeInfo(typeInfo, visitor) { + return { + enter(...args) { + const node = args[0]; + typeInfo.enter(node); + const fn = getEnterLeaveForKind(visitor, node.kind).enter; + + if (fn) { + const result = fn.apply(visitor, args); + + if (result !== undefined) { + typeInfo.leave(node); + + if (isNode(result)) { + typeInfo.enter(result); + } + } + + return result; + } + }, + + leave(...args) { + const node = args[0]; + const fn = getEnterLeaveForKind(visitor, node.kind).leave; + let result; + + if (fn) { + result = fn.apply(visitor, args); + } + + typeInfo.leave(node); + return result; + }, + }; +} diff --git a/node_modules/graphql/utilities/assertValidName.d.ts b/node_modules/graphql/utilities/assertValidName.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4188f2903dbcb7686fbc5c9fa4c0d99fd163d9da --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.d.ts @@ -0,0 +1,38 @@ +/** @category Validation */ +import { GraphQLError } from '../error/GraphQLError'; +/** + * Upholds the spec rules about naming. This deprecated helper is retained for + * backwards compatibility; call `assertName` instead because assertValidName + * will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertValidName } from 'graphql/utilities'; + * + * assertValidName('User'); // => 'User' + * assertValidName('__typename'); // throws an error + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ +export declare function assertValidName(name: string): string; +/** + * Returns an Error if a name is invalid. This deprecated helper is retained for + * backwards compatibility; call `assertName` and catch the thrown GraphQLError + * instead because isValidNameError will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns A GraphQLError if the name is invalid; otherwise undefined. + * @example + * ```ts + * import { isValidNameError } from 'graphql/utilities'; + * + * isValidNameError('User'); // => undefined + * + * const error = isValidNameError('__typename'); + * error.message; // => 'Name "__typename" must not begin with "__", which is reserved by GraphQL introspection.' + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ +export declare function isValidNameError( + name: string, +): GraphQLError | undefined; diff --git a/node_modules/graphql/utilities/assertValidName.js b/node_modules/graphql/utilities/assertValidName.js new file mode 100644 index 0000000000000000000000000000000000000000..68dca2607e4c293c20e94a24b1cd66ff3f0b028e --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.js @@ -0,0 +1,77 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.assertValidName = assertValidName; +exports.isValidNameError = isValidNameError; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _assertName = require('../type/assertName.js'); + +/** @category Validation */ + +/* c8 ignore start */ + +/** + * Upholds the spec rules about naming. This deprecated helper is retained for + * backwards compatibility; call `assertName` instead because assertValidName + * will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertValidName } from 'graphql/utilities'; + * + * assertValidName('User'); // => 'User' + * assertValidName('__typename'); // throws an error + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ +function assertValidName(name) { + const error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. This deprecated helper is retained for + * backwards compatibility; call `assertName` and catch the thrown GraphQLError + * instead because isValidNameError will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns A GraphQLError if the name is invalid; otherwise undefined. + * @example + * ```ts + * import { isValidNameError } from 'graphql/utilities'; + * + * isValidNameError('User'); // => undefined + * + * const error = isValidNameError('__typename'); + * error.message; // => 'Name "__typename" must not begin with "__", which is reserved by GraphQL introspection.' + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + +function isValidNameError(name) { + typeof name === 'string' || + (0, _devAssert.devAssert)(false, 'Expected name to be a string.'); + + if (name.startsWith('__')) { + return new _GraphQLError.GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`, + ); + } + + try { + (0, _assertName.assertName)(name); + } catch (error) { + return error; + } +} +/* c8 ignore stop */ diff --git a/node_modules/graphql/utilities/assertValidName.mjs b/node_modules/graphql/utilities/assertValidName.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1cdfd85e43c303f276443bc8a0f5595012c35575 --- /dev/null +++ b/node_modules/graphql/utilities/assertValidName.mjs @@ -0,0 +1,65 @@ +/** @category Validation */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { assertName } from '../type/assertName.mjs'; +/* c8 ignore start */ + +/** + * Upholds the spec rules about naming. This deprecated helper is retained for + * backwards compatibility; call `assertName` instead because assertValidName + * will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns The validated GraphQL name. + * @example + * ```ts + * import { assertValidName } from 'graphql/utilities'; + * + * assertValidName('User'); // => 'User' + * assertValidName('__typename'); // throws an error + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + +export function assertValidName(name) { + const error = isValidNameError(name); + + if (error) { + throw error; + } + + return name; +} +/** + * Returns an Error if a name is invalid. This deprecated helper is retained for + * backwards compatibility; call `assertName` and catch the thrown GraphQLError + * instead because isValidNameError will be removed in v17. + * @param name - The GraphQL name to validate. + * @returns A GraphQLError if the name is invalid; otherwise undefined. + * @example + * ```ts + * import { isValidNameError } from 'graphql/utilities'; + * + * isValidNameError('User'); // => undefined + * + * const error = isValidNameError('__typename'); + * error.message; // => 'Name "__typename" must not begin with "__", which is reserved by GraphQL introspection.' + * ``` + * @deprecated Please use `assertName` instead. Will be removed in v17 + */ + +export function isValidNameError(name) { + typeof name === 'string' || devAssert(false, 'Expected name to be a string.'); + + if (name.startsWith('__')) { + return new GraphQLError( + `Name "${name}" must not begin with "__", which is reserved by GraphQL introspection.`, + ); + } + + try { + assertName(name); + } catch (error) { + return error; + } +} +/* c8 ignore stop */ diff --git a/node_modules/graphql/utilities/astFromValue.d.ts b/node_modules/graphql/utilities/astFromValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a03c50244df6e89cfdedf215cda06aa5e41f932d --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.d.ts @@ -0,0 +1,58 @@ +/** @category Values */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ValueNode } from '../language/ast'; +import type { GraphQLInputType } from '../type/definition'; +/** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * @param value - Runtime value to convert. + * @param type - The GraphQL type to inspect. + * @returns A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it. + * @example + * ```ts + * import { print } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { astFromValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * const valueNode = astFromValue( + * { stars: 5, tags: ['featured', 'verified'] }, + * ReviewInput, + * ); + * + * print(valueNode); // => '{ stars: 5, tags: ["featured", "verified"] }' + * astFromValue(undefined, GraphQLString); // => null + * astFromValue(null, new GraphQLNonNull(GraphQLString)); // => null + * ``` + */ +export declare function astFromValue( + value: unknown, + type: GraphQLInputType, +): Maybe; diff --git a/node_modules/graphql/utilities/astFromValue.js b/node_modules/graphql/utilities/astFromValue.js new file mode 100644 index 0000000000000000000000000000000000000000..43568538d0b121d45160b39e47e238eb38927ff8 --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.js @@ -0,0 +1,223 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.astFromValue = astFromValue; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _isIterableObject = require('../jsutils/isIterableObject.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _kinds = require('../language/kinds.js'); + +var _definition = require('../type/definition.js'); + +var _scalars = require('../type/scalars.js'); + +/** @category Values */ + +/** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * @param value - Runtime value to convert. + * @param type - The GraphQL type to inspect. + * @returns A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it. + * @example + * ```ts + * import { print } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { astFromValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * const valueNode = astFromValue( + * { stars: 5, tags: ['featured', 'verified'] }, + * ReviewInput, + * ); + * + * print(valueNode); // => '{ stars: 5, tags: ["featured", "verified"] }' + * astFromValue(undefined, GraphQLString); // => null + * astFromValue(null, new GraphQLNonNull(GraphQLString)); // => null + * ``` + */ +function astFromValue(value, type) { + if ((0, _definition.isNonNullType)(type)) { + const astValue = astFromValue(value, type.ofType); + + if ( + (astValue === null || astValue === void 0 ? void 0 : astValue.kind) === + _kinds.Kind.NULL + ) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + if (value === null) { + return { + kind: _kinds.Kind.NULL, + }; + } // undefined + + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + + if ((0, _isIterableObject.isIterableObject)(value)) { + const valuesNodes = []; + + for (const item of value) { + const itemNode = astFromValue(item, itemType); + + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + + return { + kind: _kinds.Kind.LIST, + values: valuesNodes, + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if ((0, _definition.isInputObjectType)(type)) { + if (!(0, _isObjectLike.isObjectLike)(value)) { + return null; + } + + const fieldNodes = []; + + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: _kinds.Kind.OBJECT_FIELD, + name: { + kind: _kinds.Kind.NAME, + value: field.name, + }, + value: fieldValue, + }); + } + } + + return { + kind: _kinds.Kind.OBJECT, + fields: fieldNodes, + }; + } + + if ((0, _definition.isLeafType)(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + if (typeof serialized === 'boolean') { + return { + kind: _kinds.Kind.BOOLEAN, + value: serialized, + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === 'number' && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { + kind: _kinds.Kind.INT, + value: stringNum, + } + : { + kind: _kinds.Kind.FLOAT, + value: stringNum, + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if ((0, _definition.isEnumType)(type)) { + return { + kind: _kinds.Kind.ENUM, + value: serialized, + }; + } // ID types can use Int literals. + + if (type === _scalars.GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: _kinds.Kind.INT, + value: serialized, + }; + } + + return { + kind: _kinds.Kind.STRING, + value: serialized, + }; + } + + throw new TypeError( + `Cannot convert value to AST: ${(0, _inspect.inspect)(serialized)}.`, + ); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + * + * @internal + */ + +const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; diff --git a/node_modules/graphql/utilities/astFromValue.mjs b/node_modules/graphql/utilities/astFromValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..732eb9a1de9a5dd2e34218d404464b352dcd173e --- /dev/null +++ b/node_modules/graphql/utilities/astFromValue.mjs @@ -0,0 +1,209 @@ +/** @category Values */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { isIterableObject } from '../jsutils/isIterableObject.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { + isEnumType, + isInputObjectType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition.mjs'; +import { GraphQLID } from '../type/scalars.mjs'; +/** + * Produces a GraphQL Value AST given a JavaScript object. + * Function will match JavaScript/JSON values to GraphQL AST schema format + * by using suggested GraphQLInputType. + * + * A GraphQL type must be provided, which will be used to interpret different + * JavaScript values. + * + * | JSON Value | GraphQL Value | + * | ------------- | -------------------- | + * | Object | Input Object | + * | Array | List | + * | Boolean | Boolean | + * | String | String / Enum Value | + * | Number | Int / Float | + * | Unknown | Enum Value | + * | null | NullValue | + * @param value - Runtime value to convert. + * @param type - The GraphQL type to inspect. + * @returns A GraphQL value AST for the provided JavaScript value, or null when no literal can represent it. + * @example + * ```ts + * import { print } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { astFromValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * const valueNode = astFromValue( + * { stars: 5, tags: ['featured', 'verified'] }, + * ReviewInput, + * ); + * + * print(valueNode); // => '{ stars: 5, tags: ["featured", "verified"] }' + * astFromValue(undefined, GraphQLString); // => null + * astFromValue(null, new GraphQLNonNull(GraphQLString)); // => null + * ``` + */ + +export function astFromValue(value, type) { + if (isNonNullType(type)) { + const astValue = astFromValue(value, type.ofType); + + if ( + (astValue === null || astValue === void 0 ? void 0 : astValue.kind) === + Kind.NULL + ) { + return null; + } + + return astValue; + } // only explicit null, not undefined, NaN + + if (value === null) { + return { + kind: Kind.NULL, + }; + } // undefined + + if (value === undefined) { + return null; + } // Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but + // the value is not an array, convert the value using the list's item type. + + if (isListType(type)) { + const itemType = type.ofType; + + if (isIterableObject(value)) { + const valuesNodes = []; + + for (const item of value) { + const itemNode = astFromValue(item, itemType); + + if (itemNode != null) { + valuesNodes.push(itemNode); + } + } + + return { + kind: Kind.LIST, + values: valuesNodes, + }; + } + + return astFromValue(value, itemType); + } // Populate the fields of the input object by creating ASTs from each value + // in the JavaScript object according to the fields in the input type. + + if (isInputObjectType(type)) { + if (!isObjectLike(value)) { + return null; + } + + const fieldNodes = []; + + for (const field of Object.values(type.getFields())) { + const fieldValue = astFromValue(value[field.name], field.type); + + if (fieldValue) { + fieldNodes.push({ + kind: Kind.OBJECT_FIELD, + name: { + kind: Kind.NAME, + value: field.name, + }, + value: fieldValue, + }); + } + } + + return { + kind: Kind.OBJECT, + fields: fieldNodes, + }; + } + + if (isLeafType(type)) { + // Since value is an internally represented value, it must be serialized + // to an externally represented value before converting into an AST. + const serialized = type.serialize(value); + + if (serialized == null) { + return null; + } // Others serialize based on their corresponding JavaScript scalar types. + + if (typeof serialized === 'boolean') { + return { + kind: Kind.BOOLEAN, + value: serialized, + }; + } // JavaScript numbers can be Int or Float values. + + if (typeof serialized === 'number' && Number.isFinite(serialized)) { + const stringNum = String(serialized); + return integerStringRegExp.test(stringNum) + ? { + kind: Kind.INT, + value: stringNum, + } + : { + kind: Kind.FLOAT, + value: stringNum, + }; + } + + if (typeof serialized === 'string') { + // Enum types use Enum literals. + if (isEnumType(type)) { + return { + kind: Kind.ENUM, + value: serialized, + }; + } // ID types can use Int literals. + + if (type === GraphQLID && integerStringRegExp.test(serialized)) { + return { + kind: Kind.INT, + value: serialized, + }; + } + + return { + kind: Kind.STRING, + value: serialized, + }; + } + + throw new TypeError(`Cannot convert value to AST: ${inspect(serialized)}.`); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || invariant(false, 'Unexpected input type: ' + inspect(type)); +} +/** + * IntValue: + * - NegativeSign? 0 + * - NegativeSign? NonZeroDigit ( Digit+ )? + * + * @internal + */ + +const integerStringRegExp = /^-?(?:0|[1-9][0-9]*)$/; diff --git a/node_modules/graphql/utilities/buildASTSchema.d.ts b/node_modules/graphql/utilities/buildASTSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4ab413d80f6114520e84212f4adce55820f9006b --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.d.ts @@ -0,0 +1,94 @@ +/** @category Schema Construction */ +import type { DocumentNode } from '../language/ast'; +import type { ParseOptions } from '../language/parser'; +import type { Source } from '../language/source'; +import type { GraphQLSchemaValidationOptions } from '../type/schema'; +import { GraphQLSchema } from '../type/schema'; +/** Options used when building a schema from SDL or a parsed SDL document. */ +export interface BuildSchemaOptions extends GraphQLSchemaValidationOptions { + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; +} +/** + * Builds a GraphQLSchema from a parsed schema definition language document. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * The resulting schema has no resolver functions, so execution will use the + * default field resolver. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from a valid parsed SDL document. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { hello: String }'); + * const schema = buildASTSchema(document); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant uses validation options when the SDL references unknown types. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { broken: MissingType }'); + * + * buildASTSchema(document); // throws an error + * buildASTSchema(document, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +export declare function buildASTSchema( + documentAST: DocumentNode, + options?: BuildSchemaOptions, +): GraphQLSchema; +/** + * Builds a GraphQLSchema directly from a schema definition language source. + * @param source - The GraphQL source text or source object. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from SDL source using the default options. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant enables parser options and omits source locations. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema( + * 'directive @tag on FIELD_DEFINITION\n' + + * 'directive @compose @tag on FIELD_DEFINITION', + * { + * experimentalDirectivesOnDirectiveDefinitions: true, + * noLocation: true, + * }, + * ); + * + * const directive = schema.getDirective('compose'); + * + * directive.name; // => 'compose' + * directive.astNode.loc; // => undefined + * ``` + */ +export declare function buildSchema( + source: string | Source, + options?: BuildSchemaOptions & ParseOptions, +): GraphQLSchema; diff --git a/node_modules/graphql/utilities/buildASTSchema.js b/node_modules/graphql/utilities/buildASTSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..f909b6d6d6e55eb2a19e5358aa88e087746a0d0b --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.js @@ -0,0 +1,178 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.buildASTSchema = buildASTSchema; +exports.buildSchema = buildSchema; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _kinds = require('../language/kinds.js'); + +var _parser = require('../language/parser.js'); + +var _directives = require('../type/directives.js'); + +var _schema = require('../type/schema.js'); + +var _validate = require('../validation/validate.js'); + +var _extendSchema = require('./extendSchema.js'); + +/** @category Schema Construction */ + +/** + * Builds a GraphQLSchema from a parsed schema definition language document. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * The resulting schema has no resolver functions, so execution will use the + * default field resolver. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from a valid parsed SDL document. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { hello: String }'); + * const schema = buildASTSchema(document); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant uses validation options when the SDL references unknown types. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { broken: MissingType }'); + * + * buildASTSchema(document); // throws an error + * buildASTSchema(document, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +function buildASTSchema(documentAST, options) { + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDL)(documentAST); + } + + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false, + }; + const config = (0, _extendSchema.extendSchemaImpl)( + emptySchemaConfig, + documentAST, + options, + ); + + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case 'Query': + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + + case 'Mutation': + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + + case 'Subscription': + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } + } + } + + const directives = [ + ...config.directives, // If specified directives were not explicitly declared, add them. + ..._directives.specifiedDirectives.filter((stdDirective) => + config.directives.every( + (directive) => directive.name !== stdDirective.name, + ), + ), + ]; + return new _schema.GraphQLSchema({ ...config, directives }); +} +/** + * Builds a GraphQLSchema directly from a schema definition language source. + * @param source - The GraphQL source text or source object. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from SDL source using the default options. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant enables parser options and omits source locations. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema( + * 'directive @tag on FIELD_DEFINITION\n' + + * 'directive @compose @tag on FIELD_DEFINITION', + * { + * experimentalDirectivesOnDirectiveDefinitions: true, + * noLocation: true, + * }, + * ); + * + * const directive = schema.getDirective('compose'); + * + * directive.name; // => 'compose' + * directive.astNode.loc; // => undefined + * ``` + */ + +function buildSchema(source, options) { + const document = (0, _parser.parse)(source, { + noLocation: + options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacyFragmentVariables: + options === null || options === void 0 + ? void 0 + : options.allowLegacyFragmentVariables, + experimentalDirectivesOnDirectiveDefinitions: + options === null || options === void 0 + ? void 0 + : options.experimentalDirectivesOnDirectiveDefinitions, + }); + return buildASTSchema(document, { + assumeValidSDL: + options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); +} diff --git a/node_modules/graphql/utilities/buildASTSchema.mjs b/node_modules/graphql/utilities/buildASTSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..036492216fb7db4e8e71e6f39fa9bd04ceed79b4 --- /dev/null +++ b/node_modules/graphql/utilities/buildASTSchema.mjs @@ -0,0 +1,160 @@ +/** @category Schema Construction */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { parse } from '../language/parser.mjs'; +import { specifiedDirectives } from '../type/directives.mjs'; +import { GraphQLSchema } from '../type/schema.mjs'; +import { assertValidSDL } from '../validation/validate.mjs'; +import { extendSchemaImpl } from './extendSchema.mjs'; +/** Options used when building a schema from SDL or a parsed SDL document. */ + +/** + * Builds a GraphQLSchema from a parsed schema definition language document. + * + * If no schema definition is provided, then it will look for types named Query, + * Mutation and Subscription. + * + * The resulting schema has no resolver functions, so execution will use the + * default field resolver. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from a valid parsed SDL document. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { hello: String }'); + * const schema = buildASTSchema(document); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant uses validation options when the SDL references unknown types. + * import { parse } from 'graphql/language'; + * import { buildASTSchema } from 'graphql/utilities'; + * + * const document = parse('type Query { broken: MissingType }'); + * + * buildASTSchema(document); // throws an error + * buildASTSchema(document, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +export function buildASTSchema(documentAST, options) { + (documentAST != null && documentAST.kind === Kind.DOCUMENT) || + devAssert(false, 'Must provide valid Document AST.'); + + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + assertValidSDL(documentAST); + } + + const emptySchemaConfig = { + description: undefined, + types: [], + directives: [], + extensions: Object.create(null), + extensionASTNodes: [], + assumeValid: false, + }; + const config = extendSchemaImpl(emptySchemaConfig, documentAST, options); + + if (config.astNode == null) { + for (const type of config.types) { + switch (type.name) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + case 'Query': + // @ts-expect-error validated in `validateSchema` + config.query = type; + break; + + case 'Mutation': + // @ts-expect-error validated in `validateSchema` + config.mutation = type; + break; + + case 'Subscription': + // @ts-expect-error validated in `validateSchema` + config.subscription = type; + break; + } + } + } + + const directives = [ + ...config.directives, // If specified directives were not explicitly declared, add them. + ...specifiedDirectives.filter((stdDirective) => + config.directives.every( + (directive) => directive.name !== stdDirective.name, + ), + ), + ]; + return new GraphQLSchema({ ...config, directives }); +} +/** + * Builds a GraphQLSchema directly from a schema definition language source. + * @param source - The GraphQL source text or source object. + * @param options - Optional configuration for this operation. + * @returns The schema built from the provided SDL document. + * @example + * ```ts + * // Build a schema from SDL source using the default options. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * + * schema.getQueryType().name; // => 'Query' + * ``` + * @example + * ```ts + * // This variant enables parser options and omits source locations. + * import { buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema( + * 'directive @tag on FIELD_DEFINITION\n' + + * 'directive @compose @tag on FIELD_DEFINITION', + * { + * experimentalDirectivesOnDirectiveDefinitions: true, + * noLocation: true, + * }, + * ); + * + * const directive = schema.getDirective('compose'); + * + * directive.name; // => 'compose' + * directive.astNode.loc; // => undefined + * ``` + */ + +export function buildSchema(source, options) { + const document = parse(source, { + noLocation: + options === null || options === void 0 ? void 0 : options.noLocation, + allowLegacyFragmentVariables: + options === null || options === void 0 + ? void 0 + : options.allowLegacyFragmentVariables, + experimentalDirectivesOnDirectiveDefinitions: + options === null || options === void 0 + ? void 0 + : options.experimentalDirectivesOnDirectiveDefinitions, + }); + return buildASTSchema(document, { + assumeValidSDL: + options === null || options === void 0 ? void 0 : options.assumeValidSDL, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); +} diff --git a/node_modules/graphql/utilities/buildClientSchema.d.ts b/node_modules/graphql/utilities/buildClientSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1450153d1387c6d86e04b93b6071cd202da6286 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.d.ts @@ -0,0 +1,34 @@ +/** @category Introspection */ +import type { GraphQLSchemaValidationOptions } from '../type/schema'; +import { GraphQLSchema } from '../type/schema'; +import type { IntrospectionQuery } from './getIntrospectionQuery'; +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + * @param introspection - Introspection result data to build from. + * @param options - Optional configuration for this operation. + * @returns The client schema represented by the introspection result. + * @example + * ```ts + * import { buildClientSchema, introspectionFromSchema, buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * const clientSchema = buildClientSchema(introspectionFromSchema(schema), { + * assumeValid: true, + * }); + * + * clientSchema.getQueryType().name; // => 'Query' + * ``` + */ +export declare function buildClientSchema( + introspection: IntrospectionQuery, + options?: GraphQLSchemaValidationOptions, +): GraphQLSchema; diff --git a/node_modules/graphql/utilities/buildClientSchema.js b/node_modules/graphql/utilities/buildClientSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..d6199b130af8b7f028a2a997f131b88b0be84431 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.js @@ -0,0 +1,404 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.buildClientSchema = buildClientSchema; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _keyValMap = require('../jsutils/keyValMap.js'); + +var _parser = require('../language/parser.js'); + +var _definition = require('../type/definition.js'); + +var _directives = require('../type/directives.js'); + +var _introspection = require('../type/introspection.js'); + +var _scalars = require('../type/scalars.js'); + +var _schema = require('../type/schema.js'); + +var _valueFromAST = require('./valueFromAST.js'); + +/** @category Introspection */ + +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + * @param introspection - Introspection result data to build from. + * @param options - Optional configuration for this operation. + * @returns The client schema represented by the introspection result. + * @example + * ```ts + * import { buildClientSchema, introspectionFromSchema, buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * const clientSchema = buildClientSchema(introspectionFromSchema(schema), { + * assumeValid: true, + * }); + * + * clientSchema.getQueryType().name; // => 'Query' + * ``` + */ +function buildClientSchema(introspection, options) { + ((0, _isObjectLike.isObjectLike)(introspection) && + (0, _isObjectLike.isObjectLike)(introspection.__schema)) || + (0, _devAssert.devAssert)( + false, + `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${(0, + _inspect.inspect)(introspection)}.`, + ); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = (0, _keyValMap.keyValMap)( + schemaIntrospection.types, + (typeIntrospection) => typeIntrospection.name, + (typeIntrospection) => buildType(typeIntrospection), + ); // Include standard types only if they are used. + + for (const stdType of [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, + ]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; // Then produce and return a Schema with these types. + + return new _schema.GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === _introspection.TypeKind.LIST) { + const itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return new _definition.GraphQLList(getType(itemRef)); + } + + if (typeRef.kind === _introspection.TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + const nullableType = getType(nullableRef); + return new _definition.GraphQLNonNull( + (0, _definition.assertNullableType)(nullableType), + ); + } + + return getNamedType(typeRef); + } + + function getNamedType(typeRef) { + const typeName = typeRef.name; + + if (!typeName) { + throw new Error( + `Unknown type reference: ${(0, _inspect.inspect)(typeRef)}.`, + ); + } + + const type = typeMap[typeName]; + + if (!type) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`, + ); + } + + return type; + } + + function getObjectType(typeRef) { + return (0, _definition.assertObjectType)(getNamedType(typeRef)); + } + + function getInterfaceType(typeRef) { + return (0, _definition.assertInterfaceType)(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case _introspection.TypeKind.SCALAR: + return buildScalarDef(type); + + case _introspection.TypeKind.OBJECT: + return buildObjectDef(type); + + case _introspection.TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case _introspection.TypeKind.UNION: + return buildUnionDef(type); + + case _introspection.TypeKind.ENUM: + return buildEnumDef(type); + + case _introspection.TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`, + ); + } + + function buildScalarDef(scalarIntrospection) { + return new _definition.GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL, + }); + } + + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if ( + implementingIntrospection.interfaces === null && + implementingIntrospection.kind === _introspection.TypeKind.INTERFACE + ) { + return []; + } + + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = (0, _inspect.inspect)( + implementingIntrospection, + ); + throw new Error( + `Introspection result missing interfaces: ${implementingIntrospectionStr}.`, + ); + } + + return implementingIntrospection.interfaces.map(getInterfaceType); + } + + function buildObjectDef(objectIntrospection) { + return new _definition.GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new _definition.GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = (0, _inspect.inspect)(unionIntrospection); + throw new Error( + `Introspection result missing possibleTypes: ${unionIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = (0, _inspect.inspect)(enumIntrospection); + throw new Error( + `Introspection result missing enumValues: ${enumIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: (0, _keyValMap.keyValMap)( + enumIntrospection.enumValues, + (valueIntrospection) => valueIntrospection.name, + (valueIntrospection) => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }), + ), + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = (0, _inspect.inspect)( + inputObjectIntrospection, + ); + throw new Error( + `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`, + ); + } + + return new _definition.GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + isOneOf: inputObjectIntrospection.isOneOf, + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + `Introspection result missing fields: ${(0, _inspect.inspect)( + typeIntrospection, + )}.`, + ); + } + + return (0, _keyValMap.keyValMap)( + typeIntrospection.fields, + (fieldIntrospection) => fieldIntrospection.name, + buildField, + ); + } + + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + + if (!(0, _definition.isOutputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide output type for fields, but received: ${typeStr}.`, + ); + } + + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = (0, _inspect.inspect)(fieldIntrospection); + throw new Error( + `Introspection result missing field args: ${fieldIntrospectionStr}.`, + ); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args), + }; + } + + function buildInputValueDefMap(inputValueIntrospections) { + return (0, _keyValMap.keyValMap)( + inputValueIntrospections, + (inputValue) => inputValue.name, + buildInputValue, + ); + } + + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + + if (!(0, _definition.isInputType)(type)) { + const typeStr = (0, _inspect.inspect)(type); + throw new Error( + `Introspection must provide input type for arguments, but received: ${typeStr}.`, + ); + } + + const defaultValue = + inputValueIntrospection.defaultValue != null + ? (0, _valueFromAST.valueFromAST)( + (0, _parser.parseValue)(inputValueIntrospection.defaultValue), + type, + ) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason, + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection, + ); + throw new Error( + `Introspection result missing directive args: ${directiveIntrospectionStr}.`, + ); + } + + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = (0, _inspect.inspect)( + directiveIntrospection, + ); + throw new Error( + `Introspection result missing directive locations: ${directiveIntrospectionStr}.`, + ); + } + + return new _directives.GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + deprecationReason: directiveIntrospection.deprecationReason, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); + } +} diff --git a/node_modules/graphql/utilities/buildClientSchema.mjs b/node_modules/graphql/utilities/buildClientSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..91712ce9a2f1eea4aed294b740c7af63ca572668 --- /dev/null +++ b/node_modules/graphql/utilities/buildClientSchema.mjs @@ -0,0 +1,380 @@ +/** @category Introspection */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { keyValMap } from '../jsutils/keyValMap.mjs'; +import { parseValue } from '../language/parser.mjs'; +import { + assertInterfaceType, + assertNullableType, + assertObjectType, + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLScalarType, + GraphQLUnionType, + isInputType, + isOutputType, +} from '../type/definition.mjs'; +import { GraphQLDirective } from '../type/directives.mjs'; +import { introspectionTypes, TypeKind } from '../type/introspection.mjs'; +import { specifiedScalarTypes } from '../type/scalars.mjs'; +import { GraphQLSchema } from '../type/schema.mjs'; +import { valueFromAST } from './valueFromAST.mjs'; +/** + * Build a GraphQLSchema for use by client tools. + * + * Given the result of a client running the introspection query, creates and + * returns a GraphQLSchema instance which can be then used with all graphql-js + * tools, but cannot be used to execute a query, as introspection does not + * represent the "resolver", "parse" or "serialize" functions or any other + * server-internal mechanisms. + * + * This function expects a complete introspection result. Don't forget to check + * the "errors" field of a server response before calling this function. + * @param introspection - Introspection result data to build from. + * @param options - Optional configuration for this operation. + * @returns The client schema represented by the introspection result. + * @example + * ```ts + * import { buildClientSchema, introspectionFromSchema, buildSchema } from 'graphql/utilities'; + * + * const schema = buildSchema('type Query { hello: String }'); + * const clientSchema = buildClientSchema(introspectionFromSchema(schema), { + * assumeValid: true, + * }); + * + * clientSchema.getQueryType().name; // => 'Query' + * ``` + */ + +export function buildClientSchema(introspection, options) { + (isObjectLike(introspection) && isObjectLike(introspection.__schema)) || + devAssert( + false, + `Invalid or incomplete introspection result. Ensure that you are passing "data" property of introspection response and no "errors" was returned alongside: ${inspect( + introspection, + )}.`, + ); // Get the schema from the introspection result. + + const schemaIntrospection = introspection.__schema; // Iterate through all types, getting the type definition for each. + + const typeMap = keyValMap( + schemaIntrospection.types, + (typeIntrospection) => typeIntrospection.name, + (typeIntrospection) => buildType(typeIntrospection), + ); // Include standard types only if they are used. + + for (const stdType of [...specifiedScalarTypes, ...introspectionTypes]) { + if (typeMap[stdType.name]) { + typeMap[stdType.name] = stdType; + } + } // Get the root Query, Mutation, and Subscription types. + + const queryType = schemaIntrospection.queryType + ? getObjectType(schemaIntrospection.queryType) + : null; + const mutationType = schemaIntrospection.mutationType + ? getObjectType(schemaIntrospection.mutationType) + : null; + const subscriptionType = schemaIntrospection.subscriptionType + ? getObjectType(schemaIntrospection.subscriptionType) + : null; // Get the directives supported by Introspection, assuming empty-set if + // directives were not queried for. + + const directives = schemaIntrospection.directives + ? schemaIntrospection.directives.map(buildDirective) + : []; // Then produce and return a Schema with these types. + + return new GraphQLSchema({ + description: schemaIntrospection.description, + query: queryType, + mutation: mutationType, + subscription: subscriptionType, + types: Object.values(typeMap), + directives, + assumeValid: + options === null || options === void 0 ? void 0 : options.assumeValid, + }); // Given a type reference in introspection, return the GraphQLType instance. + // preferring cached instances before building new instances. + + function getType(typeRef) { + if (typeRef.kind === TypeKind.LIST) { + const itemRef = typeRef.ofType; + + if (!itemRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + return new GraphQLList(getType(itemRef)); + } + + if (typeRef.kind === TypeKind.NON_NULL) { + const nullableRef = typeRef.ofType; + + if (!nullableRef) { + throw new Error('Decorated type deeper than introspection query.'); + } + + const nullableType = getType(nullableRef); + return new GraphQLNonNull(assertNullableType(nullableType)); + } + + return getNamedType(typeRef); + } + + function getNamedType(typeRef) { + const typeName = typeRef.name; + + if (!typeName) { + throw new Error(`Unknown type reference: ${inspect(typeRef)}.`); + } + + const type = typeMap[typeName]; + + if (!type) { + throw new Error( + `Invalid or incomplete schema, unknown type: ${typeName}. Ensure that a full introspection query is used in order to build a client schema.`, + ); + } + + return type; + } + + function getObjectType(typeRef) { + return assertObjectType(getNamedType(typeRef)); + } + + function getInterfaceType(typeRef) { + return assertInterfaceType(getNamedType(typeRef)); + } // Given a type's introspection result, construct the correct + // GraphQLType instance. + + function buildType(type) { + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain + if (type != null && type.name != null && type.kind != null) { + // FIXME: Properly type IntrospectionType, it's a breaking change so fix in v17 + // eslint-disable-next-line @typescript-eslint/switch-exhaustiveness-check + switch (type.kind) { + case TypeKind.SCALAR: + return buildScalarDef(type); + + case TypeKind.OBJECT: + return buildObjectDef(type); + + case TypeKind.INTERFACE: + return buildInterfaceDef(type); + + case TypeKind.UNION: + return buildUnionDef(type); + + case TypeKind.ENUM: + return buildEnumDef(type); + + case TypeKind.INPUT_OBJECT: + return buildInputObjectDef(type); + } + } + + const typeStr = inspect(type); + throw new Error( + `Invalid or incomplete introspection result. Ensure that a full introspection query is used in order to build a client schema: ${typeStr}.`, + ); + } + + function buildScalarDef(scalarIntrospection) { + return new GraphQLScalarType({ + name: scalarIntrospection.name, + description: scalarIntrospection.description, + specifiedByURL: scalarIntrospection.specifiedByURL, + }); + } + + function buildImplementationsList(implementingIntrospection) { + // TODO: Temporary workaround until GraphQL ecosystem will fully support + // 'interfaces' on interface types. + if ( + implementingIntrospection.interfaces === null && + implementingIntrospection.kind === TypeKind.INTERFACE + ) { + return []; + } + + if (!implementingIntrospection.interfaces) { + const implementingIntrospectionStr = inspect(implementingIntrospection); + throw new Error( + `Introspection result missing interfaces: ${implementingIntrospectionStr}.`, + ); + } + + return implementingIntrospection.interfaces.map(getInterfaceType); + } + + function buildObjectDef(objectIntrospection) { + return new GraphQLObjectType({ + name: objectIntrospection.name, + description: objectIntrospection.description, + interfaces: () => buildImplementationsList(objectIntrospection), + fields: () => buildFieldDefMap(objectIntrospection), + }); + } + + function buildInterfaceDef(interfaceIntrospection) { + return new GraphQLInterfaceType({ + name: interfaceIntrospection.name, + description: interfaceIntrospection.description, + interfaces: () => buildImplementationsList(interfaceIntrospection), + fields: () => buildFieldDefMap(interfaceIntrospection), + }); + } + + function buildUnionDef(unionIntrospection) { + if (!unionIntrospection.possibleTypes) { + const unionIntrospectionStr = inspect(unionIntrospection); + throw new Error( + `Introspection result missing possibleTypes: ${unionIntrospectionStr}.`, + ); + } + + return new GraphQLUnionType({ + name: unionIntrospection.name, + description: unionIntrospection.description, + types: () => unionIntrospection.possibleTypes.map(getObjectType), + }); + } + + function buildEnumDef(enumIntrospection) { + if (!enumIntrospection.enumValues) { + const enumIntrospectionStr = inspect(enumIntrospection); + throw new Error( + `Introspection result missing enumValues: ${enumIntrospectionStr}.`, + ); + } + + return new GraphQLEnumType({ + name: enumIntrospection.name, + description: enumIntrospection.description, + values: keyValMap( + enumIntrospection.enumValues, + (valueIntrospection) => valueIntrospection.name, + (valueIntrospection) => ({ + description: valueIntrospection.description, + deprecationReason: valueIntrospection.deprecationReason, + }), + ), + }); + } + + function buildInputObjectDef(inputObjectIntrospection) { + if (!inputObjectIntrospection.inputFields) { + const inputObjectIntrospectionStr = inspect(inputObjectIntrospection); + throw new Error( + `Introspection result missing inputFields: ${inputObjectIntrospectionStr}.`, + ); + } + + return new GraphQLInputObjectType({ + name: inputObjectIntrospection.name, + description: inputObjectIntrospection.description, + fields: () => buildInputValueDefMap(inputObjectIntrospection.inputFields), + isOneOf: inputObjectIntrospection.isOneOf, + }); + } + + function buildFieldDefMap(typeIntrospection) { + if (!typeIntrospection.fields) { + throw new Error( + `Introspection result missing fields: ${inspect(typeIntrospection)}.`, + ); + } + + return keyValMap( + typeIntrospection.fields, + (fieldIntrospection) => fieldIntrospection.name, + buildField, + ); + } + + function buildField(fieldIntrospection) { + const type = getType(fieldIntrospection.type); + + if (!isOutputType(type)) { + const typeStr = inspect(type); + throw new Error( + `Introspection must provide output type for fields, but received: ${typeStr}.`, + ); + } + + if (!fieldIntrospection.args) { + const fieldIntrospectionStr = inspect(fieldIntrospection); + throw new Error( + `Introspection result missing field args: ${fieldIntrospectionStr}.`, + ); + } + + return { + description: fieldIntrospection.description, + deprecationReason: fieldIntrospection.deprecationReason, + type, + args: buildInputValueDefMap(fieldIntrospection.args), + }; + } + + function buildInputValueDefMap(inputValueIntrospections) { + return keyValMap( + inputValueIntrospections, + (inputValue) => inputValue.name, + buildInputValue, + ); + } + + function buildInputValue(inputValueIntrospection) { + const type = getType(inputValueIntrospection.type); + + if (!isInputType(type)) { + const typeStr = inspect(type); + throw new Error( + `Introspection must provide input type for arguments, but received: ${typeStr}.`, + ); + } + + const defaultValue = + inputValueIntrospection.defaultValue != null + ? valueFromAST(parseValue(inputValueIntrospection.defaultValue), type) + : undefined; + return { + description: inputValueIntrospection.description, + type, + defaultValue, + deprecationReason: inputValueIntrospection.deprecationReason, + }; + } + + function buildDirective(directiveIntrospection) { + if (!directiveIntrospection.args) { + const directiveIntrospectionStr = inspect(directiveIntrospection); + throw new Error( + `Introspection result missing directive args: ${directiveIntrospectionStr}.`, + ); + } + + if (!directiveIntrospection.locations) { + const directiveIntrospectionStr = inspect(directiveIntrospection); + throw new Error( + `Introspection result missing directive locations: ${directiveIntrospectionStr}.`, + ); + } + + return new GraphQLDirective({ + name: directiveIntrospection.name, + description: directiveIntrospection.description, + isRepeatable: directiveIntrospection.isRepeatable, + deprecationReason: directiveIntrospection.deprecationReason, + locations: directiveIntrospection.locations.slice(), + args: buildInputValueDefMap(directiveIntrospection.args), + }); + } +} diff --git a/node_modules/graphql/utilities/coerceInputValue.d.ts b/node_modules/graphql/utilities/coerceInputValue.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2638de1bcf640dfecaebd2465103029f0e4751b6 --- /dev/null +++ b/node_modules/graphql/utilities/coerceInputValue.d.ts @@ -0,0 +1,62 @@ +/** @category Values */ +import { GraphQLError } from '../error/GraphQLError'; +import type { GraphQLInputType } from '../type/definition'; +declare type OnErrorCB = ( + path: ReadonlyArray, + invalidValue: unknown, + error: GraphQLError, +) => void; +/** + * Coerces a JavaScript value given a GraphQL Input Type. + * @param inputValue - JavaScript value to coerce. + * @param type - GraphQL input type to coerce the value against. + * @param onError - Callback invoked for each coercion error. + * @returns Coerced value, or undefined if coercion failed and errors were reported. + * @example + * ```ts + * // Coerce runtime input values and throw on invalid input by default. + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] } + * coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error + * ``` + * @example + * ```ts + * // This variant collects coercion errors with a custom onError callback. + * import { GraphQLInt, GraphQLNonNull } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const errors = []; + * const value = coerceInputValue( + * null, + * new GraphQLNonNull(GraphQLInt), + * (path, invalidValue, error) => { + * errors.push({ path, invalidValue, message: error.message }); + * }, + * ); + * + * value; // => undefined + * errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ] + * ``` + */ +export declare function coerceInputValue( + inputValue: unknown, + type: GraphQLInputType, + onError?: OnErrorCB, +): unknown; +export {}; diff --git a/node_modules/graphql/utilities/coerceInputValue.js b/node_modules/graphql/utilities/coerceInputValue.js new file mode 100644 index 0000000000000000000000000000000000000000..52b64e49bded9447dc750f1317cd552091629e72 --- /dev/null +++ b/node_modules/graphql/utilities/coerceInputValue.js @@ -0,0 +1,264 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.coerceInputValue = coerceInputValue; + +var _didYouMean = require('../jsutils/didYouMean.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _isIterableObject = require('../jsutils/isIterableObject.js'); + +var _isObjectLike = require('../jsutils/isObjectLike.js'); + +var _Path = require('../jsutils/Path.js'); + +var _printPathArray = require('../jsutils/printPathArray.js'); + +var _suggestionList = require('../jsutils/suggestionList.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _definition = require('../type/definition.js'); + +/** @category Values */ + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + * @param inputValue - JavaScript value to coerce. + * @param type - GraphQL input type to coerce the value against. + * @param onError - Callback invoked for each coercion error. + * @returns Coerced value, or undefined if coercion failed and errors were reported. + * @example + * ```ts + * // Coerce runtime input values and throw on invalid input by default. + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] } + * coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error + * ``` + * @example + * ```ts + * // This variant collects coercion errors with a custom onError callback. + * import { GraphQLInt, GraphQLNonNull } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const errors = []; + * const value = coerceInputValue( + * null, + * new GraphQLNonNull(GraphQLInt), + * (path, invalidValue, error) => { + * errors.push({ path, invalidValue, message: error.message }); + * }, + * ); + * + * value; // => undefined + * errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ] + * ``` + */ +function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); +} + +function defaultOnError(path, invalidValue, error) { + let errorPrefix = 'Invalid value ' + (0, _inspect.inspect)(invalidValue); + + if (path.length > 0) { + errorPrefix += ` at "value${(0, _printPathArray.printPathArray)(path)}"`; + } + + error.message = errorPrefix + ': ' + error.message; + throw error; +} + +function coerceInputValueImpl(inputValue, type, onError, path) { + if ((0, _definition.isNonNullType)(type)) { + if (inputValue != null) { + return coerceInputValueImpl(inputValue, type.ofType, onError, path); + } + + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected non-nullable type "${(0, _inspect.inspect)( + type, + )}" not to be null.`, + ), + ); + return; + } + + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + + if ((0, _isIterableObject.isIterableObject)(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = (0, _Path.addPath)(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + } // Lists accept a non-list value as a list of one. + + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } + + if ((0, _definition.isInputObjectType)(type)) { + if ( + !(0, _isObjectLike.isObjectLike)(inputValue) || + Array.isArray(inputValue) + ) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}" to be an object.`, + ), + ); + return; + } + + const coercedValue = Object.create(null); + const fieldDefs = type.getFields(); + + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + const typeStr = (0, _inspect.inspect)(field.type); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${field.name}" of required type "${typeStr}" was not provided.`, + ), + ); + } + + continue; + } + + coercedValue[field.name] = coerceInputValueImpl( + fieldValue, + field.type, + onError, + (0, _Path.addPath)(path, field.name, type.name), + ); + } // Ensure every provided field is defined. + + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = (0, _suggestionList.suggestionList)( + fieldName, + Object.keys(type.getFields()), + ); + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Field "${fieldName}" is not defined by type "${type.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + ), + ); + } + } + + if (type.isOneOf) { + const keys = Object.keys(coercedValue); + + if (keys.length !== 1) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Exactly one key must be specified for OneOf type "${type.name}".`, + ), + ); + } + + const key = keys[0]; + const value = coercedValue[key]; + + if (value === null) { + onError( + (0, _Path.pathToArray)(path).concat(key), + value, + new _GraphQLError.GraphQLError(`Field "${key}" must be non-null.`), + ); + } + } + + return { ...coercedValue }; + } + + if ((0, _definition.isLeafType)(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. + + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof _GraphQLError.GraphQLError) { + onError((0, _Path.pathToArray)(path), inputValue, error); + } else { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError( + `Expected type "${type.name}". ` + error.message, + { + originalError: error, + }, + ), + ); + } + + return; + } + + if (parseResult === undefined) { + onError( + (0, _Path.pathToArray)(path), + inputValue, + new _GraphQLError.GraphQLError(`Expected type "${type.name}".`), + ); + } + + return parseResult; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); +} diff --git a/node_modules/graphql/utilities/coerceInputValue.mjs b/node_modules/graphql/utilities/coerceInputValue.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d3f1a577165b8add698cc4faa9b14ee23af05b1b --- /dev/null +++ b/node_modules/graphql/utilities/coerceInputValue.mjs @@ -0,0 +1,238 @@ +/** @category Values */ +import { didYouMean } from '../jsutils/didYouMean.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { isIterableObject } from '../jsutils/isIterableObject.mjs'; +import { isObjectLike } from '../jsutils/isObjectLike.mjs'; +import { addPath, pathToArray } from '../jsutils/Path.mjs'; +import { printPathArray } from '../jsutils/printPathArray.mjs'; +import { suggestionList } from '../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { + isInputObjectType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition.mjs'; + +/** + * Coerces a JavaScript value given a GraphQL Input Type. + * @param inputValue - JavaScript value to coerce. + * @param type - GraphQL input type to coerce the value against. + * @param onError - Callback invoked for each coercion error. + * @returns Coerced value, or undefined if coercion failed and errors were reported. + * @example + * ```ts + * // Coerce runtime input values and throw on invalid input by default. + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * coerceInputValue({ stars: '5', tags: ['featured'] }, ReviewInput); // => { stars: 5, tags: ['featured'] } + * coerceInputValue({ stars: 'bad' }, ReviewInput); // throws an error + * ``` + * @example + * ```ts + * // This variant collects coercion errors with a custom onError callback. + * import { GraphQLInt, GraphQLNonNull } from 'graphql/type'; + * import { coerceInputValue } from 'graphql/utilities'; + * + * const errors = []; + * const value = coerceInputValue( + * null, + * new GraphQLNonNull(GraphQLInt), + * (path, invalidValue, error) => { + * errors.push({ path, invalidValue, message: error.message }); + * }, + * ); + * + * value; // => undefined + * errors; // => [ { path: [], invalidValue: null, message: 'Expected non-nullable type "Int!" not to be null.' } ] + * ``` + */ +export function coerceInputValue(inputValue, type, onError = defaultOnError) { + return coerceInputValueImpl(inputValue, type, onError, undefined); +} + +function defaultOnError(path, invalidValue, error) { + let errorPrefix = 'Invalid value ' + inspect(invalidValue); + + if (path.length > 0) { + errorPrefix += ` at "value${printPathArray(path)}"`; + } + + error.message = errorPrefix + ': ' + error.message; + throw error; +} + +function coerceInputValueImpl(inputValue, type, onError, path) { + if (isNonNullType(type)) { + if (inputValue != null) { + return coerceInputValueImpl(inputValue, type.ofType, onError, path); + } + + onError( + pathToArray(path), + inputValue, + new GraphQLError( + `Expected non-nullable type "${inspect(type)}" not to be null.`, + ), + ); + return; + } + + if (inputValue == null) { + // Explicitly return the value null. + return null; + } + + if (isListType(type)) { + const itemType = type.ofType; + + if (isIterableObject(inputValue)) { + return Array.from(inputValue, (itemValue, index) => { + const itemPath = addPath(path, index, undefined); + return coerceInputValueImpl(itemValue, itemType, onError, itemPath); + }); + } // Lists accept a non-list value as a list of one. + + return [coerceInputValueImpl(inputValue, itemType, onError, path)]; + } + + if (isInputObjectType(type)) { + if (!isObjectLike(inputValue) || Array.isArray(inputValue)) { + onError( + pathToArray(path), + inputValue, + new GraphQLError(`Expected type "${type.name}" to be an object.`), + ); + return; + } + + const coercedValue = Object.create(null); + const fieldDefs = type.getFields(); + + for (const field of Object.values(fieldDefs)) { + const fieldValue = inputValue[field.name]; + + if (fieldValue === undefined) { + if (field.defaultValue !== undefined) { + coercedValue[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + const typeStr = inspect(field.type); + onError( + pathToArray(path), + inputValue, + new GraphQLError( + `Field "${field.name}" of required type "${typeStr}" was not provided.`, + ), + ); + } + + continue; + } + + coercedValue[field.name] = coerceInputValueImpl( + fieldValue, + field.type, + onError, + addPath(path, field.name, type.name), + ); + } // Ensure every provided field is defined. + + for (const fieldName of Object.keys(inputValue)) { + if (!fieldDefs[fieldName]) { + const suggestions = suggestionList( + fieldName, + Object.keys(type.getFields()), + ); + onError( + pathToArray(path), + inputValue, + new GraphQLError( + `Field "${fieldName}" is not defined by type "${type.name}".` + + didYouMean(suggestions), + ), + ); + } + } + + if (type.isOneOf) { + const keys = Object.keys(coercedValue); + + if (keys.length !== 1) { + onError( + pathToArray(path), + inputValue, + new GraphQLError( + `Exactly one key must be specified for OneOf type "${type.name}".`, + ), + ); + } + + const key = keys[0]; + const value = coercedValue[key]; + + if (value === null) { + onError( + pathToArray(path).concat(key), + value, + new GraphQLError(`Field "${key}" must be non-null.`), + ); + } + } + + return { ...coercedValue }; + } + + if (isLeafType(type)) { + let parseResult; // Scalars and Enums determine if a input value is valid via parseValue(), + // which can throw to indicate failure. If it throws, maintain a reference + // to the original error. + + try { + parseResult = type.parseValue(inputValue); + } catch (error) { + if (error instanceof GraphQLError) { + onError(pathToArray(path), inputValue, error); + } else { + onError( + pathToArray(path), + inputValue, + new GraphQLError(`Expected type "${type.name}". ` + error.message, { + originalError: error, + }), + ); + } + + return; + } + + if (parseResult === undefined) { + onError( + pathToArray(path), + inputValue, + new GraphQLError(`Expected type "${type.name}".`), + ); + } + + return parseResult; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || invariant(false, 'Unexpected input type: ' + inspect(type)); +} diff --git a/node_modules/graphql/utilities/concatAST.d.ts b/node_modules/graphql/utilities/concatAST.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d12e01d586c3130d52a224504f76a5f82855807 --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.d.ts @@ -0,0 +1,21 @@ +/** @category AST Utilities */ +import type { DocumentNode } from '../language/ast'; +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + * @param documents - Document ASTs to concatenate. + * @returns A document AST containing all definitions from the provided documents. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { concatAST } from 'graphql/utilities'; + * + * const document = concatAST([parse('type Query { a: String }'), parse('type User { id: ID }')]); + * + * document.definitions.length; // => 2 + * ``` + */ +export declare function concatAST( + documents: ReadonlyArray, +): DocumentNode; diff --git a/node_modules/graphql/utilities/concatAST.js b/node_modules/graphql/utilities/concatAST.js new file mode 100644 index 0000000000000000000000000000000000000000..14829eb7587f6f61566989343b196a8ee97ff7e2 --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.js @@ -0,0 +1,39 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.concatAST = concatAST; + +var _kinds = require('../language/kinds.js'); + +/** @category AST Utilities */ + +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + * @param documents - Document ASTs to concatenate. + * @returns A document AST containing all definitions from the provided documents. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { concatAST } from 'graphql/utilities'; + * + * const document = concatAST([parse('type Query { a: String }'), parse('type User { id: ID }')]); + * + * document.definitions.length; // => 2 + * ``` + */ +function concatAST(documents) { + const definitions = []; + + for (const doc of documents) { + definitions.push(...doc.definitions); + } + + return { + kind: _kinds.Kind.DOCUMENT, + definitions, + }; +} diff --git a/node_modules/graphql/utilities/concatAST.mjs b/node_modules/graphql/utilities/concatAST.mjs new file mode 100644 index 0000000000000000000000000000000000000000..08787193549d22a5a5a42dc1e19399645d5cc50e --- /dev/null +++ b/node_modules/graphql/utilities/concatAST.mjs @@ -0,0 +1,31 @@ +/** @category AST Utilities */ +import { Kind } from '../language/kinds.mjs'; +/** + * Provided a collection of ASTs, presumably each from different files, + * concatenate the ASTs together into batched AST, useful for validating many + * GraphQL source files which together represent one conceptual application. + * @param documents - Document ASTs to concatenate. + * @returns A document AST containing all definitions from the provided documents. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { concatAST } from 'graphql/utilities'; + * + * const document = concatAST([parse('type Query { a: String }'), parse('type User { id: ID }')]); + * + * document.definitions.length; // => 2 + * ``` + */ + +export function concatAST(documents) { + const definitions = []; + + for (const doc of documents) { + definitions.push(...doc.definitions); + } + + return { + kind: Kind.DOCUMENT, + definitions, + }; +} diff --git a/node_modules/graphql/utilities/extendSchema.d.ts b/node_modules/graphql/utilities/extendSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3357e6bf90702cf63da3218cf23e352e781ef691 --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.d.ts @@ -0,0 +1,93 @@ +/** @category Schema Construction */ +import type { DocumentNode } from '../language/ast'; +import type { + GraphQLSchemaNormalizedConfig, + GraphQLSchemaValidationOptions, +} from '../type/schema'; +import { GraphQLSchema } from '../type/schema'; +interface Options extends GraphQLSchemaValidationOptions { + /** + * Set to true to assume the SDL is valid. + * + * Default: false + */ + assumeValidSDL?: boolean; +} +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * @param schema - GraphQL schema to use. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns A new schema with the extensions and definitions applied. + * @example + * ```ts + * // Extend a schema with new fields and types. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const extensionAST = parse(` + * extend type Query { + * farewell: String + * } + * + * type Review { + * body: String + * } + * `); + * + * const extendedSchema = extendSchema(schema, extensionAST); + * + * schema.getType('Review'); // => undefined + * extendedSchema.getType('Review')?.name; // => 'Review' + * Object.keys(extendedSchema.getQueryType().getFields()); // => ['greeting', 'farewell'] + * ``` + * @example + * ```ts + * // This variant bypasses validation for an otherwise invalid extension. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const invalidExtension = parse(` + * extend type Missing { + * field: String + * } + * `); + * + * extendSchema(schema, invalidExtension); // throws an error + * extendSchema(schema, invalidExtension, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +export declare function extendSchema( + schema: GraphQLSchema, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchema; +/** @internal */ +export declare function extendSchemaImpl( + schemaConfig: GraphQLSchemaNormalizedConfig, + documentAST: DocumentNode, + options?: Options, +): GraphQLSchemaNormalizedConfig; +export {}; diff --git a/node_modules/graphql/utilities/extendSchema.js b/node_modules/graphql/utilities/extendSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..20191ece5fcae2889fecafe5452557ca1f00ad2f --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.js @@ -0,0 +1,923 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.extendSchema = extendSchema; +exports.extendSchemaImpl = extendSchemaImpl; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _keyMap = require('../jsutils/keyMap.js'); + +var _mapValue = require('../jsutils/mapValue.js'); + +var _kinds = require('../language/kinds.js'); + +var _predicates = require('../language/predicates.js'); + +var _definition = require('../type/definition.js'); + +var _directives = require('../type/directives.js'); + +var _introspection = require('../type/introspection.js'); + +var _scalars = require('../type/scalars.js'); + +var _schema = require('../type/schema.js'); + +var _validate = require('../validation/validate.js'); + +var _values = require('../execution/values.js'); + +var _valueFromAST = require('./valueFromAST.js'); + +/** @category Schema Construction */ + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * @param schema - GraphQL schema to use. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns A new schema with the extensions and definitions applied. + * @example + * ```ts + * // Extend a schema with new fields and types. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const extensionAST = parse(` + * extend type Query { + * farewell: String + * } + * + * type Review { + * body: String + * } + * `); + * + * const extendedSchema = extendSchema(schema, extensionAST); + * + * schema.getType('Review'); // => undefined + * extendedSchema.getType('Review')?.name; // => 'Review' + * Object.keys(extendedSchema.getQueryType().getFields()); // => ['greeting', 'farewell'] + * ``` + * @example + * ```ts + * // This variant bypasses validation for an otherwise invalid extension. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const invalidExtension = parse(` + * extend type Missing { + * field: String + * } + * `); + * + * extendSchema(schema, invalidExtension); // throws an error + * extendSchema(schema, invalidExtension, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +function extendSchema(schema, documentAST, options) { + (0, _schema.assertSchema)(schema); + (documentAST != null && documentAST.kind === _kinds.Kind.DOCUMENT) || + (0, _devAssert.devAssert)(false, 'Must provide valid Document AST.'); + + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + (0, _validate.assertValidSDLExtension)(documentAST, schema); + } + + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig + ? schema + : new _schema.GraphQLSchema(extendedConfig); +} +/** @internal */ + +function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; + + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); + const directiveExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. + + const schemaExtensions = []; + + for (const def of documentAST.definitions) { + if (def.kind === _kinds.Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === _kinds.Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if ((0, _predicates.isTypeDefinitionNode)(def)) { + typeDefs.push(def); + } else if ((0, _predicates.isTypeExtensionNode)(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } else if (def.kind === _kinds.Kind.DIRECTIVE_EXTENSION) { + const extendedDirectiveName = def.name.value; + const existingDirectiveExtensions = + directiveExtensionsMap[extendedDirectiveName]; + directiveExtensionsMap[extendedDirectiveName] = + existingDirectiveExtensions + ? existingDirectiveExtensions.concat([def]) + : [def]; + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + if ( + Object.keys(typeExtensionsMap).length === 0 && + typeDefs.length === 0 && + Object.keys(directiveExtensionsMap).length === 0 && + directiveDefs.length === 0 && + schemaExtensions.length === 0 && + schemaDef == null + ) { + return schemaConfig; + } + + const typeMap = Object.create(null); + + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } + + for (const typeNode of typeDefs) { + var _stdTypeMap$name; + + const name = typeNode.name.value; + typeMap[name] = + (_stdTypeMap$name = stdTypeMap[name]) !== null && + _stdTypeMap$name !== void 0 + ? _stdTypeMap$name + : buildType(typeNode); + } + + const directiveMap = Object.create(null); + + for (const existingDirective of schemaConfig.directives) { + directiveMap[existingDirective.name] = extendDirective(existingDirective); + } + + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: + schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions), + }; // Then produce and return a Schema config with these types. + + const directives = Object.values(directiveMap); // will be `Array` + + return { + description: + (_schemaDef = schemaDef) === null || _schemaDef === void 0 + ? void 0 + : (_schemaDef$descriptio = _schemaDef.description) === null || + _schemaDef$descriptio === void 0 + ? void 0 + : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [ + ...directives.map(replaceDirective), + ...directiveDefs.map(buildDirective), + ], + extensions: Object.create(null), + astNode: + (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 + ? _schemaDef2 + : schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: + (_options$assumeValid = + options === null || options === void 0 + ? void 0 + : options.assumeValid) !== null && _options$assumeValid !== void 0 + ? _options$assumeValid + : false, + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } + + if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } + + function replaceDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + args: (0, _mapValue.mapValue)(config.args, extendArg), + }); + } + + function extendNamedType(type) { + if ( + (0, _introspection.isIntrospectionType)(type) || + (0, _scalars.isSpecifiedScalarType)(type) + ) { + // Builtin types are not extended. + return type; + } + + if ((0, _definition.isScalarType)(type)) { + return extendScalarType(type); + } + + if ((0, _definition.isObjectType)(type)) { + return extendObjectType(type); + } + + if ((0, _definition.isInterfaceType)(type)) { + return extendInterfaceType(type); + } + + if ((0, _definition.isUnionType)(type)) { + return extendUnionType(type); + } + + if ((0, _definition.isEnumType)(type)) { + return extendEnumType(type); + } + + if ((0, _definition.isInputObjectType)(type)) { + return extendInputObjectType(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); + } + + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co !== void 0 + ? _typeExtensionsMap$co + : []; + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, (field) => ({ + ...field, + type: replaceType(field.type), + })), + ...buildInputFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendEnumType(type) { + var _typeExtensionsMap$ty; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && + _typeExtensionsMap$ty !== void 0 + ? _typeExtensionsMap$ty + : []; + return new _definition.GraphQLEnumType({ + ...config, + values: { ...config.values, ...buildEnumValueMap(extensions) }, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendScalarType(type) { + var _typeExtensionsMap$co2; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co2 !== void 0 + ? _typeExtensionsMap$co2 + : []; + let specifiedByURL = config.specifiedByURL; + + for (const extensionNode of extensions) { + var _getSpecifiedByURL; + + specifiedByURL = + (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && + _getSpecifiedByURL !== void 0 + ? _getSpecifiedByURL + : specifiedByURL; + } + + return new _definition.GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendObjectType(type) { + var _typeExtensionsMap$co3; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co3 !== void 0 + ? _typeExtensionsMap$co3 + : []; + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co4 !== void 0 + ? _typeExtensionsMap$co4 + : []; + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...(0, _mapValue.mapValue)(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendUnionType(type) { + var _typeExtensionsMap$co5; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co5 !== void 0 + ? _typeExtensionsMap$co5 + : []; + return new _definition.GraphQLUnionType({ + ...config, + types: () => [ + ...type.getTypes().map(replaceNamedType), + ...buildUnionTypes(extensions), + ], + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: field.args && (0, _mapValue.mapValue)(field.args, extendArg), + }; + } + + function extendArg(arg) { + return { ...arg, type: replaceType(arg.type) }; + } + + function getOperationTypes(nodes) { + const opTypes = {}; + + for (const node of nodes) { + var _node$operationTypes; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = + /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } + + return opTypes; + } + + function extendDirective(directive) { + var _directiveExtensionsM, _config$deprecationRe; + + const config = directive.toConfig(); + const extensions = + (_directiveExtensionsM = directiveExtensionsMap[config.name]) !== null && + _directiveExtensionsM !== void 0 + ? _directiveExtensionsM + : []; + const deprecationReason = + (_config$deprecationRe = config.deprecationReason) !== null && + _config$deprecationRe !== void 0 + ? _config$deprecationRe + : extensions + .map((ext) => getDeprecationReason(ext)) + .find((reason) => reason != null); + return new _directives.GraphQLDirective({ + ...config, + deprecationReason, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function getNamedType(node) { + var _stdTypeMap$name2; + + const name = node.name.value; + const type = + (_stdTypeMap$name2 = stdTypeMap[name]) !== null && + _stdTypeMap$name2 !== void 0 + ? _stdTypeMap$name2 + : typeMap[name]; + + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } + + return type; + } + + function getWrappedType(node) { + if (node.kind === _kinds.Kind.LIST_TYPE) { + return new _definition.GraphQLList(getWrappedType(node.type)); + } + + if (node.kind === _kinds.Kind.NON_NULL_TYPE) { + return new _definition.GraphQLNonNull(getWrappedType(node.type)); + } + + return getNamedType(node); + } + + function buildDirective(node) { + var _directiveExtensionsM2, _getDeprecationReason, _node$description; + + const extensions = + (_directiveExtensionsM2 = directiveExtensionsMap[node.name.value]) !== + null && _directiveExtensionsM2 !== void 0 + ? _directiveExtensionsM2 + : []; + const deprecationReason = + (_getDeprecationReason = getDeprecationReason(node)) !== null && + _getDeprecationReason !== void 0 + ? _getDeprecationReason + : extensions + .map((ext) => getDeprecationReason(ext)) + .find((reason) => reason != null); + return new _directives.GraphQLDirective({ + name: node.name.value, + description: + (_node$description = node.description) === null || + _node$description === void 0 + ? void 0 + : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ value }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + deprecationReason, + astNode: node, + extensionASTNodes: extensions, + }); + } + + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + + for (const node of nodes) { + var _node$fields; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = + /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + + for (const field of nodeFields) { + var _field$description; + + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: + (_field$description = field.description) === null || + _field$description === void 0 + ? void 0 + : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + + return fieldConfigMap; + } + + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = + /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); + + for (const arg of argsNodes) { + var _arg$description; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: + (_arg$description = arg.description) === null || + _arg$description === void 0 + ? void 0 + : _arg$description.value, + defaultValue: (0, _valueFromAST.valueFromAST)(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg, + }; + } + + return argConfigMap; + } + + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + + for (const node of nodes) { + var _node$fields2; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = + /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 + ? _node$fields2 + : []; + + for (const field of fieldsNodes) { + var _field$description2; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: + (_field$description2 = field.description) === null || + _field$description2 === void 0 + ? void 0 + : _field$description2.value, + defaultValue: (0, _valueFromAST.valueFromAST)( + field.defaultValue, + type, + ), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + + return inputFieldMap; + } + + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + + for (const node of nodes) { + var _node$values; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = + /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + + for (const value of valuesNodes) { + var _value$description; + + enumValueMap[value.name.value] = { + description: + (_value$description = value.description) === null || + _value$description === void 0 + ? void 0 + : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + } + + return enumValueMap; + } + + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$interfaces$map, _node$interfaces; + + return ( + /* c8 ignore next */ + (_node$interfaces$map = + (_node$interfaces = node.interfaces) === null || + _node$interfaces === void 0 + ? void 0 + : _node$interfaces.map(getNamedType)) !== null && + _node$interfaces$map !== void 0 + ? _node$interfaces$map + : [] + ); + }, + ); + } + + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$types$map, _node$types; + + return ( + /* c8 ignore next */ + (_node$types$map = + (_node$types = node.types) === null || _node$types === void 0 + ? void 0 + : _node$types.map(getNamedType)) !== null && + _node$types$map !== void 0 + ? _node$types$map + : [] + ); + }, + ); + } + + function buildType(astNode) { + var _typeExtensionsMap$na; + + const name = astNode.name.value; + const extensionASTNodes = + (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && + _typeExtensionsMap$na !== void 0 + ? _typeExtensionsMap$na + : []; + + switch (astNode.kind) { + case _kinds.Kind.OBJECT_TYPE_DEFINITION: { + var _astNode$description; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLObjectType({ + name, + description: + (_astNode$description = astNode.description) === null || + _astNode$description === void 0 + ? void 0 + : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: { + var _astNode$description2; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInterfaceType({ + name, + description: + (_astNode$description2 = astNode.description) === null || + _astNode$description2 === void 0 + ? void 0 + : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case _kinds.Kind.ENUM_TYPE_DEFINITION: { + var _astNode$description3; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLEnumType({ + name, + description: + (_astNode$description3 = astNode.description) === null || + _astNode$description3 === void 0 + ? void 0 + : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case _kinds.Kind.UNION_TYPE_DEFINITION: { + var _astNode$description4; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLUnionType({ + name, + description: + (_astNode$description4 = astNode.description) === null || + _astNode$description4 === void 0 + ? void 0 + : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes, + }); + } + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: { + var _astNode$description5; + + return new _definition.GraphQLScalarType({ + name, + description: + (_astNode$description5 = astNode.description) === null || + _astNode$description5 === void 0 + ? void 0 + : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes, + }); + } + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: { + var _astNode$description6; + + const allNodes = [astNode, ...extensionASTNodes]; + return new _definition.GraphQLInputObjectType({ + name, + description: + (_astNode$description6 = astNode.description) === null || + _astNode$description6 === void 0 + ? void 0 + : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + isOneOf: isOneOf(astNode), + }); + } + } + } +} + +const stdTypeMap = (0, _keyMap.keyMap)( + [..._scalars.specifiedScalarTypes, ..._introspection.introspectionTypes], + (type) => type.name, +); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + * + * @internal + */ + +function getDeprecationReason(node) { + const deprecated = (0, _values.getDirectiveValues)( + _directives.GraphQLDeprecatedDirective, + node, + ); // @ts-expect-error validated by `getDirectiveValues` + + return deprecated === null || deprecated === void 0 + ? void 0 + : deprecated.reason; +} +/** + * Given a scalar node, returns the string value for the specifiedByURL. + * + * @internal + */ + +function getSpecifiedByURL(node) { + const specifiedBy = (0, _values.getDirectiveValues)( + _directives.GraphQLSpecifiedByDirective, + node, + ); // @ts-expect-error validated by `getDirectiveValues` + + return specifiedBy === null || specifiedBy === void 0 + ? void 0 + : specifiedBy.url; +} +/** + * Given an input object node, returns if the node should be OneOf. + * + * @internal + */ + +function isOneOf(node) { + return Boolean( + (0, _values.getDirectiveValues)(_directives.GraphQLOneOfDirective, node), + ); +} diff --git a/node_modules/graphql/utilities/extendSchema.mjs b/node_modules/graphql/utilities/extendSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..59c0fa4640159e6960ba77424010a1daec1b26ba --- /dev/null +++ b/node_modules/graphql/utilities/extendSchema.mjs @@ -0,0 +1,912 @@ +/** @category Schema Construction */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { keyMap } from '../jsutils/keyMap.mjs'; +import { mapValue } from '../jsutils/mapValue.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../language/predicates.mjs'; +import { + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLScalarType, + GraphQLUnionType, + isEnumType, + isInputObjectType, + isInterfaceType, + isListType, + isNonNullType, + isObjectType, + isScalarType, + isUnionType, +} from '../type/definition.mjs'; +import { + GraphQLDeprecatedDirective, + GraphQLDirective, + GraphQLOneOfDirective, + GraphQLSpecifiedByDirective, +} from '../type/directives.mjs'; +import { + introspectionTypes, + isIntrospectionType, +} from '../type/introspection.mjs'; +import { + isSpecifiedScalarType, + specifiedScalarTypes, +} from '../type/scalars.mjs'; +import { assertSchema, GraphQLSchema } from '../type/schema.mjs'; +import { assertValidSDLExtension } from '../validation/validate.mjs'; +import { getDirectiveValues } from '../execution/values.mjs'; +import { valueFromAST } from './valueFromAST.mjs'; + +/** + * Produces a new schema given an existing schema and a document which may + * contain GraphQL type extensions and definitions. The original schema will + * remain unaltered. + * + * Because a schema represents a graph of references, a schema cannot be + * extended without effectively making an entire copy. We do not know until it's + * too late if subgraphs remain unchanged. + * + * This algorithm copies the provided schema, applying extensions while + * producing the copy. The original schema remains unaltered. + * @param schema - GraphQL schema to use. + * @param documentAST - The parsed GraphQL document AST. + * @param options - Optional configuration for this operation. + * @returns A new schema with the extensions and definitions applied. + * @example + * ```ts + * // Extend a schema with new fields and types. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const extensionAST = parse(` + * extend type Query { + * farewell: String + * } + * + * type Review { + * body: String + * } + * `); + * + * const extendedSchema = extendSchema(schema, extensionAST); + * + * schema.getType('Review'); // => undefined + * extendedSchema.getType('Review')?.name; // => 'Review' + * Object.keys(extendedSchema.getQueryType().getFields()); // => ['greeting', 'farewell'] + * ``` + * @example + * ```ts + * // This variant bypasses validation for an otherwise invalid extension. + * import { parse } from 'graphql/language'; + * import { buildSchema, extendSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const invalidExtension = parse(` + * extend type Missing { + * field: String + * } + * `); + * + * extendSchema(schema, invalidExtension); // throws an error + * extendSchema(schema, invalidExtension, { + * assumeValid: true, + * assumeValidSDL: true, + * }); // does not throw + * ``` + */ +export function extendSchema(schema, documentAST, options) { + assertSchema(schema); + (documentAST != null && documentAST.kind === Kind.DOCUMENT) || + devAssert(false, 'Must provide valid Document AST.'); + + if ( + (options === null || options === void 0 ? void 0 : options.assumeValid) !== + true && + (options === null || options === void 0 + ? void 0 + : options.assumeValidSDL) !== true + ) { + assertValidSDLExtension(documentAST, schema); + } + + const schemaConfig = schema.toConfig(); + const extendedConfig = extendSchemaImpl(schemaConfig, documentAST, options); + return schemaConfig === extendedConfig + ? schema + : new GraphQLSchema(extendedConfig); +} +/** @internal */ + +export function extendSchemaImpl(schemaConfig, documentAST, options) { + var _schemaDef, _schemaDef$descriptio, _schemaDef2, _options$assumeValid; + + // Collect the type definitions and extensions found in the document. + const typeDefs = []; + const typeExtensionsMap = Object.create(null); + const directiveExtensionsMap = Object.create(null); // New directives and types are separate because a directives and types can + // have the same name. For example, a type named "skip". + + const directiveDefs = []; + let schemaDef; // Schema extensions are collected which may add additional operation types. + + const schemaExtensions = []; + + for (const def of documentAST.definitions) { + if (def.kind === Kind.SCHEMA_DEFINITION) { + schemaDef = def; + } else if (def.kind === Kind.SCHEMA_EXTENSION) { + schemaExtensions.push(def); + } else if (isTypeDefinitionNode(def)) { + typeDefs.push(def); + } else if (isTypeExtensionNode(def)) { + const extendedTypeName = def.name.value; + const existingTypeExtensions = typeExtensionsMap[extendedTypeName]; + typeExtensionsMap[extendedTypeName] = existingTypeExtensions + ? existingTypeExtensions.concat([def]) + : [def]; + } else if (def.kind === Kind.DIRECTIVE_DEFINITION) { + directiveDefs.push(def); + } else if (def.kind === Kind.DIRECTIVE_EXTENSION) { + const extendedDirectiveName = def.name.value; + const existingDirectiveExtensions = + directiveExtensionsMap[extendedDirectiveName]; + directiveExtensionsMap[extendedDirectiveName] = + existingDirectiveExtensions + ? existingDirectiveExtensions.concat([def]) + : [def]; + } + } // If this document contains no new types, extensions, or directives then + // return the same unmodified GraphQLSchema instance. + + if ( + Object.keys(typeExtensionsMap).length === 0 && + typeDefs.length === 0 && + Object.keys(directiveExtensionsMap).length === 0 && + directiveDefs.length === 0 && + schemaExtensions.length === 0 && + schemaDef == null + ) { + return schemaConfig; + } + + const typeMap = Object.create(null); + + for (const existingType of schemaConfig.types) { + typeMap[existingType.name] = extendNamedType(existingType); + } + + for (const typeNode of typeDefs) { + var _stdTypeMap$name; + + const name = typeNode.name.value; + typeMap[name] = + (_stdTypeMap$name = stdTypeMap[name]) !== null && + _stdTypeMap$name !== void 0 + ? _stdTypeMap$name + : buildType(typeNode); + } + + const directiveMap = Object.create(null); + + for (const existingDirective of schemaConfig.directives) { + directiveMap[existingDirective.name] = extendDirective(existingDirective); + } + + const operationTypes = { + // Get the extended root operation types. + query: schemaConfig.query && replaceNamedType(schemaConfig.query), + mutation: schemaConfig.mutation && replaceNamedType(schemaConfig.mutation), + subscription: + schemaConfig.subscription && replaceNamedType(schemaConfig.subscription), + // Then, incorporate schema definition and all schema extensions. + ...(schemaDef && getOperationTypes([schemaDef])), + ...getOperationTypes(schemaExtensions), + }; // Then produce and return a Schema config with these types. + + const directives = Object.values(directiveMap); // will be `Array` + + return { + description: + (_schemaDef = schemaDef) === null || _schemaDef === void 0 + ? void 0 + : (_schemaDef$descriptio = _schemaDef.description) === null || + _schemaDef$descriptio === void 0 + ? void 0 + : _schemaDef$descriptio.value, + ...operationTypes, + types: Object.values(typeMap), + directives: [ + ...directives.map(replaceDirective), + ...directiveDefs.map(buildDirective), + ], + extensions: Object.create(null), + astNode: + (_schemaDef2 = schemaDef) !== null && _schemaDef2 !== void 0 + ? _schemaDef2 + : schemaConfig.astNode, + extensionASTNodes: schemaConfig.extensionASTNodes.concat(schemaExtensions), + assumeValid: + (_options$assumeValid = + options === null || options === void 0 + ? void 0 + : options.assumeValid) !== null && _options$assumeValid !== void 0 + ? _options$assumeValid + : false, + }; // Below are functions used for producing this schema that have closed over + // this scope and have access to the schema, cache, and newly defined types. + + function replaceType(type) { + if (isListType(type)) { + // @ts-expect-error + return new GraphQLList(replaceType(type.ofType)); + } + + if (isNonNullType(type)) { + // @ts-expect-error + return new GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + // Note: While this could make early assertions to get the correctly + // typed values, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + return typeMap[type.name]; + } + + function replaceDirective(directive) { + const config = directive.toConfig(); + return new GraphQLDirective({ + ...config, + args: mapValue(config.args, extendArg), + }); + } + + function extendNamedType(type) { + if (isIntrospectionType(type) || isSpecifiedScalarType(type)) { + // Builtin types are not extended. + return type; + } + + if (isScalarType(type)) { + return extendScalarType(type); + } + + if (isObjectType(type)) { + return extendObjectType(type); + } + + if (isInterfaceType(type)) { + return extendInterfaceType(type); + } + + if (isUnionType(type)) { + return extendUnionType(type); + } + + if (isEnumType(type)) { + return extendEnumType(type); + } + + if (isInputObjectType(type)) { + return extendInputObjectType(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible type definition nodes have been considered. + + false || invariant(false, 'Unexpected type: ' + inspect(type)); + } + + function extendInputObjectType(type) { + var _typeExtensionsMap$co; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co !== void 0 + ? _typeExtensionsMap$co + : []; + return new GraphQLInputObjectType({ + ...config, + fields: () => ({ + ...mapValue(config.fields, (field) => ({ + ...field, + type: replaceType(field.type), + })), + ...buildInputFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendEnumType(type) { + var _typeExtensionsMap$ty; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$ty = typeExtensionsMap[type.name]) !== null && + _typeExtensionsMap$ty !== void 0 + ? _typeExtensionsMap$ty + : []; + return new GraphQLEnumType({ + ...config, + values: { ...config.values, ...buildEnumValueMap(extensions) }, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendScalarType(type) { + var _typeExtensionsMap$co2; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co2 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co2 !== void 0 + ? _typeExtensionsMap$co2 + : []; + let specifiedByURL = config.specifiedByURL; + + for (const extensionNode of extensions) { + var _getSpecifiedByURL; + + specifiedByURL = + (_getSpecifiedByURL = getSpecifiedByURL(extensionNode)) !== null && + _getSpecifiedByURL !== void 0 + ? _getSpecifiedByURL + : specifiedByURL; + } + + return new GraphQLScalarType({ + ...config, + specifiedByURL, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendObjectType(type) { + var _typeExtensionsMap$co3; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co3 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co3 !== void 0 + ? _typeExtensionsMap$co3 + : []; + return new GraphQLObjectType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...mapValue(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendInterfaceType(type) { + var _typeExtensionsMap$co4; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co4 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co4 !== void 0 + ? _typeExtensionsMap$co4 + : []; + return new GraphQLInterfaceType({ + ...config, + interfaces: () => [ + ...type.getInterfaces().map(replaceNamedType), + ...buildInterfaces(extensions), + ], + fields: () => ({ + ...mapValue(config.fields, extendField), + ...buildFieldMap(extensions), + }), + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendUnionType(type) { + var _typeExtensionsMap$co5; + + const config = type.toConfig(); + const extensions = + (_typeExtensionsMap$co5 = typeExtensionsMap[config.name]) !== null && + _typeExtensionsMap$co5 !== void 0 + ? _typeExtensionsMap$co5 + : []; + return new GraphQLUnionType({ + ...config, + types: () => [ + ...type.getTypes().map(replaceNamedType), + ...buildUnionTypes(extensions), + ], + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function extendField(field) { + return { + ...field, + type: replaceType(field.type), + args: field.args && mapValue(field.args, extendArg), + }; + } + + function extendArg(arg) { + return { ...arg, type: replaceType(arg.type) }; + } + + function getOperationTypes(nodes) { + const opTypes = {}; + + for (const node of nodes) { + var _node$operationTypes; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const operationTypesNodes = + /* c8 ignore next */ + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + + for (const operationType of operationTypesNodes) { + // Note: While this could make early assertions to get the correctly + // typed values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + opTypes[operationType.operation] = getNamedType(operationType.type); + } + } + + return opTypes; + } + + function extendDirective(directive) { + var _directiveExtensionsM, _config$deprecationRe; + + const config = directive.toConfig(); + const extensions = + (_directiveExtensionsM = directiveExtensionsMap[config.name]) !== null && + _directiveExtensionsM !== void 0 + ? _directiveExtensionsM + : []; + const deprecationReason = + (_config$deprecationRe = config.deprecationReason) !== null && + _config$deprecationRe !== void 0 + ? _config$deprecationRe + : extensions + .map((ext) => getDeprecationReason(ext)) + .find((reason) => reason != null); + return new GraphQLDirective({ + ...config, + deprecationReason, + extensionASTNodes: config.extensionASTNodes.concat(extensions), + }); + } + + function getNamedType(node) { + var _stdTypeMap$name2; + + const name = node.name.value; + const type = + (_stdTypeMap$name2 = stdTypeMap[name]) !== null && + _stdTypeMap$name2 !== void 0 + ? _stdTypeMap$name2 + : typeMap[name]; + + if (type === undefined) { + throw new Error(`Unknown type: "${name}".`); + } + + return type; + } + + function getWrappedType(node) { + if (node.kind === Kind.LIST_TYPE) { + return new GraphQLList(getWrappedType(node.type)); + } + + if (node.kind === Kind.NON_NULL_TYPE) { + return new GraphQLNonNull(getWrappedType(node.type)); + } + + return getNamedType(node); + } + + function buildDirective(node) { + var _directiveExtensionsM2, _getDeprecationReason, _node$description; + + const extensions = + (_directiveExtensionsM2 = directiveExtensionsMap[node.name.value]) !== + null && _directiveExtensionsM2 !== void 0 + ? _directiveExtensionsM2 + : []; + const deprecationReason = + (_getDeprecationReason = getDeprecationReason(node)) !== null && + _getDeprecationReason !== void 0 + ? _getDeprecationReason + : extensions + .map((ext) => getDeprecationReason(ext)) + .find((reason) => reason != null); + return new GraphQLDirective({ + name: node.name.value, + description: + (_node$description = node.description) === null || + _node$description === void 0 + ? void 0 + : _node$description.value, + // @ts-expect-error + locations: node.locations.map(({ value }) => value), + isRepeatable: node.repeatable, + args: buildArgumentMap(node.arguments), + deprecationReason, + astNode: node, + extensionASTNodes: extensions, + }); + } + + function buildFieldMap(nodes) { + const fieldConfigMap = Object.create(null); + + for (const node of nodes) { + var _node$fields; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const nodeFields = + /* c8 ignore next */ + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + + for (const field of nodeFields) { + var _field$description; + + fieldConfigMap[field.name.value] = { + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + type: getWrappedType(field.type), + description: + (_field$description = field.description) === null || + _field$description === void 0 + ? void 0 + : _field$description.value, + args: buildArgumentMap(field.arguments), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + + return fieldConfigMap; + } + + function buildArgumentMap(args) { + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const argsNodes = + /* c8 ignore next */ + args !== null && args !== void 0 ? args : []; + const argConfigMap = Object.create(null); + + for (const arg of argsNodes) { + var _arg$description; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(arg.type); + argConfigMap[arg.name.value] = { + type, + description: + (_arg$description = arg.description) === null || + _arg$description === void 0 + ? void 0 + : _arg$description.value, + defaultValue: valueFromAST(arg.defaultValue, type), + deprecationReason: getDeprecationReason(arg), + astNode: arg, + }; + } + + return argConfigMap; + } + + function buildInputFieldMap(nodes) { + const inputFieldMap = Object.create(null); + + for (const node of nodes) { + var _node$fields2; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const fieldsNodes = + /* c8 ignore next */ + (_node$fields2 = node.fields) !== null && _node$fields2 !== void 0 + ? _node$fields2 + : []; + + for (const field of fieldsNodes) { + var _field$description2; + + // Note: While this could make assertions to get the correctly typed + // value, that would throw immediately while type system validation + // with validateSchema() will produce more actionable results. + const type = getWrappedType(field.type); + inputFieldMap[field.name.value] = { + type, + description: + (_field$description2 = field.description) === null || + _field$description2 === void 0 + ? void 0 + : _field$description2.value, + defaultValue: valueFromAST(field.defaultValue, type), + deprecationReason: getDeprecationReason(field), + astNode: field, + }; + } + } + + return inputFieldMap; + } + + function buildEnumValueMap(nodes) { + const enumValueMap = Object.create(null); + + for (const node of nodes) { + var _node$values; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + const valuesNodes = + /* c8 ignore next */ + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + + for (const value of valuesNodes) { + var _value$description; + + enumValueMap[value.name.value] = { + description: + (_value$description = value.description) === null || + _value$description === void 0 + ? void 0 + : _value$description.value, + deprecationReason: getDeprecationReason(value), + astNode: value, + }; + } + } + + return enumValueMap; + } + + function buildInterfaces(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$interfaces$map, _node$interfaces; + + return ( + /* c8 ignore next */ + (_node$interfaces$map = + (_node$interfaces = node.interfaces) === null || + _node$interfaces === void 0 + ? void 0 + : _node$interfaces.map(getNamedType)) !== null && + _node$interfaces$map !== void 0 + ? _node$interfaces$map + : [] + ); + }, + ); + } + + function buildUnionTypes(nodes) { + // Note: While this could make assertions to get the correctly typed + // values below, that would throw immediately while type system + // validation with validateSchema() will produce more actionable results. + // @ts-expect-error + return nodes.flatMap( + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + (node) => { + var _node$types$map, _node$types; + + return ( + /* c8 ignore next */ + (_node$types$map = + (_node$types = node.types) === null || _node$types === void 0 + ? void 0 + : _node$types.map(getNamedType)) !== null && + _node$types$map !== void 0 + ? _node$types$map + : [] + ); + }, + ); + } + + function buildType(astNode) { + var _typeExtensionsMap$na; + + const name = astNode.name.value; + const extensionASTNodes = + (_typeExtensionsMap$na = typeExtensionsMap[name]) !== null && + _typeExtensionsMap$na !== void 0 + ? _typeExtensionsMap$na + : []; + + switch (astNode.kind) { + case Kind.OBJECT_TYPE_DEFINITION: { + var _astNode$description; + + const allNodes = [astNode, ...extensionASTNodes]; + return new GraphQLObjectType({ + name, + description: + (_astNode$description = astNode.description) === null || + _astNode$description === void 0 + ? void 0 + : _astNode$description.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case Kind.INTERFACE_TYPE_DEFINITION: { + var _astNode$description2; + + const allNodes = [astNode, ...extensionASTNodes]; + return new GraphQLInterfaceType({ + name, + description: + (_astNode$description2 = astNode.description) === null || + _astNode$description2 === void 0 + ? void 0 + : _astNode$description2.value, + interfaces: () => buildInterfaces(allNodes), + fields: () => buildFieldMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case Kind.ENUM_TYPE_DEFINITION: { + var _astNode$description3; + + const allNodes = [astNode, ...extensionASTNodes]; + return new GraphQLEnumType({ + name, + description: + (_astNode$description3 = astNode.description) === null || + _astNode$description3 === void 0 + ? void 0 + : _astNode$description3.value, + values: buildEnumValueMap(allNodes), + astNode, + extensionASTNodes, + }); + } + + case Kind.UNION_TYPE_DEFINITION: { + var _astNode$description4; + + const allNodes = [astNode, ...extensionASTNodes]; + return new GraphQLUnionType({ + name, + description: + (_astNode$description4 = astNode.description) === null || + _astNode$description4 === void 0 + ? void 0 + : _astNode$description4.value, + types: () => buildUnionTypes(allNodes), + astNode, + extensionASTNodes, + }); + } + + case Kind.SCALAR_TYPE_DEFINITION: { + var _astNode$description5; + + return new GraphQLScalarType({ + name, + description: + (_astNode$description5 = astNode.description) === null || + _astNode$description5 === void 0 + ? void 0 + : _astNode$description5.value, + specifiedByURL: getSpecifiedByURL(astNode), + astNode, + extensionASTNodes, + }); + } + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: { + var _astNode$description6; + + const allNodes = [astNode, ...extensionASTNodes]; + return new GraphQLInputObjectType({ + name, + description: + (_astNode$description6 = astNode.description) === null || + _astNode$description6 === void 0 + ? void 0 + : _astNode$description6.value, + fields: () => buildInputFieldMap(allNodes), + astNode, + extensionASTNodes, + isOneOf: isOneOf(astNode), + }); + } + } + } +} +const stdTypeMap = keyMap( + [...specifiedScalarTypes, ...introspectionTypes], + (type) => type.name, +); +/** + * Given a field or enum value node, returns the string value for the + * deprecation reason. + * + * @internal + */ + +function getDeprecationReason(node) { + const deprecated = getDirectiveValues(GraphQLDeprecatedDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return deprecated === null || deprecated === void 0 + ? void 0 + : deprecated.reason; +} +/** + * Given a scalar node, returns the string value for the specifiedByURL. + * + * @internal + */ + +function getSpecifiedByURL(node) { + const specifiedBy = getDirectiveValues(GraphQLSpecifiedByDirective, node); // @ts-expect-error validated by `getDirectiveValues` + + return specifiedBy === null || specifiedBy === void 0 + ? void 0 + : specifiedBy.url; +} +/** + * Given an input object node, returns if the node should be OneOf. + * + * @internal + */ + +function isOneOf(node) { + return Boolean(getDirectiveValues(GraphQLOneOfDirective, node)); +} diff --git a/node_modules/graphql/utilities/findBreakingChanges.d.ts b/node_modules/graphql/utilities/findBreakingChanges.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c2107ea31c1b063705d47bbe9d1e20e604ee66ea --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.d.ts @@ -0,0 +1,148 @@ +/** @category Schema Changes */ +import type { GraphQLSchema } from '../type/schema'; +/** Categories of schema changes that may break existing operations. */ +declare enum BreakingChangeType { + /** Breaking change code for type removed. */ + TYPE_REMOVED = 'TYPE_REMOVED', + /** Breaking change code for type changed kind. */ + TYPE_CHANGED_KIND = 'TYPE_CHANGED_KIND', + /** Breaking change code for type removed from union. */ + TYPE_REMOVED_FROM_UNION = 'TYPE_REMOVED_FROM_UNION', + /** Breaking change code for value removed from enum. */ + VALUE_REMOVED_FROM_ENUM = 'VALUE_REMOVED_FROM_ENUM', + /** Breaking change code for required input field added. */ + REQUIRED_INPUT_FIELD_ADDED = 'REQUIRED_INPUT_FIELD_ADDED', + /** Breaking change code for implemented interface removed. */ + IMPLEMENTED_INTERFACE_REMOVED = 'IMPLEMENTED_INTERFACE_REMOVED', + /** Breaking change code for field removed. */ + FIELD_REMOVED = 'FIELD_REMOVED', + /** Breaking change code for field changed kind. */ + FIELD_CHANGED_KIND = 'FIELD_CHANGED_KIND', + /** Breaking change code for required arg added. */ + REQUIRED_ARG_ADDED = 'REQUIRED_ARG_ADDED', + /** Breaking change code for arg removed. */ + ARG_REMOVED = 'ARG_REMOVED', + /** Breaking change code for arg changed kind. */ + ARG_CHANGED_KIND = 'ARG_CHANGED_KIND', + /** Breaking change code for directive removed. */ + DIRECTIVE_REMOVED = 'DIRECTIVE_REMOVED', + /** Breaking change code for directive arg removed. */ + DIRECTIVE_ARG_REMOVED = 'DIRECTIVE_ARG_REMOVED', + /** Breaking change code for required directive arg added. */ + REQUIRED_DIRECTIVE_ARG_ADDED = 'REQUIRED_DIRECTIVE_ARG_ADDED', + /** Breaking change code for directive repeatable removed. */ + DIRECTIVE_REPEATABLE_REMOVED = 'DIRECTIVE_REPEATABLE_REMOVED', + /** Breaking change code for directive location removed. */ + DIRECTIVE_LOCATION_REMOVED = 'DIRECTIVE_LOCATION_REMOVED', +} +export { BreakingChangeType }; +/** Categories of schema changes that may be dangerous for existing operations. */ +declare enum DangerousChangeType { + /** Dangerous change code for value added to enum. */ + VALUE_ADDED_TO_ENUM = 'VALUE_ADDED_TO_ENUM', + /** Dangerous change code for type added to union. */ + TYPE_ADDED_TO_UNION = 'TYPE_ADDED_TO_UNION', + /** Dangerous change code for optional input field added. */ + OPTIONAL_INPUT_FIELD_ADDED = 'OPTIONAL_INPUT_FIELD_ADDED', + /** Dangerous change code for optional arg added. */ + OPTIONAL_ARG_ADDED = 'OPTIONAL_ARG_ADDED', + /** Dangerous change code for implemented interface added. */ + IMPLEMENTED_INTERFACE_ADDED = 'IMPLEMENTED_INTERFACE_ADDED', + /** Dangerous change code for arg default value change. */ + ARG_DEFAULT_VALUE_CHANGE = 'ARG_DEFAULT_VALUE_CHANGE', +} +export { DangerousChangeType }; +/** Description of a schema change that may break existing operations. */ +export interface BreakingChange { + /** Specific kind of breaking schema change. */ + type: BreakingChangeType; + /** Human-readable description of the breaking schema change. */ + description: string; +} +/** Description of a schema change that may be dangerous for existing operations. */ +export interface DangerousChange { + /** Specific kind of dangerous schema change. */ + type: DangerousChangeType; + /** Human-readable description of the dangerous schema change. */ + description: string; +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Breaking changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findBreakingChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * const newSchema = buildSchema(` + * type User { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const changes = findBreakingChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'FIELD_REMOVED' + * changes[0].description; // matches /User.name was removed/ + * ``` + */ +export declare function findBreakingChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array; +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Dangerous changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findDangerousChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * const newSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const changes = findDangerousChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'VALUE_ADDED_TO_ENUM' + * changes[0].description; // matches /EMPIRE was added/ + * ``` + */ +export declare function findDangerousChanges( + oldSchema: GraphQLSchema, + newSchema: GraphQLSchema, +): Array; diff --git a/node_modules/graphql/utilities/findBreakingChanges.js b/node_modules/graphql/utilities/findBreakingChanges.js new file mode 100644 index 0000000000000000000000000000000000000000..1ecb3ea093bab1cd52bbf8ddb81edac70e493020 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.js @@ -0,0 +1,615 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.DangerousChangeType = exports.BreakingChangeType = void 0; +exports.findBreakingChanges = findBreakingChanges; +exports.findDangerousChanges = findDangerousChanges; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _keyMap = require('../jsutils/keyMap.js'); + +var _printer = require('../language/printer.js'); + +var _definition = require('../type/definition.js'); + +var _scalars = require('../type/scalars.js'); + +var _astFromValue = require('./astFromValue.js'); + +var _sortValueNode = require('./sortValueNode.js'); + +/** @category Schema Changes */ + +/** Categories of schema changes that may break existing operations. */ +var BreakingChangeType; +exports.BreakingChangeType = BreakingChangeType; + +(function (BreakingChangeType) { + BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; + BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; + BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; + BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; + BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = + 'REQUIRED_INPUT_FIELD_ADDED'; + BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = + 'IMPLEMENTED_INTERFACE_REMOVED'; + BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; + BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; + BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; + BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; + BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; + BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; + BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; + BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = + 'REQUIRED_DIRECTIVE_ARG_ADDED'; + BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = + 'DIRECTIVE_REPEATABLE_REMOVED'; + BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = + 'DIRECTIVE_LOCATION_REMOVED'; +})( + BreakingChangeType || (exports.BreakingChangeType = BreakingChangeType = {}), +); + +/** Categories of schema changes that may be dangerous for existing operations. */ +var DangerousChangeType; +exports.DangerousChangeType = DangerousChangeType; + +(function (DangerousChangeType) { + DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; + DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; + DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = + 'OPTIONAL_INPUT_FIELD_ADDED'; + DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; + DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = + 'IMPLEMENTED_INTERFACE_ADDED'; + DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; +})( + DangerousChangeType || + (exports.DangerousChangeType = DangerousChangeType = {}), +); + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Breaking changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findBreakingChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * const newSchema = buildSchema(` + * type User { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const changes = findBreakingChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'FIELD_REMOVED' + * changes[0].description; // matches /User.name was removed/ + * ``` + */ +function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in BreakingChangeType, + ); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Dangerous changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findDangerousChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * const newSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const changes = findDangerousChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'VALUE_ADDED_TO_ENUM' + * changes[0].description; // matches /EMPIRE was added/ + * ``` + */ + +function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in DangerousChangeType, + ); +} + +function findSchemaChanges(oldSchema, newSchema) { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema), + ]; +} + +function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff( + oldSchema.getDirectives(), + newSchema.getDirectives(), + ); + + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.`, + }); + } + + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`, + }); + } + } + + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.`, + }); + } + + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.`, + }); + } + + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.`, + }); + } + } + } + + return schemaChanges; +} + +function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff( + Object.values(oldSchema.getTypeMap()), + Object.values(newSchema.getTypeMap()), + ); + + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: (0, _scalars.isSpecifiedScalarType)(oldType) + ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` + : `${oldType.name} was removed.`, + }); + } + + for (const [oldType, newType] of typesDiff.persisted) { + if ( + (0, _definition.isEnumType)(oldType) && + (0, _definition.isEnumType)(newType) + ) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isUnionType)(oldType) && + (0, _definition.isUnionType)(newType) + ) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isInputObjectType)(oldType) && + (0, _definition.isInputObjectType)(newType) + ) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if ( + (0, _definition.isObjectType)(oldType) && + (0, _definition.isObjectType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if ( + (0, _definition.isInterfaceType)(oldType) && + (0, _definition.isInterfaceType)(newType) + ) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${oldType.name} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } + } + + return schemaChanges; +} + +function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); + + for (const newField of fieldsDiff.added) { + if ((0, _definition.isRequiredInputField)(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.`, + }); + } + } + + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldField.type, + newField.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + + return schemaChanges; +} + +function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.`, + }); + } + + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`, + }); + } + + return schemaChanges; +} + +function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.`, + }); + } + + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.`, + }); + } + + return schemaChanges; +} + +function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`, + }); + } + + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.`, + }); + } + + return schemaChanges; +} + +function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); + + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldField.type, + newField.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + + return schemaChanges; +} + +function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`, + }); + } + + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArg.type, + newArg.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + + `${String(oldArg.type)} to ${String(newArg.type)}.`, + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`, + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); + const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`, + }); + } + } + } + } + + for (const newArg of argsDiff.added) { + if ((0, _definition.isRequiredArgument)(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } + } + + return schemaChanges; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + ((0, _definition.isListType)(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } + + if ((0, _definition.isNonNullType)(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + (0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) + ); + } + + return ( + // if they're both named types, see if their names are equivalent + ((0, _definition.isNamedType)(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if ((0, _definition.isListType)(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + (0, _definition.isListType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) + ); + } + + if ((0, _definition.isNonNullType)(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + ((0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType, + )) || // moving from non-null to nullable of the same underlying type is safe + (!(0, _definition.isNonNullType)(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) + ); + } // if they're both named types, see if their names are equivalent + + return (0, _definition.isNamedType)(newType) && oldType.name === newType.name; +} + +function typeKindName(type) { + if ((0, _definition.isScalarType)(type)) { + return 'a Scalar type'; + } + + if ((0, _definition.isObjectType)(type)) { + return 'an Object type'; + } + + if ((0, _definition.isInterfaceType)(type)) { + return 'an Interface type'; + } + + if ((0, _definition.isUnionType)(type)) { + return 'a Union type'; + } + + if ((0, _definition.isEnumType)(type)) { + return 'an Enum type'; + } + + if ((0, _definition.isInputObjectType)(type)) { + return 'an Input type'; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); +} + +function stringifyValue(value, type) { + const ast = (0, _astFromValue.astFromValue)(value, type); + ast != null || (0, _invariant.invariant)(false); + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(ast)); +} + +function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = (0, _keyMap.keyMap)(oldArray, ({ name }) => name); + const newMap = (0, _keyMap.keyMap)(newArray, ({ name }) => name); + + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } + } + + return { + added, + persisted, + removed, + }; +} diff --git a/node_modules/graphql/utilities/findBreakingChanges.mjs b/node_modules/graphql/utilities/findBreakingChanges.mjs new file mode 100644 index 0000000000000000000000000000000000000000..141ac6e5c91f18b5d22a80aca2ff6ff2f112b1e2 --- /dev/null +++ b/node_modules/graphql/utilities/findBreakingChanges.mjs @@ -0,0 +1,589 @@ +/** @category Schema Changes */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { keyMap } from '../jsutils/keyMap.mjs'; +import { print } from '../language/printer.mjs'; +import { + isEnumType, + isInputObjectType, + isInterfaceType, + isListType, + isNamedType, + isNonNullType, + isObjectType, + isRequiredArgument, + isRequiredInputField, + isScalarType, + isUnionType, +} from '../type/definition.mjs'; +import { isSpecifiedScalarType } from '../type/scalars.mjs'; +import { astFromValue } from './astFromValue.mjs'; +import { sortValueNode } from './sortValueNode.mjs'; +/** Categories of schema changes that may break existing operations. */ + +var BreakingChangeType; + +(function (BreakingChangeType) { + BreakingChangeType['TYPE_REMOVED'] = 'TYPE_REMOVED'; + BreakingChangeType['TYPE_CHANGED_KIND'] = 'TYPE_CHANGED_KIND'; + BreakingChangeType['TYPE_REMOVED_FROM_UNION'] = 'TYPE_REMOVED_FROM_UNION'; + BreakingChangeType['VALUE_REMOVED_FROM_ENUM'] = 'VALUE_REMOVED_FROM_ENUM'; + BreakingChangeType['REQUIRED_INPUT_FIELD_ADDED'] = + 'REQUIRED_INPUT_FIELD_ADDED'; + BreakingChangeType['IMPLEMENTED_INTERFACE_REMOVED'] = + 'IMPLEMENTED_INTERFACE_REMOVED'; + BreakingChangeType['FIELD_REMOVED'] = 'FIELD_REMOVED'; + BreakingChangeType['FIELD_CHANGED_KIND'] = 'FIELD_CHANGED_KIND'; + BreakingChangeType['REQUIRED_ARG_ADDED'] = 'REQUIRED_ARG_ADDED'; + BreakingChangeType['ARG_REMOVED'] = 'ARG_REMOVED'; + BreakingChangeType['ARG_CHANGED_KIND'] = 'ARG_CHANGED_KIND'; + BreakingChangeType['DIRECTIVE_REMOVED'] = 'DIRECTIVE_REMOVED'; + BreakingChangeType['DIRECTIVE_ARG_REMOVED'] = 'DIRECTIVE_ARG_REMOVED'; + BreakingChangeType['REQUIRED_DIRECTIVE_ARG_ADDED'] = + 'REQUIRED_DIRECTIVE_ARG_ADDED'; + BreakingChangeType['DIRECTIVE_REPEATABLE_REMOVED'] = + 'DIRECTIVE_REPEATABLE_REMOVED'; + BreakingChangeType['DIRECTIVE_LOCATION_REMOVED'] = + 'DIRECTIVE_LOCATION_REMOVED'; +})(BreakingChangeType || (BreakingChangeType = {})); + +export { BreakingChangeType }; +/** Categories of schema changes that may be dangerous for existing operations. */ + +var DangerousChangeType; + +(function (DangerousChangeType) { + DangerousChangeType['VALUE_ADDED_TO_ENUM'] = 'VALUE_ADDED_TO_ENUM'; + DangerousChangeType['TYPE_ADDED_TO_UNION'] = 'TYPE_ADDED_TO_UNION'; + DangerousChangeType['OPTIONAL_INPUT_FIELD_ADDED'] = + 'OPTIONAL_INPUT_FIELD_ADDED'; + DangerousChangeType['OPTIONAL_ARG_ADDED'] = 'OPTIONAL_ARG_ADDED'; + DangerousChangeType['IMPLEMENTED_INTERFACE_ADDED'] = + 'IMPLEMENTED_INTERFACE_ADDED'; + DangerousChangeType['ARG_DEFAULT_VALUE_CHANGE'] = 'ARG_DEFAULT_VALUE_CHANGE'; +})(DangerousChangeType || (DangerousChangeType = {})); + +export { DangerousChangeType }; +/** Description of a schema change that may break existing operations. */ + +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of breaking changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Breaking changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findBreakingChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * const newSchema = buildSchema(` + * type User { + * id: ID! + * } + * + * type Query { + * viewer: User + * } + * `); + * + * const changes = findBreakingChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'FIELD_REMOVED' + * changes[0].description; // matches /User.name was removed/ + * ``` + */ +export function findBreakingChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in BreakingChangeType, + ); +} +/** + * Given two schemas, returns an Array containing descriptions of all the types + * of potentially dangerous changes covered by the other functions down below. + * @param oldSchema - Schema before the change. + * @param newSchema - Schema after the change. + * @returns Dangerous changes between the two schemas. + * @example + * ```ts + * import { buildSchema, findDangerousChanges } from 'graphql/utilities'; + * + * const oldSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * episode: Episode + * } + * `); + * const newSchema = buildSchema(` + * enum Episode { + * NEW_HOPE + * EMPIRE + * } + * + * type Query { + * episode: Episode + * } + * `); + * + * const changes = findDangerousChanges(oldSchema, newSchema); + * + * changes[0].type; // => 'VALUE_ADDED_TO_ENUM' + * changes[0].description; // matches /EMPIRE was added/ + * ``` + */ + +export function findDangerousChanges(oldSchema, newSchema) { + // @ts-expect-error + return findSchemaChanges(oldSchema, newSchema).filter( + (change) => change.type in DangerousChangeType, + ); +} + +function findSchemaChanges(oldSchema, newSchema) { + return [ + ...findTypeChanges(oldSchema, newSchema), + ...findDirectiveChanges(oldSchema, newSchema), + ]; +} + +function findDirectiveChanges(oldSchema, newSchema) { + const schemaChanges = []; + const directivesDiff = diff( + oldSchema.getDirectives(), + newSchema.getDirectives(), + ); + + for (const oldDirective of directivesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REMOVED, + description: `${oldDirective.name} was removed.`, + }); + } + + for (const [oldDirective, newDirective] of directivesDiff.persisted) { + const argsDiff = diff(oldDirective.args, newDirective.args); + + for (const newArg of argsDiff.added) { + if (isRequiredArgument(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_DIRECTIVE_ARG_ADDED, + description: `A required arg ${newArg.name} on directive ${oldDirective.name} was added.`, + }); + } + } + + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_ARG_REMOVED, + description: `${oldArg.name} was removed from ${oldDirective.name}.`, + }); + } + + if (oldDirective.isRepeatable && !newDirective.isRepeatable) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_REPEATABLE_REMOVED, + description: `Repeatable flag was removed from ${oldDirective.name}.`, + }); + } + + for (const location of oldDirective.locations) { + if (!newDirective.locations.includes(location)) { + schemaChanges.push({ + type: BreakingChangeType.DIRECTIVE_LOCATION_REMOVED, + description: `${location} was removed from ${oldDirective.name}.`, + }); + } + } + } + + return schemaChanges; +} + +function findTypeChanges(oldSchema, newSchema) { + const schemaChanges = []; + const typesDiff = diff( + Object.values(oldSchema.getTypeMap()), + Object.values(newSchema.getTypeMap()), + ); + + for (const oldType of typesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED, + description: isSpecifiedScalarType(oldType) + ? `Standard scalar ${oldType.name} was removed because it is not referenced anymore.` + : `${oldType.name} was removed.`, + }); + } + + for (const [oldType, newType] of typesDiff.persisted) { + if (isEnumType(oldType) && isEnumType(newType)) { + schemaChanges.push(...findEnumTypeChanges(oldType, newType)); + } else if (isUnionType(oldType) && isUnionType(newType)) { + schemaChanges.push(...findUnionTypeChanges(oldType, newType)); + } else if (isInputObjectType(oldType) && isInputObjectType(newType)) { + schemaChanges.push(...findInputObjectTypeChanges(oldType, newType)); + } else if (isObjectType(oldType) && isObjectType(newType)) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if (isInterfaceType(oldType) && isInterfaceType(newType)) { + schemaChanges.push( + ...findFieldChanges(oldType, newType), + ...findImplementedInterfacesChanges(oldType, newType), + ); + } else if (oldType.constructor !== newType.constructor) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_CHANGED_KIND, + description: + `${oldType.name} changed from ` + + `${typeKindName(oldType)} to ${typeKindName(newType)}.`, + }); + } + } + + return schemaChanges; +} + +function findInputObjectTypeChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); + + for (const newField of fieldsDiff.added) { + if (isRequiredInputField(newField)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_INPUT_FIELD_ADDED, + description: `A required field ${newField.name} on input type ${oldType.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_INPUT_FIELD_ADDED, + description: `An optional field ${newField.name} on input type ${oldType.name} was added.`, + }); + } + } + + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + + for (const [oldField, newField] of fieldsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldField.type, + newField.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + + return schemaChanges; +} + +function findUnionTypeChanges(oldType, newType) { + const schemaChanges = []; + const possibleTypesDiff = diff(oldType.getTypes(), newType.getTypes()); + + for (const newPossibleType of possibleTypesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.TYPE_ADDED_TO_UNION, + description: `${newPossibleType.name} was added to union type ${oldType.name}.`, + }); + } + + for (const oldPossibleType of possibleTypesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.TYPE_REMOVED_FROM_UNION, + description: `${oldPossibleType.name} was removed from union type ${oldType.name}.`, + }); + } + + return schemaChanges; +} + +function findEnumTypeChanges(oldType, newType) { + const schemaChanges = []; + const valuesDiff = diff(oldType.getValues(), newType.getValues()); + + for (const newValue of valuesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.VALUE_ADDED_TO_ENUM, + description: `${newValue.name} was added to enum type ${oldType.name}.`, + }); + } + + for (const oldValue of valuesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.VALUE_REMOVED_FROM_ENUM, + description: `${oldValue.name} was removed from enum type ${oldType.name}.`, + }); + } + + return schemaChanges; +} + +function findImplementedInterfacesChanges(oldType, newType) { + const schemaChanges = []; + const interfacesDiff = diff(oldType.getInterfaces(), newType.getInterfaces()); + + for (const newInterface of interfacesDiff.added) { + schemaChanges.push({ + type: DangerousChangeType.IMPLEMENTED_INTERFACE_ADDED, + description: `${newInterface.name} added to interfaces implemented by ${oldType.name}.`, + }); + } + + for (const oldInterface of interfacesDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.IMPLEMENTED_INTERFACE_REMOVED, + description: `${oldType.name} no longer implements interface ${oldInterface.name}.`, + }); + } + + return schemaChanges; +} + +function findFieldChanges(oldType, newType) { + const schemaChanges = []; + const fieldsDiff = diff( + Object.values(oldType.getFields()), + Object.values(newType.getFields()), + ); + + for (const oldField of fieldsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_REMOVED, + description: `${oldType.name}.${oldField.name} was removed.`, + }); + } + + for (const [oldField, newField] of fieldsDiff.persisted) { + schemaChanges.push(...findArgChanges(oldType, oldField, newField)); + const isSafe = isChangeSafeForObjectOrInterfaceField( + oldField.type, + newField.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.FIELD_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} changed type from ` + + `${String(oldField.type)} to ${String(newField.type)}.`, + }); + } + } + + return schemaChanges; +} + +function findArgChanges(oldType, oldField, newField) { + const schemaChanges = []; + const argsDiff = diff(oldField.args, newField.args); + + for (const oldArg of argsDiff.removed) { + schemaChanges.push({ + type: BreakingChangeType.ARG_REMOVED, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} was removed.`, + }); + } + + for (const [oldArg, newArg] of argsDiff.persisted) { + const isSafe = isChangeSafeForInputObjectFieldOrFieldArg( + oldArg.type, + newArg.type, + ); + + if (!isSafe) { + schemaChanges.push({ + type: BreakingChangeType.ARG_CHANGED_KIND, + description: + `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed type from ` + + `${String(oldArg.type)} to ${String(newArg.type)}.`, + }); + } else if (oldArg.defaultValue !== undefined) { + if (newArg.defaultValue === undefined) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} defaultValue was removed.`, + }); + } else { + // Since we looking only for client's observable changes we should + // compare default values in the same representation as they are + // represented inside introspection. + const oldValueStr = stringifyValue(oldArg.defaultValue, oldArg.type); + const newValueStr = stringifyValue(newArg.defaultValue, newArg.type); + + if (oldValueStr !== newValueStr) { + schemaChanges.push({ + type: DangerousChangeType.ARG_DEFAULT_VALUE_CHANGE, + description: `${oldType.name}.${oldField.name} arg ${oldArg.name} has changed defaultValue from ${oldValueStr} to ${newValueStr}.`, + }); + } + } + } + } + + for (const newArg of argsDiff.added) { + if (isRequiredArgument(newArg)) { + schemaChanges.push({ + type: BreakingChangeType.REQUIRED_ARG_ADDED, + description: `A required arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } else { + schemaChanges.push({ + type: DangerousChangeType.OPTIONAL_ARG_ADDED, + description: `An optional arg ${newArg.name} on ${oldType.name}.${oldField.name} was added.`, + }); + } + } + + return schemaChanges; +} + +function isChangeSafeForObjectOrInterfaceField(oldType, newType) { + if (isListType(oldType)) { + return ( + // if they're both lists, make sure the underlying types are compatible + (isListType(newType) && + isChangeSafeForObjectOrInterfaceField( + oldType.ofType, + newType.ofType, + )) || // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); + } + + if (isNonNullType(oldType)) { + // if they're both non-null, make sure the underlying types are compatible + return ( + isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType.ofType, newType.ofType) + ); + } + + return ( + // if they're both named types, see if their names are equivalent + (isNamedType(newType) && oldType.name === newType.name) || // moving from nullable to non-null of the same underlying type is safe + (isNonNullType(newType) && + isChangeSafeForObjectOrInterfaceField(oldType, newType.ofType)) + ); +} + +function isChangeSafeForInputObjectFieldOrFieldArg(oldType, newType) { + if (isListType(oldType)) { + // if they're both lists, make sure the underlying types are compatible + return ( + isListType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType.ofType) + ); + } + + if (isNonNullType(oldType)) { + return ( + // if they're both non-null, make sure the underlying types are + // compatible + (isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg( + oldType.ofType, + newType.ofType, + )) || // moving from non-null to nullable of the same underlying type is safe + (!isNonNullType(newType) && + isChangeSafeForInputObjectFieldOrFieldArg(oldType.ofType, newType)) + ); + } // if they're both named types, see if their names are equivalent + + return isNamedType(newType) && oldType.name === newType.name; +} + +function typeKindName(type) { + if (isScalarType(type)) { + return 'a Scalar type'; + } + + if (isObjectType(type)) { + return 'an Object type'; + } + + if (isInterfaceType(type)) { + return 'an Interface type'; + } + + if (isUnionType(type)) { + return 'a Union type'; + } + + if (isEnumType(type)) { + return 'an Enum type'; + } + + if (isInputObjectType(type)) { + return 'an Input type'; + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || invariant(false, 'Unexpected type: ' + inspect(type)); +} + +function stringifyValue(value, type) { + const ast = astFromValue(value, type); + ast != null || invariant(false); + return print(sortValueNode(ast)); +} + +function diff(oldArray, newArray) { + const added = []; + const removed = []; + const persisted = []; + const oldMap = keyMap(oldArray, ({ name }) => name); + const newMap = keyMap(newArray, ({ name }) => name); + + for (const oldItem of oldArray) { + const newItem = newMap[oldItem.name]; + + if (newItem === undefined) { + removed.push(oldItem); + } else { + persisted.push([oldItem, newItem]); + } + } + + for (const newItem of newArray) { + if (oldMap[newItem.name] === undefined) { + added.push(newItem); + } + } + + return { + added, + persisted, + removed, + }; +} diff --git a/node_modules/graphql/utilities/getIntrospectionQuery.d.ts b/node_modules/graphql/utilities/getIntrospectionQuery.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b8d529827ba24080504c1bf3e325dabfbdd31af4 --- /dev/null +++ b/node_modules/graphql/utilities/getIntrospectionQuery.d.ts @@ -0,0 +1,336 @@ +/** @category Introspection */ +import type { Maybe } from '../jsutils/Maybe'; +import type { DirectiveLocation } from '../language/directiveLocation'; +/** Options controlling which fields are included in the introspection query. */ +export interface IntrospectionOptions { + /** + * Whether to include descriptions in the introspection result. + * Default: true + */ + descriptions?: boolean; + /** + * Whether to include `specifiedByURL` in the introspection result. + * Default: false + */ + specifiedByUrl?: boolean; + /** + * Whether to include `isRepeatable` flag on directives. + * Default: false + */ + directiveIsRepeatable?: boolean; + /** + * Whether to include `description` field on schema. + * Default: false + */ + schemaDescription?: boolean; + /** + * Whether target GraphQL server support deprecation of input values. + * Default: false + */ + inputValueDeprecation?: boolean; + /** + * Whether target GraphQL server supports deprecation of directives. + * Default: false + */ + experimentalDirectiveDeprecation?: boolean; + /** + * Whether target GraphQL server supports `@oneOf` input objects. + * Default: false + */ + oneOf?: boolean; + /** + * How deep to recurse into nested types, larger values will result in more + * accurate results, but have a higher load on the server. + * Some servers might restrict the maximum query depth or complexity. + * If that's the case, try decreasing this value. + * + * Default: 9 + */ + typeDepth?: number; +} +/** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + * @param options - Optional configuration for this operation. + * @returns The resolved introspection query. + * @example + * ```ts + * // Generate the default introspection query. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery(); + * + * query; // matches /__schema/ + * query; // matches /description/ + * query; // does not match /specifiedByURL/ + * ``` + * @example + * ```ts + * // This variant customizes optional introspection fields and nesting depth. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery({ + * descriptions: false, + * specifiedByUrl: true, + * directiveIsRepeatable: true, + * schemaDescription: true, + * inputValueDeprecation: true, + * experimentalDirectiveDeprecation: true, + * oneOf: true, + * typeDepth: 3, + * }); + * + * query; // does not match /description/ + * query; // matches /specifiedByURL/ + * query; // matches /isRepeatable/ + * query; // matches /includeDeprecated: true/ + * query; // matches /isOneOf/ + * (query.match(/ofType/g)?.length ?? 0) > 0; // => true + * ``` + */ +export declare function getIntrospectionQuery( + options?: IntrospectionOptions, +): string; +/** The result shape returned by a full introspection query. */ +export interface IntrospectionQuery { + /** The schema. */ + readonly __schema: IntrospectionSchema; +} +/** The introspection representation of a GraphQL schema. */ +export interface IntrospectionSchema { + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** The root object type used for query operations. */ + readonly queryType: IntrospectionNamedTypeRef; + /** The root object type used for mutation operations, if supported. */ + readonly mutationType: Maybe< + IntrospectionNamedTypeRef + >; + /** The root object type used for subscription operations, if supported. */ + readonly subscriptionType: Maybe< + IntrospectionNamedTypeRef + >; + /** Object types that belong to this union type. */ + readonly types: ReadonlyArray; + /** Directives available in this schema or applied to this AST node. */ + readonly directives: ReadonlyArray; +} +/** Any introspection representation of a GraphQL type. */ +export declare type IntrospectionType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; +/** An introspection type that can appear in output position. */ +export declare type IntrospectionOutputType = + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType; +/** An introspection type that can appear in input position. */ +export declare type IntrospectionInputType = + | IntrospectionScalarType + | IntrospectionEnumType + | IntrospectionInputObjectType; +/** The introspection representation of a scalar type. */ +export interface IntrospectionScalarType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'SCALAR'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** URL identifying the behavior specified for this custom scalar. */ + readonly specifiedByURL?: Maybe; +} +/** The introspection representation of an object type. */ +export interface IntrospectionObjectType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'OBJECT'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields: ReadonlyArray; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces: ReadonlyArray< + IntrospectionNamedTypeRef + >; +} +/** The introspection representation of an interface type. */ +export interface IntrospectionInterfaceType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'INTERFACE'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Fields declared by this object, interface, input object, or literal. */ + readonly fields: ReadonlyArray; + /** Interfaces implemented by this object or interface type. */ + readonly interfaces: ReadonlyArray< + IntrospectionNamedTypeRef + >; + /** Object types that may be returned for this abstract type. */ + readonly possibleTypes: ReadonlyArray< + IntrospectionNamedTypeRef + >; +} +/** The introspection representation of a union type. */ +export interface IntrospectionUnionType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'UNION'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Object types that may be returned for this abstract type. */ + readonly possibleTypes: ReadonlyArray< + IntrospectionNamedTypeRef + >; +} +/** The introspection representation of an enum type. */ +export interface IntrospectionEnumType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'ENUM'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Values declared by this enum type. */ + readonly enumValues: ReadonlyArray; +} +/** The introspection representation of an input object type. */ +export interface IntrospectionInputObjectType { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'INPUT_OBJECT'; + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Input fields declared by this input object type. */ + readonly inputFields: ReadonlyArray; + /** Whether this input object uses the experimental OneOf input object semantics. */ + readonly isOneOf: boolean; +} +/** + * The introspection representation of a list type reference. + * @typeParam T - The introspection type reference wrapped by this list type reference. + */ +export interface IntrospectionListTypeRef< + T extends IntrospectionTypeRef = IntrospectionTypeRef, +> { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'LIST'; + /** The type wrapped by this list or non-null type. */ + readonly ofType: T; +} +/** + * The introspection representation of a non-null type reference. + * @typeParam T - The introspection type reference wrapped by this non-null type reference. + */ +export interface IntrospectionNonNullTypeRef< + T extends IntrospectionTypeRef = IntrospectionTypeRef, +> { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: 'NON_NULL'; + /** The type wrapped by this list or non-null type. */ + readonly ofType: T; +} +/** Any introspection representation of a type reference. */ +export declare type IntrospectionTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + IntrospectionNamedTypeRef | IntrospectionListTypeRef + >; +/** An introspection type reference that can appear in output position. */ +export declare type IntrospectionOutputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + >; +/** An introspection type reference that can appear in input position. */ +export declare type IntrospectionInputTypeRef = + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef< + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + >; +/** + * The introspection representation of a named type reference. + * @typeParam T - The introspection type represented by this named type reference. + */ +export interface IntrospectionNamedTypeRef< + T extends IntrospectionType = IntrospectionType, +> { + /** The introspection kind discriminator for this type reference or type. */ + readonly kind: T['kind']; + /** The GraphQL name for this schema element. */ + readonly name: string; +} +/** The introspection representation of a field. */ +export interface IntrospectionField { + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Arguments accepted by this field or directive. */ + readonly args: ReadonlyArray; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: IntrospectionOutputTypeRef; + /** Whether this field, argument, enum value, or input value is deprecated. */ + readonly isDeprecated: boolean; + /** Reason this element is deprecated, if one was provided. */ + readonly deprecationReason: Maybe; +} +/** The introspection representation of an argument or input field. */ +export interface IntrospectionInputValue { + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** The GraphQL type reference or runtime type for this element. */ + readonly type: IntrospectionInputTypeRef; + /** Default value used when no explicit value is supplied. */ + readonly defaultValue: Maybe; + /** Whether this field, argument, enum value, or input value is deprecated. */ + readonly isDeprecated?: boolean; + /** Reason this element is deprecated, if one was provided. */ + readonly deprecationReason?: Maybe; +} +/** The introspection representation of an enum value. */ +export interface IntrospectionEnumValue { + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Whether this field, argument, enum value, or input value is deprecated. */ + readonly isDeprecated: boolean; + /** Reason this element is deprecated, if one was provided. */ + readonly deprecationReason: Maybe; +} +/** The introspection representation of a directive. */ +export interface IntrospectionDirective { + /** The GraphQL name for this schema element. */ + readonly name: string; + /** Human-readable description for this schema element, if provided. */ + readonly description?: Maybe; + /** Whether this directive may appear more than once at the same location. */ + readonly isRepeatable?: boolean; + /** Whether this field, argument, enum value, or input value is deprecated. */ + readonly isDeprecated?: boolean; + /** Reason this element is deprecated, if one was provided. */ + readonly deprecationReason?: Maybe; + /** Locations where this directive may be applied. */ + readonly locations: ReadonlyArray; + /** Arguments accepted by this field or directive. */ + readonly args: ReadonlyArray; +} diff --git a/node_modules/graphql/utilities/getIntrospectionQuery.js b/node_modules/graphql/utilities/getIntrospectionQuery.js new file mode 100644 index 0000000000000000000000000000000000000000..d379295c0dd4462c27ce7011f4d382828be1e41f --- /dev/null +++ b/node_modules/graphql/utilities/getIntrospectionQuery.js @@ -0,0 +1,179 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.getIntrospectionQuery = getIntrospectionQuery; + +/** @category Introspection */ + +/** Options controlling which fields are included in the introspection query. */ + +/** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + * @param options - Optional configuration for this operation. + * @returns The resolved introspection query. + * @example + * ```ts + * // Generate the default introspection query. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery(); + * + * query; // matches /__schema/ + * query; // matches /description/ + * query; // does not match /specifiedByURL/ + * ``` + * @example + * ```ts + * // This variant customizes optional introspection fields and nesting depth. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery({ + * descriptions: false, + * specifiedByUrl: true, + * directiveIsRepeatable: true, + * schemaDescription: true, + * inputValueDeprecation: true, + * experimentalDirectiveDeprecation: true, + * oneOf: true, + * typeDepth: 3, + * }); + * + * query; // does not match /description/ + * query; // matches /specifiedByURL/ + * query; // matches /isRepeatable/ + * query; // matches /includeDeprecated: true/ + * query; // matches /isOneOf/ + * (query.match(/ofType/g)?.length ?? 0) > 0; // => true + * ``` + */ +function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + experimentalDirectiveDeprecation: false, + oneOf: false, + typeDepth: 9, + ...options, + }; + const descriptions = optionsWithDefault.descriptions ? 'description' : ''; + const specifiedByUrl = optionsWithDefault.specifiedByUrl + ? 'specifiedByURL' + : ''; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable + ? 'isRepeatable' + : ''; + const schemaDescription = optionsWithDefault.schemaDescription + ? descriptions + : ''; + + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + + function experimentalDirectiveDeprecation(str) { + return optionsWithDefault.experimentalDirectiveDeprecation ? str : ''; + } + + const oneOf = optionsWithDefault.oneOf ? 'isOneOf' : ''; + + function ofType(level, indent) { + if (level <= 0) { + return ''; + } + + if (level > 100) { + throw new Error( + 'Please set typeDepth to a reasonable value between 0 and 100; the default is 9.', + ); + } + + return ` +${indent}ofType { +${indent} name +${indent} kind${ofType(level - 1, indent + ' ')} +${indent}}`; + } + + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name kind } + mutationType { name kind } + subscriptionType { name kind } + types { + ...FullType + } + directives${experimentalDirectiveDeprecation( + '(includeDeprecated: true)', + )} { + name + ${descriptions} + ${directiveIsRepeatable} + ${experimentalDirectiveDeprecation('isDeprecated')} + ${experimentalDirectiveDeprecation('deprecationReason')} + locations + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + ${oneOf} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation('isDeprecated')} + ${inputDeprecation('deprecationReason')} + } + + fragment TypeRef on __Type { + kind + name${ofType(optionsWithDefault.typeDepth, ' ')} + } + `; +} +/** The result shape returned by a full introspection query. */ diff --git a/node_modules/graphql/utilities/getIntrospectionQuery.mjs b/node_modules/graphql/utilities/getIntrospectionQuery.mjs new file mode 100644 index 0000000000000000000000000000000000000000..979a35b65ff592517dda81082bf27556b7c24cde --- /dev/null +++ b/node_modules/graphql/utilities/getIntrospectionQuery.mjs @@ -0,0 +1,172 @@ +/** @category Introspection */ + +/** Options controlling which fields are included in the introspection query. */ + +/** + * Produce the GraphQL query recommended for a full schema introspection. + * Accepts optional IntrospectionOptions. + * @param options - Optional configuration for this operation. + * @returns The resolved introspection query. + * @example + * ```ts + * // Generate the default introspection query. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery(); + * + * query; // matches /__schema/ + * query; // matches /description/ + * query; // does not match /specifiedByURL/ + * ``` + * @example + * ```ts + * // This variant customizes optional introspection fields and nesting depth. + * import { getIntrospectionQuery } from 'graphql/utilities'; + * + * const query = getIntrospectionQuery({ + * descriptions: false, + * specifiedByUrl: true, + * directiveIsRepeatable: true, + * schemaDescription: true, + * inputValueDeprecation: true, + * experimentalDirectiveDeprecation: true, + * oneOf: true, + * typeDepth: 3, + * }); + * + * query; // does not match /description/ + * query; // matches /specifiedByURL/ + * query; // matches /isRepeatable/ + * query; // matches /includeDeprecated: true/ + * query; // matches /isOneOf/ + * (query.match(/ofType/g)?.length ?? 0) > 0; // => true + * ``` + */ +export function getIntrospectionQuery(options) { + const optionsWithDefault = { + descriptions: true, + specifiedByUrl: false, + directiveIsRepeatable: false, + schemaDescription: false, + inputValueDeprecation: false, + experimentalDirectiveDeprecation: false, + oneOf: false, + typeDepth: 9, + ...options, + }; + const descriptions = optionsWithDefault.descriptions ? 'description' : ''; + const specifiedByUrl = optionsWithDefault.specifiedByUrl + ? 'specifiedByURL' + : ''; + const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable + ? 'isRepeatable' + : ''; + const schemaDescription = optionsWithDefault.schemaDescription + ? descriptions + : ''; + + function inputDeprecation(str) { + return optionsWithDefault.inputValueDeprecation ? str : ''; + } + + function experimentalDirectiveDeprecation(str) { + return optionsWithDefault.experimentalDirectiveDeprecation ? str : ''; + } + + const oneOf = optionsWithDefault.oneOf ? 'isOneOf' : ''; + + function ofType(level, indent) { + if (level <= 0) { + return ''; + } + + if (level > 100) { + throw new Error( + 'Please set typeDepth to a reasonable value between 0 and 100; the default is 9.', + ); + } + + return ` +${indent}ofType { +${indent} name +${indent} kind${ofType(level - 1, indent + ' ')} +${indent}}`; + } + + return ` + query IntrospectionQuery { + __schema { + ${schemaDescription} + queryType { name kind } + mutationType { name kind } + subscriptionType { name kind } + types { + ...FullType + } + directives${experimentalDirectiveDeprecation( + '(includeDeprecated: true)', + )} { + name + ${descriptions} + ${directiveIsRepeatable} + ${experimentalDirectiveDeprecation('isDeprecated')} + ${experimentalDirectiveDeprecation('deprecationReason')} + locations + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + } + } + } + + fragment FullType on __Type { + kind + name + ${descriptions} + ${specifiedByUrl} + ${oneOf} + fields(includeDeprecated: true) { + name + ${descriptions} + args${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + type { + ...TypeRef + } + isDeprecated + deprecationReason + } + inputFields${inputDeprecation('(includeDeprecated: true)')} { + ...InputValue + } + interfaces { + ...TypeRef + } + enumValues(includeDeprecated: true) { + name + ${descriptions} + isDeprecated + deprecationReason + } + possibleTypes { + ...TypeRef + } + } + + fragment InputValue on __InputValue { + name + ${descriptions} + type { ...TypeRef } + defaultValue + ${inputDeprecation('isDeprecated')} + ${inputDeprecation('deprecationReason')} + } + + fragment TypeRef on __Type { + kind + name${ofType(optionsWithDefault.typeDepth, ' ')} + } + `; +} +/** The result shape returned by a full introspection query. */ diff --git a/node_modules/graphql/utilities/getOperationAST.d.ts b/node_modules/graphql/utilities/getOperationAST.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8a200d505dd0be696a43a76108ae8353072bf26 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.d.ts @@ -0,0 +1,26 @@ +/** @category Operations */ +import type { Maybe } from '../jsutils/Maybe'; +import type { DocumentNode, OperationDefinitionNode } from '../language/ast'; +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + * @param documentAST - The parsed GraphQL document AST. + * @param operationName - The optional operation name to select. + * @returns The resolved operation ast. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { getOperationAST } from 'graphql/utilities'; + * + * const document = parse('query GetName { name }'); + * const operation = getOperationAST(document, 'GetName'); + * + * operation.name.value; // => 'GetName' + * getOperationAST(document, 'Missing'); // => undefined + * ``` + */ +export declare function getOperationAST( + documentAST: DocumentNode, + operationName?: Maybe, +): Maybe; diff --git a/node_modules/graphql/utilities/getOperationAST.js b/node_modules/graphql/utilities/getOperationAST.js new file mode 100644 index 0000000000000000000000000000000000000000..a5c4494c58abe079d0979545ea8b84d263c1dbec --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.js @@ -0,0 +1,59 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.getOperationAST = getOperationAST; + +var _kinds = require('../language/kinds.js'); + +/** @category Operations */ + +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + * @param documentAST - The parsed GraphQL document AST. + * @param operationName - The optional operation name to select. + * @returns The resolved operation ast. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { getOperationAST } from 'graphql/utilities'; + * + * const document = parse('query GetName { name }'); + * const operation = getOperationAST(document, 'GetName'); + * + * operation.name.value; // => 'GetName' + * getOperationAST(document, 'Missing'); // => undefined + * ``` + */ +function getOperationAST(documentAST, operationName) { + let operation = null; + + for (const definition of documentAST.definitions) { + if (definition.kind === _kinds.Kind.OPERATION_DEFINITION) { + var _definition$name; + + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + return definition; + } + } + } + + return operation; +} diff --git a/node_modules/graphql/utilities/getOperationAST.mjs b/node_modules/graphql/utilities/getOperationAST.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1e7b8ededb1214ac14d690d6d6b602ebc50eb445 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationAST.mjs @@ -0,0 +1,51 @@ +/** @category Operations */ +import { Kind } from '../language/kinds.mjs'; +/** + * Returns an operation AST given a document AST and optionally an operation + * name. If a name is not provided, an operation is only returned if only one is + * provided in the document. + * @param documentAST - The parsed GraphQL document AST. + * @param operationName - The optional operation name to select. + * @returns The resolved operation ast. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { getOperationAST } from 'graphql/utilities'; + * + * const document = parse('query GetName { name }'); + * const operation = getOperationAST(document, 'GetName'); + * + * operation.name.value; // => 'GetName' + * getOperationAST(document, 'Missing'); // => undefined + * ``` + */ + +export function getOperationAST(documentAST, operationName) { + let operation = null; + + for (const definition of documentAST.definitions) { + if (definition.kind === Kind.OPERATION_DEFINITION) { + var _definition$name; + + if (operationName == null) { + // If no operation name was provided, only return an Operation if there + // is one defined in the document. Upon encountering the second, return + // null. + if (operation) { + return null; + } + + operation = definition; + } else if ( + ((_definition$name = definition.name) === null || + _definition$name === void 0 + ? void 0 + : _definition$name.value) === operationName + ) { + return definition; + } + } + } + + return operation; +} diff --git a/node_modules/graphql/utilities/getOperationRootType.d.ts b/node_modules/graphql/utilities/getOperationRootType.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4fc076599720201037902f34076477e396c7e145 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.d.ts @@ -0,0 +1,32 @@ +/** @category Operations */ +import type { + OperationDefinitionNode, + OperationTypeDefinitionNode, +} from '../language/ast'; +import type { GraphQLObjectType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Extracts the root type of the operation from the schema. This deprecated + * helper is retained for backwards compatibility; call + * `GraphQLSchema.getRootType` instead because getOperationRootType will be + * removed in v17. + * @param schema - GraphQL schema to use. + * @param operation - The operation definition to inspect. + * @returns The resolved operation root type. + * @example + * ```ts + * import { buildSchema, getOperationRootType } from 'graphql/utilities'; + * import { parse } from 'graphql/language'; + * + * const schema = buildSchema('type Query { name: String }'); + * const operation = parse('{ name }').definitions[0]; + * const rootType = getOperationRootType(schema, operation); + * + * rootType.name; // => 'Query' + * ``` + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ +export declare function getOperationRootType( + schema: GraphQLSchema, + operation: OperationDefinitionNode | OperationTypeDefinitionNode, +): GraphQLObjectType; diff --git a/node_modules/graphql/utilities/getOperationRootType.js b/node_modules/graphql/utilities/getOperationRootType.js new file mode 100644 index 0000000000000000000000000000000000000000..8681ecf7819f7f61894dc23458bcdfd4a7832d4f --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.js @@ -0,0 +1,85 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.getOperationRootType = getOperationRootType; + +var _GraphQLError = require('../error/GraphQLError.js'); + +/** @category Operations */ + +/** + * Extracts the root type of the operation from the schema. This deprecated + * helper is retained for backwards compatibility; call + * `GraphQLSchema.getRootType` instead because getOperationRootType will be + * removed in v17. + * @param schema - GraphQL schema to use. + * @param operation - The operation definition to inspect. + * @returns The resolved operation root type. + * @example + * ```ts + * import { buildSchema, getOperationRootType } from 'graphql/utilities'; + * import { parse } from 'graphql/language'; + * + * const schema = buildSchema('type Query { name: String }'); + * const operation = parse('{ name }').definitions[0]; + * const rootType = getOperationRootType(schema, operation); + * + * rootType.name; // => 'Query' + * ``` + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ +function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + + if (!queryType) { + throw new _GraphQLError.GraphQLError( + 'Schema does not define the required query root type.', + { + nodes: operation, + }, + ); + } + + return queryType; + } + + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured for mutations.', + { + nodes: operation, + }, + ); + } + + return mutationType; + } + + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new _GraphQLError.GraphQLError( + 'Schema is not configured for subscriptions.', + { + nodes: operation, + }, + ); + } + + return subscriptionType; + } + + throw new _GraphQLError.GraphQLError( + 'Can only have query, mutation and subscription operations.', + { + nodes: operation, + }, + ); +} diff --git a/node_modules/graphql/utilities/getOperationRootType.mjs b/node_modules/graphql/utilities/getOperationRootType.mjs new file mode 100644 index 0000000000000000000000000000000000000000..381c824592ce5c8f34497338538a855c2489ea15 --- /dev/null +++ b/node_modules/graphql/utilities/getOperationRootType.mjs @@ -0,0 +1,71 @@ +/** @category Operations */ +import { GraphQLError } from '../error/GraphQLError.mjs'; + +/** + * Extracts the root type of the operation from the schema. This deprecated + * helper is retained for backwards compatibility; call + * `GraphQLSchema.getRootType` instead because getOperationRootType will be + * removed in v17. + * @param schema - GraphQL schema to use. + * @param operation - The operation definition to inspect. + * @returns The resolved operation root type. + * @example + * ```ts + * import { buildSchema, getOperationRootType } from 'graphql/utilities'; + * import { parse } from 'graphql/language'; + * + * const schema = buildSchema('type Query { name: String }'); + * const operation = parse('{ name }').definitions[0]; + * const rootType = getOperationRootType(schema, operation); + * + * rootType.name; // => 'Query' + * ``` + * @deprecated Please use `GraphQLSchema.getRootType` instead. Will be removed in v17 + */ +export function getOperationRootType(schema, operation) { + if (operation.operation === 'query') { + const queryType = schema.getQueryType(); + + if (!queryType) { + throw new GraphQLError( + 'Schema does not define the required query root type.', + { + nodes: operation, + }, + ); + } + + return queryType; + } + + if (operation.operation === 'mutation') { + const mutationType = schema.getMutationType(); + + if (!mutationType) { + throw new GraphQLError('Schema is not configured for mutations.', { + nodes: operation, + }); + } + + return mutationType; + } + + if (operation.operation === 'subscription') { + const subscriptionType = schema.getSubscriptionType(); + + if (!subscriptionType) { + throw new GraphQLError('Schema is not configured for subscriptions.', { + nodes: operation, + }); + } + + return subscriptionType; + } + + throw new GraphQLError( + 'Can only have query, mutation and subscription operations.', + { + nodes: operation, + }, + ); +} diff --git a/node_modules/graphql/utilities/index.d.ts b/node_modules/graphql/utilities/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..636ebdb8038335d8f19eb08e4f21316bb2a041fa --- /dev/null +++ b/node_modules/graphql/utilities/index.d.ts @@ -0,0 +1,73 @@ +/** + * Utilities for building schemas, working with introspection, transforming ASTs, + * and comparing GraphQL types. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { getIntrospectionQuery } from './getIntrospectionQuery'; +export type { + IntrospectionOptions, + IntrospectionQuery, + IntrospectionSchema, + IntrospectionType, + IntrospectionInputType, + IntrospectionOutputType, + IntrospectionScalarType, + IntrospectionObjectType, + IntrospectionInterfaceType, + IntrospectionUnionType, + IntrospectionEnumType, + IntrospectionInputObjectType, + IntrospectionTypeRef, + IntrospectionInputTypeRef, + IntrospectionOutputTypeRef, + IntrospectionNamedTypeRef, + IntrospectionListTypeRef, + IntrospectionNonNullTypeRef, + IntrospectionField, + IntrospectionInputValue, + IntrospectionEnumValue, + IntrospectionDirective, +} from './getIntrospectionQuery'; +export { getOperationAST } from './getOperationAST'; +export { getOperationRootType } from './getOperationRootType'; +export { introspectionFromSchema } from './introspectionFromSchema'; +export { buildClientSchema } from './buildClientSchema'; +export { buildASTSchema, buildSchema } from './buildASTSchema'; +export type { BuildSchemaOptions } from './buildASTSchema'; +export { extendSchema } from './extendSchema'; +export { lexicographicSortSchema } from './lexicographicSortSchema'; +export { + printSchema, + printType, + printIntrospectionSchema, +} from './printSchema'; +export { typeFromAST } from './typeFromAST'; +export { valueFromAST } from './valueFromAST'; +export { valueFromASTUntyped } from './valueFromASTUntyped'; +export { astFromValue } from './astFromValue'; +export { TypeInfo, visitWithTypeInfo } from './TypeInfo'; +export { coerceInputValue } from './coerceInputValue'; +export { concatAST } from './concatAST'; +export { separateOperations } from './separateOperations'; +export { stripIgnoredCharacters } from './stripIgnoredCharacters'; +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators'; +export { assertValidName, isValidNameError } from './assertValidName'; +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, +} from './findBreakingChanges'; +export type { BreakingChange, DangerousChange } from './findBreakingChanges'; +export type { TypedQueryDocumentNode } from './typedQueryDocumentNode'; +export { + resolveSchemaCoordinate, + resolveASTSchemaCoordinate, +} from './resolveSchemaCoordinate'; +export type { ResolvedSchemaElement } from './resolveSchemaCoordinate'; diff --git a/node_modules/graphql/utilities/index.js b/node_modules/graphql/utilities/index.js new file mode 100644 index 0000000000000000000000000000000000000000..d687dadf5cbd3988273713638262c7e95faea8ad --- /dev/null +++ b/node_modules/graphql/utilities/index.js @@ -0,0 +1,247 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'BreakingChangeType', { + enumerable: true, + get: function () { + return _findBreakingChanges.BreakingChangeType; + }, +}); +Object.defineProperty(exports, 'DangerousChangeType', { + enumerable: true, + get: function () { + return _findBreakingChanges.DangerousChangeType; + }, +}); +Object.defineProperty(exports, 'TypeInfo', { + enumerable: true, + get: function () { + return _TypeInfo.TypeInfo; + }, +}); +Object.defineProperty(exports, 'assertValidName', { + enumerable: true, + get: function () { + return _assertValidName.assertValidName; + }, +}); +Object.defineProperty(exports, 'astFromValue', { + enumerable: true, + get: function () { + return _astFromValue.astFromValue; + }, +}); +Object.defineProperty(exports, 'buildASTSchema', { + enumerable: true, + get: function () { + return _buildASTSchema.buildASTSchema; + }, +}); +Object.defineProperty(exports, 'buildClientSchema', { + enumerable: true, + get: function () { + return _buildClientSchema.buildClientSchema; + }, +}); +Object.defineProperty(exports, 'buildSchema', { + enumerable: true, + get: function () { + return _buildASTSchema.buildSchema; + }, +}); +Object.defineProperty(exports, 'coerceInputValue', { + enumerable: true, + get: function () { + return _coerceInputValue.coerceInputValue; + }, +}); +Object.defineProperty(exports, 'concatAST', { + enumerable: true, + get: function () { + return _concatAST.concatAST; + }, +}); +Object.defineProperty(exports, 'doTypesOverlap', { + enumerable: true, + get: function () { + return _typeComparators.doTypesOverlap; + }, +}); +Object.defineProperty(exports, 'extendSchema', { + enumerable: true, + get: function () { + return _extendSchema.extendSchema; + }, +}); +Object.defineProperty(exports, 'findBreakingChanges', { + enumerable: true, + get: function () { + return _findBreakingChanges.findBreakingChanges; + }, +}); +Object.defineProperty(exports, 'findDangerousChanges', { + enumerable: true, + get: function () { + return _findBreakingChanges.findDangerousChanges; + }, +}); +Object.defineProperty(exports, 'getIntrospectionQuery', { + enumerable: true, + get: function () { + return _getIntrospectionQuery.getIntrospectionQuery; + }, +}); +Object.defineProperty(exports, 'getOperationAST', { + enumerable: true, + get: function () { + return _getOperationAST.getOperationAST; + }, +}); +Object.defineProperty(exports, 'getOperationRootType', { + enumerable: true, + get: function () { + return _getOperationRootType.getOperationRootType; + }, +}); +Object.defineProperty(exports, 'introspectionFromSchema', { + enumerable: true, + get: function () { + return _introspectionFromSchema.introspectionFromSchema; + }, +}); +Object.defineProperty(exports, 'isEqualType', { + enumerable: true, + get: function () { + return _typeComparators.isEqualType; + }, +}); +Object.defineProperty(exports, 'isTypeSubTypeOf', { + enumerable: true, + get: function () { + return _typeComparators.isTypeSubTypeOf; + }, +}); +Object.defineProperty(exports, 'isValidNameError', { + enumerable: true, + get: function () { + return _assertValidName.isValidNameError; + }, +}); +Object.defineProperty(exports, 'lexicographicSortSchema', { + enumerable: true, + get: function () { + return _lexicographicSortSchema.lexicographicSortSchema; + }, +}); +Object.defineProperty(exports, 'printIntrospectionSchema', { + enumerable: true, + get: function () { + return _printSchema.printIntrospectionSchema; + }, +}); +Object.defineProperty(exports, 'printSchema', { + enumerable: true, + get: function () { + return _printSchema.printSchema; + }, +}); +Object.defineProperty(exports, 'printType', { + enumerable: true, + get: function () { + return _printSchema.printType; + }, +}); +Object.defineProperty(exports, 'resolveASTSchemaCoordinate', { + enumerable: true, + get: function () { + return _resolveSchemaCoordinate.resolveASTSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'resolveSchemaCoordinate', { + enumerable: true, + get: function () { + return _resolveSchemaCoordinate.resolveSchemaCoordinate; + }, +}); +Object.defineProperty(exports, 'separateOperations', { + enumerable: true, + get: function () { + return _separateOperations.separateOperations; + }, +}); +Object.defineProperty(exports, 'stripIgnoredCharacters', { + enumerable: true, + get: function () { + return _stripIgnoredCharacters.stripIgnoredCharacters; + }, +}); +Object.defineProperty(exports, 'typeFromAST', { + enumerable: true, + get: function () { + return _typeFromAST.typeFromAST; + }, +}); +Object.defineProperty(exports, 'valueFromAST', { + enumerable: true, + get: function () { + return _valueFromAST.valueFromAST; + }, +}); +Object.defineProperty(exports, 'valueFromASTUntyped', { + enumerable: true, + get: function () { + return _valueFromASTUntyped.valueFromASTUntyped; + }, +}); +Object.defineProperty(exports, 'visitWithTypeInfo', { + enumerable: true, + get: function () { + return _TypeInfo.visitWithTypeInfo; + }, +}); + +var _getIntrospectionQuery = require('./getIntrospectionQuery.js'); + +var _getOperationAST = require('./getOperationAST.js'); + +var _getOperationRootType = require('./getOperationRootType.js'); + +var _introspectionFromSchema = require('./introspectionFromSchema.js'); + +var _buildClientSchema = require('./buildClientSchema.js'); + +var _buildASTSchema = require('./buildASTSchema.js'); + +var _extendSchema = require('./extendSchema.js'); + +var _lexicographicSortSchema = require('./lexicographicSortSchema.js'); + +var _printSchema = require('./printSchema.js'); + +var _typeFromAST = require('./typeFromAST.js'); + +var _valueFromAST = require('./valueFromAST.js'); + +var _valueFromASTUntyped = require('./valueFromASTUntyped.js'); + +var _astFromValue = require('./astFromValue.js'); + +var _TypeInfo = require('./TypeInfo.js'); + +var _coerceInputValue = require('./coerceInputValue.js'); + +var _concatAST = require('./concatAST.js'); + +var _separateOperations = require('./separateOperations.js'); + +var _stripIgnoredCharacters = require('./stripIgnoredCharacters.js'); + +var _typeComparators = require('./typeComparators.js'); + +var _assertValidName = require('./assertValidName.js'); + +var _findBreakingChanges = require('./findBreakingChanges.js'); + +var _resolveSchemaCoordinate = require('./resolveSchemaCoordinate.js'); diff --git a/node_modules/graphql/utilities/index.mjs b/node_modules/graphql/utilities/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dd8b962ed75542e2f888dd7c57296565b0b6ccb0 --- /dev/null +++ b/node_modules/graphql/utilities/index.mjs @@ -0,0 +1,67 @@ +/** + * Utilities for building schemas, working with introspection, transforming ASTs, + * and comparing GraphQL types. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +// Produce the GraphQL query recommended for a full schema introspection. +export { getIntrospectionQuery } from './getIntrospectionQuery.mjs'; +// Gets the target Operation from a Document. +export { getOperationAST } from './getOperationAST.mjs'; // Gets the Type for the target Operation AST. + +export { getOperationRootType } from './getOperationRootType.mjs'; // Convert a GraphQLSchema to an IntrospectionQuery. + +export { introspectionFromSchema } from './introspectionFromSchema.mjs'; // Build a GraphQLSchema from an introspection result. + +export { buildClientSchema } from './buildClientSchema.mjs'; // Build a GraphQLSchema from GraphQL Schema language. + +export { buildASTSchema, buildSchema } from './buildASTSchema.mjs'; +// Extends an existing GraphQLSchema from a parsed GraphQL Schema language AST. +export { extendSchema } from './extendSchema.mjs'; // Sort a GraphQLSchema. + +export { lexicographicSortSchema } from './lexicographicSortSchema.mjs'; // Print a GraphQLSchema to GraphQL Schema language. + +export { + printSchema, + printType, + printIntrospectionSchema, +} from './printSchema.mjs'; // Create a GraphQLType from a GraphQL language AST. + +export { typeFromAST } from './typeFromAST.mjs'; // Create a JavaScript value from a GraphQL language AST with a type. + +export { valueFromAST } from './valueFromAST.mjs'; // Create a JavaScript value from a GraphQL language AST without a type. + +export { valueFromASTUntyped } from './valueFromASTUntyped.mjs'; // Create a GraphQL language AST from a JavaScript value. + +export { astFromValue } from './astFromValue.mjs'; // A helper to use within recursive-descent visitors which need to be aware of the GraphQL type system. + +export { TypeInfo, visitWithTypeInfo } from './TypeInfo.mjs'; // Coerces a JavaScript value to a GraphQL type, or produces errors. + +export { coerceInputValue } from './coerceInputValue.mjs'; // Concatenates multiple AST together. + +export { concatAST } from './concatAST.mjs'; // Separates an AST into an AST per Operation. + +export { separateOperations } from './separateOperations.mjs'; // Strips characters that are not significant to the validity or execution of a GraphQL document. + +export { stripIgnoredCharacters } from './stripIgnoredCharacters.mjs'; // Comparators for types + +export { + isEqualType, + isTypeSubTypeOf, + doTypesOverlap, +} from './typeComparators.mjs'; // Asserts that a string is a valid GraphQL name + +export { assertValidName, isValidNameError } from './assertValidName.mjs'; // Compares two GraphQLSchemas and detects breaking changes. + +export { + BreakingChangeType, + DangerousChangeType, + findBreakingChanges, + findDangerousChanges, +} from './findBreakingChanges.mjs'; +// Schema coordinates +export { + resolveSchemaCoordinate, + resolveASTSchemaCoordinate, +} from './resolveSchemaCoordinate.mjs'; diff --git a/node_modules/graphql/utilities/introspectionFromSchema.d.ts b/node_modules/graphql/utilities/introspectionFromSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6e88433c70d94dfb6f0cc15f6e2a693f353e6aee --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.d.ts @@ -0,0 +1,72 @@ +/** @category Introspection */ +import type { GraphQLSchema } from '../type/schema'; +import type { + IntrospectionOptions, + IntrospectionQuery, +} from './getIntrospectionQuery'; +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + * @param schema - GraphQL schema to use. + * @param options - Optional configuration for this operation. + * @returns Introspection result data for the schema. + * @example + * ```ts + * // Include schema metadata using the default introspection options. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * + * urlType.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * ``` + * @example + * ```ts + * // This variant disables optional introspection metadata. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema, { + * descriptions: false, + * specifiedByUrl: false, + * directiveIsRepeatable: false, + * schemaDescription: false, + * inputValueDeprecation: false, + * experimentalDirectiveDeprecation: false, + * oneOf: false, + * }); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * const deprecatedDirective = introspection.__schema.directives.find( + * (directive) => directive.name === 'deprecated', + * ); + * + * urlType.specifiedByURL; // => undefined + * urlType.description; // => undefined + * introspection.__schema.description; // => undefined + * deprecatedDirective.isRepeatable; // => undefined + * ``` + */ +export declare function introspectionFromSchema( + schema: GraphQLSchema, + options?: IntrospectionOptions, +): IntrospectionQuery; diff --git a/node_modules/graphql/utilities/introspectionFromSchema.js b/node_modules/graphql/utilities/introspectionFromSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..f0d32a2b26354c4ce8036b8fe25267d04433958a --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.js @@ -0,0 +1,99 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.introspectionFromSchema = introspectionFromSchema; + +var _invariant = require('../jsutils/invariant.js'); + +var _parser = require('../language/parser.js'); + +var _execute = require('../execution/execute.js'); + +var _getIntrospectionQuery = require('./getIntrospectionQuery.js'); + +/** @category Introspection */ + +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + * @param schema - GraphQL schema to use. + * @param options - Optional configuration for this operation. + * @returns Introspection result data for the schema. + * @example + * ```ts + * // Include schema metadata using the default introspection options. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * + * urlType.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * ``` + * @example + * ```ts + * // This variant disables optional introspection metadata. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema, { + * descriptions: false, + * specifiedByUrl: false, + * directiveIsRepeatable: false, + * schemaDescription: false, + * inputValueDeprecation: false, + * experimentalDirectiveDeprecation: false, + * oneOf: false, + * }); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * const deprecatedDirective = introspection.__schema.directives.find( + * (directive) => directive.name === 'deprecated', + * ); + * + * urlType.specifiedByURL; // => undefined + * urlType.description; // => undefined + * introspection.__schema.description; // => undefined + * deprecatedDirective.isRepeatable; // => undefined + * ``` + */ +function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + experimentalDirectiveDeprecation: true, + oneOf: true, + ...options, + }; + const document = (0, _parser.parse)( + (0, _getIntrospectionQuery.getIntrospectionQuery)(optionsWithDefaults), + ); + const result = (0, _execute.executeSync)({ + schema, + document, + }); + (!result.errors && result.data) || (0, _invariant.invariant)(false); + return result.data; +} diff --git a/node_modules/graphql/utilities/introspectionFromSchema.mjs b/node_modules/graphql/utilities/introspectionFromSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b0cbfa55ed56e2936f064e2c1fdba55a022cdba8 --- /dev/null +++ b/node_modules/graphql/utilities/introspectionFromSchema.mjs @@ -0,0 +1,86 @@ +/** @category Introspection */ +import { invariant } from '../jsutils/invariant.mjs'; +import { parse } from '../language/parser.mjs'; +import { executeSync } from '../execution/execute.mjs'; +import { getIntrospectionQuery } from './getIntrospectionQuery.mjs'; +/** + * Build an IntrospectionQuery from a GraphQLSchema + * + * IntrospectionQuery is useful for utilities that care about type and field + * relationships, but do not need to traverse through those relationships. + * + * This is the inverse of buildClientSchema. The primary use case is outside + * of the server context, for instance when doing schema comparisons. + * @param schema - GraphQL schema to use. + * @param options - Optional configuration for this operation. + * @returns Introspection result data for the schema. + * @example + * ```ts + * // Include schema metadata using the default introspection options. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * + * urlType.specifiedByURL; // => 'https://url.spec.whatwg.org/' + * ``` + * @example + * ```ts + * // This variant disables optional introspection metadata. + * import { buildSchema, introspectionFromSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * scalar Url @specifiedBy(url: "https://url.spec.whatwg.org/") + * + * type Query { + * homepage: Url + * } + * `); + * + * const introspection = introspectionFromSchema(schema, { + * descriptions: false, + * specifiedByUrl: false, + * directiveIsRepeatable: false, + * schemaDescription: false, + * inputValueDeprecation: false, + * experimentalDirectiveDeprecation: false, + * oneOf: false, + * }); + * const urlType = introspection.__schema.types.find((type) => type.name === 'Url'); + * const deprecatedDirective = introspection.__schema.directives.find( + * (directive) => directive.name === 'deprecated', + * ); + * + * urlType.specifiedByURL; // => undefined + * urlType.description; // => undefined + * introspection.__schema.description; // => undefined + * deprecatedDirective.isRepeatable; // => undefined + * ``` + */ + +export function introspectionFromSchema(schema, options) { + const optionsWithDefaults = { + specifiedByUrl: true, + directiveIsRepeatable: true, + schemaDescription: true, + inputValueDeprecation: true, + experimentalDirectiveDeprecation: true, + oneOf: true, + ...options, + }; + const document = parse(getIntrospectionQuery(optionsWithDefaults)); + const result = executeSync({ + schema, + document, + }); + (!result.errors && result.data) || invariant(false); + return result.data; +} diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.d.ts b/node_modules/graphql/utilities/lexicographicSortSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..759de8abe548f838930d86745771a6543891d553 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.d.ts @@ -0,0 +1,44 @@ +/** @category Schema Construction */ +import { GraphQLSchema } from '../type/schema'; +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + * @param schema - GraphQL schema to use. + * @returns A copy of the schema with types, fields, arguments, and values sorted lexicographically. + * @example + * ```ts + * import { buildSchema, lexicographicSortSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * zebra: String + * apple: String + * } + * + * enum Episode { + * JEDI + * NEW_HOPE + * EMPIRE + * } + * `); + * + * const sortedSchema = lexicographicSortSchema(schema); + * + * printSchema(sortedSchema); + * // => + * // enum Episode { + * // EMPIRE + * // JEDI + * // NEW_HOPE + * // } + * // + * // type Query { + * // apple: String + * // zebra: String + * // } + * ``` + */ +export declare function lexicographicSortSchema( + schema: GraphQLSchema, +): GraphQLSchema; diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.js b/node_modules/graphql/utilities/lexicographicSortSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..d4905402b4c0fd8bef20901af9d4e4c4f5594901 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.js @@ -0,0 +1,213 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.lexicographicSortSchema = lexicographicSortSchema; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _keyValMap = require('../jsutils/keyValMap.js'); + +var _naturalCompare = require('../jsutils/naturalCompare.js'); + +var _definition = require('../type/definition.js'); + +var _directives = require('../type/directives.js'); + +var _introspection = require('../type/introspection.js'); + +var _schema = require('../type/schema.js'); + +/** @category Schema Construction */ + +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + * @param schema - GraphQL schema to use. + * @returns A copy of the schema with types, fields, arguments, and values sorted lexicographically. + * @example + * ```ts + * import { buildSchema, lexicographicSortSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * zebra: String + * apple: String + * } + * + * enum Episode { + * JEDI + * NEW_HOPE + * EMPIRE + * } + * `); + * + * const sortedSchema = lexicographicSortSchema(schema); + * + * printSchema(sortedSchema); + * // => + * // enum Episode { + * // EMPIRE + * // JEDI + * // NEW_HOPE + * // } + * // + * // type Query { + * // apple: String + * // zebra: String + * // } + * ``` + */ +function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = (0, _keyValMap.keyValMap)( + sortByName(schemaConfig.types), + (type) => type.name, + sortNamedType, + ); + return new _schema.GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription), + }); + + function replaceType(type) { + if ((0, _definition.isListType)(type)) { + // @ts-expect-error + return new _definition.GraphQLList(replaceType(type.ofType)); + } else if ((0, _definition.isNonNullType)(type)) { + // @ts-expect-error + return new _definition.GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + return typeMap[type.name]; + } + + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + + function sortDirective(directive) { + const config = directive.toConfig(); + return new _directives.GraphQLDirective({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortArgs(config.args), + }); + } + + function sortArgs(args) { + return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) })); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args), + })); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + })); + } + + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } + + function sortNamedType(type) { + if ( + (0, _definition.isScalarType)(type) || + (0, _introspection.isIntrospectionType)(type) + ) { + return type; + } + + if ((0, _definition.isObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + + if ((0, _definition.isInterfaceType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + + if ((0, _definition.isUnionType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types), + }); + } + + if ((0, _definition.isEnumType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, (value) => value), + }); + } + + if ((0, _definition.isInputObjectType)(type)) { + const config = type.toConfig(); + return new _definition.GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields), + }); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); + } +} + +function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + + for (const key of Object.keys(map).sort(_naturalCompare.naturalCompare)) { + sortedMap[key] = sortValueFn(map[key]); + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, (obj) => obj.name); +} + +function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return (0, _naturalCompare.naturalCompare)(key1, key2); + }); +} diff --git a/node_modules/graphql/utilities/lexicographicSortSchema.mjs b/node_modules/graphql/utilities/lexicographicSortSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db0c3aea29e12b2cb9fe13620d20b97f2c7e9c26 --- /dev/null +++ b/node_modules/graphql/utilities/lexicographicSortSchema.mjs @@ -0,0 +1,207 @@ +/** @category Schema Construction */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { keyValMap } from '../jsutils/keyValMap.mjs'; +import { naturalCompare } from '../jsutils/naturalCompare.mjs'; +import { + GraphQLEnumType, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLUnionType, + isEnumType, + isInputObjectType, + isInterfaceType, + isListType, + isNonNullType, + isObjectType, + isScalarType, + isUnionType, +} from '../type/definition.mjs'; +import { GraphQLDirective } from '../type/directives.mjs'; +import { isIntrospectionType } from '../type/introspection.mjs'; +import { GraphQLSchema } from '../type/schema.mjs'; +/** + * Sort GraphQLSchema. + * + * This function returns a sorted copy of the given GraphQLSchema. + * @param schema - GraphQL schema to use. + * @returns A copy of the schema with types, fields, arguments, and values sorted lexicographically. + * @example + * ```ts + * import { buildSchema, lexicographicSortSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * zebra: String + * apple: String + * } + * + * enum Episode { + * JEDI + * NEW_HOPE + * EMPIRE + * } + * `); + * + * const sortedSchema = lexicographicSortSchema(schema); + * + * printSchema(sortedSchema); + * // => + * // enum Episode { + * // EMPIRE + * // JEDI + * // NEW_HOPE + * // } + * // + * // type Query { + * // apple: String + * // zebra: String + * // } + * ``` + */ + +export function lexicographicSortSchema(schema) { + const schemaConfig = schema.toConfig(); + const typeMap = keyValMap( + sortByName(schemaConfig.types), + (type) => type.name, + sortNamedType, + ); + return new GraphQLSchema({ + ...schemaConfig, + types: Object.values(typeMap), + directives: sortByName(schemaConfig.directives).map(sortDirective), + query: replaceMaybeType(schemaConfig.query), + mutation: replaceMaybeType(schemaConfig.mutation), + subscription: replaceMaybeType(schemaConfig.subscription), + }); + + function replaceType(type) { + if (isListType(type)) { + // @ts-expect-error + return new GraphQLList(replaceType(type.ofType)); + } else if (isNonNullType(type)) { + // @ts-expect-error + return new GraphQLNonNull(replaceType(type.ofType)); + } // @ts-expect-error FIXME: TS Conversion + + return replaceNamedType(type); + } + + function replaceNamedType(type) { + return typeMap[type.name]; + } + + function replaceMaybeType(maybeType) { + return maybeType && replaceNamedType(maybeType); + } + + function sortDirective(directive) { + const config = directive.toConfig(); + return new GraphQLDirective({ + ...config, + locations: sortBy(config.locations, (x) => x), + args: sortArgs(config.args), + }); + } + + function sortArgs(args) { + return sortObjMap(args, (arg) => ({ ...arg, type: replaceType(arg.type) })); + } + + function sortFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + args: field.args && sortArgs(field.args), + })); + } + + function sortInputFields(fieldsMap) { + return sortObjMap(fieldsMap, (field) => ({ + ...field, + type: replaceType(field.type), + })); + } + + function sortTypes(array) { + return sortByName(array).map(replaceNamedType); + } + + function sortNamedType(type) { + if (isScalarType(type) || isIntrospectionType(type)) { + return type; + } + + if (isObjectType(type)) { + const config = type.toConfig(); + return new GraphQLObjectType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + + if (isInterfaceType(type)) { + const config = type.toConfig(); + return new GraphQLInterfaceType({ + ...config, + interfaces: () => sortTypes(config.interfaces), + fields: () => sortFields(config.fields), + }); + } + + if (isUnionType(type)) { + const config = type.toConfig(); + return new GraphQLUnionType({ + ...config, + types: () => sortTypes(config.types), + }); + } + + if (isEnumType(type)) { + const config = type.toConfig(); + return new GraphQLEnumType({ + ...config, + values: sortObjMap(config.values, (value) => value), + }); + } + + if (isInputObjectType(type)) { + const config = type.toConfig(); + return new GraphQLInputObjectType({ + ...config, + fields: () => sortInputFields(config.fields), + }); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || invariant(false, 'Unexpected type: ' + inspect(type)); + } +} + +function sortObjMap(map, sortValueFn) { + const sortedMap = Object.create(null); + + for (const key of Object.keys(map).sort(naturalCompare)) { + sortedMap[key] = sortValueFn(map[key]); + } + + return sortedMap; +} + +function sortByName(array) { + return sortBy(array, (obj) => obj.name); +} + +function sortBy(array, mapToKey) { + return array.slice().sort((obj1, obj2) => { + const key1 = mapToKey(obj1); + const key2 = mapToKey(obj2); + return naturalCompare(key1, key2); + }); +} diff --git a/node_modules/graphql/utilities/printSchema.d.ts b/node_modules/graphql/utilities/printSchema.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d11ba4a02c7ae4ecfbc38b147a464855eb1df847 --- /dev/null +++ b/node_modules/graphql/utilities/printSchema.d.ts @@ -0,0 +1,68 @@ +/** @category Schema Printing */ +import type { GraphQLNamedType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Prints the schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * printSchema(schema); // => ['directive @upper on FIELD_DEFINITION', '', 'type Query {', ' greeting: String', '}'].join('\n') + * ``` + */ +export declare function printSchema(schema: GraphQLSchema): string; +/** + * Prints the introspection schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printIntrospectionSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const printed = printIntrospectionSchema(schema); + * + * printed; // matches /type __Schema/ + * printed; // matches /enum __TypeKind/ + * printed; // does not match /type Query/ + * ``` + */ +export declare function printIntrospectionSchema(schema: GraphQLSchema): string; +/** + * Prints the type. + * @param type - The GraphQL type to inspect. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printType } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * printType(schema.getType('User')); // => ['type User {', ' id: ID!', ' name: String', '}'].join('\n') + * ``` + */ +export declare function printType(type: GraphQLNamedType): string; diff --git a/node_modules/graphql/utilities/printSchema.js b/node_modules/graphql/utilities/printSchema.js new file mode 100644 index 0000000000000000000000000000000000000000..39983e34040286f5dca6ad1db7884b2129e4ac29 --- /dev/null +++ b/node_modules/graphql/utilities/printSchema.js @@ -0,0 +1,405 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.printIntrospectionSchema = printIntrospectionSchema; +exports.printSchema = printSchema; +exports.printType = printType; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _blockString = require('../language/blockString.js'); + +var _kinds = require('../language/kinds.js'); + +var _printer = require('../language/printer.js'); + +var _definition = require('../type/definition.js'); + +var _directives = require('../type/directives.js'); + +var _introspection = require('../type/introspection.js'); + +var _scalars = require('../type/scalars.js'); + +var _astFromValue = require('./astFromValue.js'); + +/** @category Schema Printing */ + +/** + * Prints the schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * printSchema(schema); // => ['directive @upper on FIELD_DEFINITION', '', 'type Query {', ' greeting: String', '}'].join('\n') + * ``` + */ +function printSchema(schema) { + return printFilteredSchema( + schema, + (n) => !(0, _directives.isSpecifiedDirective)(n), + isDefinedType, + ); +} +/** + * Prints the introspection schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printIntrospectionSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const printed = printIntrospectionSchema(schema); + * + * printed; // matches /type __Schema/ + * printed; // matches /enum __TypeKind/ + * printed; // does not match /type Query/ + * ``` + */ + +function printIntrospectionSchema(schema) { + return printFilteredSchema( + schema, + _directives.isSpecifiedDirective, + _introspection.isIntrospectionType, + ); +} + +function isDefinedType(type) { + return ( + !(0, _scalars.isSpecifiedScalarType)(type) && + !(0, _introspection.isIntrospectionType)(type) + ); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [ + printSchemaDefinition(schema), + ...directives.map((directive) => printDirective(directive)), + ...types.map((type) => printType(type)), + ] + .filter(Boolean) + .join('\n\n'); +} + +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + + const operationTypes = []; + const queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + + const mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + + return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. + * + * @internal + */ + +function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + const mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} +/** + * Prints the type. + * @param type - The GraphQL type to inspect. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printType } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * printType(schema.getType('User')); // => ['type User {', ' id: ID!', ' name: String', '}'].join('\n') + * ``` + */ + +function printType(type) { + if ((0, _definition.isScalarType)(type)) { + return printScalar(type); + } + + if ((0, _definition.isObjectType)(type)) { + return printObject(type); + } + + if ((0, _definition.isInterfaceType)(type)) { + return printInterface(type); + } + + if ((0, _definition.isUnionType)(type)) { + return printUnion(type); + } + + if ((0, _definition.isEnumType)(type)) { + return printEnum(type); + } + + if ((0, _definition.isInputObjectType)(type)) { + return printInputObject(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); +} + +function printScalar(type) { + return ( + printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type) + ); +} + +function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length + ? ' implements ' + interfaces.map((i) => i.name).join(' & ') + : ''; +} + +function printObject(type) { + return ( + printDescription(type) + + `type ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); +} + +function printInterface(type) { + return ( + printDescription(type) + + `interface ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); +} + +function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type) { + const values = type + .getValues() + .map( + (value, i) => + printDescription(value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value.deprecationReason), + ); + return printDescription(type) + `enum ${type.name}` + printBlock(values); +} + +function printInputObject(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f), + ); + return ( + printDescription(type) + + `input ${type.name}` + + (type.isOneOf ? ' @oneOf' : '') + + printBlock(fields) + ); +} + +function printFields(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => + printDescription(f, ' ', !i) + + ' ' + + f.name + + printArgs(f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f.deprecationReason), + ); + return printBlock(fields); +} + +function printBlock(items) { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; +} + +function printArgs(args, indentation = '') { + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + if (args.every((arg) => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return ( + '(\n' + + args + .map( + (arg, i) => + printDescription(arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg) { + const defaultAST = (0, _astFromValue.astFromValue)( + arg.defaultValue, + arg.type, + ); + let argDecl = arg.name + ': ' + String(arg.type); + + if (defaultAST) { + argDecl += ` = ${(0, _printer.print)(defaultAST)}`; + } + + return argDecl + printDeprecated(arg.deprecationReason); +} + +function printDirective(directive) { + return ( + printDescription(directive) + + 'directive @' + + directive.name + + printArgs(directive.args) + + printDeprecated(directive.deprecationReason) + + (directive.isRepeatable ? ' repeatable' : '') + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + + if (reason !== _directives.DEFAULT_DEPRECATION_REASON) { + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: reason, + }); + return ` @deprecated(reason: ${astValue})`; + } + + return ' @deprecated'; +} + +function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ''; + } + + const astValue = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: scalar.specifiedByURL, + }); + return ` @specifiedBy(url: ${astValue})`; +} + +function printDescription(def, indentation = '', firstInBlock = true) { + const { description } = def; + + if (description == null) { + return ''; + } + + const blockString = (0, _printer.print)({ + kind: _kinds.Kind.STRING, + value: description, + block: (0, _blockString.isPrintableAsBlockString)(description), + }); + const prefix = + indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} diff --git a/node_modules/graphql/utilities/printSchema.mjs b/node_modules/graphql/utilities/printSchema.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a9f52e1f1aeb4b0390b33bacea1dc6963f6e19bb --- /dev/null +++ b/node_modules/graphql/utilities/printSchema.mjs @@ -0,0 +1,382 @@ +/** @category Schema Printing */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { isPrintableAsBlockString } from '../language/blockString.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { print } from '../language/printer.mjs'; +import { + isEnumType, + isInputObjectType, + isInterfaceType, + isObjectType, + isScalarType, + isUnionType, +} from '../type/definition.mjs'; +import { + DEFAULT_DEPRECATION_REASON, + isSpecifiedDirective, +} from '../type/directives.mjs'; +import { isIntrospectionType } from '../type/introspection.mjs'; +import { isSpecifiedScalarType } from '../type/scalars.mjs'; +import { astFromValue } from './astFromValue.mjs'; +/** + * Prints the schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @upper on FIELD_DEFINITION + * + * type Query { + * greeting: String @upper + * } + * `); + * + * printSchema(schema); // => ['directive @upper on FIELD_DEFINITION', '', 'type Query {', ' greeting: String', '}'].join('\n') + * ``` + */ + +export function printSchema(schema) { + return printFilteredSchema( + schema, + (n) => !isSpecifiedDirective(n), + isDefinedType, + ); +} +/** + * Prints the introspection schema. + * @param schema - GraphQL schema to use. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printIntrospectionSchema } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * const printed = printIntrospectionSchema(schema); + * + * printed; // matches /type __Schema/ + * printed; // matches /enum __TypeKind/ + * printed; // does not match /type Query/ + * ``` + */ + +export function printIntrospectionSchema(schema) { + return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType); +} + +function isDefinedType(type) { + return !isSpecifiedScalarType(type) && !isIntrospectionType(type); +} + +function printFilteredSchema(schema, directiveFilter, typeFilter) { + const directives = schema.getDirectives().filter(directiveFilter); + const types = Object.values(schema.getTypeMap()).filter(typeFilter); + return [ + printSchemaDefinition(schema), + ...directives.map((directive) => printDirective(directive)), + ...types.map((type) => printType(type)), + ] + .filter(Boolean) + .join('\n\n'); +} + +function printSchemaDefinition(schema) { + if (schema.description == null && isSchemaOfCommonNames(schema)) { + return; + } + + const operationTypes = []; + const queryType = schema.getQueryType(); + + if (queryType) { + operationTypes.push(` query: ${queryType.name}`); + } + + const mutationType = schema.getMutationType(); + + if (mutationType) { + operationTypes.push(` mutation: ${mutationType.name}`); + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + operationTypes.push(` subscription: ${subscriptionType.name}`); + } + + return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; +} +/** + * GraphQL schema define root types for each type of operation. These types are + * the same as any other type and can be named in any manner, however there is + * a common naming convention: + * + * ```graphql + * schema { + * query: Query + * mutation: Mutation + * subscription: Subscription + * } + * ``` + * + * When using this naming convention, the schema description can be omitted. + * + * @internal + */ + +function isSchemaOfCommonNames(schema) { + const queryType = schema.getQueryType(); + + if (queryType && queryType.name !== 'Query') { + return false; + } + + const mutationType = schema.getMutationType(); + + if (mutationType && mutationType.name !== 'Mutation') { + return false; + } + + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType && subscriptionType.name !== 'Subscription') { + return false; + } + + return true; +} +/** + * Prints the type. + * @param type - The GraphQL type to inspect. + * @returns The printed string representation. + * @example + * ```ts + * import { buildSchema, printType } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * id: ID! + * name: String + * } + * + * type Query { + * viewer: User + * } + * `); + * + * printType(schema.getType('User')); // => ['type User {', ' id: ID!', ' name: String', '}'].join('\n') + * ``` + */ + +export function printType(type) { + if (isScalarType(type)) { + return printScalar(type); + } + + if (isObjectType(type)) { + return printObject(type); + } + + if (isInterfaceType(type)) { + return printInterface(type); + } + + if (isUnionType(type)) { + return printUnion(type); + } + + if (isEnumType(type)) { + return printEnum(type); + } + + if (isInputObjectType(type)) { + return printInputObject(type); + } + /* c8 ignore next 3 */ + // Not reachable, all possible types have been considered. + + false || invariant(false, 'Unexpected type: ' + inspect(type)); +} + +function printScalar(type) { + return ( + printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type) + ); +} + +function printImplementedInterfaces(type) { + const interfaces = type.getInterfaces(); + return interfaces.length + ? ' implements ' + interfaces.map((i) => i.name).join(' & ') + : ''; +} + +function printObject(type) { + return ( + printDescription(type) + + `type ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); +} + +function printInterface(type) { + return ( + printDescription(type) + + `interface ${type.name}` + + printImplementedInterfaces(type) + + printFields(type) + ); +} + +function printUnion(type) { + const types = type.getTypes(); + const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; + return printDescription(type) + 'union ' + type.name + possibleTypes; +} + +function printEnum(type) { + const values = type + .getValues() + .map( + (value, i) => + printDescription(value, ' ', !i) + + ' ' + + value.name + + printDeprecated(value.deprecationReason), + ); + return printDescription(type) + `enum ${type.name}` + printBlock(values); +} + +function printInputObject(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f), + ); + return ( + printDescription(type) + + `input ${type.name}` + + (type.isOneOf ? ' @oneOf' : '') + + printBlock(fields) + ); +} + +function printFields(type) { + const fields = Object.values(type.getFields()).map( + (f, i) => + printDescription(f, ' ', !i) + + ' ' + + f.name + + printArgs(f.args, ' ') + + ': ' + + String(f.type) + + printDeprecated(f.deprecationReason), + ); + return printBlock(fields); +} + +function printBlock(items) { + return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; +} + +function printArgs(args, indentation = '') { + if (args.length === 0) { + return ''; + } // If every arg does not have a description, print them on one line. + + if (args.every((arg) => !arg.description)) { + return '(' + args.map(printInputValue).join(', ') + ')'; + } + + return ( + '(\n' + + args + .map( + (arg, i) => + printDescription(arg, ' ' + indentation, !i) + + ' ' + + indentation + + printInputValue(arg), + ) + .join('\n') + + '\n' + + indentation + + ')' + ); +} + +function printInputValue(arg) { + const defaultAST = astFromValue(arg.defaultValue, arg.type); + let argDecl = arg.name + ': ' + String(arg.type); + + if (defaultAST) { + argDecl += ` = ${print(defaultAST)}`; + } + + return argDecl + printDeprecated(arg.deprecationReason); +} + +function printDirective(directive) { + return ( + printDescription(directive) + + 'directive @' + + directive.name + + printArgs(directive.args) + + printDeprecated(directive.deprecationReason) + + (directive.isRepeatable ? ' repeatable' : '') + + ' on ' + + directive.locations.join(' | ') + ); +} + +function printDeprecated(reason) { + if (reason == null) { + return ''; + } + + if (reason !== DEFAULT_DEPRECATION_REASON) { + const astValue = print({ + kind: Kind.STRING, + value: reason, + }); + return ` @deprecated(reason: ${astValue})`; + } + + return ' @deprecated'; +} + +function printSpecifiedByURL(scalar) { + if (scalar.specifiedByURL == null) { + return ''; + } + + const astValue = print({ + kind: Kind.STRING, + value: scalar.specifiedByURL, + }); + return ` @specifiedBy(url: ${astValue})`; +} + +function printDescription(def, indentation = '', firstInBlock = true) { + const { description } = def; + + if (description == null) { + return ''; + } + + const blockString = print({ + kind: Kind.STRING, + value: description, + block: isPrintableAsBlockString(description), + }); + const prefix = + indentation && !firstInBlock ? '\n' + indentation : indentation; + return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; +} diff --git a/node_modules/graphql/utilities/resolveSchemaCoordinate.d.ts b/node_modules/graphql/utilities/resolveSchemaCoordinate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c1aaaf95dc4530416d0f4eb4733552481553949c --- /dev/null +++ b/node_modules/graphql/utilities/resolveSchemaCoordinate.d.ts @@ -0,0 +1,142 @@ +/** @category Schema Coordinates */ +import type { SchemaCoordinateNode } from '../language/ast'; +import type { Source } from '../language/source'; +import type { + GraphQLArgument, + GraphQLEnumType, + GraphQLEnumValue, + GraphQLField, + GraphQLInputField, + GraphQLInputObjectType, + GraphQLInterfaceType, + GraphQLNamedType, + GraphQLObjectType, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +/** + * A resolved schema element may be one of the following kinds: + * + * @internal + */ +export interface ResolvedNamedType { + readonly kind: 'NamedType'; + readonly type: GraphQLNamedType; +} +/** @internal */ +export interface ResolvedField { + readonly kind: 'Field'; + readonly type: GraphQLObjectType | GraphQLInterfaceType; + readonly field: GraphQLField; +} +/** @internal */ +export interface ResolvedInputField { + readonly kind: 'InputField'; + readonly type: GraphQLInputObjectType; + readonly inputField: GraphQLInputField; +} +/** @internal */ +export interface ResolvedEnumValue { + readonly kind: 'EnumValue'; + readonly type: GraphQLEnumType; + readonly enumValue: GraphQLEnumValue; +} +/** @internal */ +export interface ResolvedFieldArgument { + readonly kind: 'FieldArgument'; + readonly type: GraphQLObjectType | GraphQLInterfaceType; + readonly field: GraphQLField; + readonly fieldArgument: GraphQLArgument; +} +/** @internal */ +export interface ResolvedDirective { + readonly kind: 'Directive'; + readonly directive: GraphQLDirective; +} +/** @internal */ +export interface ResolvedDirectiveArgument { + readonly kind: 'DirectiveArgument'; + readonly directive: GraphQLDirective; + readonly directiveArgument: GraphQLArgument; +} +/** A schema element resolved from a schema coordinate. */ +export declare type ResolvedSchemaElement = + | ResolvedNamedType + | ResolvedField + | ResolvedInputField + | ResolvedEnumValue + | ResolvedFieldArgument + | ResolvedDirective + | ResolvedDirectiveArgument; +/** + * A schema coordinate is resolved in the context of a GraphQL schema to + * uniquely identify a schema element. It returns undefined if the schema + * coordinate does not resolve to a schema element, meta-field, or introspection + * schema element. It will throw if the containing schema element (if + * applicable) does not exist. + * + * https://spec.graphql.org/draft/#sec-Schema-Coordinates.Semantics + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the coordinate, or undefined if none exists. + * @example + * ```ts + * import { buildSchema, resolveSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @tag(name: String!) on FIELD_DEFINITION + * + * input ReviewInput { + * stars: Int! + * } + * + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * reviews(input: ReviewInput): [String] @tag(name: "reviews") + * } + * `); + * + * resolveSchemaCoordinate(schema, 'Query').kind; // => 'NamedType' + * resolveSchemaCoordinate(schema, 'Query.reviews').kind; // => 'Field' + * resolveSchemaCoordinate(schema, 'Query.reviews(input:)').kind; // => 'FieldArgument' + * resolveSchemaCoordinate(schema, 'ReviewInput.stars').kind; // => 'InputField' + * resolveSchemaCoordinate(schema, 'Episode.NEW_HOPE').kind; // => 'EnumValue' + * resolveSchemaCoordinate(schema, '@tag').kind; // => 'Directive' + * resolveSchemaCoordinate(schema, '@tag(name:)').kind; // => 'DirectiveArgument' + * resolveSchemaCoordinate(schema, 'Query.missing'); // => undefined + * ``` + */ +export declare function resolveSchemaCoordinate( + schema: GraphQLSchema, + schemaCoordinate: string | Source, +): ResolvedSchemaElement | undefined; +/** + * Resolves schema coordinate from a parsed SchemaCoordinate node. + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the parsed coordinate, or undefined if none exists. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * import { buildSchema, resolveASTSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const coordinate = parseSchemaCoordinate('Query.greeting(name:)'); + * const resolved = resolveASTSchemaCoordinate(schema, coordinate); + * + * resolved.kind; // => 'FieldArgument' + * resolved.field.name; // => 'greeting' + * resolved.fieldArgument.name; // => 'name' + * ``` + */ +export declare function resolveASTSchemaCoordinate( + schema: GraphQLSchema, + schemaCoordinate: SchemaCoordinateNode, +): ResolvedSchemaElement | undefined; diff --git a/node_modules/graphql/utilities/resolveSchemaCoordinate.js b/node_modules/graphql/utilities/resolveSchemaCoordinate.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c0b374ab3b0efce3b974eed1ff5eab01a6cc59 --- /dev/null +++ b/node_modules/graphql/utilities/resolveSchemaCoordinate.js @@ -0,0 +1,324 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.resolveASTSchemaCoordinate = resolveASTSchemaCoordinate; +exports.resolveSchemaCoordinate = resolveSchemaCoordinate; + +var _inspect = require('../jsutils/inspect.js'); + +var _kinds = require('../language/kinds.js'); + +var _parser = require('../language/parser.js'); + +var _definition = require('../type/definition.js'); + +/** @category Schema Coordinates */ + +/** + * A schema coordinate is resolved in the context of a GraphQL schema to + * uniquely identify a schema element. It returns undefined if the schema + * coordinate does not resolve to a schema element, meta-field, or introspection + * schema element. It will throw if the containing schema element (if + * applicable) does not exist. + * + * https://spec.graphql.org/draft/#sec-Schema-Coordinates.Semantics + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the coordinate, or undefined if none exists. + * @example + * ```ts + * import { buildSchema, resolveSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @tag(name: String!) on FIELD_DEFINITION + * + * input ReviewInput { + * stars: Int! + * } + * + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * reviews(input: ReviewInput): [String] @tag(name: "reviews") + * } + * `); + * + * resolveSchemaCoordinate(schema, 'Query').kind; // => 'NamedType' + * resolveSchemaCoordinate(schema, 'Query.reviews').kind; // => 'Field' + * resolveSchemaCoordinate(schema, 'Query.reviews(input:)').kind; // => 'FieldArgument' + * resolveSchemaCoordinate(schema, 'ReviewInput.stars').kind; // => 'InputField' + * resolveSchemaCoordinate(schema, 'Episode.NEW_HOPE').kind; // => 'EnumValue' + * resolveSchemaCoordinate(schema, '@tag').kind; // => 'Directive' + * resolveSchemaCoordinate(schema, '@tag(name:)').kind; // => 'DirectiveArgument' + * resolveSchemaCoordinate(schema, 'Query.missing'); // => undefined + * ``` + */ +function resolveSchemaCoordinate(schema, schemaCoordinate) { + return resolveASTSchemaCoordinate( + schema, + (0, _parser.parseSchemaCoordinate)(schemaCoordinate), + ); +} +/** + * TypeCoordinate : Name + * + * @internal + */ + +function resolveTypeCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of {Name}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 2. Return the type in the {schema} named {typeName} if it exists. + + if (type == null) { + return; + } + + return { + kind: 'NamedType', + type, + }; +} +/** + * MemberCoordinate : Name . Name + * + * @internal + */ + +function resolveMemberCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of the first {Name}. + // 2. Let {type} be the type in the {schema} named {typeName}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 3. Assert: {type} must exist, and must be an Enum, Input Object, Object or Interface type. + + if (!type) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + typeName, + )} to be defined as a type in the schema.`, + ); + } + + if ( + !(0, _definition.isEnumType)(type) && + !(0, _definition.isInputObjectType)(type) && + !(0, _definition.isObjectType)(type) && + !(0, _definition.isInterfaceType)(type) + ) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + typeName, + )} to be an Enum, Input Object, Object or Interface type.`, + ); + } // 4. If {type} is an Enum type: + + if ((0, _definition.isEnumType)(type)) { + // 1. Let {enumValueName} be the value of the second {Name}. + const enumValueName = schemaCoordinate.memberName.value; + const enumValue = type.getValue(enumValueName); // 2. Return the enum value of {type} named {enumValueName} if it exists. + + if (enumValue == null) { + return; + } + + return { + kind: 'EnumValue', + type, + enumValue, + }; + } // 5. Otherwise, if {type} is an Input Object type: + + if ((0, _definition.isInputObjectType)(type)) { + // 1. Let {inputFieldName} be the value of the second {Name}. + const inputFieldName = schemaCoordinate.memberName.value; + const inputField = type.getFields()[inputFieldName]; // 2. Return the input field of {type} named {inputFieldName} if it exists. + + if (inputField == null) { + return; + } + + return { + kind: 'InputField', + type, + inputField, + }; + } // 6. Otherwise: + // 1. Let {fieldName} be the value of the second {Name}. + + const fieldName = schemaCoordinate.memberName.value; + const field = type.getFields()[fieldName]; // 2. Return the field of {type} named {fieldName} if it exists. + + if (field == null) { + return; + } + + return { + kind: 'Field', + type, + field, + }; +} +/** + * ArgumentCoordinate : Name . Name ( Name : ) + * + * @internal + */ + +function resolveArgumentCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of the first {Name}. + // 2. Let {type} be the type in the {schema} named {typeName}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 3. Assert: {type} must exist, and be an Object or Interface type. + + if (type == null) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + typeName, + )} to be defined as a type in the schema.`, + ); + } + + if ( + !(0, _definition.isObjectType)(type) && + !(0, _definition.isInterfaceType)(type) + ) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + typeName, + )} to be an object type or interface type.`, + ); + } // 4. Let {fieldName} be the value of the second {Name}. + // 5. Let {field} be the field of {type} named {fieldName}. + + const fieldName = schemaCoordinate.fieldName.value; + const field = type.getFields()[fieldName]; // 7. Assert: {field} must exist. + + if (field == null) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + fieldName, + )} to exist as a field of type ${(0, _inspect.inspect)( + typeName, + )} in the schema.`, + ); + } // 7. Let {fieldArgumentName} be the value of the third {Name}. + + const fieldArgumentName = schemaCoordinate.argumentName.value; + const fieldArgument = field.args.find( + (arg) => arg.name === fieldArgumentName, + ); // 8. Return the argument of {field} named {fieldArgumentName} if it exists. + + if (fieldArgument == null) { + return; + } + + return { + kind: 'FieldArgument', + type, + field, + fieldArgument, + }; +} +/** + * DirectiveCoordinate : \@ Name + * + * @internal + */ + +function resolveDirectiveCoordinate(schema, schemaCoordinate) { + // 1. Let {directiveName} be the value of {Name}. + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); // 2. Return the directive in the {schema} named {directiveName} if it exists. + + if (!directive) { + return; + } + + return { + kind: 'Directive', + directive, + }; +} +/** + * DirectiveArgumentCoordinate : \@ Name ( Name : ) + * + * @internal + */ + +function resolveDirectiveArgumentCoordinate(schema, schemaCoordinate) { + // 1. Let {directiveName} be the value of the first {Name}. + // 2. Let {directive} be the directive in the {schema} named {directiveName}. + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); // 3. Assert {directive} must exist. + + if (!directive) { + throw new Error( + `Expected ${(0, _inspect.inspect)( + directiveName, + )} to be defined as a directive in the schema.`, + ); + } // 4. Let {directiveArgumentName} be the value of the second {Name}. + + const { + argumentName: { value: directiveArgumentName }, + } = schemaCoordinate; + const directiveArgument = directive.args.find( + (arg) => arg.name === directiveArgumentName, + ); // 5. Return the argument of {directive} named {directiveArgumentName} if it exists. + + if (!directiveArgument) { + return; + } + + return { + kind: 'DirectiveArgument', + directive, + directiveArgument, + }; +} +/** + * Resolves schema coordinate from a parsed SchemaCoordinate node. + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the parsed coordinate, or undefined if none exists. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * import { buildSchema, resolveASTSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const coordinate = parseSchemaCoordinate('Query.greeting(name:)'); + * const resolved = resolveASTSchemaCoordinate(schema, coordinate); + * + * resolved.kind; // => 'FieldArgument' + * resolved.field.name; // => 'greeting' + * resolved.fieldArgument.name; // => 'name' + * ``` + */ + +function resolveASTSchemaCoordinate(schema, schemaCoordinate) { + switch (schemaCoordinate.kind) { + case _kinds.Kind.TYPE_COORDINATE: + return resolveTypeCoordinate(schema, schemaCoordinate); + + case _kinds.Kind.MEMBER_COORDINATE: + return resolveMemberCoordinate(schema, schemaCoordinate); + + case _kinds.Kind.ARGUMENT_COORDINATE: + return resolveArgumentCoordinate(schema, schemaCoordinate); + + case _kinds.Kind.DIRECTIVE_COORDINATE: + return resolveDirectiveCoordinate(schema, schemaCoordinate); + + case _kinds.Kind.DIRECTIVE_ARGUMENT_COORDINATE: + return resolveDirectiveArgumentCoordinate(schema, schemaCoordinate); + } +} diff --git a/node_modules/graphql/utilities/resolveSchemaCoordinate.mjs b/node_modules/graphql/utilities/resolveSchemaCoordinate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f7772205e2b06e16a61fce1ea4af78ca8e0b22e1 --- /dev/null +++ b/node_modules/graphql/utilities/resolveSchemaCoordinate.mjs @@ -0,0 +1,306 @@ +/** @category Schema Coordinates */ +import { inspect } from '../jsutils/inspect.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { parseSchemaCoordinate } from '../language/parser.mjs'; +import { + isEnumType, + isInputObjectType, + isInterfaceType, + isObjectType, +} from '../type/definition.mjs'; + +/** + * A schema coordinate is resolved in the context of a GraphQL schema to + * uniquely identify a schema element. It returns undefined if the schema + * coordinate does not resolve to a schema element, meta-field, or introspection + * schema element. It will throw if the containing schema element (if + * applicable) does not exist. + * + * https://spec.graphql.org/draft/#sec-Schema-Coordinates.Semantics + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the coordinate, or undefined if none exists. + * @example + * ```ts + * import { buildSchema, resolveSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * directive @tag(name: String!) on FIELD_DEFINITION + * + * input ReviewInput { + * stars: Int! + * } + * + * enum Episode { + * NEW_HOPE + * } + * + * type Query { + * reviews(input: ReviewInput): [String] @tag(name: "reviews") + * } + * `); + * + * resolveSchemaCoordinate(schema, 'Query').kind; // => 'NamedType' + * resolveSchemaCoordinate(schema, 'Query.reviews').kind; // => 'Field' + * resolveSchemaCoordinate(schema, 'Query.reviews(input:)').kind; // => 'FieldArgument' + * resolveSchemaCoordinate(schema, 'ReviewInput.stars').kind; // => 'InputField' + * resolveSchemaCoordinate(schema, 'Episode.NEW_HOPE').kind; // => 'EnumValue' + * resolveSchemaCoordinate(schema, '@tag').kind; // => 'Directive' + * resolveSchemaCoordinate(schema, '@tag(name:)').kind; // => 'DirectiveArgument' + * resolveSchemaCoordinate(schema, 'Query.missing'); // => undefined + * ``` + */ +export function resolveSchemaCoordinate(schema, schemaCoordinate) { + return resolveASTSchemaCoordinate( + schema, + parseSchemaCoordinate(schemaCoordinate), + ); +} +/** + * TypeCoordinate : Name + * + * @internal + */ + +function resolveTypeCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of {Name}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 2. Return the type in the {schema} named {typeName} if it exists. + + if (type == null) { + return; + } + + return { + kind: 'NamedType', + type, + }; +} +/** + * MemberCoordinate : Name . Name + * + * @internal + */ + +function resolveMemberCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of the first {Name}. + // 2. Let {type} be the type in the {schema} named {typeName}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 3. Assert: {type} must exist, and must be an Enum, Input Object, Object or Interface type. + + if (!type) { + throw new Error( + `Expected ${inspect(typeName)} to be defined as a type in the schema.`, + ); + } + + if ( + !isEnumType(type) && + !isInputObjectType(type) && + !isObjectType(type) && + !isInterfaceType(type) + ) { + throw new Error( + `Expected ${inspect( + typeName, + )} to be an Enum, Input Object, Object or Interface type.`, + ); + } // 4. If {type} is an Enum type: + + if (isEnumType(type)) { + // 1. Let {enumValueName} be the value of the second {Name}. + const enumValueName = schemaCoordinate.memberName.value; + const enumValue = type.getValue(enumValueName); // 2. Return the enum value of {type} named {enumValueName} if it exists. + + if (enumValue == null) { + return; + } + + return { + kind: 'EnumValue', + type, + enumValue, + }; + } // 5. Otherwise, if {type} is an Input Object type: + + if (isInputObjectType(type)) { + // 1. Let {inputFieldName} be the value of the second {Name}. + const inputFieldName = schemaCoordinate.memberName.value; + const inputField = type.getFields()[inputFieldName]; // 2. Return the input field of {type} named {inputFieldName} if it exists. + + if (inputField == null) { + return; + } + + return { + kind: 'InputField', + type, + inputField, + }; + } // 6. Otherwise: + // 1. Let {fieldName} be the value of the second {Name}. + + const fieldName = schemaCoordinate.memberName.value; + const field = type.getFields()[fieldName]; // 2. Return the field of {type} named {fieldName} if it exists. + + if (field == null) { + return; + } + + return { + kind: 'Field', + type, + field, + }; +} +/** + * ArgumentCoordinate : Name . Name ( Name : ) + * + * @internal + */ + +function resolveArgumentCoordinate(schema, schemaCoordinate) { + // 1. Let {typeName} be the value of the first {Name}. + // 2. Let {type} be the type in the {schema} named {typeName}. + const typeName = schemaCoordinate.name.value; + const type = schema.getType(typeName); // 3. Assert: {type} must exist, and be an Object or Interface type. + + if (type == null) { + throw new Error( + `Expected ${inspect(typeName)} to be defined as a type in the schema.`, + ); + } + + if (!isObjectType(type) && !isInterfaceType(type)) { + throw new Error( + `Expected ${inspect(typeName)} to be an object type or interface type.`, + ); + } // 4. Let {fieldName} be the value of the second {Name}. + // 5. Let {field} be the field of {type} named {fieldName}. + + const fieldName = schemaCoordinate.fieldName.value; + const field = type.getFields()[fieldName]; // 7. Assert: {field} must exist. + + if (field == null) { + throw new Error( + `Expected ${inspect(fieldName)} to exist as a field of type ${inspect( + typeName, + )} in the schema.`, + ); + } // 7. Let {fieldArgumentName} be the value of the third {Name}. + + const fieldArgumentName = schemaCoordinate.argumentName.value; + const fieldArgument = field.args.find( + (arg) => arg.name === fieldArgumentName, + ); // 8. Return the argument of {field} named {fieldArgumentName} if it exists. + + if (fieldArgument == null) { + return; + } + + return { + kind: 'FieldArgument', + type, + field, + fieldArgument, + }; +} +/** + * DirectiveCoordinate : \@ Name + * + * @internal + */ + +function resolveDirectiveCoordinate(schema, schemaCoordinate) { + // 1. Let {directiveName} be the value of {Name}. + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); // 2. Return the directive in the {schema} named {directiveName} if it exists. + + if (!directive) { + return; + } + + return { + kind: 'Directive', + directive, + }; +} +/** + * DirectiveArgumentCoordinate : \@ Name ( Name : ) + * + * @internal + */ + +function resolveDirectiveArgumentCoordinate(schema, schemaCoordinate) { + // 1. Let {directiveName} be the value of the first {Name}. + // 2. Let {directive} be the directive in the {schema} named {directiveName}. + const directiveName = schemaCoordinate.name.value; + const directive = schema.getDirective(directiveName); // 3. Assert {directive} must exist. + + if (!directive) { + throw new Error( + `Expected ${inspect( + directiveName, + )} to be defined as a directive in the schema.`, + ); + } // 4. Let {directiveArgumentName} be the value of the second {Name}. + + const { + argumentName: { value: directiveArgumentName }, + } = schemaCoordinate; + const directiveArgument = directive.args.find( + (arg) => arg.name === directiveArgumentName, + ); // 5. Return the argument of {directive} named {directiveArgumentName} if it exists. + + if (!directiveArgument) { + return; + } + + return { + kind: 'DirectiveArgument', + directive, + directiveArgument, + }; +} +/** + * Resolves schema coordinate from a parsed SchemaCoordinate node. + * @param schema - GraphQL schema to use. + * @param schemaCoordinate - The schema coordinate to resolve. + * @returns The schema element identified by the parsed coordinate, or undefined if none exists. + * @example + * ```ts + * import { parseSchemaCoordinate } from 'graphql/language'; + * import { buildSchema, resolveASTSchemaCoordinate } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const coordinate = parseSchemaCoordinate('Query.greeting(name:)'); + * const resolved = resolveASTSchemaCoordinate(schema, coordinate); + * + * resolved.kind; // => 'FieldArgument' + * resolved.field.name; // => 'greeting' + * resolved.fieldArgument.name; // => 'name' + * ``` + */ + +export function resolveASTSchemaCoordinate(schema, schemaCoordinate) { + switch (schemaCoordinate.kind) { + case Kind.TYPE_COORDINATE: + return resolveTypeCoordinate(schema, schemaCoordinate); + + case Kind.MEMBER_COORDINATE: + return resolveMemberCoordinate(schema, schemaCoordinate); + + case Kind.ARGUMENT_COORDINATE: + return resolveArgumentCoordinate(schema, schemaCoordinate); + + case Kind.DIRECTIVE_COORDINATE: + return resolveDirectiveCoordinate(schema, schemaCoordinate); + + case Kind.DIRECTIVE_ARGUMENT_COORDINATE: + return resolveDirectiveArgumentCoordinate(schema, schemaCoordinate); + } +} diff --git a/node_modules/graphql/utilities/separateOperations.d.ts b/node_modules/graphql/utilities/separateOperations.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..69d1d937950c0bfa551edda624bf8a14674f5e1c --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.d.ts @@ -0,0 +1,41 @@ +/** @category AST Utilities */ +import type { ObjMap } from '../jsutils/ObjMap'; +import type { DocumentNode } from '../language/ast'; +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + * @param documentAST - The parsed GraphQL document AST. + * @returns A map of operation names to documents containing each operation and its referenced fragments. + * @example + * ```ts + * import { parse, print } from 'graphql/language'; + * import { separateOperations } from 'graphql/utilities'; + * + * const document = parse(` + * query GetUser { + * viewer { + * ...UserFields + * } + * } + * + * query GetStatus { + * status + * } + * + * fragment UserFields on User { + * id + * } + * `); + * + * const separated = separateOperations(document); + * + * Object.keys(separated); // => ['GetUser', 'GetStatus'] + * print(separated.GetUser); // matches /fragment UserFields/ + * print(separated.GetStatus); // does not match /fragment UserFields/ + * ``` + */ +export declare function separateOperations( + documentAST: DocumentNode, +): ObjMap; diff --git a/node_modules/graphql/utilities/separateOperations.js b/node_modules/graphql/utilities/separateOperations.js new file mode 100644 index 0000000000000000000000000000000000000000..2b59bd9e7355f8241c2e695fd65183d366f64730 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.js @@ -0,0 +1,119 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.separateOperations = separateOperations; + +var _kinds = require('../language/kinds.js'); + +var _visitor = require('../language/visitor.js'); + +/** @category AST Utilities */ + +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + * @param documentAST - The parsed GraphQL document AST. + * @returns A map of operation names to documents containing each operation and its referenced fragments. + * @example + * ```ts + * import { parse, print } from 'graphql/language'; + * import { separateOperations } from 'graphql/utilities'; + * + * const document = parse(` + * query GetUser { + * viewer { + * ...UserFields + * } + * } + * + * query GetStatus { + * status + * } + * + * fragment UserFields on User { + * id + * } + * `); + * + * const separated = separateOperations(document); + * + * Object.keys(separated); // => ['GetUser', 'GetStatus'] + * print(separated.GetUser); // matches /fragment UserFields/ + * print(separated.GetStatus); // does not match /fragment UserFields/ + * ``` + */ +function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + + case _kinds.Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies( + definitionNode.selectionSet, + ); + break; + + default: // ignore non-executable definitions + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + + for (const operation of operations) { + const dependencies = new Set(); + + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: _kinds.Kind.DOCUMENT, + definitions: documentAST.definitions.filter( + (node) => + node === operation || + (node.kind === _kinds.Kind.FRAGMENT_DEFINITION && + dependencies.has(node.name.value)), + ), + }; + } + + return separatedDocumentASTs; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} + +function collectDependencies(selectionSet) { + const dependencies = []; + (0, _visitor.visit)(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + }, + }); + return dependencies; +} diff --git a/node_modules/graphql/utilities/separateOperations.mjs b/node_modules/graphql/utilities/separateOperations.mjs new file mode 100644 index 0000000000000000000000000000000000000000..fdb17b3f2342396b668d43c80706523df8a11189 --- /dev/null +++ b/node_modules/graphql/utilities/separateOperations.mjs @@ -0,0 +1,110 @@ +/** @category AST Utilities */ +import { Kind } from '../language/kinds.mjs'; +import { visit } from '../language/visitor.mjs'; +/** + * separateOperations accepts a single AST document which may contain many + * operations and fragments and returns a collection of AST documents each of + * which contains a single operation as well the fragment definitions it + * refers to. + * @param documentAST - The parsed GraphQL document AST. + * @returns A map of operation names to documents containing each operation and its referenced fragments. + * @example + * ```ts + * import { parse, print } from 'graphql/language'; + * import { separateOperations } from 'graphql/utilities'; + * + * const document = parse(` + * query GetUser { + * viewer { + * ...UserFields + * } + * } + * + * query GetStatus { + * status + * } + * + * fragment UserFields on User { + * id + * } + * `); + * + * const separated = separateOperations(document); + * + * Object.keys(separated); // => ['GetUser', 'GetStatus'] + * print(separated.GetUser); // matches /fragment UserFields/ + * print(separated.GetStatus); // does not match /fragment UserFields/ + * ``` + */ + +export function separateOperations(documentAST) { + const operations = []; + const depGraph = Object.create(null); // Populate metadata and build a dependency graph. + + for (const definitionNode of documentAST.definitions) { + switch (definitionNode.kind) { + case Kind.OPERATION_DEFINITION: + operations.push(definitionNode); + break; + + case Kind.FRAGMENT_DEFINITION: + depGraph[definitionNode.name.value] = collectDependencies( + definitionNode.selectionSet, + ); + break; + + default: // ignore non-executable definitions + } + } // For each operation, produce a new synthesized AST which includes only what + // is necessary for completing that operation. + + const separatedDocumentASTs = Object.create(null); + + for (const operation of operations) { + const dependencies = new Set(); + + for (const fragmentName of collectDependencies(operation.selectionSet)) { + collectTransitiveDependencies(dependencies, depGraph, fragmentName); + } // Provides the empty string for anonymous operations. + + const operationName = operation.name ? operation.name.value : ''; // The list of definition nodes to be included for this operation, sorted + // to retain the same order as the original document. + + separatedDocumentASTs[operationName] = { + kind: Kind.DOCUMENT, + definitions: documentAST.definitions.filter( + (node) => + node === operation || + (node.kind === Kind.FRAGMENT_DEFINITION && + dependencies.has(node.name.value)), + ), + }; + } + + return separatedDocumentASTs; +} + +// From a dependency graph, collects a list of transitive dependencies by +// recursing through a dependency graph. +function collectTransitiveDependencies(collected, depGraph, fromName) { + if (!collected.has(fromName)) { + collected.add(fromName); + const immediateDeps = depGraph[fromName]; + + if (immediateDeps !== undefined) { + for (const toName of immediateDeps) { + collectTransitiveDependencies(collected, depGraph, toName); + } + } + } +} + +function collectDependencies(selectionSet) { + const dependencies = []; + visit(selectionSet, { + FragmentSpread(node) { + dependencies.push(node.name.value); + }, + }); + return dependencies; +} diff --git a/node_modules/graphql/utilities/sortValueNode.d.ts b/node_modules/graphql/utilities/sortValueNode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d7a9de3380fb4637be6db72d44deb7766be38b4 --- /dev/null +++ b/node_modules/graphql/utilities/sortValueNode.d.ts @@ -0,0 +1,9 @@ +import type { ValueNode } from '../language/ast'; +/** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ +export declare function sortValueNode(valueNode: ValueNode): ValueNode; diff --git a/node_modules/graphql/utilities/sortValueNode.js b/node_modules/graphql/utilities/sortValueNode.js new file mode 100644 index 0000000000000000000000000000000000000000..cf4bbfd08077e517023b81f76ab8cb0b46d587d8 --- /dev/null +++ b/node_modules/graphql/utilities/sortValueNode.js @@ -0,0 +1,47 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.sortValueNode = sortValueNode; + +var _naturalCompare = require('../jsutils/naturalCompare.js'); + +var _kinds = require('../language/kinds.js'); + +/** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ +function sortValueNode(valueNode) { + switch (valueNode.kind) { + case _kinds.Kind.OBJECT: + return { ...valueNode, fields: sortFields(valueNode.fields) }; + + case _kinds.Kind.LIST: + return { ...valueNode, values: valueNode.values.map(sortValueNode) }; + + case _kinds.Kind.INT: + case _kinds.Kind.FLOAT: + case _kinds.Kind.STRING: + case _kinds.Kind.BOOLEAN: + case _kinds.Kind.NULL: + case _kinds.Kind.ENUM: + case _kinds.Kind.VARIABLE: + return valueNode; + } +} + +function sortFields(fields) { + return fields + .map((fieldNode) => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value), + })) + .sort((fieldA, fieldB) => + (0, _naturalCompare.naturalCompare)(fieldA.name.value, fieldB.name.value), + ); +} diff --git a/node_modules/graphql/utilities/sortValueNode.mjs b/node_modules/graphql/utilities/sortValueNode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..79bece3ea006f757539644dfee68c0186d4dc8fa --- /dev/null +++ b/node_modules/graphql/utilities/sortValueNode.mjs @@ -0,0 +1,39 @@ +import { naturalCompare } from '../jsutils/naturalCompare.mjs'; +import { Kind } from '../language/kinds.mjs'; +/** + * Sort ValueNode. + * + * This function returns a sorted copy of the given ValueNode. + * + * @internal + */ + +export function sortValueNode(valueNode) { + switch (valueNode.kind) { + case Kind.OBJECT: + return { ...valueNode, fields: sortFields(valueNode.fields) }; + + case Kind.LIST: + return { ...valueNode, values: valueNode.values.map(sortValueNode) }; + + case Kind.INT: + case Kind.FLOAT: + case Kind.STRING: + case Kind.BOOLEAN: + case Kind.NULL: + case Kind.ENUM: + case Kind.VARIABLE: + return valueNode; + } +} + +function sortFields(fields) { + return fields + .map((fieldNode) => ({ + ...fieldNode, + value: sortValueNode(fieldNode.value), + })) + .sort((fieldA, fieldB) => + naturalCompare(fieldA.name.value, fieldB.name.value), + ); +} diff --git a/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts b/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b3fd3846087c525da187ce6f32abed6b0bababdb --- /dev/null +++ b/node_modules/graphql/utilities/stripIgnoredCharacters.d.ts @@ -0,0 +1,69 @@ +/** @category AST Utilities */ +import { Source } from '../language/source'; +/** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * @param source - The GraphQL source text or source object. + * @returns A semantically equivalent GraphQL source string without ignored characters. + * @example Query source + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * @example SDL source + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + * @example + * ```ts + * import { stripIgnoredCharacters } from 'graphql/utilities'; + * + * const source = stripIgnoredCharacters('query Example { name }'); + * + * source; // => 'query Example{name}' + * ``` + */ +export declare function stripIgnoredCharacters(source: string | Source): string; diff --git a/node_modules/graphql/utilities/stripIgnoredCharacters.js b/node_modules/graphql/utilities/stripIgnoredCharacters.js new file mode 100644 index 0000000000000000000000000000000000000000..8ca274a4542ae6cf99e5c404e1b69008960d7527 --- /dev/null +++ b/node_modules/graphql/utilities/stripIgnoredCharacters.js @@ -0,0 +1,131 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.stripIgnoredCharacters = stripIgnoredCharacters; + +var _blockString = require('../language/blockString.js'); + +var _lexer = require('../language/lexer.js'); + +var _source = require('../language/source.js'); + +var _tokenKind = require('../language/tokenKind.js'); + +/** @category AST Utilities */ + +/** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * @param source - The GraphQL source text or source object. + * @returns A semantically equivalent GraphQL source string without ignored characters. + * @example Query source + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * @example SDL source + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + * @example + * ```ts + * import { stripIgnoredCharacters } from 'graphql/utilities'; + * + * const source = stripIgnoredCharacters('query Example { name }'); + * + * source; // => 'query Example{name}' + * ``` + */ +function stripIgnoredCharacters(source) { + const sourceObj = (0, _source.isSource)(source) + ? source + : new _source.Source(source); + const body = sourceObj.body; + const lexer = new _lexer.Lexer(sourceObj); + let strippedBody = ''; + let wasLastAddedTokenNonPunctuator = false; + + while (lexer.advance().kind !== _tokenKind.TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + * + * @internal + */ + + const isNonPunctuator = !(0, _lexer.isPunctuatorTokenKind)( + currentToken.kind, + ); + + if (wasLastAddedTokenNonPunctuator) { + if ( + isNonPunctuator || + currentToken.kind === _tokenKind.TokenKind.SPREAD + ) { + strippedBody += ' '; + } + } + + const tokenBody = body.slice(currentToken.start, currentToken.end); + + if (tokenKind === _tokenKind.TokenKind.BLOCK_STRING) { + strippedBody += (0, _blockString.printBlockString)(currentToken.value, { + minimize: true, + }); + } else { + strippedBody += tokenBody; + } + + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + + return strippedBody; +} diff --git a/node_modules/graphql/utilities/stripIgnoredCharacters.mjs b/node_modules/graphql/utilities/stripIgnoredCharacters.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ece76282b6d9748318a7ad257cea832c941df0ad --- /dev/null +++ b/node_modules/graphql/utilities/stripIgnoredCharacters.mjs @@ -0,0 +1,113 @@ +/** @category AST Utilities */ +import { printBlockString } from '../language/blockString.mjs'; +import { isPunctuatorTokenKind, Lexer } from '../language/lexer.mjs'; +import { isSource, Source } from '../language/source.mjs'; +import { TokenKind } from '../language/tokenKind.mjs'; +/** + * Strips characters that are not significant to the validity or execution + * of a GraphQL document: + * - UnicodeBOM + * - WhiteSpace + * - LineTerminator + * - Comment + * - Comma + * - BlockString indentation + * + * Note: It is required to have a delimiter character between neighboring + * non-punctuator tokens and this function always uses single space as delimiter. + * + * It is guaranteed that both input and output documents if parsed would result + * in the exact same AST except for nodes location. + * + * Warning: It is guaranteed that this function will always produce stable results. + * However, it's not guaranteed that it will stay the same between different + * releases due to bugfixes or changes in the GraphQL specification. + * @param source - The GraphQL source text or source object. + * @returns A semantically equivalent GraphQL source string without ignored characters. + * @example Query source + * ```graphql + * query SomeQuery($foo: String!, $bar: String) { + * someField(foo: $foo, bar: $bar) { + * a + * b { + * c + * d + * } + * } + * } + * ``` + * + * Becomes: + * + * ```graphql + * query SomeQuery($foo:String!$bar:String){someField(foo:$foo bar:$bar){a b{c d}}} + * ``` + * @example SDL source + * ```graphql + * """ + * Type description + * """ + * type Foo { + * """ + * Field description + * """ + * bar: String + * } + * ``` + * + * Becomes: + * + * ```graphql + * """Type description""" type Foo{"""Field description""" bar:String} + * ``` + * @example + * ```ts + * import { stripIgnoredCharacters } from 'graphql/utilities'; + * + * const source = stripIgnoredCharacters('query Example { name }'); + * + * source; // => 'query Example{name}' + * ``` + */ + +export function stripIgnoredCharacters(source) { + const sourceObj = isSource(source) ? source : new Source(source); + const body = sourceObj.body; + const lexer = new Lexer(sourceObj); + let strippedBody = ''; + let wasLastAddedTokenNonPunctuator = false; + + while (lexer.advance().kind !== TokenKind.EOF) { + const currentToken = lexer.token; + const tokenKind = currentToken.kind; + /** + * Every two non-punctuator tokens should have space between them. + * Also prevent case of non-punctuator token following by spread resulting + * in invalid token (e.g. `1...` is invalid Float token). + * + * @internal + */ + + const isNonPunctuator = !isPunctuatorTokenKind(currentToken.kind); + + if (wasLastAddedTokenNonPunctuator) { + if (isNonPunctuator || currentToken.kind === TokenKind.SPREAD) { + strippedBody += ' '; + } + } + + const tokenBody = body.slice(currentToken.start, currentToken.end); + + if (tokenKind === TokenKind.BLOCK_STRING) { + strippedBody += printBlockString(currentToken.value, { + minimize: true, + }); + } else { + strippedBody += tokenBody; + } + + wasLastAddedTokenNonPunctuator = isNonPunctuator; + } + + return strippedBody; +} diff --git a/node_modules/graphql/utilities/typeComparators.d.ts b/node_modules/graphql/utilities/typeComparators.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2c1e367598d98c521a8ff80d6c77182da44682ee --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.d.ts @@ -0,0 +1,116 @@ +/** @category Type Comparisons */ +import type { GraphQLCompositeType, GraphQLType } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Provided two types, return true if the types are equal (invariant). + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when both types are equal. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { isEqualType } from 'graphql/utilities'; + * + * isEqualType(GraphQLString, GraphQLString); // => true + * isEqualType(new GraphQLList(GraphQLString), new GraphQLList(GraphQLString)); // => true + * isEqualType(new GraphQLNonNull(GraphQLString), GraphQLString); // => false + * ``` + */ +export declare function isEqualType( + typeA: GraphQLType, + typeB: GraphQLType, +): boolean; +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + * @param schema - GraphQL schema to use. + * @param maybeSubType - The possible subtype to compare. + * @param superType - The possible supertype to compare. + * @returns True when `maybeSubType` is equal to or a subtype of `superType`. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { + * GraphQLNonNull, + * assertInterfaceType, + * assertObjectType, + * } from 'graphql/type'; + * import { isTypeSubTypeOf } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * + * isTypeSubTypeOf(schema, User, Node); // => true + * isTypeSubTypeOf(schema, new GraphQLNonNull(User), Node); // => true + * isTypeSubTypeOf(schema, Node, User); // => false + * ``` + */ +export declare function isTypeSubTypeOf( + schema: GraphQLSchema, + maybeSubType: GraphQLType, + superType: GraphQLType, +): boolean; +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + * @param schema - GraphQL schema to use. + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when the two composite types can apply to at least one common object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType, assertUnionType } from 'graphql/type'; + * import { doTypesOverlap } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * union StillImage = Photo + * + * type Query { + * media: [Media] + * } + * `); + * const Media = assertUnionType(schema.getType('Media')); + * const StillImage = assertUnionType(schema.getType('StillImage')); + * const Video = assertObjectType(schema.getType('Video')); + * + * doTypesOverlap(schema, Media, StillImage); // => true + * doTypesOverlap(schema, StillImage, Video); // => false + * ``` + */ +export declare function doTypesOverlap( + schema: GraphQLSchema, + typeA: GraphQLCompositeType, + typeB: GraphQLCompositeType, +): boolean; diff --git a/node_modules/graphql/utilities/typeComparators.js b/node_modules/graphql/utilities/typeComparators.js new file mode 100644 index 0000000000000000000000000000000000000000..abbba9b4dd100d0aa98c5f25373b5928cb6f37cf --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.js @@ -0,0 +1,201 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.doTypesOverlap = doTypesOverlap; +exports.isEqualType = isEqualType; +exports.isTypeSubTypeOf = isTypeSubTypeOf; + +var _definition = require('../type/definition.js'); + +/** @category Type Comparisons */ + +/** + * Provided two types, return true if the types are equal (invariant). + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when both types are equal. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { isEqualType } from 'graphql/utilities'; + * + * isEqualType(GraphQLString, GraphQLString); // => true + * isEqualType(new GraphQLList(GraphQLString), new GraphQLList(GraphQLString)); // => true + * isEqualType(new GraphQLNonNull(GraphQLString), GraphQLString); // => false + * ``` + */ +function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + if ( + (0, _definition.isNonNullType)(typeA) && + (0, _definition.isNonNullType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + if ( + (0, _definition.isListType)(typeA) && + (0, _definition.isListType)(typeB) + ) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + * @param schema - GraphQL schema to use. + * @param maybeSubType - The possible subtype to compare. + * @param superType - The possible supertype to compare. + * @returns True when `maybeSubType` is equal to or a subtype of `superType`. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { + * GraphQLNonNull, + * assertInterfaceType, + * assertObjectType, + * } from 'graphql/type'; + * import { isTypeSubTypeOf } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * + * isTypeSubTypeOf(schema, User, Node); // => true + * isTypeSubTypeOf(schema, new GraphQLNonNull(User), Node); // => true + * isTypeSubTypeOf(schema, Node, User); // => false + * ``` + */ + +function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + if ((0, _definition.isNonNullType)(superType)) { + if ((0, _definition.isNonNullType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isNonNullType)(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if ((0, _definition.isListType)(superType)) { + if ((0, _definition.isListType)(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if ((0, _definition.isListType)(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return ( + (0, _definition.isAbstractType)(superType) && + ((0, _definition.isInterfaceType)(maybeSubType) || + (0, _definition.isObjectType)(maybeSubType)) && + schema.isSubType(superType, maybeSubType) + ); +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + * @param schema - GraphQL schema to use. + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when the two composite types can apply to at least one common object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType, assertUnionType } from 'graphql/type'; + * import { doTypesOverlap } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * union StillImage = Photo + * + * type Query { + * media: [Media] + * } + * `); + * const Media = assertUnionType(schema.getType('Media')); + * const StillImage = assertUnionType(schema.getType('StillImage')); + * const Video = assertObjectType(schema.getType('Video')); + * + * doTypesOverlap(schema, Media, StillImage); // => true + * doTypesOverlap(schema, StillImage, Video); // => false + * ``` + */ + +function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if ((0, _definition.isAbstractType)(typeA)) { + if ((0, _definition.isAbstractType)(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some((type) => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. + + return schema.isSubType(typeA, typeB); + } + + if ((0, _definition.isAbstractType)(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. + + return false; +} diff --git a/node_modules/graphql/utilities/typeComparators.mjs b/node_modules/graphql/utilities/typeComparators.mjs new file mode 100644 index 0000000000000000000000000000000000000000..859a1cc6f6588ebda5486bf24133100255580986 --- /dev/null +++ b/node_modules/graphql/utilities/typeComparators.mjs @@ -0,0 +1,190 @@ +/** @category Type Comparisons */ +import { + isAbstractType, + isInterfaceType, + isListType, + isNonNullType, + isObjectType, +} from '../type/definition.mjs'; + +/** + * Provided two types, return true if the types are equal (invariant). + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when both types are equal. + * @example + * ```ts + * import { + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { isEqualType } from 'graphql/utilities'; + * + * isEqualType(GraphQLString, GraphQLString); // => true + * isEqualType(new GraphQLList(GraphQLString), new GraphQLList(GraphQLString)); // => true + * isEqualType(new GraphQLNonNull(GraphQLString), GraphQLString); // => false + * ``` + */ +export function isEqualType(typeA, typeB) { + // Equivalent types are equal. + if (typeA === typeB) { + return true; + } // If either type is non-null, the other must also be non-null. + + if (isNonNullType(typeA) && isNonNullType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // If either type is a list, the other must also be a list. + + if (isListType(typeA) && isListType(typeB)) { + return isEqualType(typeA.ofType, typeB.ofType); + } // Otherwise the types are not equal. + + return false; +} +/** + * Provided a type and a super type, return true if the first type is either + * equal or a subset of the second super type (covariant). + * @param schema - GraphQL schema to use. + * @param maybeSubType - The possible subtype to compare. + * @param superType - The possible supertype to compare. + * @returns True when `maybeSubType` is equal to or a subtype of `superType`. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { + * GraphQLNonNull, + * assertInterfaceType, + * assertObjectType, + * } from 'graphql/type'; + * import { isTypeSubTypeOf } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * interface Node { + * id: ID! + * } + * + * type User implements Node { + * id: ID! + * } + * + * type Query { + * node: Node + * } + * `); + * const Node = assertInterfaceType(schema.getType('Node')); + * const User = assertObjectType(schema.getType('User')); + * + * isTypeSubTypeOf(schema, User, Node); // => true + * isTypeSubTypeOf(schema, new GraphQLNonNull(User), Node); // => true + * isTypeSubTypeOf(schema, Node, User); // => false + * ``` + */ + +export function isTypeSubTypeOf(schema, maybeSubType, superType) { + // Equivalent type is a valid subtype + if (maybeSubType === superType) { + return true; + } // If superType is non-null, maybeSubType must also be non-null. + + if (isNonNullType(superType)) { + if (isNonNullType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isNonNullType(maybeSubType)) { + // If superType is nullable, maybeSubType may be non-null or nullable. + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType); + } // If superType type is a list, maybeSubType type must also be a list. + + if (isListType(superType)) { + if (isListType(maybeSubType)) { + return isTypeSubTypeOf(schema, maybeSubType.ofType, superType.ofType); + } + + return false; + } + + if (isListType(maybeSubType)) { + // If superType is not a list, maybeSubType must also be not a list. + return false; + } // If superType type is an abstract type, check if it is super type of maybeSubType. + // Otherwise, the child type is not a valid subtype of the parent type. + + return ( + isAbstractType(superType) && + (isInterfaceType(maybeSubType) || isObjectType(maybeSubType)) && + schema.isSubType(superType, maybeSubType) + ); +} +/** + * Provided two composite types, determine if they "overlap". Two composite + * types overlap when the Sets of possible concrete types for each intersect. + * + * This is often used to determine if a fragment of a given type could possibly + * be visited in a context of another type. + * + * This function is commutative. + * @param schema - GraphQL schema to use. + * @param typeA - The first GraphQL type to compare. + * @param typeB - The second GraphQL type to compare. + * @returns True when the two composite types can apply to at least one common object type. + * @example + * ```ts + * import { buildSchema } from 'graphql/utilities'; + * import { assertObjectType, assertUnionType } from 'graphql/type'; + * import { doTypesOverlap } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Photo { + * url: String! + * } + * + * type Video { + * url: String! + * } + * + * union Media = Photo | Video + * union StillImage = Photo + * + * type Query { + * media: [Media] + * } + * `); + * const Media = assertUnionType(schema.getType('Media')); + * const StillImage = assertUnionType(schema.getType('StillImage')); + * const Video = assertObjectType(schema.getType('Video')); + * + * doTypesOverlap(schema, Media, StillImage); // => true + * doTypesOverlap(schema, StillImage, Video); // => false + * ``` + */ + +export function doTypesOverlap(schema, typeA, typeB) { + // Equivalent types overlap + if (typeA === typeB) { + return true; + } + + if (isAbstractType(typeA)) { + if (isAbstractType(typeB)) { + // If both types are abstract, then determine if there is any intersection + // between possible concrete types of each. + return schema + .getPossibleTypes(typeA) + .some((type) => schema.isSubType(typeB, type)); + } // Determine if the latter type is a possible concrete type of the former. + + return schema.isSubType(typeA, typeB); + } + + if (isAbstractType(typeB)) { + // Determine if the former type is a possible concrete type of the latter. + return schema.isSubType(typeB, typeA); + } // Otherwise the types do not overlap. + + return false; +} diff --git a/node_modules/graphql/utilities/typeFromAST.d.ts b/node_modules/graphql/utilities/typeFromAST.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a3b0ee781befe3be0c9227bf1e25cd04324c6b0c --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.d.ts @@ -0,0 +1,118 @@ +/** @category Values */ +import type { + ListTypeNode, + NamedTypeNode, + NonNullTypeNode, + TypeNode, +} from '../language/ast'; +import type { GraphQLNamedType, GraphQLType } from '../type/definition'; +import { GraphQLList, GraphQLNonNull } from '../type/definition'; +import type { GraphQLSchema } from '../type/schema'; +/** + * Given a Schema and an AST node describing a type, return a GraphQLType + * definition which applies to that type. For example, if provided the parsed + * AST node for `[User]`, a GraphQLList instance will be returned, containing + * the type called "User" found in the schema. If a type called "User" is not + * found in the schema, then undefined will be returned. + * @param schema - GraphQL schema to use. + * @param typeNode - The GraphQL type AST node to resolve. + * @returns The GraphQL type referenced by the AST node, or undefined if it cannot be resolved. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * import { buildSchema, typeFromAST } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * typeFromAST(schema, parseType('String'))?.toString(); // => 'String' + * typeFromAST(schema, parseType('Missing')); // => undefined + * ``` + */ +export declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NamedTypeNode, +): GraphQLNamedType | undefined; +/** + * Resolves a list type AST node against a schema. + * @param schema - GraphQL schema to use. + * @param typeNode - The list type AST node to resolve. + * @returns The GraphQL list type referenced by the AST node, or undefined if + * it cannot be resolved. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * import { buildSchema, typeFromAST } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * tags: [String] + * } + * `); + * + * typeFromAST(schema, parseType('[String]'))?.toString(); // => '[String]' + * typeFromAST(schema, parseType('[Missing]')); // => undefined + * ``` + */ +export declare function typeFromAST( + schema: GraphQLSchema, + typeNode: ListTypeNode, +): GraphQLList | undefined; +/** + * Resolves a non-null type AST node against a schema. + * @param schema - GraphQL schema to use. + * @param typeNode - The non-null type AST node to resolve. + * @returns The GraphQL non-null type referenced by the AST node, or undefined + * if it cannot be resolved. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * import { buildSchema, typeFromAST } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type Query { + * name: String! + * } + * `); + * + * typeFromAST(schema, parseType('String!'))?.toString(); // => 'String!' + * typeFromAST(schema, parseType('[String!]!'))?.toString(); // => '[String!]!' + * ``` + */ +export declare function typeFromAST( + schema: GraphQLSchema, + typeNode: NonNullTypeNode, +): GraphQLNonNull | undefined; +/** + * Resolves a type AST node against a schema. + * @param schema - GraphQL schema to use. + * @param typeNode - The GraphQL type AST node to resolve. + * @returns The GraphQL type referenced by the AST node, or undefined if it + * cannot be resolved. + * @example + * ```ts + * import { parseType } from 'graphql/language'; + * import { buildSchema, typeFromAST } from 'graphql/utilities'; + * + * const schema = buildSchema(` + * type User { + * name: String + * } + * + * type Query { + * users: [User!]! + * } + * `); + * + * typeFromAST(schema, parseType('User'))?.toString(); // => 'User' + * typeFromAST(schema, parseType('[User!]!'))?.toString(); // => '[User!]!' + * typeFromAST(schema, parseType('Missing')); // => undefined + * ``` + */ +export declare function typeFromAST( + schema: GraphQLSchema, + typeNode: TypeNode, +): GraphQLType | undefined; diff --git a/node_modules/graphql/utilities/typeFromAST.js b/node_modules/graphql/utilities/typeFromAST.js new file mode 100644 index 0000000000000000000000000000000000000000..c6389de3402bb5879a7ec64aac03bf9e6cea33ce --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.js @@ -0,0 +1,30 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.typeFromAST = typeFromAST; + +var _kinds = require('../language/kinds.js'); + +var _definition = require('../type/definition.js'); + +/** @category Values */ + +/** @internal */ +function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case _kinds.Kind.LIST_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLList(innerType); + } + + case _kinds.Kind.NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new _definition.GraphQLNonNull(innerType); + } + + case _kinds.Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } +} diff --git a/node_modules/graphql/utilities/typeFromAST.mjs b/node_modules/graphql/utilities/typeFromAST.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c108c20403a8aaad8451c63d96e8c48b13af23cc --- /dev/null +++ b/node_modules/graphql/utilities/typeFromAST.mjs @@ -0,0 +1,21 @@ +/** @category Values */ +import { Kind } from '../language/kinds.mjs'; +import { GraphQLList, GraphQLNonNull } from '../type/definition.mjs'; + +/** @internal */ +export function typeFromAST(schema, typeNode) { + switch (typeNode.kind) { + case Kind.LIST_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLList(innerType); + } + + case Kind.NON_NULL_TYPE: { + const innerType = typeFromAST(schema, typeNode.type); + return innerType && new GraphQLNonNull(innerType); + } + + case Kind.NAMED_TYPE: + return schema.getType(typeNode.name.value); + } +} diff --git a/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts b/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ca6a7d58c5cf1556608421e0a3990a71b5169131 --- /dev/null +++ b/node_modules/graphql/utilities/typedQueryDocumentNode.d.ts @@ -0,0 +1,26 @@ +/** @category Typed Documents */ +import type { DocumentNode, ExecutableDefinitionNode } from '../language/ast'; +/** + * Wrapper type that contains DocumentNode and types that can be deduced from it. + * @typeParam TResponseData - Typed GraphQL response data shape. + * @typeParam TRequestVariables - Typed GraphQL request variables shape. + */ +export interface TypedQueryDocumentNode< + TResponseData = { + [key: string]: any; + }, + TRequestVariables = { + [key: string]: any; + }, +> extends DocumentNode { + /** Top-level executable and type-system definitions in this document. */ + readonly definitions: ReadonlyArray; + /** + * This type is used to ensure that the variables you pass in to the query are assignable to Variables + * and that the Result is assignable to whatever you pass your result to. The method is never actually + * implemented, but the type is valid because we list it as optional + */ + __ensureTypesOfVariablesAndResultMatching?: ( + variables: TRequestVariables, + ) => TResponseData; +} diff --git a/node_modules/graphql/utilities/typedQueryDocumentNode.js b/node_modules/graphql/utilities/typedQueryDocumentNode.js new file mode 100644 index 0000000000000000000000000000000000000000..b92811b00ce45269375f44bfb34fff79dfc55808 --- /dev/null +++ b/node_modules/graphql/utilities/typedQueryDocumentNode.js @@ -0,0 +1,5 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); diff --git a/node_modules/graphql/utilities/typedQueryDocumentNode.mjs b/node_modules/graphql/utilities/typedQueryDocumentNode.mjs new file mode 100644 index 0000000000000000000000000000000000000000..cb0ff5c3b541f646105198ee23ac0fc3d805023e --- /dev/null +++ b/node_modules/graphql/utilities/typedQueryDocumentNode.mjs @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/graphql/utilities/valueFromAST.d.ts b/node_modules/graphql/utilities/valueFromAST.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8df805bb575338e1e4a87bc3d416dde6c2b259ad --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.d.ts @@ -0,0 +1,67 @@ +/** @category Values */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { ValueNode } from '../language/ast'; +import type { GraphQLInputType } from '../type/definition'; +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * @param valueNode - GraphQL value AST node to convert. + * @param type - The GraphQL type to inspect. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type. + * @example + * ```ts + * // Coerce literal values without variables. + * import { parseValue } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * valueFromAST(parseValue('{ stars: 5, tags: ["featured"] }'), ReviewInput); // => { stars: 5, tags: ['featured'] } + * valueFromAST(parseValue('{ stars: "bad" }'), ReviewInput); // => undefined + * ``` + * @example + * ```ts + * // This variant resolves variable references from runtime values. + * import { parseValue } from 'graphql/language'; + * import { GraphQLInt } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5 + * valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined + * ``` + */ +export declare function valueFromAST( + valueNode: Maybe, + type: GraphQLInputType, + variables?: Maybe>, +): unknown; diff --git a/node_modules/graphql/utilities/valueFromAST.js b/node_modules/graphql/utilities/valueFromAST.js new file mode 100644 index 0000000000000000000000000000000000000000..0b65b6681084e1dfc328108b61f5a22885221c59 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.js @@ -0,0 +1,246 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.valueFromAST = valueFromAST; + +var _inspect = require('../jsutils/inspect.js'); + +var _invariant = require('../jsutils/invariant.js'); + +var _keyMap = require('../jsutils/keyMap.js'); + +var _kinds = require('../language/kinds.js'); + +var _definition = require('../type/definition.js'); + +/** @category Values */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * @param valueNode - GraphQL value AST node to convert. + * @param type - The GraphQL type to inspect. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type. + * @example + * ```ts + * // Coerce literal values without variables. + * import { parseValue } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * valueFromAST(parseValue('{ stars: 5, tags: ["featured"] }'), ReviewInput); // => { stars: 5, tags: ['featured'] } + * valueFromAST(parseValue('{ stars: "bad" }'), ReviewInput); // => undefined + * ``` + * @example + * ```ts + * // This variant resolves variable references from runtime values. + * import { parseValue } from 'graphql/language'; + * import { GraphQLInt } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5 + * valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined + * ``` + */ +function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (valueNode.kind === _kinds.Kind.VARIABLE) { + const variableName = valueNode.name.value; + + if ( + variables == null || + variables[variableName] === undefined || + !hasOwnProperty(variables, variableName) + ) { + // No valid return value. + return; + } + + const variableValue = variables[variableName]; + + if (variableValue === null && (0, _definition.isNonNullType)(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + return variableValue; + } + + if ((0, _definition.isNonNullType)(type)) { + if (valueNode.kind === _kinds.Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === _kinds.Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if ((0, _definition.isListType)(type)) { + const itemType = type.ofType; + + if (valueNode.kind === _kinds.Kind.LIST) { + const coercedValues = []; + + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if ((0, _definition.isNonNullType)(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + const coercedValue = valueFromAST(valueNode, itemType, variables); + + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if ((0, _definition.isInputObjectType)(type)) { + if (valueNode.kind !== _kinds.Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + const coercedObj = Object.create(null); + const fieldNodes = (0, _keyMap.keyMap)( + valueNode.fields, + (field) => field.name.value, + ); + + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if ((0, _definition.isNonNullType)(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + if (type.isOneOf) { + const keys = Object.keys(coercedObj); + + if (keys.length !== 1) { + return; // Invalid: not exactly one key, intentionally return no value. + } + + if (coercedObj[keys[0]] === null) { + return; // Invalid: value not non-null, intentionally return no value. + } + } + + return coercedObj; + } + + if ((0, _definition.isLeafType)(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if (result === undefined) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. + + false || + (0, _invariant.invariant)( + false, + 'Unexpected input type: ' + (0, _inspect.inspect)(type), + ); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === _kinds.Kind.VARIABLE && + (variables == null || + variables[valueNode.name.value] === undefined || + !hasOwnProperty(variables, valueNode.name.value)) + ); +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/utilities/valueFromAST.mjs b/node_modules/graphql/utilities/valueFromAST.mjs new file mode 100644 index 0000000000000000000000000000000000000000..66f7da061b5514ca785a99c698026ac227554f67 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromAST.mjs @@ -0,0 +1,232 @@ +/** @category Values */ +import { inspect } from '../jsutils/inspect.mjs'; +import { invariant } from '../jsutils/invariant.mjs'; +import { keyMap } from '../jsutils/keyMap.mjs'; +import { Kind } from '../language/kinds.mjs'; +import { + isInputObjectType, + isLeafType, + isListType, + isNonNullType, +} from '../type/definition.mjs'; +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * A GraphQL type must be provided, which will be used to interpret different + * GraphQL Value literals. + * + * Returns `undefined` when the value could not be validly coerced according to + * the provided type. + * + * | GraphQL Value | JSON Value | + * | -------------------- | ------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String | String | + * | Int / Float | Number | + * | Enum Value | Unknown | + * | NullValue | null | + * @param valueNode - GraphQL value AST node to convert. + * @param type - The GraphQL type to inspect. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns The coerced JavaScript value, or undefined if the AST value cannot be coerced to the type. + * @example + * ```ts + * // Coerce literal values without variables. + * import { parseValue } from 'graphql/language'; + * import { + * GraphQLInputObjectType, + * GraphQLInt, + * GraphQLList, + * GraphQLNonNull, + * GraphQLString, + * } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * const ReviewInput = new GraphQLInputObjectType({ + * name: 'ReviewInput', + * fields: { + * stars: { type: new GraphQLNonNull(GraphQLInt) }, + * tags: { type: new GraphQLList(GraphQLString) }, + * }, + * }); + * + * valueFromAST(parseValue('{ stars: 5, tags: ["featured"] }'), ReviewInput); // => { stars: 5, tags: ['featured'] } + * valueFromAST(parseValue('{ stars: "bad" }'), ReviewInput); // => undefined + * ``` + * @example + * ```ts + * // This variant resolves variable references from runtime values. + * import { parseValue } from 'graphql/language'; + * import { GraphQLInt } from 'graphql/type'; + * import { valueFromAST } from 'graphql/utilities'; + * + * valueFromAST(parseValue('$stars'), GraphQLInt, { stars: 5 }); // => 5 + * valueFromAST(parseValue('$stars'), GraphQLInt, {}); // => undefined + * ``` + */ + +export function valueFromAST(valueNode, type, variables) { + if (!valueNode) { + // When there is no node, then there is also no value. + // Importantly, this is different from returning the value null. + return; + } + + if (valueNode.kind === Kind.VARIABLE) { + const variableName = valueNode.name.value; + + if ( + variables == null || + variables[variableName] === undefined || + !hasOwnProperty(variables, variableName) + ) { + // No valid return value. + return; + } + + const variableValue = variables[variableName]; + + if (variableValue === null && isNonNullType(type)) { + return; // Invalid: intentionally return no value. + } // Note: This does no further checking that this variable is correct. + // This assumes that this query has been validated and the variable + // usage here is of the correct type. + + return variableValue; + } + + if (isNonNullType(type)) { + if (valueNode.kind === Kind.NULL) { + return; // Invalid: intentionally return no value. + } + + return valueFromAST(valueNode, type.ofType, variables); + } + + if (valueNode.kind === Kind.NULL) { + // This is explicitly returning the value null. + return null; + } + + if (isListType(type)) { + const itemType = type.ofType; + + if (valueNode.kind === Kind.LIST) { + const coercedValues = []; + + for (const itemNode of valueNode.values) { + if (isMissingVariable(itemNode, variables)) { + // If an array contains a missing variable, it is either coerced to + // null or if the item type is non-null, it considered invalid. + if (isNonNullType(itemType)) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(null); + } else { + const itemValue = valueFromAST(itemNode, itemType, variables); + + if (itemValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedValues.push(itemValue); + } + } + + return coercedValues; + } + + const coercedValue = valueFromAST(valueNode, itemType, variables); + + if (coercedValue === undefined) { + return; // Invalid: intentionally return no value. + } + + return [coercedValue]; + } + + if (isInputObjectType(type)) { + if (valueNode.kind !== Kind.OBJECT) { + return; // Invalid: intentionally return no value. + } + + const coercedObj = Object.create(null); + const fieldNodes = keyMap(valueNode.fields, (field) => field.name.value); + + for (const field of Object.values(type.getFields())) { + const fieldNode = fieldNodes[field.name]; + + if (!fieldNode || isMissingVariable(fieldNode.value, variables)) { + if (field.defaultValue !== undefined) { + coercedObj[field.name] = field.defaultValue; + } else if (isNonNullType(field.type)) { + return; // Invalid: intentionally return no value. + } + + continue; + } + + const fieldValue = valueFromAST(fieldNode.value, field.type, variables); + + if (fieldValue === undefined) { + return; // Invalid: intentionally return no value. + } + + coercedObj[field.name] = fieldValue; + } + + if (type.isOneOf) { + const keys = Object.keys(coercedObj); + + if (keys.length !== 1) { + return; // Invalid: not exactly one key, intentionally return no value. + } + + if (coercedObj[keys[0]] === null) { + return; // Invalid: value not non-null, intentionally return no value. + } + } + + return coercedObj; + } + + if (isLeafType(type)) { + // Scalars and Enums fulfill parsing a literal value via parseLiteral(). + // Invalid values represent a failure to parse correctly, in which case + // no value is returned. + let result; + + try { + result = type.parseLiteral(valueNode, variables); + } catch (_error) { + return; // Invalid: intentionally return no value. + } + + if (result === undefined) { + return; // Invalid: intentionally return no value. + } + + return result; + } + /* c8 ignore next 3 */ + // Not reachable, all possible input types have been considered. + + false || invariant(false, 'Unexpected input type: ' + inspect(type)); +} // Returns true if the provided valueNode is a variable which is not defined +// in the set of variables. + +function isMissingVariable(valueNode, variables) { + return ( + valueNode.kind === Kind.VARIABLE && + (variables == null || + variables[valueNode.name.value] === undefined || + !hasOwnProperty(variables, valueNode.name.value)) + ); +} + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.d.ts b/node_modules/graphql/utilities/valueFromASTUntyped.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52e16022488c4959d1e41ecdbc5d82d9138ecac2 --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.d.ts @@ -0,0 +1,36 @@ +/** @category Values */ +import type { Maybe } from '../jsutils/Maybe'; +import type { ObjMap } from '../jsutils/ObjMap'; +import type { ValueNode } from '../language/ast'; +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Because no GraphQL type is provided, the returned JavaScript value reflects + * the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * @param valueNode - GraphQL value AST node to convert. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns JavaScript value represented by the GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { valueFromASTUntyped } from 'graphql/utilities'; + * + * const value = valueFromASTUntyped(parseValue('[1, 2, 3]')); + * + * value; // => [1, 2, 3] + * valueFromASTUntyped(parseValue('$name'), { name: 'Ada' }); // => 'Ada' + * ``` + */ +export declare function valueFromASTUntyped( + valueNode: ValueNode, + variables?: Maybe>, +): unknown; diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.js b/node_modules/graphql/utilities/valueFromASTUntyped.js new file mode 100644 index 0000000000000000000000000000000000000000..d40987f1958625d731938d793d4702d505745f0b --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.valueFromASTUntyped = valueFromASTUntyped; + +var _keyValMap = require('../jsutils/keyValMap.js'); + +var _kinds = require('../language/kinds.js'); + +/** @category Values */ + +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Because no GraphQL type is provided, the returned JavaScript value reflects + * the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * @param valueNode - GraphQL value AST node to convert. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns JavaScript value represented by the GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { valueFromASTUntyped } from 'graphql/utilities'; + * + * const value = valueFromASTUntyped(parseValue('[1, 2, 3]')); + * + * value; // => [1, 2, 3] + * valueFromASTUntyped(parseValue('$name'), { name: 'Ada' }); // => 'Ada' + * ``` + */ +function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case _kinds.Kind.NULL: + return null; + + case _kinds.Kind.INT: + return parseInt(valueNode.value, 10); + + case _kinds.Kind.FLOAT: + return parseFloat(valueNode.value); + + case _kinds.Kind.STRING: + case _kinds.Kind.ENUM: + case _kinds.Kind.BOOLEAN: + return valueNode.value; + + case _kinds.Kind.LIST: + return valueNode.values.map((node) => + valueFromASTUntyped(node, variables), + ); + + case _kinds.Kind.OBJECT: + return (0, _keyValMap.keyValMap)( + valueNode.fields, + (field) => field.name.value, + (field) => valueFromASTUntyped(field.value, variables), + ); + + case _kinds.Kind.VARIABLE: + return variables === null || variables === void 0 + ? void 0 + : variables[valueNode.name.value]; + } +} diff --git a/node_modules/graphql/utilities/valueFromASTUntyped.mjs b/node_modules/graphql/utilities/valueFromASTUntyped.mjs new file mode 100644 index 0000000000000000000000000000000000000000..c4874856d558b6c2ef335213486763c46ccac32b --- /dev/null +++ b/node_modules/graphql/utilities/valueFromASTUntyped.mjs @@ -0,0 +1,66 @@ +/** @category Values */ +import { keyValMap } from '../jsutils/keyValMap.mjs'; +import { Kind } from '../language/kinds.mjs'; +/** + * Produces a JavaScript value given a GraphQL Value AST. + * + * Because no GraphQL type is provided, the returned JavaScript value reflects + * the provided GraphQL value AST. + * + * | GraphQL Value | JavaScript Value | + * | -------------------- | ---------------- | + * | Input Object | Object | + * | List | Array | + * | Boolean | Boolean | + * | String / Enum | String | + * | Int / Float | Number | + * | Null | null | + * @param valueNode - GraphQL value AST node to convert. + * @param variables - Optional runtime variable values keyed by variable name. + * @returns JavaScript value represented by the GraphQL value AST. + * @example + * ```ts + * import { parseValue } from 'graphql/language'; + * import { valueFromASTUntyped } from 'graphql/utilities'; + * + * const value = valueFromASTUntyped(parseValue('[1, 2, 3]')); + * + * value; // => [1, 2, 3] + * valueFromASTUntyped(parseValue('$name'), { name: 'Ada' }); // => 'Ada' + * ``` + */ + +export function valueFromASTUntyped(valueNode, variables) { + switch (valueNode.kind) { + case Kind.NULL: + return null; + + case Kind.INT: + return parseInt(valueNode.value, 10); + + case Kind.FLOAT: + return parseFloat(valueNode.value); + + case Kind.STRING: + case Kind.ENUM: + case Kind.BOOLEAN: + return valueNode.value; + + case Kind.LIST: + return valueNode.values.map((node) => + valueFromASTUntyped(node, variables), + ); + + case Kind.OBJECT: + return keyValMap( + valueNode.fields, + (field) => field.name.value, + (field) => valueFromASTUntyped(field.value, variables), + ); + + case Kind.VARIABLE: + return variables === null || variables === void 0 + ? void 0 + : variables[valueNode.name.value]; + } +} diff --git a/node_modules/graphql/validation/ValidationContext.d.ts b/node_modules/graphql/validation/ValidationContext.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..52506badafb9c534620c111da09285134ebc7fa4 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.d.ts @@ -0,0 +1,495 @@ +/** @category Validation Context */ +import type { Maybe } from '../jsutils/Maybe'; +import type { GraphQLError } from '../error/GraphQLError'; +import type { + DocumentNode, + FragmentDefinitionNode, + FragmentSpreadNode, + OperationDefinitionNode, + SelectionSetNode, + VariableNode, +} from '../language/ast'; +import type { ASTVisitor } from '../language/visitor'; +import type { + GraphQLArgument, + GraphQLCompositeType, + GraphQLEnumValue, + GraphQLField, + GraphQLInputType, + GraphQLOutputType, +} from '../type/definition'; +import type { GraphQLDirective } from '../type/directives'; +import type { GraphQLSchema } from '../type/schema'; +import { TypeInfo } from '../utilities/TypeInfo'; +declare type NodeWithSelectionSet = + | OperationDefinitionNode + | FragmentDefinitionNode; +interface VariableUsage { + readonly node: VariableNode; + readonly type: Maybe; + readonly defaultValue: Maybe; + readonly parentType: Maybe; +} +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + * + * @internal + */ +export declare class ASTValidationContext { + private _ast; + private _onError; + private _fragments; + private _fragmentSpreads; + private _recursivelyReferencedFragments; + constructor(ast: DocumentNode, onError: (error: GraphQLError) => void); + get [Symbol.toStringTag](): string; + reportError(error: GraphQLError): void; + getDocument(): DocumentNode; + getFragment(name: string): Maybe; + getFragmentSpreads(node: SelectionSetNode): ReadonlyArray; + getRecursivelyReferencedFragments( + operation: OperationDefinitionNode, + ): ReadonlyArray; +} +/** @internal */ +export declare type ASTValidationRule = ( + context: ASTValidationContext, +) => ASTVisitor; +/** @internal */ +export declare class SDLValidationContext extends ASTValidationContext { + private _schema; + constructor( + ast: DocumentNode, + schema: Maybe, + onError: (error: GraphQLError) => void, + ); + get [Symbol.toStringTag](): string; + getSchema(): Maybe; +} +/** @internal */ +export declare type SDLValidationRule = ( + context: SDLValidationContext, +) => ASTVisitor; +/** Validation context passed to query validation rules. */ +export declare class ValidationContext extends ASTValidationContext { + private _schema; + private _typeInfo; + private _variableUsages; + private _recursiveVariableUsages; + /** + * Creates a ValidationContext instance. + * @param schema - Schema used to validate the document. + * @param ast - Document AST being validated. + * @param typeInfo - TypeInfo instance used to track traversal state. + * @param onError - Callback invoked for each validation error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const errors = []; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * (error) => errors.push(error), + * ); + * + * context.reportError(new GraphQLError('Example validation error.')); + * + * context.getSchema(); // => schema + * errors[0].message; // => 'Example validation error.' + * ``` + */ + constructor( + schema: GraphQLSchema, + ast: DocumentNode, + typeInfo: TypeInfo, + onError: (error: GraphQLError) => void, + ); + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + get [Symbol.toStringTag](): string; + /** + * Returns the schema being used by this validation context. + * @returns The schema being validated against. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const context = new ValidationContext( + * schema, + * parse('{ greeting }'), + * new TypeInfo(schema), + * () => {}, + * ); + * + * context.getSchema().getQueryType()?.name; // => 'Query' + * ``` + */ + getSchema(): GraphQLSchema; + /** + * Returns variable usages found directly within this node. + * @param node - The AST node to inspect or visit. + * @returns Variable usages found directly within this node. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const document = parse('query ($name: String) { greeting(name: $name) }'); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getVariableUsages(operation); + * + * usages[0].node.name.value; // => 'name' + * String(usages[0].type); // => 'String' + * ``` + */ + getVariableUsages(node: NodeWithSelectionSet): ReadonlyArray; + /** + * Returns variable usages for an operation, including variables used by referenced fragments. + * @param operation - Operation definition to inspect. + * @returns Variable usages reachable from the operation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name(prefix: String): String + * } + * `); + * const document = parse(` + * query ($prefix: String) { + * viewer { + * ...UserName + * } + * } + * + * fragment UserName on User { + * name(prefix: $prefix) + * } + * `); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getRecursiveVariableUsages(operation); + * + * usages.map((usage) => usage.node.name.value); // => ['prefix'] + * ``` + */ + getRecursiveVariableUsages( + operation: OperationDefinitionNode, + ): ReadonlyArray; + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let typeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * typeName = String(context.getType()); + * }, + * }), + * ); + * + * typeName; // => 'String' + * ``` + */ + getType(): Maybe; + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * parentTypeName = context.getParentType()?.name; + * }, + * }), + * ); + * + * parentTypeName; // => 'Query' + * ``` + */ + getParentType(): Maybe; + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let inputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * inputTypeName = String(context.getInputType()); + * }, + * }), + * ); + * + * inputTypeName; // => 'Int' + * ``` + */ + getInputType(): Maybe; + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const document = parse('{ reviews(filter: { stars: 5 }) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentInputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * ObjectField: () => { + * parentInputTypeName = String(context.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypeName; // => 'ReviewFilter' + * ``` + */ + getParentInputType(): Maybe; + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let fieldName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = context.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + getFieldDef(): Maybe>; + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting @include(if: true) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let directiveName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = context.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + getDirective(): Maybe; + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let argumentName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = context.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + getArgument(): Maybe; + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort): [String] + * } + * `); + * const document = parse('{ reviews(sort: OLDEST) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let enumValueName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = context.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + getEnumValue(): Maybe; +} +/** A function that creates an AST visitor for validating a GraphQL document. */ +export declare type ValidationRule = (context: ValidationContext) => ASTVisitor; +export {}; diff --git a/node_modules/graphql/validation/ValidationContext.js b/node_modules/graphql/validation/ValidationContext.js new file mode 100644 index 0000000000000000000000000000000000000000..a1164be1c05065dec1e7ec6570ebea59ab0b3e61 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.js @@ -0,0 +1,633 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.ValidationContext = + exports.SDLValidationContext = + exports.ASTValidationContext = + void 0; + +var _kinds = require('../language/kinds.js'); + +var _visitor = require('../language/visitor.js'); + +var _TypeInfo = require('../utilities/TypeInfo.js'); + +/** @category Validation Context */ + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + * + * @internal + */ +class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + + get [Symbol.toStringTag]() { + return 'ASTValidationContext'; + } + + reportError(error) { + this._onError(error); + } + + getDocument() { + return this._ast; + } + + getFragment(name) { + let fragments; + + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + + this._fragments = fragments; + } + + return fragments[name]; + } + + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + + while ((set = setsToVisit.pop())) { + for (const selection of set.selections) { + if (selection.kind === _kinds.Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + } + + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + + while ((node = nodesToVisit.pop())) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + } +} +/** @internal */ + +exports.ASTValidationContext = ASTValidationContext; + +/** @internal */ +class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + + get [Symbol.toStringTag]() { + return 'SDLValidationContext'; + } + + getSchema() { + return this._schema; + } +} +/** @internal */ + +exports.SDLValidationContext = SDLValidationContext; + +/** Validation context passed to query validation rules. */ +class ValidationContext extends ASTValidationContext { + /** + * Creates a ValidationContext instance. + * @param schema - Schema used to validate the document. + * @param ast - Document AST being validated. + * @param typeInfo - TypeInfo instance used to track traversal state. + * @param onError - Callback invoked for each validation error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const errors = []; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * (error) => errors.push(error), + * ); + * + * context.reportError(new GraphQLError('Example validation error.')); + * + * context.getSchema(); // => schema + * errors[0].message; // => 'Example validation error.' + * ``` + */ + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'ValidationContext'; + } + /** + * Returns the schema being used by this validation context. + * @returns The schema being validated against. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const context = new ValidationContext( + * schema, + * parse('{ greeting }'), + * new TypeInfo(schema), + * () => {}, + * ); + * + * context.getSchema().getQueryType()?.name; // => 'Query' + * ``` + */ + + getSchema() { + return this._schema; + } + /** + * Returns variable usages found directly within this node. + * @param node - The AST node to inspect or visit. + * @returns Variable usages found directly within this node. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const document = parse('query ($name: String) { greeting(name: $name) }'); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getVariableUsages(operation); + * + * usages[0].node.name.value; // => 'name' + * String(usages[0].type); // => 'String' + * ``` + */ + + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + + if (!usages) { + const newUsages = []; + const typeInfo = new _TypeInfo.TypeInfo(this._schema); + (0, _visitor.visit)( + node, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, { + VariableDefinition: () => false, + + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + parentType: typeInfo.getParentInputType(), + }); + }, + }), + ); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + } + /** + * Returns variable usages for an operation, including variables used by referenced fragments. + * @param operation - Operation definition to inspect. + * @returns Variable usages reachable from the operation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name(prefix: String): String + * } + * `); + * const document = parse(` + * query ($prefix: String) { + * viewer { + * ...UserName + * } + * } + * + * fragment UserName on User { + * name(prefix: $prefix) + * } + * `); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getRecursiveVariableUsages(operation); + * + * usages.map((usage) => usage.node.name.value); // => ['prefix'] + * ``` + */ + + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + } + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let typeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * typeName = String(context.getType()); + * }, + * }), + * ); + * + * typeName; // => 'String' + * ``` + */ + + getType() { + return this._typeInfo.getType(); + } + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * parentTypeName = context.getParentType()?.name; + * }, + * }), + * ); + * + * parentTypeName; // => 'Query' + * ``` + */ + + getParentType() { + return this._typeInfo.getParentType(); + } + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let inputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * inputTypeName = String(context.getInputType()); + * }, + * }), + * ); + * + * inputTypeName; // => 'Int' + * ``` + */ + + getInputType() { + return this._typeInfo.getInputType(); + } + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const document = parse('{ reviews(filter: { stars: 5 }) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentInputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * ObjectField: () => { + * parentInputTypeName = String(context.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypeName; // => 'ReviewFilter' + * ``` + */ + + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let fieldName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = context.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting @include(if: true) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let directiveName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = context.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + + getDirective() { + return this._typeInfo.getDirective(); + } + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let argumentName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = context.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + + getArgument() { + return this._typeInfo.getArgument(); + } + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort): [String] + * } + * `); + * const document = parse('{ reviews(sort: OLDEST) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let enumValueName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = context.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + + getEnumValue() { + return this._typeInfo.getEnumValue(); + } +} +/** A function that creates an AST visitor for validating a GraphQL document. */ + +exports.ValidationContext = ValidationContext; diff --git a/node_modules/graphql/validation/ValidationContext.mjs b/node_modules/graphql/validation/ValidationContext.mjs new file mode 100644 index 0000000000000000000000000000000000000000..ccb25023f6ee7a4702dc732d6fa7484279d4b615 --- /dev/null +++ b/node_modules/graphql/validation/ValidationContext.mjs @@ -0,0 +1,614 @@ +/** @category Validation Context */ +import { Kind } from '../language/kinds.mjs'; +import { visit } from '../language/visitor.mjs'; +import { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo.mjs'; + +/** + * An instance of this class is passed as the "this" context to all validators, + * allowing access to commonly useful contextual information from within a + * validation rule. + * + * @internal + */ +export class ASTValidationContext { + constructor(ast, onError) { + this._ast = ast; + this._fragments = undefined; + this._fragmentSpreads = new Map(); + this._recursivelyReferencedFragments = new Map(); + this._onError = onError; + } + + get [Symbol.toStringTag]() { + return 'ASTValidationContext'; + } + + reportError(error) { + this._onError(error); + } + + getDocument() { + return this._ast; + } + + getFragment(name) { + let fragments; + + if (this._fragments) { + fragments = this._fragments; + } else { + fragments = Object.create(null); + + for (const defNode of this.getDocument().definitions) { + if (defNode.kind === Kind.FRAGMENT_DEFINITION) { + fragments[defNode.name.value] = defNode; + } + } + + this._fragments = fragments; + } + + return fragments[name]; + } + + getFragmentSpreads(node) { + let spreads = this._fragmentSpreads.get(node); + + if (!spreads) { + spreads = []; + const setsToVisit = [node]; + let set; + + while ((set = setsToVisit.pop())) { + for (const selection of set.selections) { + if (selection.kind === Kind.FRAGMENT_SPREAD) { + spreads.push(selection); + } else if (selection.selectionSet) { + setsToVisit.push(selection.selectionSet); + } + } + } + + this._fragmentSpreads.set(node, spreads); + } + + return spreads; + } + + getRecursivelyReferencedFragments(operation) { + let fragments = this._recursivelyReferencedFragments.get(operation); + + if (!fragments) { + fragments = []; + const collectedNames = Object.create(null); + const nodesToVisit = [operation.selectionSet]; + let node; + + while ((node = nodesToVisit.pop())) { + for (const spread of this.getFragmentSpreads(node)) { + const fragName = spread.name.value; + + if (collectedNames[fragName] !== true) { + collectedNames[fragName] = true; + const fragment = this.getFragment(fragName); + + if (fragment) { + fragments.push(fragment); + nodesToVisit.push(fragment.selectionSet); + } + } + } + } + + this._recursivelyReferencedFragments.set(operation, fragments); + } + + return fragments; + } +} +/** @internal */ + +/** @internal */ +export class SDLValidationContext extends ASTValidationContext { + constructor(ast, schema, onError) { + super(ast, onError); + this._schema = schema; + } + + get [Symbol.toStringTag]() { + return 'SDLValidationContext'; + } + + getSchema() { + return this._schema; + } +} +/** @internal */ + +/** Validation context passed to query validation rules. */ +export class ValidationContext extends ASTValidationContext { + /** + * Creates a ValidationContext instance. + * @param schema - Schema used to validate the document. + * @param ast - Document AST being validated. + * @param typeInfo - TypeInfo instance used to track traversal state. + * @param onError - Callback invoked for each validation error. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { GraphQLError } from 'graphql/error'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const errors = []; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * (error) => errors.push(error), + * ); + * + * context.reportError(new GraphQLError('Example validation error.')); + * + * context.getSchema(); // => schema + * errors[0].message; // => 'Example validation error.' + * ``` + */ + constructor(schema, ast, typeInfo, onError) { + super(ast, onError); + this._schema = schema; + this._typeInfo = typeInfo; + this._variableUsages = new Map(); + this._recursiveVariableUsages = new Map(); + } + /** + * Returns the value used by `Object.prototype.toString`. + * @returns The built-in string tag for this object. + */ + + get [Symbol.toStringTag]() { + return 'ValidationContext'; + } + /** + * Returns the schema being used by this validation context. + * @returns The schema being validated against. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const context = new ValidationContext( + * schema, + * parse('{ greeting }'), + * new TypeInfo(schema), + * () => {}, + * ); + * + * context.getSchema().getQueryType()?.name; // => 'Query' + * ``` + */ + + getSchema() { + return this._schema; + } + /** + * Returns variable usages found directly within this node. + * @param node - The AST node to inspect or visit. + * @returns Variable usages found directly within this node. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting(name: String): String + * } + * `); + * const document = parse('query ($name: String) { greeting(name: $name) }'); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getVariableUsages(operation); + * + * usages[0].node.name.value; // => 'name' + * String(usages[0].type); // => 'String' + * ``` + */ + + getVariableUsages(node) { + let usages = this._variableUsages.get(node); + + if (!usages) { + const newUsages = []; + const typeInfo = new TypeInfo(this._schema); + visit( + node, + visitWithTypeInfo(typeInfo, { + VariableDefinition: () => false, + + Variable(variable) { + newUsages.push({ + node: variable, + type: typeInfo.getInputType(), + defaultValue: typeInfo.getDefaultValue(), + parentType: typeInfo.getParentInputType(), + }); + }, + }), + ); + usages = newUsages; + + this._variableUsages.set(node, usages); + } + + return usages; + } + /** + * Returns variable usages for an operation, including variables used by referenced fragments. + * @param operation - Operation definition to inspect. + * @returns Variable usages reachable from the operation. + * @example + * ```ts + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * viewer: User + * } + * + * type User { + * name(prefix: String): String + * } + * `); + * const document = parse(` + * query ($prefix: String) { + * viewer { + * ...UserName + * } + * } + * + * fragment UserName on User { + * name(prefix: $prefix) + * } + * `); + * const operation = document.definitions[0]; + * const context = new ValidationContext( + * schema, + * document, + * new TypeInfo(schema), + * () => {}, + * ); + * + * const usages = context.getRecursiveVariableUsages(operation); + * + * usages.map((usage) => usage.node.name.value); // => ['prefix'] + * ``` + */ + + getRecursiveVariableUsages(operation) { + let usages = this._recursiveVariableUsages.get(operation); + + if (!usages) { + usages = this.getVariableUsages(operation); + + for (const frag of this.getRecursivelyReferencedFragments(operation)) { + usages = usages.concat(this.getVariableUsages(frag)); + } + + this._recursiveVariableUsages.set(operation, usages); + } + + return usages; + } + /** + * Returns the current output type at this point in traversal. + * @returns The current output type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let typeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * typeName = String(context.getType()); + * }, + * }), + * ); + * + * typeName; // => 'String' + * ``` + */ + + getType() { + return this._typeInfo.getType(); + } + /** + * Returns the current parent composite type. + * @returns The current parent composite type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * parentTypeName = context.getParentType()?.name; + * }, + * }), + * ); + * + * parentTypeName; // => 'Query' + * ``` + */ + + getParentType() { + return this._typeInfo.getParentType(); + } + /** + * Returns the current input type at this point in traversal. + * @returns The current input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let inputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * inputTypeName = String(context.getInputType()); + * }, + * }), + * ); + * + * inputTypeName; // => 'Int' + * ``` + */ + + getInputType() { + return this._typeInfo.getInputType(); + } + /** + * Returns the parent input type for the current input position. + * @returns The parent input type, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input ReviewFilter { + * stars: Int + * } + * + * type Query { + * reviews(filter: ReviewFilter): [String] + * } + * `); + * const document = parse('{ reviews(filter: { stars: 5 }) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let parentInputTypeName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * ObjectField: () => { + * parentInputTypeName = String(context.getParentInputType()); + * }, + * }), + * ); + * + * parentInputTypeName; // => 'ReviewFilter' + * ``` + */ + + getParentInputType() { + return this._typeInfo.getParentInputType(); + } + /** + * Returns the current field definition. + * @returns The current field definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let fieldName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Field: () => { + * fieldName = context.getFieldDef()?.name; + * }, + * }), + * ); + * + * fieldName; // => 'greeting' + * ``` + */ + + getFieldDef() { + return this._typeInfo.getFieldDef(); + } + /** + * Returns the current directive definition. + * @returns The current directive definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ greeting @include(if: true) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let directiveName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Directive: () => { + * directiveName = context.getDirective()?.name; + * }, + * }), + * ); + * + * directiveName; // => 'include' + * ``` + */ + + getDirective() { + return this._typeInfo.getDirective(); + } + /** + * Returns the current argument definition. + * @returns The current argument definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * reviews(limit: Int): [String] + * } + * `); + * const document = parse('{ reviews(limit: 5) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let argumentName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * Argument: () => { + * argumentName = context.getArgument()?.name; + * }, + * }), + * ); + * + * argumentName; // => 'limit' + * ``` + */ + + getArgument() { + return this._typeInfo.getArgument(); + } + /** + * Returns the current enum value definition. + * @returns The current enum value definition, if known. + * @example + * ```ts + * import { parse, visit } from 'graphql/language'; + * import { buildSchema, TypeInfo, visitWithTypeInfo } from 'graphql/utilities'; + * import { ValidationContext } from 'graphql/validation'; + * + * const schema = buildSchema(` + * enum Sort { + * NEWEST + * OLDEST + * } + * + * type Query { + * reviews(sort: Sort): [String] + * } + * `); + * const document = parse('{ reviews(sort: OLDEST) }'); + * const typeInfo = new TypeInfo(schema); + * const context = new ValidationContext(schema, document, typeInfo, () => {}); + * let enumValueName; + * + * visit( + * document, + * visitWithTypeInfo(typeInfo, { + * EnumValue: () => { + * enumValueName = context.getEnumValue()?.name; + * }, + * }), + * ); + * + * enumValueName; // => 'OLDEST' + * ``` + */ + + getEnumValue() { + return this._typeInfo.getEnumValue(); + } +} +/** A function that creates an AST visitor for validating a GraphQL document. */ diff --git a/node_modules/graphql/validation/index.d.ts b/node_modules/graphql/validation/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2e51d23797ba0123ecd9f36fbfe2c625a29e5f1a --- /dev/null +++ b/node_modules/graphql/validation/index.d.ts @@ -0,0 +1,47 @@ +/** + * Validate GraphQL documents and schemas with the specified validation rules. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { validate } from './validate'; +export { ValidationContext } from './ValidationContext'; +export type { ValidationRule } from './ValidationContext'; +export { specifiedRules, recommendedRules } from './specifiedRules'; +export { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule'; +export { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule'; +export { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule'; +export { KnownArgumentNamesRule } from './rules/KnownArgumentNamesRule'; +export { KnownDirectivesRule } from './rules/KnownDirectivesRule'; +export { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule'; +export { KnownTypeNamesRule } from './rules/KnownTypeNamesRule'; +export { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule'; +export { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule'; +export { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule'; +export { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule'; +export { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule'; +export { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule'; +export { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule'; +export { ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArgumentsRule'; +export { ScalarLeafsRule } from './rules/ScalarLeafsRule'; +export { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule'; +export { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule'; +export { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule'; +export { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule'; +export { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule'; +export { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule'; +export { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule'; +export { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule'; +export { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule'; +export { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule'; +export { MaxIntrospectionDepthRule } from './rules/MaxIntrospectionDepthRule'; +export { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule'; +export { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule'; +export { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule'; +export { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule'; +export { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule'; +export { UniqueArgumentDefinitionNamesRule } from './rules/UniqueArgumentDefinitionNamesRule'; +export { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule'; +export { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule'; +export { NoDeprecatedCustomRule } from './rules/custom/NoDeprecatedCustomRule'; +export { NoSchemaIntrospectionCustomRule } from './rules/custom/NoSchemaIntrospectionCustomRule'; diff --git a/node_modules/graphql/validation/index.js b/node_modules/graphql/validation/index.js new file mode 100644 index 0000000000000000000000000000000000000000..1c56b890c735b4aa784b9154ec54c77879deb834 --- /dev/null +++ b/node_modules/graphql/validation/index.js @@ -0,0 +1,331 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +Object.defineProperty(exports, 'ExecutableDefinitionsRule', { + enumerable: true, + get: function () { + return _ExecutableDefinitionsRule.ExecutableDefinitionsRule; + }, +}); +Object.defineProperty(exports, 'FieldsOnCorrectTypeRule', { + enumerable: true, + get: function () { + return _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule; + }, +}); +Object.defineProperty(exports, 'FragmentsOnCompositeTypesRule', { + enumerable: true, + get: function () { + return _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule; + }, +}); +Object.defineProperty(exports, 'KnownArgumentNamesRule', { + enumerable: true, + get: function () { + return _KnownArgumentNamesRule.KnownArgumentNamesRule; + }, +}); +Object.defineProperty(exports, 'KnownDirectivesRule', { + enumerable: true, + get: function () { + return _KnownDirectivesRule.KnownDirectivesRule; + }, +}); +Object.defineProperty(exports, 'KnownFragmentNamesRule', { + enumerable: true, + get: function () { + return _KnownFragmentNamesRule.KnownFragmentNamesRule; + }, +}); +Object.defineProperty(exports, 'KnownTypeNamesRule', { + enumerable: true, + get: function () { + return _KnownTypeNamesRule.KnownTypeNamesRule; + }, +}); +Object.defineProperty(exports, 'LoneAnonymousOperationRule', { + enumerable: true, + get: function () { + return _LoneAnonymousOperationRule.LoneAnonymousOperationRule; + }, +}); +Object.defineProperty(exports, 'LoneSchemaDefinitionRule', { + enumerable: true, + get: function () { + return _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule; + }, +}); +Object.defineProperty(exports, 'MaxIntrospectionDepthRule', { + enumerable: true, + get: function () { + return _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule; + }, +}); +Object.defineProperty(exports, 'NoDeprecatedCustomRule', { + enumerable: true, + get: function () { + return _NoDeprecatedCustomRule.NoDeprecatedCustomRule; + }, +}); +Object.defineProperty(exports, 'NoFragmentCyclesRule', { + enumerable: true, + get: function () { + return _NoFragmentCyclesRule.NoFragmentCyclesRule; + }, +}); +Object.defineProperty(exports, 'NoSchemaIntrospectionCustomRule', { + enumerable: true, + get: function () { + return _NoSchemaIntrospectionCustomRule.NoSchemaIntrospectionCustomRule; + }, +}); +Object.defineProperty(exports, 'NoUndefinedVariablesRule', { + enumerable: true, + get: function () { + return _NoUndefinedVariablesRule.NoUndefinedVariablesRule; + }, +}); +Object.defineProperty(exports, 'NoUnusedFragmentsRule', { + enumerable: true, + get: function () { + return _NoUnusedFragmentsRule.NoUnusedFragmentsRule; + }, +}); +Object.defineProperty(exports, 'NoUnusedVariablesRule', { + enumerable: true, + get: function () { + return _NoUnusedVariablesRule.NoUnusedVariablesRule; + }, +}); +Object.defineProperty(exports, 'OverlappingFieldsCanBeMergedRule', { + enumerable: true, + get: function () { + return _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule; + }, +}); +Object.defineProperty(exports, 'PossibleFragmentSpreadsRule', { + enumerable: true, + get: function () { + return _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule; + }, +}); +Object.defineProperty(exports, 'PossibleTypeExtensionsRule', { + enumerable: true, + get: function () { + return _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule; + }, +}); +Object.defineProperty(exports, 'ProvidedRequiredArgumentsRule', { + enumerable: true, + get: function () { + return _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule; + }, +}); +Object.defineProperty(exports, 'ScalarLeafsRule', { + enumerable: true, + get: function () { + return _ScalarLeafsRule.ScalarLeafsRule; + }, +}); +Object.defineProperty(exports, 'SingleFieldSubscriptionsRule', { + enumerable: true, + get: function () { + return _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule; + }, +}); +Object.defineProperty(exports, 'UniqueArgumentDefinitionNamesRule', { + enumerable: true, + get: function () { + return _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueArgumentNamesRule', { + enumerable: true, + get: function () { + return _UniqueArgumentNamesRule.UniqueArgumentNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueDirectiveNamesRule', { + enumerable: true, + get: function () { + return _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueDirectivesPerLocationRule', { + enumerable: true, + get: function () { + return _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule; + }, +}); +Object.defineProperty(exports, 'UniqueEnumValueNamesRule', { + enumerable: true, + get: function () { + return _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueFieldDefinitionNamesRule', { + enumerable: true, + get: function () { + return _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueFragmentNamesRule', { + enumerable: true, + get: function () { + return _UniqueFragmentNamesRule.UniqueFragmentNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueInputFieldNamesRule', { + enumerable: true, + get: function () { + return _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueOperationNamesRule', { + enumerable: true, + get: function () { + return _UniqueOperationNamesRule.UniqueOperationNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueOperationTypesRule', { + enumerable: true, + get: function () { + return _UniqueOperationTypesRule.UniqueOperationTypesRule; + }, +}); +Object.defineProperty(exports, 'UniqueTypeNamesRule', { + enumerable: true, + get: function () { + return _UniqueTypeNamesRule.UniqueTypeNamesRule; + }, +}); +Object.defineProperty(exports, 'UniqueVariableNamesRule', { + enumerable: true, + get: function () { + return _UniqueVariableNamesRule.UniqueVariableNamesRule; + }, +}); +Object.defineProperty(exports, 'ValidationContext', { + enumerable: true, + get: function () { + return _ValidationContext.ValidationContext; + }, +}); +Object.defineProperty(exports, 'ValuesOfCorrectTypeRule', { + enumerable: true, + get: function () { + return _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule; + }, +}); +Object.defineProperty(exports, 'VariablesAreInputTypesRule', { + enumerable: true, + get: function () { + return _VariablesAreInputTypesRule.VariablesAreInputTypesRule; + }, +}); +Object.defineProperty(exports, 'VariablesInAllowedPositionRule', { + enumerable: true, + get: function () { + return _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule; + }, +}); +Object.defineProperty(exports, 'recommendedRules', { + enumerable: true, + get: function () { + return _specifiedRules.recommendedRules; + }, +}); +Object.defineProperty(exports, 'specifiedRules', { + enumerable: true, + get: function () { + return _specifiedRules.specifiedRules; + }, +}); +Object.defineProperty(exports, 'validate', { + enumerable: true, + get: function () { + return _validate.validate; + }, +}); + +var _validate = require('./validate.js'); + +var _ValidationContext = require('./ValidationContext.js'); + +var _specifiedRules = require('./specifiedRules.js'); + +var _ExecutableDefinitionsRule = require('./rules/ExecutableDefinitionsRule.js'); + +var _FieldsOnCorrectTypeRule = require('./rules/FieldsOnCorrectTypeRule.js'); + +var _FragmentsOnCompositeTypesRule = require('./rules/FragmentsOnCompositeTypesRule.js'); + +var _KnownArgumentNamesRule = require('./rules/KnownArgumentNamesRule.js'); + +var _KnownDirectivesRule = require('./rules/KnownDirectivesRule.js'); + +var _KnownFragmentNamesRule = require('./rules/KnownFragmentNamesRule.js'); + +var _KnownTypeNamesRule = require('./rules/KnownTypeNamesRule.js'); + +var _LoneAnonymousOperationRule = require('./rules/LoneAnonymousOperationRule.js'); + +var _NoFragmentCyclesRule = require('./rules/NoFragmentCyclesRule.js'); + +var _NoUndefinedVariablesRule = require('./rules/NoUndefinedVariablesRule.js'); + +var _NoUnusedFragmentsRule = require('./rules/NoUnusedFragmentsRule.js'); + +var _NoUnusedVariablesRule = require('./rules/NoUnusedVariablesRule.js'); + +var _OverlappingFieldsCanBeMergedRule = require('./rules/OverlappingFieldsCanBeMergedRule.js'); + +var _PossibleFragmentSpreadsRule = require('./rules/PossibleFragmentSpreadsRule.js'); + +var _ProvidedRequiredArgumentsRule = require('./rules/ProvidedRequiredArgumentsRule.js'); + +var _ScalarLeafsRule = require('./rules/ScalarLeafsRule.js'); + +var _SingleFieldSubscriptionsRule = require('./rules/SingleFieldSubscriptionsRule.js'); + +var _UniqueArgumentNamesRule = require('./rules/UniqueArgumentNamesRule.js'); + +var _UniqueDirectivesPerLocationRule = require('./rules/UniqueDirectivesPerLocationRule.js'); + +var _UniqueFragmentNamesRule = require('./rules/UniqueFragmentNamesRule.js'); + +var _UniqueInputFieldNamesRule = require('./rules/UniqueInputFieldNamesRule.js'); + +var _UniqueOperationNamesRule = require('./rules/UniqueOperationNamesRule.js'); + +var _UniqueVariableNamesRule = require('./rules/UniqueVariableNamesRule.js'); + +var _ValuesOfCorrectTypeRule = require('./rules/ValuesOfCorrectTypeRule.js'); + +var _VariablesAreInputTypesRule = require('./rules/VariablesAreInputTypesRule.js'); + +var _VariablesInAllowedPositionRule = require('./rules/VariablesInAllowedPositionRule.js'); + +var _MaxIntrospectionDepthRule = require('./rules/MaxIntrospectionDepthRule.js'); + +var _LoneSchemaDefinitionRule = require('./rules/LoneSchemaDefinitionRule.js'); + +var _UniqueOperationTypesRule = require('./rules/UniqueOperationTypesRule.js'); + +var _UniqueTypeNamesRule = require('./rules/UniqueTypeNamesRule.js'); + +var _UniqueEnumValueNamesRule = require('./rules/UniqueEnumValueNamesRule.js'); + +var _UniqueFieldDefinitionNamesRule = require('./rules/UniqueFieldDefinitionNamesRule.js'); + +var _UniqueArgumentDefinitionNamesRule = require('./rules/UniqueArgumentDefinitionNamesRule.js'); + +var _UniqueDirectiveNamesRule = require('./rules/UniqueDirectiveNamesRule.js'); + +var _PossibleTypeExtensionsRule = require('./rules/PossibleTypeExtensionsRule.js'); + +var _NoDeprecatedCustomRule = require('./rules/custom/NoDeprecatedCustomRule.js'); + +var _NoSchemaIntrospectionCustomRule = require('./rules/custom/NoSchemaIntrospectionCustomRule.js'); diff --git a/node_modules/graphql/validation/index.mjs b/node_modules/graphql/validation/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e067407e759fc674f6306130a308ca2636256b2 --- /dev/null +++ b/node_modules/graphql/validation/index.mjs @@ -0,0 +1,75 @@ +/** + * Validate GraphQL documents and schemas with the specified validation rules. + * + * These exports are also available from the root `graphql` package. + * @packageDocumentation + */ +export { validate } from './validate.mjs'; +export { ValidationContext } from './ValidationContext.mjs'; +// All validation rules in the GraphQL Specification. +export { specifiedRules, recommendedRules } from './specifiedRules.mjs'; // Spec Section: "Executable Definitions" + +export { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule.mjs'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +export { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule.mjs'; // Spec Section: "Fragments on Composite Types" + +export { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule.mjs'; // Spec Section: "Argument Names" + +export { KnownArgumentNamesRule } from './rules/KnownArgumentNamesRule.mjs'; // Spec Section: "Directives Are Defined" + +export { KnownDirectivesRule } from './rules/KnownDirectivesRule.mjs'; // Spec Section: "Fragment spread target defined" + +export { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule.mjs'; // Spec Section: "Fragment Spread Type Existence" + +export { KnownTypeNamesRule } from './rules/KnownTypeNamesRule.mjs'; // Spec Section: "Lone Anonymous Operation" + +export { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule.mjs'; // Spec Section: "Fragments must not form cycles" + +export { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule.mjs'; // Spec Section: "All Variable Used Defined" + +export { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule.mjs'; // Spec Section: "Fragments must be used" + +export { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule.mjs'; // Spec Section: "All Variables Used" + +export { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule.mjs'; // Spec Section: "Field Selection Merging" + +export { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule.mjs'; // Spec Section: "Fragment spread is possible" + +export { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule.mjs'; // Spec Section: "Argument Optionality" + +export { ProvidedRequiredArgumentsRule } from './rules/ProvidedRequiredArgumentsRule.mjs'; // Spec Section: "Leaf Field Selections" + +export { ScalarLeafsRule } from './rules/ScalarLeafsRule.mjs'; // Spec Section: "Subscriptions with Single Root Field" + +export { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule.mjs'; // Spec Section: "Argument Uniqueness" + +export { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule.mjs'; // Spec Section: "Directives Are Unique Per Location" + +export { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule.mjs'; // Spec Section: "Fragment Name Uniqueness" + +export { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule.mjs'; // Spec Section: "Input Object Field Uniqueness" + +export { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule.mjs'; // Spec Section: "Operation Name Uniqueness" + +export { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule.mjs'; // Spec Section: "Variable Uniqueness" + +export { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule.mjs'; // Spec Section: "Values Type Correctness" + +export { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule.mjs'; // Spec Section: "Variables are Input Types" + +export { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule.mjs'; // Spec Section: "All Variable Usages Are Allowed" + +export { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule.mjs'; +export { MaxIntrospectionDepthRule } from './rules/MaxIntrospectionDepthRule.mjs'; // SDL-specific validation rules + +export { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule.mjs'; +export { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule.mjs'; +export { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule.mjs'; +export { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule.mjs'; +export { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule.mjs'; +export { UniqueArgumentDefinitionNamesRule } from './rules/UniqueArgumentDefinitionNamesRule.mjs'; +export { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule.mjs'; +export { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule.mjs'; // Optional rules not defined by the GraphQL Specification + +export { NoDeprecatedCustomRule } from './rules/custom/NoDeprecatedCustomRule.mjs'; +export { NoSchemaIntrospectionCustomRule } from './rules/custom/NoSchemaIntrospectionCustomRule.mjs'; diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..95dd4672babe55675117750d9a5ddb2604ff3075 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ExecutableDefinitionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * type Extra { field: String } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ExecutableDefinitionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ExecutableDefinitionsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function ExecutableDefinitionsRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..fe5760e202261bd46c1b9232bc7b6c42920a8f5d --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.ExecutableDefinitionsRule = ExecutableDefinitionsRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _predicates = require('../../language/predicates.js'); + +/** @category Validation Rules */ + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ExecutableDefinitionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * type Extra { field: String } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ExecutableDefinitionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ExecutableDefinitionsRule]); + * + * validErrors; // => [] + * ``` + */ +function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!(0, _predicates.isExecutableDefinitionNode)(definition)) { + const defName = + definition.kind === _kinds.Kind.SCHEMA_DEFINITION || + definition.kind === _kinds.Kind.SCHEMA_EXTENSION + ? 'schema' + : '"' + definition.name.value + '"'; + context.reportError( + new _GraphQLError.GraphQLError( + `The ${defName} definition is not executable.`, + { + nodes: definition, + }, + ), + ); + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..b97745fbcbcca8625ed8bde9d3580a44c4a0cbb6 --- /dev/null +++ b/node_modules/graphql/validation/rules/ExecutableDefinitionsRule.mjs @@ -0,0 +1,62 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { isExecutableDefinitionNode } from '../../language/predicates.mjs'; + +/** + * Executable definitions + * + * A GraphQL document is only valid for execution if all definitions are either + * operation or fragment definitions. + * + * See https://spec.graphql.org/draft/#sec-Executable-Definitions + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ExecutableDefinitionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * type Extra { field: String } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ExecutableDefinitionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ExecutableDefinitionsRule]); + * + * validErrors; // => [] + * ``` + */ +export function ExecutableDefinitionsRule(context) { + return { + Document(node) { + for (const definition of node.definitions) { + if (!isExecutableDefinitionNode(definition)) { + const defName = + definition.kind === Kind.SCHEMA_DEFINITION || + definition.kind === Kind.SCHEMA_EXTENSION + ? 'schema' + : '"' + definition.name.value + '"'; + context.reportError( + new GraphQLError(`The ${defName} definition is not executable.`, { + nodes: definition, + }), + ); + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e844450b7054aefd6b9a87dd80d6fd0eb3984f02 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FieldsOnCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FieldsOnCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [FieldsOnCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function FieldsOnCorrectTypeRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js new file mode 100644 index 0000000000000000000000000000000000000000..a5fe7a2781ab62feae0732def470e25f62157129 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.js @@ -0,0 +1,178 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.FieldsOnCorrectTypeRule = FieldsOnCorrectTypeRule; + +var _didYouMean = require('../../jsutils/didYouMean.js'); + +var _naturalCompare = require('../../jsutils/naturalCompare.js'); + +var _suggestionList = require('../../jsutils/suggestionList.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FieldsOnCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FieldsOnCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [FieldsOnCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + + if (type) { + const fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + let suggestion = (0, _didYouMean.didYouMean)( + 'to use an inline fragment on', + getSuggestedTypeNames(schema, type, fieldName), + ); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = (0, _didYouMean.didYouMean)( + getSuggestedFieldNames(type, fieldName), + ); + } // Report an error, including helpful suggestions. + + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot query field "${fieldName}" on type "${type.name}".` + + suggestion, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + * + * @internal + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (!(0, _definition.isAbstractType)(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + + const suggestedTypes = new Set(); + const usageCount = Object.create(null); + + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = + ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== + null && _usageCount$possibleI !== void 0 + ? _usageCount$possibleI + : 0) + 1; + } + } + + return [...suggestedTypes] + .sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + if ( + (0, _definition.isInterfaceType)(typeA) && + schema.isSubType(typeA, typeB) + ) { + return -1; + } + + if ( + (0, _definition.isInterfaceType)(typeB) && + schema.isSubType(typeB, typeA) + ) { + return 1; + } + + return (0, _naturalCompare.naturalCompare)(typeA.name, typeB.name); + }) + .map((x) => x.name); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + * + * @internal + */ + +function getSuggestedFieldNames(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) + ) { + const possibleFieldNames = Object.keys(type.getFields()); + return (0, _suggestionList.suggestionList)(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + return []; +} diff --git a/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..26bce8aa5015d70642a44db78873458dac149c99 --- /dev/null +++ b/node_modules/graphql/validation/rules/FieldsOnCorrectTypeRule.mjs @@ -0,0 +1,159 @@ +/** @category Validation Rules */ +import { didYouMean } from '../../jsutils/didYouMean.mjs'; +import { naturalCompare } from '../../jsutils/naturalCompare.mjs'; +import { suggestionList } from '../../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { + isAbstractType, + isInterfaceType, + isObjectType, +} from '../../type/definition.mjs'; + +/** + * Fields on correct type + * + * A GraphQL document is only valid if all fields selected are defined by the + * parent type, or are an allowed meta field such as __typename. + * + * See https://spec.graphql.org/draft/#sec-Field-Selections + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FieldsOnCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FieldsOnCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [FieldsOnCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +export function FieldsOnCorrectTypeRule(context) { + return { + Field(node) { + const type = context.getParentType(); + + if (type) { + const fieldDef = context.getFieldDef(); + + if (!fieldDef) { + // This field doesn't exist, lets look for suggestions. + const schema = context.getSchema(); + const fieldName = node.name.value; // First determine if there are any suggested types to condition on. + + let suggestion = didYouMean( + 'to use an inline fragment on', + getSuggestedTypeNames(schema, type, fieldName), + ); // If there are no suggested types, then perhaps this was a typo? + + if (suggestion === '') { + suggestion = didYouMean(getSuggestedFieldNames(type, fieldName)); + } // Report an error, including helpful suggestions. + + context.reportError( + new GraphQLError( + `Cannot query field "${fieldName}" on type "${type.name}".` + + suggestion, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} +/** + * Go through all of the implementations of type, as well as the interfaces that + * they implement. If any of those types include the provided field, suggest them, + * sorted by how often the type is referenced. + * + * @internal + */ + +function getSuggestedTypeNames(schema, type, fieldName) { + if (!isAbstractType(type)) { + // Must be an Object type, which does not have possible fields. + return []; + } + + const suggestedTypes = new Set(); + const usageCount = Object.create(null); + + for (const possibleType of schema.getPossibleTypes(type)) { + if (!possibleType.getFields()[fieldName]) { + continue; + } // This object type defines this field. + + suggestedTypes.add(possibleType); + usageCount[possibleType.name] = 1; + + for (const possibleInterface of possibleType.getInterfaces()) { + var _usageCount$possibleI; + + if (!possibleInterface.getFields()[fieldName]) { + continue; + } // This interface type defines this field. + + suggestedTypes.add(possibleInterface); + usageCount[possibleInterface.name] = + ((_usageCount$possibleI = usageCount[possibleInterface.name]) !== + null && _usageCount$possibleI !== void 0 + ? _usageCount$possibleI + : 0) + 1; + } + } + + return [...suggestedTypes] + .sort((typeA, typeB) => { + // Suggest both interface and object types based on how common they are. + const usageCountDiff = usageCount[typeB.name] - usageCount[typeA.name]; + + if (usageCountDiff !== 0) { + return usageCountDiff; + } // Suggest super types first followed by subtypes + + if (isInterfaceType(typeA) && schema.isSubType(typeA, typeB)) { + return -1; + } + + if (isInterfaceType(typeB) && schema.isSubType(typeB, typeA)) { + return 1; + } + + return naturalCompare(typeA.name, typeB.name); + }) + .map((x) => x.name); +} +/** + * For the field name provided, determine if there are any similar field names + * that may be the result of a typo. + * + * @internal + */ + +function getSuggestedFieldNames(type, fieldName) { + if (isObjectType(type) || isInterfaceType(type)) { + const possibleFieldNames = Object.keys(type.getFields()); + return suggestionList(fieldName, possibleFieldNames); + } // Otherwise, must be a Union type, which does not define fields. + + return []; +} diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5ef51a9a258d6c50b39266cabf64b8a493c4340f --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.d.ts @@ -0,0 +1,42 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FragmentsOnCompositeTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on String { length } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FragmentsOnCompositeTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [FragmentsOnCompositeTypesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function FragmentsOnCompositeTypesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..347ef7a9fbe2b5142a356e3bb45c5d02446ec530 --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.js @@ -0,0 +1,98 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.FragmentsOnCompositeTypesRule = FragmentsOnCompositeTypesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _printer = require('../../language/printer.js'); + +var _definition = require('../../type/definition.js'); + +var _typeFromAST = require('../../utilities/typeFromAST.js'); + +/** @category Validation Rules */ + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FragmentsOnCompositeTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on String { length } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FragmentsOnCompositeTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [FragmentsOnCompositeTypesRule]); + * + * validErrors; // => [] + * ``` + */ +function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + + if (typeCondition) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + typeCondition, + ); + + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot condition on non composite type "${typeStr}".`, + { + nodes: typeCondition, + }, + ), + ); + } + } + }, + + FragmentDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.typeCondition, + ); + + if (type && !(0, _definition.isCompositeType)(type)) { + const typeStr = (0, _printer.print)(node.typeCondition); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, + { + nodes: node.typeCondition, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6e62d1beaabab7578ad94812d2da9fdc52a30ebc --- /dev/null +++ b/node_modules/graphql/validation/rules/FragmentsOnCompositeTypesRule.mjs @@ -0,0 +1,81 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { print } from '../../language/printer.mjs'; +import { isCompositeType } from '../../type/definition.mjs'; +import { typeFromAST } from '../../utilities/typeFromAST.mjs'; + +/** + * Fragments on composite type + * + * Fragments use a type condition to determine if they apply, since fragments + * can only be spread into a composite type (object, interface, or union), the + * type condition must also be a composite type. + * + * See https://spec.graphql.org/draft/#sec-Fragments-On-Composite-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { FragmentsOnCompositeTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on String { length } + * `); + * const invalidErrors = validate(schema, invalidDocument, [FragmentsOnCompositeTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [FragmentsOnCompositeTypesRule]); + * + * validErrors; // => [] + * ``` + */ +export function FragmentsOnCompositeTypesRule(context) { + return { + InlineFragment(node) { + const typeCondition = node.typeCondition; + + if (typeCondition) { + const type = typeFromAST(context.getSchema(), typeCondition); + + if (type && !isCompositeType(type)) { + const typeStr = print(typeCondition); + context.reportError( + new GraphQLError( + `Fragment cannot condition on non composite type "${typeStr}".`, + { + nodes: typeCondition, + }, + ), + ); + } + } + }, + + FragmentDefinition(node) { + const type = typeFromAST(context.getSchema(), node.typeCondition); + + if (type && !isCompositeType(type)) { + const typeStr = print(node.typeCondition); + context.reportError( + new GraphQLError( + `Fragment "${node.name.value}" cannot condition on non composite type "${typeStr}".`, + { + nodes: node.typeCondition, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..153c92d8cd762caf8b476eb587ac16b43b5b7dac --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.d.ts @@ -0,0 +1,49 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(unknown: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [KnownArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function KnownArgumentNamesRule( + context: ValidationContext, +): ASTVisitor; +/** @internal */ +export declare function KnownArgumentNamesOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..9e14d9e82620a2125e190415222e88be40810aee --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.js @@ -0,0 +1,147 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.KnownArgumentNamesOnDirectivesRule = KnownArgumentNamesOnDirectivesRule; +exports.KnownArgumentNamesRule = KnownArgumentNamesRule; + +var _didYouMean = require('../../jsutils/didYouMean.js'); + +var _suggestionList = require('../../jsutils/suggestionList.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _directives = require('../../type/directives.js'); + +/** @category Validation Rules */ + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(unknown: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [KnownArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map((arg) => arg.name); + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgsNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + }, + ), + ); + } + }, + }; +} +/** @internal */ + +function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map((arg) => arg.name); + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value); + } + } + + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + + if (!knownArgs.includes(argName)) { + const suggestions = (0, _suggestionList.suggestionList)( + argName, + knownArgs, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown argument "${argName}" on directive "@${directiveName}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: argNode, + }, + ), + ); + } + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..815f4059e3c8a26d0f789e2bb00a67cebbf0fc97 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownArgumentNamesRule.mjs @@ -0,0 +1,128 @@ +/** @category Validation Rules */ +import { didYouMean } from '../../jsutils/didYouMean.mjs'; +import { suggestionList } from '../../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { specifiedDirectives } from '../../type/directives.mjs'; + +/** + * Known argument names + * + * A GraphQL field is only valid if all supplied arguments are defined by + * that field. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * See https://spec.graphql.org/draft/#sec-Directives-Are-In-Valid-Locations + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(unknown: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [KnownArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function KnownArgumentNamesRule(context) { + return { + // eslint-disable-next-line new-cap + ...KnownArgumentNamesOnDirectivesRule(context), + + Argument(argNode) { + const argDef = context.getArgument(); + const fieldDef = context.getFieldDef(); + const parentType = context.getParentType(); + + if (!argDef && fieldDef && parentType) { + const argName = argNode.name.value; + const knownArgsNames = fieldDef.args.map((arg) => arg.name); + const suggestions = suggestionList(argName, knownArgsNames); + context.reportError( + new GraphQLError( + `Unknown argument "${argName}" on field "${parentType.name}.${fieldDef.name}".` + + didYouMean(suggestions), + { + nodes: argNode, + }, + ), + ); + } + }, + }; +} +/** @internal */ + +export function KnownArgumentNamesOnDirectivesRule(context) { + const directiveArgs = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + + for (const directive of definedDirectives) { + directiveArgs[directive.name] = directive.args.map((arg) => arg.name); + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argsNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + directiveArgs[def.name.value] = argsNodes.map((arg) => arg.name.value); + } + } + + return { + Directive(directiveNode) { + const directiveName = directiveNode.name.value; + const knownArgs = directiveArgs[directiveName]; + + if (directiveNode.arguments && knownArgs) { + for (const argNode of directiveNode.arguments) { + const argName = argNode.name.value; + + if (!knownArgs.includes(argName)) { + const suggestions = suggestionList(argName, knownArgs); + context.reportError( + new GraphQLError( + `Unknown argument "${argName}" on directive "@${directiveName}".` + + didYouMean(suggestions), + { + nodes: argNode, + }, + ), + ); + } + } + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts b/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5da669177caad5c0741a82047fad53fad30dc15e --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectivesRule.d.ts @@ -0,0 +1,44 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownDirectivesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @unknown } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownDirectivesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [KnownDirectivesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function KnownDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/KnownDirectivesRule.js b/node_modules/graphql/validation/rules/KnownDirectivesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..12879b2a91299da30a061b8c17fa69c11cc75d97 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectivesRule.js @@ -0,0 +1,200 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.KnownDirectivesRule = KnownDirectivesRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _invariant = require('../../jsutils/invariant.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _ast = require('../../language/ast.js'); + +var _directiveLocation = require('../../language/directiveLocation.js'); + +var _kinds = require('../../language/kinds.js'); + +var _directives = require('../../type/directives.js'); + +/** @category Validation Rules */ + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownDirectivesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @unknown } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownDirectivesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [KnownDirectivesRule]); + * + * validErrors; // => [] + * ``` + */ +function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map((name) => name.value); + } + } + + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + + if (!locations) { + context.reportError( + new _GraphQLError.GraphQLError(`Unknown directive "@${name}".`, { + nodes: node, + }), + ); + return; + } + + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${name}" may not be used on ${candidateLocation}.`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + 'kind' in appliedTo || (0, _invariant.invariant)(false); + + switch (appliedTo.kind) { + case _kinds.Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + + case _kinds.Kind.FIELD: + return _directiveLocation.DirectiveLocation.FIELD; + + case _kinds.Kind.FRAGMENT_SPREAD: + return _directiveLocation.DirectiveLocation.FRAGMENT_SPREAD; + + case _kinds.Kind.INLINE_FRAGMENT: + return _directiveLocation.DirectiveLocation.INLINE_FRAGMENT; + + case _kinds.Kind.FRAGMENT_DEFINITION: + return _directiveLocation.DirectiveLocation.FRAGMENT_DEFINITION; + + case _kinds.Kind.VARIABLE_DEFINITION: + return _directiveLocation.DirectiveLocation.VARIABLE_DEFINITION; + + case _kinds.Kind.SCHEMA_DEFINITION: + case _kinds.Kind.SCHEMA_EXTENSION: + return _directiveLocation.DirectiveLocation.SCHEMA; + + case _kinds.Kind.SCALAR_TYPE_DEFINITION: + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.SCALAR; + + case _kinds.Kind.OBJECT_TYPE_DEFINITION: + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.OBJECT; + + case _kinds.Kind.FIELD_DEFINITION: + return _directiveLocation.DirectiveLocation.FIELD_DEFINITION; + + case _kinds.Kind.INTERFACE_TYPE_DEFINITION: + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INTERFACE; + + case _kinds.Kind.UNION_TYPE_DEFINITION: + case _kinds.Kind.UNION_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.UNION; + + case _kinds.Kind.ENUM_TYPE_DEFINITION: + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.ENUM; + + case _kinds.Kind.ENUM_VALUE_DEFINITION: + return _directiveLocation.DirectiveLocation.ENUM_VALUE; + + case _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION: + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return _directiveLocation.DirectiveLocation.INPUT_OBJECT; + + case _kinds.Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + 'kind' in parentNode || (0, _invariant.invariant)(false); + return parentNode.kind === _kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION + ? _directiveLocation.DirectiveLocation.INPUT_FIELD_DEFINITION + : _directiveLocation.DirectiveLocation.ARGUMENT_DEFINITION; + } + + case _kinds.Kind.DIRECTIVE_DEFINITION: + case _kinds.Kind.DIRECTIVE_EXTENSION: + return _directiveLocation.DirectiveLocation.DIRECTIVE_DEFINITION; + // Not reachable, all possible types have been considered. + + /* c8 ignore next */ + + default: + false || + (0, _invariant.invariant)( + false, + 'Unexpected kind: ' + (0, _inspect.inspect)(appliedTo.kind), + ); + } +} + +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case _ast.OperationTypeNode.QUERY: + return _directiveLocation.DirectiveLocation.QUERY; + + case _ast.OperationTypeNode.MUTATION: + return _directiveLocation.DirectiveLocation.MUTATION; + + case _ast.OperationTypeNode.SUBSCRIPTION: + return _directiveLocation.DirectiveLocation.SUBSCRIPTION; + } +} diff --git a/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs b/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e5275b37d9da0088ef819f5b493bdf9414296e18 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownDirectivesRule.mjs @@ -0,0 +1,182 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { invariant } from '../../jsutils/invariant.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { OperationTypeNode } from '../../language/ast.mjs'; +import { DirectiveLocation } from '../../language/directiveLocation.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { specifiedDirectives } from '../../type/directives.mjs'; + +/** + * Known directives + * + * A GraphQL document is only valid if all `@directives` are known by the + * schema and legally positioned. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownDirectivesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @unknown } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownDirectivesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [KnownDirectivesRule]); + * + * validErrors; // => [] + * ``` + */ +export function KnownDirectivesRule(context) { + const locationsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + + for (const directive of definedDirectives) { + locationsMap[directive.name] = directive.locations; + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + locationsMap[def.name.value] = def.locations.map((name) => name.value); + } + } + + return { + Directive(node, _key, _parent, _path, ancestors) { + const name = node.name.value; + const locations = locationsMap[name]; + + if (!locations) { + context.reportError( + new GraphQLError(`Unknown directive "@${name}".`, { + nodes: node, + }), + ); + return; + } + + const candidateLocation = getDirectiveLocationForASTPath(ancestors); + + if (candidateLocation && !locations.includes(candidateLocation)) { + context.reportError( + new GraphQLError( + `Directive "@${name}" may not be used on ${candidateLocation}.`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} + +function getDirectiveLocationForASTPath(ancestors) { + const appliedTo = ancestors[ancestors.length - 1]; + 'kind' in appliedTo || invariant(false); + + switch (appliedTo.kind) { + case Kind.OPERATION_DEFINITION: + return getDirectiveLocationForOperation(appliedTo.operation); + + case Kind.FIELD: + return DirectiveLocation.FIELD; + + case Kind.FRAGMENT_SPREAD: + return DirectiveLocation.FRAGMENT_SPREAD; + + case Kind.INLINE_FRAGMENT: + return DirectiveLocation.INLINE_FRAGMENT; + + case Kind.FRAGMENT_DEFINITION: + return DirectiveLocation.FRAGMENT_DEFINITION; + + case Kind.VARIABLE_DEFINITION: + return DirectiveLocation.VARIABLE_DEFINITION; + + case Kind.SCHEMA_DEFINITION: + case Kind.SCHEMA_EXTENSION: + return DirectiveLocation.SCHEMA; + + case Kind.SCALAR_TYPE_DEFINITION: + case Kind.SCALAR_TYPE_EXTENSION: + return DirectiveLocation.SCALAR; + + case Kind.OBJECT_TYPE_DEFINITION: + case Kind.OBJECT_TYPE_EXTENSION: + return DirectiveLocation.OBJECT; + + case Kind.FIELD_DEFINITION: + return DirectiveLocation.FIELD_DEFINITION; + + case Kind.INTERFACE_TYPE_DEFINITION: + case Kind.INTERFACE_TYPE_EXTENSION: + return DirectiveLocation.INTERFACE; + + case Kind.UNION_TYPE_DEFINITION: + case Kind.UNION_TYPE_EXTENSION: + return DirectiveLocation.UNION; + + case Kind.ENUM_TYPE_DEFINITION: + case Kind.ENUM_TYPE_EXTENSION: + return DirectiveLocation.ENUM; + + case Kind.ENUM_VALUE_DEFINITION: + return DirectiveLocation.ENUM_VALUE; + + case Kind.INPUT_OBJECT_TYPE_DEFINITION: + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return DirectiveLocation.INPUT_OBJECT; + + case Kind.INPUT_VALUE_DEFINITION: { + const parentNode = ancestors[ancestors.length - 3]; + 'kind' in parentNode || invariant(false); + return parentNode.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION + ? DirectiveLocation.INPUT_FIELD_DEFINITION + : DirectiveLocation.ARGUMENT_DEFINITION; + } + + case Kind.DIRECTIVE_DEFINITION: + case Kind.DIRECTIVE_EXTENSION: + return DirectiveLocation.DIRECTIVE_DEFINITION; + // Not reachable, all possible types have been considered. + + /* c8 ignore next */ + + default: + false || invariant(false, 'Unexpected kind: ' + inspect(appliedTo.kind)); + } +} + +function getDirectiveLocationForOperation(operation) { + switch (operation) { + case OperationTypeNode.QUERY: + return DirectiveLocation.QUERY; + + case OperationTypeNode.MUTATION: + return DirectiveLocation.MUTATION; + + case OperationTypeNode.SUBSCRIPTION: + return DirectiveLocation.SUBSCRIPTION; + } +} diff --git a/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a9c0666078e9acd6e99dbce510f0860d0729db0 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { ...Missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment NameFields on Query { name } query { ...NameFields } + * `); + * const validErrors = validate(schema, validDocument, [KnownFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function KnownFragmentNamesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..566d4bc3d9fccaa8c15840ce40e2c2e7ae0af17b --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.js @@ -0,0 +1,65 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.KnownFragmentNamesRule = KnownFragmentNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { ...Missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment NameFields on Query { name } query { ...NameFields } + * `); + * const validErrors = validate(schema, validDocument, [KnownFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown fragment "${fragmentName}".`, + { + nodes: node.name, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d97539fb5a62beb4e6b692760a6f879116560543 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownFragmentNamesRule.mjs @@ -0,0 +1,54 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Known fragment names + * + * A GraphQL document is only valid if all `...Fragment` fragment spreads refer + * to fragments defined in the same document. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spread-target-defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { ...Missing } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment NameFields on Query { name } query { ...NameFields } + * `); + * const validErrors = validate(schema, validDocument, [KnownFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function KnownFragmentNamesRule(context) { + return { + FragmentSpread(node) { + const fragmentName = node.name.value; + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + context.reportError( + new GraphQLError(`Unknown fragment "${fragmentName}".`, { + nodes: node.name, + }), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts b/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ae3ee9560b5beab864ec89f2b3f042f94562f896 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNamesRule.d.ts @@ -0,0 +1,44 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownTypeNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on Missing { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownTypeNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [KnownTypeNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function KnownTypeNamesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/KnownTypeNamesRule.js b/node_modules/graphql/validation/rules/KnownTypeNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..749435f639789252ebd4f165bebd0d60938dce51 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNamesRule.js @@ -0,0 +1,118 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.KnownTypeNamesRule = KnownTypeNamesRule; + +var _didYouMean = require('../../jsutils/didYouMean.js'); + +var _suggestionList = require('../../jsutils/suggestionList.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _predicates = require('../../language/predicates.js'); + +var _introspection = require('../../type/introspection.js'); + +var _scalars = require('../../type/scalars.js'); + +/** @category Validation Rules */ + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownTypeNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on Missing { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownTypeNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [KnownTypeNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = true; + } + } + + const typeNames = [ + ...Object.keys(existingTypesMap), + ...Object.keys(definedTypes), + ]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + + const definitionNode = + (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 + ? _ancestors$ + : parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + isSDL ? standardTypeNames.concat(typeNames) : typeNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Unknown type "${typeName}".` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node, + }, + ), + ); + } + }, + }; +} + +const standardTypeNames = [ + ..._scalars.specifiedScalarTypes, + ..._introspection.introspectionTypes, +].map((type) => type.name); + +function isSDLNode(value) { + return ( + 'kind' in value && + ((0, _predicates.isTypeSystemDefinitionNode)(value) || + (0, _predicates.isTypeSystemExtensionNode)(value)) + ); +} diff --git a/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs b/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..38d665f9dd9e8662be26698a2bbacecbf04f2795 --- /dev/null +++ b/node_modules/graphql/validation/rules/KnownTypeNamesRule.mjs @@ -0,0 +1,105 @@ +/** @category Validation Rules */ +import { didYouMean } from '../../jsutils/didYouMean.mjs'; +import { suggestionList } from '../../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { + isTypeDefinitionNode, + isTypeSystemDefinitionNode, + isTypeSystemExtensionNode, +} from '../../language/predicates.mjs'; +import { introspectionTypes } from '../../type/introspection.mjs'; +import { specifiedScalarTypes } from '../../type/scalars.mjs'; + +/** + * Known type names + * + * A GraphQL document is only valid if referenced types (specifically + * variable definitions and fragment conditions) are defined by the type schema. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Spread-Type-Existence + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { KnownTypeNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Bad on Missing { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [KnownTypeNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Good on Query { name } + * `); + * const validErrors = validate(schema, validDocument, [KnownTypeNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function KnownTypeNamesRule(context) { + const schema = context.getSchema(); + const existingTypesMap = schema ? schema.getTypeMap() : Object.create(null); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = true; + } + } + + const typeNames = [ + ...Object.keys(existingTypesMap), + ...Object.keys(definedTypes), + ]; + return { + NamedType(node, _1, parent, _2, ancestors) { + const typeName = node.name.value; + + if (!existingTypesMap[typeName] && !definedTypes[typeName]) { + var _ancestors$; + + const definitionNode = + (_ancestors$ = ancestors[2]) !== null && _ancestors$ !== void 0 + ? _ancestors$ + : parent; + const isSDL = definitionNode != null && isSDLNode(definitionNode); + + if (isSDL && standardTypeNames.includes(typeName)) { + return; + } + + const suggestedTypes = suggestionList( + typeName, + isSDL ? standardTypeNames.concat(typeNames) : typeNames, + ); + context.reportError( + new GraphQLError( + `Unknown type "${typeName}".` + didYouMean(suggestedTypes), + { + nodes: node, + }, + ), + ); + } + }, + }; +} +const standardTypeNames = [...specifiedScalarTypes, ...introspectionTypes].map( + (type) => type.name, +); + +function isSDLNode(value) { + return ( + 'kind' in value && + (isTypeSystemDefinitionNode(value) || isTypeSystemExtensionNode(value)) + ); +} diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6768a9a8876884c5b38770bc0e8b2ebd229921d2 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { LoneAnonymousOperationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query { name } query Other { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [LoneAnonymousOperationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [LoneAnonymousOperationRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function LoneAnonymousOperationRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js new file mode 100644 index 0000000000000000000000000000000000000000..55abcac79a6bd21d05ef502894f5177f1158af20 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.js @@ -0,0 +1,71 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.LoneAnonymousOperationRule = LoneAnonymousOperationRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +/** @category Validation Rules */ + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { LoneAnonymousOperationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query { name } query Other { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [LoneAnonymousOperationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [LoneAnonymousOperationRule]); + * + * validErrors; // => [] + * ``` + */ +function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + (definition) => definition.kind === _kinds.Kind.OPERATION_DEFINITION, + ).length; + }, + + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + 'This anonymous operation must be the only defined operation.', + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..427792755ef9fa64535cbac680c10392116a93ec --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneAnonymousOperationRule.mjs @@ -0,0 +1,62 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; + +/** + * Lone anonymous operation + * + * A GraphQL document is only valid if when it contains an anonymous operation + * (the query short-hand) that it contains only that one operation definition. + * + * See https://spec.graphql.org/draft/#sec-Lone-Anonymous-Operation + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { LoneAnonymousOperationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query { name } query Other { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [LoneAnonymousOperationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [LoneAnonymousOperationRule]); + * + * validErrors; // => [] + * ``` + */ +export function LoneAnonymousOperationRule(context) { + let operationCount = 0; + return { + Document(node) { + operationCount = node.definitions.filter( + (definition) => definition.kind === Kind.OPERATION_DEFINITION, + ).length; + }, + + OperationDefinition(node) { + if (!node.name && operationCount > 1) { + context.reportError( + new GraphQLError( + 'This anonymous operation must be the only defined operation.', + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..fce33ce0c0826f5b64ad4e7c7a83882215db4ad9 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { LoneSchemaDefinitionRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query } schema { query: Query } type Query { name: String } + * `; + * + * LoneSchemaDefinitionRule.name; // => 'LoneSchemaDefinitionRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function LoneSchemaDefinitionRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js new file mode 100644 index 0000000000000000000000000000000000000000..1b777fb05cdcd83356c3410e4e52752d60e5c021 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.js @@ -0,0 +1,89 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.LoneSchemaDefinitionRule = LoneSchemaDefinitionRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { LoneSchemaDefinitionRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query } schema { query: Query } type Query { name: String } + * `; + * + * LoneSchemaDefinitionRule.name; // => 'LoneSchemaDefinitionRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + + const oldSchema = context.getSchema(); + const alreadyDefined = + (_ref = + (_ref2 = + (_oldSchema$astNode = + oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 + ? _oldSchema$astNode + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getQueryType()) !== null && _ref2 !== void 0 + ? _ref2 + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getMutationType()) !== null && _ref !== void 0 + ? _ref + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Cannot define a new schema within a schema extension.', + { + nodes: node, + }, + ), + ); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Must provide only one schema definition.', + { + nodes: node, + }, + ), + ); + } + + ++schemaDefinitionsCount; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8a2539162175f905e64b08aae5c463db61869390 --- /dev/null +++ b/node_modules/graphql/validation/rules/LoneSchemaDefinitionRule.mjs @@ -0,0 +1,78 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Lone Schema definition + * + * A GraphQL document is only valid if it contains only one schema definition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { LoneSchemaDefinitionRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query } schema { query: Query } type Query { name: String } + * `; + * + * LoneSchemaDefinitionRule.name; // => 'LoneSchemaDefinitionRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function LoneSchemaDefinitionRule(context) { + var _ref, _ref2, _oldSchema$astNode; + + const oldSchema = context.getSchema(); + const alreadyDefined = + (_ref = + (_ref2 = + (_oldSchema$astNode = + oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.astNode) !== null && _oldSchema$astNode !== void 0 + ? _oldSchema$astNode + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getQueryType()) !== null && _ref2 !== void 0 + ? _ref2 + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getMutationType()) !== null && _ref !== void 0 + ? _ref + : oldSchema === null || oldSchema === void 0 + ? void 0 + : oldSchema.getSubscriptionType(); + let schemaDefinitionsCount = 0; + return { + SchemaDefinition(node) { + if (alreadyDefined) { + context.reportError( + new GraphQLError( + 'Cannot define a new schema within a schema extension.', + { + nodes: node, + }, + ), + ); + return; + } + + if (schemaDefinitionsCount > 0) { + context.reportError( + new GraphQLError('Must provide only one schema definition.', { + nodes: node, + }), + ); + } + + ++schemaDefinitionsCount; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.d.ts b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f5df050f5cdd9a435eaa5d55670aabc836cea1f --- /dev/null +++ b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.d.ts @@ -0,0 +1,36 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Implements the max introspection depth validation rule. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { MaxIntrospectionDepthRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { types { fields { type { fields { type { fields { name } } } } } } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [MaxIntrospectionDepthRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const validErrors = validate(schema, validDocument, [MaxIntrospectionDepthRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function MaxIntrospectionDepthRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.js b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.js new file mode 100644 index 0000000000000000000000000000000000000000..90cb01e5adf5ca86669fc4e5b3ccf57b44afc2b9 --- /dev/null +++ b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.js @@ -0,0 +1,123 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.MaxIntrospectionDepthRule = MaxIntrospectionDepthRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +/** @category Validation Rules */ +const MAX_LISTS_DEPTH = 3; +/** + * Implements the max introspection depth validation rule. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { MaxIntrospectionDepthRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { types { fields { type { fields { type { fields { name } } } } } } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [MaxIntrospectionDepthRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const validErrors = validate(schema, validDocument, [MaxIntrospectionDepthRule]); + * + * validErrors; // => [] + * ``` + */ + +function MaxIntrospectionDepthRule(context) { + /** + * Counts the depth of list fields in "__Type" recursively and + * returns `true` if the limit has been reached. + * + * @internal + */ + function checkDepth(node, visitedFragments = Object.create(null), depth = 0) { + if (node.kind === _kinds.Kind.FRAGMENT_SPREAD) { + const fragmentName = node.name.value; + + if (visitedFragments[fragmentName] === true) { + // Fragment cycles are handled by `NoFragmentCyclesRule`. + return false; + } + + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + // Missing fragments checks are handled by `KnownFragmentNamesRule`. + return false; + } // Rather than following an immutable programming pattern which has + // significant memory and garbage collection overhead, we've opted to + // take a mutable approach for efficiency's sake. Importantly visiting a + // fragment twice is fine, so long as you don't do one visit inside the + // other. + + try { + visitedFragments[fragmentName] = true; + return checkDepth(fragment, visitedFragments, depth); + } finally { + visitedFragments[fragmentName] = undefined; + } + } + + if ( + node.kind === _kinds.Kind.FIELD && // check all introspection lists + (node.name.value === 'fields' || + node.name.value === 'interfaces' || + node.name.value === 'possibleTypes' || + node.name.value === 'inputFields') + ) { + // eslint-disable-next-line no-param-reassign + depth++; + + if (depth >= MAX_LISTS_DEPTH) { + return true; + } + } // handles fields and inline fragments + + if ('selectionSet' in node && node.selectionSet) { + for (const child of node.selectionSet.selections) { + if (checkDepth(child, visitedFragments, depth)) { + return true; + } + } + } + + return false; + } + + return { + Field(node) { + if (node.name.value === '__schema' || node.name.value === '__type') { + if (checkDepth(node)) { + context.reportError( + new _GraphQLError.GraphQLError( + 'Maximum introspection depth exceeded', + { + nodes: [node], + }, + ), + ); + return false; + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.mjs b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..411a5dc74718d473b8c27aa8ee8945880cad4c76 --- /dev/null +++ b/node_modules/graphql/validation/rules/MaxIntrospectionDepthRule.mjs @@ -0,0 +1,111 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +const MAX_LISTS_DEPTH = 3; +/** + * Implements the max introspection depth validation rule. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { MaxIntrospectionDepthRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { types { fields { type { fields { type { fields { name } } } } } } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [MaxIntrospectionDepthRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const validErrors = validate(schema, validDocument, [MaxIntrospectionDepthRule]); + * + * validErrors; // => [] + * ``` + */ + +export function MaxIntrospectionDepthRule(context) { + /** + * Counts the depth of list fields in "__Type" recursively and + * returns `true` if the limit has been reached. + * + * @internal + */ + function checkDepth(node, visitedFragments = Object.create(null), depth = 0) { + if (node.kind === Kind.FRAGMENT_SPREAD) { + const fragmentName = node.name.value; + + if (visitedFragments[fragmentName] === true) { + // Fragment cycles are handled by `NoFragmentCyclesRule`. + return false; + } + + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + // Missing fragments checks are handled by `KnownFragmentNamesRule`. + return false; + } // Rather than following an immutable programming pattern which has + // significant memory and garbage collection overhead, we've opted to + // take a mutable approach for efficiency's sake. Importantly visiting a + // fragment twice is fine, so long as you don't do one visit inside the + // other. + + try { + visitedFragments[fragmentName] = true; + return checkDepth(fragment, visitedFragments, depth); + } finally { + visitedFragments[fragmentName] = undefined; + } + } + + if ( + node.kind === Kind.FIELD && // check all introspection lists + (node.name.value === 'fields' || + node.name.value === 'interfaces' || + node.name.value === 'possibleTypes' || + node.name.value === 'inputFields') + ) { + // eslint-disable-next-line no-param-reassign + depth++; + + if (depth >= MAX_LISTS_DEPTH) { + return true; + } + } // handles fields and inline fragments + + if ('selectionSet' in node && node.selectionSet) { + for (const child of node.selectionSet.selections) { + if (checkDepth(child, visitedFragments, depth)) { + return true; + } + } + } + + return false; + } + + return { + Field(node) { + if (node.name.value === '__schema' || node.name.value === '__type') { + if (checkDepth(node)) { + context.reportError( + new GraphQLError('Maximum introspection depth exceeded', { + nodes: [node], + }), + ); + return false; + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5dc8b47ee6cec9891df4ae52cf2bad69566880d --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoFragmentCyclesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { ...B } fragment B on Query { ...A } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoFragmentCyclesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [NoFragmentCyclesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoFragmentCyclesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..c739cf51b8d86020d0c318cf57e723dc35267792 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.js @@ -0,0 +1,114 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoFragmentCyclesRule = NoFragmentCyclesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoFragmentCyclesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { ...B } fragment B on Query { ...A } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoFragmentCyclesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [NoFragmentCyclesRule]); + * + * validErrors; // => [] + * ``` + */ +function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + const spreadPath = []; // Position in the spread path + + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath + .slice(0, -1) + .map((s) => '"' + s.name.value + '"') + .join(', '); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot spread fragment "${spreadName}" within itself` + + (viaPath !== '' ? ` via ${viaPath}.` : '.'), + { + nodes: cyclePath, + }, + ), + ); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..83529ccfe23ac078eb90c7d13e356b658923a942 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoFragmentCyclesRule.mjs @@ -0,0 +1,106 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * No fragment cycles + * + * The graph of fragment spreads must not form any cycles including spreading itself. + * Otherwise an operation could infinitely spread or infinitely execute on cycles in the underlying data. + * + * See https://spec.graphql.org/draft/#sec-Fragment-spreads-must-not-form-cycles + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoFragmentCyclesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { ...B } fragment B on Query { ...A } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoFragmentCyclesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [NoFragmentCyclesRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoFragmentCyclesRule(context) { + // Tracks already visited fragments to maintain O(N) and to ensure that cycles + // are not redundantly reported. + const visitedFrags = Object.create(null); // Array of AST nodes used to produce meaningful errors + + const spreadPath = []; // Position in the spread path + + const spreadPathIndexByName = Object.create(null); + return { + OperationDefinition: () => false, + + FragmentDefinition(node) { + detectCycleRecursive(node); + return false; + }, + }; // This does a straight-forward DFS to find cycles. + // It does not terminate when a cycle was found but continues to explore + // the graph to find all possible cycles. + + function detectCycleRecursive(fragment) { + if (visitedFrags[fragment.name.value]) { + return; + } + + const fragmentName = fragment.name.value; + visitedFrags[fragmentName] = true; + const spreadNodes = context.getFragmentSpreads(fragment.selectionSet); + + if (spreadNodes.length === 0) { + return; + } + + spreadPathIndexByName[fragmentName] = spreadPath.length; + + for (const spreadNode of spreadNodes) { + const spreadName = spreadNode.name.value; + const cycleIndex = spreadPathIndexByName[spreadName]; + spreadPath.push(spreadNode); + + if (cycleIndex === undefined) { + const spreadFragment = context.getFragment(spreadName); + + if (spreadFragment) { + detectCycleRecursive(spreadFragment); + } + } else { + const cyclePath = spreadPath.slice(cycleIndex); + const viaPath = cyclePath + .slice(0, -1) + .map((s) => '"' + s.name.value + '"') + .join(', '); + context.reportError( + new GraphQLError( + `Cannot spread fragment "${spreadName}" within itself` + + (viaPath !== '' ? ` via ${viaPath}.` : '.'), + { + nodes: cyclePath, + }, + ), + ); + } + + spreadPath.pop(); + } + + spreadPathIndexByName[fragmentName] = undefined; + } +} diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8bdf57dc671cba6a7df0b63970b317123ce7460e --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUndefinedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { field(arg: $missing) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUndefinedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUndefinedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoUndefinedVariablesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..379e6e2014c075b2a0d5a43fa72013aa81894964 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.js @@ -0,0 +1,81 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoUndefinedVariablesRule = NoUndefinedVariablesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUndefinedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { field(arg: $missing) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUndefinedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUndefinedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + const varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` + : `Variable "$${varName}" is not defined.`, + { + nodes: [node, operation], + }, + ), + ); + } + } + }, + }, + + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..0b2a7e0718a60554ee41f586122a365771c5c8d8 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUndefinedVariablesRule.mjs @@ -0,0 +1,73 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * No undefined variables + * + * A GraphQL operation is only valid if all variables encountered, both directly + * and via fragment spreads, are defined by that operation. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Uses-Defined + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUndefinedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { field(arg: $missing) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUndefinedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUndefinedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoUndefinedVariablesRule(context) { + let variableNameDefined = Object.create(null); + return { + OperationDefinition: { + enter() { + variableNameDefined = Object.create(null); + }, + + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + const varName = node.name.value; + + if (variableNameDefined[varName] !== true) { + context.reportError( + new GraphQLError( + operation.name + ? `Variable "$${varName}" is not defined by operation "${operation.name.value}".` + : `Variable "$${varName}" is not defined.`, + { + nodes: [node, operation], + }, + ), + ); + } + } + }, + }, + + VariableDefinition(node) { + variableNameDefined[node.variable.name.value] = true; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c641f29b7b9697ad34722e1d0fcd542e2eb0cb94 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedFragmentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Unused on Query { name } query { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedFragmentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Used on Query { name } query { ...Used } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedFragmentsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoUnusedFragmentsRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..2905ab716ed2ac086e0d9d4cf6d3d5a1d9e9ad60 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.js @@ -0,0 +1,90 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoUnusedFragmentsRule = NoUnusedFragmentsRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedFragmentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Unused on Query { name } query { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedFragmentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Used on Query { name } query { ...Used } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedFragmentsRule]); + * + * validErrors; // => [] + * ``` + */ +function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" is never used.`, + { + nodes: fragmentDef, + }, + ), + ); + } + } + }, + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e21560ba52a070e403b71ab0e52a7ac9e0e92dc7 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedFragmentsRule.mjs @@ -0,0 +1,79 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * No unused fragments + * + * A GraphQL document is only valid if all fragment definitions are spread + * within operations, or spread within other fragments spread within operations. + * + * See https://spec.graphql.org/draft/#sec-Fragments-Must-Be-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedFragmentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment Unused on Query { name } query { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedFragmentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment Used on Query { name } query { ...Used } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedFragmentsRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoUnusedFragmentsRule(context) { + const operationDefs = []; + const fragmentDefs = []; + return { + OperationDefinition(node) { + operationDefs.push(node); + return false; + }, + + FragmentDefinition(node) { + fragmentDefs.push(node); + return false; + }, + + Document: { + leave() { + const fragmentNameUsed = Object.create(null); + + for (const operation of operationDefs) { + for (const fragment of context.getRecursivelyReferencedFragments( + operation, + )) { + fragmentNameUsed[fragment.name.value] = true; + } + } + + for (const fragmentDef of fragmentDefs) { + const fragName = fragmentDef.name.value; + + if (fragmentNameUsed[fragName] !== true) { + context.reportError( + new GraphQLError(`Fragment "${fragName}" is never used.`, { + nodes: fragmentDef, + }), + ); + } + } + }, + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96673f3c0d66e8b072b8ddafa0c4ea194ee41e42 --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.d.ts @@ -0,0 +1,42 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoUnusedVariablesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..1165d2e571a1854e4d5533d6eba3808fd9f58cbd --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoUnusedVariablesRule = NoUnusedVariablesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError( + new _GraphQLError.GraphQLError( + operation.name + ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` + : `Variable "$${variableName}" is never used.`, + { + nodes: variableDef, + }, + ), + ); + } + } + }, + }, + + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} diff --git a/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f2d3cfcd328dcc5739dc89f3349555f3595c323e --- /dev/null +++ b/node_modules/graphql/validation/rules/NoUnusedVariablesRule.mjs @@ -0,0 +1,79 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * No unused variables + * + * A GraphQL operation is only valid if all variables defined by an operation + * are used, either directly or within a spread fragment. + * + * See https://spec.graphql.org/draft/#sec-All-Variables-Used + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoUnusedVariablesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID) { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoUnusedVariablesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [NoUnusedVariablesRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoUnusedVariablesRule(context) { + let variableDefs = []; + return { + OperationDefinition: { + enter() { + variableDefs = []; + }, + + leave(operation) { + const variableNameUsed = Object.create(null); + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node } of usages) { + variableNameUsed[node.name.value] = true; + } + + for (const variableDef of variableDefs) { + const variableName = variableDef.variable.name.value; + + if (variableNameUsed[variableName] !== true) { + context.reportError( + new GraphQLError( + operation.name + ? `Variable "$${variableName}" is never used in operation "${operation.name.value}".` + : `Variable "$${variableName}" is never used.`, + { + nodes: variableDef, + }, + ), + ); + } + } + }, + }, + + VariableDefinition(def) { + variableDefs.push(def); + }, + }; +} diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..24fe6ce583e06fa3d0882ada6087627f4bdc1812 --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.d.ts @@ -0,0 +1,47 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { OverlappingFieldsCanBeMergedRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * name: String + * barkVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { value: barkVolume value: name } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [OverlappingFieldsCanBeMergedRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { barkVolume name } } + * `); + * const validErrors = validate(schema, validDocument, [OverlappingFieldsCanBeMergedRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function OverlappingFieldsCanBeMergedRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js new file mode 100644 index 0000000000000000000000000000000000000000..3b599f864f2083cd8dee7138875c39d747956741 --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.js @@ -0,0 +1,907 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.OverlappingFieldsCanBeMergedRule = OverlappingFieldsCanBeMergedRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _printer = require('../../language/printer.js'); + +var _definition = require('../../type/definition.js'); + +var _sortValueNode = require('../../utilities/sortValueNode.js'); + +var _typeFromAST = require('../../utilities/typeFromAST.js'); + +/** @category Validation Rules */ +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subReason]) => + `subfields "${responseName}" conflict because ` + + reasonMessage(subReason), + ) + .join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { OverlappingFieldsCanBeMergedRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * name: String + * barkVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { value: barkVolume value: name } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [OverlappingFieldsCanBeMergedRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { barkVolume name } } + * `); + * const validErrors = validate(schema, validDocument, [OverlappingFieldsCanBeMergedRule]); + * + * validErrors; // => [] + * ``` + */ + +function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when fields and a fragment or two fragments are compared + // "between" each other for conflicts. Comparisons made be made many times, + // so memoizing this can dramatically improve the performance of this validator. + const comparedFieldsAndFragmentPairs = new OrderedPairSet(); + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); + + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError( + new _GraphQLError.GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + { + nodes: fields1.concat(fields2), + }, + ), + ); + } + }, + }; +} + +/** + * Find all conflicts found "within" a selection set, including those found + * via spreading in fragments. Called when visiting each SelectionSet in the + * GraphQL Document. + * + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + * @internal + */ +function findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentType, + selectionSet, +) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, + ); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + +function collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentName, +) { + // Memoize so the fields and fragments are not compared for conflicts more + // than once. + if ( + comparedFieldsAndFragmentPairs.has( + fieldMap, + fragmentName, + areMutuallyExclusive, + ) + ) { + return; + } + + comparedFieldsAndFragmentPairs.add( + fieldMap, + fragmentName, + areMutuallyExclusive, + ); + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + const [fieldMap2, referencedFragmentNames] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); // Do not compare a fragment's fieldMap to itself. + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (const referencedFragmentName of referencedFragmentNames) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + referencedFragmentName, + ); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + +function collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, +) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + const [fieldMap1, referencedFragmentNames1] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, referencedFragmentNames2] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + referencedFragmentName2, + ); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + referencedFragmentName1, + fragmentName2, + ); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + +function findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + parentType1, + selectionSet1, + parentType2, + selectionSet2, +) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); // (H) First, collect all conflicts between these two collections of field. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentName2, + ); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentName1, + ); + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, + ); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + +function collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + +function collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + fieldMap1, + fieldMap2, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, + ); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + +function findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, +) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + (0, _definition.isObjectType)(parentType1) && + (0, _definition.isObjectType)(parentType2)); + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + + if (name1 !== name2) { + return [ + [responseName, `"${name1}" and "${name2}" are different fields`], + [node1], + [node2], + ]; + } // Two field calls must have the same arguments. + + if (!sameArguments(node1, node2)) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } // The return type for each field. + + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${(0, _inspect.inspect)( + type1, + )}" and "${(0, _inspect.inspect)(type2)}"`, + ], + [node1], + [node2], + ]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + (0, _definition.getNamedType)(type1), + selectionSet1, + (0, _definition.getNamedType)(type2), + selectionSet2, + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; + + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + + if (args2 === undefined || args2.length === 0) { + return false; + } + /* c8 ignore next */ + + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ + } + + const values2 = new Map(args2.map(({ name, value }) => [name.value, value])); + return args1.every((arg1) => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); + + if (value2 === undefined) { + return false; + } + + return stringifyValue(value1) === stringifyValue(value2); + }); +} + +function stringifyValue(value) { + return (0, _printer.print)((0, _sortValueNode.sortValueNode)(value)); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + +function doTypesConflict(type1, type2) { + if ((0, _definition.isListType)(type1)) { + return (0, _definition.isListType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + + if ((0, _definition.isListType)(type2)) { + return true; + } + + if ((0, _definition.isNonNullType)(type1)) { + return (0, _definition.isNonNullType)(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + + if ((0, _definition.isNonNullType)(type2)) { + return true; + } + + if ( + (0, _definition.isLeafType)(type1) || + (0, _definition.isLeafType)(type2) + ) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + +function getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, +) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (cached) { + return cached; + } + + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ); + + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + +function getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + const fragmentType = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + fragment.typeCondition, + ); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); +} + +function _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case _kinds.Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; + + if ( + (0, _definition.isObjectType)(parentType) || + (0, _definition.isInterfaceType)(parentType) + ) { + fieldDef = parentType.getFields()[fieldName]; + } + + const responseName = selection.alias + ? selection.alias.value + : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + + case _kinds.Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case _kinds.Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? (0, _typeFromAST.typeFromAST)(context.getSchema(), typeCondition) + : parentType; + + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + + break; + } + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], + ]; + } +} +/** + * A way to keep track of pairs of things where the ordering of the pair + * matters. + * + * Provides a third argument for has/set to allow flagging the pair as + * weakly or strongly present within the collection. + * + * @internal + */ + +class OrderedPairSet { + constructor() { + this._data = new Map(); + } + + has(a, b, weaklyPresent) { + var _this$_data$get; + + const result = + (_this$_data$get = this._data.get(a)) === null || + _this$_data$get === void 0 + ? void 0 + : _this$_data$get.get(b); + + if (result === undefined) { + return false; + } + + return weaklyPresent ? true : weaklyPresent === result; + } + + add(a, b, weaklyPresent) { + const map = this._data.get(a); + + if (map === undefined) { + this._data.set(a, new Map([[b, weaklyPresent]])); + } else { + map.set(b, weaklyPresent); + } + } +} +/** + * A way to keep track of pairs of similar things when the ordering of the pair + * does not matter. + * + * @internal + */ + +class PairSet { + constructor() { + this._orderedPairSet = new OrderedPairSet(); + } + + has(a, b, weaklyPresent) { + return a < b + ? this._orderedPairSet.has(a, b, weaklyPresent) + : this._orderedPairSet.has(b, a, weaklyPresent); + } + + add(a, b, weaklyPresent) { + if (a < b) { + this._orderedPairSet.add(a, b, weaklyPresent); + } else { + this._orderedPairSet.add(b, a, weaklyPresent); + } + } +} diff --git a/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..abd8ad52f1016932c9f1d7b6b254357656ac723f --- /dev/null +++ b/node_modules/graphql/validation/rules/OverlappingFieldsCanBeMergedRule.mjs @@ -0,0 +1,892 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { print } from '../../language/printer.mjs'; +import { + getNamedType, + isInterfaceType, + isLeafType, + isListType, + isNonNullType, + isObjectType, +} from '../../type/definition.mjs'; +import { sortValueNode } from '../../utilities/sortValueNode.mjs'; +import { typeFromAST } from '../../utilities/typeFromAST.mjs'; + +function reasonMessage(reason) { + if (Array.isArray(reason)) { + return reason + .map( + ([responseName, subReason]) => + `subfields "${responseName}" conflict because ` + + reasonMessage(subReason), + ) + .join(' and '); + } + + return reason; +} +/** + * Overlapping fields can be merged + * + * A selection set is only valid if all fields (including spreading any + * fragments) either correspond to distinct response names or can be merged + * without ambiguity. + * + * See https://spec.graphql.org/draft/#sec-Field-Selection-Merging + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { OverlappingFieldsCanBeMergedRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * name: String + * barkVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { value: barkVolume value: name } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [OverlappingFieldsCanBeMergedRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { barkVolume name } } + * `); + * const validErrors = validate(schema, validDocument, [OverlappingFieldsCanBeMergedRule]); + * + * validErrors; // => [] + * ``` + */ + +export function OverlappingFieldsCanBeMergedRule(context) { + // A memoization for when fields and a fragment or two fragments are compared + // "between" each other for conflicts. Comparisons made be made many times, + // so memoizing this can dramatically improve the performance of this validator. + const comparedFieldsAndFragmentPairs = new OrderedPairSet(); + const comparedFragmentPairs = new PairSet(); // A cache for the "field map" and list of fragment names found in any given + // selection set. Selection sets may be asked for this information multiple + // times, so this improves the performance of this validator. + + const cachedFieldsAndFragmentNames = new Map(); + return { + SelectionSet(selectionSet) { + const conflicts = findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + context.getParentType(), + selectionSet, + ); + + for (const [[responseName, reason], fields1, fields2] of conflicts) { + const reasonMsg = reasonMessage(reason); + context.reportError( + new GraphQLError( + `Fields "${responseName}" conflict because ${reasonMsg}. Use different aliases on the fields to fetch both if this was intentional.`, + { + nodes: fields1.concat(fields2), + }, + ), + ); + } + }, + }; +} + +/** + * Find all conflicts found "within" a selection set, including those found + * via spreading in fragments. Called when visiting each SelectionSet in the + * GraphQL Document. + * + * Algorithm: + * + * Conflicts occur when two fields exist in a query which will produce the same + * response name, but represent differing values, thus creating a conflict. + * The algorithm below finds all conflicts via making a series of comparisons + * between fields. In order to compare as few fields as possible, this makes + * a series of comparisons "within" sets of fields and "between" sets of fields. + * + * Given any selection set, a collection produces both a set of fields by + * also including all inline fragments, as well as a list of fragments + * referenced by fragment spreads. + * + * A) Each selection set represented in the document first compares "within" its + * collected set of fields, finding any conflicts between every pair of + * overlapping fields. + * Note: This is the *only time* that the fields "within" a set are compared + * to each other. After this only fields "between" sets are compared. + * + * B) Also, if any fragment is referenced in a selection set, then a + * comparison is made "between" the original set of fields and the + * referenced fragment. + * + * C) Also, if multiple fragments are referenced, then comparisons + * are made "between" each referenced fragment. + * + * D) When comparing "between" a set of fields and a referenced fragment, first + * a comparison is made between each field in the original set of fields and + * each field in the referenced set of fields. + * + * E) Also, if any fragment is referenced in the referenced selection set, + * then a comparison is made "between" the original set of fields and the + * referenced fragment (recursively referring to step D). + * + * F) When comparing "between" two fragments, first a comparison is made between + * each field in the first referenced set of fields and each field in the + * second referenced set of fields. + * + * G) Also, any fragments referenced by the first must be compared to the + * second, and any fragments referenced by the second must be compared to the + * first (recursively referring to step F). + * + * H) When comparing two fields, if both have selection sets, then a comparison + * is made "between" both selection sets, first comparing the set of fields in + * the first selection set with the set of fields in the second. + * + * I) Also, if any fragment is referenced in either selection set, then a + * comparison is made "between" the other set of fields and the + * referenced fragment. + * + * J) Also, if two fragments are referenced in both selection sets, then a + * comparison is made "between" the two fragments. + * + * @internal + */ +function findConflictsWithinSelectionSet( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentType, + selectionSet, +) { + const conflicts = []; + const [fieldMap, fragmentNames] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, + ); // (A) Find find all conflicts "within" the fields of this selection set. + // Note: this is the *only place* `collectConflictsWithin` is called. + + collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, + ); + + if (fragmentNames.length !== 0) { + // (B) Then collect conflicts between these fields and those represented by + // each spread fragment name found. + for (let i = 0; i < fragmentNames.length; i++) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fieldMap, + fragmentNames[i], + ); // (C) Then compare this fragment with all other fragments found in this + // selection set to collect conflicts between fragments spread together. + // This compares each item in the list of fragment names to every other + // item in that same list (except for itself). + + for (let j = i + 1; j < fragmentNames.length; j++) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, + fragmentNames[i], + fragmentNames[j], + ); + } + } + } + + return conflicts; +} // Collect all conflicts found between a set of fields and a fragment reference +// including via spreading in any nested fragments. + +function collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fragmentName, +) { + // Memoize so the fields and fragments are not compared for conflicts more + // than once. + if ( + comparedFieldsAndFragmentPairs.has( + fieldMap, + fragmentName, + areMutuallyExclusive, + ) + ) { + return; + } + + comparedFieldsAndFragmentPairs.add( + fieldMap, + fragmentName, + areMutuallyExclusive, + ); + const fragment = context.getFragment(fragmentName); + + if (!fragment) { + return; + } + + const [fieldMap2, referencedFragmentNames] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, + ); // Do not compare a fragment's fieldMap to itself. + + if (fieldMap === fieldMap2) { + return; + } // (D) First collect any conflicts between the provided collection of fields + // and the collection of fields represented by the given fragment. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + fieldMap2, + ); // (E) Then collect any conflicts between the provided collection of fields + // and any fragment names found in the given fragment. + + for (const referencedFragmentName of referencedFragmentNames) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap, + referencedFragmentName, + ); + } +} // Collect all conflicts found between two fragments, including via spreading in +// any nested fragments. + +function collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, +) { + // No need to compare a fragment to itself. + if (fragmentName1 === fragmentName2) { + return; + } // Memoize so two fragments are not compared for conflicts more than once. + + if ( + comparedFragmentPairs.has( + fragmentName1, + fragmentName2, + areMutuallyExclusive, + ) + ) { + return; + } + + comparedFragmentPairs.add(fragmentName1, fragmentName2, areMutuallyExclusive); + const fragment1 = context.getFragment(fragmentName1); + const fragment2 = context.getFragment(fragmentName2); + + if (!fragment1 || !fragment2) { + return; + } + + const [fieldMap1, referencedFragmentNames1] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment1, + ); + const [fieldMap2, referencedFragmentNames2] = + getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment2, + ); // (F) First, collect all conflicts between these two collections of fields + // (not including any nested fragments). + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (G) Then collect conflicts between the first fragment and any nested + // fragments spread in the second fragment. + + for (const referencedFragmentName2 of referencedFragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + referencedFragmentName2, + ); + } // (G) Then collect conflicts between the second fragment and any nested + // fragments spread in the first fragment. + + for (const referencedFragmentName1 of referencedFragmentNames1) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + referencedFragmentName1, + fragmentName2, + ); + } +} // Find all conflicts found between two selection sets, including those found +// via spreading in fragments. Called when determining if conflicts exist +// between the sub-fields of two overlapping fields. + +function findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + parentType1, + selectionSet1, + parentType2, + selectionSet2, +) { + const conflicts = []; + const [fieldMap1, fragmentNames1] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType1, + selectionSet1, + ); + const [fieldMap2, fragmentNames2] = getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType2, + selectionSet2, + ); // (H) First, collect all conflicts between these two collections of field. + + collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fieldMap2, + ); // (I) Then collect conflicts between the first collection of fields and + // those referenced by each fragment name associated with the second. + + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap1, + fragmentName2, + ); + } // (I) Then collect conflicts between the second collection of fields and + // those referenced by each fragment name associated with the first. + + for (const fragmentName1 of fragmentNames1) { + collectConflictsBetweenFieldsAndFragment( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fieldMap2, + fragmentName1, + ); + } // (J) Also collect conflicts between any fragment names by the first and + // fragment names by the second. This compares each item in the first set of + // names to each item in the second set of names. + + for (const fragmentName1 of fragmentNames1) { + for (const fragmentName2 of fragmentNames2) { + collectConflictsBetweenFragments( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + fragmentName1, + fragmentName2, + ); + } + } + + return conflicts; +} // Collect all Conflicts "within" one collection of fields. + +function collectConflictsWithin( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + fieldMap, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For every response name, if there are multiple fields, they + // must be compared to find a potential conflict. + for (const [responseName, fields] of Object.entries(fieldMap)) { + // This compares every field in the list to every other field in this list + // (except to itself). If the list only has one item, nothing needs to + // be compared. + if (fields.length > 1) { + for (let i = 0; i < fields.length; i++) { + for (let j = i + 1; j < fields.length; j++) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + false, // within one collection is never mutually exclusive + responseName, + fields[i], + fields[j], + ); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Collect all Conflicts between two collections of fields. This is similar to, +// but different from the `collectConflictsWithin` function above. This check +// assumes that `collectConflictsWithin` has already been called on each +// provided collection of fields. This is true because this validator traverses +// each individual selection set. + +function collectConflictsBetween( + context, + conflicts, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + fieldMap1, + fieldMap2, +) { + // A field map is a keyed collection, where each key represents a response + // name and the value at that key is a list of all fields which provide that + // response name. For any response name which appears in both provided field + // maps, each field from the first field map must be compared to every field + // in the second field map to find potential conflicts. + for (const [responseName, fields1] of Object.entries(fieldMap1)) { + const fields2 = fieldMap2[responseName]; + + if (fields2) { + for (const field1 of fields1) { + for (const field2 of fields2) { + const conflict = findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, + ); + + if (conflict) { + conflicts.push(conflict); + } + } + } + } + } +} // Determines if there is a conflict between two particular fields, including +// comparing their sub-fields. + +function findConflict( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + parentFieldsAreMutuallyExclusive, + responseName, + field1, + field2, +) { + const [parentType1, node1, def1] = field1; + const [parentType2, node2, def2] = field2; // If it is known that two fields could not possibly apply at the same + // time, due to the parent types, then it is safe to permit them to diverge + // in aliased field or arguments used as they will not present any ambiguity + // by differing. + // It is known that two parent types could never overlap if they are + // different Object types. Interface or Union types might overlap - if not + // in the current state of the schema, then perhaps in some future version, + // thus may not safely diverge. + + const areMutuallyExclusive = + parentFieldsAreMutuallyExclusive || + (parentType1 !== parentType2 && + isObjectType(parentType1) && + isObjectType(parentType2)); + + if (!areMutuallyExclusive) { + // Two aliases must refer to the same field. + const name1 = node1.name.value; + const name2 = node2.name.value; + + if (name1 !== name2) { + return [ + [responseName, `"${name1}" and "${name2}" are different fields`], + [node1], + [node2], + ]; + } // Two field calls must have the same arguments. + + if (!sameArguments(node1, node2)) { + return [ + [responseName, 'they have differing arguments'], + [node1], + [node2], + ]; + } + } // The return type for each field. + + const type1 = def1 === null || def1 === void 0 ? void 0 : def1.type; + const type2 = def2 === null || def2 === void 0 ? void 0 : def2.type; + + if (type1 && type2 && doTypesConflict(type1, type2)) { + return [ + [ + responseName, + `they return conflicting types "${inspect(type1)}" and "${inspect( + type2, + )}"`, + ], + [node1], + [node2], + ]; + } // Collect and compare sub-fields. Use the same "visited fragment names" list + // for both collections so fields in a fragment reference are never + // compared to themselves. + + const selectionSet1 = node1.selectionSet; + const selectionSet2 = node2.selectionSet; + + if (selectionSet1 && selectionSet2) { + const conflicts = findConflictsBetweenSubSelectionSets( + context, + cachedFieldsAndFragmentNames, + comparedFieldsAndFragmentPairs, + comparedFragmentPairs, + areMutuallyExclusive, + getNamedType(type1), + selectionSet1, + getNamedType(type2), + selectionSet2, + ); + return subfieldConflicts(conflicts, responseName, node1, node2); + } +} + +function sameArguments(node1, node2) { + const args1 = node1.arguments; + const args2 = node2.arguments; + + if (args1 === undefined || args1.length === 0) { + return args2 === undefined || args2.length === 0; + } + + if (args2 === undefined || args2.length === 0) { + return false; + } + /* c8 ignore next */ + + if (args1.length !== args2.length) { + /* c8 ignore next */ + return false; + /* c8 ignore next */ + } + + const values2 = new Map(args2.map(({ name, value }) => [name.value, value])); + return args1.every((arg1) => { + const value1 = arg1.value; + const value2 = values2.get(arg1.name.value); + + if (value2 === undefined) { + return false; + } + + return stringifyValue(value1) === stringifyValue(value2); + }); +} + +function stringifyValue(value) { + return print(sortValueNode(value)); +} // Two types conflict if both types could not apply to a value simultaneously. +// Composite types are ignored as their individual field types will be compared +// later recursively. However List and Non-Null types must match. + +function doTypesConflict(type1, type2) { + if (isListType(type1)) { + return isListType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + + if (isListType(type2)) { + return true; + } + + if (isNonNullType(type1)) { + return isNonNullType(type2) + ? doTypesConflict(type1.ofType, type2.ofType) + : true; + } + + if (isNonNullType(type2)) { + return true; + } + + if (isLeafType(type1) || isLeafType(type2)) { + return type1 !== type2; + } + + return false; +} // Given a selection set, return the collection of fields (a mapping of response +// name to field nodes and definitions) as well as a list of fragment names +// referenced via fragment spreads. + +function getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + parentType, + selectionSet, +) { + const cached = cachedFieldsAndFragmentNames.get(selectionSet); + + if (cached) { + return cached; + } + + const nodeAndDefs = Object.create(null); + const fragmentNames = Object.create(null); + + _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, + ); + + const result = [nodeAndDefs, Object.keys(fragmentNames)]; + cachedFieldsAndFragmentNames.set(selectionSet, result); + return result; +} // Given a reference to a fragment, return the represented collection of fields +// as well as a list of nested fragment names referenced via fragment spreads. + +function getReferencedFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragment, +) { + // Short-circuit building a type from the node if possible. + const cached = cachedFieldsAndFragmentNames.get(fragment.selectionSet); + + if (cached) { + return cached; + } + + const fragmentType = typeFromAST(context.getSchema(), fragment.typeCondition); + return getFieldsAndFragmentNames( + context, + cachedFieldsAndFragmentNames, + fragmentType, + fragment.selectionSet, + ); +} + +function _collectFieldsAndFragmentNames( + context, + parentType, + selectionSet, + nodeAndDefs, + fragmentNames, +) { + for (const selection of selectionSet.selections) { + switch (selection.kind) { + case Kind.FIELD: { + const fieldName = selection.name.value; + let fieldDef; + + if (isObjectType(parentType) || isInterfaceType(parentType)) { + fieldDef = parentType.getFields()[fieldName]; + } + + const responseName = selection.alias + ? selection.alias.value + : fieldName; + + if (!nodeAndDefs[responseName]) { + nodeAndDefs[responseName] = []; + } + + nodeAndDefs[responseName].push([parentType, selection, fieldDef]); + break; + } + + case Kind.FRAGMENT_SPREAD: + fragmentNames[selection.name.value] = true; + break; + + case Kind.INLINE_FRAGMENT: { + const typeCondition = selection.typeCondition; + const inlineFragmentType = typeCondition + ? typeFromAST(context.getSchema(), typeCondition) + : parentType; + + _collectFieldsAndFragmentNames( + context, + inlineFragmentType, + selection.selectionSet, + nodeAndDefs, + fragmentNames, + ); + + break; + } + } + } +} // Given a series of Conflicts which occurred between two sub-fields, generate +// a single Conflict. + +function subfieldConflicts(conflicts, responseName, node1, node2) { + if (conflicts.length > 0) { + return [ + [responseName, conflicts.map(([reason]) => reason)], + [node1, ...conflicts.map(([, fields1]) => fields1).flat()], + [node2, ...conflicts.map(([, , fields2]) => fields2).flat()], + ]; + } +} +/** + * A way to keep track of pairs of things where the ordering of the pair + * matters. + * + * Provides a third argument for has/set to allow flagging the pair as + * weakly or strongly present within the collection. + * + * @internal + */ + +class OrderedPairSet { + constructor() { + this._data = new Map(); + } + + has(a, b, weaklyPresent) { + var _this$_data$get; + + const result = + (_this$_data$get = this._data.get(a)) === null || + _this$_data$get === void 0 + ? void 0 + : _this$_data$get.get(b); + + if (result === undefined) { + return false; + } + + return weaklyPresent ? true : weaklyPresent === result; + } + + add(a, b, weaklyPresent) { + const map = this._data.get(a); + + if (map === undefined) { + this._data.set(a, new Map([[b, weaklyPresent]])); + } else { + map.set(b, weaklyPresent); + } + } +} +/** + * A way to keep track of pairs of similar things when the ordering of the pair + * does not matter. + * + * @internal + */ + +class PairSet { + constructor() { + this._orderedPairSet = new OrderedPairSet(); + } + + has(a, b, weaklyPresent) { + return a < b + ? this._orderedPairSet.has(a, b, weaklyPresent) + : this._orderedPairSet.has(b, a, weaklyPresent); + } + + add(a, b, weaklyPresent) { + if (a < b) { + this._orderedPairSet.add(a, b, weaklyPresent); + } else { + this._orderedPairSet.add(b, a, weaklyPresent); + } + } +} diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..af68fe68f75bf2ca439773cbcba3c36f6461b935 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.d.ts @@ -0,0 +1,48 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { PossibleFragmentSpreadsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * barkVolume: Int + * } + * + * type Cat { + * meowVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { ... on Cat { meowVolume } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [PossibleFragmentSpreadsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { ... on Dog { barkVolume } } } + * `); + * const validErrors = validate(schema, validDocument, [PossibleFragmentSpreadsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function PossibleFragmentSpreadsRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..2afd05c301992b25b79a1d887d1cc3d368951477 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.js @@ -0,0 +1,132 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.PossibleFragmentSpreadsRule = PossibleFragmentSpreadsRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _definition = require('../../type/definition.js'); + +var _typeComparators = require('../../utilities/typeComparators.js'); + +var _typeFromAST = require('../../utilities/typeFromAST.js'); + +/** @category Validation Rules */ + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { PossibleFragmentSpreadsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * barkVolume: Int + * } + * + * type Cat { + * meowVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { ... on Cat { meowVolume } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [PossibleFragmentSpreadsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { ... on Dog { barkVolume } } } + * `); + * const validErrors = validate(schema, validDocument, [PossibleFragmentSpreadsRule]); + * + * validErrors; // => [] + * ``` + */ +function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + + if ( + (0, _definition.isCompositeType)(fragType) && + (0, _definition.isCompositeType)(parentType) && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType, + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, + + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + + if ( + fragType && + parentType && + !(0, _typeComparators.doTypesOverlap)( + context.getSchema(), + fragType, + parentType, + ) + ) { + const parentTypeStr = (0, _inspect.inspect)(parentType); + const fragTypeStr = (0, _inspect.inspect)(fragType); + context.reportError( + new _GraphQLError.GraphQLError( + `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} + +function getFragmentType(context, name) { + const frag = context.getFragment(name); + + if (frag) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + frag.typeCondition, + ); + + if ((0, _definition.isCompositeType)(type)) { + return type; + } + } +} diff --git a/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..71f0fe85f5846545b3c512cf2ad7277bf0c1a720 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleFragmentSpreadsRule.mjs @@ -0,0 +1,109 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { isCompositeType } from '../../type/definition.mjs'; +import { doTypesOverlap } from '../../utilities/typeComparators.mjs'; +import { typeFromAST } from '../../utilities/typeFromAST.mjs'; + +/** + * Possible fragment spread + * + * A fragment spread is only valid if the type condition could ever possibly + * be true: if there is a non-empty intersection of the possible parent types, + * and possible types which pass the type condition. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { PossibleFragmentSpreadsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * dog: Dog + * } + * + * type Dog { + * barkVolume: Int + * } + * + * type Cat { + * meowVolume: Int + * } + * `); + * + * const invalidDocument = parse(` + * { dog { ... on Cat { meowVolume } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [PossibleFragmentSpreadsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { dog { ... on Dog { barkVolume } } } + * `); + * const validErrors = validate(schema, validDocument, [PossibleFragmentSpreadsRule]); + * + * validErrors; // => [] + * ``` + */ +export function PossibleFragmentSpreadsRule(context) { + return { + InlineFragment(node) { + const fragType = context.getType(); + const parentType = context.getParentType(); + + if ( + isCompositeType(fragType) && + isCompositeType(parentType) && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + const parentTypeStr = inspect(parentType); + const fragTypeStr = inspect(fragType); + context.reportError( + new GraphQLError( + `Fragment cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, + + FragmentSpread(node) { + const fragName = node.name.value; + const fragType = getFragmentType(context, fragName); + const parentType = context.getParentType(); + + if ( + fragType && + parentType && + !doTypesOverlap(context.getSchema(), fragType, parentType) + ) { + const parentTypeStr = inspect(parentType); + const fragTypeStr = inspect(fragType); + context.reportError( + new GraphQLError( + `Fragment "${fragName}" cannot be spread here as objects of type "${parentTypeStr}" can never be of type "${fragTypeStr}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} + +function getFragmentType(context, name) { + const frag = context.getFragment(name); + + if (frag) { + const type = typeFromAST(context.getSchema(), frag.typeCondition); + + if (isCompositeType(type)) { + return type; + } + } +} diff --git a/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..887d0729f979a8f391b04718a66e4d76bc0a2cb5 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { PossibleTypeExtensionsRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * extend type Missing { name: String } type Query { name: String } + * `; + * + * PossibleTypeExtensionsRule.name; // => 'PossibleTypeExtensionsRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } extend type Query { other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function PossibleTypeExtensionsRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..ebadff35993d040c7ee356c93fffa2871ce9ea27 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.js @@ -0,0 +1,193 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.PossibleTypeExtensionsRule = PossibleTypeExtensionsRule; + +var _didYouMean = require('../../jsutils/didYouMean.js'); + +var _inspect = require('../../jsutils/inspect.js'); + +var _invariant = require('../../jsutils/invariant.js'); + +var _suggestionList = require('../../jsutils/suggestionList.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _predicates = require('../../language/predicates.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { PossibleTypeExtensionsRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * extend type Missing { name: String } type Query { name: String } + * `; + * + * PossibleTypeExtensionsRule.name; // => 'PossibleTypeExtensionsRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } extend type Query { other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if ((0, _predicates.isTypeDefinitionNode)(def)) { + definedTypes[def.name.value] = def; + } + } + + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension, + }; + + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = + schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + let expectedKind; + + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend non-${kindStr} type "${typeName}".`, + { + nodes: defNode ? [defNode, node] : node, + }, + ), + ); + } + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 + ? void 0 + : schema.getTypeMap()), + }); + const suggestedTypes = (0, _suggestionList.suggestionList)( + typeName, + allTypeNames, + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Cannot extend type "${typeName}" because it is not defined.` + + (0, _didYouMean.didYouMean)(suggestedTypes), + { + nodes: node.name, + }, + ), + ); + } + } +} + +const defKindToExtKind = { + [_kinds.Kind.SCALAR_TYPE_DEFINITION]: _kinds.Kind.SCALAR_TYPE_EXTENSION, + [_kinds.Kind.OBJECT_TYPE_DEFINITION]: _kinds.Kind.OBJECT_TYPE_EXTENSION, + [_kinds.Kind.INTERFACE_TYPE_DEFINITION]: _kinds.Kind.INTERFACE_TYPE_EXTENSION, + [_kinds.Kind.UNION_TYPE_DEFINITION]: _kinds.Kind.UNION_TYPE_EXTENSION, + [_kinds.Kind.ENUM_TYPE_DEFINITION]: _kinds.Kind.ENUM_TYPE_EXTENSION, + [_kinds.Kind.INPUT_OBJECT_TYPE_DEFINITION]: + _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION, +}; + +function typeToExtKind(type) { + if ((0, _definition.isScalarType)(type)) { + return _kinds.Kind.SCALAR_TYPE_EXTENSION; + } + + if ((0, _definition.isObjectType)(type)) { + return _kinds.Kind.OBJECT_TYPE_EXTENSION; + } + + if ((0, _definition.isInterfaceType)(type)) { + return _kinds.Kind.INTERFACE_TYPE_EXTENSION; + } + + if ((0, _definition.isUnionType)(type)) { + return _kinds.Kind.UNION_TYPE_EXTENSION; + } + + if ((0, _definition.isEnumType)(type)) { + return _kinds.Kind.ENUM_TYPE_EXTENSION; + } + + if ((0, _definition.isInputObjectType)(type)) { + return _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered + + false || + (0, _invariant.invariant)( + false, + 'Unexpected type: ' + (0, _inspect.inspect)(type), + ); +} + +function extensionKindToTypeName(kind) { + switch (kind) { + case _kinds.Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + + case _kinds.Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + + case _kinds.Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + + case _kinds.Kind.UNION_TYPE_EXTENSION: + return 'union'; + + case _kinds.Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + + case _kinds.Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + // Not reachable. All possible types have been considered + + /* c8 ignore next */ + + default: + false || + (0, _invariant.invariant)( + false, + 'Unexpected kind: ' + (0, _inspect.inspect)(kind), + ); + } +} diff --git a/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8703b266b7fb73a12b16084ae12b34b16168ab64 --- /dev/null +++ b/node_modules/graphql/validation/rules/PossibleTypeExtensionsRule.mjs @@ -0,0 +1,169 @@ +/** @category Validation Rules */ +import { didYouMean } from '../../jsutils/didYouMean.mjs'; +import { inspect } from '../../jsutils/inspect.mjs'; +import { invariant } from '../../jsutils/invariant.mjs'; +import { suggestionList } from '../../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { isTypeDefinitionNode } from '../../language/predicates.mjs'; +import { + isEnumType, + isInputObjectType, + isInterfaceType, + isObjectType, + isScalarType, + isUnionType, +} from '../../type/definition.mjs'; + +/** + * Possible type extension + * + * A type extension is only valid if the type is defined and has the same kind. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { PossibleTypeExtensionsRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * extend type Missing { name: String } type Query { name: String } + * `; + * + * PossibleTypeExtensionsRule.name; // => 'PossibleTypeExtensionsRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } extend type Query { other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function PossibleTypeExtensionsRule(context) { + const schema = context.getSchema(); + const definedTypes = Object.create(null); + + for (const def of context.getDocument().definitions) { + if (isTypeDefinitionNode(def)) { + definedTypes[def.name.value] = def; + } + } + + return { + ScalarTypeExtension: checkExtension, + ObjectTypeExtension: checkExtension, + InterfaceTypeExtension: checkExtension, + UnionTypeExtension: checkExtension, + EnumTypeExtension: checkExtension, + InputObjectTypeExtension: checkExtension, + }; + + function checkExtension(node) { + const typeName = node.name.value; + const defNode = definedTypes[typeName]; + const existingType = + schema === null || schema === void 0 ? void 0 : schema.getType(typeName); + let expectedKind; + + if (defNode) { + expectedKind = defKindToExtKind[defNode.kind]; + } else if (existingType) { + expectedKind = typeToExtKind(existingType); + } + + if (expectedKind) { + if (expectedKind !== node.kind) { + const kindStr = extensionKindToTypeName(node.kind); + context.reportError( + new GraphQLError(`Cannot extend non-${kindStr} type "${typeName}".`, { + nodes: defNode ? [defNode, node] : node, + }), + ); + } + } else { + const allTypeNames = Object.keys({ + ...definedTypes, + ...(schema === null || schema === void 0 + ? void 0 + : schema.getTypeMap()), + }); + const suggestedTypes = suggestionList(typeName, allTypeNames); + context.reportError( + new GraphQLError( + `Cannot extend type "${typeName}" because it is not defined.` + + didYouMean(suggestedTypes), + { + nodes: node.name, + }, + ), + ); + } + } +} +const defKindToExtKind = { + [Kind.SCALAR_TYPE_DEFINITION]: Kind.SCALAR_TYPE_EXTENSION, + [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION, + [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION, + [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION, + [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION, + [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION, +}; + +function typeToExtKind(type) { + if (isScalarType(type)) { + return Kind.SCALAR_TYPE_EXTENSION; + } + + if (isObjectType(type)) { + return Kind.OBJECT_TYPE_EXTENSION; + } + + if (isInterfaceType(type)) { + return Kind.INTERFACE_TYPE_EXTENSION; + } + + if (isUnionType(type)) { + return Kind.UNION_TYPE_EXTENSION; + } + + if (isEnumType(type)) { + return Kind.ENUM_TYPE_EXTENSION; + } + + if (isInputObjectType(type)) { + return Kind.INPUT_OBJECT_TYPE_EXTENSION; + } + /* c8 ignore next 3 */ + // Not reachable. All possible types have been considered + + false || invariant(false, 'Unexpected type: ' + inspect(type)); +} + +function extensionKindToTypeName(kind) { + switch (kind) { + case Kind.SCALAR_TYPE_EXTENSION: + return 'scalar'; + + case Kind.OBJECT_TYPE_EXTENSION: + return 'object'; + + case Kind.INTERFACE_TYPE_EXTENSION: + return 'interface'; + + case Kind.UNION_TYPE_EXTENSION: + return 'union'; + + case Kind.ENUM_TYPE_EXTENSION: + return 'enum'; + + case Kind.INPUT_OBJECT_TYPE_EXTENSION: + return 'input object'; + // Not reachable. All possible types have been considered + + /* c8 ignore next */ + + default: + false || invariant(false, 'Unexpected kind: ' + inspect(kind)); + } +} diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3102a42d3fc6caa802309dce3bcaba8b953a871 --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.d.ts @@ -0,0 +1,46 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ProvidedRequiredArgumentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(required: String!): String + * } + * `); + * + * const invalidDocument = parse(` + * { field } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ProvidedRequiredArgumentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(required: "x") } + * `); + * const validErrors = validate(schema, validDocument, [ProvidedRequiredArgumentsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function ProvidedRequiredArgumentsRule( + context: ValidationContext, +): ASTVisitor; +/** @internal */ +export declare function ProvidedRequiredArgumentsOnDirectivesRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..5068c8f9ee2f439152f2e9fc09ded74f4f560d4b --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.js @@ -0,0 +1,189 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.ProvidedRequiredArgumentsOnDirectivesRule = + ProvidedRequiredArgumentsOnDirectivesRule; +exports.ProvidedRequiredArgumentsRule = ProvidedRequiredArgumentsRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _keyMap = require('../../jsutils/keyMap.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _printer = require('../../language/printer.js'); + +var _definition = require('../../type/definition.js'); + +var _directives = require('../../type/directives.js'); + +/** @category Validation Rules */ + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ProvidedRequiredArgumentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(required: String!): String + * } + * `); + * + * const invalidDocument = parse(` + * { field } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ProvidedRequiredArgumentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(required: "x") } + * `); + * const validErrors = validate(schema, validDocument, [ProvidedRequiredArgumentsRule]); + * + * validErrors; // => [] + * ``` + */ +function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; + + const fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || + _fieldNode$arguments === void 0 + ? void 0 + : _fieldNode$arguments.map((arg) => arg.name.value), + ); + + for (const argDef of fieldDef.args) { + if ( + !providedArgs.has(argDef.name) && + (0, _definition.isRequiredArgument)(argDef) + ) { + const argTypeStr = (0, _inspect.inspect)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, + { + nodes: fieldNode, + }, + ), + ); + } + } + }, + }, + }; +} +/** @internal */ + +function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; + + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = + (_schema$getDirectives = + schema === null || schema === void 0 + ? void 0 + : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 + ? _schema$getDirectives + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = (0, _keyMap.keyMap)( + directive.args.filter(_definition.isRequiredArgument), + (arg) => arg.name, + ); + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + requiredArgsMap[def.name.value] = (0, _keyMap.keyMap)( + argNodes.filter(isRequiredArgumentNode), + (arg) => arg.name.value, + ); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); + + for (const [argName, argDef] of Object.entries(requiredArgs)) { + if (!argNodeMap.has(argName)) { + const argType = (0, _definition.isType)(argDef.type) + ? (0, _inspect.inspect)(argDef.type) + : (0, _printer.print)(argDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, + { + nodes: directiveNode, + }, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg) { + return ( + arg.type.kind === _kinds.Kind.NON_NULL_TYPE && arg.defaultValue == null + ); +} diff --git a/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..dfe636678f3ceee6440028487e55428ff5f98cc4 --- /dev/null +++ b/node_modules/graphql/validation/rules/ProvidedRequiredArgumentsRule.mjs @@ -0,0 +1,168 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { keyMap } from '../../jsutils/keyMap.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { print } from '../../language/printer.mjs'; +import { isRequiredArgument, isType } from '../../type/definition.mjs'; +import { specifiedDirectives } from '../../type/directives.mjs'; + +/** + * Provided required arguments + * + * A field or directive is only valid if all required (non-null without a + * default value) field arguments have been provided. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ProvidedRequiredArgumentsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(required: String!): String + * } + * `); + * + * const invalidDocument = parse(` + * { field } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ProvidedRequiredArgumentsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(required: "x") } + * `); + * const validErrors = validate(schema, validDocument, [ProvidedRequiredArgumentsRule]); + * + * validErrors; // => [] + * ``` + */ +export function ProvidedRequiredArgumentsRule(context) { + return { + // eslint-disable-next-line new-cap + ...ProvidedRequiredArgumentsOnDirectivesRule(context), + Field: { + // Validate on leave to allow for deeper errors to appear first. + leave(fieldNode) { + var _fieldNode$arguments; + + const fieldDef = context.getFieldDef(); + + if (!fieldDef) { + return false; + } + + const providedArgs = new Set( // FIXME: https://github.com/graphql/graphql-js/issues/2203 + /* c8 ignore next */ + (_fieldNode$arguments = fieldNode.arguments) === null || + _fieldNode$arguments === void 0 + ? void 0 + : _fieldNode$arguments.map((arg) => arg.name.value), + ); + + for (const argDef of fieldDef.args) { + if (!providedArgs.has(argDef.name) && isRequiredArgument(argDef)) { + const argTypeStr = inspect(argDef.type); + context.reportError( + new GraphQLError( + `Field "${fieldDef.name}" argument "${argDef.name}" of type "${argTypeStr}" is required, but it was not provided.`, + { + nodes: fieldNode, + }, + ), + ); + } + } + }, + }, + }; +} +/** @internal */ + +export function ProvidedRequiredArgumentsOnDirectivesRule(context) { + var _schema$getDirectives; + + const requiredArgsMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = + (_schema$getDirectives = + schema === null || schema === void 0 + ? void 0 + : schema.getDirectives()) !== null && _schema$getDirectives !== void 0 + ? _schema$getDirectives + : specifiedDirectives; + + for (const directive of definedDirectives) { + requiredArgsMap[directive.name] = keyMap( + directive.args.filter(isRequiredArgument), + (arg) => arg.name, + ); + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + var _def$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_def$arguments = def.arguments) !== null && _def$arguments !== void 0 + ? _def$arguments + : []; + requiredArgsMap[def.name.value] = keyMap( + argNodes.filter(isRequiredArgumentNode), + (arg) => arg.name.value, + ); + } + } + + return { + Directive: { + // Validate on leave to allow for deeper errors to appear first. + leave(directiveNode) { + const directiveName = directiveNode.name.value; + const requiredArgs = requiredArgsMap[directiveName]; + + if (requiredArgs) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + const argNodeMap = new Set(argNodes.map((arg) => arg.name.value)); + + for (const [argName, argDef] of Object.entries(requiredArgs)) { + if (!argNodeMap.has(argName)) { + const argType = isType(argDef.type) + ? inspect(argDef.type) + : print(argDef.type); + context.reportError( + new GraphQLError( + `Directive "@${directiveName}" argument "${argName}" of type "${argType}" is required, but it was not provided.`, + { + nodes: directiveNode, + }, + ), + ); + } + } + } + }, + }, + }; +} + +function isRequiredArgumentNode(arg) { + return arg.type.kind === Kind.NON_NULL_TYPE && arg.defaultValue == null; +} diff --git a/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts b/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..1f68059638a85283fab94c9247083d566ee64e7b --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafsRule.d.ts @@ -0,0 +1,37 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ScalarLeafsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name { length } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ScalarLeafsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ScalarLeafsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function ScalarLeafsRule(context: ValidationContext): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/ScalarLeafsRule.js b/node_modules/graphql/validation/rules/ScalarLeafsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..d801bbffdbd0d6ce9c0c57db1bd4806a2b1e2692 --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafsRule.js @@ -0,0 +1,95 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.ScalarLeafsRule = ScalarLeafsRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ScalarLeafsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name { length } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ScalarLeafsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ScalarLeafsRule]); + * + * validErrors; // => [] + * ``` + */ +function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + + if (type) { + if ((0, _definition.isLeafType)((0, _definition.getNamedType)(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, + { + nodes: selectionSet, + }, + ), + ); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, + { + nodes: node, + }, + ), + ); + } else if (selectionSet.selections.length === 0) { + const fieldName = node.name.value; + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs b/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d055613c39d8e05253fd301cac049e6d814e454c --- /dev/null +++ b/node_modules/graphql/validation/rules/ScalarLeafsRule.mjs @@ -0,0 +1,85 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { getNamedType, isLeafType } from '../../type/definition.mjs'; + +/** + * Scalar leafs + * + * A GraphQL document is valid only if all leaf fields (fields without + * sub selections) are of scalar or enum types. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ScalarLeafsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name { length } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ScalarLeafsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [ScalarLeafsRule]); + * + * validErrors; // => [] + * ``` + */ +export function ScalarLeafsRule(context) { + return { + Field(node) { + const type = context.getType(); + const selectionSet = node.selectionSet; + + if (type) { + if (isLeafType(getNamedType(type))) { + if (selectionSet) { + const fieldName = node.name.value; + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Field "${fieldName}" must not have a selection since type "${typeStr}" has no subfields.`, + { + nodes: selectionSet, + }, + ), + ); + } + } else if (!selectionSet) { + const fieldName = node.name.value; + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have a selection of subfields. Did you mean "${fieldName} { ... }"?`, + { + nodes: node, + }, + ), + ); + } else if (selectionSet.selections.length === 0) { + const fieldName = node.name.value; + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Field "${fieldName}" of type "${typeStr}" must have at least one field selected.`, + { + nodes: node, + }, + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e50f191dd56b774df305a5e83e94d01b9f2ce504 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.d.ts @@ -0,0 +1,46 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { SingleFieldSubscriptionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * + * type Subscription { + * a: String + * b: String + * } + * `); + * + * const invalidDocument = parse(` + * subscription { a b } + * `); + * const invalidErrors = validate(schema, invalidDocument, [SingleFieldSubscriptionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * subscription { a } + * `); + * const validErrors = validate(schema, validDocument, [SingleFieldSubscriptionsRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function SingleFieldSubscriptionsRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js new file mode 100644 index 0000000000000000000000000000000000000000..65fb6a83529ac0b1a19b9692a587a529714485d8 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.js @@ -0,0 +1,120 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.SingleFieldSubscriptionsRule = SingleFieldSubscriptionsRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _collectFields = require('../../execution/collectFields.js'); + +/** @category Validation Rules */ + +/** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { SingleFieldSubscriptionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * + * type Subscription { + * a: String + * b: String + * } + * `); + * + * const invalidDocument = parse(` + * subscription { a b } + * `); + * const invalidErrors = validate(schema, invalidDocument, [SingleFieldSubscriptionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * subscription { a } + * `); + * const validErrors = validate(schema, validDocument, [SingleFieldSubscriptionsRule]); + * + * validErrors; // => [] + * ``` + */ +function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === 'subscription') { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); + + for (const definition of document.definitions) { + if (definition.kind === _kinds.Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; + } + } + + const fields = (0, _collectFields.collectFields)( + schema, + fragments, + variableValues, + subscriptionType, + node.selectionSet, + ); + + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = fieldSelectionLists.slice(1); + const extraFieldSelections = extraFieldSelectionLists.flat(); + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must select only one top level field.` + : 'Anonymous Subscription must select only one top level field.', + { + nodes: extraFieldSelections, + }, + ), + ); + } + + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; + + if (fieldName.startsWith('__')) { + context.reportError( + new _GraphQLError.GraphQLError( + operationName != null + ? `Subscription "${operationName}" must not select an introspection top level field.` + : 'Anonymous Subscription must not select an introspection top level field.', + { + nodes: fieldNodes, + }, + ), + ); + } + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..9fa712d368a221d5edc9bf19cea15aebab6b0d20 --- /dev/null +++ b/node_modules/graphql/validation/rules/SingleFieldSubscriptionsRule.mjs @@ -0,0 +1,110 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { collectFields } from '../../execution/collectFields.mjs'; + +/** + * Subscriptions must only include a non-introspection field. + * + * A GraphQL subscription is valid only if it contains a single root field and + * that root field is not an introspection field. + * + * See https://spec.graphql.org/draft/#sec-Single-root-field + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { SingleFieldSubscriptionsRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * + * type Subscription { + * a: String + * b: String + * } + * `); + * + * const invalidDocument = parse(` + * subscription { a b } + * `); + * const invalidErrors = validate(schema, invalidDocument, [SingleFieldSubscriptionsRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * subscription { a } + * `); + * const validErrors = validate(schema, validDocument, [SingleFieldSubscriptionsRule]); + * + * validErrors; // => [] + * ``` + */ +export function SingleFieldSubscriptionsRule(context) { + return { + OperationDefinition(node) { + if (node.operation === 'subscription') { + const schema = context.getSchema(); + const subscriptionType = schema.getSubscriptionType(); + + if (subscriptionType) { + const operationName = node.name ? node.name.value : null; + const variableValues = Object.create(null); + const document = context.getDocument(); + const fragments = Object.create(null); + + for (const definition of document.definitions) { + if (definition.kind === Kind.FRAGMENT_DEFINITION) { + fragments[definition.name.value] = definition; + } + } + + const fields = collectFields( + schema, + fragments, + variableValues, + subscriptionType, + node.selectionSet, + ); + + if (fields.size > 1) { + const fieldSelectionLists = [...fields.values()]; + const extraFieldSelectionLists = fieldSelectionLists.slice(1); + const extraFieldSelections = extraFieldSelectionLists.flat(); + context.reportError( + new GraphQLError( + operationName != null + ? `Subscription "${operationName}" must select only one top level field.` + : 'Anonymous Subscription must select only one top level field.', + { + nodes: extraFieldSelections, + }, + ), + ); + } + + for (const fieldNodes of fields.values()) { + const field = fieldNodes[0]; + const fieldName = field.name.value; + + if (fieldName.startsWith('__')) { + context.reportError( + new GraphQLError( + operationName != null + ? `Subscription "${operationName}" must not select an introspection top level field.` + : 'Anonymous Subscription must not select an introspection top level field.', + { + nodes: fieldNodes, + }, + ), + ); + } + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c56985a92622d1ebd47b082eaeafaae5d4ca513c --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.d.ts @@ -0,0 +1,32 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueArgumentDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { field(arg: String, arg: Int): String } + * `; + * + * UniqueArgumentDefinitionNamesRule.name; // => 'UniqueArgumentDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { field(arg: String): String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueArgumentDefinitionNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.js b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..f7a3c3faa02316f3d07ed97e6ebf4b6c1ce32b89 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.js @@ -0,0 +1,114 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueArgumentDefinitionNamesRule = UniqueArgumentDefinitionNamesRule; + +var _groupBy = require('../../jsutils/groupBy.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueArgumentDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { field(arg: String, arg: Int): String } + * `; + * + * UniqueArgumentDefinitionNamesRule.name; // => 'UniqueArgumentDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { field(arg: String): String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField, + }; + + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; + + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_typeNode$fields = typeNode.fields) !== null && + _typeNode$fields !== void 0 + ? _typeNode$fields + : []; + + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; + + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_fieldDef$arguments = fieldDef.arguments) !== null && + _fieldDef$arguments !== void 0 + ? _fieldDef$arguments + : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } + + return false; + } + + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value, + ); + + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `Argument "${parentName}(${argName}:)" can only be defined once.`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..03df6112736944e8b0feeb6bee49e62bd8f1d051 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentDefinitionNamesRule.mjs @@ -0,0 +1,102 @@ +/** @category Validation Rules */ +import { groupBy } from '../../jsutils/groupBy.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique argument definition names + * + * A GraphQL Object or Interface type is only valid if all its fields have uniquely named arguments. + * A GraphQL Directive is only valid if all its arguments are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueArgumentDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { field(arg: String, arg: Int): String } + * `; + * + * UniqueArgumentDefinitionNamesRule.name; // => 'UniqueArgumentDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { field(arg: String): String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueArgumentDefinitionNamesRule(context) { + return { + DirectiveDefinition(directiveNode) { + var _directiveNode$argume; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_directiveNode$argume = directiveNode.arguments) !== null && + _directiveNode$argume !== void 0 + ? _directiveNode$argume + : []; + return checkArgUniqueness(`@${directiveNode.name.value}`, argumentNodes); + }, + + InterfaceTypeDefinition: checkArgUniquenessPerField, + InterfaceTypeExtension: checkArgUniquenessPerField, + ObjectTypeDefinition: checkArgUniquenessPerField, + ObjectTypeExtension: checkArgUniquenessPerField, + }; + + function checkArgUniquenessPerField(typeNode) { + var _typeNode$fields; + + const typeName = typeNode.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_typeNode$fields = typeNode.fields) !== null && + _typeNode$fields !== void 0 + ? _typeNode$fields + : []; + + for (const fieldDef of fieldNodes) { + var _fieldDef$arguments; + + const fieldName = fieldDef.name.value; // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const argumentNodes = + (_fieldDef$arguments = fieldDef.arguments) !== null && + _fieldDef$arguments !== void 0 + ? _fieldDef$arguments + : []; + checkArgUniqueness(`${typeName}.${fieldName}`, argumentNodes); + } + + return false; + } + + function checkArgUniqueness(parentName, argumentNodes) { + const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value); + + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new GraphQLError( + `Argument "${parentName}(${argName}:)" can only be defined once.`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dbe336de9b8a73ad97e2dee907aa11901e6dec8a --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(arg: "1", arg: "2") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [UniqueArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueArgumentNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..56dae174f3f3f3312f76e8203ac1f6aa9249f44b --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.js @@ -0,0 +1,84 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueArgumentNamesRule = UniqueArgumentNamesRule; + +var _groupBy = require('../../jsutils/groupBy.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(arg: "1", arg: "2") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [UniqueArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness, + }; + + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_parentNode$arguments = parentNode.arguments) !== null && + _parentNode$arguments !== void 0 + ? _parentNode$arguments + : []; + const seenArgs = (0, _groupBy.groupBy)( + argumentNodes, + (arg) => arg.name.value, + ); + + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one argument named "${argName}".`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + } +} diff --git a/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..44159ffb77965607976341a6d333f65f8f897ff2 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueArgumentNamesRule.mjs @@ -0,0 +1,72 @@ +/** @category Validation Rules */ +import { groupBy } from '../../jsutils/groupBy.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique argument names + * + * A GraphQL field or directive is only valid if all supplied arguments are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Argument-Names + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueArgumentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: String): String + * } + * `); + * + * const invalidDocument = parse(` + * { field(arg: "1", arg: "2") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueArgumentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { field(arg: "1") } + * `); + * const validErrors = validate(schema, validDocument, [UniqueArgumentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueArgumentNamesRule(context) { + return { + Field: checkArgUniqueness, + Directive: checkArgUniqueness, + }; + + function checkArgUniqueness(parentNode) { + var _parentNode$arguments; + + // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const argumentNodes = + (_parentNode$arguments = parentNode.arguments) !== null && + _parentNode$arguments !== void 0 + ? _parentNode$arguments + : []; + const seenArgs = groupBy(argumentNodes, (arg) => arg.name.value); + + for (const [argName, argNodes] of seenArgs) { + if (argNodes.length > 1) { + context.reportError( + new GraphQLError( + `There can be only one argument named "${argName}".`, + { + nodes: argNodes.map((node) => node.name), + }, + ), + ); + } + } + } +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..62769ee0d5e383d9ddc0402d926c10dace55ec3e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueDirectiveNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * directive @tag on FIELD directive @tag on QUERY type Query { name: String } + * `; + * + * UniqueDirectiveNamesRule.name; // => 'UniqueDirectiveNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * directive @tag on FIELD type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueDirectiveNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..7976194525ba2821d249393d37240ea1b4c5e471 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.js @@ -0,0 +1,76 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueDirectiveNamesRule = UniqueDirectiveNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueDirectiveNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * directive @tag on FIELD directive @tag on QUERY type Query { name: String } + * `; + * + * UniqueDirectiveNamesRule.name; // => 'UniqueDirectiveNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * directive @tag on FIELD type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + + if ( + schema !== null && + schema !== void 0 && + schema.getDirective(directiveName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, + { + nodes: node.name, + }, + ), + ); + return; + } + + if (knownDirectiveNames[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one directive named "@${directiveName}".`, + { + nodes: [knownDirectiveNames[directiveName], node.name], + }, + ), + ); + } else { + knownDirectiveNames[directiveName] = node.name; + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..4ea4b748c56daf978772f02ee9b2ecb50799c9d3 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectiveNamesRule.mjs @@ -0,0 +1,68 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique directive names + * + * A GraphQL document is only valid if all defined directives have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueDirectiveNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * directive @tag on FIELD directive @tag on QUERY type Query { name: String } + * `; + * + * UniqueDirectiveNamesRule.name; // => 'UniqueDirectiveNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * directive @tag on FIELD type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueDirectiveNamesRule(context) { + const knownDirectiveNames = Object.create(null); + const schema = context.getSchema(); + return { + DirectiveDefinition(node) { + const directiveName = node.name.value; + + if ( + schema !== null && + schema !== void 0 && + schema.getDirective(directiveName) + ) { + context.reportError( + new GraphQLError( + `Directive "@${directiveName}" already exists in the schema. It cannot be redefined.`, + { + nodes: node.name, + }, + ), + ); + return; + } + + if (knownDirectiveNames[directiveName]) { + context.reportError( + new GraphQLError( + `There can be only one directive named "@${directiveName}".`, + { + nodes: [knownDirectiveNames[directiveName], node.name], + }, + ), + ); + } else { + knownDirectiveNames[directiveName] = node.name; + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..6a027b059663f6f46c39852626b8b5dc2c508b73 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.d.ts @@ -0,0 +1,44 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { + SDLValidationContext, + ValidationContext, +} from '../ValidationContext'; +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueDirectivesPerLocationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @include(if: true) @include(if: false) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueDirectivesPerLocationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueDirectivesPerLocationRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueDirectivesPerLocationRule( + context: ValidationContext | SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js new file mode 100644 index 0000000000000000000000000000000000000000..b8d7461c0eaa28f1a93c4486a2372afe08b1597e --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.js @@ -0,0 +1,136 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueDirectivesPerLocationRule = UniqueDirectivesPerLocationRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _predicates = require('../../language/predicates.js'); + +var _directives = require('../../type/directives.js'); + +/** @category Validation Rules */ + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueDirectivesPerLocationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @include(if: true) @include(if: false) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueDirectivesPerLocationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueDirectivesPerLocationRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : _directives.specifiedDirectives; + + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === _kinds.Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + const directiveDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!('directives' in node) || !node.directives) { + return; + } + + let seenDirectives; + + if ( + node.kind === _kinds.Kind.SCHEMA_DEFINITION || + node.kind === _kinds.Kind.SCHEMA_EXTENSION + ) { + seenDirectives = schemaDirectives; + } else if ( + (0, _predicates.isTypeDefinitionNode)(node) || + (0, _predicates.isTypeExtensionNode)(node) + ) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else if ( + node.kind === _kinds.Kind.DIRECTIVE_DEFINITION || + node.kind === _kinds.Kind.DIRECTIVE_EXTENSION + ) { + const directiveName = node.name.value; + seenDirectives = directiveDirectivesMap[directiveName]; + + if (seenDirectives === undefined) { + directiveDirectivesMap[directiveName] = seenDirectives = + Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (const directive of node.directives) { + const directiveName = directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `The directive "@${directiveName}" can only be used once at this location.`, + { + nodes: [seenDirectives[directiveName], directive], + }, + ), + ); + } else { + seenDirectives[directiveName] = directive; + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bb1f4b141d05b54b3ec04fe33bd73cabb83ad7dd --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueDirectivesPerLocationRule.mjs @@ -0,0 +1,125 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { + isTypeDefinitionNode, + isTypeExtensionNode, +} from '../../language/predicates.mjs'; +import { specifiedDirectives } from '../../type/directives.mjs'; + +/** + * Unique directive names per location + * + * A GraphQL document is only valid if all non-repeatable directives at + * a given location are uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Directives-Are-Unique-Per-Location + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueDirectivesPerLocationRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { name @include(if: true) @include(if: false) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueDirectivesPerLocationRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name @include(if: true) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueDirectivesPerLocationRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueDirectivesPerLocationRule(context) { + const uniqueDirectiveMap = Object.create(null); + const schema = context.getSchema(); + const definedDirectives = schema + ? schema.getDirectives() + : specifiedDirectives; + + for (const directive of definedDirectives) { + uniqueDirectiveMap[directive.name] = !directive.isRepeatable; + } + + const astDefinitions = context.getDocument().definitions; + + for (const def of astDefinitions) { + if (def.kind === Kind.DIRECTIVE_DEFINITION) { + uniqueDirectiveMap[def.name.value] = !def.repeatable; + } + } + + const schemaDirectives = Object.create(null); + const typeDirectivesMap = Object.create(null); + const directiveDirectivesMap = Object.create(null); + return { + // Many different AST nodes may contain directives. Rather than listing + // them all, just listen for entering any node, and check to see if it + // defines any directives. + enter(node) { + if (!('directives' in node) || !node.directives) { + return; + } + + let seenDirectives; + + if ( + node.kind === Kind.SCHEMA_DEFINITION || + node.kind === Kind.SCHEMA_EXTENSION + ) { + seenDirectives = schemaDirectives; + } else if (isTypeDefinitionNode(node) || isTypeExtensionNode(node)) { + const typeName = node.name.value; + seenDirectives = typeDirectivesMap[typeName]; + + if (seenDirectives === undefined) { + typeDirectivesMap[typeName] = seenDirectives = Object.create(null); + } + } else if ( + node.kind === Kind.DIRECTIVE_DEFINITION || + node.kind === Kind.DIRECTIVE_EXTENSION + ) { + const directiveName = node.name.value; + seenDirectives = directiveDirectivesMap[directiveName]; + + if (seenDirectives === undefined) { + directiveDirectivesMap[directiveName] = seenDirectives = + Object.create(null); + } + } else { + seenDirectives = Object.create(null); + } + + for (const directive of node.directives) { + const directiveName = directive.name.value; + + if (uniqueDirectiveMap[directiveName]) { + if (seenDirectives[directiveName]) { + context.reportError( + new GraphQLError( + `The directive "@${directiveName}" can only be used once at this location.`, + { + nodes: [seenDirectives[directiveName], directive], + }, + ), + ); + } else { + seenDirectives[directiveName] = directive; + } + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ec29cf7facaf068d570e8a5be6704fcde4e49a74 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueEnumValueNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * enum Status { ACTIVE ACTIVE } type Query { status: Status } + * `; + * + * UniqueEnumValueNamesRule.name; // => 'UniqueEnumValueNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * enum Status { ACTIVE INACTIVE } type Query { status: Status } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueEnumValueNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..247e0abbde1320cf3a15d0b9cac3052477b1bb84 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.js @@ -0,0 +1,97 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueEnumValueNamesRule = UniqueEnumValueNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueEnumValueNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * enum Status { ACTIVE ACTIVE } type Query { status: Status } + * `; + * + * UniqueEnumValueNamesRule.name; // => 'UniqueEnumValueNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * enum Status { ACTIVE INACTIVE } type Query { status: Status } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness, + }; + + function checkValueUniqueness(node) { + var _node$values; + + const typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + const valueNames = knownValueNames[typeName]; + + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + + if ( + (0, _definition.isEnumType)(existingType) && + existingType.getValue(valueName) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: valueDef.name, + }, + ), + ); + } else if (valueNames[valueName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Enum value "${typeName}.${valueName}" can only be defined once.`, + { + nodes: [valueNames[valueName], valueDef.name], + }, + ), + ); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..09d02748317eb81fdd6cfc3fa6c7f604fa8acc76 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueEnumValueNamesRule.mjs @@ -0,0 +1,85 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { isEnumType } from '../../type/definition.mjs'; + +/** + * Unique enum value names + * + * A GraphQL enum type is only valid if all its values are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueEnumValueNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * enum Status { ACTIVE ACTIVE } type Query { status: Status } + * `; + * + * UniqueEnumValueNamesRule.name; // => 'UniqueEnumValueNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * enum Status { ACTIVE INACTIVE } type Query { status: Status } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueEnumValueNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownValueNames = Object.create(null); + return { + EnumTypeDefinition: checkValueUniqueness, + EnumTypeExtension: checkValueUniqueness, + }; + + function checkValueUniqueness(node) { + var _node$values; + + const typeName = node.name.value; + + if (!knownValueNames[typeName]) { + knownValueNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const valueNodes = + (_node$values = node.values) !== null && _node$values !== void 0 + ? _node$values + : []; + const valueNames = knownValueNames[typeName]; + + for (const valueDef of valueNodes) { + const valueName = valueDef.name.value; + const existingType = existingTypeMap[typeName]; + + if (isEnumType(existingType) && existingType.getValue(valueName)) { + context.reportError( + new GraphQLError( + `Enum value "${typeName}.${valueName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: valueDef.name, + }, + ), + ); + } else if (valueNames[valueName]) { + context.reportError( + new GraphQLError( + `Enum value "${typeName}.${valueName}" can only be defined once.`, + { + nodes: [valueNames[valueName], valueDef.name], + }, + ), + ); + } else { + valueNames[valueName] = valueDef.name; + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8118da9b4a3ea719bc54910314423252412eaf14 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String name: String } + * `; + * + * UniqueFieldDefinitionNamesRule.name; // => 'UniqueFieldDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueFieldDefinitionNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..0800d7256a3976821e7262fc3499c8b505cee6f2 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.js @@ -0,0 +1,109 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueFieldDefinitionNamesRule = UniqueFieldDefinitionNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String name: String } + * `; + * + * UniqueFieldDefinitionNamesRule.name; // => 'UniqueFieldDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness, + }; + + function checkFieldUniqueness(node) { + var _node$fields; + + const typeName = node.name.value; + + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + const fieldNames = knownFieldNames[typeName]; + + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: fieldDef.name, + }, + ), + ); + } else if (fieldNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${typeName}.${fieldName}" can only be defined once.`, + { + nodes: [fieldNames[fieldName], fieldDef.name], + }, + ), + ); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type, fieldName) { + if ( + (0, _definition.isObjectType)(type) || + (0, _definition.isInterfaceType)(type) || + (0, _definition.isInputObjectType)(type) + ) { + return type.getFields()[fieldName] != null; + } + + return false; +} diff --git a/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d82e28e564c74b769dedc9aebfe6cb2583af569 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFieldDefinitionNamesRule.mjs @@ -0,0 +1,100 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { + isInputObjectType, + isInterfaceType, + isObjectType, +} from '../../type/definition.mjs'; + +/** + * Unique field definition names + * + * A GraphQL complex type is only valid if all its fields are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueFieldDefinitionNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String name: String } + * `; + * + * UniqueFieldDefinitionNamesRule.name; // => 'UniqueFieldDefinitionNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String other: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueFieldDefinitionNamesRule(context) { + const schema = context.getSchema(); + const existingTypeMap = schema ? schema.getTypeMap() : Object.create(null); + const knownFieldNames = Object.create(null); + return { + InputObjectTypeDefinition: checkFieldUniqueness, + InputObjectTypeExtension: checkFieldUniqueness, + InterfaceTypeDefinition: checkFieldUniqueness, + InterfaceTypeExtension: checkFieldUniqueness, + ObjectTypeDefinition: checkFieldUniqueness, + ObjectTypeExtension: checkFieldUniqueness, + }; + + function checkFieldUniqueness(node) { + var _node$fields; + + const typeName = node.name.value; + + if (!knownFieldNames[typeName]) { + knownFieldNames[typeName] = Object.create(null); + } // FIXME: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + + const fieldNodes = + (_node$fields = node.fields) !== null && _node$fields !== void 0 + ? _node$fields + : []; + const fieldNames = knownFieldNames[typeName]; + + for (const fieldDef of fieldNodes) { + const fieldName = fieldDef.name.value; + + if (hasField(existingTypeMap[typeName], fieldName)) { + context.reportError( + new GraphQLError( + `Field "${typeName}.${fieldName}" already exists in the schema. It cannot also be defined in this type extension.`, + { + nodes: fieldDef.name, + }, + ), + ); + } else if (fieldNames[fieldName]) { + context.reportError( + new GraphQLError( + `Field "${typeName}.${fieldName}" can only be defined once.`, + { + nodes: [fieldNames[fieldName], fieldDef.name], + }, + ), + ); + } else { + fieldNames[fieldName] = fieldDef.name; + } + } + + return false; + } +} + +function hasField(type, fieldName) { + if (isObjectType(type) || isInterfaceType(type) || isInputObjectType(type)) { + return type.getFields()[fieldName] != null; + } + + return false; +} diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ee5f96953077905f4179529f44996e003138ae0d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.d.ts @@ -0,0 +1,40 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { name } fragment A on Query { name } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [UniqueFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueFragmentNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..a78be9031d4641f59d75db3804ebf8164f5d3aa4 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueFragmentNamesRule = UniqueFragmentNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { name } fragment A on Query { name } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [UniqueFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + + FragmentDefinition(node) { + const fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one fragment named "${fragmentName}".`, + { + nodes: [knownFragmentNames[fragmentName], node.name], + }, + ), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..f899fc4ebf25d6d56b72c1d7a8638acb4684dd39 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueFragmentNamesRule.mjs @@ -0,0 +1,62 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique fragment names + * + * A GraphQL document is only valid if all defined fragments have unique names. + * + * See https://spec.graphql.org/draft/#sec-Fragment-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueFragmentNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * fragment A on Query { name } fragment A on Query { name } query { ...A } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueFragmentNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * fragment A on Query { name } query { ...A } + * `); + * const validErrors = validate(schema, validDocument, [UniqueFragmentNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueFragmentNamesRule(context) { + const knownFragmentNames = Object.create(null); + return { + OperationDefinition: () => false, + + FragmentDefinition(node) { + const fragmentName = node.name.value; + + if (knownFragmentNames[fragmentName]) { + context.reportError( + new GraphQLError( + `There can be only one fragment named "${fragmentName}".`, + { + nodes: [knownFragmentNames[fragmentName], node.name], + }, + ), + ); + } else { + knownFragmentNames[fragmentName] = node.name; + } + + return false; + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a16ee51772db8c544214b2b97205014e194d0e37 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.d.ts @@ -0,0 +1,45 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueInputFieldNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input Filter { + * name: String + * } + * + * type Query { + * search(filter: Filter): String + * } + * `); + * + * const invalidDocument = parse(` + * { search(filter: { name: "a", name: "b" }) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueInputFieldNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { search(filter: { name: "a" }) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueInputFieldNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueInputFieldNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..c04f8b65a02cc56bca644a7b6887de9ec3a0e79f --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.js @@ -0,0 +1,87 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueInputFieldNamesRule = UniqueInputFieldNamesRule; + +var _invariant = require('../../jsutils/invariant.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueInputFieldNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input Filter { + * name: String + * } + * + * type Query { + * search(filter: Filter): String + * } + * `); + * + * const invalidDocument = parse(` + * { search(filter: { name: "a", name: "b" }) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueInputFieldNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { search(filter: { name: "a" }) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueInputFieldNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || (0, _invariant.invariant)(false); + knownNames = prevKnownNames; + }, + }, + + ObjectField(node) { + const fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one input field named "${fieldName}".`, + { + nodes: [knownNames[fieldName], node.name], + }, + ), + ); + } else { + knownNames[fieldName] = node.name; + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5bddb3906ac7c83692cbe86146e9b964b2025f4d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueInputFieldNamesRule.mjs @@ -0,0 +1,78 @@ +/** @category Validation Rules */ +import { invariant } from '../../jsutils/invariant.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique input field names + * + * A GraphQL input object value is only valid if all supplied fields are + * uniquely named. + * + * See https://spec.graphql.org/draft/#sec-Input-Object-Field-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueInputFieldNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * input Filter { + * name: String + * } + * + * type Query { + * search(filter: Filter): String + * } + * `); + * + * const invalidDocument = parse(` + * { search(filter: { name: "a", name: "b" }) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueInputFieldNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { search(filter: { name: "a" }) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueInputFieldNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueInputFieldNamesRule(context) { + const knownNameStack = []; + let knownNames = Object.create(null); + return { + ObjectValue: { + enter() { + knownNameStack.push(knownNames); + knownNames = Object.create(null); + }, + + leave() { + const prevKnownNames = knownNameStack.pop(); + prevKnownNames || invariant(false); + knownNames = prevKnownNames; + }, + }, + + ObjectField(node) { + const fieldName = node.name.value; + + if (knownNames[fieldName]) { + context.reportError( + new GraphQLError( + `There can be only one input field named "${fieldName}".`, + { + nodes: [knownNames[fieldName], node.name], + }, + ), + ); + } else { + knownNames[fieldName] = node.name; + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2f09c49b294f2ec0a9c7dd4498ae87a041d09610 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.d.ts @@ -0,0 +1,40 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueOperationNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query Same { name } query Same { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueOperationNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query One { name } query Two { name } + * `); + * const validErrors = validate(schema, validDocument, [UniqueOperationNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueOperationNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..1adba4b3c1790e7c57b7bafc456e5a608c68e7ce --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.js @@ -0,0 +1,75 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueOperationNamesRule = UniqueOperationNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueOperationNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query Same { name } query Same { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueOperationNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query One { name } query Two { name } + * `); + * const validErrors = validate(schema, validDocument, [UniqueOperationNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one operation named "${operationName.value}".`, + { + nodes: [ + knownOperationNames[operationName.value], + operationName, + ], + }, + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + + FragmentDefinition: () => false, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..420b3f46874da6d4ede80450262ba9c3db2519d4 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationNamesRule.mjs @@ -0,0 +1,67 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique operation names + * + * A GraphQL document is only valid if all defined operations have unique names. + * + * See https://spec.graphql.org/draft/#sec-Operation-Name-Uniqueness + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueOperationNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query Same { name } query Same { name } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueOperationNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query One { name } query Two { name } + * `); + * const validErrors = validate(schema, validDocument, [UniqueOperationNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueOperationNamesRule(context) { + const knownOperationNames = Object.create(null); + return { + OperationDefinition(node) { + const operationName = node.name; + + if (operationName) { + if (knownOperationNames[operationName.value]) { + context.reportError( + new GraphQLError( + `There can be only one operation named "${operationName.value}".`, + { + nodes: [ + knownOperationNames[operationName.value], + operationName, + ], + }, + ), + ); + } else { + knownOperationNames[operationName.value] = operationName; + } + } + + return false; + }, + + FragmentDefinition: () => false, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d1c5b7a7533f5c00fc2be1044fda4032a144db62 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueOperationTypesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query query: Other } type Query { name: String } type Other { name: String } + * `; + * + * UniqueOperationTypesRule.name; // => 'UniqueOperationTypesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueOperationTypesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..470f8e8f8185eef7ae13b923fdbc73bafa9a55c1 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.js @@ -0,0 +1,93 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueOperationTypesRule = UniqueOperationTypesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueOperationTypesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query query: Other } type Query { name: String } type Other { name: String } + * `; + * + * UniqueOperationTypesRule.name; // => 'UniqueOperationTypesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema + ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType(), + } + : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes, + }; + + function checkOperationTypes(node) { + var _node$operationTypes; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const operationTypesNodes = + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; + + if (existingOperationTypes[operation]) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type for ${operation} already defined in the schema. It cannot be redefined.`, + { + nodes: operationType, + }, + ), + ); + } else if (alreadyDefinedOperationType) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one ${operation} type in schema.`, + { + nodes: [alreadyDefinedOperationType, operationType], + }, + ), + ); + } else { + definedOperationTypes[operation] = operationType; + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..754c8862d53e3cf35e668bc876ade1aeca26c21d --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueOperationTypesRule.mjs @@ -0,0 +1,85 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique operation types + * + * A GraphQL document is only valid if it has only one type per operation. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueOperationTypesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * schema { query: Query query: Other } type Query { name: String } type Other { name: String } + * `; + * + * UniqueOperationTypesRule.name; // => 'UniqueOperationTypesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * schema { query: Query } type Query { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueOperationTypesRule(context) { + const schema = context.getSchema(); + const definedOperationTypes = Object.create(null); + const existingOperationTypes = schema + ? { + query: schema.getQueryType(), + mutation: schema.getMutationType(), + subscription: schema.getSubscriptionType(), + } + : {}; + return { + SchemaDefinition: checkOperationTypes, + SchemaExtension: checkOperationTypes, + }; + + function checkOperationTypes(node) { + var _node$operationTypes; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const operationTypesNodes = + (_node$operationTypes = node.operationTypes) !== null && + _node$operationTypes !== void 0 + ? _node$operationTypes + : []; + + for (const operationType of operationTypesNodes) { + const operation = operationType.operation; + const alreadyDefinedOperationType = definedOperationTypes[operation]; + + if (existingOperationTypes[operation]) { + context.reportError( + new GraphQLError( + `Type for ${operation} already defined in the schema. It cannot be redefined.`, + { + nodes: operationType, + }, + ), + ); + } else if (alreadyDefinedOperationType) { + context.reportError( + new GraphQLError( + `There can be only one ${operation} type in schema.`, + { + nodes: [alreadyDefinedOperationType, operationType], + }, + ), + ); + } else { + definedOperationTypes[operation] = operationType; + } + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a5ca5f0f348707753ab1c19a1329c67e37d1f29 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.d.ts @@ -0,0 +1,31 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { SDLValidationContext } from '../ValidationContext'; +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueTypeNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String } type Query { other: String } + * `; + * + * UniqueTypeNamesRule.name; // => 'UniqueTypeNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } type Other { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export declare function UniqueTypeNamesRule( + context: SDLValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..a1f918ee2af7ffaa7b4f3b747d58d325cc00e593 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueTypeNamesRule = UniqueTypeNamesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueTypeNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String } type Query { other: String } + * `; + * + * UniqueTypeNamesRule.name; // => 'UniqueTypeNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } type Other { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName, + }; + + function checkTypeName(node) { + const typeName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, + { + nodes: node.name, + }, + ), + ); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one type named "${typeName}".`, + { + nodes: [knownTypeNames[typeName], node.name], + }, + ), + ); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..feda609d0fd1d347b560cfad09713c1269a90a17 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueTypeNamesRule.mjs @@ -0,0 +1,68 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique type names + * + * A GraphQL document is only valid if all defined types have unique names. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema } from 'graphql'; + * import { UniqueTypeNamesRule } from 'graphql/validation'; + * + * const invalidSDL = ` + * type Query { name: String } type Query { other: String } + * `; + * + * UniqueTypeNamesRule.name; // => 'UniqueTypeNamesRule' + * buildSchema(invalidSDL); // throws an error + * + * const validSDL = ` + * type Query { name: String } type Other { name: String } + * `; + * + * buildSchema(validSDL); // does not throw + * ``` + */ +export function UniqueTypeNamesRule(context) { + const knownTypeNames = Object.create(null); + const schema = context.getSchema(); + return { + ScalarTypeDefinition: checkTypeName, + ObjectTypeDefinition: checkTypeName, + InterfaceTypeDefinition: checkTypeName, + UnionTypeDefinition: checkTypeName, + EnumTypeDefinition: checkTypeName, + InputObjectTypeDefinition: checkTypeName, + }; + + function checkTypeName(node) { + const typeName = node.name.value; + + if (schema !== null && schema !== void 0 && schema.getType(typeName)) { + context.reportError( + new GraphQLError( + `Type "${typeName}" already exists in the schema. It cannot also be defined in this type definition.`, + { + nodes: node.name, + }, + ), + ); + return; + } + + if (knownTypeNames[typeName]) { + context.reportError( + new GraphQLError(`There can be only one type named "${typeName}".`, { + nodes: [knownTypeNames[typeName], node.name], + }), + ); + } else { + knownTypeNames[typeName] = node.name; + } + + return false; + } +} diff --git a/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3bd9a834ce3e84ec1b8ba4a03e2a377a06140e43 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.d.ts @@ -0,0 +1,38 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ASTValidationContext } from '../ValidationContext'; +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueVariableNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID, $id: ID) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueVariableNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueVariableNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function UniqueVariableNamesRule( + context: ASTValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..6ff856cb0d707200c92b3ef50c92105026ccdec1 --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.js @@ -0,0 +1,78 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.UniqueVariableNamesRule = UniqueVariableNamesRule; + +var _groupBy = require('../../jsutils/groupBy.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +/** @category Validation Rules */ + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueVariableNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID, $id: ID) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueVariableNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueVariableNamesRule]); + * + * validErrors; // => [] + * ``` + */ +function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = + (_operationNode$variab = operationNode.variableDefinitions) !== null && + _operationNode$variab !== void 0 + ? _operationNode$variab + : []; + const seenVariableDefinitions = (0, _groupBy.groupBy)( + variableDefinitions, + (node) => node.variable.name.value, + ); + + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError( + new _GraphQLError.GraphQLError( + `There can be only one variable named "$${variableName}".`, + { + nodes: variableNodes.map((node) => node.variable.name), + }, + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..63591d7d5c7ddc1d2c020e7c50d5f2fd613ef91a --- /dev/null +++ b/node_modules/graphql/validation/rules/UniqueVariableNamesRule.mjs @@ -0,0 +1,69 @@ +/** @category Validation Rules */ +import { groupBy } from '../../jsutils/groupBy.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; + +/** + * Unique variable names + * + * A GraphQL operation is only valid if all its variables are uniquely named. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { UniqueVariableNamesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: ID, $id: ID) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [UniqueVariableNamesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [UniqueVariableNamesRule]); + * + * validErrors; // => [] + * ``` + */ +export function UniqueVariableNamesRule(context) { + return { + OperationDefinition(operationNode) { + var _operationNode$variab; + + // See: https://github.com/graphql/graphql-js/issues/2203 + + /* c8 ignore next */ + const variableDefinitions = + (_operationNode$variab = operationNode.variableDefinitions) !== null && + _operationNode$variab !== void 0 + ? _operationNode$variab + : []; + const seenVariableDefinitions = groupBy( + variableDefinitions, + (node) => node.variable.name.value, + ); + + for (const [variableName, variableNodes] of seenVariableDefinitions) { + if (variableNodes.length > 1) { + context.reportError( + new GraphQLError( + `There can be only one variable named "$${variableName}".`, + { + nodes: variableNodes.map((node) => node.variable.name), + }, + ), + ); + } + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea1865ea05315a160d209136ff65857122dc8660 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.d.ts @@ -0,0 +1,41 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ValuesOfCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * count(limit: Int): Int + * } + * `); + * + * const invalidDocument = parse(` + * { count(limit: "many") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ValuesOfCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { count(limit: 1) } + * `); + * const validErrors = validate(schema, validDocument, [ValuesOfCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function ValuesOfCorrectTypeRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js new file mode 100644 index 0000000000000000000000000000000000000000..18630b8bada55a1824f2b4f350f372e60b6c3ba4 --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.js @@ -0,0 +1,271 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.ValuesOfCorrectTypeRule = ValuesOfCorrectTypeRule; + +var _didYouMean = require('../../jsutils/didYouMean.js'); + +var _inspect = require('../../jsutils/inspect.js'); + +var _keyMap = require('../../jsutils/keyMap.js'); + +var _suggestionList = require('../../jsutils/suggestionList.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _printer = require('../../language/printer.js'); + +var _definition = require('../../type/definition.js'); + +/** @category Validation Rules */ + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ValuesOfCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * count(limit: Int): Int + * } + * `); + * + * const invalidDocument = parse(` + * { count(limit: "many") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ValuesOfCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { count(limit: 1) } + * `); + * const validErrors = validate(schema, validDocument, [ValuesOfCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +function ValuesOfCorrectTypeRule(context) { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = (0, _definition.getNullableType)( + context.getParentInputType(), + ); + + if (!(0, _definition.isListType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + + ObjectValue(node) { + const type = (0, _definition.getNamedType)(context.getInputType()); + + if (!(0, _definition.isInputObjectType)(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + const fieldNodeMap = (0, _keyMap.keyMap)( + node.fields, + (field) => field.name.value, + ); + + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + + if (!fieldNode && (0, _definition.isRequiredInputField)(fieldDef)) { + const typeStr = (0, _inspect.inspect)(fieldDef.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, + { + nodes: node, + }, + ), + ); + } + } + + if (type.isOneOf) { + validateOneOfInputObject(context, node, type, fieldNodeMap); + } + }, + + ObjectField(node) { + const parentType = (0, _definition.getNamedType)( + context.getParentInputType(), + ); + const fieldType = context.getInputType(); + + if (!fieldType && (0, _definition.isInputObjectType)(parentType)) { + const suggestions = (0, _suggestionList.suggestionList)( + node.name.value, + Object.keys(parentType.getFields()), + ); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${node.name.value}" is not defined by type "${parentType.name}".` + + (0, _didYouMean.didYouMean)(suggestions), + { + nodes: node, + }, + ), + ); + } + }, + + NullValue(node) { + const type = context.getInputType(); + + if ((0, _definition.isNonNullType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${(0, _inspect.inspect)( + type, + )}", found ${(0, _printer.print)(node)}.`, + { + nodes: node, + }, + ), + ); + } + }, + + EnumValue: (node) => isValidValueNode(context, node), + IntValue: (node) => isValidValueNode(context, node), + FloatValue: (node) => isValidValueNode(context, node), + // Descriptions are string values that would not validate according + // to the below logic, but since (per the specification) descriptions must + // not affect validation, they are ignored entirely when visiting the AST + // and do not require special handling. + // See https://spec.graphql.org/draft/#sec-Descriptions + StringValue: (node) => isValidValueNode(context, node), + BooleanValue: (node) => isValidValueNode(context, node), + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + * + * @internal + */ + +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + + if (!locationType) { + return; + } + + const type = (0, _definition.getNamedType)(locationType); + + if (!(0, _definition.isLeafType)(type)) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}.`, + { + nodes: node, + }, + ), + ); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + try { + const parseResult = type.parseLiteral( + node, + undefined, + /* variables */ + ); + + if (parseResult === undefined) { + const typeStr = (0, _inspect.inspect)(locationType); + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}.`, + { + nodes: node, + }, + ), + ); + } + } catch (error) { + const typeStr = (0, _inspect.inspect)(locationType); + + if (error instanceof _GraphQLError.GraphQLError) { + context.reportError(error); + } else { + context.reportError( + new _GraphQLError.GraphQLError( + `Expected value of type "${typeStr}", found ${(0, _printer.print)( + node, + )}; ` + error.message, + { + nodes: node, + originalError: error, + }, + ), + ); + } + } +} + +function validateOneOfInputObject(context, node, type, fieldNodeMap) { + var _fieldNodeMap$keys$; + + const keys = Object.keys(fieldNodeMap); + const isNotExactlyOneField = keys.length !== 1; + + if (isNotExactlyOneField) { + context.reportError( + new _GraphQLError.GraphQLError( + `OneOf Input Object "${type.name}" must specify exactly one key.`, + { + nodes: [node], + }, + ), + ); + return; + } + + const value = + (_fieldNodeMap$keys$ = fieldNodeMap[keys[0]]) === null || + _fieldNodeMap$keys$ === void 0 + ? void 0 + : _fieldNodeMap$keys$.value; + const isNullLiteral = !value || value.kind === _kinds.Kind.NULL; + + if (isNullLiteral) { + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${type.name}.${keys[0]}" must be non-null.`, + { + nodes: [node], + }, + ), + ); + } +} diff --git a/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6631330916952d79561e7548f2ccf8119ce90d5f --- /dev/null +++ b/node_modules/graphql/validation/rules/ValuesOfCorrectTypeRule.mjs @@ -0,0 +1,247 @@ +/** @category Validation Rules */ +import { didYouMean } from '../../jsutils/didYouMean.mjs'; +import { inspect } from '../../jsutils/inspect.mjs'; +import { keyMap } from '../../jsutils/keyMap.mjs'; +import { suggestionList } from '../../jsutils/suggestionList.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { print } from '../../language/printer.mjs'; +import { + getNamedType, + getNullableType, + isInputObjectType, + isLeafType, + isListType, + isNonNullType, + isRequiredInputField, +} from '../../type/definition.mjs'; + +/** + * Value literals of correct type + * + * A GraphQL document is only valid if all value literals are of the type + * expected at their position. + * + * See https://spec.graphql.org/draft/#sec-Values-of-Correct-Type + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { ValuesOfCorrectTypeRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * count(limit: Int): Int + * } + * `); + * + * const invalidDocument = parse(` + * { count(limit: "many") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [ValuesOfCorrectTypeRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { count(limit: 1) } + * `); + * const validErrors = validate(schema, validDocument, [ValuesOfCorrectTypeRule]); + * + * validErrors; // => [] + * ``` + */ +export function ValuesOfCorrectTypeRule(context) { + return { + ListValue(node) { + // Note: TypeInfo will traverse into a list's item type, so look to the + // parent input type to check if it is a list. + const type = getNullableType(context.getParentInputType()); + + if (!isListType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } + }, + + ObjectValue(node) { + const type = getNamedType(context.getInputType()); + + if (!isInputObjectType(type)) { + isValidValueNode(context, node); + return false; // Don't traverse further. + } // Ensure every required field exists. + + const fieldNodeMap = keyMap(node.fields, (field) => field.name.value); + + for (const fieldDef of Object.values(type.getFields())) { + const fieldNode = fieldNodeMap[fieldDef.name]; + + if (!fieldNode && isRequiredInputField(fieldDef)) { + const typeStr = inspect(fieldDef.type); + context.reportError( + new GraphQLError( + `Field "${type.name}.${fieldDef.name}" of required type "${typeStr}" was not provided.`, + { + nodes: node, + }, + ), + ); + } + } + + if (type.isOneOf) { + validateOneOfInputObject(context, node, type, fieldNodeMap); + } + }, + + ObjectField(node) { + const parentType = getNamedType(context.getParentInputType()); + const fieldType = context.getInputType(); + + if (!fieldType && isInputObjectType(parentType)) { + const suggestions = suggestionList( + node.name.value, + Object.keys(parentType.getFields()), + ); + context.reportError( + new GraphQLError( + `Field "${node.name.value}" is not defined by type "${parentType.name}".` + + didYouMean(suggestions), + { + nodes: node, + }, + ), + ); + } + }, + + NullValue(node) { + const type = context.getInputType(); + + if (isNonNullType(type)) { + context.reportError( + new GraphQLError( + `Expected value of type "${inspect(type)}", found ${print(node)}.`, + { + nodes: node, + }, + ), + ); + } + }, + + EnumValue: (node) => isValidValueNode(context, node), + IntValue: (node) => isValidValueNode(context, node), + FloatValue: (node) => isValidValueNode(context, node), + // Descriptions are string values that would not validate according + // to the below logic, but since (per the specification) descriptions must + // not affect validation, they are ignored entirely when visiting the AST + // and do not require special handling. + // See https://spec.graphql.org/draft/#sec-Descriptions + StringValue: (node) => isValidValueNode(context, node), + BooleanValue: (node) => isValidValueNode(context, node), + }; +} +/** + * Any value literal may be a valid representation of a Scalar, depending on + * that scalar type. + * + * @internal + */ + +function isValidValueNode(context, node) { + // Report any error at the full type expected by the location. + const locationType = context.getInputType(); + + if (!locationType) { + return; + } + + const type = getNamedType(locationType); + + if (!isLeafType(type)) { + const typeStr = inspect(locationType); + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}.`, + { + nodes: node, + }, + ), + ); + return; + } // Scalars and Enums determine if a literal value is valid via parseLiteral(), + // which may throw or return an invalid value to indicate failure. + + try { + const parseResult = type.parseLiteral( + node, + undefined, + /* variables */ + ); + + if (parseResult === undefined) { + const typeStr = inspect(locationType); + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}.`, + { + nodes: node, + }, + ), + ); + } + } catch (error) { + const typeStr = inspect(locationType); + + if (error instanceof GraphQLError) { + context.reportError(error); + } else { + context.reportError( + new GraphQLError( + `Expected value of type "${typeStr}", found ${print(node)}; ` + + error.message, + { + nodes: node, + originalError: error, + }, + ), + ); + } + } +} + +function validateOneOfInputObject(context, node, type, fieldNodeMap) { + var _fieldNodeMap$keys$; + + const keys = Object.keys(fieldNodeMap); + const isNotExactlyOneField = keys.length !== 1; + + if (isNotExactlyOneField) { + context.reportError( + new GraphQLError( + `OneOf Input Object "${type.name}" must specify exactly one key.`, + { + nodes: [node], + }, + ), + ); + return; + } + + const value = + (_fieldNodeMap$keys$ = fieldNodeMap[keys[0]]) === null || + _fieldNodeMap$keys$ === void 0 + ? void 0 + : _fieldNodeMap$keys$.value; + const isNullLiteral = !value || value.kind === Kind.NULL; + + if (isNullLiteral) { + context.reportError( + new GraphQLError(`Field "${type.name}.${keys[0]}" must be non-null.`, { + nodes: [node], + }), + ); + } +} diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..47977dcca453390d2368f23c31aeb724c5a840b6 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.d.ts @@ -0,0 +1,45 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesAreInputTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * + * type User { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($user: User) { field(arg: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesAreInputTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesAreInputTypesRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function VariablesAreInputTypesRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js new file mode 100644 index 0000000000000000000000000000000000000000..de1040acae46c12bbab3ffb63d58f602487befed --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.js @@ -0,0 +1,79 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.VariablesAreInputTypesRule = VariablesAreInputTypesRule; + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _printer = require('../../language/printer.js'); + +var _definition = require('../../type/definition.js'); + +var _typeFromAST = require('../../utilities/typeFromAST.js'); + +/** @category Validation Rules */ + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesAreInputTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * + * type User { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($user: User) { field(arg: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesAreInputTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesAreInputTypesRule]); + * + * validErrors; // => [] + * ``` + */ +function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = (0, _typeFromAST.typeFromAST)( + context.getSchema(), + node.type, + ); + + if (type !== undefined && !(0, _definition.isInputType)(type)) { + const variableName = node.variable.name.value; + const typeName = (0, _printer.print)(node.type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${variableName}" cannot be non-input type "${typeName}".`, + { + nodes: node.type, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..5548961cc92aa9a50b12d70daccf4c376a985511 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesAreInputTypesRule.mjs @@ -0,0 +1,65 @@ +/** @category Validation Rules */ +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { print } from '../../language/printer.mjs'; +import { isInputType } from '../../type/definition.mjs'; +import { typeFromAST } from '../../utilities/typeFromAST.mjs'; + +/** + * Variables are input types + * + * A GraphQL operation is only valid if all the variables it defines are of + * input types (scalar, enum, or input object). + * + * See https://spec.graphql.org/draft/#sec-Variables-Are-Input-Types + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesAreInputTypesRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID): String + * } + * + * type User { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * query ($user: User) { field(arg: "1") } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesAreInputTypesRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesAreInputTypesRule]); + * + * validErrors; // => [] + * ``` + */ +export function VariablesAreInputTypesRule(context) { + return { + VariableDefinition(node) { + const type = typeFromAST(context.getSchema(), node.type); + + if (type !== undefined && !isInputType(type)) { + const variableName = node.variable.name.value; + const typeName = print(node.type); + context.reportError( + new GraphQLError( + `Variable "$${variableName}" cannot be non-input type "${typeName}".`, + { + nodes: node.type, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dcbb56a82fcd35189b1389b0b23103ed5b04fa57 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.d.ts @@ -0,0 +1,40 @@ +/** @category Validation Rules */ +import type { ASTVisitor } from '../../language/visitor'; +import type { ValidationContext } from '../ValidationContext'; +/** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesInAllowedPositionRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID!): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: String) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesInAllowedPositionRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID!) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesInAllowedPositionRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function VariablesInAllowedPositionRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js new file mode 100644 index 0000000000000000000000000000000000000000..36cede901357f4aebfbced23cdbc50a8688a88b3 --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.js @@ -0,0 +1,165 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.VariablesInAllowedPositionRule = VariablesInAllowedPositionRule; + +var _inspect = require('../../jsutils/inspect.js'); + +var _GraphQLError = require('../../error/GraphQLError.js'); + +var _kinds = require('../../language/kinds.js'); + +var _definition = require('../../type/definition.js'); + +var _typeComparators = require('../../utilities/typeComparators.js'); + +var _typeFromAST = require('../../utilities/typeFromAST.js'); + +/** @category Validation Rules */ + +/** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesInAllowedPositionRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID!): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: String) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesInAllowedPositionRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID!) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesInAllowedPositionRule]); + * + * validErrors; // => [] + * ``` + */ +function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node, type, defaultValue, parentType } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = (0, _typeFromAST.typeFromAST)(schema, varDef.type); + + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + const varTypeStr = (0, _inspect.inspect)(varType); + const typeStr = (0, _inspect.inspect)(type); + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, + { + nodes: [varDef, node], + }, + ), + ); + } + + if ( + (0, _definition.isInputObjectType)(parentType) && + parentType.isOneOf && + (0, _definition.isNullableType)(varType) + ) { + context.reportError( + new _GraphQLError.GraphQLError( + `Variable "$${varName}" is of type "${varType}" but must be non-nullable to be used for OneOf Input Object "${parentType}".`, + { + nodes: [varDef, node], + }, + ), + ); + } + } + } + }, + }, + + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * including considering if default values exist for either the variable + * or the location at which it is located. + * + * OneOf Input Object Type fields are considered separately above to + * provide a more descriptive error message. + * + * @internal + */ + +function allowedVariableUsage( + schema, + varType, + varDefaultValue, + locationType, + locationDefaultValue, +) { + if ( + (0, _definition.isNonNullType)(locationType) && + !(0, _definition.isNonNullType)(varType) + ) { + const hasNonNullVariableDefaultValue = + varDefaultValue != null && varDefaultValue.kind !== _kinds.Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + const nullableLocationType = locationType.ofType; + return (0, _typeComparators.isTypeSubTypeOf)( + schema, + varType, + nullableLocationType, + ); + } + + return (0, _typeComparators.isTypeSubTypeOf)(schema, varType, locationType); +} diff --git a/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..1ed0156b32d883e2304c235ad4d5a27ad1c32f5f --- /dev/null +++ b/node_modules/graphql/validation/rules/VariablesInAllowedPositionRule.mjs @@ -0,0 +1,149 @@ +/** @category Validation Rules */ +import { inspect } from '../../jsutils/inspect.mjs'; +import { GraphQLError } from '../../error/GraphQLError.mjs'; +import { Kind } from '../../language/kinds.mjs'; +import { + isInputObjectType, + isNonNullType, + isNullableType, +} from '../../type/definition.mjs'; +import { isTypeSubTypeOf } from '../../utilities/typeComparators.mjs'; +import { typeFromAST } from '../../utilities/typeFromAST.mjs'; + +/** + * Variables in allowed position + * + * Variable usages must be compatible with the arguments they are passed to. + * + * See https://spec.graphql.org/draft/#sec-All-Variable-Usages-are-Allowed + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { VariablesInAllowedPositionRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * field(arg: ID!): String + * } + * `); + * + * const invalidDocument = parse(` + * query ($id: String) { field(arg: $id) } + * `); + * const invalidErrors = validate(schema, invalidDocument, [VariablesInAllowedPositionRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * query ($id: ID!) { field(arg: $id) } + * `); + * const validErrors = validate(schema, validDocument, [VariablesInAllowedPositionRule]); + * + * validErrors; // => [] + * ``` + */ +export function VariablesInAllowedPositionRule(context) { + let varDefMap = Object.create(null); + return { + OperationDefinition: { + enter() { + varDefMap = Object.create(null); + }, + + leave(operation) { + const usages = context.getRecursiveVariableUsages(operation); + + for (const { node, type, defaultValue, parentType } of usages) { + const varName = node.name.value; + const varDef = varDefMap[varName]; + + if (varDef && type) { + // A var type is allowed if it is the same or more strict (e.g. is + // a subtype of) than the expected type. It can be more strict if + // the variable type is non-null when the expected type is nullable. + // If both are list types, the variable item type can be more strict + // than the expected item type (contravariant). + const schema = context.getSchema(); + const varType = typeFromAST(schema, varDef.type); + + if ( + varType && + !allowedVariableUsage( + schema, + varType, + varDef.defaultValue, + type, + defaultValue, + ) + ) { + const varTypeStr = inspect(varType); + const typeStr = inspect(type); + context.reportError( + new GraphQLError( + `Variable "$${varName}" of type "${varTypeStr}" used in position expecting type "${typeStr}".`, + { + nodes: [varDef, node], + }, + ), + ); + } + + if ( + isInputObjectType(parentType) && + parentType.isOneOf && + isNullableType(varType) + ) { + context.reportError( + new GraphQLError( + `Variable "$${varName}" is of type "${varType}" but must be non-nullable to be used for OneOf Input Object "${parentType}".`, + { + nodes: [varDef, node], + }, + ), + ); + } + } + } + }, + }, + + VariableDefinition(node) { + varDefMap[node.variable.name.value] = node; + }, + }; +} +/** + * Returns true if the variable is allowed in the location it was found, + * including considering if default values exist for either the variable + * or the location at which it is located. + * + * OneOf Input Object Type fields are considered separately above to + * provide a more descriptive error message. + * + * @internal + */ + +function allowedVariableUsage( + schema, + varType, + varDefaultValue, + locationType, + locationDefaultValue, +) { + if (isNonNullType(locationType) && !isNonNullType(varType)) { + const hasNonNullVariableDefaultValue = + varDefaultValue != null && varDefaultValue.kind !== Kind.NULL; + const hasLocationDefaultValue = locationDefaultValue !== undefined; + + if (!hasNonNullVariableDefaultValue && !hasLocationDefaultValue) { + return false; + } + + const nullableLocationType = locationType.ofType; + return isTypeSubTypeOf(schema, varType, nullableLocationType); + } + + return isTypeSubTypeOf(schema, varType, locationType); +} diff --git a/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..739e321ff3b1067f08092df51f21b1d9c9cde523 --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.d.ts @@ -0,0 +1,56 @@ +/** @category Custom Rules */ +import type { ASTVisitor } from '../../../language/visitor'; +import type { ValidationContext } from '../../ValidationContext'; +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * parse, + * validate, + * } from 'graphql'; + * import { NoDeprecatedCustomRule } from 'graphql/validation'; + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * name: { type: GraphQLString }, + * oldName: { + * type: GraphQLString, + * deprecationReason: 'Use name instead.', + * }, + * }, + * }), + * }); + * + * const invalidDocument = parse(` + * { oldName } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoDeprecatedCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoDeprecatedCustomRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoDeprecatedCustomRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js new file mode 100644 index 0000000000000000000000000000000000000000..c8e21bbbfbf704533f7460b338bf105f736244d3 --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.js @@ -0,0 +1,173 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoDeprecatedCustomRule = NoDeprecatedCustomRule; + +var _invariant = require('../../../jsutils/invariant.js'); + +var _GraphQLError = require('../../../error/GraphQLError.js'); + +var _definition = require('../../../type/definition.js'); + +/** @category Custom Rules */ + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * parse, + * validate, + * } from 'graphql'; + * import { NoDeprecatedCustomRule } from 'graphql/validation'; + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * name: { type: GraphQLString }, + * oldName: { + * type: GraphQLString, + * deprecationReason: 'Use name instead.', + * }, + * }, + * }), + * }); + * + * const invalidDocument = parse(` + * { oldName } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoDeprecatedCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoDeprecatedCustomRule]); + * + * validErrors; // => [] + * ``` + */ +function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = + fieldDef === null || fieldDef === void 0 + ? void 0 + : fieldDef.deprecationReason; + + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, + + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = + argDef === null || argDef === void 0 + ? void 0 + : argDef.deprecationReason; + + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + + if (directiveDef != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + (parentType != null && fieldDef != null) || + (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + } + }, + + ObjectField(node) { + const inputObjectDef = (0, _definition.getNamedType)( + context.getParentInputType(), + ); + + if ((0, _definition.isInputObjectType)(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = + inputFieldDef === null || inputFieldDef === void 0 + ? void 0 + : inputFieldDef.deprecationReason; + + if (deprecationReason != null) { + context.reportError( + new _GraphQLError.GraphQLError( + `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + } + }, + + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = + enumValueDef === null || enumValueDef === void 0 + ? void 0 + : enumValueDef.deprecationReason; + + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = (0, _definition.getNamedType)( + context.getInputType(), + ); + enumTypeDef != null || (0, _invariant.invariant)(false); + context.reportError( + new _GraphQLError.GraphQLError( + `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..a51abb9d216d5d07d1e358bab9077b3d4a0021c9 --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoDeprecatedCustomRule.mjs @@ -0,0 +1,158 @@ +/** @category Custom Rules */ +import { invariant } from '../../../jsutils/invariant.mjs'; +import { GraphQLError } from '../../../error/GraphQLError.mjs'; +import { getNamedType, isInputObjectType } from '../../../type/definition.mjs'; + +/** + * No deprecated + * + * A GraphQL document is only valid if all selected fields and all used enum values have not been + * deprecated. + * + * Note: This rule is optional and is not part of the Validation section of the GraphQL + * Specification. The main purpose of this rule is detection of deprecated usages and not + * necessarily to forbid their use when querying a service. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { + * GraphQLObjectType, + * GraphQLSchema, + * GraphQLString, + * parse, + * validate, + * } from 'graphql'; + * import { NoDeprecatedCustomRule } from 'graphql/validation'; + * + * const schema = new GraphQLSchema({ + * query: new GraphQLObjectType({ + * name: 'Query', + * fields: { + * name: { type: GraphQLString }, + * oldName: { + * type: GraphQLString, + * deprecationReason: 'Use name instead.', + * }, + * }, + * }), + * }); + * + * const invalidDocument = parse(` + * { oldName } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoDeprecatedCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoDeprecatedCustomRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoDeprecatedCustomRule(context) { + return { + Field(node) { + const fieldDef = context.getFieldDef(); + const deprecationReason = + fieldDef === null || fieldDef === void 0 + ? void 0 + : fieldDef.deprecationReason; + + if (fieldDef && deprecationReason != null) { + const parentType = context.getParentType(); + parentType != null || invariant(false); + context.reportError( + new GraphQLError( + `The field ${parentType.name}.${fieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, + + Argument(node) { + const argDef = context.getArgument(); + const deprecationReason = + argDef === null || argDef === void 0 + ? void 0 + : argDef.deprecationReason; + + if (argDef && deprecationReason != null) { + const directiveDef = context.getDirective(); + + if (directiveDef != null) { + context.reportError( + new GraphQLError( + `Directive "@${directiveDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } else { + const parentType = context.getParentType(); + const fieldDef = context.getFieldDef(); + (parentType != null && fieldDef != null) || invariant(false); + context.reportError( + new GraphQLError( + `Field "${parentType.name}.${fieldDef.name}" argument "${argDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + } + }, + + ObjectField(node) { + const inputObjectDef = getNamedType(context.getParentInputType()); + + if (isInputObjectType(inputObjectDef)) { + const inputFieldDef = inputObjectDef.getFields()[node.name.value]; + const deprecationReason = + inputFieldDef === null || inputFieldDef === void 0 + ? void 0 + : inputFieldDef.deprecationReason; + + if (deprecationReason != null) { + context.reportError( + new GraphQLError( + `The input field ${inputObjectDef.name}.${inputFieldDef.name} is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + } + }, + + EnumValue(node) { + const enumValueDef = context.getEnumValue(); + const deprecationReason = + enumValueDef === null || enumValueDef === void 0 + ? void 0 + : enumValueDef.deprecationReason; + + if (enumValueDef && deprecationReason != null) { + const enumTypeDef = getNamedType(context.getInputType()); + enumTypeDef != null || invariant(false); + context.reportError( + new GraphQLError( + `The enum value "${enumTypeDef.name}.${enumValueDef.name}" is deprecated. ${deprecationReason}`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..0d1595ae36517e027abd26e49b46524ef81063bf --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.d.ts @@ -0,0 +1,43 @@ +/** @category Custom Rules */ +import type { ASTVisitor } from '../../../language/visitor'; +import type { ValidationContext } from '../../ValidationContext'; +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoSchemaIntrospectionCustomRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoSchemaIntrospectionCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoSchemaIntrospectionCustomRule]); + * + * validErrors; // => [] + * ``` + */ +export declare function NoSchemaIntrospectionCustomRule( + context: ValidationContext, +): ASTVisitor; diff --git a/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js new file mode 100644 index 0000000000000000000000000000000000000000..34af9210ab437332d356874561bcaf513207b836 --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.js @@ -0,0 +1,70 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.NoSchemaIntrospectionCustomRule = NoSchemaIntrospectionCustomRule; + +var _GraphQLError = require('../../../error/GraphQLError.js'); + +var _definition = require('../../../type/definition.js'); + +var _introspection = require('../../../type/introspection.js'); + +/** @category Custom Rules */ + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoSchemaIntrospectionCustomRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoSchemaIntrospectionCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoSchemaIntrospectionCustomRule]); + * + * validErrors; // => [] + * ``` + */ +function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = (0, _definition.getNamedType)(context.getType()); + + if (type && (0, _introspection.isIntrospectionType)(type)) { + context.reportError( + new _GraphQLError.GraphQLError( + `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3ddc914f1f00d400a853d0802ec540bb5d93c72e --- /dev/null +++ b/node_modules/graphql/validation/rules/custom/NoSchemaIntrospectionCustomRule.mjs @@ -0,0 +1,60 @@ +/** @category Custom Rules */ +import { GraphQLError } from '../../../error/GraphQLError.mjs'; +import { getNamedType } from '../../../type/definition.mjs'; +import { isIntrospectionType } from '../../../type/introspection.mjs'; + +/** + * Prohibit introspection queries + * + * A GraphQL document is only valid if all fields selected are not fields that + * return an introspection type. + * + * Note: This rule is optional and is not part of the Validation section of the + * GraphQL Specification. This rule effectively disables introspection, which + * does not reflect best practices and should only be done if absolutely necessary. + * @param context - The validation context used while checking the document. + * @returns A visitor that reports validation errors for this rule. + * @example + * ```ts + * import { buildSchema, parse, validate } from 'graphql'; + * import { NoSchemaIntrospectionCustomRule } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * name: String + * } + * `); + * + * const invalidDocument = parse(` + * { __schema { queryType { name } } } + * `); + * const invalidErrors = validate(schema, invalidDocument, [NoSchemaIntrospectionCustomRule]); + * + * invalidErrors.length; // => 1 + * + * const validDocument = parse(` + * { name } + * `); + * const validErrors = validate(schema, validDocument, [NoSchemaIntrospectionCustomRule]); + * + * validErrors; // => [] + * ``` + */ +export function NoSchemaIntrospectionCustomRule(context) { + return { + Field(node) { + const type = getNamedType(context.getType()); + + if (type && isIntrospectionType(type)) { + context.reportError( + new GraphQLError( + `GraphQL introspection has been disabled, but the requested query contained the field "${node.name.value}".`, + { + nodes: node, + }, + ), + ); + } + }, + }; +} diff --git a/node_modules/graphql/validation/specifiedRules.d.ts b/node_modules/graphql/validation/specifiedRules.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c882d7bca7ff683461b40dce5180a4203266c303 --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.d.ts @@ -0,0 +1,17 @@ +/** @category Validation Rules */ +import { MaxIntrospectionDepthRule } from './rules/MaxIntrospectionDepthRule'; +import type { SDLValidationRule, ValidationRule } from './ValidationContext'; +/** + * Technically these aren't part of the spec but they are strongly encouraged + * validation rules. + */ +export declare const recommendedRules: readonly typeof MaxIntrospectionDepthRule[]; +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ +export declare const specifiedRules: ReadonlyArray; +/** @internal */ +export declare const specifiedSDLRules: ReadonlyArray; diff --git a/node_modules/graphql/validation/specifiedRules.js b/node_modules/graphql/validation/specifiedRules.js new file mode 100644 index 0000000000000000000000000000000000000000..7d45f172d113e06ac616b9d3da7b2f321bd1c0ff --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.js @@ -0,0 +1,175 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.specifiedSDLRules = + exports.specifiedRules = + exports.recommendedRules = + void 0; + +var _ExecutableDefinitionsRule = require('./rules/ExecutableDefinitionsRule.js'); + +var _FieldsOnCorrectTypeRule = require('./rules/FieldsOnCorrectTypeRule.js'); + +var _FragmentsOnCompositeTypesRule = require('./rules/FragmentsOnCompositeTypesRule.js'); + +var _KnownArgumentNamesRule = require('./rules/KnownArgumentNamesRule.js'); + +var _KnownDirectivesRule = require('./rules/KnownDirectivesRule.js'); + +var _KnownFragmentNamesRule = require('./rules/KnownFragmentNamesRule.js'); + +var _KnownTypeNamesRule = require('./rules/KnownTypeNamesRule.js'); + +var _LoneAnonymousOperationRule = require('./rules/LoneAnonymousOperationRule.js'); + +var _LoneSchemaDefinitionRule = require('./rules/LoneSchemaDefinitionRule.js'); + +var _MaxIntrospectionDepthRule = require('./rules/MaxIntrospectionDepthRule.js'); + +var _NoFragmentCyclesRule = require('./rules/NoFragmentCyclesRule.js'); + +var _NoUndefinedVariablesRule = require('./rules/NoUndefinedVariablesRule.js'); + +var _NoUnusedFragmentsRule = require('./rules/NoUnusedFragmentsRule.js'); + +var _NoUnusedVariablesRule = require('./rules/NoUnusedVariablesRule.js'); + +var _OverlappingFieldsCanBeMergedRule = require('./rules/OverlappingFieldsCanBeMergedRule.js'); + +var _PossibleFragmentSpreadsRule = require('./rules/PossibleFragmentSpreadsRule.js'); + +var _PossibleTypeExtensionsRule = require('./rules/PossibleTypeExtensionsRule.js'); + +var _ProvidedRequiredArgumentsRule = require('./rules/ProvidedRequiredArgumentsRule.js'); + +var _ScalarLeafsRule = require('./rules/ScalarLeafsRule.js'); + +var _SingleFieldSubscriptionsRule = require('./rules/SingleFieldSubscriptionsRule.js'); + +var _UniqueArgumentDefinitionNamesRule = require('./rules/UniqueArgumentDefinitionNamesRule.js'); + +var _UniqueArgumentNamesRule = require('./rules/UniqueArgumentNamesRule.js'); + +var _UniqueDirectiveNamesRule = require('./rules/UniqueDirectiveNamesRule.js'); + +var _UniqueDirectivesPerLocationRule = require('./rules/UniqueDirectivesPerLocationRule.js'); + +var _UniqueEnumValueNamesRule = require('./rules/UniqueEnumValueNamesRule.js'); + +var _UniqueFieldDefinitionNamesRule = require('./rules/UniqueFieldDefinitionNamesRule.js'); + +var _UniqueFragmentNamesRule = require('./rules/UniqueFragmentNamesRule.js'); + +var _UniqueInputFieldNamesRule = require('./rules/UniqueInputFieldNamesRule.js'); + +var _UniqueOperationNamesRule = require('./rules/UniqueOperationNamesRule.js'); + +var _UniqueOperationTypesRule = require('./rules/UniqueOperationTypesRule.js'); + +var _UniqueTypeNamesRule = require('./rules/UniqueTypeNamesRule.js'); + +var _UniqueVariableNamesRule = require('./rules/UniqueVariableNamesRule.js'); + +var _ValuesOfCorrectTypeRule = require('./rules/ValuesOfCorrectTypeRule.js'); + +var _VariablesAreInputTypesRule = require('./rules/VariablesAreInputTypesRule.js'); + +var _VariablesInAllowedPositionRule = require('./rules/VariablesInAllowedPositionRule.js'); + +/** @category Validation Rules */ +// Spec Section: "Executable Definitions" +// Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" +// Spec Section: "Fragments on Composite Types" +// Spec Section: "Argument Names" +// Spec Section: "Directives Are Defined" +// Spec Section: "Fragment spread target defined" +// Spec Section: "Fragment Spread Type Existence" +// Spec Section: "Lone Anonymous Operation" +// SDL-specific validation rules +// TODO: Spec Section +// Spec Section: "Fragments must not form cycles" +// Spec Section: "All Variable Used Defined" +// Spec Section: "Fragments must be used" +// Spec Section: "All Variables Used" +// Spec Section: "Field Selection Merging" +// Spec Section: "Fragment spread is possible" +// Spec Section: "Argument Optionality" +// Spec Section: "Leaf Field Selections" +// Spec Section: "Subscriptions with Single Root Field" +// Spec Section: "Argument Uniqueness" +// Spec Section: "Directives Are Unique Per Location" +// Spec Section: "Fragment Name Uniqueness" +// Spec Section: "Input Object Field Uniqueness" +// Spec Section: "Operation Name Uniqueness" +// Spec Section: "Variable Uniqueness" +// Spec Section: "Value Type Correctness" +// Spec Section: "Variables are Input Types" +// Spec Section: "All Variable Usages Are Allowed" + +/** + * Technically these aren't part of the spec but they are strongly encouraged + * validation rules. + */ +const recommendedRules = Object.freeze([ + _MaxIntrospectionDepthRule.MaxIntrospectionDepthRule, +]); +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + +exports.recommendedRules = recommendedRules; +const specifiedRules = Object.freeze([ + _ExecutableDefinitionsRule.ExecutableDefinitionsRule, + _UniqueOperationNamesRule.UniqueOperationNamesRule, + _LoneAnonymousOperationRule.LoneAnonymousOperationRule, + _SingleFieldSubscriptionsRule.SingleFieldSubscriptionsRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _FragmentsOnCompositeTypesRule.FragmentsOnCompositeTypesRule, + _VariablesAreInputTypesRule.VariablesAreInputTypesRule, + _ScalarLeafsRule.ScalarLeafsRule, + _FieldsOnCorrectTypeRule.FieldsOnCorrectTypeRule, + _UniqueFragmentNamesRule.UniqueFragmentNamesRule, + _KnownFragmentNamesRule.KnownFragmentNamesRule, + _NoUnusedFragmentsRule.NoUnusedFragmentsRule, + _PossibleFragmentSpreadsRule.PossibleFragmentSpreadsRule, + _NoFragmentCyclesRule.NoFragmentCyclesRule, + _UniqueVariableNamesRule.UniqueVariableNamesRule, + _NoUndefinedVariablesRule.NoUndefinedVariablesRule, + _NoUnusedVariablesRule.NoUnusedVariablesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _KnownArgumentNamesRule.KnownArgumentNamesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _ValuesOfCorrectTypeRule.ValuesOfCorrectTypeRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsRule, + _VariablesInAllowedPositionRule.VariablesInAllowedPositionRule, + _OverlappingFieldsCanBeMergedRule.OverlappingFieldsCanBeMergedRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + ...recommendedRules, +]); +/** @internal */ + +exports.specifiedRules = specifiedRules; +const specifiedSDLRules = Object.freeze([ + _LoneSchemaDefinitionRule.LoneSchemaDefinitionRule, + _UniqueOperationTypesRule.UniqueOperationTypesRule, + _UniqueTypeNamesRule.UniqueTypeNamesRule, + _UniqueEnumValueNamesRule.UniqueEnumValueNamesRule, + _UniqueFieldDefinitionNamesRule.UniqueFieldDefinitionNamesRule, + _UniqueArgumentDefinitionNamesRule.UniqueArgumentDefinitionNamesRule, + _UniqueDirectiveNamesRule.UniqueDirectiveNamesRule, + _KnownTypeNamesRule.KnownTypeNamesRule, + _KnownDirectivesRule.KnownDirectivesRule, + _UniqueDirectivesPerLocationRule.UniqueDirectivesPerLocationRule, + _PossibleTypeExtensionsRule.PossibleTypeExtensionsRule, + _KnownArgumentNamesRule.KnownArgumentNamesOnDirectivesRule, + _UniqueArgumentNamesRule.UniqueArgumentNamesRule, + _UniqueInputFieldNamesRule.UniqueInputFieldNamesRule, + _ProvidedRequiredArgumentsRule.ProvidedRequiredArgumentsOnDirectivesRule, +]); +exports.specifiedSDLRules = specifiedSDLRules; diff --git a/node_modules/graphql/validation/specifiedRules.mjs b/node_modules/graphql/validation/specifiedRules.mjs new file mode 100644 index 0000000000000000000000000000000000000000..100d18f0950c89383e6e0aeb53740707b1a3e4ed --- /dev/null +++ b/node_modules/graphql/validation/specifiedRules.mjs @@ -0,0 +1,131 @@ +/** @category Validation Rules */ +// Spec Section: "Executable Definitions" +import { ExecutableDefinitionsRule } from './rules/ExecutableDefinitionsRule.mjs'; // Spec Section: "Field Selections on Objects, Interfaces, and Unions Types" + +import { FieldsOnCorrectTypeRule } from './rules/FieldsOnCorrectTypeRule.mjs'; // Spec Section: "Fragments on Composite Types" + +import { FragmentsOnCompositeTypesRule } from './rules/FragmentsOnCompositeTypesRule.mjs'; // Spec Section: "Argument Names" + +import { + KnownArgumentNamesOnDirectivesRule, + KnownArgumentNamesRule, +} from './rules/KnownArgumentNamesRule.mjs'; // Spec Section: "Directives Are Defined" + +import { KnownDirectivesRule } from './rules/KnownDirectivesRule.mjs'; // Spec Section: "Fragment spread target defined" + +import { KnownFragmentNamesRule } from './rules/KnownFragmentNamesRule.mjs'; // Spec Section: "Fragment Spread Type Existence" + +import { KnownTypeNamesRule } from './rules/KnownTypeNamesRule.mjs'; // Spec Section: "Lone Anonymous Operation" + +import { LoneAnonymousOperationRule } from './rules/LoneAnonymousOperationRule.mjs'; // SDL-specific validation rules + +import { LoneSchemaDefinitionRule } from './rules/LoneSchemaDefinitionRule.mjs'; // TODO: Spec Section + +import { MaxIntrospectionDepthRule } from './rules/MaxIntrospectionDepthRule.mjs'; // Spec Section: "Fragments must not form cycles" + +import { NoFragmentCyclesRule } from './rules/NoFragmentCyclesRule.mjs'; // Spec Section: "All Variable Used Defined" + +import { NoUndefinedVariablesRule } from './rules/NoUndefinedVariablesRule.mjs'; // Spec Section: "Fragments must be used" + +import { NoUnusedFragmentsRule } from './rules/NoUnusedFragmentsRule.mjs'; // Spec Section: "All Variables Used" + +import { NoUnusedVariablesRule } from './rules/NoUnusedVariablesRule.mjs'; // Spec Section: "Field Selection Merging" + +import { OverlappingFieldsCanBeMergedRule } from './rules/OverlappingFieldsCanBeMergedRule.mjs'; // Spec Section: "Fragment spread is possible" + +import { PossibleFragmentSpreadsRule } from './rules/PossibleFragmentSpreadsRule.mjs'; +import { PossibleTypeExtensionsRule } from './rules/PossibleTypeExtensionsRule.mjs'; // Spec Section: "Argument Optionality" + +import { + ProvidedRequiredArgumentsOnDirectivesRule, + ProvidedRequiredArgumentsRule, +} from './rules/ProvidedRequiredArgumentsRule.mjs'; // Spec Section: "Leaf Field Selections" + +import { ScalarLeafsRule } from './rules/ScalarLeafsRule.mjs'; // Spec Section: "Subscriptions with Single Root Field" + +import { SingleFieldSubscriptionsRule } from './rules/SingleFieldSubscriptionsRule.mjs'; +import { UniqueArgumentDefinitionNamesRule } from './rules/UniqueArgumentDefinitionNamesRule.mjs'; // Spec Section: "Argument Uniqueness" + +import { UniqueArgumentNamesRule } from './rules/UniqueArgumentNamesRule.mjs'; +import { UniqueDirectiveNamesRule } from './rules/UniqueDirectiveNamesRule.mjs'; // Spec Section: "Directives Are Unique Per Location" + +import { UniqueDirectivesPerLocationRule } from './rules/UniqueDirectivesPerLocationRule.mjs'; +import { UniqueEnumValueNamesRule } from './rules/UniqueEnumValueNamesRule.mjs'; +import { UniqueFieldDefinitionNamesRule } from './rules/UniqueFieldDefinitionNamesRule.mjs'; // Spec Section: "Fragment Name Uniqueness" + +import { UniqueFragmentNamesRule } from './rules/UniqueFragmentNamesRule.mjs'; // Spec Section: "Input Object Field Uniqueness" + +import { UniqueInputFieldNamesRule } from './rules/UniqueInputFieldNamesRule.mjs'; // Spec Section: "Operation Name Uniqueness" + +import { UniqueOperationNamesRule } from './rules/UniqueOperationNamesRule.mjs'; +import { UniqueOperationTypesRule } from './rules/UniqueOperationTypesRule.mjs'; +import { UniqueTypeNamesRule } from './rules/UniqueTypeNamesRule.mjs'; // Spec Section: "Variable Uniqueness" + +import { UniqueVariableNamesRule } from './rules/UniqueVariableNamesRule.mjs'; // Spec Section: "Value Type Correctness" + +import { ValuesOfCorrectTypeRule } from './rules/ValuesOfCorrectTypeRule.mjs'; // Spec Section: "Variables are Input Types" + +import { VariablesAreInputTypesRule } from './rules/VariablesAreInputTypesRule.mjs'; // Spec Section: "All Variable Usages Are Allowed" + +import { VariablesInAllowedPositionRule } from './rules/VariablesInAllowedPositionRule.mjs'; + +/** + * Technically these aren't part of the spec but they are strongly encouraged + * validation rules. + */ +export const recommendedRules = Object.freeze([MaxIntrospectionDepthRule]); +/** + * This set includes all validation rules defined by the GraphQL spec. + * + * The order of the rules in this list has been adjusted to lead to the + * most clear output when encountering multiple validation errors. + */ + +export const specifiedRules = Object.freeze([ + ExecutableDefinitionsRule, + UniqueOperationNamesRule, + LoneAnonymousOperationRule, + SingleFieldSubscriptionsRule, + KnownTypeNamesRule, + FragmentsOnCompositeTypesRule, + VariablesAreInputTypesRule, + ScalarLeafsRule, + FieldsOnCorrectTypeRule, + UniqueFragmentNamesRule, + KnownFragmentNamesRule, + NoUnusedFragmentsRule, + PossibleFragmentSpreadsRule, + NoFragmentCyclesRule, + UniqueVariableNamesRule, + NoUndefinedVariablesRule, + NoUnusedVariablesRule, + KnownDirectivesRule, + UniqueDirectivesPerLocationRule, + KnownArgumentNamesRule, + UniqueArgumentNamesRule, + ValuesOfCorrectTypeRule, + ProvidedRequiredArgumentsRule, + VariablesInAllowedPositionRule, + OverlappingFieldsCanBeMergedRule, + UniqueInputFieldNamesRule, + ...recommendedRules, +]); +/** @internal */ + +export const specifiedSDLRules = Object.freeze([ + LoneSchemaDefinitionRule, + UniqueOperationTypesRule, + UniqueTypeNamesRule, + UniqueEnumValueNamesRule, + UniqueFieldDefinitionNamesRule, + UniqueArgumentDefinitionNamesRule, + UniqueDirectiveNamesRule, + KnownTypeNamesRule, + KnownDirectivesRule, + UniqueDirectivesPerLocationRule, + PossibleTypeExtensionsRule, + KnownArgumentNamesOnDirectivesRule, + UniqueArgumentNamesRule, + UniqueInputFieldNamesRule, + ProvidedRequiredArgumentsOnDirectivesRule, +]); diff --git a/node_modules/graphql/validation/validate.d.ts b/node_modules/graphql/validation/validate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc8319cc0d5ff2d4fbda7a5e14bd5356533de452 --- /dev/null +++ b/node_modules/graphql/validation/validate.d.ts @@ -0,0 +1,122 @@ +/** @category Validation */ +import type { Maybe } from '../jsutils/Maybe'; +import { GraphQLError } from '../error/GraphQLError'; +import type { DocumentNode } from '../language/ast'; +import type { GraphQLSchema } from '../type/schema'; +import { TypeInfo } from '../utilities/TypeInfo'; +import type { SDLValidationRule, ValidationRule } from './ValidationContext'; +/** + * Options used when validating a GraphQL document. + * @internal + */ +export interface ValidationOptions { + /** + * Maximum number of validation errors before validation stops. + * @internal + */ + maxErrors?: number; +} +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rule is a function that returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so `maxErrors` defaults to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + * @param schema - Schema to validate against. + * @param documentAST - Document AST to validate. + * @param rules - Validation rules to apply. + * @param options - Validation options, including error limits. + * @param typeInfo - TypeInfo instance to update during traversal. + * @returns Validation errors, or an empty array when the document is valid. + * @example + * ```ts + * // Validate with the default specified rules. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * validate(schema, parse('{ greeting }')); // => [] + * + * const errors = validate(schema, parse('{ missing }')); + * errors[0].message; // => 'Cannot query field "missing" on type "Query".' + * ``` + * @example + * ```ts + * // This variant uses a custom rule list, TypeInfo, and validation options. + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { FieldsOnCorrectTypeRule, validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ missingOne missingTwo }'); + * + * const errors = validate( + * schema, + * document, + * [FieldsOnCorrectTypeRule], + * { maxErrors: 1 }, + * new TypeInfo(schema), + * ); + * + * errors.length; // => 2 + * errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.' + * ``` + */ +export declare function validate( + schema: GraphQLSchema, + documentAST: DocumentNode, + rules?: ReadonlyArray, + options?: ValidationOptions, + /** + * Deprecated TypeInfo instance used to track traversal state during + * validation. Omit this argument so validate creates the TypeInfo instance. + * @deprecated will be removed in 17.0.0 + */ + typeInfo?: TypeInfo, +): ReadonlyArray; +/** @internal */ +export declare function validateSDL( + documentAST: DocumentNode, + schemaToExtend?: Maybe, + rules?: ReadonlyArray, +): ReadonlyArray; +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export declare function assertValidSDL(documentAST: DocumentNode): void; +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ +export declare function assertValidSDLExtension( + documentAST: DocumentNode, + schema: GraphQLSchema, +): void; diff --git a/node_modules/graphql/validation/validate.js b/node_modules/graphql/validation/validate.js new file mode 100644 index 0000000000000000000000000000000000000000..fa2fb376807fb14cd094555044d629afbcee7216 --- /dev/null +++ b/node_modules/graphql/validation/validate.js @@ -0,0 +1,219 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.assertValidSDL = assertValidSDL; +exports.assertValidSDLExtension = assertValidSDLExtension; +exports.validate = validate; +exports.validateSDL = validateSDL; + +var _devAssert = require('../jsutils/devAssert.js'); + +var _mapValue = require('../jsutils/mapValue.js'); + +var _GraphQLError = require('../error/GraphQLError.js'); + +var _ast = require('../language/ast.js'); + +var _visitor = require('../language/visitor.js'); + +var _validate = require('../type/validate.js'); + +var _TypeInfo = require('../utilities/TypeInfo.js'); + +var _specifiedRules = require('./specifiedRules.js'); + +var _ValidationContext = require('./ValidationContext.js'); + +/** @category Validation */ +// Per the specification, descriptions must not affect validation. +// See https://spec.graphql.org/draft/#sec-Descriptions +const QueryDocumentKeysToValidate = (0, _mapValue.mapValue)( + _ast.QueryDocumentKeys, + (keys) => keys.filter((key) => key !== 'description'), +); +/** + * Options used when validating a GraphQL document. + * @internal + */ + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rule is a function that returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so `maxErrors` defaults to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + * @param schema - Schema to validate against. + * @param documentAST - Document AST to validate. + * @param rules - Validation rules to apply. + * @param options - Validation options, including error limits. + * @param typeInfo - TypeInfo instance to update during traversal. + * @returns Validation errors, or an empty array when the document is valid. + * @example + * ```ts + * // Validate with the default specified rules. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * validate(schema, parse('{ greeting }')); // => [] + * + * const errors = validate(schema, parse('{ missing }')); + * errors[0].message; // => 'Cannot query field "missing" on type "Query".' + * ``` + * @example + * ```ts + * // This variant uses a custom rule list, TypeInfo, and validation options. + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { FieldsOnCorrectTypeRule, validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ missingOne missingTwo }'); + * + * const errors = validate( + * schema, + * document, + * [FieldsOnCorrectTypeRule], + * { maxErrors: 1 }, + * new TypeInfo(schema), + * ); + * + * errors.length; // => 2 + * errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.' + * ``` + */ +function validate( + schema, + documentAST, + rules = _specifiedRules.specifiedRules, + options, + /** + * Deprecated TypeInfo instance used to track traversal state during + * validation. Omit this argument so validate creates the TypeInfo instance. + * @deprecated will be removed in 17.0.0 + */ + typeInfo = new _TypeInfo.TypeInfo(schema), +) { + var _options$maxErrors; + + const maxErrors = + (_options$maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors) !== + null && _options$maxErrors !== void 0 + ? _options$maxErrors + : 100; + documentAST || (0, _devAssert.devAssert)(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + (0, _validate.assertValidSchema)(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new _ValidationContext.ValidationContext( + schema, + documentAST, + typeInfo, + (error) => { + if (errors.length >= maxErrors) { + errors.push( + new _GraphQLError.GraphQLError( + 'Too many validation errors, error limit reached. Validation aborted.', + ), + ); // eslint-disable-next-line @typescript-eslint/no-throw-literal + + throw abortObj; + } + + errors.push(error); + }, + ); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + const visitor = (0, _visitor.visitInParallel)( + rules.map((rule) => rule(context)), + ); // Visit the whole document with each instance of all provided rules. + + try { + (0, _visitor.visit)( + documentAST, + (0, _TypeInfo.visitWithTypeInfo)(typeInfo, visitor), + QueryDocumentKeysToValidate, + ); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + + return errors; +} +/** @internal */ + +function validateSDL( + documentAST, + schemaToExtend, + rules = _specifiedRules.specifiedSDLRules, +) { + const errors = []; + const context = new _ValidationContext.SDLValidationContext( + documentAST, + schemaToExtend, + (error) => { + errors.push(error); + }, + ); + const visitors = rules.map((rule) => rule(context)); + (0, _visitor.visit)(documentAST, (0, _visitor.visitInParallel)(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} diff --git a/node_modules/graphql/validation/validate.mjs b/node_modules/graphql/validation/validate.mjs new file mode 100644 index 0000000000000000000000000000000000000000..091153eff366b28a09fa61f1e327b085f5e46ffe --- /dev/null +++ b/node_modules/graphql/validation/validate.mjs @@ -0,0 +1,200 @@ +/** @category Validation */ +import { devAssert } from '../jsutils/devAssert.mjs'; +import { mapValue } from '../jsutils/mapValue.mjs'; +import { GraphQLError } from '../error/GraphQLError.mjs'; +import { QueryDocumentKeys } from '../language/ast.mjs'; +import { visit, visitInParallel } from '../language/visitor.mjs'; +import { assertValidSchema } from '../type/validate.mjs'; +import { TypeInfo, visitWithTypeInfo } from '../utilities/TypeInfo.mjs'; +import { specifiedRules, specifiedSDLRules } from './specifiedRules.mjs'; +import { + SDLValidationContext, + ValidationContext, +} from './ValidationContext.mjs'; // Per the specification, descriptions must not affect validation. +// See https://spec.graphql.org/draft/#sec-Descriptions + +const QueryDocumentKeysToValidate = mapValue(QueryDocumentKeys, (keys) => + keys.filter((key) => key !== 'description'), +); +/** + * Options used when validating a GraphQL document. + * @internal + */ + +/** + * Implements the "Validation" section of the spec. + * + * Validation runs synchronously, returning an array of encountered errors, or + * an empty array if no errors were encountered and the document is valid. + * + * A list of specific validation rules may be provided. If not provided, the + * default list of rules defined by the GraphQL specification will be used. + * + * Each validation rule is a function that returns a visitor + * (see the language/visitor API). Visitor methods are expected to return + * GraphQLErrors, or Arrays of GraphQLErrors when invalid. + * + * Validate will stop validation after a `maxErrors` limit has been reached. + * Attackers can send pathologically invalid queries to induce a DoS attack, + * so `maxErrors` defaults to 100 errors. + * + * Optionally a custom TypeInfo instance may be provided. If not provided, one + * will be created from the provided schema. + * @param schema - Schema to validate against. + * @param documentAST - Document AST to validate. + * @param rules - Validation rules to apply. + * @param options - Validation options, including error limits. + * @param typeInfo - TypeInfo instance to update during traversal. + * @returns Validation errors, or an empty array when the document is valid. + * @example + * ```ts + * // Validate with the default specified rules. + * import { parse } from 'graphql/language'; + * import { buildSchema } from 'graphql/utilities'; + * import { validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * + * validate(schema, parse('{ greeting }')); // => [] + * + * const errors = validate(schema, parse('{ missing }')); + * errors[0].message; // => 'Cannot query field "missing" on type "Query".' + * ``` + * @example + * ```ts + * // This variant uses a custom rule list, TypeInfo, and validation options. + * import { parse } from 'graphql/language'; + * import { buildSchema, TypeInfo } from 'graphql/utilities'; + * import { FieldsOnCorrectTypeRule, validate } from 'graphql/validation'; + * + * const schema = buildSchema(` + * type Query { + * greeting: String + * } + * `); + * const document = parse('{ missingOne missingTwo }'); + * + * const errors = validate( + * schema, + * document, + * [FieldsOnCorrectTypeRule], + * { maxErrors: 1 }, + * new TypeInfo(schema), + * ); + * + * errors.length; // => 2 + * errors[1].message; // => 'Too many validation errors, error limit reached. Validation aborted.' + * ``` + */ +export function validate( + schema, + documentAST, + rules = specifiedRules, + options, + /** + * Deprecated TypeInfo instance used to track traversal state during + * validation. Omit this argument so validate creates the TypeInfo instance. + * @deprecated will be removed in 17.0.0 + */ + typeInfo = new TypeInfo(schema), +) { + var _options$maxErrors; + + const maxErrors = + (_options$maxErrors = + options === null || options === void 0 ? void 0 : options.maxErrors) !== + null && _options$maxErrors !== void 0 + ? _options$maxErrors + : 100; + documentAST || devAssert(false, 'Must provide document.'); // If the schema used for validation is invalid, throw an error. + + assertValidSchema(schema); + const abortObj = Object.freeze({}); + const errors = []; + const context = new ValidationContext( + schema, + documentAST, + typeInfo, + (error) => { + if (errors.length >= maxErrors) { + errors.push( + new GraphQLError( + 'Too many validation errors, error limit reached. Validation aborted.', + ), + ); // eslint-disable-next-line @typescript-eslint/no-throw-literal + + throw abortObj; + } + + errors.push(error); + }, + ); // This uses a specialized visitor which runs multiple visitors in parallel, + // while maintaining the visitor skip and break API. + + const visitor = visitInParallel(rules.map((rule) => rule(context))); // Visit the whole document with each instance of all provided rules. + + try { + visit( + documentAST, + visitWithTypeInfo(typeInfo, visitor), + QueryDocumentKeysToValidate, + ); + } catch (e) { + if (e !== abortObj) { + throw e; + } + } + + return errors; +} +/** @internal */ + +export function validateSDL( + documentAST, + schemaToExtend, + rules = specifiedSDLRules, +) { + const errors = []; + const context = new SDLValidationContext( + documentAST, + schemaToExtend, + (error) => { + errors.push(error); + }, + ); + const visitors = rules.map((rule) => rule(context)); + visit(documentAST, visitInParallel(visitors)); + return errors; +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDL(documentAST) { + const errors = validateSDL(documentAST); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} +/** + * Utility function which asserts a SDL document is valid by throwing an error + * if it is invalid. + * + * @internal + */ + +export function assertValidSDLExtension(documentAST, schema) { + const errors = validateSDL(documentAST, schema); + + if (errors.length !== 0) { + throw new Error(errors.map((error) => error.message).join('\n\n')); + } +} diff --git a/node_modules/graphql/version.d.ts b/node_modules/graphql/version.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5333b01e653c6b289d4118c7a89e07196df5c410 --- /dev/null +++ b/node_modules/graphql/version.d.ts @@ -0,0 +1,10 @@ +/** @category Version */ +/** A string containing the version of the GraphQL.js library */ +export declare const version: string; +/** An object containing the components of the GraphQL.js version string */ +export declare const versionInfo: Readonly<{ + major: number; + minor: number; + patch: number; + preReleaseTag: string | null; +}>; diff --git a/node_modules/graphql/version.js b/node_modules/graphql/version.js new file mode 100644 index 0000000000000000000000000000000000000000..f552f66949c4d2b2a30765b076b1bd33a814dda1 --- /dev/null +++ b/node_modules/graphql/version.js @@ -0,0 +1,23 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { + value: true, +}); +exports.versionInfo = exports.version = void 0; + +/** @category Version */ +// Note: This file is autogenerated using "resources/gen-version.js" script and +// automatically updated by "npm version" command. + +/** A string containing the version of the GraphQL.js library */ +const version = '16.14.2'; +/** An object containing the components of the GraphQL.js version string */ + +exports.version = version; +const versionInfo = Object.freeze({ + major: 16, + minor: 14, + patch: 2, + preReleaseTag: null, +}); +exports.versionInfo = versionInfo; diff --git a/node_modules/graphql/version.mjs b/node_modules/graphql/version.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e2d41b40ac76f0abf68f350f86aa02c5c299a8c9 --- /dev/null +++ b/node_modules/graphql/version.mjs @@ -0,0 +1,14 @@ +/** @category Version */ +// Note: This file is autogenerated using "resources/gen-version.js" script and +// automatically updated by "npm version" command. + +/** A string containing the version of the GraphQL.js library */ +export const version = '16.14.2'; +/** An object containing the components of the GraphQL.js version string */ + +export const versionInfo = Object.freeze({ + major: 16, + minor: 14, + patch: 2, + preReleaseTag: null, +}); diff --git a/node_modules/has-flag/index.d.ts b/node_modules/has-flag/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a0a48c89112785902cb109a27475840fd0952de8 --- /dev/null +++ b/node_modules/has-flag/index.d.ts @@ -0,0 +1,39 @@ +/** +Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag. + +@param flag - CLI flag to look for. The `--` prefix is optional. +@param argv - CLI arguments. Default: `process.argv`. +@returns Whether the flag exists. + +@example +``` +// $ ts-node foo.ts -f --unicorn --foo=bar -- --rainbow + +// foo.ts +import hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` +*/ +declare function hasFlag(flag: string, argv?: string[]): boolean; + +export = hasFlag; diff --git a/node_modules/has-flag/index.js b/node_modules/has-flag/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b6f80b1f8ffd7658a11af977a9df3c296008d4cd --- /dev/null +++ b/node_modules/has-flag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +module.exports = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; diff --git a/node_modules/has-flag/license b/node_modules/has-flag/license new file mode 100644 index 0000000000000000000000000000000000000000..e7af2f77107d73046421ef56c4684cbfdd3c1e89 --- /dev/null +++ b/node_modules/has-flag/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/has-flag/package.json b/node_modules/has-flag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a9cba4b856d046212a2a2f13fb911ae1deb4c3b5 --- /dev/null +++ b/node_modules/has-flag/package.json @@ -0,0 +1,46 @@ +{ + "name": "has-flag", + "version": "4.0.0", + "description": "Check if argv has a specific flag", + "license": "MIT", + "repository": "sindresorhus/has-flag", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "has", + "check", + "detect", + "contains", + "find", + "flag", + "cli", + "command-line", + "argv", + "process", + "arg", + "args", + "argument", + "arguments", + "getopt", + "minimist", + "optimist" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/has-flag/readme.md b/node_modules/has-flag/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..3f72dff29a69612c14eaec559e2a11bcced48b5b --- /dev/null +++ b/node_modules/has-flag/readme.md @@ -0,0 +1,89 @@ +# has-flag [![Build Status](https://travis-ci.org/sindresorhus/has-flag.svg?branch=master)](https://travis-ci.org/sindresorhus/has-flag) + +> Check if [`argv`](https://nodejs.org/docs/latest/api/process.html#process_process_argv) has a specific flag + +Correctly stops looking after an `--` argument terminator. + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + + +## Install + +``` +$ npm install has-flag +``` + + +## Usage + +```js +// foo.js +const hasFlag = require('has-flag'); + +hasFlag('unicorn'); +//=> true + +hasFlag('--unicorn'); +//=> true + +hasFlag('f'); +//=> true + +hasFlag('-f'); +//=> true + +hasFlag('foo=bar'); +//=> true + +hasFlag('foo'); +//=> false + +hasFlag('rainbow'); +//=> false +``` + +``` +$ node foo.js -f --unicorn --foo=bar -- --rainbow +``` + + +## API + +### hasFlag(flag, [argv]) + +Returns a boolean for whether the flag exists. + +#### flag + +Type: `string` + +CLI flag to look for. The `--` prefix is optional. + +#### argv + +Type: `string[]`
+Default: `process.argv` + +CLI arguments. + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/has-symbols/.eslintrc b/node_modules/has-symbols/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..2d9a66a8acdbacede413918d9c0c8eaaacee7457 --- /dev/null +++ b/node_modules/has-symbols/.eslintrc @@ -0,0 +1,11 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "max-statements-per-line": [2, { "max": 2 }], + "no-magic-numbers": 0, + "multiline-comment-style": 0, + } +} diff --git a/node_modules/has-symbols/.github/FUNDING.yml b/node_modules/has-symbols/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..04cf87e66ed8daa00712b7926d2ed63a9108c2ae --- /dev/null +++ b/node_modules/has-symbols/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-symbols +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-symbols/.nycrc b/node_modules/has-symbols/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..bdd626ce91477abbdd489b79988baebadbd3c897 --- /dev/null +++ b/node_modules/has-symbols/.nycrc @@ -0,0 +1,9 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-symbols/CHANGELOG.md b/node_modules/has-symbols/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..cc3cf8390d16d4568d961f93395b7d330c4ada27 --- /dev/null +++ b/node_modules/has-symbols/CHANGELOG.md @@ -0,0 +1,91 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.1.0](https://github.com/inspect-js/has-symbols/compare/v1.0.3...v1.1.0) - 2024-12-02 + +### Commits + +- [actions] update workflows [`548c0bf`](https://github.com/inspect-js/has-symbols/commit/548c0bf8c9b1235458df7a1c0490b0064647a282) +- [actions] further shard; update action deps [`bec56bb`](https://github.com/inspect-js/has-symbols/commit/bec56bb0fb44b43a786686b944875a3175cf3ff3) +- [meta] use `npmignore` to autogenerate an npmignore file [`ac81032`](https://github.com/inspect-js/has-symbols/commit/ac81032809157e0a079e5264e9ce9b6f1275777e) +- [New] add types [`6469cbf`](https://github.com/inspect-js/has-symbols/commit/6469cbff1866cfe367b2b3d181d9296ec14b2a3d) +- [actions] update rebase action to use reusable workflow [`9c9d4d0`](https://github.com/inspect-js/has-symbols/commit/9c9d4d0d8938e4b267acdf8e421f4e92d1716d72) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`adb5887`](https://github.com/inspect-js/has-symbols/commit/adb5887ca9444849b08beb5caaa9e1d42320cdfb) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `tape` [`13ec198`](https://github.com/inspect-js/has-symbols/commit/13ec198ec80f1993a87710af1606a1970b22c7cb) +- [Dev Deps] update `auto-changelog`, `core-js`, `tape` [`941be52`](https://github.com/inspect-js/has-symbols/commit/941be5248387cab1da72509b22acf3fdb223f057) +- [Tests] replace `aud` with `npm audit` [`74f49e9`](https://github.com/inspect-js/has-symbols/commit/74f49e9a9d17a443020784234a1c53ce765b3559) +- [Dev Deps] update `npmignore` [`9c0ac04`](https://github.com/inspect-js/has-symbols/commit/9c0ac0452a834f4c2a4b54044f2d6a89f17e9a70) +- [Dev Deps] add missing peer dep [`52337a5`](https://github.com/inspect-js/has-symbols/commit/52337a5621cced61f846f2afdab7707a8132cc12) + +## [v1.0.3](https://github.com/inspect-js/has-symbols/compare/v1.0.2...v1.0.3) - 2022-03-01 + +### Commits + +- [actions] use `node/install` instead of `node/run`; use `codecov` action [`518b28f`](https://github.com/inspect-js/has-symbols/commit/518b28f6c5a516cbccae30794e40aa9f738b1693) +- [meta] add `bugs` and `homepage` fields; reorder package.json [`c480b13`](https://github.com/inspect-js/has-symbols/commit/c480b13fd6802b557e1cef9749872cb5fdeef744) +- [actions] reuse common workflows [`01d0ee0`](https://github.com/inspect-js/has-symbols/commit/01d0ee0a8d97c0947f5edb73eb722027a77b2b07) +- [actions] update codecov uploader [`6424ebe`](https://github.com/inspect-js/has-symbols/commit/6424ebe86b2c9c7c3d2e9bd4413a4e4f168cb275) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`dfa7e7f`](https://github.com/inspect-js/has-symbols/commit/dfa7e7ff38b594645d8c8222aab895157fa7e282) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`0c8d436`](https://github.com/inspect-js/has-symbols/commit/0c8d43685c45189cea9018191d4fd7eca91c9d02) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`9026554`](https://github.com/inspect-js/has-symbols/commit/902655442a1bf88e72b42345494ef0c60f5d36ab) +- [readme] add actions and codecov badges [`eaa9682`](https://github.com/inspect-js/has-symbols/commit/eaa9682f990f481d3acf7a1c7600bec36f7b3adc) +- [Dev Deps] update `eslint`, `tape` [`bc7a3ba`](https://github.com/inspect-js/has-symbols/commit/bc7a3ba46f27b7743f8a2579732d59d1b9ac791e) +- [Dev Deps] update `eslint`, `auto-changelog` [`0ace00a`](https://github.com/inspect-js/has-symbols/commit/0ace00af08a88cdd1e6ce0d60357d941c60c2d9f) +- [meta] use `prepublishOnly` script for npm 7+ [`093f72b`](https://github.com/inspect-js/has-symbols/commit/093f72bc2b0ed00c781f444922a5034257bf561d) +- [Tests] test on all 16 minors [`9b80d3d`](https://github.com/inspect-js/has-symbols/commit/9b80d3d9102529f04c20ec5b1fcc6e38426c6b03) + +## [v1.0.2](https://github.com/inspect-js/has-symbols/compare/v1.0.1...v1.0.2) - 2021-02-27 + +### Fixed + +- [Fix] use a universal way to get the original Symbol [`#11`](https://github.com/inspect-js/has-symbols/issues/11) + +### Commits + +- [Tests] migrate tests to Github Actions [`90ae798`](https://github.com/inspect-js/has-symbols/commit/90ae79820bdfe7bc703d67f5f3c5e205f98556d3) +- [meta] do not publish github action workflow files [`29e60a1`](https://github.com/inspect-js/has-symbols/commit/29e60a1b7c25c7f1acf7acff4a9320d0d10c49b4) +- [Tests] run `nyc` on all tests [`8476b91`](https://github.com/inspect-js/has-symbols/commit/8476b915650d360915abe2522505abf4b0e8f0ae) +- [readme] fix repo URLs, remove defunct badges [`126288e`](https://github.com/inspect-js/has-symbols/commit/126288ecc1797c0a40247a6b78bcb2e0bc5d7036) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `core-js`, `get-own-property-symbols` [`d84bdfa`](https://github.com/inspect-js/has-symbols/commit/d84bdfa48ac5188abbb4904b42614cd6c030940a) +- [Tests] fix linting errors [`0df3070`](https://github.com/inspect-js/has-symbols/commit/0df3070b981b6c9f2ee530c09189a7f5c6def839) +- [actions] add "Allow Edits" workflow [`1e6bc29`](https://github.com/inspect-js/has-symbols/commit/1e6bc29b188f32b9648657b07eda08504be5aa9c) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` [`36cea2a`](https://github.com/inspect-js/has-symbols/commit/36cea2addd4e6ec435f35a2656b4e9ef82498e9b) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1278338`](https://github.com/inspect-js/has-symbols/commit/127833801865fbc2cc8979beb9ca869c7bfe8222) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `tape` [`1493254`](https://github.com/inspect-js/has-symbols/commit/1493254eda13db5fb8fc5e4a3e8324b3d196029d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js` [`b090bf2`](https://github.com/inspect-js/has-symbols/commit/b090bf214d3679a30edc1e2d729d466ab5183e1d) +- [actions] switch Automatic Rebase workflow to `pull_request_target` event [`4addb7a`](https://github.com/inspect-js/has-symbols/commit/4addb7ab4dc73f927ae99928d68817554fc21dc0) +- [Dev Deps] update `auto-changelog`, `tape` [`81d0baf`](https://github.com/inspect-js/has-symbols/commit/81d0baf3816096a89a8558e8043895f7a7d10d8b) +- [Dev Deps] update `auto-changelog`; add `aud` [`1a4e561`](https://github.com/inspect-js/has-symbols/commit/1a4e5612c25d91c3a03d509721d02630bc4fe3da) +- [readme] remove unused testling URLs [`3000941`](https://github.com/inspect-js/has-symbols/commit/3000941f958046e923ed8152edb1ef4a599e6fcc) +- [Tests] only audit prod deps [`692e974`](https://github.com/inspect-js/has-symbols/commit/692e9743c912410e9440207631a643a34b4741a1) +- [Dev Deps] update `@ljharb/eslint-config` [`51c946c`](https://github.com/inspect-js/has-symbols/commit/51c946c7f6baa793ec5390bb5a45cdce16b4ba76) + +## [v1.0.1](https://github.com/inspect-js/has-symbols/compare/v1.0.0...v1.0.1) - 2019-11-16 + +### Commits + +- [Tests] use shared travis-ci configs [`ce396c9`](https://github.com/inspect-js/has-symbols/commit/ce396c9419ff11c43d0da5d05cdbb79f7fb42229) +- [Tests] up to `node` `v12.4`, `v11.15`, `v10.15`, `v9.11`, `v8.15`, `v7.10`, `v6.17`, `v4.9`; use `nvm install-latest-npm` [`0690732`](https://github.com/inspect-js/has-symbols/commit/0690732801f47ab429f39ba1962f522d5c462d6b) +- [meta] add `auto-changelog` [`2163d0b`](https://github.com/inspect-js/has-symbols/commit/2163d0b7f36343076b8f947cd1667dd1750f26fc) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `core-js`, `safe-publish-latest`, `tape` [`8e0951f`](https://github.com/inspect-js/has-symbols/commit/8e0951f1a7a2e52068222b7bb73511761e6e4d9c) +- [actions] add automatic rebasing / merge commit blocking [`b09cdb7`](https://github.com/inspect-js/has-symbols/commit/b09cdb7cd7ee39e7a769878f56e2d6066f5ccd1d) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `core-js`, `get-own-property-symbols`, `tape` [`1dd42cd`](https://github.com/inspect-js/has-symbols/commit/1dd42cd86183ed0c50f99b1062345c458babca91) +- [meta] create FUNDING.yml [`aa57a17`](https://github.com/inspect-js/has-symbols/commit/aa57a17b19708906d1927f821ea8e73394d84ca4) +- Only apps should have lockfiles [`a2d8bea`](https://github.com/inspect-js/has-symbols/commit/a2d8bea23a97d15c09eaf60f5b107fcf9a4d57aa) +- [Tests] use `npx aud` instead of `nsp` or `npm audit` with hoops [`9e96cb7`](https://github.com/inspect-js/has-symbols/commit/9e96cb783746cbed0c10ef78e599a8eaa7ebe193) +- [meta] add `funding` field [`a0b32cf`](https://github.com/inspect-js/has-symbols/commit/a0b32cf68e803f963c1639b6d47b0a9d6440bab0) +- [Dev Deps] update `safe-publish-latest` [`cb9f0a5`](https://github.com/inspect-js/has-symbols/commit/cb9f0a521a3a1790f1064d437edd33bb6c3d6af0) + +## v1.0.0 - 2016-09-19 + +### Commits + +- Tests. [`ecb6eb9`](https://github.com/inspect-js/has-symbols/commit/ecb6eb934e4883137f3f93b965ba5e0a98df430d) +- package.json [`88a337c`](https://github.com/inspect-js/has-symbols/commit/88a337cee0864a0da35f5d19e69ff0ef0150e46a) +- Initial commit [`42e1e55`](https://github.com/inspect-js/has-symbols/commit/42e1e5502536a2b8ac529c9443984acd14836b1c) +- Initial implementation. [`33f5cc6`](https://github.com/inspect-js/has-symbols/commit/33f5cc6cdff86e2194b081ee842bfdc63caf43fb) +- read me [`01f1170`](https://github.com/inspect-js/has-symbols/commit/01f1170188ff7cb1558aa297f6ba5b516c6d7b0c) diff --git a/node_modules/has-symbols/LICENSE b/node_modules/has-symbols/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..df31cbf3c064d00ba5f15a3bb13c957b598b96a1 --- /dev/null +++ b/node_modules/has-symbols/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Jordan Harband + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-symbols/README.md b/node_modules/has-symbols/README.md new file mode 100644 index 0000000000000000000000000000000000000000..33905f0fc92c406715fef234ba43605c95390b30 --- /dev/null +++ b/node_modules/has-symbols/README.md @@ -0,0 +1,46 @@ +# has-symbols [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has Symbol support. Supports spec, or shams. + +## Example + +```js +var hasSymbols = require('has-symbols'); + +hasSymbols() === true; // if the environment has native Symbol support. Not polyfillable, not forgeable. + +var hasSymbolsKinda = require('has-symbols/shams'); +hasSymbolsKinda() === true; // if the environment has a Symbol sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-symbols +[2]: https://versionbadg.es/inspect-js/has-symbols.svg +[5]: https://david-dm.org/inspect-js/has-symbols.svg +[6]: https://david-dm.org/inspect-js/has-symbols +[7]: https://david-dm.org/inspect-js/has-symbols/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-symbols#info=devDependencies +[11]: https://nodei.co/npm/has-symbols.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-symbols.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-symbols.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-symbols +[codecov-image]: https://codecov.io/gh/inspect-js/has-symbols/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-symbols/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-symbols +[actions-url]: https://github.com/inspect-js/has-symbols/actions diff --git a/node_modules/has-symbols/index.d.ts b/node_modules/has-symbols/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b98595004b23ce56854e4be1181217591e34776 --- /dev/null +++ b/node_modules/has-symbols/index.d.ts @@ -0,0 +1,3 @@ +declare function hasNativeSymbols(): boolean; + +export = hasNativeSymbols; \ No newline at end of file diff --git a/node_modules/has-symbols/index.js b/node_modules/has-symbols/index.js new file mode 100644 index 0000000000000000000000000000000000000000..fa65265a9d45a38560d60c71f0a3305802c39365 --- /dev/null +++ b/node_modules/has-symbols/index.js @@ -0,0 +1,14 @@ +'use strict'; + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = require('./shams'); + +/** @type {import('.')} */ +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; diff --git a/node_modules/has-symbols/package.json b/node_modules/has-symbols/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d835e20b957be00d24b62cfc3e7243cc9f133ca2 --- /dev/null +++ b/node_modules/has-symbols/package.json @@ -0,0 +1,111 @@ +{ + "name": "has-symbols", + "version": "1.1.0", + "description": "Determine if the JS environment has Symbol support. Supports spec, or shams.", + "main": "index.js", + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "npx npm@'>=10.2' audit --production", + "tests-only": "npm run test:stock && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "postlint": "tsc -p . && attw -P", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git://github.com/inspect-js/has-symbols.git" + }, + "keywords": [ + "Symbol", + "symbols", + "typeof", + "sham", + "polyfill", + "native", + "core-js", + "ES6" + ], + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/ljharb/has-symbols/issues" + }, + "homepage": "https://github.com/ljharb/has-symbols#readme", + "devDependencies": { + "@arethetypeswrong/cli": "^0.17.0", + "@ljharb/eslint-config": "^21.1.1", + "@ljharb/tsconfig": "^0.2.0", + "@types/core-js": "^2.5.8", + "@types/tape": "^5.6.5", + "auto-changelog": "^2.5.0", + "core-js": "^2.6.12", + "encoding": "^0.1.13", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "testling": { + "files": "test/index.js", + "browsers": [ + "iexplore/6.0..latest", + "firefox/3.0..6.0", + "firefox/15.0..latest", + "firefox/nightly", + "chrome/4.0..10.0", + "chrome/20.0..latest", + "chrome/canary", + "opera/10.0..latest", + "opera/next", + "safari/4.0..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2" + ] + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "types" + ] + } +} diff --git a/node_modules/has-symbols/shams.d.ts b/node_modules/has-symbols/shams.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8d0bf2435e7e4f5d6c01058b738243f6361b186b --- /dev/null +++ b/node_modules/has-symbols/shams.d.ts @@ -0,0 +1,3 @@ +declare function hasSymbolShams(): boolean; + +export = hasSymbolShams; \ No newline at end of file diff --git a/node_modules/has-symbols/shams.js b/node_modules/has-symbols/shams.js new file mode 100644 index 0000000000000000000000000000000000000000..f97b474105d705cc4acb88c32aaf60cfb28bf6b3 --- /dev/null +++ b/node_modules/has-symbols/shams.js @@ -0,0 +1,45 @@ +'use strict'; + +/** @type {import('./shams')} */ +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; +}; diff --git a/node_modules/has-symbols/test/index.js b/node_modules/has-symbols/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..352129ca356c8ce4ba2e5e6b78c092f401e0f2da --- /dev/null +++ b/node_modules/has-symbols/test/index.js @@ -0,0 +1,22 @@ +'use strict'; + +var test = require('tape'); +var hasSymbols = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbols, 'function', 'is a function'); + t.equal(typeof hasSymbols(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbols are supported', { skip: !hasSymbols() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbols are not supported', { skip: hasSymbols() }, function (t) { + t.equal(typeof Symbol, 'undefined', 'global Symbol is undefined'); + t.equal(typeof Object.getOwnPropertySymbols, 'undefined', 'Object.getOwnPropertySymbols does not exist'); + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/core-js.js b/node_modules/has-symbols/test/shams/core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..1a29024ea215a7eefa9e372a75ac2d9c1b9e2abb --- /dev/null +++ b/node_modules/has-symbols/test/shams/core-js.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + require('core-js/fn/symbol'); + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/shams/get-own-property-symbols.js b/node_modules/has-symbols/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..e0296f8e25c8f10b0b4fbb428b8d92c04c5373a9 --- /dev/null +++ b/node_modules/has-symbols/test/shams/get-own-property-symbols.js @@ -0,0 +1,29 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error TS is stupid and doesn't know about top level return + return; +} + +var hasSymbols = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbols(), false, 'hasSymbols is false before polyfilling'); + + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasSymbolsAfter = hasSymbols(); + t.equal(hasSymbolsAfter, true, 'hasSymbols is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-symbols/test/tests.js b/node_modules/has-symbols/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..66a2cb800239b52fded1d03a2747967f17c92251 --- /dev/null +++ b/node_modules/has-symbols/test/tests.js @@ -0,0 +1,58 @@ +'use strict'; + +/** @type {(t: import('tape').Test) => false | void} */ +// eslint-disable-next-line consistent-return +module.exports = function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + + if (typeof Symbol !== 'function') { return false; } + + t.notEqual(Symbol(), Symbol(), 'two symbols are not equal'); + + /* + t.equal( + Symbol.prototype.toString.call(Symbol('foo')), + Symbol.prototype.toString.call(Symbol('foo')), + 'two symbols with the same description stringify the same' + ); + */ + + /* + var foo = Symbol('foo'); + + t.notEqual( + String(foo), + String(Symbol('bar')), + 'two symbols with different descriptions do not stringify the same' + ); + */ + + t.equal(typeof Symbol.prototype.toString, 'function', 'Symbol#toString is a function'); + // t.equal(String(foo), Symbol.prototype.toString.call(foo), 'Symbol#toString equals String of the same symbol'); + + t.equal(typeof Object.getOwnPropertySymbols, 'function', 'Object.getOwnPropertySymbols is a function'); + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + t.notEqual(typeof sym, 'string', 'Symbol is not a string'); + t.equal(Object.prototype.toString.call(sym), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + t.equal(Object.prototype.toString.call(symObj), '[object Symbol]', 'symbol primitive Object#toStrings properly'); + + var symVal = 42; + obj[sym] = symVal; + // eslint-disable-next-line no-restricted-syntax, no-unused-vars + for (var _ in obj) { t.fail('symbol property key was found in for..in of object'); } + + t.deepEqual(Object.keys(obj), [], 'no enumerable own keys on symbol-valued object'); + t.deepEqual(Object.getOwnPropertyNames(obj), [], 'no own names on symbol-valued object'); + t.deepEqual(Object.getOwnPropertySymbols(obj), [sym], 'one own symbol on symbol-valued object'); + t.equal(Object.prototype.propertyIsEnumerable.call(obj, sym), true, 'symbol is enumerable'); + t.deepEqual(Object.getOwnPropertyDescriptor(obj, sym), { + configurable: true, + enumerable: true, + value: 42, + writable: true + }, 'property descriptor is correct'); +}; diff --git a/node_modules/has-symbols/tsconfig.json b/node_modules/has-symbols/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..ba99af43fe36a32096fd9bdd451c200215f9293e --- /dev/null +++ b/node_modules/has-symbols/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "@ljharb/tsconfig", + "compilerOptions": { + "target": "ES2021", + "maxNodeModuleJsDepth": 0, + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/has-tostringtag/.eslintrc b/node_modules/has-tostringtag/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..3b5d9e90ec405f85dd7f9066656efccc51193697 --- /dev/null +++ b/node_modules/has-tostringtag/.eslintrc @@ -0,0 +1,5 @@ +{ + "root": true, + + "extends": "@ljharb", +} diff --git a/node_modules/has-tostringtag/.github/FUNDING.yml b/node_modules/has-tostringtag/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a450e70826f140f9e92de4b5bc6967db78eafca --- /dev/null +++ b/node_modules/has-tostringtag/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/has-tostringtag +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] diff --git a/node_modules/has-tostringtag/.nycrc b/node_modules/has-tostringtag/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/has-tostringtag/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/has-tostringtag/CHANGELOG.md b/node_modules/has-tostringtag/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..eb186ec601ca337a3e77d372edbdc1d560cd4294 --- /dev/null +++ b/node_modules/has-tostringtag/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v1.0.2](https://github.com/inspect-js/has-tostringtag/compare/v1.0.1...v1.0.2) - 2024-02-01 + +### Fixed + +- [Fix] move `has-symbols` back to prod deps [`#3`](https://github.com/inspect-js/has-tostringtag/issues/3) + +## [v1.0.1](https://github.com/inspect-js/has-tostringtag/compare/v1.0.0...v1.0.1) - 2024-02-01 + +### Commits + +- [patch] add types [`9276414`](https://github.com/inspect-js/has-tostringtag/commit/9276414b22fab3eeb234688841722c4be113201f) +- [meta] use `npmignore` to autogenerate an npmignore file [`5c0dcd1`](https://github.com/inspect-js/has-tostringtag/commit/5c0dcd1ff66419562a30d1fd88b966cc36bce5fc) +- [actions] reuse common workflows [`dee9509`](https://github.com/inspect-js/has-tostringtag/commit/dee950904ab5719b62cf8d73d2ac950b09093266) +- [actions] update codecov uploader [`b8cb3a0`](https://github.com/inspect-js/has-tostringtag/commit/b8cb3a0b8ffbb1593012c4c2daa45fb25642825d) +- [Tests] generate coverage [`be5b288`](https://github.com/inspect-js/has-tostringtag/commit/be5b28889e2735cdbcef387f84c2829995f2f05e) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `safe-publish-latest`, `tape` [`69a0827`](https://github.com/inspect-js/has-tostringtag/commit/69a0827974e9b877b2c75b70b057555da8f25a65) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `aud`, `auto-changelog`, `tape` [`4c9e210`](https://github.com/inspect-js/has-tostringtag/commit/4c9e210a5682f0557a3235d36b68ce809d7fb825) +- [actions] update rebase action to use reusable workflow [`ca8dcd3`](https://github.com/inspect-js/has-tostringtag/commit/ca8dcd3a6f3f5805d7e3fd461b654aedba0946e7) +- [Dev Deps] update `@ljharb/eslint-config`, `aud`, `npmignore`, `tape` [`07f3eaf`](https://github.com/inspect-js/has-tostringtag/commit/07f3eafa45dd98208c94479737da77f9a69b94c4) +- [Deps] update `has-symbols` [`999e009`](https://github.com/inspect-js/has-tostringtag/commit/999e0095a7d1749a58f55472ec8bf8108cdfdcf3) +- [Tests] remove staging tests since they fail on modern node [`9d9526b`](https://github.com/inspect-js/has-tostringtag/commit/9d9526b1dc1ca7f2292b52efda4c3d857b0e39bd) + +## v1.0.0 - 2021-08-05 + +### Commits + +- Tests [`6b6f573`](https://github.com/inspect-js/has-tostringtag/commit/6b6f5734dc2058badb300ff0783efdad95fe1a65) +- Initial commit [`2f8190e`](https://github.com/inspect-js/has-tostringtag/commit/2f8190e799fac32ba9b95a076c0255e01d7ce475) +- [meta] do not publish github action workflow files [`6e08cc4`](https://github.com/inspect-js/has-tostringtag/commit/6e08cc4e0fea7ec71ef66e70734b2af2c4a8b71b) +- readme [`94bed6c`](https://github.com/inspect-js/has-tostringtag/commit/94bed6c9560cbbfda034f8d6c260bb7b0db33c1a) +- npm init [`be67840`](https://github.com/inspect-js/has-tostringtag/commit/be67840ab92ee7adb98bcc65261975543f815fa5) +- Implementation [`c4914ec`](https://github.com/inspect-js/has-tostringtag/commit/c4914ecc51ddee692c85b471ae0a5d8123030fbf) +- [meta] use `auto-changelog` [`4aaf768`](https://github.com/inspect-js/has-tostringtag/commit/4aaf76895ae01d7b739f2b19f967ef2372506cd7) +- Only apps should have lockfiles [`bc4d99e`](https://github.com/inspect-js/has-tostringtag/commit/bc4d99e4bf494afbaa235c5f098df6e642edf724) +- [meta] add `safe-publish-latest` [`6523c05`](https://github.com/inspect-js/has-tostringtag/commit/6523c05c9b87140f3ae74c9daf91633dd9ff4e1f) diff --git a/node_modules/has-tostringtag/LICENSE b/node_modules/has-tostringtag/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7948bc02a7937478ae009ff3796e76b25bdfbb08 --- /dev/null +++ b/node_modules/has-tostringtag/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Inspect JS + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/has-tostringtag/README.md b/node_modules/has-tostringtag/README.md new file mode 100644 index 0000000000000000000000000000000000000000..67a5e929dfce41c47370c4141ed9fae8ba6aea21 --- /dev/null +++ b/node_modules/has-tostringtag/README.md @@ -0,0 +1,46 @@ +# has-tostringtag [![Version Badge][2]][1] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![dependency status][5]][6] +[![dev dependency status][7]][8] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][11]][1] + +Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams. + +## Example + +```js +var hasSymbolToStringTag = require('has-tostringtag'); + +hasSymbolToStringTag() === true; // if the environment has native Symbol.toStringTag support. Not polyfillable, not forgeable. + +var hasSymbolToStringTagKinda = require('has-tostringtag/shams'); +hasSymbolToStringTagKinda() === true; // if the environment has a Symbol.toStringTag sham that mostly follows the spec. +``` + +## Supported Symbol shams + - get-own-property-symbols [npm](https://www.npmjs.com/package/get-own-property-symbols) | [github](https://github.com/WebReflection/get-own-property-symbols) + - core-js [npm](https://www.npmjs.com/package/core-js) | [github](https://github.com/zloirock/core-js) + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[1]: https://npmjs.org/package/has-tostringtag +[2]: https://versionbadg.es/inspect-js/has-tostringtag.svg +[5]: https://david-dm.org/inspect-js/has-tostringtag.svg +[6]: https://david-dm.org/inspect-js/has-tostringtag +[7]: https://david-dm.org/inspect-js/has-tostringtag/dev-status.svg +[8]: https://david-dm.org/inspect-js/has-tostringtag#info=devDependencies +[11]: https://nodei.co/npm/has-tostringtag.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/has-tostringtag.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/has-tostringtag.svg +[downloads-url]: https://npm-stat.com/charts.html?package=has-tostringtag +[codecov-image]: https://codecov.io/gh/inspect-js/has-tostringtag/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/has-tostringtag/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/has-tostringtag +[actions-url]: https://github.com/inspect-js/has-tostringtag/actions diff --git a/node_modules/has-tostringtag/index.d.ts b/node_modules/has-tostringtag/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a61bc60a86c3c7149b6fcef29c4826d2ee404235 --- /dev/null +++ b/node_modules/has-tostringtag/index.d.ts @@ -0,0 +1,3 @@ +declare function hasToStringTag(): boolean; + +export = hasToStringTag; diff --git a/node_modules/has-tostringtag/index.js b/node_modules/has-tostringtag/index.js new file mode 100644 index 0000000000000000000000000000000000000000..77bfa00702851e245eaca0b4bb197075e4afd9a9 --- /dev/null +++ b/node_modules/has-tostringtag/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var hasSymbols = require('has-symbols'); + +/** @type {import('.')} */ +module.exports = function hasToStringTag() { + return hasSymbols() && typeof Symbol.toStringTag === 'symbol'; +}; diff --git a/node_modules/has-tostringtag/package.json b/node_modules/has-tostringtag/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e5b0300258950d1cd622fc5367ddf50717278ce0 --- /dev/null +++ b/node_modules/has-tostringtag/package.json @@ -0,0 +1,108 @@ +{ + "name": "has-tostringtag", + "version": "1.0.2", + "author": { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + }, + "contributors": [ + { + "name": "Jordan Harband", + "email": "ljharb@gmail.com", + "url": "http://ljharb.codes" + } + ], + "description": "Determine if the JS environment has `Symbol.toStringTag` support. Supports spec, or shams.", + "license": "MIT", + "main": "index.js", + "types": "./index.d.ts", + "exports": { + ".": [ + { + "types": "./index.d.ts", + "default": "./index.js" + }, + "./index.js" + ], + "./shams": [ + { + "types": "./shams.d.ts", + "default": "./shams.js" + }, + "./shams.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublishOnly": "safe-publish-latest", + "prepublish": "not-in-publish || npm run prepublishOnly", + "pretest": "npm run --silent lint", + "test": "npm run tests-only", + "posttest": "aud --production", + "tests-only": "npm run test:stock && npm run test:shams", + "test:stock": "nyc node test", + "test:staging": "nyc node --harmony --es-staging test", + "test:shams": "npm run --silent test:shams:getownpropertysymbols && npm run --silent test:shams:corejs", + "test:shams:corejs": "nyc node test/shams/core-js.js", + "test:shams:getownpropertysymbols": "nyc node test/shams/get-own-property-symbols.js", + "lint": "eslint --ext=js,mjs .", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/has-tostringtag.git" + }, + "bugs": { + "url": "https://github.com/inspect-js/has-tostringtag/issues" + }, + "homepage": "https://github.com/inspect-js/has-tostringtag#readme", + "keywords": [ + "javascript", + "ecmascript", + "symbol", + "symbols", + "tostringtag", + "Symbol.toStringTag" + ], + "devDependencies": { + "@ljharb/eslint-config": "^21.1.0", + "@types/has-symbols": "^1.0.2", + "@types/tape": "^5.6.4", + "aud": "^2.0.4", + "auto-changelog": "^2.4.0", + "core-js": "^2.6.12", + "eslint": "=8.8.0", + "get-own-property-symbols": "^0.9.5", + "in-publish": "^2.0.1", + "npmignore": "^0.3.1", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.7.4", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows" + ] + }, + "dependencies": { + "has-symbols": "^1.0.3" + } +} diff --git a/node_modules/has-tostringtag/shams.d.ts b/node_modules/has-tostringtag/shams.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ea4aeecfd04c4c0b3dc79389754968cf1e201c06 --- /dev/null +++ b/node_modules/has-tostringtag/shams.d.ts @@ -0,0 +1,3 @@ +declare function hasToStringTagShams(): boolean; + +export = hasToStringTagShams; diff --git a/node_modules/has-tostringtag/shams.js b/node_modules/has-tostringtag/shams.js new file mode 100644 index 0000000000000000000000000000000000000000..809580dbd6a347bb63b22eb116a14e32bcd64cda --- /dev/null +++ b/node_modules/has-tostringtag/shams.js @@ -0,0 +1,8 @@ +'use strict'; + +var hasSymbols = require('has-symbols/shams'); + +/** @type {import('.')} */ +module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; +}; diff --git a/node_modules/has-tostringtag/test/index.js b/node_modules/has-tostringtag/test/index.js new file mode 100644 index 0000000000000000000000000000000000000000..0679afdfa78bffebe91fda3023491bba375b53a6 --- /dev/null +++ b/node_modules/has-tostringtag/test/index.js @@ -0,0 +1,21 @@ +'use strict'; + +var test = require('tape'); +var hasSymbolToStringTag = require('../'); +var runSymbolTests = require('./tests'); + +test('interface', function (t) { + t.equal(typeof hasSymbolToStringTag, 'function', 'is a function'); + t.equal(typeof hasSymbolToStringTag(), 'boolean', 'returns a boolean'); + t.end(); +}); + +test('Symbol.toStringTag exists', { skip: !hasSymbolToStringTag() }, function (t) { + runSymbolTests(t); + t.end(); +}); + +test('Symbol.toStringTag does not exist', { skip: hasSymbolToStringTag() }, function (t) { + t.equal(typeof Symbol === 'undefined' ? 'undefined' : typeof Symbol.toStringTag, 'undefined', 'global Symbol.toStringTag is undefined'); + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/core-js.js b/node_modules/has-tostringtag/test/shams/core-js.js new file mode 100644 index 0000000000000000000000000000000000000000..7ab214da3433e437bbd54ce422e389e88c01c1f7 --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/core-js.js @@ -0,0 +1,31 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol') { + test('has native Symbol.toStringTag support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol.toStringTag, 'symbol'); + t.end(); + }); + // @ts-expect-error CJS has top-level return + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + // @ts-expect-error no types defined + require('core-js/fn/symbol'); + // @ts-expect-error no types defined + require('core-js/fn/symbol/to-string-tag'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js new file mode 100644 index 0000000000000000000000000000000000000000..c8af44c522e5067c08511d5171f7e037f615e3d2 --- /dev/null +++ b/node_modules/has-tostringtag/test/shams/get-own-property-symbols.js @@ -0,0 +1,30 @@ +'use strict'; + +var test = require('tape'); + +if (typeof Symbol === 'function' && typeof Symbol() === 'symbol') { + test('has native Symbol support', function (t) { + t.equal(typeof Symbol, 'function'); + t.equal(typeof Symbol(), 'symbol'); + t.end(); + }); + // @ts-expect-error CJS has top-level return + return; +} + +var hasSymbolToStringTag = require('../../shams'); + +test('polyfilled Symbols', function (t) { + /* eslint-disable global-require */ + t.equal(hasSymbolToStringTag(), false, 'hasSymbolToStringTag is false before polyfilling'); + + // @ts-expect-error no types defined + require('get-own-property-symbols'); + + require('../tests')(t); + + var hasToStringTagAfter = hasSymbolToStringTag(); + t.equal(hasToStringTagAfter, true, 'hasSymbolToStringTag is true after polyfilling'); + /* eslint-enable global-require */ + t.end(); +}); diff --git a/node_modules/has-tostringtag/test/tests.js b/node_modules/has-tostringtag/test/tests.js new file mode 100644 index 0000000000000000000000000000000000000000..2aa0d48877e45a58bf4b421ff7a110f529dbd0a0 --- /dev/null +++ b/node_modules/has-tostringtag/test/tests.js @@ -0,0 +1,15 @@ +'use strict'; + +// eslint-disable-next-line consistent-return +module.exports = /** @type {(t: import('tape').Test) => void | false} */ function runSymbolTests(t) { + t.equal(typeof Symbol, 'function', 'global Symbol is a function'); + t.ok(Symbol.toStringTag, 'Symbol.toStringTag exists'); + + if (typeof Symbol !== 'function' || !Symbol.toStringTag) { return false; } + + /** @type {{ [Symbol.toStringTag]?: 'test'}} */ + var obj = {}; + obj[Symbol.toStringTag] = 'test'; + + t.equal(Object.prototype.toString.call(obj), '[object test]'); +}; diff --git a/node_modules/has-tostringtag/tsconfig.json b/node_modules/has-tostringtag/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..2002ce5a53532769b9b5bc561dac11518c384d13 --- /dev/null +++ b/node_modules/has-tostringtag/tsconfig.json @@ -0,0 +1,49 @@ +{ + "compilerOptions": { + /* Visit https://aka.ms/tsconfig to read more about this file */ + + /* Projects */ + + /* Language and Environment */ + "target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ + // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ + // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ + "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ + // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ + + /* Modules */ + "module": "commonjs", /* Specify what module code is generated. */ + // "rootDir": "./", /* Specify the root folder within your source files. */ + // "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */ + // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ + // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ + // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ + "typeRoots": ["types"], /* Specify multiple folders that act like './node_modules/@types'. */ + "resolveJsonModule": true, /* Enable importing .json files. */ + // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */ + + /* JavaScript Support */ + "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ + "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ + "maxNodeModuleJsDepth": 0, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ + + /* Emit */ + "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ + "declarationMap": true, /* Create sourcemaps for d.ts files. */ + "noEmit": true, /* Disable emitting files from a compilation. */ + + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ + "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ + "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ + + /* Type Checking */ + "strict": true, /* Enable all strict type-checking options. */ + + /* Completeness */ + //"skipLibCheck": true /* Skip type checking all .d.ts files. */ + }, + "exclude": [ + "coverage" + ] +} diff --git a/node_modules/hasown/.github/FUNDING.yml b/node_modules/hasown/.github/FUNDING.yml new file mode 100644 index 0000000000000000000000000000000000000000..d68c8b716ff04186cd4c0ed8f85af474cfbfbc6a --- /dev/null +++ b/node_modules/hasown/.github/FUNDING.yml @@ -0,0 +1,12 @@ +# These are supported funding model platforms + +github: [ljharb] +patreon: # Replace with a single Patreon username +open_collective: # Replace with a single Open Collective username +ko_fi: # Replace with a single Ko-fi username +tidelift: npm/hasown +community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry +liberapay: # Replace with a single Liberapay username +issuehunt: # Replace with a single IssueHunt username +otechie: # Replace with a single Otechie username +custom: # Replace with a single custom sponsorship URL diff --git a/node_modules/hasown/.nycrc b/node_modules/hasown/.nycrc new file mode 100644 index 0000000000000000000000000000000000000000..1826526e091b89c896e7099ccd891db79165e329 --- /dev/null +++ b/node_modules/hasown/.nycrc @@ -0,0 +1,13 @@ +{ + "all": true, + "check-coverage": false, + "reporter": ["text-summary", "text", "html", "json"], + "lines": 86, + "statements": 85.93, + "functions": 82.43, + "branches": 76.06, + "exclude": [ + "coverage", + "test" + ] +} diff --git a/node_modules/hasown/CHANGELOG.md b/node_modules/hasown/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..90a43dc309b047ad27d1efee6c1f08c6d522583f --- /dev/null +++ b/node_modules/hasown/CHANGELOG.md @@ -0,0 +1,58 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v2.0.4](https://github.com/inspect-js/hasOwn/compare/v2.0.3...v2.0.4) - 2026-05-28 + +### Commits + +- [types] drop the dead key-narrowing overload [`fdab00e`](https://github.com/inspect-js/hasOwn/commit/fdab00e2703e65411424e19bf86a7e72a8f10da9) +- [Dev Deps] update `@ljharb/eslint-config`, `auto-changelog`, `eslint` [`91f6247`](https://github.com/inspect-js/hasOwn/commit/91f624768dd0f7db0d019b89d4d86bd66e20ec30) + +## [v2.0.3](https://github.com/inspect-js/hasOwn/compare/v2.0.2...v2.0.3) - 2026-04-17 + +### Commits + +- [actions] update workflows [`fb837b8`](https://github.com/inspect-js/hasOwn/commit/fb837b849bcdb8416fdc8fd344edfacd5574696c) +- [Dev Deps] update `@arethetypeswrong/cli`, `@ljharb/eslint-config`, `@ljharb/tsconfig`, `@types/tape`, `auto-changelog`, `eslint`, `mock-property`, `npmignore`, `tape` [`f4b279b`](https://github.com/inspect-js/hasOwn/commit/f4b279bd682be34b3f0ede2a58d4e8acb58d6d47) +- [Dev Deps] update `eslint`, `@ljharb/eslint-config`; migrate to flat config [`7e415ce`](https://github.com/inspect-js/hasOwn/commit/7e415cee55ebf43b3c34d7fd86db73a9928b05f7) +- [Dev Deps] update `eslint` [`ef313da`](https://github.com/inspect-js/hasOwn/commit/ef313da342d33b60e23e738b9f5a86f6065f39ef) +- [meta] use `npm audit` instead of `aud` [`d5c6d4d`](https://github.com/inspect-js/hasOwn/commit/d5c6d4d7a19c6ca4f14ac173b30d8bf25abcabee) +- [types] add overload that narrows the key [`cc03a09`](https://github.com/inspect-js/hasOwn/commit/cc03a097e9402fb8b86d413050e67f790dd6c8c5) + +## [v2.0.2](https://github.com/inspect-js/hasOwn/compare/v2.0.1...v2.0.2) - 2024-03-10 + +### Commits + +- [types] use shared config [`68e9d4d`](https://github.com/inspect-js/hasOwn/commit/68e9d4dab6facb4f05f02c6baea94a3f2a4e44b2) +- [actions] remove redundant finisher; use reusable workflow [`241a68e`](https://github.com/inspect-js/hasOwn/commit/241a68e13ea1fe52bec5ba7f74144befc31fae7b) +- [Tests] increase coverage [`4125c0d`](https://github.com/inspect-js/hasOwn/commit/4125c0d6121db56ae30e38346dfb0c000b04f0a7) +- [Tests] skip `npm ls` in old node due to TS [`01b9282`](https://github.com/inspect-js/hasOwn/commit/01b92822f9971dea031eafdd14767df41d61c202) +- [types] improve predicate type [`d340f85`](https://github.com/inspect-js/hasOwn/commit/d340f85ce02e286ef61096cbbb6697081d40a12b) +- [Dev Deps] update `tape` [`70089fc`](https://github.com/inspect-js/hasOwn/commit/70089fcf544e64acc024cbe60f5a9b00acad86de) +- [Tests] use `@arethetypeswrong/cli` [`50b272c`](https://github.com/inspect-js/hasOwn/commit/50b272c829f40d053a3dd91c9796e0ac0b2af084) + +## [v2.0.1](https://github.com/inspect-js/hasOwn/compare/v2.0.0...v2.0.1) - 2024-02-10 + +### Commits + +- [types] use a handwritten d.ts file; fix exported type [`012b989`](https://github.com/inspect-js/hasOwn/commit/012b9898ccf91dc441e2ebf594ff70270a5fda58) +- [Dev Deps] update `@types/function-bind`, `@types/mock-property`, `@types/tape`, `aud`, `mock-property`, `npmignore`, `tape`, `typescript` [`977a56f`](https://github.com/inspect-js/hasOwn/commit/977a56f51a1f8b20566f3c471612137894644025) +- [meta] add `sideEffects` flag [`3a60b7b`](https://github.com/inspect-js/hasOwn/commit/3a60b7bf42fccd8c605e5f145a6fcc83b13cb46f) + +## [v2.0.0](https://github.com/inspect-js/hasOwn/compare/v1.0.1...v2.0.0) - 2023-10-19 + +### Commits + +- revamped implementation, tests, readme [`72bf8b3`](https://github.com/inspect-js/hasOwn/commit/72bf8b338e77a638f0a290c63ffaed18339c36b4) +- [meta] revamp package.json [`079775f`](https://github.com/inspect-js/hasOwn/commit/079775fb1ec72c1c6334069593617a0be3847458) +- Only apps should have lockfiles [`6640e23`](https://github.com/inspect-js/hasOwn/commit/6640e233d1bb8b65260880f90787637db157d215) + +## v1.0.1 - 2023-10-10 + +### Commits + +- Initial commit [`8dbfde6`](https://github.com/inspect-js/hasOwn/commit/8dbfde6e8fb0ebb076fab38d138f2984eb340a62) diff --git a/node_modules/hasown/LICENSE b/node_modules/hasown/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0314929078de8a733a0af9c8ba5bc00aca094cc9 --- /dev/null +++ b/node_modules/hasown/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Jordan Harband and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/hasown/README.md b/node_modules/hasown/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f759b8a8396e3993fb7901d7551d38ee2a786b31 --- /dev/null +++ b/node_modules/hasown/README.md @@ -0,0 +1,40 @@ +# hasown [![Version Badge][npm-version-svg]][package-url] + +[![github actions][actions-image]][actions-url] +[![coverage][codecov-image]][codecov-url] +[![License][license-image]][license-url] +[![Downloads][downloads-image]][downloads-url] + +[![npm badge][npm-badge-png]][package-url] + +A robust, ES3 compatible, "has own property" predicate. + +## Example + +```js +const assert = require('assert'); +const hasOwn = require('hasown'); + +assert.equal(hasOwn({}, 'toString'), false); +assert.equal(hasOwn([], 'length'), true); +assert.equal(hasOwn({ a: 42 }, 'a'), true); +``` + +## Tests +Simply clone the repo, `npm install`, and run `npm test` + +[package-url]: https://npmjs.org/package/hasown +[npm-version-svg]: https://versionbadg.es/inspect-js/hasown.svg +[deps-svg]: https://david-dm.org/inspect-js/hasOwn.svg +[deps-url]: https://david-dm.org/inspect-js/hasOwn +[dev-deps-svg]: https://david-dm.org/inspect-js/hasOwn/dev-status.svg +[dev-deps-url]: https://david-dm.org/inspect-js/hasOwn#info=devDependencies +[npm-badge-png]: https://nodei.co/npm/hasown.png?downloads=true&stars=true +[license-image]: https://img.shields.io/npm/l/hasown.svg +[license-url]: LICENSE +[downloads-image]: https://img.shields.io/npm/dm/hasown.svg +[downloads-url]: https://npm-stat.com/charts.html?package=hasown +[codecov-image]: https://codecov.io/gh/inspect-js/hasOwn/branch/main/graphs/badge.svg +[codecov-url]: https://app.codecov.io/gh/inspect-js/hasOwn/ +[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/inspect-js/hasOwn +[actions-url]: https://github.com/inspect-js/hasOwn/actions diff --git a/node_modules/hasown/eslint.config.mjs b/node_modules/hasown/eslint.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..3d634a0969b313e68694b29530cd777f1d0616b2 --- /dev/null +++ b/node_modules/hasown/eslint.config.mjs @@ -0,0 +1,6 @@ +import ljharbConfig from '@ljharb/eslint-config/flat'; + +export default [ + ...ljharbConfig, + { rules: { 'no-extra-parens': 'off' } }, +]; diff --git a/node_modules/hasown/index.d.ts b/node_modules/hasown/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..aafdf3b2b8f0ef01aa1b3e44596560eee3f38ff7 --- /dev/null +++ b/node_modules/hasown/index.d.ts @@ -0,0 +1,3 @@ +declare function hasOwn(o: O, p: K): o is O & Record; + +export = hasOwn; diff --git a/node_modules/hasown/index.js b/node_modules/hasown/index.js new file mode 100644 index 0000000000000000000000000000000000000000..34e60591349679d8cbdb1033a60eb5d171d7637e --- /dev/null +++ b/node_modules/hasown/index.js @@ -0,0 +1,8 @@ +'use strict'; + +var call = Function.prototype.call; +var $hasOwn = Object.prototype.hasOwnProperty; +var bind = require('function-bind'); + +/** @type {import('.')} */ +module.exports = bind.call(call, $hasOwn); diff --git a/node_modules/hasown/package.json b/node_modules/hasown/package.json new file mode 100644 index 0000000000000000000000000000000000000000..fb86cc3743bf6d1bc3ef39a0e980878b6bd07aa3 --- /dev/null +++ b/node_modules/hasown/package.json @@ -0,0 +1,91 @@ +{ + "name": "hasown", + "version": "2.0.4", + "description": "A robust, ES3 compatible, \"has own property\" predicate.", + "main": "index.js", + "exports": { + ".": "./index.js", + "./package.json": "./package.json" + }, + "types": "index.d.ts", + "sideEffects": false, + "scripts": { + "prepack": "npmignore --auto --commentLines=autogenerated", + "prepublish": "not-in-publish || npm run prepublishOnly", + "prepublishOnly": "safe-publish-latest", + "prelint": "evalmd README.md", + "lint": "eslint .", + "postlint": "npm run tsc", + "pretest": "npm run lint", + "tsc": "tsc -p .", + "posttsc": "attw -P", + "tests-only": "nyc tape 'test/**/*.js'", + "test": "npm run tests-only", + "posttest": "npx npm@\">= 10.2\" audit --production", + "version": "auto-changelog && git add CHANGELOG.md", + "postversion": "auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\"" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/inspect-js/hasOwn.git" + }, + "keywords": [ + "has", + "hasOwnProperty", + "hasOwn", + "has-own", + "own", + "has", + "property", + "in", + "javascript", + "ecmascript" + ], + "author": "Jordan Harband ", + "license": "MIT", + "bugs": { + "url": "https://github.com/inspect-js/hasOwn/issues" + }, + "homepage": "https://github.com/inspect-js/hasOwn#readme", + "dependencies": { + "function-bind": "^1.1.2" + }, + "devDependencies": { + "@arethetypeswrong/cli": "^0.18.2", + "@ljharb/eslint-config": "^22.2.3", + "@ljharb/tsconfig": "^0.3.2", + "@types/function-bind": "^1.1.10", + "@types/tape": "^5.8.1", + "auto-changelog": "^2.5.1", + "eslint": "^10.4.0", + "evalmd": "^0.0.19", + "in-publish": "^2.0.1", + "jiti": "^0.0.0", + "mock-property": "^1.1.0", + "npmignore": "^0.3.5", + "nyc": "^10.3.2", + "safe-publish-latest": "^2.0.0", + "tape": "^5.9.0", + "typescript": "next" + }, + "engines": { + "node": ">= 0.4" + }, + "testling": { + "files": "test/index.js" + }, + "auto-changelog": { + "output": "CHANGELOG.md", + "template": "keepachangelog", + "unreleased": false, + "commitLimit": false, + "backfillLimit": false, + "hideCredit": true + }, + "publishConfig": { + "ignore": [ + ".github/workflows", + "test" + ] + } +} diff --git a/node_modules/hasown/tsconfig.json b/node_modules/hasown/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..0930c565850326810b8efe09ca98895aeffd8f21 --- /dev/null +++ b/node_modules/hasown/tsconfig.json @@ -0,0 +1,6 @@ +{ + "extends": "@ljharb/tsconfig", + "exclude": [ + "coverage", + ], +} diff --git a/node_modules/headers-polyfill/LICENSE b/node_modules/headers-polyfill/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f1314ab0e19339e67ca87d7a650cfd4ca3eed891 --- /dev/null +++ b/node_modules/headers-polyfill/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2020–present Artem Zakharchenko + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/headers-polyfill/README.md b/node_modules/headers-polyfill/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5cbb3a35aaf78511f500b2c581ceacd774881884 --- /dev/null +++ b/node_modules/headers-polyfill/README.md @@ -0,0 +1,204 @@ +[![Published version](https://img.shields.io/npm/v/headers-polyfill.svg)](https://www.npmjs.com/package/headers-polyfill) + +# `headers-polyfill` + +A `Headers` class polyfill and transformation library. + +## Motivation + +Various request issuing libraries utilize a different format of headers. This library chooses the [`Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) instance as the middle-ground between server and client, and provides functions to convert that instance to primitives and vice-versa. + +## Install + +```bash +npm install headers-polyfill +``` + +## Polyfill + +This package exports the `Headers` class that polyfills the native [`window.Headers`](https://developer.mozilla.org/en-US/docs/Web/API/Headers) implementation. This allows you to construct and manage headers using the same API in non-browser environments. + +```js +import { Headers } from 'headers-polyfill' + +const headers = new Headers({ + Accept: '*/*', + 'Content-Type': 'application/json', +}) + +headers.get('accept') // "*/*" +``` + +## Methods + +The `Headers` polyfill instance supports the same methods as the standard `Headers` instance: + +- [`.has()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/has) +- [`.get()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/get) +- [`.set()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/set) +- [`.append()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/append) +- [`.delete()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/delete) +- [`.forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/forEach) +- [`.getSetCookie()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/getSetCookie) + +As well as the iterator methods: + +- [`.keys()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/keys) +- [`.values()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/values) +- [`.entries()`](https://developer.mozilla.org/en-US/docs/Web/API/Headers/entries) + +## Transformations + +### `getRawHeaders()` + +Returns an object consisting of the header name/value pairs but preserving raw header names. + +```js +const headers = new Headers({ + Accept: '*/*', + 'Content-Type': 'application/json', +}) + +headers.raw() +// { "Accept": "*/*", "Content-Type": "application/json" } +``` + +### Headers ⭢ N + +- `headersToString: (h: Headers): string` + +```js +import { headersToString } from 'headers-polyfill' + +headersToString( + new Headers({ + connection: 'keep-alive', + 'content-type': ['text/plain', 'image/png'], + }) +) +// connetion: keep-alive +// content-type: text/plain, image/png +``` + +- `headersToList: (h: Headers): Array<[string, string | string[]]>` + +```js +import { headersToList } from 'headers-polyfill' + +headersToList( + new Headers({ + connection: 'keep-alive', + 'content-type': ['text/plain', 'image/png'], + }) +) +// [['connection', 'keep-alive'], ['content-type', ['text/plain', 'image/png']]] +``` + +- `headersToObject: (h: Headers): Record` + +```js +import { headersToObject } from 'headers-polyfill' + +headersToObject( + new Headers({ + connection: 'keep-alive', + 'content-type': ['text/plain', 'image/png'], + }) +) +// { connection: 'keep-alive', 'content-type': ['text/plain', 'image/png'] } +``` + +### N ⭢ Headers + +- `stringToHeaders: (s: string): Headers` + +```js +import { stringToHeaders } from 'headers-polyfill' + + +const stringToHeaders(` +connection: keep-alive +content-type: text/plain, image/png +`) +// Headers { connection: 'keep-alive', 'content-type': ['text/plain', 'image/png'] } +``` + +- `listToHeaders: (l: Array<[string, string | string[]]>): Headers` + +```js +import { listToHeaders } from 'headers-polyfill' + +listToHeaders([ + ['connection', 'keep-alive'], + ['content-type', ['text/plain', 'image/png']], +]) +// Headers { connection: 'keep-alive', 'content-type': ['text/plain', 'image/png'] } +``` + +- `objectToHeaders: (o: Record): Headers` + +```js +import { objectToHeaders } from 'headers-polyfill' + +objectToHeaders({ + connection: 'keep-alive', + 'content-type': ['text/plain', 'image/png'], +}) +// Headers { connection: 'keep-alive', 'content-type': ['text/plain', 'image/png'] } +``` + +--- + +## Utilities + +- `reduceHeadersObject: (o: Record, reducer: (acc: R, name: string, value: string | string[]) => R) => R` + +```js +import { reduceHeadersObject } from 'headers-polyfill' + +reduceHeadersObject < + HeadersObject > + ({ + Accept: '*/*', + 'Content-Type': ['application/json', 'text/plain'], + }, + (headers, name, value) => { + headers[name.toLowerCase()] = value + return headers + }, + {}) +// { 'accept': '*/*', 'content-type': ['application/json', 'text/plain'] } +``` + +- `appendHeader: (o: Record, n: string, v: string | string[]): Record` + +```js +import { appendHeader } from 'headers-polyfill' + +appendHeader( + { 'content-type': 'application/json' }, + 'content-type', + 'text/plain' +) +// { 'content-type': ['application/json', 'text/plain']} +``` + +- `flattenHeadersList: (l: Array<[string, string | string[]]>): Array` + +```js +import { flattenHeadersList } from 'headers-polyfill' + +flattenHeadersList([['content-type', ['text/plain', 'image/png']]]) +// ['content-type', 'text/plain, image/png'] +``` + +- `flattenHeadersObject: (o: Record): Record` + +```js +import { flattenHeadersObject } from 'headers-polyfill' + +flattenHeadersObject({ + 'content-type': ['text/plain', 'image/png'], +}) +// { 'content-type': 'text/plain, image/png' } +``` diff --git a/node_modules/headers-polyfill/lib/index.cjs b/node_modules/headers-polyfill/lib/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..c1e8646f0da0cfad0bfdc6fb8be97f649826c299 --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.cjs @@ -0,0 +1,303 @@ +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +let set_cookie_parser = require("set-cookie-parser"); +//#region src/utils/normalizeHeaderName.ts +const HEADERS_INVALID_CHARACTERS = /[^a-z0-9\-#$%&'*+.^_`|~]/i; +function normalizeHeaderName(name) { + if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === "") throw new TypeError("Invalid character in header field name"); + return name.trim().toLowerCase(); +} +//#endregion +//#region src/utils/normalizeHeaderValue.ts +const charCodesToRemove = [ + String.fromCharCode(10), + String.fromCharCode(13), + String.fromCharCode(9), + String.fromCharCode(32) +]; +const HEADER_VALUE_REMOVE_REGEXP = new RegExp(`(^[${charCodesToRemove.join("")}]|$[${charCodesToRemove.join("")}])`, "g"); +/** +* Normalize the given header value. +* @see https://fetch.spec.whatwg.org/#concept-header-value-normalize +*/ +function normalizeHeaderValue(value) { + return value.replace(HEADER_VALUE_REMOVE_REGEXP, ""); +} +//#endregion +//#region src/utils/isValidHeaderName.ts +/** +* Validate the given header name. +* @see https://fetch.spec.whatwg.org/#header-name +*/ +function isValidHeaderName(value) { + if (typeof value !== "string") return false; + if (value.length === 0) return false; + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i); + if (character > 127 || !isToken(character)) return false; + } + return true; +} +function isToken(value) { + return ![ + 127, + 32, + "(", + ")", + "<", + ">", + "@", + ",", + ";", + ":", + "\\", + "\"", + "/", + "[", + "]", + "?", + "=", + "{", + "}" + ].includes(value); +} +//#endregion +//#region src/utils/isValidHeaderValue.ts +/** +* Validate the given header value. +* @see https://fetch.spec.whatwg.org/#header-value +*/ +function isValidHeaderValue(value) { + if (typeof value !== "string") return false; + if (value.trim() !== value) return false; + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i); + if (character === 0 || character === 10 || character === 13) return false; + } + return true; +} +//#endregion +//#region src/Headers.ts +let _Symbol$toStringTag; +const NORMALIZED_HEADERS = Symbol("normalizedHeaders"); +const RAW_HEADER_NAMES = Symbol("rawHeaderNames"); +const HEADER_VALUE_DELIMITER = ", "; +var Headers = class Headers { + constructor(init) { + this[NORMALIZED_HEADERS] = {}; + this[RAW_HEADER_NAMES] = /* @__PURE__ */ new Map(); + this[_Symbol$toStringTag] = "Headers"; + /** + * @note Cannot necessarily check if the `init` is an instance of the + * `Headers` because that class may not be defined in Node or jsdom. + */ + if (["Headers", "HeadersPolyfill"].includes(init?.constructor?.name) || init instanceof Headers || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) init.forEach((value, name) => { + this.append(name, value); + }, this); + else if (Array.isArray(init)) init.forEach(([name, value]) => { + this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value); + }); + else if (init) Object.getOwnPropertyNames(init).forEach((name) => { + const value = init[name]; + this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value); + }); + } + [(_Symbol$toStringTag = Symbol.toStringTag, Symbol.iterator)]() { + return this.entries(); + } + *keys() { + for (const [name] of this.entries()) yield name; + } + *values() { + for (const [, value] of this.entries()) yield value; + } + *entries() { + let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => a.localeCompare(b)); + for (const name of sortedKeys) if (name === "set-cookie") for (const value of this.getSetCookie()) yield [name, value]; + else yield [name, this.get(name)]; + } + /** + * Returns a boolean stating whether a `Headers` object contains a certain header. + */ + has(name) { + if (!isValidHeaderName(name)) throw new TypeError(`Invalid header name "${name}"`); + return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name)); + } + /** + * Returns a `ByteString` sequence of all the values of a header with a given name. + */ + get(name) { + if (!isValidHeaderName(name)) throw TypeError(`Invalid header name "${name}"`); + return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null; + } + /** + * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + set(name, value) { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return; + const normalizedName = normalizeHeaderName(name); + const normalizedValue = normalizeHeaderValue(value); + this[NORMALIZED_HEADERS][normalizedName] = normalizeHeaderValue(normalizedValue); + this[RAW_HEADER_NAMES].set(normalizedName, name); + } + /** + * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + append(name, value) { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return; + const normalizedName = normalizeHeaderName(name); + const normalizedValue = normalizeHeaderValue(value); + let resolvedValue = this.has(normalizedName) ? `${this.get(normalizedName)}, ${normalizedValue}` : normalizedValue; + this.set(name, resolvedValue); + } + /** + * Deletes a header from the `Headers` object. + */ + delete(name) { + if (!isValidHeaderName(name)) return; + if (!this.has(name)) return; + const normalizedName = normalizeHeaderName(name); + delete this[NORMALIZED_HEADERS][normalizedName]; + this[RAW_HEADER_NAMES].delete(normalizedName); + } + /** + * Traverses the `Headers` object, + * calling the given callback for each header. + */ + forEach(callback, thisArg) { + for (const [name, value] of this.entries()) callback.call(thisArg, value, name, this); + } + /** + * Returns an array containing the values + * of all Set-Cookie headers associated + * with a response + */ + getSetCookie() { + const setCookieHeader = this.get("set-cookie"); + if (setCookieHeader === null) return []; + if (setCookieHeader === "") return [""]; + return (0, set_cookie_parser.splitCookiesString)(setCookieHeader); + } +}; +//#endregion +//#region src/getRawHeaders.ts +/** +* Returns the object of all raw headers. +*/ +function getRawHeaders(headers) { + const rawHeaders = {}; + for (const [name, value] of headers.entries()) rawHeaders[headers[RAW_HEADER_NAMES].get(name)] = value; + return rawHeaders; +} +//#endregion +//#region src/transformers/headersToList.ts +function headersToList(headers) { + const headersList = []; + headers.forEach((value, name) => { + const resolvedValue = value.includes(",") ? value.split(",").map((value) => value.trim()) : value; + headersList.push([name, resolvedValue]); + }); + return headersList; +} +//#endregion +//#region src/transformers/headersToString.ts +/** +* Converts a given `Headers` instance to its string representation. +*/ +function headersToString(headers) { + return headersToList(headers).map(([name, value]) => { + return `${name}: ${[].concat(value).join(", ")}`; + }).join("\r\n"); +} +//#endregion +//#region src/transformers/headersToObject.ts +const singleValueHeaders = ["user-agent"]; +/** +* Converts a given `Headers` instance into a plain object. +* Respects headers with multiple values. +*/ +function headersToObject(headers) { + const headersObject = {}; + headers.forEach((value, name) => { + headersObject[name] = !singleValueHeaders.includes(name.toLowerCase()) && value.includes(",") ? value.split(",").map((s) => s.trim()) : value; + }); + return headersObject; +} +//#endregion +//#region src/transformers/stringToHeaders.ts +/** +* Converts a string representation of headers (i.e. from XMLHttpRequest) +* to a new `Headers` instance. +*/ +function stringToHeaders(str) { + return str.trim().split(/[\r\n]+/).reduce((headers, line) => { + if (line.trim() === "") return headers; + const parts = line.split(": "); + const name = parts.shift(); + const value = parts.join(": "); + headers.append(name, value); + return headers; + }, new Headers()); +} +//#endregion +//#region src/transformers/listToHeaders.ts +function listToHeaders(list) { + const headers = new Headers(); + list.forEach(([name, value]) => { + [].concat(value).forEach((value) => { + headers.append(name, value); + }); + }); + return headers; +} +//#endregion +//#region src/transformers/reduceHeadersObject.ts +/** +* Reduces given headers object instnace. +*/ +function reduceHeadersObject(headers, reducer, initialState) { + return Object.keys(headers).reduce((nextHeaders, name) => { + return reducer(nextHeaders, name, headers[name]); + }, initialState); +} +//#endregion +//#region src/transformers/objectToHeaders.ts +/** +* Converts a given headers object to a new `Headers` instance. +*/ +function objectToHeaders(headersObject) { + return reduceHeadersObject(headersObject, (headers, name, value) => { + [].concat(value).filter(Boolean).forEach((value) => { + headers.append(name, value); + }); + return headers; + }, new Headers()); +} +//#endregion +//#region src/transformers/flattenHeadersList.ts +function flattenHeadersList(list) { + return list.map(([name, values]) => { + return [name, [].concat(values).join(", ")]; + }); +} +//#endregion +//#region src/transformers/flattenHeadersObject.ts +function flattenHeadersObject(headersObject) { + return reduceHeadersObject(headersObject, (headers, name, value) => { + headers[name] = [].concat(value).join(", "); + return headers; + }, {}); +} +//#endregion +exports.Headers = Headers; +exports.flattenHeadersList = flattenHeadersList; +exports.flattenHeadersObject = flattenHeadersObject; +exports.getRawHeaders = getRawHeaders; +exports.headersToList = headersToList; +exports.headersToObject = headersToObject; +exports.headersToString = headersToString; +exports.listToHeaders = listToHeaders; +exports.objectToHeaders = objectToHeaders; +exports.reduceHeadersObject = reduceHeadersObject; +exports.stringToHeaders = stringToHeaders; + +//# sourceMappingURL=index.cjs.map \ No newline at end of file diff --git a/node_modules/headers-polyfill/lib/index.cjs.map b/node_modules/headers-polyfill/lib/index.cjs.map new file mode 100644 index 0000000000000000000000000000000000000000..421fd5d0b5a817ef05bf09ab2b7935cd03c1b05f --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs","names":[],"sources":["../src/utils/normalizeHeaderName.ts","../src/utils/normalizeHeaderValue.ts","../src/utils/isValidHeaderName.ts","../src/utils/isValidHeaderValue.ts","../src/Headers.ts","../src/getRawHeaders.ts","../src/transformers/headersToList.ts","../src/transformers/headersToString.ts","../src/transformers/headersToObject.ts","../src/transformers/stringToHeaders.ts","../src/transformers/listToHeaders.ts","../src/transformers/reduceHeadersObject.ts","../src/transformers/objectToHeaders.ts","../src/transformers/flattenHeadersList.ts","../src/transformers/flattenHeadersObject.ts"],"sourcesContent":["const HEADERS_INVALID_CHARACTERS = /[^a-z0-9\\-#$%&'*+.^_`|~]/i\n\nexport function normalizeHeaderName(name: string): string {\n if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === '') {\n throw new TypeError('Invalid character in header field name')\n }\n\n return name.trim().toLowerCase()\n}\n","const charCodesToRemove = [\n String.fromCharCode(0x0a),\n String.fromCharCode(0x0d),\n String.fromCharCode(0x09),\n String.fromCharCode(0x20),\n]\n\nconst HEADER_VALUE_REMOVE_REGEXP = new RegExp(\n `(^[${charCodesToRemove.join('')}]|$[${charCodesToRemove.join('')}])`,\n 'g'\n)\n\n/**\n * Normalize the given header value.\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n */\nexport function normalizeHeaderValue(value: string): string {\n const nextValue = value.replace(HEADER_VALUE_REMOVE_REGEXP, '')\n return nextValue\n}\n","/**\n * Validate the given header name.\n * @see https://fetch.spec.whatwg.org/#header-name\n */\nexport function isValidHeaderName(value: unknown) {\n if (typeof value !== 'string') {\n return false\n }\n\n if (value.length === 0) {\n return false\n }\n\n for (let i = 0; i < value.length; i++) {\n const character = value.charCodeAt(i)\n\n if (character > 0x7f || !isToken(character)) {\n return false\n }\n }\n\n return true\n}\n\nfunction isToken(value: string | number): boolean {\n return ![\n 0x7f,\n 0x20,\n '(',\n ')',\n '<',\n '>',\n '@',\n ',',\n ';',\n ':',\n '\\\\',\n '\"',\n '/',\n '[',\n ']',\n '?',\n '=',\n '{',\n '}',\n ].includes(value)\n}\n","/**\n * Validate the given header value.\n * @see https://fetch.spec.whatwg.org/#header-value\n */\nexport function isValidHeaderValue(value: unknown): boolean {\n if (typeof value !== 'string') {\n return false\n }\n\n if (value.trim() !== value) {\n return false\n }\n\n for (let i = 0; i < value.length; i++) {\n const character = value.charCodeAt(i)\n\n if (\n // NUL.\n character === 0x00 ||\n // HTTP newline bytes.\n character === 0x0a ||\n character === 0x0d\n ) {\n return false\n }\n }\n\n return true\n}\n","import { splitCookiesString } from 'set-cookie-parser'\nimport { HeadersList, HeadersObject } from './glossary'\nimport { normalizeHeaderName } from './utils/normalizeHeaderName'\nimport { normalizeHeaderValue } from './utils/normalizeHeaderValue'\nimport { isValidHeaderName } from './utils/isValidHeaderName'\nimport { isValidHeaderValue } from './utils/isValidHeaderValue'\n\nexport const NORMALIZED_HEADERS: unique symbol = Symbol('normalizedHeaders')\n\nexport const RAW_HEADER_NAMES: unique symbol = Symbol('rawHeaderNames')\n\nconst HEADER_VALUE_DELIMITER = ', ' as const\n\nexport class Headers {\n // Normalized header {\"name\":\"a, b\"} storage.\n private [NORMALIZED_HEADERS]: Record = {}\n\n // Keeps the mapping between the raw header name\n // and the normalized header name to ease the lookup.\n private [RAW_HEADER_NAMES]: Map = new Map()\n\n constructor(init?: HeadersInit | HeadersObject | HeadersList) {\n /**\n * @note Cannot necessarily check if the `init` is an instance of the\n * `Headers` because that class may not be defined in Node or jsdom.\n */\n if (\n ['Headers', 'HeadersPolyfill'].includes(init?.constructor?.name) ||\n init instanceof Headers ||\n (typeof globalThis.Headers !== 'undefined' &&\n init instanceof globalThis.Headers)\n ) {\n const initialHeaders = init as Headers\n initialHeaders.forEach((value, name) => {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(init)) {\n init.forEach(([name, value]) => {\n this.append(\n name,\n Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value\n )\n })\n } else if (init) {\n Object.getOwnPropertyNames(init).forEach((name) => {\n const value = init[name]\n this.append(\n name,\n Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value\n )\n })\n }\n }\n\n [Symbol.toStringTag] = 'Headers';\n\n [Symbol.iterator]() {\n return this.entries()\n }\n\n *keys(): Generator {\n for (const [name] of this.entries()) {\n yield name\n }\n }\n\n *values(): Generator {\n for (const [, value] of this.entries()) {\n yield value\n }\n }\n\n *entries(): Generator<[string, string]> {\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) =>\n a.localeCompare(b)\n )\n for (const name of sortedKeys) {\n if (name === 'set-cookie') {\n for (const value of this.getSetCookie()) {\n yield [name, value]\n }\n } else {\n yield [name, this.get(name)]\n }\n }\n }\n\n /**\n * Returns a boolean stating whether a `Headers` object contains a certain header.\n */\n has(name: string): boolean {\n if (!isValidHeaderName(name)) {\n throw new TypeError(`Invalid header name \"${name}\"`)\n }\n\n return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name))\n }\n\n /**\n * Returns a `ByteString` sequence of all the values of a header with a given name.\n */\n get(name: string): string | null {\n if (!isValidHeaderName(name)) {\n throw TypeError(`Invalid header name \"${name}\"`)\n }\n\n return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null\n }\n\n /**\n * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.\n */\n set(name: string, value: string): void {\n if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n const normalizedValue = normalizeHeaderValue(value)\n\n this[NORMALIZED_HEADERS][normalizedName] =\n normalizeHeaderValue(normalizedValue)\n this[RAW_HEADER_NAMES].set(normalizedName, name)\n }\n\n /**\n * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.\n */\n append(name: string, value: string): void {\n if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n const normalizedValue = normalizeHeaderValue(value)\n\n let resolvedValue = this.has(normalizedName)\n ? `${this.get(normalizedName)}, ${normalizedValue}`\n : normalizedValue\n\n this.set(name, resolvedValue)\n }\n\n /**\n * Deletes a header from the `Headers` object.\n */\n delete(name: string): void {\n if (!isValidHeaderName(name)) {\n return\n }\n\n if (!this.has(name)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n delete this[NORMALIZED_HEADERS][normalizedName]\n this[RAW_HEADER_NAMES].delete(normalizedName)\n }\n\n /**\n * Traverses the `Headers` object,\n * calling the given callback for each header.\n */\n forEach(\n callback: (\n this: ThisArg,\n value: string,\n name: string,\n parent: this\n ) => void,\n thisArg?: ThisArg\n ) {\n for (const [name, value] of this.entries()) {\n callback.call(thisArg, value, name, this)\n }\n }\n\n /**\n * Returns an array containing the values\n * of all Set-Cookie headers associated\n * with a response\n */\n getSetCookie(): string[] {\n const setCookieHeader = this.get('set-cookie')\n\n if (setCookieHeader === null) {\n return []\n }\n\n if (setCookieHeader === '') {\n return ['']\n }\n\n return splitCookiesString(setCookieHeader)\n }\n}\n","import { RAW_HEADER_NAMES } from './Headers'\n\n/**\n * Returns the object of all raw headers.\n */\nexport function getRawHeaders(headers: Headers) {\n const rawHeaders: Record = {}\n\n for (const [name, value] of headers.entries()) {\n rawHeaders[headers[RAW_HEADER_NAMES].get(name)] = value\n }\n\n return rawHeaders\n}\n","import { HeadersList } from '../glossary'\n\nexport function headersToList(headers: Headers): HeadersList {\n const headersList: HeadersList = []\n\n headers.forEach((value, name) => {\n const resolvedValue = value.includes(',')\n ? value.split(',').map((value) => value.trim())\n : value\n\n headersList.push([name, resolvedValue])\n })\n\n return headersList\n}\n","import { headersToList } from './headersToList'\n\n/**\n * Converts a given `Headers` instance to its string representation.\n */\nexport function headersToString(headers: Headers): string {\n const list = headersToList(headers)\n const lines = list.map(([name, value]) => {\n const values = ([] as string[]).concat(value)\n return `${name}: ${values.join(', ')}`\n })\n\n return lines.join('\\r\\n')\n}\n","import { HeadersObject } from '../glossary'\n\n// List of headers that cannot have multiple values,\n// while potentially having a comma in their single value.\nconst singleValueHeaders = ['user-agent']\n\n/**\n * Converts a given `Headers` instance into a plain object.\n * Respects headers with multiple values.\n */\nexport function headersToObject(headers: Headers): HeadersObject {\n const headersObject: HeadersObject = {}\n\n headers.forEach((value, name) => {\n const isMultiValue =\n !singleValueHeaders.includes(name.toLowerCase()) && value.includes(',')\n headersObject[name] = isMultiValue\n ? value.split(',').map((s) => s.trim())\n : value\n })\n\n return headersObject\n}\n","import { Headers } from '../Headers'\n\n/**\n * Converts a string representation of headers (i.e. from XMLHttpRequest)\n * to a new `Headers` instance.\n */\nexport function stringToHeaders(str: string): Headers {\n const lines = str.trim().split(/[\\r\\n]+/)\n\n return lines.reduce((headers, line) => {\n if (line.trim() === '') {\n return headers\n }\n\n const parts = line.split(': ')\n const name = parts.shift()\n const value = parts.join(': ')\n headers.append(name, value)\n\n return headers\n }, new Headers())\n}\n","import { Headers } from '../Headers'\nimport { HeadersList } from '../glossary'\n\nexport function listToHeaders(list: HeadersList): Headers {\n const headers = new Headers()\n\n list.forEach(([name, value]) => {\n const values = ([] as string[]).concat(value)\n\n values.forEach((value) => {\n headers.append(name, value)\n })\n })\n\n return headers\n}\n","import { HeadersObject } from '../glossary'\n\n/**\n * Reduces given headers object instnace.\n */\nexport function reduceHeadersObject(\n headers: HeadersObject,\n reducer: (headers: R, name: string, value: string | string[]) => R,\n initialState: R\n): R {\n return Object.keys(headers).reduce((nextHeaders, name) => {\n return reducer(nextHeaders, name, headers[name])\n }, initialState)\n}\n","import { Headers } from '../Headers'\nimport { reduceHeadersObject } from './reduceHeadersObject'\n\n/**\n * Converts a given headers object to a new `Headers` instance.\n */\nexport function objectToHeaders(\n headersObject: Record\n): Headers {\n return reduceHeadersObject(\n headersObject,\n (headers, name, value) => {\n const values = ([] as string[]).concat(value).filter(Boolean)\n\n values.forEach((value) => {\n headers.append(name, value)\n })\n\n return headers\n },\n new Headers()\n )\n}\n","import { HeadersList, FlatHeadersList } from '../glossary'\n\nexport function flattenHeadersList(list: HeadersList): FlatHeadersList {\n return list.map(([name, values]) => {\n return [name, ([] as string[]).concat(values).join(', ')]\n })\n}\n","import { HeadersObject, FlatHeadersObject } from '../glossary'\nimport { reduceHeadersObject } from './reduceHeadersObject'\n\nexport function flattenHeadersObject(\n headersObject: HeadersObject\n): FlatHeadersObject {\n return reduceHeadersObject(\n headersObject,\n (headers, name, value) => {\n headers[name] = ([] as string[]).concat(value).join(', ')\n return headers\n },\n {}\n )\n}\n"],"mappings":";;;AAAA,MAAM,6BAA6B;AAEnC,SAAgB,oBAAoB,MAAsB;AACxD,KAAI,2BAA2B,KAAK,KAAK,IAAI,KAAK,MAAM,KAAK,GAC3D,OAAM,IAAI,UAAU,yCAAyC;AAG/D,QAAO,KAAK,MAAM,CAAC,aAAa;;;;ACPlC,MAAM,oBAAoB;CACxB,OAAO,aAAa,GAAK;CACzB,OAAO,aAAa,GAAK;CACzB,OAAO,aAAa,EAAK;CACzB,OAAO,aAAa,GAAK;CAC1B;AAED,MAAM,6BAA6B,IAAI,OACrC,MAAM,kBAAkB,KAAK,GAAG,CAAC,MAAM,kBAAkB,KAAK,GAAG,CAAC,KAClE,IACD;;;;;AAMD,SAAgB,qBAAqB,OAAuB;AAE1D,QADkB,MAAM,QAAQ,4BAA4B,GAAG;;;;;;;;ACbjE,SAAgB,kBAAkB,OAAgB;AAChD,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,MAAM,WAAW,EACnB,QAAO;AAGT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,YAAY,MAAM,WAAW,EAAE;AAErC,MAAI,YAAY,OAAQ,CAAC,QAAQ,UAAU,CACzC,QAAO;;AAIX,QAAO;;AAGT,SAAS,QAAQ,OAAiC;AAChD,QAAO,CAAC;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,SAAS,MAAM;;;;;;;;ACzCnB,SAAgB,mBAAmB,OAAyB;AAC1D,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,MAAM,MAAM,KAAK,MACnB,QAAO;AAGT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,YAAY,MAAM,WAAW,EAAE;AAErC,MAEE,cAAc,KAEd,cAAc,MACd,cAAc,GAEd,QAAO;;AAIX,QAAO;;;;;ACpBT,MAAa,qBAAoC,OAAO,oBAAoB;AAE5E,MAAa,mBAAkC,OAAO,iBAAiB;AAEvE,MAAM,yBAAyB;AAE/B,IAAa,UAAb,MAAa,QAAQ;CAQnB,YAAY,MAAkD;OANrD,sBAA8C,EAAE;OAIhD,oCAAyC,IAAI,KAAK;8BAmCpC;;;;;AA5BrB,MACE,CAAC,WAAW,kBAAkB,CAAC,SAAS,MAAM,aAAa,KAAK,IAChE,gBAAgB,WACf,OAAO,WAAW,YAAY,eAC7B,gBAAgB,WAAW,QAEN,MACR,SAAS,OAAO,SAAS;AACtC,QAAK,OAAO,MAAM,MAAM;KACvB,KAAK;WACC,MAAM,QAAQ,KAAK,CAC5B,MAAK,SAAS,CAAC,MAAM,WAAW;AAC9B,QAAK,OACH,MACA,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,uBAAuB,GAAG,MAC7D;IACD;WACO,KACT,QAAO,oBAAoB,KAAK,CAAC,SAAS,SAAS;GACjD,MAAM,QAAQ,KAAK;AACnB,QAAK,OACH,MACA,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,uBAAuB,GAAG,MAC7D;IACD;;CAMN,EAAA,sBAFC,OAAO,aAEP,OAAO,aAAY;AAClB,SAAO,KAAK,SAAS;;CAGvB,CAAC,OAA0B;AACzB,OAAK,MAAM,CAAC,SAAS,KAAK,SAAS,CACjC,OAAM;;CAIV,CAAC,SAA4B;AAC3B,OAAK,MAAM,GAAG,UAAU,KAAK,SAAS,CACpC,OAAM;;CAIV,CAAC,UAAuC;EAEtC,IAAI,aAAa,OAAO,KAAK,KAAK,oBAAoB,CAAC,MAAM,GAAG,MAC9D,EAAE,cAAc,EAAE,CACnB;AACD,OAAK,MAAM,QAAQ,WACjB,KAAI,SAAS,aACX,MAAK,MAAM,SAAS,KAAK,cAAc,CACrC,OAAM,CAAC,MAAM,MAAM;MAGrB,OAAM,CAAC,MAAM,KAAK,IAAI,KAAK,CAAC;;;;;CAQlC,IAAI,MAAuB;AACzB,MAAI,CAAC,kBAAkB,KAAK,CAC1B,OAAM,IAAI,UAAU,wBAAwB,KAAK,GAAG;AAGtD,SAAO,KAAK,oBAAoB,eAAe,oBAAoB,KAAK,CAAC;;;;;CAM3E,IAAI,MAA6B;AAC/B,MAAI,CAAC,kBAAkB,KAAK,CAC1B,OAAM,UAAU,wBAAwB,KAAK,GAAG;AAGlD,SAAO,KAAK,oBAAoB,oBAAoB,KAAK,KAAK;;;;;CAMhE,IAAI,MAAc,OAAqB;AACrC,MAAI,CAAC,kBAAkB,KAAK,IAAI,CAAC,mBAAmB,MAAM,CACxD;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;EAChD,MAAM,kBAAkB,qBAAqB,MAAM;AAEnD,OAAK,oBAAoB,kBACvB,qBAAqB,gBAAgB;AACvC,OAAK,kBAAkB,IAAI,gBAAgB,KAAK;;;;;CAMlD,OAAO,MAAc,OAAqB;AACxC,MAAI,CAAC,kBAAkB,KAAK,IAAI,CAAC,mBAAmB,MAAM,CACxD;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;EAChD,MAAM,kBAAkB,qBAAqB,MAAM;EAEnD,IAAI,gBAAgB,KAAK,IAAI,eAAe,GACxC,GAAG,KAAK,IAAI,eAAe,CAAC,IAAI,oBAChC;AAEJ,OAAK,IAAI,MAAM,cAAc;;;;;CAM/B,OAAO,MAAoB;AACzB,MAAI,CAAC,kBAAkB,KAAK,CAC1B;AAGF,MAAI,CAAC,KAAK,IAAI,KAAK,CACjB;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;AAChD,SAAO,KAAK,oBAAoB;AAChC,OAAK,kBAAkB,OAAO,eAAe;;;;;;CAO/C,QACE,UAMA,SACA;AACA,OAAK,MAAM,CAAC,MAAM,UAAU,KAAK,SAAS,CACxC,UAAS,KAAK,SAAS,OAAO,MAAM,KAAK;;;;;;;CAS7C,eAAyB;EACvB,MAAM,kBAAkB,KAAK,IAAI,aAAa;AAE9C,MAAI,oBAAoB,KACtB,QAAO,EAAE;AAGX,MAAI,oBAAoB,GACtB,QAAO,CAAC,GAAG;AAGb,UAAA,GAAA,kBAAA,oBAA0B,gBAAgB;;;;;;;;AC9L9C,SAAgB,cAAc,SAAkB;CAC9C,MAAM,aAAqC,EAAE;AAE7C,MAAK,MAAM,CAAC,MAAM,UAAU,QAAQ,SAAS,CAC3C,YAAW,QAAQ,kBAAkB,IAAI,KAAK,IAAI;AAGpD,QAAO;;;;ACVT,SAAgB,cAAc,SAA+B;CAC3D,MAAM,cAA2B,EAAE;AAEnC,SAAQ,SAAS,OAAO,SAAS;EAC/B,MAAM,gBAAgB,MAAM,SAAS,IAAI,GACrC,MAAM,MAAM,IAAI,CAAC,KAAK,UAAU,MAAM,MAAM,CAAC,GAC7C;AAEJ,cAAY,KAAK,CAAC,MAAM,cAAc,CAAC;GACvC;AAEF,QAAO;;;;;;;ACRT,SAAgB,gBAAgB,SAA0B;AAOxD,QANa,cAAc,QAAQ,CAChB,KAAK,CAAC,MAAM,WAAW;AAExC,SAAO,GAAG,KAAK,IADC,EAAE,CAAc,OAAO,MAAM,CACnB,KAAK,KAAK;GACpC,CAEW,KAAK,OAAO;;;;ACR3B,MAAM,qBAAqB,CAAC,aAAa;;;;;AAMzC,SAAgB,gBAAgB,SAAiC;CAC/D,MAAM,gBAA+B,EAAE;AAEvC,SAAQ,SAAS,OAAO,SAAS;AAG/B,gBAAc,QADZ,CAAC,mBAAmB,SAAS,KAAK,aAAa,CAAC,IAAI,MAAM,SAAS,IAAI,GAErE,MAAM,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC,GACrC;GACJ;AAEF,QAAO;;;;;;;;ACfT,SAAgB,gBAAgB,KAAsB;AAGpD,QAFc,IAAI,MAAM,CAAC,MAAM,UAAU,CAE5B,QAAQ,SAAS,SAAS;AACrC,MAAI,KAAK,MAAM,KAAK,GAClB,QAAO;EAGT,MAAM,QAAQ,KAAK,MAAM,KAAK;EAC9B,MAAM,OAAO,MAAM,OAAO;EAC1B,MAAM,QAAQ,MAAM,KAAK,KAAK;AAC9B,UAAQ,OAAO,MAAM,MAAM;AAE3B,SAAO;IACN,IAAI,SAAS,CAAC;;;;ACjBnB,SAAgB,cAAc,MAA4B;CACxD,MAAM,UAAU,IAAI,SAAS;AAE7B,MAAK,SAAS,CAAC,MAAM,WAAW;AACd,IAAE,CAAc,OAAO,MAAM,CAEtC,SAAS,UAAU;AACxB,WAAQ,OAAO,MAAM,MAAM;IAC3B;GACF;AAEF,QAAO;;;;;;;ACTT,SAAgB,oBACd,SACA,SACA,cACG;AACH,QAAO,OAAO,KAAK,QAAQ,CAAC,QAAW,aAAa,SAAS;AAC3D,SAAO,QAAQ,aAAa,MAAM,QAAQ,MAAM;IAC/C,aAAa;;;;;;;ACNlB,SAAgB,gBACd,eACS;AACT,QAAO,oBACL,gBACC,SAAS,MAAM,UAAU;AACR,IAAE,CAAc,OAAO,MAAM,CAAC,OAAO,QAAQ,CAEtD,SAAS,UAAU;AACxB,WAAQ,OAAO,MAAM,MAAM;IAC3B;AAEF,SAAO;IAET,IAAI,SAAS,CACd;;;;ACnBH,SAAgB,mBAAmB,MAAoC;AACrE,QAAO,KAAK,KAAK,CAAC,MAAM,YAAY;AAClC,SAAO,CAAC,MAAO,EAAE,CAAc,OAAO,OAAO,CAAC,KAAK,KAAK,CAAC;GACzD;;;;ACFJ,SAAgB,qBACd,eACmB;AACnB,QAAO,oBACL,gBACC,SAAS,MAAM,UAAU;AACxB,UAAQ,QAAS,EAAE,CAAc,OAAO,MAAM,CAAC,KAAK,KAAK;AACzD,SAAO;IAET,EAAE,CACH"} \ No newline at end of file diff --git a/node_modules/headers-polyfill/lib/index.d.cts b/node_modules/headers-polyfill/lib/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..f8adb866ed19a0046e37ddeb3e21dc6ecc8da6ed --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.d.cts @@ -0,0 +1,103 @@ +//#region src/glossary.d.ts +type HeadersList = Array<[string, string | string[]]>; +type FlatHeadersList = [string, string][]; +type HeadersObject = Record; +type FlatHeadersObject = Record; +//#endregion +//#region src/Headers.d.ts +declare const NORMALIZED_HEADERS: unique symbol; +declare const RAW_HEADER_NAMES: unique symbol; +declare class Headers$1 { + private [NORMALIZED_HEADERS]; + private [RAW_HEADER_NAMES]; + constructor(init?: HeadersInit | HeadersObject | HeadersList); + [Symbol.toStringTag]: string; + [Symbol.iterator](): Generator<[string, string], any, any>; + keys(): Generator; + values(): Generator; + entries(): Generator<[string, string]>; + /** + * Returns a boolean stating whether a `Headers` object contains a certain header. + */ + has(name: string): boolean; + /** + * Returns a `ByteString` sequence of all the values of a header with a given name. + */ + get(name: string): string | null; + /** + * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + set(name: string, value: string): void; + /** + * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + append(name: string, value: string): void; + /** + * Deletes a header from the `Headers` object. + */ + delete(name: string): void; + /** + * Traverses the `Headers` object, + * calling the given callback for each header. + */ + forEach(callback: (this: ThisArg, value: string, name: string, parent: this) => void, thisArg?: ThisArg): void; + /** + * Returns an array containing the values + * of all Set-Cookie headers associated + * with a response + */ + getSetCookie(): string[]; +} +//#endregion +//#region src/getRawHeaders.d.ts +/** + * Returns the object of all raw headers. + */ +declare function getRawHeaders(headers: Headers): Record; +//#endregion +//#region src/transformers/headersToString.d.ts +/** + * Converts a given `Headers` instance to its string representation. + */ +declare function headersToString(headers: Headers): string; +//#endregion +//#region src/transformers/headersToList.d.ts +declare function headersToList(headers: Headers): HeadersList; +//#endregion +//#region src/transformers/headersToObject.d.ts +/** + * Converts a given `Headers` instance into a plain object. + * Respects headers with multiple values. + */ +declare function headersToObject(headers: Headers): HeadersObject; +//#endregion +//#region src/transformers/stringToHeaders.d.ts +/** + * Converts a string representation of headers (i.e. from XMLHttpRequest) + * to a new `Headers` instance. + */ +declare function stringToHeaders(str: string): Headers$1; +//#endregion +//#region src/transformers/listToHeaders.d.ts +declare function listToHeaders(list: HeadersList): Headers$1; +//#endregion +//#region src/transformers/objectToHeaders.d.ts +/** + * Converts a given headers object to a new `Headers` instance. + */ +declare function objectToHeaders(headersObject: Record): Headers$1; +//#endregion +//#region src/transformers/reduceHeadersObject.d.ts +/** + * Reduces given headers object instnace. + */ +declare function reduceHeadersObject(headers: HeadersObject, reducer: (headers: R, name: string, value: string | string[]) => R, initialState: R): R; +//#endregion +//#region src/transformers/flattenHeadersList.d.ts +declare function flattenHeadersList(list: HeadersList): FlatHeadersList; +//#endregion +//#region src/transformers/flattenHeadersObject.d.ts +declare function flattenHeadersObject(headersObject: HeadersObject): FlatHeadersObject; +//#endregion +export { type FlatHeadersList, type FlatHeadersObject, Headers$1 as Headers, type HeadersList, type HeadersObject, flattenHeadersList, flattenHeadersObject, getRawHeaders, headersToList, headersToObject, headersToString, listToHeaders, objectToHeaders, reduceHeadersObject, stringToHeaders }; +//# sourceMappingURL=index.d.cts.map \ No newline at end of file diff --git a/node_modules/headers-polyfill/lib/index.d.mts b/node_modules/headers-polyfill/lib/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..f0adaf244fe804612d4cbbc38bc99db58fb94bba --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.d.mts @@ -0,0 +1,103 @@ +//#region src/glossary.d.ts +type HeadersList = Array<[string, string | string[]]>; +type FlatHeadersList = [string, string][]; +type HeadersObject = Record; +type FlatHeadersObject = Record; +//#endregion +//#region src/Headers.d.ts +declare const NORMALIZED_HEADERS: unique symbol; +declare const RAW_HEADER_NAMES: unique symbol; +declare class Headers$1 { + private [NORMALIZED_HEADERS]; + private [RAW_HEADER_NAMES]; + constructor(init?: HeadersInit | HeadersObject | HeadersList); + [Symbol.toStringTag]: string; + [Symbol.iterator](): Generator<[string, string], any, any>; + keys(): Generator; + values(): Generator; + entries(): Generator<[string, string]>; + /** + * Returns a boolean stating whether a `Headers` object contains a certain header. + */ + has(name: string): boolean; + /** + * Returns a `ByteString` sequence of all the values of a header with a given name. + */ + get(name: string): string | null; + /** + * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + set(name: string, value: string): void; + /** + * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + append(name: string, value: string): void; + /** + * Deletes a header from the `Headers` object. + */ + delete(name: string): void; + /** + * Traverses the `Headers` object, + * calling the given callback for each header. + */ + forEach(callback: (this: ThisArg, value: string, name: string, parent: this) => void, thisArg?: ThisArg): void; + /** + * Returns an array containing the values + * of all Set-Cookie headers associated + * with a response + */ + getSetCookie(): string[]; +} +//#endregion +//#region src/getRawHeaders.d.ts +/** + * Returns the object of all raw headers. + */ +declare function getRawHeaders(headers: Headers): Record; +//#endregion +//#region src/transformers/headersToString.d.ts +/** + * Converts a given `Headers` instance to its string representation. + */ +declare function headersToString(headers: Headers): string; +//#endregion +//#region src/transformers/headersToList.d.ts +declare function headersToList(headers: Headers): HeadersList; +//#endregion +//#region src/transformers/headersToObject.d.ts +/** + * Converts a given `Headers` instance into a plain object. + * Respects headers with multiple values. + */ +declare function headersToObject(headers: Headers): HeadersObject; +//#endregion +//#region src/transformers/stringToHeaders.d.ts +/** + * Converts a string representation of headers (i.e. from XMLHttpRequest) + * to a new `Headers` instance. + */ +declare function stringToHeaders(str: string): Headers$1; +//#endregion +//#region src/transformers/listToHeaders.d.ts +declare function listToHeaders(list: HeadersList): Headers$1; +//#endregion +//#region src/transformers/objectToHeaders.d.ts +/** + * Converts a given headers object to a new `Headers` instance. + */ +declare function objectToHeaders(headersObject: Record): Headers$1; +//#endregion +//#region src/transformers/reduceHeadersObject.d.ts +/** + * Reduces given headers object instnace. + */ +declare function reduceHeadersObject(headers: HeadersObject, reducer: (headers: R, name: string, value: string | string[]) => R, initialState: R): R; +//#endregion +//#region src/transformers/flattenHeadersList.d.ts +declare function flattenHeadersList(list: HeadersList): FlatHeadersList; +//#endregion +//#region src/transformers/flattenHeadersObject.d.ts +declare function flattenHeadersObject(headersObject: HeadersObject): FlatHeadersObject; +//#endregion +export { type FlatHeadersList, type FlatHeadersObject, Headers$1 as Headers, type HeadersList, type HeadersObject, flattenHeadersList, flattenHeadersObject, getRawHeaders, headersToList, headersToObject, headersToString, listToHeaders, objectToHeaders, reduceHeadersObject, stringToHeaders }; +//# sourceMappingURL=index.d.mts.map \ No newline at end of file diff --git a/node_modules/headers-polyfill/lib/index.mjs b/node_modules/headers-polyfill/lib/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e684ceb6a62d76d53a4a2b5bc5eb06a1bf50a928 --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.mjs @@ -0,0 +1,292 @@ +import { splitCookiesString } from "set-cookie-parser"; +//#region src/utils/normalizeHeaderName.ts +const HEADERS_INVALID_CHARACTERS = /[^a-z0-9\-#$%&'*+.^_`|~]/i; +function normalizeHeaderName(name) { + if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === "") throw new TypeError("Invalid character in header field name"); + return name.trim().toLowerCase(); +} +//#endregion +//#region src/utils/normalizeHeaderValue.ts +const charCodesToRemove = [ + String.fromCharCode(10), + String.fromCharCode(13), + String.fromCharCode(9), + String.fromCharCode(32) +]; +const HEADER_VALUE_REMOVE_REGEXP = new RegExp(`(^[${charCodesToRemove.join("")}]|$[${charCodesToRemove.join("")}])`, "g"); +/** +* Normalize the given header value. +* @see https://fetch.spec.whatwg.org/#concept-header-value-normalize +*/ +function normalizeHeaderValue(value) { + return value.replace(HEADER_VALUE_REMOVE_REGEXP, ""); +} +//#endregion +//#region src/utils/isValidHeaderName.ts +/** +* Validate the given header name. +* @see https://fetch.spec.whatwg.org/#header-name +*/ +function isValidHeaderName(value) { + if (typeof value !== "string") return false; + if (value.length === 0) return false; + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i); + if (character > 127 || !isToken(character)) return false; + } + return true; +} +function isToken(value) { + return ![ + 127, + 32, + "(", + ")", + "<", + ">", + "@", + ",", + ";", + ":", + "\\", + "\"", + "/", + "[", + "]", + "?", + "=", + "{", + "}" + ].includes(value); +} +//#endregion +//#region src/utils/isValidHeaderValue.ts +/** +* Validate the given header value. +* @see https://fetch.spec.whatwg.org/#header-value +*/ +function isValidHeaderValue(value) { + if (typeof value !== "string") return false; + if (value.trim() !== value) return false; + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i); + if (character === 0 || character === 10 || character === 13) return false; + } + return true; +} +//#endregion +//#region src/Headers.ts +let _Symbol$toStringTag; +const NORMALIZED_HEADERS = Symbol("normalizedHeaders"); +const RAW_HEADER_NAMES = Symbol("rawHeaderNames"); +const HEADER_VALUE_DELIMITER = ", "; +var Headers = class Headers { + constructor(init) { + this[NORMALIZED_HEADERS] = {}; + this[RAW_HEADER_NAMES] = /* @__PURE__ */ new Map(); + this[_Symbol$toStringTag] = "Headers"; + /** + * @note Cannot necessarily check if the `init` is an instance of the + * `Headers` because that class may not be defined in Node or jsdom. + */ + if (["Headers", "HeadersPolyfill"].includes(init?.constructor?.name) || init instanceof Headers || typeof globalThis.Headers !== "undefined" && init instanceof globalThis.Headers) init.forEach((value, name) => { + this.append(name, value); + }, this); + else if (Array.isArray(init)) init.forEach(([name, value]) => { + this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value); + }); + else if (init) Object.getOwnPropertyNames(init).forEach((name) => { + const value = init[name]; + this.append(name, Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value); + }); + } + [(_Symbol$toStringTag = Symbol.toStringTag, Symbol.iterator)]() { + return this.entries(); + } + *keys() { + for (const [name] of this.entries()) yield name; + } + *values() { + for (const [, value] of this.entries()) yield value; + } + *entries() { + let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => a.localeCompare(b)); + for (const name of sortedKeys) if (name === "set-cookie") for (const value of this.getSetCookie()) yield [name, value]; + else yield [name, this.get(name)]; + } + /** + * Returns a boolean stating whether a `Headers` object contains a certain header. + */ + has(name) { + if (!isValidHeaderName(name)) throw new TypeError(`Invalid header name "${name}"`); + return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name)); + } + /** + * Returns a `ByteString` sequence of all the values of a header with a given name. + */ + get(name) { + if (!isValidHeaderName(name)) throw TypeError(`Invalid header name "${name}"`); + return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null; + } + /** + * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + set(name, value) { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return; + const normalizedName = normalizeHeaderName(name); + const normalizedValue = normalizeHeaderValue(value); + this[NORMALIZED_HEADERS][normalizedName] = normalizeHeaderValue(normalizedValue); + this[RAW_HEADER_NAMES].set(normalizedName, name); + } + /** + * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + append(name, value) { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) return; + const normalizedName = normalizeHeaderName(name); + const normalizedValue = normalizeHeaderValue(value); + let resolvedValue = this.has(normalizedName) ? `${this.get(normalizedName)}, ${normalizedValue}` : normalizedValue; + this.set(name, resolvedValue); + } + /** + * Deletes a header from the `Headers` object. + */ + delete(name) { + if (!isValidHeaderName(name)) return; + if (!this.has(name)) return; + const normalizedName = normalizeHeaderName(name); + delete this[NORMALIZED_HEADERS][normalizedName]; + this[RAW_HEADER_NAMES].delete(normalizedName); + } + /** + * Traverses the `Headers` object, + * calling the given callback for each header. + */ + forEach(callback, thisArg) { + for (const [name, value] of this.entries()) callback.call(thisArg, value, name, this); + } + /** + * Returns an array containing the values + * of all Set-Cookie headers associated + * with a response + */ + getSetCookie() { + const setCookieHeader = this.get("set-cookie"); + if (setCookieHeader === null) return []; + if (setCookieHeader === "") return [""]; + return splitCookiesString(setCookieHeader); + } +}; +//#endregion +//#region src/getRawHeaders.ts +/** +* Returns the object of all raw headers. +*/ +function getRawHeaders(headers) { + const rawHeaders = {}; + for (const [name, value] of headers.entries()) rawHeaders[headers[RAW_HEADER_NAMES].get(name)] = value; + return rawHeaders; +} +//#endregion +//#region src/transformers/headersToList.ts +function headersToList(headers) { + const headersList = []; + headers.forEach((value, name) => { + const resolvedValue = value.includes(",") ? value.split(",").map((value) => value.trim()) : value; + headersList.push([name, resolvedValue]); + }); + return headersList; +} +//#endregion +//#region src/transformers/headersToString.ts +/** +* Converts a given `Headers` instance to its string representation. +*/ +function headersToString(headers) { + return headersToList(headers).map(([name, value]) => { + return `${name}: ${[].concat(value).join(", ")}`; + }).join("\r\n"); +} +//#endregion +//#region src/transformers/headersToObject.ts +const singleValueHeaders = ["user-agent"]; +/** +* Converts a given `Headers` instance into a plain object. +* Respects headers with multiple values. +*/ +function headersToObject(headers) { + const headersObject = {}; + headers.forEach((value, name) => { + headersObject[name] = !singleValueHeaders.includes(name.toLowerCase()) && value.includes(",") ? value.split(",").map((s) => s.trim()) : value; + }); + return headersObject; +} +//#endregion +//#region src/transformers/stringToHeaders.ts +/** +* Converts a string representation of headers (i.e. from XMLHttpRequest) +* to a new `Headers` instance. +*/ +function stringToHeaders(str) { + return str.trim().split(/[\r\n]+/).reduce((headers, line) => { + if (line.trim() === "") return headers; + const parts = line.split(": "); + const name = parts.shift(); + const value = parts.join(": "); + headers.append(name, value); + return headers; + }, new Headers()); +} +//#endregion +//#region src/transformers/listToHeaders.ts +function listToHeaders(list) { + const headers = new Headers(); + list.forEach(([name, value]) => { + [].concat(value).forEach((value) => { + headers.append(name, value); + }); + }); + return headers; +} +//#endregion +//#region src/transformers/reduceHeadersObject.ts +/** +* Reduces given headers object instnace. +*/ +function reduceHeadersObject(headers, reducer, initialState) { + return Object.keys(headers).reduce((nextHeaders, name) => { + return reducer(nextHeaders, name, headers[name]); + }, initialState); +} +//#endregion +//#region src/transformers/objectToHeaders.ts +/** +* Converts a given headers object to a new `Headers` instance. +*/ +function objectToHeaders(headersObject) { + return reduceHeadersObject(headersObject, (headers, name, value) => { + [].concat(value).filter(Boolean).forEach((value) => { + headers.append(name, value); + }); + return headers; + }, new Headers()); +} +//#endregion +//#region src/transformers/flattenHeadersList.ts +function flattenHeadersList(list) { + return list.map(([name, values]) => { + return [name, [].concat(values).join(", ")]; + }); +} +//#endregion +//#region src/transformers/flattenHeadersObject.ts +function flattenHeadersObject(headersObject) { + return reduceHeadersObject(headersObject, (headers, name, value) => { + headers[name] = [].concat(value).join(", "); + return headers; + }, {}); +} +//#endregion +export { Headers, flattenHeadersList, flattenHeadersObject, getRawHeaders, headersToList, headersToObject, headersToString, listToHeaders, objectToHeaders, reduceHeadersObject, stringToHeaders }; + +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/headers-polyfill/lib/index.mjs.map b/node_modules/headers-polyfill/lib/index.mjs.map new file mode 100644 index 0000000000000000000000000000000000000000..68c3a975d8973bc38707e0e1ec63d472c5a22c21 --- /dev/null +++ b/node_modules/headers-polyfill/lib/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","names":[],"sources":["../src/utils/normalizeHeaderName.ts","../src/utils/normalizeHeaderValue.ts","../src/utils/isValidHeaderName.ts","../src/utils/isValidHeaderValue.ts","../src/Headers.ts","../src/getRawHeaders.ts","../src/transformers/headersToList.ts","../src/transformers/headersToString.ts","../src/transformers/headersToObject.ts","../src/transformers/stringToHeaders.ts","../src/transformers/listToHeaders.ts","../src/transformers/reduceHeadersObject.ts","../src/transformers/objectToHeaders.ts","../src/transformers/flattenHeadersList.ts","../src/transformers/flattenHeadersObject.ts"],"sourcesContent":["const HEADERS_INVALID_CHARACTERS = /[^a-z0-9\\-#$%&'*+.^_`|~]/i\n\nexport function normalizeHeaderName(name: string): string {\n if (HEADERS_INVALID_CHARACTERS.test(name) || name.trim() === '') {\n throw new TypeError('Invalid character in header field name')\n }\n\n return name.trim().toLowerCase()\n}\n","const charCodesToRemove = [\n String.fromCharCode(0x0a),\n String.fromCharCode(0x0d),\n String.fromCharCode(0x09),\n String.fromCharCode(0x20),\n]\n\nconst HEADER_VALUE_REMOVE_REGEXP = new RegExp(\n `(^[${charCodesToRemove.join('')}]|$[${charCodesToRemove.join('')}])`,\n 'g'\n)\n\n/**\n * Normalize the given header value.\n * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize\n */\nexport function normalizeHeaderValue(value: string): string {\n const nextValue = value.replace(HEADER_VALUE_REMOVE_REGEXP, '')\n return nextValue\n}\n","/**\n * Validate the given header name.\n * @see https://fetch.spec.whatwg.org/#header-name\n */\nexport function isValidHeaderName(value: unknown) {\n if (typeof value !== 'string') {\n return false\n }\n\n if (value.length === 0) {\n return false\n }\n\n for (let i = 0; i < value.length; i++) {\n const character = value.charCodeAt(i)\n\n if (character > 0x7f || !isToken(character)) {\n return false\n }\n }\n\n return true\n}\n\nfunction isToken(value: string | number): boolean {\n return ![\n 0x7f,\n 0x20,\n '(',\n ')',\n '<',\n '>',\n '@',\n ',',\n ';',\n ':',\n '\\\\',\n '\"',\n '/',\n '[',\n ']',\n '?',\n '=',\n '{',\n '}',\n ].includes(value)\n}\n","/**\n * Validate the given header value.\n * @see https://fetch.spec.whatwg.org/#header-value\n */\nexport function isValidHeaderValue(value: unknown): boolean {\n if (typeof value !== 'string') {\n return false\n }\n\n if (value.trim() !== value) {\n return false\n }\n\n for (let i = 0; i < value.length; i++) {\n const character = value.charCodeAt(i)\n\n if (\n // NUL.\n character === 0x00 ||\n // HTTP newline bytes.\n character === 0x0a ||\n character === 0x0d\n ) {\n return false\n }\n }\n\n return true\n}\n","import { splitCookiesString } from 'set-cookie-parser'\nimport { HeadersList, HeadersObject } from './glossary'\nimport { normalizeHeaderName } from './utils/normalizeHeaderName'\nimport { normalizeHeaderValue } from './utils/normalizeHeaderValue'\nimport { isValidHeaderName } from './utils/isValidHeaderName'\nimport { isValidHeaderValue } from './utils/isValidHeaderValue'\n\nexport const NORMALIZED_HEADERS: unique symbol = Symbol('normalizedHeaders')\n\nexport const RAW_HEADER_NAMES: unique symbol = Symbol('rawHeaderNames')\n\nconst HEADER_VALUE_DELIMITER = ', ' as const\n\nexport class Headers {\n // Normalized header {\"name\":\"a, b\"} storage.\n private [NORMALIZED_HEADERS]: Record = {}\n\n // Keeps the mapping between the raw header name\n // and the normalized header name to ease the lookup.\n private [RAW_HEADER_NAMES]: Map = new Map()\n\n constructor(init?: HeadersInit | HeadersObject | HeadersList) {\n /**\n * @note Cannot necessarily check if the `init` is an instance of the\n * `Headers` because that class may not be defined in Node or jsdom.\n */\n if (\n ['Headers', 'HeadersPolyfill'].includes(init?.constructor?.name) ||\n init instanceof Headers ||\n (typeof globalThis.Headers !== 'undefined' &&\n init instanceof globalThis.Headers)\n ) {\n const initialHeaders = init as Headers\n initialHeaders.forEach((value, name) => {\n this.append(name, value)\n }, this)\n } else if (Array.isArray(init)) {\n init.forEach(([name, value]) => {\n this.append(\n name,\n Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value\n )\n })\n } else if (init) {\n Object.getOwnPropertyNames(init).forEach((name) => {\n const value = init[name]\n this.append(\n name,\n Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value\n )\n })\n }\n }\n\n [Symbol.toStringTag] = 'Headers';\n\n [Symbol.iterator]() {\n return this.entries()\n }\n\n *keys(): Generator {\n for (const [name] of this.entries()) {\n yield name\n }\n }\n\n *values(): Generator {\n for (const [, value] of this.entries()) {\n yield value\n }\n }\n\n *entries(): Generator<[string, string]> {\n // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine\n let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) =>\n a.localeCompare(b)\n )\n for (const name of sortedKeys) {\n if (name === 'set-cookie') {\n for (const value of this.getSetCookie()) {\n yield [name, value]\n }\n } else {\n yield [name, this.get(name)]\n }\n }\n }\n\n /**\n * Returns a boolean stating whether a `Headers` object contains a certain header.\n */\n has(name: string): boolean {\n if (!isValidHeaderName(name)) {\n throw new TypeError(`Invalid header name \"${name}\"`)\n }\n\n return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name))\n }\n\n /**\n * Returns a `ByteString` sequence of all the values of a header with a given name.\n */\n get(name: string): string | null {\n if (!isValidHeaderName(name)) {\n throw TypeError(`Invalid header name \"${name}\"`)\n }\n\n return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null\n }\n\n /**\n * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist.\n */\n set(name: string, value: string): void {\n if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n const normalizedValue = normalizeHeaderValue(value)\n\n this[NORMALIZED_HEADERS][normalizedName] =\n normalizeHeaderValue(normalizedValue)\n this[RAW_HEADER_NAMES].set(normalizedName, name)\n }\n\n /**\n * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist.\n */\n append(name: string, value: string): void {\n if (!isValidHeaderName(name) || !isValidHeaderValue(value)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n const normalizedValue = normalizeHeaderValue(value)\n\n let resolvedValue = this.has(normalizedName)\n ? `${this.get(normalizedName)}, ${normalizedValue}`\n : normalizedValue\n\n this.set(name, resolvedValue)\n }\n\n /**\n * Deletes a header from the `Headers` object.\n */\n delete(name: string): void {\n if (!isValidHeaderName(name)) {\n return\n }\n\n if (!this.has(name)) {\n return\n }\n\n const normalizedName = normalizeHeaderName(name)\n delete this[NORMALIZED_HEADERS][normalizedName]\n this[RAW_HEADER_NAMES].delete(normalizedName)\n }\n\n /**\n * Traverses the `Headers` object,\n * calling the given callback for each header.\n */\n forEach(\n callback: (\n this: ThisArg,\n value: string,\n name: string,\n parent: this\n ) => void,\n thisArg?: ThisArg\n ) {\n for (const [name, value] of this.entries()) {\n callback.call(thisArg, value, name, this)\n }\n }\n\n /**\n * Returns an array containing the values\n * of all Set-Cookie headers associated\n * with a response\n */\n getSetCookie(): string[] {\n const setCookieHeader = this.get('set-cookie')\n\n if (setCookieHeader === null) {\n return []\n }\n\n if (setCookieHeader === '') {\n return ['']\n }\n\n return splitCookiesString(setCookieHeader)\n }\n}\n","import { RAW_HEADER_NAMES } from './Headers'\n\n/**\n * Returns the object of all raw headers.\n */\nexport function getRawHeaders(headers: Headers) {\n const rawHeaders: Record = {}\n\n for (const [name, value] of headers.entries()) {\n rawHeaders[headers[RAW_HEADER_NAMES].get(name)] = value\n }\n\n return rawHeaders\n}\n","import { HeadersList } from '../glossary'\n\nexport function headersToList(headers: Headers): HeadersList {\n const headersList: HeadersList = []\n\n headers.forEach((value, name) => {\n const resolvedValue = value.includes(',')\n ? value.split(',').map((value) => value.trim())\n : value\n\n headersList.push([name, resolvedValue])\n })\n\n return headersList\n}\n","import { headersToList } from './headersToList'\n\n/**\n * Converts a given `Headers` instance to its string representation.\n */\nexport function headersToString(headers: Headers): string {\n const list = headersToList(headers)\n const lines = list.map(([name, value]) => {\n const values = ([] as string[]).concat(value)\n return `${name}: ${values.join(', ')}`\n })\n\n return lines.join('\\r\\n')\n}\n","import { HeadersObject } from '../glossary'\n\n// List of headers that cannot have multiple values,\n// while potentially having a comma in their single value.\nconst singleValueHeaders = ['user-agent']\n\n/**\n * Converts a given `Headers` instance into a plain object.\n * Respects headers with multiple values.\n */\nexport function headersToObject(headers: Headers): HeadersObject {\n const headersObject: HeadersObject = {}\n\n headers.forEach((value, name) => {\n const isMultiValue =\n !singleValueHeaders.includes(name.toLowerCase()) && value.includes(',')\n headersObject[name] = isMultiValue\n ? value.split(',').map((s) => s.trim())\n : value\n })\n\n return headersObject\n}\n","import { Headers } from '../Headers'\n\n/**\n * Converts a string representation of headers (i.e. from XMLHttpRequest)\n * to a new `Headers` instance.\n */\nexport function stringToHeaders(str: string): Headers {\n const lines = str.trim().split(/[\\r\\n]+/)\n\n return lines.reduce((headers, line) => {\n if (line.trim() === '') {\n return headers\n }\n\n const parts = line.split(': ')\n const name = parts.shift()\n const value = parts.join(': ')\n headers.append(name, value)\n\n return headers\n }, new Headers())\n}\n","import { Headers } from '../Headers'\nimport { HeadersList } from '../glossary'\n\nexport function listToHeaders(list: HeadersList): Headers {\n const headers = new Headers()\n\n list.forEach(([name, value]) => {\n const values = ([] as string[]).concat(value)\n\n values.forEach((value) => {\n headers.append(name, value)\n })\n })\n\n return headers\n}\n","import { HeadersObject } from '../glossary'\n\n/**\n * Reduces given headers object instnace.\n */\nexport function reduceHeadersObject(\n headers: HeadersObject,\n reducer: (headers: R, name: string, value: string | string[]) => R,\n initialState: R\n): R {\n return Object.keys(headers).reduce((nextHeaders, name) => {\n return reducer(nextHeaders, name, headers[name])\n }, initialState)\n}\n","import { Headers } from '../Headers'\nimport { reduceHeadersObject } from './reduceHeadersObject'\n\n/**\n * Converts a given headers object to a new `Headers` instance.\n */\nexport function objectToHeaders(\n headersObject: Record\n): Headers {\n return reduceHeadersObject(\n headersObject,\n (headers, name, value) => {\n const values = ([] as string[]).concat(value).filter(Boolean)\n\n values.forEach((value) => {\n headers.append(name, value)\n })\n\n return headers\n },\n new Headers()\n )\n}\n","import { HeadersList, FlatHeadersList } from '../glossary'\n\nexport function flattenHeadersList(list: HeadersList): FlatHeadersList {\n return list.map(([name, values]) => {\n return [name, ([] as string[]).concat(values).join(', ')]\n })\n}\n","import { HeadersObject, FlatHeadersObject } from '../glossary'\nimport { reduceHeadersObject } from './reduceHeadersObject'\n\nexport function flattenHeadersObject(\n headersObject: HeadersObject\n): FlatHeadersObject {\n return reduceHeadersObject(\n headersObject,\n (headers, name, value) => {\n headers[name] = ([] as string[]).concat(value).join(', ')\n return headers\n },\n {}\n )\n}\n"],"mappings":";;AAAA,MAAM,6BAA6B;AAEnC,SAAgB,oBAAoB,MAAsB;AACxD,KAAI,2BAA2B,KAAK,KAAK,IAAI,KAAK,MAAM,KAAK,GAC3D,OAAM,IAAI,UAAU,yCAAyC;AAG/D,QAAO,KAAK,MAAM,CAAC,aAAa;;;;ACPlC,MAAM,oBAAoB;CACxB,OAAO,aAAa,GAAK;CACzB,OAAO,aAAa,GAAK;CACzB,OAAO,aAAa,EAAK;CACzB,OAAO,aAAa,GAAK;CAC1B;AAED,MAAM,6BAA6B,IAAI,OACrC,MAAM,kBAAkB,KAAK,GAAG,CAAC,MAAM,kBAAkB,KAAK,GAAG,CAAC,KAClE,IACD;;;;;AAMD,SAAgB,qBAAqB,OAAuB;AAE1D,QADkB,MAAM,QAAQ,4BAA4B,GAAG;;;;;;;;ACbjE,SAAgB,kBAAkB,OAAgB;AAChD,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,MAAM,WAAW,EACnB,QAAO;AAGT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,YAAY,MAAM,WAAW,EAAE;AAErC,MAAI,YAAY,OAAQ,CAAC,QAAQ,UAAU,CACzC,QAAO;;AAIX,QAAO;;AAGT,SAAS,QAAQ,OAAiC;AAChD,QAAO,CAAC;EACN;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,SAAS,MAAM;;;;;;;;ACzCnB,SAAgB,mBAAmB,OAAyB;AAC1D,KAAI,OAAO,UAAU,SACnB,QAAO;AAGT,KAAI,MAAM,MAAM,KAAK,MACnB,QAAO;AAGT,MAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,YAAY,MAAM,WAAW,EAAE;AAErC,MAEE,cAAc,KAEd,cAAc,MACd,cAAc,GAEd,QAAO;;AAIX,QAAO;;;;;ACpBT,MAAa,qBAAoC,OAAO,oBAAoB;AAE5E,MAAa,mBAAkC,OAAO,iBAAiB;AAEvE,MAAM,yBAAyB;AAE/B,IAAa,UAAb,MAAa,QAAQ;CAQnB,YAAY,MAAkD;OANrD,sBAA8C,EAAE;OAIhD,oCAAyC,IAAI,KAAK;8BAmCpC;;;;;AA5BrB,MACE,CAAC,WAAW,kBAAkB,CAAC,SAAS,MAAM,aAAa,KAAK,IAChE,gBAAgB,WACf,OAAO,WAAW,YAAY,eAC7B,gBAAgB,WAAW,QAEN,MACR,SAAS,OAAO,SAAS;AACtC,QAAK,OAAO,MAAM,MAAM;KACvB,KAAK;WACC,MAAM,QAAQ,KAAK,CAC5B,MAAK,SAAS,CAAC,MAAM,WAAW;AAC9B,QAAK,OACH,MACA,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,uBAAuB,GAAG,MAC7D;IACD;WACO,KACT,QAAO,oBAAoB,KAAK,CAAC,SAAS,SAAS;GACjD,MAAM,QAAQ,KAAK;AACnB,QAAK,OACH,MACA,MAAM,QAAQ,MAAM,GAAG,MAAM,KAAK,uBAAuB,GAAG,MAC7D;IACD;;CAMN,EAAA,sBAFC,OAAO,aAEP,OAAO,aAAY;AAClB,SAAO,KAAK,SAAS;;CAGvB,CAAC,OAA0B;AACzB,OAAK,MAAM,CAAC,SAAS,KAAK,SAAS,CACjC,OAAM;;CAIV,CAAC,SAA4B;AAC3B,OAAK,MAAM,GAAG,UAAU,KAAK,SAAS,CACpC,OAAM;;CAIV,CAAC,UAAuC;EAEtC,IAAI,aAAa,OAAO,KAAK,KAAK,oBAAoB,CAAC,MAAM,GAAG,MAC9D,EAAE,cAAc,EAAE,CACnB;AACD,OAAK,MAAM,QAAQ,WACjB,KAAI,SAAS,aACX,MAAK,MAAM,SAAS,KAAK,cAAc,CACrC,OAAM,CAAC,MAAM,MAAM;MAGrB,OAAM,CAAC,MAAM,KAAK,IAAI,KAAK,CAAC;;;;;CAQlC,IAAI,MAAuB;AACzB,MAAI,CAAC,kBAAkB,KAAK,CAC1B,OAAM,IAAI,UAAU,wBAAwB,KAAK,GAAG;AAGtD,SAAO,KAAK,oBAAoB,eAAe,oBAAoB,KAAK,CAAC;;;;;CAM3E,IAAI,MAA6B;AAC/B,MAAI,CAAC,kBAAkB,KAAK,CAC1B,OAAM,UAAU,wBAAwB,KAAK,GAAG;AAGlD,SAAO,KAAK,oBAAoB,oBAAoB,KAAK,KAAK;;;;;CAMhE,IAAI,MAAc,OAAqB;AACrC,MAAI,CAAC,kBAAkB,KAAK,IAAI,CAAC,mBAAmB,MAAM,CACxD;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;EAChD,MAAM,kBAAkB,qBAAqB,MAAM;AAEnD,OAAK,oBAAoB,kBACvB,qBAAqB,gBAAgB;AACvC,OAAK,kBAAkB,IAAI,gBAAgB,KAAK;;;;;CAMlD,OAAO,MAAc,OAAqB;AACxC,MAAI,CAAC,kBAAkB,KAAK,IAAI,CAAC,mBAAmB,MAAM,CACxD;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;EAChD,MAAM,kBAAkB,qBAAqB,MAAM;EAEnD,IAAI,gBAAgB,KAAK,IAAI,eAAe,GACxC,GAAG,KAAK,IAAI,eAAe,CAAC,IAAI,oBAChC;AAEJ,OAAK,IAAI,MAAM,cAAc;;;;;CAM/B,OAAO,MAAoB;AACzB,MAAI,CAAC,kBAAkB,KAAK,CAC1B;AAGF,MAAI,CAAC,KAAK,IAAI,KAAK,CACjB;EAGF,MAAM,iBAAiB,oBAAoB,KAAK;AAChD,SAAO,KAAK,oBAAoB;AAChC,OAAK,kBAAkB,OAAO,eAAe;;;;;;CAO/C,QACE,UAMA,SACA;AACA,OAAK,MAAM,CAAC,MAAM,UAAU,KAAK,SAAS,CACxC,UAAS,KAAK,SAAS,OAAO,MAAM,KAAK;;;;;;;CAS7C,eAAyB;EACvB,MAAM,kBAAkB,KAAK,IAAI,aAAa;AAE9C,MAAI,oBAAoB,KACtB,QAAO,EAAE;AAGX,MAAI,oBAAoB,GACtB,QAAO,CAAC,GAAG;AAGb,SAAO,mBAAmB,gBAAgB;;;;;;;;AC9L9C,SAAgB,cAAc,SAAkB;CAC9C,MAAM,aAAqC,EAAE;AAE7C,MAAK,MAAM,CAAC,MAAM,UAAU,QAAQ,SAAS,CAC3C,YAAW,QAAQ,kBAAkB,IAAI,KAAK,IAAI;AAGpD,QAAO;;;;ACVT,SAAgB,cAAc,SAA+B;CAC3D,MAAM,cAA2B,EAAE;AAEnC,SAAQ,SAAS,OAAO,SAAS;EAC/B,MAAM,gBAAgB,MAAM,SAAS,IAAI,GACrC,MAAM,MAAM,IAAI,CAAC,KAAK,UAAU,MAAM,MAAM,CAAC,GAC7C;AAEJ,cAAY,KAAK,CAAC,MAAM,cAAc,CAAC;GACvC;AAEF,QAAO;;;;;;;ACRT,SAAgB,gBAAgB,SAA0B;AAOxD,QANa,cAAc,QAAQ,CAChB,KAAK,CAAC,MAAM,WAAW;AAExC,SAAO,GAAG,KAAK,IADC,EAAE,CAAc,OAAO,MAAM,CACnB,KAAK,KAAK;GACpC,CAEW,KAAK,OAAO;;;;ACR3B,MAAM,qBAAqB,CAAC,aAAa;;;;;AAMzC,SAAgB,gBAAgB,SAAiC;CAC/D,MAAM,gBAA+B,EAAE;AAEvC,SAAQ,SAAS,OAAO,SAAS;AAG/B,gBAAc,QADZ,CAAC,mBAAmB,SAAS,KAAK,aAAa,CAAC,IAAI,MAAM,SAAS,IAAI,GAErE,MAAM,MAAM,IAAI,CAAC,KAAK,MAAM,EAAE,MAAM,CAAC,GACrC;GACJ;AAEF,QAAO;;;;;;;;ACfT,SAAgB,gBAAgB,KAAsB;AAGpD,QAFc,IAAI,MAAM,CAAC,MAAM,UAAU,CAE5B,QAAQ,SAAS,SAAS;AACrC,MAAI,KAAK,MAAM,KAAK,GAClB,QAAO;EAGT,MAAM,QAAQ,KAAK,MAAM,KAAK;EAC9B,MAAM,OAAO,MAAM,OAAO;EAC1B,MAAM,QAAQ,MAAM,KAAK,KAAK;AAC9B,UAAQ,OAAO,MAAM,MAAM;AAE3B,SAAO;IACN,IAAI,SAAS,CAAC;;;;ACjBnB,SAAgB,cAAc,MAA4B;CACxD,MAAM,UAAU,IAAI,SAAS;AAE7B,MAAK,SAAS,CAAC,MAAM,WAAW;AACd,IAAE,CAAc,OAAO,MAAM,CAEtC,SAAS,UAAU;AACxB,WAAQ,OAAO,MAAM,MAAM;IAC3B;GACF;AAEF,QAAO;;;;;;;ACTT,SAAgB,oBACd,SACA,SACA,cACG;AACH,QAAO,OAAO,KAAK,QAAQ,CAAC,QAAW,aAAa,SAAS;AAC3D,SAAO,QAAQ,aAAa,MAAM,QAAQ,MAAM;IAC/C,aAAa;;;;;;;ACNlB,SAAgB,gBACd,eACS;AACT,QAAO,oBACL,gBACC,SAAS,MAAM,UAAU;AACR,IAAE,CAAc,OAAO,MAAM,CAAC,OAAO,QAAQ,CAEtD,SAAS,UAAU;AACxB,WAAQ,OAAO,MAAM,MAAM;IAC3B;AAEF,SAAO;IAET,IAAI,SAAS,CACd;;;;ACnBH,SAAgB,mBAAmB,MAAoC;AACrE,QAAO,KAAK,KAAK,CAAC,MAAM,YAAY;AAClC,SAAO,CAAC,MAAO,EAAE,CAAc,OAAO,OAAO,CAAC,KAAK,KAAK,CAAC;GACzD;;;;ACFJ,SAAgB,qBACd,eACmB;AACnB,QAAO,oBACL,gBACC,SAAS,MAAM,UAAU;AACxB,UAAQ,QAAS,EAAE,CAAc,OAAO,MAAM,CAAC,KAAK,KAAK;AACzD,SAAO;IAET,EAAE,CACH"} \ No newline at end of file diff --git a/node_modules/headers-polyfill/package.json b/node_modules/headers-polyfill/package.json new file mode 100644 index 0000000000000000000000000000000000000000..82018f44f6b78e445060b8ac14e7fec91289d948 --- /dev/null +++ b/node_modules/headers-polyfill/package.json @@ -0,0 +1,50 @@ +{ + "type": "module", + "name": "headers-polyfill", + "version": "5.0.1", + "description": "A native \"Headers\" class polyfill.", + "main": "./lib/index.cjs", + "module": "./lib/index.mjs", + "exports": { + ".": { + "require": { + "types": "./lib/index.d.cts", + "default": "./lib/index.cjs" + }, + "default": { + "types": "./lib/index.d.mts", + "default": "./lib/index.mjs" + } + } + }, + "repository": { + "type": "http", + "url": "https://github.com/mswjs/headers-polyfill" + }, + "author": "Artem Zakharchenko", + "license": "MIT", + "files": [ + "./lib", + "./src", + "README.md" + ], + "devDependencies": { + "@ossjs/release": "^0.10.1", + "jsdom": "^28.1.0", + "publint": "^0.3.18", + "tsdown": "^0.21.0", + "typescript": "^5.9.3", + "vitest": "^4.0.18" + }, + "dependencies": { + "@types/set-cookie-parser": "^2.4.10", + "set-cookie-parser": "^3.0.1" + }, + "scripts": { + "start": "tsdown --watch", + "build": "tsdown", + "test": "vitest", + "lint": "publint", + "release": "release publish" + } +} \ No newline at end of file diff --git a/node_modules/headers-polyfill/src/Headers.test.ts b/node_modules/headers-polyfill/src/Headers.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3671ebbd1e34986cb42a8c6b57f0e69b4689348a --- /dev/null +++ b/node_modules/headers-polyfill/src/Headers.test.ts @@ -0,0 +1,483 @@ +/** + * @jest-environment jsdom + */ +import { Headers } from './Headers' + +describe('constructor()', () => { + it('can be created without any arguments', () => { + const headers = new Headers() + expect(Object.fromEntries(headers.entries())).toEqual({}) + }) + + it('can be created given a Headers instance', () => { + const headers = new Headers(new window.Headers({ Accept: '*/*' })) + expect(Object.fromEntries(headers.entries())).toEqual({ accept: '*/*' }) + }) + + it('can be created given a polyfilled Headers instance', () => { + const firstHeaders = new Headers({ Accept: '*/*' }) + const headers = new Headers(firstHeaders) + expect(Object.fromEntries(headers.entries())).toEqual({ accept: '*/*' }) + }) + + it('can be created given a ["name", "a"] list', () => { + const headers = new Headers([['accept', '*/*']]) + expect(headers.get('accept')).toEqual('*/*') + }) + + it('can be created given a ["name", ["a", "b"]] list', () => { + const headers = new Headers([['accept', ['application/json', 'image/png']]]) + expect(headers.get('accept')).toEqual('application/json, image/png') + }) + + it('can be created given a ["name", "a, b"] list', () => { + const headers = new Headers([['accept', 'application/json, image/png']]) + expect(headers.get('accept')).toEqual('application/json, image/png') + }) + + it('can be created given an headers object', () => { + const headers = new Headers({ accept: '*/*' }) + expect(headers.get('accept')).toEqual('*/*') + }) + + it('can be created given an object with a null prototype', () => { + const headersInit = Object.create(null) + headersInit.accept = '*/*' + const headers = new Headers(headersInit) + expect(headers.get('accept')).toEqual('*/*') + }) + + it('duplicates values for the same header names with different casing', () => { + const headers = new Headers({ + 'accept-encoding': 'gzip, deflate, br', + 'Accept-Encoding': 'gzip, deflate, br', + }) + expect(headers.get('accept-encoding')).toEqual( + 'gzip, deflate, br, gzip, deflate, br' + ) + }) +}) + +describe('[Symbol.iterator]', () => { + it('returns the iterator with the [name, value] pairs', () => { + const headers = new Headers({ + accept: '*/*', + 'accept-language': 'en-US', + 'content-type': 'application/json', + }) + + const entries: Array<[string, string]> = [] + + for (const entry of headers) { + entries.push(entry) + } + + expect(entries).toEqual([ + ['accept', '*/*'], + ['accept-language', 'en-US'], + ['content-type', 'application/json'], + ]) + }) + + it('returns an empty iterator when there is no headers', () => { + const headers = new Headers() + const entries: Array<[string, string]> = [] + + for (const entry of headers) { + entries.push(entry) + } + + expect(entries).toEqual([]) + }) +}) + +describe('[Symbol.toStringTag]', () => { + it('returns "[object Headers]" when called', () => { + expect(new Headers().toString()).toEqual('[object Headers]') + }) +}) + +describe('.keys()', () => { + it('returns the iterator with the header keys', () => { + const headers = new Headers({ + accept: '*/*', + 'accept-language': 'en-US', + 'content-type': 'application/json', + }) + const keys: Array = [] + + for (const name of headers.keys()) { + keys.push(name) + } + + expect(keys).toEqual(['accept', 'accept-language', 'content-type']) + }) + + it('returns an empty iterator when there is no headers', () => { + const headers = new Headers() + const keys: Array = [] + + for (const name of headers.keys()) { + keys.push(name) + } + + expect(keys).toEqual([]) + }) + + it('sorts returned keys alphabetically', () => { + const headers = new Headers() + headers.set('X-B', '1') + headers.set('X-A', '2') + headers.set('X-C', '3') + expect(Array.from(headers.keys())).toEqual(['x-a', 'x-b', 'x-c']) + }) + + it('does not combine set-cookie headers', () => { + const headers = new Headers() + headers.append('Set-Cookie', 'a=1') + headers.append('Set-Cookie', 'b=2') + expect(Array.from(headers.keys())).toEqual(['set-cookie', 'set-cookie']) + }) + + if (process.version.startsWith('22.')) { + it('returns an iterator with [Symbol.dispose] defined', () => { + const headers = new Headers() + expect(headers.keys()[Symbol.dispose]).toBeInstanceOf(Function) + }) + } +}) + +describe('.values()', () => { + it('returns the iterator with the header values', () => { + const headers = new Headers({ + accept: '*/*', + 'accept-language': 'en-US', + 'content-type': 'application/json', + }) + const values: Array = [] + + for (const value of headers.values()) { + values.push(value) + } + + expect(values).toEqual(['*/*', 'en-US', 'application/json']) + }) + + it('returns an empty iterator when there is no headers', () => { + const headers = new Headers() + const values: Array = [] + + for (const value of headers.values()) { + values.push(value) + } + + expect(values).toEqual([]) + }) + + it('sorts returned values alphabetically', () => { + const headers = new Headers() + headers.set('X-B', '1') + headers.set('X-A', '2') + headers.set('X-C', '3') + expect(Array.from(headers.values())).toEqual(['2', '1', '3']) + }) + + it('does not combine set-cookie headers', () => { + const headers = new Headers() + headers.append('Set-Cookie', 'a=1') + headers.append('Set-Cookie', 'b=2') + expect(Array.from(headers.values())).toEqual(['a=1', 'b=2']) + }) + + if (process.version.startsWith('22.')) { + it('returns an iterator with [Symbol.dispose] defined', () => { + const headers = new Headers() + expect(headers.values()[Symbol.dispose]).toBeInstanceOf(Function) + }) + } +}) + +describe('.entries()', () => { + it('returns the iterator with the [name, value] pairs', () => { + const headers = new Headers({ + accept: '*/*', + 'accept-language': 'en-US', + 'content-type': 'application/json', + }) + const entries: Array<[string, string]> = [] + + for (const entry of headers.entries()) { + entries.push(entry) + } + + expect(entries).toEqual([ + ['accept', '*/*'], + ['accept-language', 'en-US'], + ['content-type', 'application/json'], + ]) + }) + + it('returns an empty iterator when there is no headers', () => { + const headers = new Headers() + const entries: Array<[string, string]> = [] + + for (const entry of headers.entries()) { + entries.push(entry) + } + + expect(entries).toEqual([]) + }) + + it('sorts alphabetically', () => { + const headers = new Headers() + headers.set('X-B', '1') + headers.set('X-A', '2') + headers.set('X-C', '3') + expect(Array.from(headers.entries())).toEqual([ + ['x-a', '2'], + ['x-b', '1'], + ['x-c', '3'], + ]) + }) + + it('does not combine set-cookie headers', () => { + const headers = new Headers() + headers.append('Set-Cookie', 'a=1') + headers.append('Set-Cookie', 'b=2') + expect(Array.from(headers.entries())).toEqual([ + ['set-cookie', 'a=1'], + ['set-cookie', 'b=2'], + ]) + }) + + if (process.version.startsWith('22.')) { + it('returns an iterator with [Symbol.dispose] defined', () => { + const headers = new Headers() + expect(headers.entries()[Symbol.dispose]).toBeInstanceOf(Function) + }) + } +}) + +describe('.has()', () => { + it('throws a TypeError given an invalid header name', () => { + const headers = new Headers() + expect(() => + headers.has( + // @ts-expect-error + 123 + ) + ).toThrow(new TypeError('Invalid header name "123"')) + }) + + it('returns true given an existing header name', () => { + const headers = new Headers({ accept: '*/*' }) + expect(headers.has('accept')).toBe(true) + expect(headers.has('AcCePt')).toBe(true) + }) + + it('returns false given a non-existing header name', () => { + const headers = new Headers({ accept: '*/*' }) + expect(headers.has('content-type')).toBe(false) + expect(headers.has('CoNtEnT-TyPe')).toBe(false) + }) +}) + +describe('.get()', () => { + it('throws a TypeError given an invalid header name', () => { + const headers = new Headers() + expect(() => + headers.get( + // @ts-expect-error + 123 + ) + ).toThrow(new TypeError('Invalid header name "123"')) + }) + + it('returns the value of the existing header name', () => { + const headers = new Headers({ 'Content-Type': 'text/plain' }) + expect(headers.get('Content-Type')).toEqual('text/plain') + expect(headers.get('content-type')).toEqual('text/plain') + expect(headers.get('CoNtEnT-TyPe')).toEqual('text/plain') + }) + + it('returns null given a non-existing header name', () => { + const headers = new Headers({ 'Content-Type': 'text/plain' }) + expect(headers.get('accept')).toBeNull() + expect(headers.get('Accept')).toBeNull() + expect(headers.get('AcCePt')).toBeNull() + }) + + it('return an empty string for an empty header value', () => { + const headers = new Headers({ 'Content-Type': '' }) + expect(headers.get('Content-Type')).toEqual('') + }) +}) + +describe('.set()', () => { + it('returns if given an invalid header name', () => { + const headers = new Headers() + expect( + headers.set( + // @ts-expect-error + 123, + 'value' + ) + ).toBeUndefined() + expect(Object.fromEntries(headers.entries())).toEqual({}) + }) + + it('returns if given an invalid header value', () => { + const headers = new Headers() + expect( + headers.set( + 'foo', + // @ts-expect-error + 123 + ) + ).toBeUndefined() + expect(headers.set('foo', ' value ')).toBeUndefined() + expect(Object.fromEntries(headers.entries())).toEqual({}) + }) + + it('sets a new header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.set('content-type', 'application/json') + expect(headers.get('accept')).toEqual('*/*') + expect(headers.get('content-type')).toEqual('application/json') + }) + + it('overrides an existing header with the same name', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.set('accept', 'image/png') + expect(headers.get('accept')).toEqual('image/png') + + headers.set('AcCePt', 'text/plain') + expect(headers.get('accept')).toEqual('text/plain') + }) +}) + +describe('.append()', () => { + it('appends a new header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.append('content-type', 'application/json') + expect(headers.get('accept')).toEqual('*/*') + expect(headers.get('content-type')).toEqual('application/json') + }) + + it('joins the values with the existing header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.append('accept', 'image/png') + expect(headers.get('accept')).toEqual('*/*, image/png') + }) + + it('duplicates values with the existing header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.append('Accept', '*/*') + expect(headers.get('accept')).toEqual('*/*, */*') + }) +}) + +describe('.delete()', () => { + it('returns if given an invalid header name', () => { + const headers = new Headers({ accept: '*/*' }) + expect( + headers.delete( + // @ts-expect-error + 123 + ) + ).toBeUndefined() + expect(Object.fromEntries(headers.entries())).toEqual({ + accept: '*/*', + }) + }) + + it('deletes the existing header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.delete('accept') + expect(headers.has('accept')).toBe(false) + expect(headers.has('AcCePt')).toBe(false) + expect(headers.get('accept')).toBeNull() + expect(headers.get('AcCePt')).toBeNull() + }) + + it('does nothing given a non-existing header', () => { + const headers = new Headers({ accept: '*/*' }) + + headers.delete('content-type') + expect(headers.get('accept')).toEqual('*/*') + expect(headers.get('AcCePt')).toEqual('*/*') + }) +}) + +describe('.forEach()', () => { + it('traverses each header once', () => { + const headers = new Headers({ accept: '*/*', 'user-agent': 'agent' }) + const headerSet = new Set() + + headers.forEach((value, name, headers) => { + expect(value).toBe(headers.get(name)) + expect(headerSet.has(name)).toBe(false) + headerSet.add(name) + }) + + // `Headers.forEach` returns normalized lowercase names. + expect(headerSet).toEqual(new Set(['accept', 'user-agent'])) + }) + + it('traverses each header once with a custom "this" argument', () => { + const headers = new Headers({ accept: '*/*', 'User-Agent': 'agent' }) + const headerSet = new Set() + + headers.forEach(function (value, name, headers) { + expect(value).toBe(headers.get(name)) + expect(this.has(name)).toBe(false) + this.add(name) + }, headerSet) + + expect(headerSet).toEqual(new Set(['accept', 'user-agent'])) + }) +}) + +describe('.getSetCookie()', () => { + it('returns an empty array given no Set-Cookie headers', () => { + const headers = new Headers() + expect(headers.getSetCookie()).toEqual([]) + }) + + it('returns empty string if Set-Cookie header was set to empty string', () => { + const headers = new Headers({ 'Set-Cookie': '' }) + expect(headers.getSetCookie()).toEqual(['']) + }) + + it('returns a list of a single existing Set-Cookie header', () => { + const headers = new Headers({ + 'Set-Cookie': 'name=cookie; Expires=Wed, 21 Oct 2015 07:28:00 GMT', + }) + expect(headers.getSetCookie()).toEqual([ + 'name=cookie; Expires=Wed, 21 Oct 2015 07:28:00 GMT', + ]) + }) + + it('returns a list of all existing Set-Cookie headers', () => { + const headers = new Headers() + headers.append( + 'Set-Cookie', + 'name=cookie; Expires=Wed, 21 Oct 2015 07:28:00 GMT' + ) + headers.append( + 'Set-Cookie', + 'name=session; Expires=Wed, 21 Oct 2015 07:28:00 GMT' + ) + + expect(headers.getSetCookie()).toEqual([ + 'name=cookie; Expires=Wed, 21 Oct 2015 07:28:00 GMT', + 'name=session; Expires=Wed, 21 Oct 2015 07:28:00 GMT', + ]) + }) +}) diff --git a/node_modules/headers-polyfill/src/Headers.ts b/node_modules/headers-polyfill/src/Headers.ts new file mode 100644 index 0000000000000000000000000000000000000000..c9794c374287cd9e1c76eb29288cd058c85d7265 --- /dev/null +++ b/node_modules/headers-polyfill/src/Headers.ts @@ -0,0 +1,198 @@ +import { splitCookiesString } from 'set-cookie-parser' +import { HeadersList, HeadersObject } from './glossary' +import { normalizeHeaderName } from './utils/normalizeHeaderName' +import { normalizeHeaderValue } from './utils/normalizeHeaderValue' +import { isValidHeaderName } from './utils/isValidHeaderName' +import { isValidHeaderValue } from './utils/isValidHeaderValue' + +export const NORMALIZED_HEADERS: unique symbol = Symbol('normalizedHeaders') + +export const RAW_HEADER_NAMES: unique symbol = Symbol('rawHeaderNames') + +const HEADER_VALUE_DELIMITER = ', ' as const + +export class Headers { + // Normalized header {"name":"a, b"} storage. + private [NORMALIZED_HEADERS]: Record = {} + + // Keeps the mapping between the raw header name + // and the normalized header name to ease the lookup. + private [RAW_HEADER_NAMES]: Map = new Map() + + constructor(init?: HeadersInit | HeadersObject | HeadersList) { + /** + * @note Cannot necessarily check if the `init` is an instance of the + * `Headers` because that class may not be defined in Node or jsdom. + */ + if ( + ['Headers', 'HeadersPolyfill'].includes(init?.constructor?.name) || + init instanceof Headers || + (typeof globalThis.Headers !== 'undefined' && + init instanceof globalThis.Headers) + ) { + const initialHeaders = init as Headers + initialHeaders.forEach((value, name) => { + this.append(name, value) + }, this) + } else if (Array.isArray(init)) { + init.forEach(([name, value]) => { + this.append( + name, + Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value + ) + }) + } else if (init) { + Object.getOwnPropertyNames(init).forEach((name) => { + const value = init[name] + this.append( + name, + Array.isArray(value) ? value.join(HEADER_VALUE_DELIMITER) : value + ) + }) + } + } + + [Symbol.toStringTag] = 'Headers'; + + [Symbol.iterator]() { + return this.entries() + } + + *keys(): Generator { + for (const [name] of this.entries()) { + yield name + } + } + + *values(): Generator { + for (const [, value] of this.entries()) { + yield value + } + } + + *entries(): Generator<[string, string]> { + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + let sortedKeys = Object.keys(this[NORMALIZED_HEADERS]).sort((a, b) => + a.localeCompare(b) + ) + for (const name of sortedKeys) { + if (name === 'set-cookie') { + for (const value of this.getSetCookie()) { + yield [name, value] + } + } else { + yield [name, this.get(name)] + } + } + } + + /** + * Returns a boolean stating whether a `Headers` object contains a certain header. + */ + has(name: string): boolean { + if (!isValidHeaderName(name)) { + throw new TypeError(`Invalid header name "${name}"`) + } + + return this[NORMALIZED_HEADERS].hasOwnProperty(normalizeHeaderName(name)) + } + + /** + * Returns a `ByteString` sequence of all the values of a header with a given name. + */ + get(name: string): string | null { + if (!isValidHeaderName(name)) { + throw TypeError(`Invalid header name "${name}"`) + } + + return this[NORMALIZED_HEADERS][normalizeHeaderName(name)] ?? null + } + + /** + * Sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + set(name: string, value: string): void { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) { + return + } + + const normalizedName = normalizeHeaderName(name) + const normalizedValue = normalizeHeaderValue(value) + + this[NORMALIZED_HEADERS][normalizedName] = + normalizeHeaderValue(normalizedValue) + this[RAW_HEADER_NAMES].set(normalizedName, name) + } + + /** + * Appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. + */ + append(name: string, value: string): void { + if (!isValidHeaderName(name) || !isValidHeaderValue(value)) { + return + } + + const normalizedName = normalizeHeaderName(name) + const normalizedValue = normalizeHeaderValue(value) + + let resolvedValue = this.has(normalizedName) + ? `${this.get(normalizedName)}, ${normalizedValue}` + : normalizedValue + + this.set(name, resolvedValue) + } + + /** + * Deletes a header from the `Headers` object. + */ + delete(name: string): void { + if (!isValidHeaderName(name)) { + return + } + + if (!this.has(name)) { + return + } + + const normalizedName = normalizeHeaderName(name) + delete this[NORMALIZED_HEADERS][normalizedName] + this[RAW_HEADER_NAMES].delete(normalizedName) + } + + /** + * Traverses the `Headers` object, + * calling the given callback for each header. + */ + forEach( + callback: ( + this: ThisArg, + value: string, + name: string, + parent: this + ) => void, + thisArg?: ThisArg + ) { + for (const [name, value] of this.entries()) { + callback.call(thisArg, value, name, this) + } + } + + /** + * Returns an array containing the values + * of all Set-Cookie headers associated + * with a response + */ + getSetCookie(): string[] { + const setCookieHeader = this.get('set-cookie') + + if (setCookieHeader === null) { + return [] + } + + if (setCookieHeader === '') { + return [''] + } + + return splitCookiesString(setCookieHeader) + } +} diff --git a/node_modules/headers-polyfill/src/getRawHeaders.test.ts b/node_modules/headers-polyfill/src/getRawHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..061918acc557b02f3a30eaf6406a43b05b856f5b --- /dev/null +++ b/node_modules/headers-polyfill/src/getRawHeaders.test.ts @@ -0,0 +1,19 @@ +import { Headers } from './Headers' +import { getRawHeaders } from './getRawHeaders' + +it('returns a headers objects with the raw names', () => { + const headers = new Headers({ + Accept: '*/*', + 'ConTent-Type': ['application/json', 'text/plain'], + }) + expect(getRawHeaders(headers)).toEqual({ + Accept: '*/*', + 'ConTent-Type': 'application/json, text/plain', + }) +}) + +it('returns an empty object when there is no headers', () => { + expect(getRawHeaders(new Headers())).toEqual({}) + expect(getRawHeaders(new Headers({}))).toEqual({}) + expect(getRawHeaders(new Headers([]))).toEqual({}) +}) diff --git a/node_modules/headers-polyfill/src/getRawHeaders.ts b/node_modules/headers-polyfill/src/getRawHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1835f52e039517e503be528e5cbdeef938bc7e5 --- /dev/null +++ b/node_modules/headers-polyfill/src/getRawHeaders.ts @@ -0,0 +1,14 @@ +import { RAW_HEADER_NAMES } from './Headers' + +/** + * Returns the object of all raw headers. + */ +export function getRawHeaders(headers: Headers) { + const rawHeaders: Record = {} + + for (const [name, value] of headers.entries()) { + rawHeaders[headers[RAW_HEADER_NAMES].get(name)] = value + } + + return rawHeaders +} diff --git a/node_modules/headers-polyfill/src/glossary.ts b/node_modules/headers-polyfill/src/glossary.ts new file mode 100644 index 0000000000000000000000000000000000000000..777e466f83f6aafb166e82c496fbfc086bc0002d --- /dev/null +++ b/node_modules/headers-polyfill/src/glossary.ts @@ -0,0 +1,4 @@ +export type HeadersList = Array<[string, string | string[]]> +export type FlatHeadersList = [string, string][] +export type HeadersObject = Record +export type FlatHeadersObject = Record diff --git a/node_modules/headers-polyfill/src/index.ts b/node_modules/headers-polyfill/src/index.ts new file mode 100644 index 0000000000000000000000000000000000000000..8f36b19a48f78353ba6ce5b480f14cbaafedd7db --- /dev/null +++ b/node_modules/headers-polyfill/src/index.ts @@ -0,0 +1,21 @@ +export { Headers } from './Headers' + +export { getRawHeaders } from './getRawHeaders' +export { headersToString } from './transformers/headersToString' +export { headersToList } from './transformers/headersToList' +export { headersToObject } from './transformers/headersToObject' +export { stringToHeaders } from './transformers/stringToHeaders' +export { listToHeaders } from './transformers/listToHeaders' +export { objectToHeaders } from './transformers/objectToHeaders' + +export { reduceHeadersObject } from './transformers/reduceHeadersObject' +export { flattenHeadersList } from './transformers/flattenHeadersList' +export { flattenHeadersObject } from './transformers/flattenHeadersObject' + +/* Typings */ +export type { + HeadersList, + FlatHeadersList, + HeadersObject, + FlatHeadersObject, +} from './glossary' diff --git a/node_modules/headers-polyfill/src/transformers/appendHeader.test.ts b/node_modules/headers-polyfill/src/transformers/appendHeader.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9418ad6875d9d7b5b885c3360b8609d85d534dbc --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/appendHeader.test.ts @@ -0,0 +1,62 @@ +import { appendHeader } from './appendHeader' + +describe('appendHeader', () => { + describe('given appending a non-existing header', () => { + describe('with a single new value', () => { + it('should create it and assign the value', () => { + const headers = appendHeader({}, 'content-type', 'application/json') + expect(headers).toHaveProperty('content-type', 'application/json') + }) + }) + + describe('with multiple new values', () => { + it('should create a list of values', () => { + const headers = appendHeader({}, 'accept', [ + 'application/json', + 'text/plain', + ]) + expect(headers).toHaveProperty('accept', [ + 'application/json', + 'text/plain', + ]) + }) + }) + }) + + describe('given appending to an existing header', () => { + describe('with a single new value', () => { + it('should append a single value to existing values', () => { + const headers = appendHeader( + { + 'content-type': 'application/json', + }, + 'content-type', + 'image/png' + ) + + expect(headers).toHaveProperty('content-type', [ + 'application/json', + 'image/png', + ]) + }) + }) + + describe('with multiple new values', () => { + it('should merge multiple values with existing values', () => { + const headers = appendHeader( + { + 'content-type': 'application/json', + }, + 'content-type', + ['image/png', 'text/plain'] + ) + + expect(headers).toHaveProperty('content-type', [ + 'application/json', + 'image/png', + 'text/plain', + ]) + }) + }) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/appendHeader.ts b/node_modules/headers-polyfill/src/transformers/appendHeader.ts new file mode 100644 index 0000000000000000000000000000000000000000..a501c29fdfb39311cc8b5e4d19a6a42fb7a72910 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/appendHeader.ts @@ -0,0 +1,21 @@ +import { HeadersObject } from '../glossary' + +/** + * Appends a given header to the headers object. + * Converts multiple values into a list. + */ +export function appendHeader( + headers: HeadersObject, + name: string, + value: string | string[] +): HeadersObject { + if (headers.hasOwnProperty(name)) { + return Object.assign({}, headers, { + [name]: ([] as string[]).concat(headers[name]).concat(value), + }) + } + + return Object.assign({}, headers, { + [name]: value, + }) +} diff --git a/node_modules/headers-polyfill/src/transformers/flattenHeadersList.test.ts b/node_modules/headers-polyfill/src/transformers/flattenHeadersList.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..700004a65d069d3c9ff41aee4ffd3ca3ce4539e1 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/flattenHeadersList.test.ts @@ -0,0 +1,16 @@ +import { HeadersList } from '../glossary' +import { flattenHeadersList } from './flattenHeadersList' + +describe('given a headers list', () => { + it('flattens its multi-value headers', () => { + const headersList: HeadersList = [ + ['accept', ['application/json', 'text/xml']], + ['content-type', 'application/pdf'], + ] + + expect(flattenHeadersList(headersList)).toEqual([ + ['accept', 'application/json, text/xml'], + ['content-type', 'application/pdf'], + ]) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/flattenHeadersList.ts b/node_modules/headers-polyfill/src/transformers/flattenHeadersList.ts new file mode 100644 index 0000000000000000000000000000000000000000..a270e00aad9ab840bfc3284371271b1e5d14887e --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/flattenHeadersList.ts @@ -0,0 +1,7 @@ +import { HeadersList, FlatHeadersList } from '../glossary' + +export function flattenHeadersList(list: HeadersList): FlatHeadersList { + return list.map(([name, values]) => { + return [name, ([] as string[]).concat(values).join(', ')] + }) +} diff --git a/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.test.ts b/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..86309ba46885024aa05c136ae26d987a3759dd45 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.test.ts @@ -0,0 +1,16 @@ +import { flattenHeadersObject } from './flattenHeadersObject' +import { HeadersObject } from '../glossary' + +describe('given a headers object', () => { + it('flattens its multi-value headers', () => { + const headersObject: HeadersObject = { + Accept: ['application/json', 'text/xml'], + 'Content-Type': 'application/pdf', + } + + expect(flattenHeadersObject(headersObject)).toEqual({ + Accept: 'application/json, text/xml', + 'Content-Type': 'application/pdf', + }) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.ts b/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..6fdecbd6fd16b0ad0d1cdf2009323773e87e92c9 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/flattenHeadersObject.ts @@ -0,0 +1,15 @@ +import { HeadersObject, FlatHeadersObject } from '../glossary' +import { reduceHeadersObject } from './reduceHeadersObject' + +export function flattenHeadersObject( + headersObject: HeadersObject +): FlatHeadersObject { + return reduceHeadersObject( + headersObject, + (headers, name, value) => { + headers[name] = ([] as string[]).concat(value).join(', ') + return headers + }, + {} + ) +} diff --git a/node_modules/headers-polyfill/src/transformers/headersToList.node.test.ts b/node_modules/headers-polyfill/src/transformers/headersToList.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..f5ca9b798746086e657a10d883dd99d6ee5bc68c --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToList.node.test.ts @@ -0,0 +1,40 @@ +/** + * @jest-environment node + */ +import { Headers } from '../Headers' +import { headersToList } from './headersToList' + +describe('given Headers with a single header', () => { + it('should return its list representation', () => { + const headers = new Headers({ Accept: 'application/json' }) + expect(headersToList(headers)).toEqual([['accept', 'application/json']]) + }) +}) + +describe('given Headers with a single header and multiple values', () => { + it('should return those values in a nested list', () => { + const headers = new Headers({ Accept: 'application/json' }) + headers.append('Accept', 'text/plain') + + expect(headersToList(headers)).toEqual([ + ['accept', ['application/json', 'text/plain']], + ]) + }) +}) + +describe('given Headers with various headers', () => { + it('should return their list representation', () => { + const headers = new Headers({ + Accept: 'application/json', + 'Content-Length': '1234', + 'Content-Type': 'text/xml', + }) + headers.append('Accept', 'text/plain') + + expect(headersToList(headers)).toEqual([ + ['accept', ['application/json', 'text/plain']], + ['content-length', '1234'], + ['content-type', 'text/xml'], + ]) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/headersToList.test.ts b/node_modules/headers-polyfill/src/transformers/headersToList.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..e460ceba985e4fe6818718cd3641347dcc4a8e62 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToList.test.ts @@ -0,0 +1,39 @@ +/** + * @jest-environment jsdom + */ +import { headersToList } from './headersToList' + +describe('given Headers with a single header', () => { + it('should return its list representation', () => { + const headers = new Headers({ Accept: 'application/json' }) + expect(headersToList(headers)).toEqual([['accept', 'application/json']]) + }) +}) + +describe('given Headers with a single header and multiple values', () => { + it('should return those values in a nested list', () => { + const headers = new Headers({ Accept: 'application/json' }) + headers.append('Accept', 'text/plain') + + expect(headersToList(headers)).toEqual([ + ['accept', ['application/json', 'text/plain']], + ]) + }) +}) + +describe('given Headers with various headers', () => { + it('should return their list representation', () => { + const headers = new Headers({ + Accept: 'application/json', + 'Content-Length': '1234', + 'Content-Type': 'text/xml', + }) + headers.append('Accept', 'text/plain') + + expect(headersToList(headers)).toEqual([ + ['accept', ['application/json', 'text/plain']], + ['content-length', '1234'], + ['content-type', 'text/xml'], + ]) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/headersToList.ts b/node_modules/headers-polyfill/src/transformers/headersToList.ts new file mode 100644 index 0000000000000000000000000000000000000000..903bc550d142a5cd11fe8fc9e1d3400212e5083b --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToList.ts @@ -0,0 +1,15 @@ +import { HeadersList } from '../glossary' + +export function headersToList(headers: Headers): HeadersList { + const headersList: HeadersList = [] + + headers.forEach((value, name) => { + const resolvedValue = value.includes(',') + ? value.split(',').map((value) => value.trim()) + : value + + headersList.push([name, resolvedValue]) + }) + + return headersList +} diff --git a/node_modules/headers-polyfill/src/transformers/headersToObject.node.test.ts b/node_modules/headers-polyfill/src/transformers/headersToObject.node.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fcf09bac4bdb45de82054fbe9de5d9c3d347e875 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToObject.node.test.ts @@ -0,0 +1,56 @@ +/** + * @jest-environment node + */ +import { headersToObject } from './headersToObject' +import { Headers } from '../Headers' + +describe('given Headers with a single header', () => { + it('should return that single header in an Object', () => { + const headers = new Headers({ 'Content-Type': 'application/json' }) + expect(headersToObject(headers)).toEqual({ + 'content-type': 'application/json', + }) + }) +}) + +describe('given Headers with a single header and multiple values', () => { + it('should put that header values into an array', () => { + const headers = new Headers({ Accept: 'application/json' }) + headers.append('Accept', 'text/plain') + + expect(headersToObject(headers)).toEqual({ + accept: ['application/json', 'text/plain'], + }) + }) +}) + +describe('given Headers with multiple different headers', () => { + it('should return an object representing those headers', () => { + const headers = new Headers({ + Accept: 'application/json', + 'Content-Length': '1234', + 'Content-Type': 'application/json', + }) + headers.append('Accept', 'text/plain') + + expect(headersToObject(headers)).toEqual({ + accept: ['application/json', 'text/plain'], + 'content-length': '1234', + 'content-type': 'application/json', + }) + }) +}) + +describe('given Headers with a single header that includes a semicolon', () => { + it('should preserve a single header', () => { + const headers = new Headers({ + 'user-agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.0 Safari/537.36', + }) + + expect(headersToObject(headers)).toEqual({ + 'user-agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.0 Safari/537.36', + }) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/headersToObject.test.ts b/node_modules/headers-polyfill/src/transformers/headersToObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..16ece026ce224a26f73378e0e5de556efc3e8832 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToObject.test.ts @@ -0,0 +1,55 @@ +/** + * @jest-environment jsdom + */ +import { headersToObject } from './headersToObject' + +describe('given Headers with a single header', () => { + it('should return that single header in an Object', () => { + const headers = new Headers({ 'Content-Type': 'application/json' }) + expect(headersToObject(headers)).toEqual({ + 'content-type': 'application/json', + }) + }) +}) + +describe('given Headers with a single header and multiple values', () => { + it('should put that header values into an array', () => { + const headers = new Headers({ Accept: 'application/json' }) + headers.append('Accept', 'text/plain') + + expect(headersToObject(headers)).toEqual({ + accept: ['application/json', 'text/plain'], + }) + }) +}) + +describe('given Headers with multiple different headers', () => { + it('should return an object representing those headers', () => { + const headers = new Headers({ + Accept: 'application/json', + 'Content-Length': '1234', + 'Content-Type': 'application/json', + }) + headers.append('Accept', 'text/plain') + + expect(headersToObject(headers)).toEqual({ + accept: ['application/json', 'text/plain'], + 'content-length': '1234', + 'content-type': 'application/json', + }) + }) +}) + +describe('given Headers with a single header that includes a semicolon', () => { + it('should preserve a single header', () => { + const headers = new Headers({ + 'user-agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.0 Safari/537.36', + }) + + expect(headersToObject(headers)).toEqual({ + 'user-agent': + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.0 Safari/537.36', + }) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/headersToObject.ts b/node_modules/headers-polyfill/src/transformers/headersToObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..224dfacb49d871cb7b7bf578e0e12c6c1ce9b38c --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToObject.ts @@ -0,0 +1,23 @@ +import { HeadersObject } from '../glossary' + +// List of headers that cannot have multiple values, +// while potentially having a comma in their single value. +const singleValueHeaders = ['user-agent'] + +/** + * Converts a given `Headers` instance into a plain object. + * Respects headers with multiple values. + */ +export function headersToObject(headers: Headers): HeadersObject { + const headersObject: HeadersObject = {} + + headers.forEach((value, name) => { + const isMultiValue = + !singleValueHeaders.includes(name.toLowerCase()) && value.includes(',') + headersObject[name] = isMultiValue + ? value.split(',').map((s) => s.trim()) + : value + }) + + return headersObject +} diff --git a/node_modules/headers-polyfill/src/transformers/headersToString.test.ts b/node_modules/headers-polyfill/src/transformers/headersToString.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..a2ccb468142514b1e431648f0ecdf016a4a581ce --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToString.test.ts @@ -0,0 +1,51 @@ +/** + * @jest-environment jsdom + */ +import { headersToString } from './headersToString' +import { Headers } from '../Headers' + +describe('headersToString', () => { + describe('given a standard Headers instance', () => { + it('returns its string representation', () => { + const headers = new Headers({ + date: 'Fri, 08 Dec 2017 21:04:30 GMT', + 'content-encoding': 'gzip', + 'content-type': 'text/html; charset=utf-8', + connection: 'keep-alive', + 'content-length': '6502', + }) + + expect(headersToString(headers)).toEqual( + ` +connection: keep-alive\r +content-encoding: gzip\r +content-length: 6502\r +content-type: text/html; charset=utf-8\r +date: Fri, 08 Dec 2017 21:04:30 GMT\r + `.trim() + ) + }) + }) + + describe('given a polyfill Headers instance', () => { + it('returns its string representation', () => { + const headers = new Headers({ + date: 'Fri, 08 Dec 2017 21:04:30 GMT', + 'content-encoding': 'gzip', + 'content-type': 'text/html; charset=utf-8', + connection: 'keep-alive', + 'content-length': '6502', + }) + + expect(headersToString(headers)).toEqual( + ` +connection: keep-alive\r +content-encoding: gzip\r +content-length: 6502\r +content-type: text/html; charset=utf-8\r +date: Fri, 08 Dec 2017 21:04:30 GMT\r + `.trim() + ) + }) + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/headersToString.ts b/node_modules/headers-polyfill/src/transformers/headersToString.ts new file mode 100644 index 0000000000000000000000000000000000000000..b1c9ed6e3c7afc3d8178984e8b7e2fcc7ae93b78 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/headersToString.ts @@ -0,0 +1,14 @@ +import { headersToList } from './headersToList' + +/** + * Converts a given `Headers` instance to its string representation. + */ +export function headersToString(headers: Headers): string { + const list = headersToList(headers) + const lines = list.map(([name, value]) => { + const values = ([] as string[]).concat(value) + return `${name}: ${values.join(', ')}` + }) + + return lines.join('\r\n') +} diff --git a/node_modules/headers-polyfill/src/transformers/listToHeaders.test.ts b/node_modules/headers-polyfill/src/transformers/listToHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..298123db65d9895eec20b75d65e24a0130a2cd74 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/listToHeaders.test.ts @@ -0,0 +1,19 @@ +import { listToHeaders } from './listToHeaders' +import { Headers } from '../Headers' +import { HeadersList } from '../glossary' + +describe('given a list representation of headers', () => { + it('returns a Headers instance', () => { + const list: HeadersList = [ + ['accept', ['application/json', 'text/plain']], + ['content-length', '1234'], + ['content-type', 'application/json'], + ] + + const headers = listToHeaders(list) + expect(headers).toBeInstanceOf(Headers) + expect(headers.get('accept')).toEqual('application/json, text/plain') + expect(headers.get('content-length')).toEqual('1234') + expect(headers.get('content-type')).toEqual('application/json') + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/listToHeaders.ts b/node_modules/headers-polyfill/src/transformers/listToHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..137d8d3c63ce9d3bfb5f4810f50eeb35970f6954 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/listToHeaders.ts @@ -0,0 +1,16 @@ +import { Headers } from '../Headers' +import { HeadersList } from '../glossary' + +export function listToHeaders(list: HeadersList): Headers { + const headers = new Headers() + + list.forEach(([name, value]) => { + const values = ([] as string[]).concat(value) + + values.forEach((value) => { + headers.append(name, value) + }) + }) + + return headers +} diff --git a/node_modules/headers-polyfill/src/transformers/objectToHeaders.test.ts b/node_modules/headers-polyfill/src/transformers/objectToHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6ba86a1e33fe072f9e39b7af1172f4d91d0d20a --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/objectToHeaders.test.ts @@ -0,0 +1,21 @@ +import { objectToHeaders } from './objectToHeaders' +import { Headers } from '../Headers' +import { HeadersObject } from '../glossary' + +describe('given an object representation of headers', () => { + it('returns a Headers instance', () => { + const headersObject: HeadersObject = { + Accept: ['application/json', 'text/plain'], + 'Content-Length': '1234', + 'Content-Type': 'text/xml', + 'X-Custom-Header': undefined, + } + const headers = objectToHeaders(headersObject) + + expect(headers).toBeInstanceOf(Headers) + expect(headers.get('accept')).toEqual('application/json, text/plain') + expect(headers.get('content-length')).toEqual('1234') + expect(headers.get('content-type')).toEqual('text/xml') + expect(headers.get('x-custom-header')).toBeNull() + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/objectToHeaders.ts b/node_modules/headers-polyfill/src/transformers/objectToHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..40ba72e7df93e50f8c12c83d83b441ce7343981c --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/objectToHeaders.ts @@ -0,0 +1,23 @@ +import { Headers } from '../Headers' +import { reduceHeadersObject } from './reduceHeadersObject' + +/** + * Converts a given headers object to a new `Headers` instance. + */ +export function objectToHeaders( + headersObject: Record +): Headers { + return reduceHeadersObject( + headersObject, + (headers, name, value) => { + const values = ([] as string[]).concat(value).filter(Boolean) + + values.forEach((value) => { + headers.append(name, value) + }) + + return headers + }, + new Headers() + ) +} diff --git a/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.test.ts b/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..ce124cade19d765ae26a620a139ee12d7d5eeb60 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.test.ts @@ -0,0 +1,23 @@ +import { reduceHeadersObject } from './reduceHeadersObject' +import { HeadersObject } from '../glossary' + +test('reduces headers to lowercase headers', () => { + const headers: HeadersObject = { + Accept: '*/*', + 'Content-Type': ['application/json', 'text/plain'], + } + + const lowercaseHeaders = reduceHeadersObject( + headers, + (obj, name, value) => { + obj[name.toLowerCase()] = value + return obj + }, + {} + ) + + expect(lowercaseHeaders).toEqual({ + accept: '*/*', + 'content-type': ['application/json', 'text/plain'], + }) +}) diff --git a/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.ts b/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.ts new file mode 100644 index 0000000000000000000000000000000000000000..d0a98248e6fab80868aa5b212ae7e2aa4e77a538 --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/reduceHeadersObject.ts @@ -0,0 +1,14 @@ +import { HeadersObject } from '../glossary' + +/** + * Reduces given headers object instnace. + */ +export function reduceHeadersObject( + headers: HeadersObject, + reducer: (headers: R, name: string, value: string | string[]) => R, + initialState: R +): R { + return Object.keys(headers).reduce((nextHeaders, name) => { + return reducer(nextHeaders, name, headers[name]) + }, initialState) +} diff --git a/node_modules/headers-polyfill/src/transformers/stringToHeaders.test.ts b/node_modules/headers-polyfill/src/transformers/stringToHeaders.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..c6e61d295e3c73b4ef08bd75e4c18d0cd8592cdb --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/stringToHeaders.test.ts @@ -0,0 +1,36 @@ +import { Headers } from '../Headers' +import { stringToHeaders } from './stringToHeaders' + +it('returns a Headers instance given a headers string', () => { + const headersString = ` +date: Fri, 08 Dec 2017 21:04:30 GMT\r\n +content-encoding: gzip\r\n +x-content-type-options: nosniff\r\n +server: meinheld/0.6.1\r\n +x-frame-options: DENY\r\n +content-type: text/html; charset=utf-8\r\n +connection: keep-alive\r\n +vary: Cookie, Accept-Encoding\r\n +content-length: 6502\r\n +x-xss-protection: 1; mode=block\r\n + ` + const headers = stringToHeaders(headersString) + + expect(headers).toBeInstanceOf(Headers) + expect(headers.get('date')).toEqual('Fri, 08 Dec 2017 21:04:30 GMT') + expect(headers.get('content-encoding')).toEqual('gzip') + expect(headers.get('x-content-type-options')).toEqual('nosniff') + expect(headers.get('server')).toEqual('meinheld/0.6.1') + expect(headers.get('x-frame-options')).toEqual('DENY') + expect(headers.get('content-type')).toEqual('text/html; charset=utf-8') + expect(headers.get('connection')).toEqual('keep-alive') + expect(headers.get('vary')).toEqual('Cookie, Accept-Encoding') + expect(headers.get('content-length')).toEqual('6502') + expect(headers.get('x-xss-protection')).toEqual('1; mode=block') +}) + +it('returns a Headers instance given an empty string', () => { + const headers = stringToHeaders('') + expect(headers).toBeInstanceOf(Headers) + expect(Object.fromEntries(headers)).toEqual({}) +}) diff --git a/node_modules/headers-polyfill/src/transformers/stringToHeaders.ts b/node_modules/headers-polyfill/src/transformers/stringToHeaders.ts new file mode 100644 index 0000000000000000000000000000000000000000..3ed30aa1dab0fdeeeb59c5b509ab0044316afb7a --- /dev/null +++ b/node_modules/headers-polyfill/src/transformers/stringToHeaders.ts @@ -0,0 +1,22 @@ +import { Headers } from '../Headers' + +/** + * Converts a string representation of headers (i.e. from XMLHttpRequest) + * to a new `Headers` instance. + */ +export function stringToHeaders(str: string): Headers { + const lines = str.trim().split(/[\r\n]+/) + + return lines.reduce((headers, line) => { + if (line.trim() === '') { + return headers + } + + const parts = line.split(': ') + const name = parts.shift() + const value = parts.join(': ') + headers.append(name, value) + + return headers + }, new Headers()) +} diff --git a/node_modules/headers-polyfill/src/utils/isValidHeaderName.ts b/node_modules/headers-polyfill/src/utils/isValidHeaderName.ts new file mode 100644 index 0000000000000000000000000000000000000000..72747b6c0fedf35b2a52c5b59a075270d77f3f30 --- /dev/null +++ b/node_modules/headers-polyfill/src/utils/isValidHeaderName.ts @@ -0,0 +1,47 @@ +/** + * Validate the given header name. + * @see https://fetch.spec.whatwg.org/#header-name + */ +export function isValidHeaderName(value: unknown) { + if (typeof value !== 'string') { + return false + } + + if (value.length === 0) { + return false + } + + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i) + + if (character > 0x7f || !isToken(character)) { + return false + } + } + + return true +} + +function isToken(value: string | number): boolean { + return ![ + 0x7f, + 0x20, + '(', + ')', + '<', + '>', + '@', + ',', + ';', + ':', + '\\', + '"', + '/', + '[', + ']', + '?', + '=', + '{', + '}', + ].includes(value) +} diff --git a/node_modules/headers-polyfill/src/utils/isValidHeaderValue.ts b/node_modules/headers-polyfill/src/utils/isValidHeaderValue.ts new file mode 100644 index 0000000000000000000000000000000000000000..108721f0b6246fae02a7dad6b50b0340046dd8f4 --- /dev/null +++ b/node_modules/headers-polyfill/src/utils/isValidHeaderValue.ts @@ -0,0 +1,29 @@ +/** + * Validate the given header value. + * @see https://fetch.spec.whatwg.org/#header-value + */ +export function isValidHeaderValue(value: unknown): boolean { + if (typeof value !== 'string') { + return false + } + + if (value.trim() !== value) { + return false + } + + for (let i = 0; i < value.length; i++) { + const character = value.charCodeAt(i) + + if ( + // NUL. + character === 0x00 || + // HTTP newline bytes. + character === 0x0a || + character === 0x0d + ) { + return false + } + } + + return true +}