@softistx/riva-graphql 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +182 -2
  3. package/dist/bff/index.d.ts +14 -0
  4. package/dist/bff/index.d.ts.map +1 -0
  5. package/dist/bff/index.js +13 -0
  6. package/dist/bff/index.js.map +10 -0
  7. package/dist/cache/field-key.d.ts +21 -0
  8. package/dist/cache/field-key.d.ts.map +1 -0
  9. package/dist/cache/index.d.ts +3 -0
  10. package/dist/cache/index.d.ts.map +1 -0
  11. package/dist/cache/index.js +380 -0
  12. package/dist/cache/index.js.map +17 -0
  13. package/dist/cache/normalized.d.ts +14 -0
  14. package/dist/cache/normalized.d.ts.map +1 -0
  15. package/dist/cache/read.d.ts +11 -0
  16. package/dist/cache/read.d.ts.map +1 -0
  17. package/dist/cache/selection.d.ts +33 -0
  18. package/dist/cache/selection.d.ts.map +1 -0
  19. package/dist/cache/type-match.d.ts +16 -0
  20. package/dist/cache/type-match.d.ts.map +1 -0
  21. package/dist/cache/typename.d.ts +10 -0
  22. package/dist/cache/typename.d.ts.map +1 -0
  23. package/dist/cache/values.d.ts +15 -0
  24. package/dist/cache/values.d.ts.map +1 -0
  25. package/dist/cache/write.d.ts +18 -0
  26. package/dist/cache/write.d.ts.map +1 -0
  27. package/dist/chunks/index-etvmjkh7.js +11 -0
  28. package/dist/chunks/index-etvmjkh7.js.map +10 -0
  29. package/dist/chunks/index-zpgy1hwx.js +59 -0
  30. package/dist/chunks/index-zpgy1hwx.js.map +11 -0
  31. package/dist/client-transport.d.ts +10 -0
  32. package/dist/client-transport.d.ts.map +1 -0
  33. package/dist/codegen/index.d.ts +34 -0
  34. package/dist/codegen/index.d.ts.map +1 -0
  35. package/dist/codegen/index.js +44 -0
  36. package/dist/codegen/index.js.map +10 -0
  37. package/dist/errors.d.ts +16 -0
  38. package/dist/errors.d.ts.map +1 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +96 -0
  42. package/dist/index.js.map +12 -0
  43. package/dist/infinite/index.d.ts +15 -0
  44. package/dist/infinite/index.d.ts.map +1 -0
  45. package/dist/infinite/index.js +26 -0
  46. package/dist/infinite/index.js.map +10 -0
  47. package/dist/operation.d.ts +24 -0
  48. package/dist/operation.d.ts.map +1 -0
  49. package/dist/query.d.ts +40 -0
  50. package/dist/query.d.ts.map +1 -0
  51. package/dist/run.d.ts +5 -0
  52. package/dist/run.d.ts.map +1 -0
  53. package/dist/server/index.d.ts +20 -0
  54. package/dist/server/index.d.ts.map +1 -0
  55. package/dist/server/index.js +47 -0
  56. package/dist/server/index.js.map +10 -0
  57. package/dist/transport.d.ts +17 -0
  58. package/dist/transport.d.ts.map +1 -0
  59. package/dist/types.d.ts +6 -0
  60. package/dist/types.d.ts.map +1 -0
  61. package/docs/README.md +22 -0
  62. package/docs/guide/bff.md +54 -0
  63. package/docs/guide/cache.md +47 -0
  64. package/docs/guide/codegen.md +67 -0
  65. package/docs/guide/documents.md +49 -0
  66. package/docs/guide/errors.md +42 -0
  67. package/docs/guide/infinite.md +48 -0
  68. package/docs/guide/mutations.md +38 -0
  69. package/docs/guide/queries.md +42 -0
  70. package/docs/guide/transport.md +71 -0
  71. package/docs/troubleshooting.md +210 -0
  72. package/package.json +104 -5
@@ -0,0 +1,17 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cache/normalized.ts", "../src/cache/read.ts", "../src/cache/field-key.ts", "../src/cache/selection.ts", "../src/cache/values.ts", "../src/cache/type-match.ts", "../src/cache/typename.ts", "../src/cache/write.ts"],
4
+ "sourcesContent": [
5
+ "import type { CachePolicy } from '@softistx/riva';\nimport { type EntitiesOptions, entities } from '@softistx/riva/entities';\nimport type { BoundOperation, OperationCache } from '../query';\nimport type { Variables } from './field-key';\nimport { readResult } from './read';\nimport { cacheDocumentOf, variablesOf, type Walk } from './selection';\nimport { type PossibleTypes, typeMatcher } from './type-match';\nimport { assertTypename } from './typename';\nimport { type Root, writeResult } from './write';\n\nexport interface NormalizedOptions extends EntitiesOptions {\n\t/** The abstract types' members, for fragments on interfaces and unions (codegen's `fragment-matcher`). */\n\tpossibleTypes?: PossibleTypes;\n}\n\n/**\n * The selection-aware normalized cache, for `query(DOC, { cache: normalized() })`\n * and `mutation(DOC, { cache: normalized() })`. Share one between a client's\n * definitions: it fixes the entity identity rules the client's store uses.\n */\nexport function normalized(opts: NormalizedOptions = {}): OperationCache {\n\tconst matches = typeMatcher(opts.possibleTypes);\n\treturn {\n\t\tforOperation(op: BoundOperation): CachePolicy {\n\t\t\tassertTypename(op.document);\n\t\t\tconst document = cacheDocumentOf(op.document);\n\t\t\tconst walk = (variables: Variables): Walk => ({\n\t\t\t\tdocument,\n\t\t\t\tmatches,\n\t\t\t\tvariables,\n\t\t\t});\n\t\t\treturn entities(opts, {\n\t\t\t\tnormalize: (store, data, vars) =>\n\t\t\t\t\twriteResult(walk(variablesOf(document.operation, vars)), store, data),\n\t\t\t\tdenormalize: (store, root) =>\n\t\t\t\t\troot === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: readResult(walk({}), store, root as Root),\n\t\t\t}) as CachePolicy;\n\t\t},\n\t};\n}\n",
6
+ "import type { EntityReader } from '@softistx/riva/entities';\nimport { isPlain, isRef } from '@softistx/riva/entities';\nimport type { FieldNode, SelectionSetNode } from 'graphql';\nimport { fieldKey } from './field-key';\nimport { collectFields, subSelections, type Walk } from './selection';\nimport { mergeValues, type Stored } from './values';\nimport type { Root } from './write';\n\ninterface Reader extends Walk {\n\treadonly store: EntityReader;\n}\n\n/** Marks a read that met a missing field or entity. */\nconst missing: unique symbol = Symbol('missing');\ntype Missing = typeof missing;\n\n/**\n * Denormalizes a query's result by its selection: fragments, aliases,\n * arguments and `@skip`/`@include` applied, each entity read through its signal\n * (so the caller's computed is notified). Any field or entity missing makes\n * the whole result `undefined`.\n */\nexport function readResult(\n\twalk: Walk,\n\tstore: EntityReader,\n\troot: Root,\n): Record<string, unknown> | undefined {\n\tconst reader: Reader = { ...walk, variables: root.vars, store };\n\tconst data = readObject(\n\t\treader,\n\t\troot.data,\n\t\t[walk.document.operation.selectionSet],\n\t\ttrue,\n\t);\n\treturn data === missing ? undefined : data;\n}\n\nfunction readObject(\n\treader: Reader,\n\tsource: Stored,\n\tsets: readonly SelectionSetNode[],\n\troot = false,\n): Record<string, unknown> | Missing {\n\tconst typename = source['__typename'];\n\tconst { fields, undecided } = collectFields(\n\t\tsets,\n\t\ttypeof typename === 'string' ? typename : undefined,\n\t\t// The root has no `__typename`: a fragment on the root type applies.\n\t\troot ? { ...reader, matches: () => true } : reader,\n\t\tfalse,\n\t);\n\tconst result: Record<string, unknown> = {};\n\tfor (const [responseKey, nodes] of fields) {\n\t\tconst key = fieldKey(nodes[0] as FieldNode, reader.variables);\n\t\tif (!Object.hasOwn(source, key)) return missing;\n\t\tconst value = readValue(reader, source[key], subSelections(nodes));\n\t\tif (value === missing) return missing;\n\t\tresult[responseKey] = value;\n\t}\n\t// A fragment on an abstract type with no possibleTypes: kept when whole.\n\tlet out = result;\n\tfor (const set of undecided) {\n\t\tconst extra = readObject(reader, source, [set]);\n\t\tif (extra !== missing) out = mergeValues(out, extra) as typeof out;\n\t}\n\treturn out;\n}\n\nfunction readValue(\n\treader: Reader,\n\tvalue: unknown,\n\tsets: readonly SelectionSetNode[],\n): unknown {\n\tif (value === null || typeof value !== 'object') return value;\n\tif (sets.length === 0) return value;\n\tif (Array.isArray(value)) {\n\t\tconst items = value.map((item) => readValue(reader, item, sets));\n\t\treturn items.includes(missing) ? missing : items;\n\t}\n\tif (isRef(value)) {\n\t\tconst target = reader.store.fields(value.__ref);\n\t\treturn target ? readObject(reader, target, sets) : missing;\n\t}\n\treturn isPlain(value) ? readObject(reader, value, sets) : value;\n}\n",
7
+ "import type { FieldNode, ValueNode } from 'graphql';\n\n/** An operation's variables, its defaults applied. */\nexport type Variables = Readonly<Record<string, unknown>>;\n\n/** A GraphQL value as plain JSON, its variables read from `variables` (an unset one is `undefined`). */\nexport function valueNode(node: ValueNode, variables: Variables): unknown {\n\tswitch (node.kind) {\n\t\tcase 'Variable':\n\t\t\treturn variables[node.name.value];\n\t\tcase 'IntValue':\n\t\tcase 'FloatValue':\n\t\t\treturn Number(node.value);\n\t\tcase 'NullValue':\n\t\t\treturn null;\n\t\tcase 'ListValue':\n\t\t\treturn node.values.map((v) => valueNode(v, variables));\n\t\tcase 'ObjectValue': {\n\t\t\tconst out: Record<string, unknown> = {};\n\t\t\tfor (const f of node.fields)\n\t\t\t\tout[f.name.value] = valueNode(f.value, variables);\n\t\t\treturn out;\n\t\t}\n\t\tdefault:\n\t\t\t// String, Boolean and Enum values.\n\t\t\treturn node.value;\n\t}\n}\n\n/**\n * Where a field is stored: its name, and its arguments when it has any,\n * keys sorted, so `book(id: 1)` and `book(id: $id)` with `id: 1` share a key:\n * `book({\"id\":1})`. An alias never reaches the key.\n */\nexport function fieldKey(field: FieldNode, variables: Variables): string {\n\tconst name = field.name.value;\n\tif (!field.arguments?.length) return name;\n\tconst args: Record<string, unknown> = {};\n\tfor (const argument of field.arguments) {\n\t\tconst value = valueNode(argument.value, variables);\n\t\tif (value !== undefined) args[argument.name.value] = value;\n\t}\n\tif (Object.keys(args).length === 0) return name;\n\treturn `${name}(${stableJson(args)})`;\n}\n\n/** The field's name in a field key: `book` for `book({\"id\":1})`. */\nexport function fieldNameOf(key: string): string {\n\tconst open = key.indexOf('(');\n\treturn open < 0 ? key : key.slice(0, open);\n}\n\n/**\n * JSON whose object keys are sorted, at every depth, written as\n * `JSON.stringify` writes it otherwise: `toJSON` is honoured (a `Date` is its\n * ISO string) and a value JSON leaves out is left out. So the key is what\n * goes on the wire. Integer-like keys keep the engine's own order.\n */\nexport function stableJson(value: unknown): string {\n\treturn (\n\t\tJSON.stringify(value, (_, v) =>\n\t\t\tv && typeof v === 'object' && !Array.isArray(v)\n\t\t\t\t? Object.fromEntries(\n\t\t\t\t\t\tObject.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)),\n\t\t\t\t\t)\n\t\t\t\t: v,\n\t\t) ?? 'null'\n\t);\n}\n",
8
+ "import { RivaError } from '@softistx/riva';\nimport type {\n\tDocumentNode,\n\tFieldNode,\n\tFragmentDefinitionNode,\n\tOperationDefinitionNode,\n\tSelectionNode,\n\tSelectionSetNode,\n} from 'graphql';\nimport { type Variables, valueNode } from './field-key';\nimport type { TypeMatcher } from './type-match';\n\n/** A document as the cache walks it: its operation and its fragments by name. */\nexport interface CacheDocument {\n\treadonly operation: OperationDefinitionNode;\n\treadonly fragments: ReadonlyMap<string, FragmentDefinitionNode>;\n}\n\n/** One walk of a document: the variables, defaults applied, and the type matcher. */\nexport interface Walk {\n\treadonly document: CacheDocument;\n\treadonly variables: Variables;\n\treadonly matches: TypeMatcher;\n}\n\n/** The fields to visit on one object, by response key (alias or name). */\nexport interface Collected {\n\treadonly fields: Map<string, FieldNode[]>;\n\t/** Fragments whose type condition could not be decided: read only when whole. */\n\treadonly undecided: SelectionSetNode[];\n}\n\n/** The operation and fragments of a document; throws a `RivaError` (`RIVA_DEFINITION`) when it holds no operation. */\nexport function cacheDocumentOf(node: DocumentNode): CacheDocument {\n\tlet operation: OperationDefinitionNode | undefined;\n\tconst fragments = new Map<string, FragmentDefinitionNode>();\n\tfor (const definition of node.definitions) {\n\t\tif (definition.kind === 'OperationDefinition') operation ??= definition;\n\t\telse if (definition.kind === 'FragmentDefinition')\n\t\t\tfragments.set(definition.name.value, definition);\n\t}\n\tif (!operation)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t'riva-graphql: the document holds no operation; query it with one named operation.',\n\t\t);\n\treturn { operation, fragments };\n}\n\n/** The variables given, each one left out taking its declared default. */\nexport function variablesOf(\n\toperation: OperationDefinitionNode,\n\tgiven: unknown,\n): Variables {\n\tconst variables: Record<string, unknown> = {\n\t\t...(given as Record<string, unknown> | undefined),\n\t};\n\tfor (const definition of operation.variableDefinitions ?? []) {\n\t\tconst name = definition.variable.name.value;\n\t\tif (variables[name] === undefined && definition.defaultValue)\n\t\t\tvariables[name] = valueNode(definition.defaultValue, {});\n\t}\n\treturn variables;\n}\n\n/**\n * The fields the selection sets ask of an object of `typename`: `@skip`\n * and `@include` applied, fragments matched, same response keys grouped.\n * With `undecidedApply`, an undecided fragment's fields join the others.\n */\nexport function collectFields(\n\tsets: readonly SelectionSetNode[],\n\ttypename: string | undefined,\n\twalk: Walk,\n\tundecidedApply: boolean,\n): Collected {\n\tconst collected: Collected = { fields: new Map(), undecided: [] };\n\tconst seen = new Set<string>();\n\tconst visit = (set: SelectionSetNode) => {\n\t\tfor (const selection of set.selections) {\n\t\t\tif (!included(selection, walk.variables)) continue;\n\t\t\tif (selection.kind === 'Field') {\n\t\t\t\tconst key = selection.alias?.value ?? selection.name.value;\n\t\t\t\tconst group = collected.fields.get(key);\n\t\t\t\tif (group) group.push(selection);\n\t\t\t\telse collected.fields.set(key, [selection]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst fragment = fragmentOf(selection, walk, seen);\n\t\t\tif (!fragment) continue;\n\t\t\tconst match = walk.matches(fragment.condition, typename);\n\t\t\tif (match || (match === undefined && undecidedApply)) visit(fragment.set);\n\t\t\telse if (match === undefined) collected.undecided.push(fragment.set);\n\t\t}\n\t};\n\tfor (const set of sets) visit(set);\n\treturn collected;\n}\n\n/** The sub-selections of fields grouped under one response key. */\nexport function subSelections(\n\tfields: readonly FieldNode[],\n): SelectionSetNode[] {\n\treturn fields.flatMap((field) =>\n\t\tfield.selectionSet ? [field.selectionSet] : [],\n\t);\n}\n\nfunction fragmentOf(\n\tselection: Exclude<SelectionNode, FieldNode>,\n\twalk: Walk,\n\tseen: Set<string>,\n): { condition: string | undefined; set: SelectionSetNode } | undefined {\n\tif (selection.kind === 'InlineFragment')\n\t\treturn {\n\t\t\tcondition: selection.typeCondition?.name.value,\n\t\t\tset: selection.selectionSet,\n\t\t};\n\tconst name = selection.name.value;\n\tif (seen.has(name)) return undefined;\n\tseen.add(name);\n\tconst definition = walk.document.fragments.get(name);\n\tif (!definition)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-graphql: the document uses the fragment ${name} but does not define it; include its definition in the document.`,\n\t\t);\n\treturn {\n\t\tcondition: definition.typeCondition.name.value,\n\t\tset: definition.selectionSet,\n\t};\n}\n\n/** `@skip(if:)` and `@include(if:)`, read from the variables. */\nfunction included(selection: SelectionNode, variables: Variables): boolean {\n\tfor (const directive of selection.directives ?? []) {\n\t\tconst name = directive.name.value;\n\t\tif (name !== 'skip' && name !== 'include') continue;\n\t\tconst argument = directive.arguments?.find((a) => a.name.value === 'if');\n\t\tconst value = argument ? valueNode(argument.value, variables) : undefined;\n\t\tif (name === 'skip' && value === true) return false;\n\t\tif (name === 'include' && value !== true) return false;\n\t}\n\treturn true;\n}\n",
9
+ "import { RivaError } from '@softistx/riva';\nimport { isPlain } from '@softistx/riva/entities';\n\n/** The fields of an entity, or of an object stored inside one, by field key. */\nexport type Stored = Record<string, unknown>;\n\n/**\n * Refuses a value JSON could not hold: the cache holds JSON as the network\n * sends it (a custom scalar arrives as a string). `field` names the field\n * key the value was given for, in the error. A number must be finite, and an\n * object or array must not contain itself.\n */\nexport function assertJson(\n\tvalue: unknown,\n\tfield: string,\n\tseen: WeakSet<object> = new WeakSet(),\n): void {\n\tconst type = typeof value;\n\tif (value === null || type === 'string' || type === 'boolean') return;\n\tif (type === 'number' && Number.isFinite(value)) return;\n\tconst list = Array.isArray(value);\n\tconst obj = value as { constructor: { name: string } };\n\tif (type === 'object' && (list || isPlain(value)) && !seen.has(value)) {\n\t\tseen.add(value);\n\t\tfor (const item of list ? value : Object.values(value))\n\t\t\tassertJson(item, field, seen);\n\t\t// Left again: the same object twice, not nested in itself, is fine.\n\t\tseen.delete(value);\n\t\treturn;\n\t}\n\tthrow new RivaError(\n\t\t'RIVA_CACHE',\n\t\t`The GraphQL cache holds JSON: field ${field} holds ${\n\t\t\ttype === 'object'\n\t\t\t\t? seen.has(obj)\n\t\t\t\t\t? 'a cycle'\n\t\t\t\t\t: obj.constructor.name\n\t\t\t\t: type === 'number'\n\t\t\t\t\t? value\n\t\t\t\t\t: type\n\t\t}.`,\n\t);\n}\n\n/**\n * `b` merged over `a`, without changing either: objects field by field, two\n * lists of the same length item by item; otherwise `b` wins.\n */\nexport function mergeValues(a: unknown, b: unknown): unknown {\n\tif (isPlain(a) && isPlain(b)) {\n\t\tconst out: Record<string, unknown> = { ...a };\n\t\tfor (const k of Object.keys(b)) out[k] = mergeValues(a[k], b[k]);\n\t\treturn out;\n\t}\n\tif (Array.isArray(a) && Array.isArray(b) && a.length === b.length)\n\t\treturn a.map((x, i) => mergeValues(x, b[i]));\n\treturn b;\n}\n",
10
+ "/** Each interface and union with the object types it stands for, as codegen's `fragment-matcher` writes it. */\nexport type PossibleTypes = Readonly<Record<string, readonly string[]>>;\n\n/**\n * Whether a fragment's type condition holds for an object's `__typename`:\n * `true`, `false`, or `undefined` when the cache cannot tell (an abstract\n * type with no `possibleTypes`, or an object with no `__typename`).\n */\nexport type TypeMatcher = (\n\tcondition: string | undefined,\n\ttypename: string | undefined,\n) => boolean | undefined;\n\n/**\n * Matches by `possibleTypes`, its members followed through nested abstract\n * types. Given any, it is taken as complete: a condition it does not list\n * is an object type. Given none, a condition other than the typename is\n * undecided.\n */\nexport function typeMatcher(possibleTypes: PossibleTypes = {}): TypeMatcher {\n\tconst members = closure(possibleTypes);\n\tconst known = members.size > 0;\n\treturn (condition, typename) => {\n\t\tif (condition === undefined || condition === typename) return true;\n\t\tif (typename === undefined) return undefined;\n\t\tconst types = members.get(condition);\n\t\tif (types) return types.has(typename);\n\t\treturn known ? false : undefined;\n\t};\n}\n\n/** Each abstract type with every type it stands for, at any depth. */\nfunction closure(possibleTypes: PossibleTypes): Map<string, Set<string>> {\n\tconst members = new Map<string, Set<string>>();\n\tconst expand = (type: string, into: Set<string>, seen: Set<string>) => {\n\t\tif (seen.has(type)) return;\n\t\tseen.add(type);\n\t\tfor (const member of possibleTypes[type] ?? []) {\n\t\t\tinto.add(member);\n\t\t\tif (Object.hasOwn(possibleTypes, member)) expand(member, into, seen);\n\t\t}\n\t};\n\tfor (const type of Object.keys(possibleTypes)) {\n\t\tconst into = new Set<string>();\n\t\texpand(type, into, new Set());\n\t\tmembers.set(type, into);\n\t}\n\treturn members;\n}\n",
11
+ "import { RivaError } from '@softistx/riva';\nimport type {\n\tDocumentNode,\n\tFragmentDefinitionNode,\n\tSelectionSetNode,\n} from 'graphql';\n\nconst missing = (field: string) =>\n\t`riva-graphql: the field \"${field}\" selects no __typename, which the cache needs to identify objects: add the client preset's addTypenameSelectionDocumentTransform to its documentTransforms.`;\n\n/**\n * Throws a `RivaError` (`RIVA_DEFINITION`) when an object of the document cannot be identified:\n * a selection set below the operation's own that selects no `__typename`,\n * directly or through an inline fragment with no type condition (a type\n * condition or a fragment spread covers one branch only). The document\n * is never rewritten, since a persisted id is the hash of its text.\n */\nexport function assertTypename(node: DocumentNode): void {\n\tconst fragments = new Map<string, FragmentDefinitionNode>();\n\tfor (const d of node.definitions)\n\t\tif (d.kind === 'FragmentDefinition') fragments.set(d.name.value, d);\n\n\t// Selected directly, or in an inline fragment with no type condition: a\n\t// branch of a union or a named fragment selecting it covers only its type.\n\tconst has = (set: SelectionSetNode): boolean =>\n\t\tset.selections.some((s) =>\n\t\t\ts.kind === 'Field'\n\t\t\t\t? s.name.value === '__typename'\n\t\t\t\t: s.kind === 'InlineFragment' &&\n\t\t\t\t\t!s.typeCondition &&\n\t\t\t\t\thas(s.selectionSet),\n\t\t);\n\n\tconst check = (set: SelectionSetNode, seen: Set<string>): void => {\n\t\tfor (const s of set.selections) {\n\t\t\tif (s.kind === 'Field') {\n\t\t\t\tif (s.selectionSet && !has(s.selectionSet))\n\t\t\t\t\tthrow new RivaError('RIVA_DEFINITION', missing(s.name.value));\n\t\t\t\tif (s.selectionSet) check(s.selectionSet, seen);\n\t\t\t} else if (s.kind === 'InlineFragment') check(s.selectionSet, seen);\n\t\t\telse {\n\t\t\t\tconst f = fragments.get(s.name.value);\n\t\t\t\tif (f && !seen.has(f.name.value)) {\n\t\t\t\t\tseen.add(f.name.value);\n\t\t\t\t\tcheck(f.selectionSet, seen);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\tfor (const d of node.definitions)\n\t\tif (d.kind === 'OperationDefinition') check(d.selectionSet, new Set());\n}\n",
12
+ "import { RivaError } from '@softistx/riva';\nimport type { EntityReader, Fields, Normalized } from '@softistx/riva/entities';\nimport { isPlain, isRef } from '@softistx/riva/entities';\nimport type { FieldNode, SelectionSetNode } from 'graphql';\nimport { fieldKey } from './field-key';\nimport { collectFields, subSelections, type Walk } from './selection';\nimport { assertJson, type Stored } from './values';\n\ninterface Writer extends Walk {\n\treadonly store: EntityReader;\n\t/** The fields to merge, by entity, once the whole walk succeeded. */\n\treadonly pending: Map<string, Stored>;\n}\n\n/** What a query entry stores: the variables and the root fields by field key. */\nexport interface Root {\n\treadonly vars: Fields;\n\treadonly data: Stored;\n}\n\n/**\n * Normalizes an operation's data: each object with an identity becomes an\n * entity, its fields set by field key (arguments in the key, aliases not);\n * the others are stored inside their parent. A query keeps its root fields\n * in its own `root`; a mutation keeps none (its arguments may hold secrets),\n * only the entities it returns. Nothing is merged here: `pending` holds the\n * entities' fields, so a write that throws halfway changes nothing.\n */\nexport function writeResult(\n\twalk: Walk,\n\tstore: EntityReader,\n\tdata: unknown,\n): Normalized {\n\tif (!isPlain(data))\n\t\tthrow new RivaError(\n\t\t\t'RIVA_CACHE',\n\t\t\t\"The GraphQL cache stores an operation's data: an object.\",\n\t\t);\n\tconst writer: Writer = { ...walk, store, pending: new Map() };\n\tconst { operation } = walk.document;\n\tconst { fields } = collectFields(\n\t\t[operation.selectionSet],\n\t\tundefined,\n\t\t// The root has no `__typename`: a fragment on the root type applies.\n\t\t{ ...walk, matches: () => true },\n\t\ttrue,\n\t);\n\tconst entries = writeFields(writer, data, fields, undefined);\n\tconst root: Root | undefined =\n\t\toperation.operation === 'query'\n\t\t\t? { vars: walk.variables, data: entries }\n\t\t\t: undefined;\n\treturn { root, pending: writer.pending };\n}\n\nfunction writeObject(\n\twriter: Writer,\n\tdata: Record<string, unknown>,\n\tsets: readonly SelectionSetNode[],\n\texisting: unknown,\n): unknown {\n\tconst typename = data['__typename'];\n\tconst { fields } = collectFields(\n\t\tsets,\n\t\ttypeof typename === 'string' ? typename : undefined,\n\t\twriter,\n\t\ttrue,\n\t);\n\tconst ref = writer.store.identify(byName(data, fields));\n\tif (ref) {\n\t\tconst held = { ...writer.store.peek(ref), ...writer.pending.get(ref) };\n\t\tconst entries = writeFields(writer, data, fields, held);\n\t\twriter.pending.set(ref, { ...writer.pending.get(ref), ...entries });\n\t\treturn { __ref: ref };\n\t}\n\t// Embedded (no id): merged over what the same field held for the same type,\n\t// so two queries selecting different fields of it both stay whole; replaced\n\t// when a shared scalar disagrees (a reordered list).\n\tconst previous =\n\t\tisPlain(existing) && !isRef(existing) && existing['__typename'] === typename\n\t\t\t? existing\n\t\t\t: undefined;\n\tconst entries = writeFields(writer, data, fields, previous);\n\tif (previous && agrees(previous, entries)) return { ...previous, ...entries };\n\treturn previous ? writeFields(writer, data, fields, undefined) : entries;\n}\n\nconst isNested = (v: unknown): boolean => typeof v === 'object' && v !== null;\n\n/** Two writes of one embedded object describe the same object when their shared scalars are equal. */\nfunction agrees(a: Stored, b: Stored): boolean {\n\treturn Object.keys(b).every((k) => {\n\t\tconst x = a[k];\n\t\tconst y = b[k];\n\t\treturn !Object.hasOwn(a, k) || isNested(x) || isNested(y) || x === y;\n\t});\n}\n\nfunction writeFields(\n\twriter: Writer,\n\tdata: Record<string, unknown>,\n\tfields: ReadonlyMap<string, FieldNode[]>,\n\tprevious: Stored | undefined,\n): Stored {\n\tconst entries: Stored = {};\n\tfor (const [responseKey, nodes] of fields) {\n\t\tif (!Object.hasOwn(data, responseKey)) continue;\n\t\tconst key = fieldKey(nodes[0] as FieldNode, writer.variables);\n\t\t// The same field under two aliases: the second walk merges over the first.\n\t\tentries[key] = writeValue(\n\t\t\twriter,\n\t\t\tdata[responseKey],\n\t\t\tkey,\n\t\t\tsubSelections(nodes),\n\t\t\tObject.hasOwn(entries, key) ? entries[key] : previous?.[key],\n\t\t);\n\t}\n\treturn entries;\n}\n\n/** `field` is the field key the value is written under, for a refusal's message. */\nfunction writeValue(\n\twriter: Writer,\n\tvalue: unknown,\n\tfield: string,\n\tsets: readonly SelectionSetNode[],\n\texisting: unknown,\n): unknown {\n\tif (value === undefined || value === null) return null;\n\t// A leaf: a scalar's value, a JSON one included, kept as it came.\n\tif (sets.length === 0) {\n\t\tassertJson(value, field);\n\t\treturn value;\n\t}\n\tif (Array.isArray(value))\n\t\treturn value.map((item, i) =>\n\t\t\twriteValue(\n\t\t\t\twriter,\n\t\t\t\titem,\n\t\t\t\tfield,\n\t\t\t\tsets,\n\t\t\t\t// Lists of one length are read item by item: two queries selecting\n\t\t\t\t// other fields of the items both stay whole.\n\t\t\t\tArray.isArray(existing) && existing.length === value.length\n\t\t\t\t\t? existing[i]\n\t\t\t\t\t: undefined,\n\t\t\t),\n\t\t);\n\tif (!isPlain(value)) {\n\t\tassertJson(value, field);\n\t\treturn value;\n\t}\n\treturn writeObject(writer, value, sets, existing);\n}\n\n/** The object's argument-less fields by their names, aliases resolved: what the identity reads. */\nfunction byName(\n\tdata: Record<string, unknown>,\n\tfields: ReadonlyMap<string, FieldNode[]>,\n): Record<string, unknown> {\n\tconst named: Record<string, unknown> = {};\n\tfor (const [responseKey, [node]] of fields) {\n\t\tif (!node || node.arguments?.length || !Object.hasOwn(data, responseKey))\n\t\t\tcontinue;\n\t\tconst name = node.name.value;\n\t\tif (!Object.hasOwn(named, name)) named[name] = data[responseKey];\n\t}\n\treturn named;\n}\n"
13
+ ],
14
+ "mappings": ";AACA;;;ACAA,oBAAS;;;ACKF,SAAS,SAAS,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764756E2164756E21",
16
+ "names": []
17
+ }
@@ -0,0 +1,14 @@
1
+ import { type EntitiesOptions } from '@softistx/riva/entities';
2
+ import type { OperationCache } from '../query';
3
+ import { type PossibleTypes } from './type-match';
4
+ export interface NormalizedOptions extends EntitiesOptions {
5
+ /** The abstract types' members, for fragments on interfaces and unions (codegen's `fragment-matcher`). */
6
+ possibleTypes?: PossibleTypes;
7
+ }
8
+ /**
9
+ * The selection-aware normalized cache, for `query(DOC, { cache: normalized() })`
10
+ * and `mutation(DOC, { cache: normalized() })`. Share one between a client's
11
+ * definitions: it fixes the entity identity rules the client's store uses.
12
+ */
13
+ export declare function normalized(opts?: NormalizedOptions): OperationCache;
14
+ //# sourceMappingURL=normalized.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"normalized.d.ts","sourceRoot":"","sources":["../../src/cache/normalized.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,eAAe,EAAY,MAAM,yBAAyB,CAAC;AACzE,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,UAAU,CAAC;AAI/D,OAAO,EAAE,KAAK,aAAa,EAAe,MAAM,cAAc,CAAC;AAI/D,MAAM,WAAW,iBAAkB,SAAQ,eAAe;IACzD,0GAA0G;IAC1G,aAAa,CAAC,EAAE,aAAa,CAAC;CAC9B;AAED;;;;GAIG;AACH,wBAAgB,UAAU,CAAC,IAAI,GAAE,iBAAsB,GAAG,cAAc,CAqBvE"}
@@ -0,0 +1,11 @@
1
+ import type { EntityReader } from '@softistx/riva/entities';
2
+ import { type Walk } from './selection';
3
+ import type { Root } from './write';
4
+ /**
5
+ * Denormalizes a query's result by its selection: fragments, aliases,
6
+ * arguments and `@skip`/`@include` applied, each entity read through its signal
7
+ * (so the caller's computed is notified). Any field or entity missing makes
8
+ * the whole result `undefined`.
9
+ */
10
+ export declare function readResult(walk: Walk, store: EntityReader, root: Root): Record<string, unknown> | undefined;
11
+ //# sourceMappingURL=read.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"read.d.ts","sourceRoot":"","sources":["../../src/cache/read.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AAI5D,OAAO,EAAgC,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AAEtE,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAUpC;;;;;GAKG;AACH,wBAAgB,UAAU,CACzB,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,YAAY,EACnB,IAAI,EAAE,IAAI,GACR,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CASrC"}
@@ -0,0 +1,33 @@
1
+ import type { DocumentNode, FieldNode, FragmentDefinitionNode, OperationDefinitionNode, SelectionSetNode } from 'graphql';
2
+ import { type Variables } from './field-key';
3
+ import type { TypeMatcher } from './type-match';
4
+ /** A document as the cache walks it: its operation and its fragments by name. */
5
+ export interface CacheDocument {
6
+ readonly operation: OperationDefinitionNode;
7
+ readonly fragments: ReadonlyMap<string, FragmentDefinitionNode>;
8
+ }
9
+ /** One walk of a document: the variables, defaults applied, and the type matcher. */
10
+ export interface Walk {
11
+ readonly document: CacheDocument;
12
+ readonly variables: Variables;
13
+ readonly matches: TypeMatcher;
14
+ }
15
+ /** The fields to visit on one object, by response key (alias or name). */
16
+ export interface Collected {
17
+ readonly fields: Map<string, FieldNode[]>;
18
+ /** Fragments whose type condition could not be decided: read only when whole. */
19
+ readonly undecided: SelectionSetNode[];
20
+ }
21
+ /** The operation and fragments of a document; throws a `RivaError` (`RIVA_DEFINITION`) when it holds no operation. */
22
+ export declare function cacheDocumentOf(node: DocumentNode): CacheDocument;
23
+ /** The variables given, each one left out taking its declared default. */
24
+ export declare function variablesOf(operation: OperationDefinitionNode, given: unknown): Variables;
25
+ /**
26
+ * The fields the selection sets ask of an object of `typename`: `@skip`
27
+ * and `@include` applied, fragments matched, same response keys grouped.
28
+ * With `undecidedApply`, an undecided fragment's fields join the others.
29
+ */
30
+ export declare function collectFields(sets: readonly SelectionSetNode[], typename: string | undefined, walk: Walk, undecidedApply: boolean): Collected;
31
+ /** The sub-selections of fields grouped under one response key. */
32
+ export declare function subSelections(fields: readonly FieldNode[]): SelectionSetNode[];
33
+ //# sourceMappingURL=selection.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"selection.d.ts","sourceRoot":"","sources":["../../src/cache/selection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,YAAY,EACZ,SAAS,EACT,sBAAsB,EACtB,uBAAuB,EAEvB,gBAAgB,EAChB,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,KAAK,SAAS,EAAa,MAAM,aAAa,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,iFAAiF;AACjF,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,SAAS,EAAE,uBAAuB,CAAC;IAC5C,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,MAAM,EAAE,sBAAsB,CAAC,CAAC;CAChE;AAED,qFAAqF;AACrF,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,QAAQ,EAAE,aAAa,CAAC;IACjC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAC;CAC9B;AAED,0EAA0E;AAC1E,MAAM,WAAW,SAAS;IACzB,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC;IAC1C,iFAAiF;IACjF,QAAQ,CAAC,SAAS,EAAE,gBAAgB,EAAE,CAAC;CACvC;AAED,sHAAsH;AACtH,wBAAgB,eAAe,CAAC,IAAI,EAAE,YAAY,GAAG,aAAa,CAcjE;AAED,0EAA0E;AAC1E,wBAAgB,WAAW,CAC1B,SAAS,EAAE,uBAAuB,EAClC,KAAK,EAAE,OAAO,GACZ,SAAS,CAUX;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAC5B,IAAI,EAAE,SAAS,gBAAgB,EAAE,EACjC,QAAQ,EAAE,MAAM,GAAG,SAAS,EAC5B,IAAI,EAAE,IAAI,EACV,cAAc,EAAE,OAAO,GACrB,SAAS,CAsBX;AAED,mEAAmE;AACnE,wBAAgB,aAAa,CAC5B,MAAM,EAAE,SAAS,SAAS,EAAE,GAC1B,gBAAgB,EAAE,CAIpB"}
@@ -0,0 +1,16 @@
1
+ /** Each interface and union with the object types it stands for, as codegen's `fragment-matcher` writes it. */
2
+ export type PossibleTypes = Readonly<Record<string, readonly string[]>>;
3
+ /**
4
+ * Whether a fragment's type condition holds for an object's `__typename`:
5
+ * `true`, `false`, or `undefined` when the cache cannot tell (an abstract
6
+ * type with no `possibleTypes`, or an object with no `__typename`).
7
+ */
8
+ export type TypeMatcher = (condition: string | undefined, typename: string | undefined) => boolean | undefined;
9
+ /**
10
+ * Matches by `possibleTypes`, its members followed through nested abstract
11
+ * types. Given any, it is taken as complete: a condition it does not list
12
+ * is an object type. Given none, a condition other than the typename is
13
+ * undecided.
14
+ */
15
+ export declare function typeMatcher(possibleTypes?: PossibleTypes): TypeMatcher;
16
+ //# sourceMappingURL=type-match.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"type-match.d.ts","sourceRoot":"","sources":["../../src/cache/type-match.ts"],"names":[],"mappings":"AAAA,+GAA+G;AAC/G,MAAM,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;AAExE;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CACzB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,QAAQ,EAAE,MAAM,GAAG,SAAS,KACxB,OAAO,GAAG,SAAS,CAAC;AAEzB;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,aAAa,GAAE,aAAkB,GAAG,WAAW,CAU1E"}
@@ -0,0 +1,10 @@
1
+ import type { DocumentNode } from 'graphql';
2
+ /**
3
+ * Throws a `RivaError` (`RIVA_DEFINITION`) when an object of the document cannot be identified:
4
+ * a selection set below the operation's own that selects no `__typename`,
5
+ * directly or through an inline fragment with no type condition (a type
6
+ * condition or a fragment spread covers one branch only). The document
7
+ * is never rewritten, since a persisted id is the hash of its text.
8
+ */
9
+ export declare function assertTypename(node: DocumentNode): void;
10
+ //# sourceMappingURL=typename.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typename.d.ts","sourceRoot":"","sources":["../../src/cache/typename.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACX,YAAY,EAGZ,MAAM,SAAS,CAAC;AAKjB;;;;;;GAMG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAkCvD"}
@@ -0,0 +1,15 @@
1
+ /** The fields of an entity, or of an object stored inside one, by field key. */
2
+ export type Stored = Record<string, unknown>;
3
+ /**
4
+ * Refuses a value JSON could not hold: the cache holds JSON as the network
5
+ * sends it (a custom scalar arrives as a string). `field` names the field
6
+ * key the value was given for, in the error. A number must be finite, and an
7
+ * object or array must not contain itself.
8
+ */
9
+ export declare function assertJson(value: unknown, field: string, seen?: WeakSet<object>): void;
10
+ /**
11
+ * `b` merged over `a`, without changing either: objects field by field, two
12
+ * lists of the same length item by item; otherwise `b` wins.
13
+ */
14
+ export declare function mergeValues(a: unknown, b: unknown): unknown;
15
+ //# sourceMappingURL=values.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"values.d.ts","sourceRoot":"","sources":["../../src/cache/values.ts"],"names":[],"mappings":"AAGA,gFAAgF;AAChF,MAAM,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAE7C;;;;;GAKG;AACH,wBAAgB,UAAU,CACzB,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,EACb,IAAI,GAAE,OAAO,CAAC,MAAM,CAAiB,GACnC,IAAI,CA0BN;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,OAAO,GAAG,OAAO,CAS3D"}
@@ -0,0 +1,18 @@
1
+ import type { EntityReader, Fields, Normalized } from '@softistx/riva/entities';
2
+ import { type Walk } from './selection';
3
+ import { type Stored } from './values';
4
+ /** What a query entry stores: the variables and the root fields by field key. */
5
+ export interface Root {
6
+ readonly vars: Fields;
7
+ readonly data: Stored;
8
+ }
9
+ /**
10
+ * Normalizes an operation's data: each object with an identity becomes an
11
+ * entity, its fields set by field key (arguments in the key, aliases not);
12
+ * the others are stored inside their parent. A query keeps its root fields
13
+ * in its own `root`; a mutation keeps none (its arguments may hold secrets),
14
+ * only the entities it returns. Nothing is merged here: `pending` holds the
15
+ * entities' fields, so a write that throws halfway changes nothing.
16
+ */
17
+ export declare function writeResult(walk: Walk, store: EntityReader, data: unknown): Normalized;
18
+ //# sourceMappingURL=write.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"write.d.ts","sourceRoot":"","sources":["../../src/cache/write.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAIhF,OAAO,EAAgC,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AACtE,OAAO,EAAc,KAAK,MAAM,EAAE,MAAM,UAAU,CAAC;AAQnD,iFAAiF;AACjF,MAAM,WAAW,IAAI;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;CACtB;AAED;;;;;;;GAOG;AACH,wBAAgB,WAAW,CAC1B,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,YAAY,EACnB,IAAI,EAAE,OAAO,GACX,UAAU,CAqBZ"}
@@ -0,0 +1,11 @@
1
+ import {
2
+ transportOf
3
+ } from "./index-zpgy1hwx.js";
4
+
5
+ // src/run.ts
6
+ var fetchOf = (operation) => async (vars, ctx) => transportOf(ctx.client).execute(operation, vars, { signal: ctx.signal });
7
+
8
+ export { fetchOf };
9
+
10
+ //# debugId=FC84D050D2E558A164756E2164756E21
11
+ //# sourceMappingURL=index-etvmjkh7.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/run.ts"],
4
+ "sourcesContent": [
5
+ "import type { FetchContext } from '@softistx/riva';\nimport type { Operation } from './operation';\nimport { transportOf } from './transport';\n\n/** The core's `fetch` / `run` of an operation: through the transport of the client in scope. */\nexport const fetchOf =\n\t<Data, Vars>(operation: Operation<Data, Vars>) =>\n\tasync (vars: Vars, ctx: FetchContext): Promise<Data> =>\n\t\ttransportOf(ctx.client).execute(operation, vars, { signal: ctx.signal });\n"
6
+ ],
7
+ "mappings": ";;;;;AAKO,IAAM,UACZ,CAAa,cACb,OAAO,MAAY,QAClB,YAAY,IAAI,MAAM,EAAE,QAAQ,WAAW,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;",
8
+ "debugId": "FC84D050D2E558A164756E2164756E21",
9
+ "names": []
10
+ }
@@ -0,0 +1,59 @@
1
+ // src/operation.ts
2
+ import { RivaError } from "@softistx/riva";
3
+ var cache = new WeakMap;
4
+ function hashOf(document) {
5
+ const meta = document.__meta__;
6
+ return typeof meta?.hash === "string" ? meta.hash : undefined;
7
+ }
8
+ function read(document) {
9
+ const definitions = Array.isArray(document?.definitions) ? document.definitions : undefined;
10
+ if (!definitions)
11
+ throw new RivaError("RIVA_DEFINITION", 'riva-graphql: expected a TypedDocumentNode (set documentMode: "documentNode" in the client preset), got something else.');
12
+ const operations = definitions.filter((d) => d.kind === "OperationDefinition");
13
+ const [first] = operations;
14
+ if (!first)
15
+ throw new RivaError("RIVA_DEFINITION", "riva-graphql: the document holds no operation (a fragment alone cannot be queried).");
16
+ if (operations.length > 1)
17
+ throw new RivaError("RIVA_DEFINITION", `riva-graphql: the document holds ${operations.length} operations; define one operation per document.`);
18
+ const name = first.name?.value;
19
+ if (!name)
20
+ throw new RivaError("RIVA_DEFINITION", "riva-graphql: the operation has no name; name it (query Patients { ... }) so it has an id.");
21
+ if (first.operation === "subscription")
22
+ throw new RivaError("RIVA_DEFINITION", `riva-graphql: ${name} is a subscription; subscriptions are not supported yet.`);
23
+ const persistedId = hashOf(document);
24
+ return {
25
+ document,
26
+ name,
27
+ kind: first.operation,
28
+ persistedId,
29
+ id: persistedId ?? name
30
+ };
31
+ }
32
+ function operationOf2(document, expected) {
33
+ let op = cache.get(document);
34
+ if (!op) {
35
+ op = read(document);
36
+ cache.set(document, op);
37
+ }
38
+ if (expected && op.kind !== expected)
39
+ throw new RivaError("RIVA_DEFINITION", `riva-graphql: ${op.name} is a ${op.kind}; use ${op.kind}() to define it, not ${expected}().`);
40
+ return op;
41
+ }
42
+
43
+ // src/transport.ts
44
+ import { RivaScopeError } from "@softistx/riva";
45
+ var SLOT = {};
46
+ function provideGraphQL2(client, transport) {
47
+ client.slots.set(SLOT, transport);
48
+ }
49
+ function transportOf(client) {
50
+ const transport = client.slots.get(SLOT);
51
+ if (!transport)
52
+ throw new RivaScopeError("No GraphQL transport on this RivaClient: call provideGraphQL(client, graphqlClientTransport(gqlClient)) when you create it.");
53
+ return transport;
54
+ }
55
+
56
+ export { operationOf2, provideGraphQL2, transportOf };
57
+
58
+ //# debugId=B4D4E6471FA422BC64756E2164756E21
59
+ //# sourceMappingURL=index-zpgy1hwx.js.map
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/operation.ts", "../src/transport.ts"],
4
+ "sourcesContent": [
5
+ "import type { TypedDocumentNode } from '@graphql-typed-document-node/core';\nimport { RivaError } from '@softistx/riva';\nimport type { DocumentNode } from 'graphql';\n\nexport type OperationKind = 'query' | 'mutation';\n\n/**\n * What a transport executes: the typed document and what was read from it.\n * `id` names the operation to a server that holds an allowlist: its persisted\n * id when the document carries one, else its name.\n */\nexport interface Operation<Data = unknown, Vars = unknown> {\n\treadonly document: TypedDocumentNode<Data, Vars>;\n\t/** The operation's name, unique in the application. */\n\treadonly name: string;\n\treadonly kind: OperationKind;\n\t/** The client preset's `__meta__.hash`, when the document carries one. */\n\treadonly persistedId: string | undefined;\n\t/** `persistedId`, else `name`. */\n\treadonly id: string;\n}\n\nconst cache = new WeakMap<object, Operation>();\n\n/** `__meta__.hash` of a document the client preset wrote with `persistedDocuments`. */\nfunction hashOf(document: object): string | undefined {\n\t// biome-ignore lint/style/useNamingConvention: the client preset's property\n\tconst meta = (document as { __meta__?: { hash?: unknown } }).__meta__;\n\treturn typeof meta?.hash === 'string' ? meta.hash : undefined;\n}\n\nfunction read(document: DocumentNode): Operation {\n\tconst definitions = Array.isArray(document?.definitions)\n\t\t? document.definitions\n\t\t: undefined;\n\tif (!definitions)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t'riva-graphql: expected a TypedDocumentNode (set documentMode: \"documentNode\" in the client preset), got something else.',\n\t\t);\n\tconst operations = definitions.filter(\n\t\t(d) => d.kind === 'OperationDefinition',\n\t);\n\tconst [first] = operations;\n\tif (!first)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t'riva-graphql: the document holds no operation (a fragment alone cannot be queried).',\n\t\t);\n\tif (operations.length > 1)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-graphql: the document holds ${operations.length} operations; define one operation per document.`,\n\t\t);\n\tconst name = first.name?.value;\n\tif (!name)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t'riva-graphql: the operation has no name; name it (query Patients { ... }) so it has an id.',\n\t\t);\n\tif (first.operation === 'subscription')\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-graphql: ${name} is a subscription; subscriptions are not supported yet.`,\n\t\t);\n\tconst persistedId = hashOf(document);\n\treturn {\n\t\tdocument: document as unknown as Operation['document'],\n\t\tname,\n\t\tkind: first.operation,\n\t\tpersistedId,\n\t\tid: persistedId ?? name,\n\t};\n}\n\n/**\n * Reads a document once. Throws a `RivaError` (`RIVA_DEFINITION`) when it is not a document node,\n * holds no operation, several, an unnamed one or a subscription, or when it\n * is not of the `expected` kind.\n */\nexport function operationOf<Data, Vars>(\n\tdocument: TypedDocumentNode<Data, Vars>,\n\texpected?: OperationKind,\n): Operation<Data, Vars> {\n\tlet op = cache.get(document);\n\tif (!op) {\n\t\top = read(document);\n\t\tcache.set(document, op);\n\t}\n\tif (expected && op.kind !== expected)\n\t\tthrow new RivaError(\n\t\t\t'RIVA_DEFINITION',\n\t\t\t`riva-graphql: ${op.name} is a ${op.kind}; use ${op.kind}() to define it, not ${expected}().`,\n\t\t);\n\treturn op as Operation<Data, Vars>;\n}\n",
6
+ "import { type RivaClient, RivaScopeError } from '@softistx/riva';\nimport type { Operation } from './operation';\n\n/**\n * Runs one operation. `@softistx/riva-graphql` ships `graphqlClientTransport`;\n * any object of this shape works (a transport that posts the id and the\n * variables to a BFF route, a test double). It throws `RivaError`s.\n */\nexport interface GraphQLTransport {\n\texecute<Data, Vars>(\n\t\toperation: Operation<Data, Vars>,\n\t\tvariables: Vars,\n\t\toptions: { signal: AbortSignal },\n\t): Promise<Data>;\n}\n\n// Held on the client's slots: the transport of a request dies with its client.\nconst SLOT = {};\n\n/** Gives `client` the transport its GraphQL definitions fetch through. */\nexport function provideGraphQL(\n\tclient: RivaClient,\n\ttransport: GraphQLTransport,\n): void {\n\tclient.slots.set(SLOT, transport);\n}\n\n/** The transport `provideGraphQL` gave `client`; throws `RivaScopeError` when none. */\nexport function transportOf(client: RivaClient): GraphQLTransport {\n\tconst transport = client.slots.get(SLOT) as GraphQLTransport | undefined;\n\tif (!transport)\n\t\tthrow new RivaScopeError(\n\t\t\t'No GraphQL transport on this RivaClient: call provideGraphQL(client, graphqlClientTransport(gqlClient)) when you create it.',\n\t\t);\n\treturn transport;\n}\n"
7
+ ],
8
+ "mappings": ";AACA;AAqBA,IAAM,QAAQ,IAAI;A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GP,SAAS,eAAc,CAC7B,QACA,WACO;AAAA,EACP,OAAO,MAAM,IAAI,MAAM,SAAS;AAAA;AAI1B,SAAS,WAAW,CAAC,QAAsC;AAAA,EACjE,MAAM,YAAY,OAAO,MAAM,IAAI,IAAI;AAAA,EACvC,IAAI,CAAC;AAAA,IACJ,MAAM,IAAI,eACT,6HACD;AAAA,EACD,OAAO;AAAA;",
9
+ "debugId": "B4D4E6471FA422BC64756E2164756E21",
10
+ "names": []
11
+ }
@@ -0,0 +1,10 @@
1
+ import type { GraphQLClient } from '@softistx/graphql-client';
2
+ import type { GraphQLTransport } from './transport';
3
+ /**
4
+ * The transport over an `@softistx/graphql-client` client: a query goes
5
+ * through `client.query`, a mutation through `client.mutate`, with the
6
+ * definition's signal. The client's own `persisted` option decides whether the
7
+ * persisted id or the text is sent. Its errors are mapped by `toRivaError`.
8
+ */
9
+ export declare function graphqlClientTransport(client: GraphQLClient): GraphQLTransport;
10
+ //# sourceMappingURL=client-transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-transport.d.ts","sourceRoot":"","sources":["../src/client-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AAE9D,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAEpD;;;;;GAKG;AACH,wBAAgB,sBAAsB,CACrC,MAAM,EAAE,aAAa,GACnB,gBAAgB,CAiBlB"}
@@ -0,0 +1,34 @@
1
+ export interface AllowlistConfig {
2
+ /**
3
+ * What keys the manifest. `persisted` (default): the preset's own keys, the
4
+ * `__meta__.hash` the runtime sends. `name`: the operation name, for
5
+ * documents with no persisted id (the runtime then uses the name as the id).
6
+ */
7
+ ids?: 'persisted' | 'name';
8
+ }
9
+ export interface AllowlistEntry {
10
+ readonly id: string;
11
+ readonly name: string;
12
+ readonly kind: 'query' | 'mutation';
13
+ /** The text to execute: the operation and the fragments it uses. */
14
+ readonly document: string;
15
+ }
16
+ /** The manifest a `/_data` route reads: entries by id, sorted by id. */
17
+ export type AllowlistManifest = Readonly<Record<string, AllowlistEntry>>;
18
+ /**
19
+ * Builds the manifest from the client preset's `persisted-documents.json`
20
+ * (`{ [hash]: text }`). The hash keys are kept as they are, so an id is the
21
+ * very `__meta__.hash` the runtime sends. Deterministic: sorted by id.
22
+ *
23
+ * Throws on a text with no named query or mutation, and when two operations
24
+ * share a name (names are the ids of `ids: 'name'`).
25
+ */
26
+ export declare function buildAllowlist(persisted: Readonly<Record<string, string>>, config?: AllowlistConfig): AllowlistManifest;
27
+ /**
28
+ * Reads the preset's `persisted-documents.json` and writes the allowlist
29
+ * manifest next to where the BFF reads it. Run it after codegen, from
30
+ * `hooks.afterAllFileWrite` (the preset's files all exist by then, whatever
31
+ * the order of the outputs).
32
+ */
33
+ export declare function writeAllowlist(persistedPath: string, outPath: string, config?: AllowlistConfig): Promise<AllowlistManifest>;
34
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/codegen/index.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,eAAe;IAC/B;;;;OAIG;IACH,GAAG,CAAC,EAAE,WAAW,GAAG,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,UAAU,CAAC;IACpC,oEAAoE;IACpE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC1B;AAED,wEAAwE;AACxE,MAAM,MAAM,iBAAiB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAAC;AAKzE;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAC7B,SAAS,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,EAC3C,MAAM,GAAE,eAAoB,GAC1B,iBAAiB,CA6BnB;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CACnC,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,MAAM,EACf,MAAM,GAAE,eAAoB,GAC1B,OAAO,CAAC,iBAAiB,CAAC,CAM5B"}
@@ -0,0 +1,44 @@
1
+ // src/codegen/index.ts
2
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
3
+ import { dirname } from "node:path";
4
+ import { Kind, parse } from "graphql";
5
+ var operationOf = (definitions) => definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION);
6
+ function buildAllowlist(persisted, config = {}) {
7
+ const byName = new Map;
8
+ const entries = [];
9
+ for (const [hash, text] of Object.entries(persisted)) {
10
+ const [op, ...rest] = operationOf(parse(text).definitions);
11
+ if (!op || rest.length > 0 || op.kind !== Kind.OPERATION_DEFINITION)
12
+ throw new Error(`@softistx/riva-graphql/codegen: the persisted document ${hash} must hold exactly one operation.`);
13
+ const name = op.name?.value;
14
+ if (!name || op.operation === "subscription")
15
+ throw new Error(`@softistx/riva-graphql/codegen: the persisted document ${hash} must be a named query or mutation.`);
16
+ const first = byName.get(name);
17
+ if (first !== undefined)
18
+ throw new Error(`@softistx/riva-graphql/codegen: the operation "${name}" is defined twice (${first} and ${hash}); operation names must be unique.`);
19
+ byName.set(name, hash);
20
+ entries.push({
21
+ id: config.ids === "name" ? name : hash,
22
+ name,
23
+ kind: op.operation,
24
+ document: text
25
+ });
26
+ }
27
+ entries.sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
28
+ return Object.fromEntries(entries.map((e) => [e.id, e]));
29
+ }
30
+ async function writeAllowlist(persistedPath, outPath, config = {}) {
31
+ const persisted = JSON.parse(await readFile(persistedPath, "utf8"));
32
+ const manifest = buildAllowlist(persisted, config);
33
+ await mkdir(dirname(outPath), { recursive: true });
34
+ await writeFile(outPath, `${JSON.stringify(manifest, null, "\t")}
35
+ `);
36
+ return manifest;
37
+ }
38
+ export {
39
+ buildAllowlist,
40
+ writeAllowlist
41
+ };
42
+
43
+ //# debugId=3BCECD54DD05AE5964756E2164756E21
44
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/codegen/index.ts"],
4
+ "sourcesContent": [
5
+ "import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { type DefinitionNode, Kind, parse } from 'graphql';\n\nexport interface AllowlistConfig {\n\t/**\n\t * What keys the manifest. `persisted` (default): the preset's own keys, the\n\t * `__meta__.hash` the runtime sends. `name`: the operation name, for\n\t * documents with no persisted id (the runtime then uses the name as the id).\n\t */\n\tids?: 'persisted' | 'name';\n}\n\nexport interface AllowlistEntry {\n\treadonly id: string;\n\treadonly name: string;\n\treadonly kind: 'query' | 'mutation';\n\t/** The text to execute: the operation and the fragments it uses. */\n\treadonly document: string;\n}\n\n/** The manifest a `/_data` route reads: entries by id, sorted by id. */\nexport type AllowlistManifest = Readonly<Record<string, AllowlistEntry>>;\n\nconst operationOf = (definitions: readonly DefinitionNode[]) =>\n\tdefinitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION);\n\n/**\n * Builds the manifest from the client preset's `persisted-documents.json`\n * (`{ [hash]: text }`). The hash keys are kept as they are, so an id is the\n * very `__meta__.hash` the runtime sends. Deterministic: sorted by id.\n *\n * Throws on a text with no named query or mutation, and when two operations\n * share a name (names are the ids of `ids: 'name'`).\n */\nexport function buildAllowlist(\n\tpersisted: Readonly<Record<string, string>>,\n\tconfig: AllowlistConfig = {},\n): AllowlistManifest {\n\tconst byName = new Map<string, string>();\n\tconst entries: AllowlistEntry[] = [];\n\tfor (const [hash, text] of Object.entries(persisted)) {\n\t\tconst [op, ...rest] = operationOf(parse(text).definitions);\n\t\tif (!op || rest.length > 0 || op.kind !== Kind.OPERATION_DEFINITION)\n\t\t\tthrow new Error(\n\t\t\t\t`@softistx/riva-graphql/codegen: the persisted document ${hash} must hold exactly one operation.`,\n\t\t\t);\n\t\tconst name = op.name?.value;\n\t\tif (!name || op.operation === 'subscription')\n\t\t\tthrow new Error(\n\t\t\t\t`@softistx/riva-graphql/codegen: the persisted document ${hash} must be a named query or mutation.`,\n\t\t\t);\n\t\tconst first = byName.get(name);\n\t\tif (first !== undefined)\n\t\t\tthrow new Error(\n\t\t\t\t`@softistx/riva-graphql/codegen: the operation \"${name}\" is defined twice (${first} and ${hash}); operation names must be unique.`,\n\t\t\t);\n\t\tbyName.set(name, hash);\n\t\tentries.push({\n\t\t\tid: config.ids === 'name' ? name : hash,\n\t\t\tname,\n\t\t\tkind: op.operation,\n\t\t\tdocument: text,\n\t\t});\n\t}\n\tentries.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));\n\treturn Object.fromEntries(entries.map((e) => [e.id, e]));\n}\n\n/**\n * Reads the preset's `persisted-documents.json` and writes the allowlist\n * manifest next to where the BFF reads it. Run it after codegen, from\n * `hooks.afterAllFileWrite` (the preset's files all exist by then, whatever\n * the order of the outputs).\n */\nexport async function writeAllowlist(\n\tpersistedPath: string,\n\toutPath: string,\n\tconfig: AllowlistConfig = {},\n): Promise<AllowlistManifest> {\n\tconst persisted = JSON.parse(await readFile(persistedPath, 'utf8'));\n\tconst manifest = buildAllowlist(persisted, config);\n\tawait mkdir(dirname(outPath), { recursive: true });\n\tawait writeFile(outPath, `${JSON.stringify(manifest, null, '\\t')}\\n`);\n\treturn manifest;\n}\n"
6
+ ],
7
+ "mappings": ";AAAA;AACA;AACA;AAsBA,IAAM,cAAc,CAAC,gBACpB,YAAY,OAAO,CAAC,MAAM,EAAE,SAAS,KAAK,oBAAoB;AAUxD,SAAS,cAAc,CAC7B,WACA,SAA0B,CAAC,GACP;AAAA,EACpB,MAAM,SAAS,IAAI;AAAA,EACnB,MAAM,UAA4B,CAAC;AAAA,EACnC,YAAY,MAAM,SAAS,OAAO,QAAQ,SAAS,GAAG;AAAA,IACrD,OA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softistx/graphql-client` throws to riva's errors, so the
3
+ * core's retry policy and `instanceof` checks work:
4
+ *
5
+ * - the caller's abort: `RivaAbortError`;
6
+ * - `ApiError` (the response carried `errors`): `RivaRequestError` with the
7
+ * API's `extensions.code` untouched, its `status`, retryable only for 5xx,
8
+ * 408 and 429; the `ApiError` is its `cause`;
9
+ * - `ApiStatusError`: `RivaHttpError`;
10
+ * - `ApiUnavailableError`: `RivaNetworkError` (unreachable, timeout) or a
11
+ * non-retryable `RivaRequestError` (`RIVA_INVALID_RESPONSE`).
12
+ *
13
+ * Anything else is returned as it is.
14
+ */
15
+ export declare function toRivaError(error: unknown, signal?: AbortSignal): unknown;
16
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAqBA;;;;;;;;;;;;;GAaG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CA0BzE"}
@@ -0,0 +1,7 @@
1
+ export { graphqlClientTransport } from './client-transport';
2
+ export { toRivaError } from './errors';
3
+ export { type Operation, type OperationKind, operationOf } from './operation';
4
+ export { type GraphQLMutationOptions, type GraphQLQueryOptions, mutation, type OperationCache, query, } from './query';
5
+ export { type GraphQLTransport, provideGraphQL } from './transport';
6
+ export type { VarsOf } from './types';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACvC,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK,aAAa,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC9E,OAAO,EACN,KAAK,sBAAsB,EAC3B,KAAK,mBAAmB,EACxB,QAAQ,EACR,KAAK,cAAc,EACnB,KAAK,GACL,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,KAAK,gBAAgB,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACpE,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,96 @@
1
+ import {
2
+ operationOf2,
3
+ provideGraphQL2
4
+ } from "./chunks/index-zpgy1hwx.js";
5
+ import {
6
+ fetchOf
7
+ } from "./chunks/index-etvmjkh7.js";
8
+
9
+ // src/errors.ts
10
+ import {
11
+ isRetryableStatus,
12
+ RivaAbortError,
13
+ RivaHttpError,
14
+ RivaNetworkError,
15
+ RivaRequestError
16
+ } from "@softistx/riva";
17
+ var isNamed = (e, name) => e instanceof Error && e.name === name;
18
+ function toRivaError(error, signal) {
19
+ if (error instanceof RivaAbortError)
20
+ return error;
21
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError")
22
+ return new RivaAbortError;
23
+ if (isNamed(error, "ApiError") && Array.isArray(error.errors)) {
24
+ const status = error.status ?? 400;
25
+ return new RivaRequestError(error.code ?? "GRAPHQL_ERROR", error.message, {
26
+ status,
27
+ retryable: isRetryableStatus(status),
28
+ cause: error
29
+ });
30
+ }
31
+ if (isNamed(error, "ApiStatusError") && typeof error.status === "number")
32
+ return new RivaHttpError(error.status, error.message, { cause: error });
33
+ if (isNamed(error, "ApiUnavailableError")) {
34
+ if (error.reason === "invalid-response")
35
+ return new RivaRequestError("RIVA_INVALID_RESPONSE", error.message, {
36
+ retryable: false,
37
+ cause: error
38
+ });
39
+ return new RivaNetworkError(error.message, { cause: error });
40
+ }
41
+ return error;
42
+ }
43
+
44
+ // src/client-transport.ts
45
+ function graphqlClientTransport(client) {
46
+ return {
47
+ async execute(operation, variables, { signal }) {
48
+ const call = [operation.document, variables, { signal }];
49
+ try {
50
+ return await (operation.kind === "mutation" ? client.mutate(...call) : client.query(...call));
51
+ } catch (error) {
52
+ throw toRivaError(error, signal);
53
+ }
54
+ }
55
+ };
56
+ }
57
+ // src/query.ts
58
+ import {
59
+ mutation as coreMutation,
60
+ query as coreQuery
61
+ } from "@softistx/riva";
62
+ var policyOf = (cache, op) => {
63
+ const policy = cache && "forOperation" in cache ? cache.forOperation(op) : cache;
64
+ return policy ? { cache: policy } : {};
65
+ };
66
+ function query(document, opts = {}) {
67
+ const op = operationOf2(document, "query");
68
+ const { id, cache, ...rest } = opts;
69
+ return coreQuery({
70
+ ...rest,
71
+ ...policyOf(cache, op),
72
+ id: id ?? op.id,
73
+ fetch: fetchOf(op)
74
+ });
75
+ }
76
+ function mutation(document, opts = {}) {
77
+ const op = operationOf2(document, "mutation");
78
+ const { id, cache, ...rest } = opts;
79
+ return coreMutation({
80
+ ...rest,
81
+ ...policyOf(cache, op),
82
+ id: id ?? op.id,
83
+ run: fetchOf(op)
84
+ });
85
+ }
86
+ export {
87
+ graphqlClientTransport,
88
+ mutation,
89
+ operationOf2 as operationOf,
90
+ provideGraphQL2 as provideGraphQL,
91
+ query,
92
+ toRivaError
93
+ };
94
+
95
+ //# debugId=62F134F7C948C7F564756E2164756E21
96
+ //# sourceMappingURL=index.js.map