← Back to Official Package Registry
Tier 4: FinTech, GraphQL, CDP & SSO • Zero-Codegen GraphQL & Dataloaderv1.0.0 • 70 KB • Ed25519 Verified

graphql@1.0.0

Homoiconic GraphQL schema builder, query/mutation/fragment parser, N+1 batching Dataloader, introspection, and HTML5 GraphiQL Explorer.

use [graphql]use [graphql/parser]
veko pkg add graphql@1.0.0
Run in Browser PlaygroundDownload 1.0.0.vkpRaw demo.vk

graphql

Zero-codegen homoiconic GraphQL engine, recursive-descent document parser, __schema introspection, batching Dataloader, and Light-First HTML5 GraphiQL Explorer for web/App.

Overview

graphql implements a complete, dependency-free GraphQL server and query engine in pure Veko:

  • graphql/parser: Spec-compliant GraphQL lexer and recursive-descent parser (tokenize-gql, parse-document) supporting query, mutation, subscription, shorthand { ... } queries, operation names, typed variable definitions with defaults ($id: ID! = "1"), field aliases (primary: user(...)), rich argument literals (ints, floats, strings, """...""" block strings, booleans, null, enums, nested lists, input objects, and $var references), @include(if: ...) and @skip(if: ...) directives, named fragments (...UserFields), and inline fragments (... on User { ... }).
  • graphql: Imperative and homoiconic (from-quote) schema builders (new-schema, define-object, define-enum, field, query-field, mutation-field), spec-compliant execute with Non-Null error bubbling, built-in __typename, __schema, and __type introspection, N+1 batching and per-request caching Dataloader (new-dataloader, load-one, load-many), and one-line mount-graphql integration for web/App serving both POST /graphql and a Light-First zero-CDN HTML5 GraphiQL Explorer on GET /graphql.

Installation

powershell
veko pkg add graphql@1.0.0

Import the engine and parser modules:

rebol
use [
    gql    = graphql
    parser = graphql/parser
    web
]

Architecture

  1. Zero-Codegen Homoiconic SDL (from-quote): Define enums, object types, field arguments, Non-Null modifiers, and root query/mutation operations directly inside a native Veko quote [...] block paired with a 'Type.field' resolver map—eliminating external SDL code generation steps.
  2. CollectFields Merging & Non-Null Bubbling: execute implements GraphQL's CollectFields selection merging across aliases, @skip/@include directives, named fragment spreads (with cycle protection), and type-conditioned inline fragments. Resolver errors record exact response path arrays and bubble .null cleanly across non-nullable (!) boundaries.
  3. Deterministic Dataloader Batching: load-many deduplicates requested keys, skips keys already present in the per-request cache, dispatches at most one batch_fn call for missing keys, and returns values aligned 1:1 with the caller's input key list.
  4. Self-Contained Light-First GraphiQL Studio: mount-graphql serves an embedded HTML5 Explorer (data-theme="light" default with persistent localStorage Dark Mode toggle, Ctrl+Enter execution, JSON variables pane, and Lightbox Schema Introspection modal) with zero external CDN requests.

Complete API Reference

graphql/parser

Type / SignatureDescription
GqlDocument = struct { operations block[GqlOperation], fragments map }Parsed GraphQL executable document AST.
GqlOperation, GqlFragment, GqlFieldSel, GqlFragSpread, GqlInlineFrag, GqlVarDef, GqlDirectiveTyped AST nodes for operations, fragments, selections, variables, and directives.
tokenize-gql = fn [src str] block[GqlTok]Lexical scanner ignoring # comments and insignificant commas.
parse-document = fn [src str] GqlDocumentParses a GraphQL query/mutation document string into GqlDocument.

graphql

Type / SignatureDescription
Schema, ObjectDef, EnumDef, FieldDefExecutable GraphQL schema and type definitions.
Dataloader = struct { batch_fn any, cache map, batch_calls i64, cache_hits i64 }Per-request batching and memoizing loader.
new-schema = fn [] SchemaCreates an empty GraphQL schema with a Query root object.
field = fn [name str, type_str str /args args map = {} /resolve resolver any = .none /desc description str = ''] FieldDefDefines an object field (defaults to reading parent.<name> when resolver == .none).
define-enum = fn [mut schema Schema, name str, values block[str] /desc description str = ''] enumRegisters a GraphQL ENUM type.
define-object = fn [mut schema Schema, name str, fields block[FieldDef] /desc description str = ''] enumRegisters a GraphQL OBJECT type.
query-field / mutation-fieldRegisters a root field on Query or Mutation.
from-quote = fn [dsl block, resolvers map] SchemaBuilds an executable Schema from a homoiconic quote [...] block and 'Type.field' resolver map.
execute = fn [schema Schema, doc_str str, variables map, ctx any /operation_name op_name str = ''] mapExecutes a GraphQL operation and returns { data = ..., errors = [...] }.
new-dataloader = fn [batch_fn any] DataloaderCreates a Dataloader around `fn [keys block] block
load-many = fn [mut loader Dataloader, keys block] block / load-one = fn [mut loader Dataloader, key any] anyBatches and caches key lookups deterministically.
prime-dataloader / clear-dataloaderSeeds or clears a Dataloader's per-request cache.
mount-graphql = fn [mut app web/App, path str, schema Schema /ctx_fn make_ctx any = .none /title explorer_title str = 'Veko GraphQL Explorer'] enumMounts POST <path> and GET <path> Explorer onto web/App.

Example Usage

rebol
use [gql = graphql, web]

schema = gql/from-quote (quote [
    object User [ id ID!, name String! ]
    query [ user [id ID!] User ]
]) {
    'Query.user' = fn [_p any, args map, _ctx any] any [
        { id = (map/get args 'id'), name = 'Ada Lovelace' }
    ]
}

res = gql/execute schema 'query($id: ID!) { u: user(id: $id) { __typename id name } }' { id = 'u-1' } {}
println (json/encode res.data)

mut app = web/new-app
_ = gql/mount-graphql mut app '/graphql' schema

Verification

powershell
veko check packages/graphql/src/parser.vk
veko check packages/graphql/src/mod.vk
veko check packages/graphql/examples/demo.vk
veko run -C all packages/graphql/examples/demo.vk
packages/graphql/examples/demo.vkSelf-contained runnable example & assertion suite
Raw .vk
// packages/graphql/examples/demo.vk
// Self-contained runnable verification suite for `graphql` (`1.0.0`):
// Complex document parser (aliases, variables + defaults, `@skip` / `@include`, named & inline
// fragments), homoiconic `from-quote` schema execution (queries + mutations + `__typename`),
// `__schema` / `__type` introspection, `Dataloader` N+1 batching + caching, and `web/App`
// `POST /graphql` + `GET /graphql` Light-First GraphiQL Explorer dispatch!

use [
	web
	gql    = graphql
	parser = graphql/parser
]

assert-eq = fn [label str, got any, want any] any [
	if got != want [
		println `[FAIL] {label}: got {mold got}, expected {mold want}`
		return (err `assert-eq failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

assert-true = fn [label str, cond bool] any [
	if not cond [
		println `[FAIL] {label}`
		return (err `assert-true failed: {label}`)
	]
	println `[PASS] {label}`
	.ok
]

main = fn [] any [
	println '=== graphql 1.0.0 Verification Suite ==='

	// 1. Parser verification: operation, variables with defaults, aliases, nested input objects,
	//    `@include` / `@skip`, named fragments (`...UserFields`), and inline fragments (`... on User`)
	complex_doc_str = '
		# GraphQL query exercising full June 2018 / Oct 2021 grammar
		query FetchDashboard($primaryId: ID! = "u-1", $secondaryId: ID!, $hideRole: Boolean = false, $withPosts: Boolean = true) {
			primary: user(id: $primaryId) {
				__typename
				...UserFields
				... on User @include(if: $withPosts) {
					posts(filter: { published: true, tags: ["veko", "graphql"] }) {
						id
						title
					}
				}
			}
			secondary: user(id: $secondaryId) {
				id
				name
			}
		}

		fragment UserFields on User {
			id
			name
			role @skip(if: $hideRole)
		}
	'

	parsed_doc = parser/parse-document/or complex_doc_str [e -> return e]
	_ = assert-eq/or 'Parser extracts 1 named query operation' (len parsed_doc.operations) 1 [e -> return e]
	_ = assert-eq/or 'Operation name == FetchDashboard' parsed_doc.operations[0].name 'FetchDashboard' [e -> return e]
	_ = assert-eq/or 'Operation defines 4 typed variables' (len parsed_doc.operations[0].variables) 4 [e -> return e]
	_ = assert-eq/or 'Default value on $primaryId == u-1' parsed_doc.operations[0].variables[0].default_val 'u-1' [e -> return e]
	_ = assert-true/or 'Named fragment UserFields registered in document' (map/has? parsed_doc.fragments 'UserFields') [e -> return e]

	// 2. Prove `Dataloader` batches multiple duplicate & distinct keys into 1 batch call + caches repeats
	users_db = {
		'u-1' = { id = 'u-1', name = 'Ada Lovelace', role = .ADMIN }
		'u-2' = { id = 'u-2', name = 'Grace Hopper', role = .MEMBER }
		'u-3' = { id = 'u-3', name = 'Ken Thompson', role = .MEMBER }
	}
	posts_db = [
		{ id = 'p-10', author_id = 'u-1', title = 'Zero-Codegen GraphQL in Veko', published = true }
		{ id = 'p-11', author_id = 'u-1', title = 'Draft Internal Notes',         published = false }
		{ id = 'p-12', author_id = 'u-2', title = 'Deterministic Wasm 3.0',       published = true }
		{ id = 'p-13', author_id = 'u-3', title = 'SQLite Slotted B-Trees',       published = true }
	]

	mut user_loader = gql/new-dataloader fn [batch_ids block] block [
		mut out = block/with-cap (len batch_ids)
		mut i = 0
		while i < (len batch_ids) [
			uid = str/append '' batch_ids[i]
			push mut out (map/get/or users_db uid [ .null ])
			i = i + 1
		]
		out
	]

	// Simulate 5 child resolver lookups across 3 unique authors (`u-1` x2, `u-2` x2, `u-3` x1)
	loaded_authors = gql/load-many/or mut user_loader ['u-1' 'u-2' 'u-1' 'u-3' 'u-2'] [e -> return e]
	_ = assert-eq/or 'Dataloader returns all 5 requested authors in order' (len loaded_authors) 5 [e -> return e]
	_ = assert-eq/or 'Dataloader deduplicated 5 lookups into 1 single batch call' user_loader.batch_calls 1 [e -> return e]
	_ = assert-eq/or 'Subsequent load-one hits per-request cache without extra batch call' (map/get (gql/load-one mut user_loader 'u-2') 'name') 'Grace Hopper' [e -> return e]
	_ = assert-eq/or 'Dataloader batch_calls remains 1 after cached load-one' user_loader.batch_calls 1 [e -> return e]
	_ = assert-true/or 'Dataloader recorded cache hits' (user_loader.cache_hits >= 1) [e -> return e]

	// 3. Homoiconic `from-quote` Schema Builder + Query & Mutation Execution
	schema = gql/from-quote (quote [
		enum Role [ADMIN MEMBER GUEST]

		object Post [
			id        ID!
			title     String!
			published Boolean!
			author    User!
		]

		object User [
			id    ID!
			name  String!
			role  Role
			posts [Post!]!
		]

		query [
			user  [id ID!] User
			posts [publishedOnly Boolean] [Post!]!
		]

		mutation [
			createPost [authorId ID!, title String!] Post!
		]
	]) {
		'Query.user' = fn [_parent any, args map, ctx any] any [
			uid = str/append '' (map/get args 'id')
			map/get/or ctx.users uid [ .null ]
		]
		'Query.posts' = fn [_parent any, args map, ctx any] any [
			pub_only = (map/get/or args 'publishedOnly' [ false ]) == true
			mut res = []
			mut i = 0
			while i < (len ctx.posts) [
				p = ctx.posts[i]
				if (not pub_only) or p.published == true [
					push mut res p
				]
				i = i + 1
			]
			res
		]
		'User.posts' = fn [user any, args map, ctx any] any [
			uid = str/append '' (map/get user 'id')
			flt = map/get/or args 'filter' [ {} ]
			want_pub = map/get/or flt 'published' [ .null ]
			mut res = []
			mut i = 0
			while i < (len ctx.posts) [
				p = ctx.posts[i]
				pub_ok = if want_pub == .null [ true ] else [ p.published == want_pub ]
				if p.author_id == uid and pub_ok [
					push mut res p
				]
				i = i + 1
			]
			res
		]
		'Post.author' = fn [post any, _args map, ctx any] any [
			aid = str/append '' (map/get post 'author_id')
			// Resolved from pre-batched Dataloader cache in `ctx`!
			mut ld = ctx.user_loader
			gql/load-one mut ld aid
		]
		'Mutation.createPost' = fn [_parent any, args map, _ctx any] any [
			{
				id        = 'p-99'
				author_id = (str/append '' (map/get args 'authorId'))
				title     = (str/append '' (map/get args 'title'))
				published = true
			}
		]
	}

	exec_ctx = {
		users       = users_db
		posts       = posts_db
		user_loader = user_loader
	}

	// Execute `complex_doc_str`: `$primaryId` uses default `"u-1"`, `$hideRole = true` skips `role`!
	q_res = gql/execute schema complex_doc_str { secondaryId = 'u-2', hideRole = true, withPosts = true } exec_ctx
	_ = assert-eq/or 'Complex GraphQL query executes with 0 errors' (len q_res.errors) 0 [e -> return e]

	primary_u = map/get q_res.data 'primary'
	secondary_u = map/get q_res.data 'secondary'
	_ = assert-eq/or 'Alias primary.__typename == User' (map/get primary_u '__typename') 'User' [e -> return e]
	_ = assert-eq/or 'Fragment spread resolved primary.name == Ada Lovelace' (map/get primary_u 'name') 'Ada Lovelace' [e -> return e]
	_ = assert-eq/or '@skip(if: $hideRole) omitted role field when true' (map/has? primary_u 'role') false [e -> return e]
	u1_posts = map/get primary_u 'posts'
	_ = assert-eq/or 'Nested input-object filter { published: true } returned 1 published post for u-1' (len u1_posts) 1 [e -> return e]
	_ = assert-eq/or 'Alias secondary.name == Grace Hopper' (map/get secondary_u 'name') 'Grace Hopper' [e -> return e]

	// Execute Mutation (`createPost` + nested `author` resolved via primed Dataloader)
	mut_doc = 'mutation NewArticle($aid: ID!, $title: String!) { createPost(authorId: $aid, title: $title) { id title author { id name role } } }'
	m_res = gql/execute schema mut_doc { aid = 'u-3', title = 'Homoiconic Schemas' } exec_ctx
	_ = assert-eq/or 'GraphQL mutation executes with 0 errors' (len m_res.errors) 0 [e -> return e]
	created_p = map/get m_res.data 'createPost'
	_ = assert-eq/or 'Mutation returned created post id == p-99' (map/get created_p 'id') 'p-99' [e -> return e]
	_ = assert-eq/or 'Mutation nested Post.author resolved Ken Thompson' (map/get (map/get created_p 'author') 'name') 'Ken Thompson' [e -> return e]
	_ = assert-eq/or 'Enum value serialized as ADMIN/MEMBER string' (map/get (map/get created_p 'author') 'role') 'MEMBER' [e -> return e]

	// 4. Built-in `__schema` and `__type` Introspection
	intro_res = gql/execute schema '{ __schema { queryType { name } mutationType { name } types { kind name } } roleType: __type(name: "Role") { kind name enumValues { name } } }' {} exec_ctx
	_ = assert-eq/or 'Introspection query executes with 0 errors' (len intro_res.errors) 0 [e -> return e]
	isch = map/get intro_res.data '__schema'
	_ = assert-eq/or '__schema.queryType.name == Query' (map/get (map/get isch 'queryType') 'name') 'Query' [e -> return e]
	_ = assert-eq/or '__schema.mutationType.name == Mutation' (map/get (map/get isch 'mutationType') 'name') 'Mutation' [e -> return e]
	rtype = map/get intro_res.data 'roleType'
	_ = assert-eq/or '__type(name: "Role") kind == ENUM with 3 enumValues' (len (map/get rtype 'enumValues')) 3 [e -> return e]

	// 5. Mount onto `web/App` and dispatch `GET /graphql` Explorer + `POST /graphql` JSON execution
	mut app = web/new-app
	_ = gql/mount-graphql/ctx_fn/title mut app '/graphql' schema (fn [_req web/Request] any [ exec_ctx ]) 'Veko GraphQL Studio'

	get_explorer_req = web/Request {
		method  = 'GET'
		path    = '/graphql'
		target  = '/graphql'
		query   = {}
		params  = {}
		headers = { 'Accept' = 'text/html' }
		body    = (bytes/with-cap 0)
	}
	get_resp = web/handle-request app get_explorer_req
	html_body = bytes/to-str get_resp.body
	_ = assert-eq/or 'GET /graphql returns 200 OK HTML5 GraphiQL Explorer' get_resp.status 200 [e -> return e]
	_ = assert-true/or 'GraphiQL Explorer is Light-First (data-theme="light") & zero-CDN' ((str/contains? html_body 'data-theme="light"') and (str/contains? html_body 'Veko GraphQL Studio')) [e -> return e]

	post_payload = json/encode {
		query     = 'query($onlyPub: Boolean) { posts(publishedOnly: $onlyPub) { id title author { name } } }'
		variables = { onlyPub = true }
	}
	post_req = web/Request {
		method  = 'POST'
		path    = '/graphql'
		target  = '/graphql'
		query   = {}
		params  = {}
		headers = { 'Content-Type' = 'application/json' }
		body    = (bytes/from-str post_payload)
	}
	post_resp = web/handle-request app post_req
	_ = assert-eq/or 'POST /graphql returns 200 OK JSON response' post_resp.status 200 [e -> return e]
	post_json = json/decode (bytes/to-str post_resp.body)
	http_posts = map/get (map/get post_json 'data') 'posts'
	_ = assert-eq/or 'POST /graphql returns 3 published posts with nested authors' (len http_posts) 3 [e -> return e]
	_ = assert-eq/or 'POST /graphql omits errors key when 0 errors occurred' (map/has? post_json 'errors') false [e -> return e]

	println 'ALL graphql 1.0.0 TESTS PASSED'
	.ok
]

res = main
if err? res [
	println (mold res)
	os/exit 1
]
Cryptographic Provenance

Ed25519 Signature & Merkle Integrity

Registry URL: https://veko-lang.org/pkg/graphql/1.0.0.vkp
Archive SHA-256: 7f6079ddbaa0045782e7fdbd492bd69225e0aa8f4dca0c7a3f7f6950e7a538ce
Merkle Root: e7eb491b1df8b7446d25eb765738d698cb631346a7d9f37791fa37f4f29eba65
Signer Trust Key: ed25519:27406074d8681da1d4e6420f5d887cac15c313334c249ac047ba9d4e2df72b70
Embedded VKP1 Manifest

manifest.json

{"name":"graphql","version":"1.0.0","tier":4.0,"tier_label":"Tier 4: FinTech, GraphQL, CDP & SSO","category":"Zero-Codegen GraphQL & Dataloader","description":"Homoiconic GraphQL schema builder, query/mutation/fragment parser, N+1 batching Dataloader, introspection, and HTML5 GraphiQL Explorer.","modules":["graphql","graphql/parser"],"homepage":"https://veko-lang.org/packages/graphql"}
Bundle Entry PathSizeLeaf SHA-256 Digest
README.md5 KB4d8cdb07273fea9b24444d5bd08d046c96946e6eeb8dd88bc1bb55e460f8a105
examples/demo.vk10 KB7d37d92e94ce3ebf541dac73cb68e7c11e72cd19237e107ebee57a4a578c744f
mod.vk34 KBb59ead17364d37a2648d4a0a6061ce9d590592b8f792802aa3d629e393d96fd1
parser.vk18 KB264d5278389630e1c36b4234370336740a892a99e46d1b7c8f7b77fde9519cb1