Skip to content

@lanexio/parser-grammar-graphql

This page documents @lanexio/parser-grammar-graphql, the GraphQL grammar package for Lanexio™ Parser implementing the GraphQL October 2021 specification with auto-detection of executable documents vs schema definition language (SDL). The package also ships the first-party GraphQL validation layer: buildSchema (SDL type system), validate (five spec rules plus an engine depth limit), and a graphql-js adapter on the ./graphql-js subpath export behind an optional peer. See the GraphQL Validation ecosystem page for the layer overview.

  • Version: Stable
  • Module name: parser-grammar-graphql
  • Package: @lanexio/parser-grammar-graphql
  • Import path: @lanexio/parser-grammar-graphql
  • Layer: 2 (Grammar)
  • Runtime: Universal
  • Module format: ESM
  • Stability: Stable
  • Primary use case: Parse GraphQL documents (queries, mutations, subscriptions, SDL) into a flat AST, and validate executable documents against a schema built from SDL.
  • You need to parse GraphQL query documents into a traversable AST.
  • You need to parse GraphQL SDL (schema definition language) documents.
  • You need auto-detection between executable and schema documents.
  • You need to build a schema from SDL and validate documents against it without pulling in graphql-js (buildSchema and validate).
  • You already hold a graphql-js schema and want to validate Lanexio Parser trees with it (the optional graphql-js adapter).
BoundaryDescription
InputsUint8Array (source bytes)
OutputsLexTree (flat AST)
Side effectsNone
DeterminismYes
External dependencies@lanexio/parser-core (required); graphql (optional peer, adapter only)
Never-throw guaranteeYes (parse, buildSchema, and validate; the adapter degrades)
Security surfaceNone (parse and validate only, no output generation)
  1. Install the package.

    Terminal window
    pnpm add @lanexio/parser-grammar-graphql
  2. Import the named export.

    import { parseGraphql } from '@lanexio/parser-grammar-graphql';
RequirementRequiredLayerNotes
@lanexio/parser-coreYes1^1.0.0
graphqlNo (optional peer)n/a^16.14.2. Imported only by the graphql-js adapter on the ./graphql-js subpath export, lazily at first call. Absent disables the adapter; validate and buildSchema are unaffected.
import { parseGraphql } from '@lanexio/parser-grammar-graphql';
const encoder = new TextEncoder();
const bytes = encoder.encode('{ user { name email } }');
const tree = parseGraphql(bytes);
console.log(tree.nodeCount);
const encoder = new TextEncoder();
const tree = parseGraphql(encoder.encode(`
type Query {
user(id: ID!): User
}
`));

The package builds a schema from SDL and validates executable documents against it. Neither function ever throws: malformed SDL produces diagnostics, and document problems produce findings.

buildSchema(sdl: string | Uint8Array) parses SDL and returns { schema, diagnostics }. The schema records object, interface, input, scalar, enum, and union types with field arguments, default values, implemented interfaces, union members, and resolved possible types. SDL order does not matter because possible types resolve in a second pass. When the SDL omits an explicit schema block, a type named Query is the default query root.

import { buildSchema } from '@lanexio/parser-grammar-graphql';
const { schema, diagnostics } = buildSchema(`
enum Role { ADMIN USER }
type User { id: ID! role: Role }
type Query { me: User }
`);
// schema.queryType === 'Query'
// diagnostics === []

validate(document: LexTree | Uint8Array, schema: GraphqlSchema) runs five spec rules over an executable document: operation (the operation resolves to a defined root type), field (the field exists on the scoped type and leaf types carry no sub-selections), argument (names are declared and unique), fragment (spreads reference a defined fragment and type conditions name an existing composite type), and value (const literals coerce to their declared type). Findings carry { rule, message, range }, where range is the byte range of the offending node.

Recursive descent is bounded at MAX_VALIDATION_DEPTH = 512. A document that nests deeper (a chain of nested selection sets or a deeply nested const-value literal) is pruned and reported as a single depth finding, never a stack overflow. The depth tag is an engine safety limit, not a GraphQL spec rule.

import { parseGraphql, buildSchema, validate } from '@lanexio/parser-grammar-graphql';
const { schema } = buildSchema(`type Query { me: User } type User { id: ID! }`);
const tree = parseGraphql(new TextEncoder().encode('{ me { id nope } }'));
const result = validate(tree, schema);
// result.ok === false
// result.findings[0].message === 'Cannot query field "nope" on type "User".'

The adapter is exported only from the @lanexio/parser-grammar-graphql/graphql-js subpath, never from the package root, so the root .d.ts carries no graphql types. Both functions are async and load the optional graphql peer lazily on the first call through a guarded, memoized dynamic import.

import { toGraphqlJsDocument, validateWithGraphqlJs } from '@lanexio/parser-grammar-graphql/graphql-js';

await toGraphqlJsDocument(tree) rebuilds a graphql-js DocumentNode from the source bytes, and await validateWithGraphqlJs(tree, schema) runs graphql-js validation against a graphql-js schema. With the peer absent, toGraphqlJsDocument resolves to null and validateWithGraphqlJs resolves to a single graphql-js-unavailable finding.

ExportTypeDescription
parseGraphql(bytes: Uint8Array) => LexTreeParse GraphQL. Never throws. Auto-detects executable vs SDL.
GraphqlKindconst objectNumeric kind IDs for all GraphQL node types.
GraphqlFieldconst objectNumeric field IDs for GraphQL slots.
GRAPHQL_FIELD_NAMES_BY_IDreadonly string[]Field name lookup by numeric field ID.
GRAPHQL_KIND_NAMES_BY_IDreadonly Record<number, string>Kind-name lookup by numeric ID.
graphqlGrammarLanexioParserPureGrammarGrammar descriptor for use with parser-pure.
graphqlRegistrationGrammarRegistrationRegistration for the unified grammar registry.
graphqlReuseOracleReuseOracleIncremental reuse oracle.
buildSchemafunctionBuild a schema from SDL (string or bytes). Never throws; malformed SDL returns diagnostics.
validatefunctionFive-rule document validator over a tree or bytes. Never throws; findings carry rule, message, and byte range.
toGraphqlJsDocument (subpath ./graphql-js)async (tree) => Promise<DocumentNode | null>Bridge to graphql-js. Resolves to null when the optional graphql peer is absent. Loads the peer lazily on first call.
validateWithGraphqlJs (subpath ./graphql-js)async (tree, schema: unknown) => Promise<ValidationResult>graphql-js validation over a Lanexio Parser tree. Degrades to a graphql-js-unavailable finding when the optional peer is absent. Loads the peer lazily on first call.

No options object. The function signature is parseGraphql(bytes: Uint8Array): LexTree. Options are reserved for future extension.

PropertyTypeDescription
rootLexNodeRoot node of the document.
nodeCountnumberTotal nodes in the tree.
sourceUint8ArrayOriginal parsed bytes.
TypePurposeNotes
GraphqlKindTypeUnion of all GraphqlKind valuesType-safe kind reference
GraphqlFieldTypeUnion of all GraphqlField valuesType-safe field reference
GraphqlSchemaSchema built by buildSchemaMaps type names to SchemaType; names the query/mutation/subscription roots
SchemaTypeOne schema typeKind plus fields, interfaces, possible types, enum values, union members
BuildSchemaResultReturn of buildSchema{ schema, diagnostics }
ValidationResultReturn of validate{ ok, findings }
ValidationFindingOne finding{ rule, message, range }
ValidationRuleRule tag unionThe five spec rules plus the engine depth limit; graphql-js and graphql-js-unavailable are emitted only by the adapter subpath

No configuration options. GraphQL documents are parsed with auto-detection between executable and SDL modes.

  • No direct accessibility surface. The GraphQL parser produces flat AST data structures.
ConcernStatus
Generated output semanticsNot applicable (query/schema format)
ARIA attributes in serialized outputNot applicable
Semantic element round-tripNot applicable
  • parseGraphql never throws on any byte sequence.
ThreatMitigationStatus
Malformed input byte sequencePanic-free guarantee: all inputs accepted, errors produce LexError AST nodesImplemented
PackageRelationshipLayerNotes
@lanexio/parser-coreRequires1Provides LexTree, LexNode, LexCursor
@lanexio/parserConsumes6Unified entry point
VersionDateStatusNotable changes
1.0.02026-05-29CurrentInitial stable release. Apache-2.0.
  • None.