@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.
Layer contract
Section titled “Layer contract”When to use this module
Section titled “When to use this module”- 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 (
buildSchemaandvalidate). - You already hold a graphql-js schema and want to validate Lanexio Parser trees with it (the optional graphql-js adapter).
Module boundary
Section titled “Module boundary”| Boundary | Description |
|---|---|
| Inputs | Uint8Array (source bytes) |
| Outputs | LexTree (flat AST) |
| Side effects | None |
| Determinism | Yes |
| External dependencies | @lanexio/parser-core (required); graphql (optional peer, adapter only) |
| Never-throw guarantee | Yes (parse, buildSchema, and validate; the adapter degrades) |
| Security surface | None (parse and validate only, no output generation) |
Installation
Section titled “Installation”-
Install the package.
Terminal window pnpm add @lanexio/parser-grammar-graphqlTerminal window npm install @lanexio/parser-grammar-graphqlTerminal window yarn add @lanexio/parser-grammar-graphql -
Import the named export.
import { parseGraphql } from '@lanexio/parser-grammar-graphql';
Peer dependencies
Section titled “Peer dependencies”| Requirement | Required | Layer | Notes |
|---|---|---|---|
@lanexio/parser-core | Yes | 1 | ^1.0.0 |
graphql | No (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. |
Basic Usage
Section titled “Basic Usage”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);SDL parsing
Section titled “SDL parsing”const encoder = new TextEncoder();const tree = parseGraphql(encoder.encode(` type Query { user(id: ID!): User }`));Validation and type system
Section titled “Validation and type system”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
Section titled “buildSchema”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
Section titled “validate”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".'graphql-js adapter (subpath)
Section titled “graphql-js adapter (subpath)”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.
Exports
Section titled “Exports”| Export | Type | Description |
|---|---|---|
parseGraphql | (bytes: Uint8Array) => LexTree | Parse GraphQL. Never throws. Auto-detects executable vs SDL. |
GraphqlKind | const object | Numeric kind IDs for all GraphQL node types. |
GraphqlField | const object | Numeric field IDs for GraphQL slots. |
GRAPHQL_FIELD_NAMES_BY_ID | readonly string[] | Field name lookup by numeric field ID. |
GRAPHQL_KIND_NAMES_BY_ID | readonly Record<number, string> | Kind-name lookup by numeric ID. |
graphqlGrammar | LanexioParserPureGrammar | Grammar descriptor for use with parser-pure. |
graphqlRegistration | GrammarRegistration | Registration for the unified grammar registry. |
graphqlReuseOracle | ReuseOracle | Incremental reuse oracle. |
buildSchema | function | Build a schema from SDL (string or bytes). Never throws; malformed SDL returns diagnostics. |
validate | function | Five-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. |
Options
Section titled “Options”No options object. The function signature is parseGraphql(bytes: Uint8Array): LexTree. Options are reserved for future extension.
Return shape
Section titled “Return shape”| Property | Type | Description |
|---|---|---|
root | LexNode | Root node of the document. |
nodeCount | number | Total nodes in the tree. |
source | Uint8Array | Original parsed bytes. |
Exported types
Section titled “Exported types”| Type | Purpose | Notes |
|---|---|---|
GraphqlKindType | Union of all GraphqlKind values | Type-safe kind reference |
GraphqlFieldType | Union of all GraphqlField values | Type-safe field reference |
GraphqlSchema | Schema built by buildSchema | Maps type names to SchemaType; names the query/mutation/subscription roots |
SchemaType | One schema type | Kind plus fields, interfaces, possible types, enum values, union members |
BuildSchemaResult | Return of buildSchema | { schema, diagnostics } |
ValidationResult | Return of validate | { ok, findings } |
ValidationFinding | One finding | { rule, message, range } |
ValidationRule | Rule tag union | The five spec rules plus the engine depth limit; graphql-js and graphql-js-unavailable are emitted only by the adapter subpath |
Configuration and Extension
Section titled “Configuration and Extension”No configuration options. GraphQL documents are parsed with auto-detection between executable and SDL modes.
Accessibility
Section titled “Accessibility”Accessibility requirements
Section titled “Accessibility requirements”- No direct accessibility surface. The GraphQL parser produces flat AST data structures.
Accessibility checklist
Section titled “Accessibility checklist”| Concern | Status |
|---|---|
| Generated output semantics | Not applicable (query/schema format) |
| ARIA attributes in serialized output | Not applicable |
| Semantic element round-trip | Not applicable |
Security
Section titled “Security”Security considerations
Section titled “Security considerations”parseGraphqlnever throws on any byte sequence.
| Threat | Mitigation | Status |
|---|---|---|
| Malformed input byte sequence | Panic-free guarantee: all inputs accepted, errors produce LexError AST nodes | Implemented |
Companion packages
Section titled “Companion packages”| Package | Relationship | Layer | Notes |
|---|---|---|---|
@lanexio/parser-core | Requires | 1 | Provides LexTree, LexNode, LexCursor |
@lanexio/parser | Consumes | 6 | Unified entry point |
Changelog
Section titled “Changelog”| Version | Date | Status | Notable changes |
|---|---|---|---|
1.0.0 | 2026-05-29 | Current | Initial stable release. Apache-2.0. |
Migration notes
Section titled “Migration notes”- None.