@simtlix/simfinity-js 2.6.4 → 3.0.1

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.
@@ -0,0 +1,613 @@
1
+ /**
2
+ * Type declarations for @simtlix/simfinity-js.
3
+ *
4
+ * Mirrors the public API of src/index.js (which re-exports the MCP surface of
5
+ * src/mcp.js). Mongoose and @modelcontextprotocol/sdk values are deliberately
6
+ * typed loosely (`any`) so this package does not hard-depend on either
7
+ * optional dependency's type definitions.
8
+ */
9
+
10
+ import type {
11
+ GraphQLSchema,
12
+ GraphQLObjectType,
13
+ GraphQLInputObjectType,
14
+ GraphQLOutputType,
15
+ GraphQLScalarType,
16
+ GraphQLField,
17
+ } from 'graphql';
18
+
19
+ /* ========================================================================== *
20
+ * Errors
21
+ * ========================================================================== */
22
+
23
+ /** Base error type: carries a code, an HTTP-like status and a timestamp in `extensions`. */
24
+ export class SimfinityError extends Error {
25
+ constructor(message: string, code?: string, status?: number);
26
+ extensions: {
27
+ code: string | undefined;
28
+ status: number | undefined;
29
+ timestamp: string;
30
+ };
31
+ getCode(): string | undefined;
32
+ getStatus(): number | undefined;
33
+ getTimestamp(): string;
34
+ }
35
+
36
+ /** Wrapper for unexpected errors; code is always 'INTERNAL_SERVER_ERROR'. */
37
+ export class InternalServerError extends SimfinityError {
38
+ constructor(message: string, cause?: unknown);
39
+ cause?: unknown;
40
+ getCause(): unknown;
41
+ }
42
+
43
+ /* ========================================================================== *
44
+ * MCP surface (src/mcp.js)
45
+ * ========================================================================== */
46
+
47
+ /** Loose JSON Schema fragment (draft 2020-12 keywords as plain properties). */
48
+ export type JSONSchema = Record<string, unknown>;
49
+
50
+ /** MCP behavioral hints attached to every generated tool. */
51
+ export interface MCPToolAnnotations {
52
+ title?: string;
53
+ readOnlyHint?: boolean;
54
+ destructiveHint?: boolean;
55
+ idempotentHint?: boolean;
56
+ openWorldHint?: boolean;
57
+ [key: string]: unknown;
58
+ }
59
+
60
+ /** Root operation category a tool was generated from. */
61
+ export type MCPToolKind = 'query' | 'mutation';
62
+
63
+ /** A generated MCP tool definition. */
64
+ export interface MCPTool {
65
+ /** Published tool name (GraphQL field name, optionally prefixed via `toolNamePrefix`). */
66
+ name: string;
67
+ title: string;
68
+ description: string;
69
+ /** JSON Schema for the tool arguments (full-fidelity conversion of the GraphQL args). */
70
+ inputSchema: JSONSchema;
71
+ /**
72
+ * JSON Schema mirroring the generated selection set (nullable GraphQL
73
+ * positions accept `null`). Omitted when a `toolOverrides` `selection` is
74
+ * set for the tool, since the mirrored schema could no longer be guaranteed
75
+ * accurate.
76
+ */
77
+ outputSchema?: JSONSchema;
78
+ annotations: MCPToolAnnotations;
79
+ kind: MCPToolKind;
80
+ }
81
+
82
+ /** Retry policy for remote execution (queries only — mutations are never retried). */
83
+ export interface MCPRetryOptions {
84
+ /** Number of retries after the initial attempt. */
85
+ attempts?: number;
86
+ /** Linear backoff base in milliseconds (delay = backoffMs * attemptIndex). */
87
+ backoffMs?: number;
88
+ }
89
+
90
+ /** Execute operations in-process against the provided GraphQLSchema (default). */
91
+ export interface MCPInProcessExecutionOptions {
92
+ mode?: 'in-process';
93
+ }
94
+
95
+ /** Execute operations by POSTing to a remote GraphQL HTTP endpoint. */
96
+ export interface MCPRemoteExecutionOptions {
97
+ mode: 'remote';
98
+ /** GraphQL HTTP endpoint URL. Required in remote mode. */
99
+ endpoint: string;
100
+ /** Extra HTTP headers merged over `content-type: application/json`. */
101
+ headers?: Record<string, string>;
102
+ /** Abort slow remote requests after this many milliseconds (AbortSignal.timeout). */
103
+ timeoutMs?: number;
104
+ /** Retry policy for transport failures, HTTP 5xx and 429 (queries only). */
105
+ retry?: MCPRetryOptions;
106
+ }
107
+
108
+ /** Execution strategy: discriminated on `mode`. */
109
+ export type MCPExecutionOptions = MCPInProcessExecutionOptions | MCPRemoteExecutionOptions;
110
+
111
+ /** Per-tool override applied over the generated definition. */
112
+ export interface MCPToolOverride {
113
+ description?: string;
114
+ title?: string;
115
+ /** Merged over the generated annotations. */
116
+ annotations?: MCPToolAnnotations;
117
+ selectionDepth?: number;
118
+ includeId?: boolean;
119
+ /**
120
+ * Explicit GraphQL selection set replacing the generated one. Accepts
121
+ * `'id title'` or `'{ id title }'`. Setting it omits the tool's
122
+ * `outputSchema`.
123
+ */
124
+ selection?: string;
125
+ }
126
+
127
+ /** Guardrails applied by `callTool`. */
128
+ export interface MCPLimits {
129
+ /** Reject (isError MCP_PAGE_SIZE_EXCEEDED) when `args.pagination.size` exceeds this. */
130
+ maxPageSize?: number;
131
+ /**
132
+ * Injected as `args.pagination` when the tool has a pagination arg and the
133
+ * caller sent none. QLPagination declares `page` and `size` non-null, so
134
+ * both are required here; `size` must not exceed `maxPageSize` (validated
135
+ * at setup, MCP_INVALID_LIMITS).
136
+ */
137
+ defaultPagination?: {
138
+ page: number;
139
+ size: number;
140
+ count?: boolean;
141
+ [key: string]: unknown;
142
+ };
143
+ /** Reject (isError MCP_RESULT_TOO_LARGE) when the serialized data is larger than this. */
144
+ maxResultBytes?: number;
145
+ }
146
+
147
+ /** Per-call metadata passed through to middleware and context factories (e.g. the SDK's RequestHandlerExtra). */
148
+ export interface MCPCallExtra {
149
+ /** Already-aborted signals make `callTool` throw MCP_CALL_CANCELLED; remote fetches receive the combined signal. */
150
+ signal?: AbortSignal;
151
+ [key: string]: unknown;
152
+ }
153
+
154
+ /** The mutable call descriptor handed to each tool middleware. */
155
+ export interface MCPToolMiddlewareCall {
156
+ /** Published (prefixed) tool name. */
157
+ name: string;
158
+ /** Tool arguments; middleware may mutate or replace this. */
159
+ args: Record<string, unknown>;
160
+ /** Per-call metadata (may be undefined for direct `callTool` invocations). */
161
+ extra: MCPCallExtra | undefined;
162
+ kind: MCPToolKind;
163
+ /** The prebuilt GraphQL operation document for this tool. */
164
+ operation: string;
165
+ }
166
+
167
+ /** Result of a tool call (MCP CallToolResult shape). */
168
+ export interface CallToolResult {
169
+ content: Array<{ type: 'text'; text: string }>;
170
+ isError: boolean;
171
+ /** Present on success when the GraphQL `data` is non-null; absent on errors. */
172
+ structuredContent?: Record<string, unknown>;
173
+ /** Present when a total record count is available (pagination.count / remote extensions.count). */
174
+ _meta?: { count?: number };
175
+ }
176
+
177
+ /**
178
+ * Koa-style middleware run around every tool execution. May mutate
179
+ * `call.args`, short-circuit by returning a result without calling `next()`,
180
+ * or throw. Calling `next()` twice rejects with MCP_MIDDLEWARE_ERROR.
181
+ */
182
+ export type MCPToolMiddleware = (
183
+ call: MCPToolMiddlewareCall,
184
+ next: () => Promise<CallToolResult>,
185
+ ) => CallToolResult | Promise<CallToolResult>;
186
+
187
+ /** GraphQL context factory for in-process / stdio execution. */
188
+ export type MCPContextFactory = (extra?: MCPCallExtra) => unknown;
189
+
190
+ /** GraphQL context factory for the HTTP handler (invoked per request with the Express request). */
191
+ export type MCPHTTPContextFactory = (req: any, extra?: MCPCallExtra) => unknown;
192
+
193
+ /** Envelop-style plugin; only the `onSchemaChange` hook is invoked (in-process mode, once before serving). */
194
+ export interface EnvelopSchemaPlugin {
195
+ onSchemaChange?: (payload: {
196
+ schema: GraphQLSchema;
197
+ replaceSchema: (schema: GraphQLSchema) => void;
198
+ }) => void;
199
+ [key: string]: unknown;
200
+ }
201
+
202
+ /** Options for {@link generateMCPTools}. All optional; defaults preserve previous behavior. */
203
+ export interface GenerateMCPToolsOptions {
204
+ /** Execution strategy. Defaults to in-process execution against the schema. */
205
+ execution?: MCPExecutionOptions | null;
206
+ /**
207
+ * GraphQL context value or factory. In-process / stdio: `(extra) => ctx`
208
+ * ({@link MCPContextFactory}); the HTTP handler invokes a function context as
209
+ * `(req, extra) => ctx` per request ({@link MCPHTTPContextFactory}).
210
+ */
211
+ context?: unknown;
212
+ /** Only expose these tool/field names or the categories 'query' / 'mutation'. */
213
+ include?: string | string[];
214
+ /** Never expose these tool/field names or categories. Wins over `include`. */
215
+ exclude?: string | string[];
216
+ /** Only expose tools whose entity (return) type has one of these names. */
217
+ includeTypes?: string | string[];
218
+ /** Never expose tools whose entity (return) type has one of these names. */
219
+ excludeTypes?: string | string[];
220
+ /** Nesting depth for the auto-generated selection set and output schema. Default 1. */
221
+ selectionDepth?: number;
222
+ /** Always select `id` when nothing else is selectable on an object type. Default true. */
223
+ includeId?: boolean;
224
+ /** Prefix prepended to every published tool name (validated /^[a-zA-Z0-9_-]+$/). */
225
+ toolNamePrefix?: string;
226
+ /** Per-tool overrides keyed by published tool name or unprefixed field name. */
227
+ toolOverrides?: Record<string, MCPToolOverride>;
228
+ /** Koa-style middleware run around every tool execution. */
229
+ toolMiddleware?: MCPToolMiddleware[];
230
+ /** Pagination / result-size guardrails. */
231
+ limits?: MCPLimits;
232
+ /** Envelop-style plugins whose `onSchemaChange` hook is applied before serving (in-process mode only). */
233
+ schemaPlugins?: EnvelopSchemaPlugin[];
234
+ }
235
+
236
+ /** Options for the MCP server / transport factories. */
237
+ export interface MCPServerOptions extends GenerateMCPToolsOptions {
238
+ /** MCP server name (default 'simfinity-mcp'). */
239
+ serverName?: string;
240
+ /** MCP server version (default '1.0.0'). */
241
+ serverVersion?: string;
242
+ }
243
+
244
+ /** Extra options accepted by {@link createHTTPMCPHandler}. */
245
+ export interface HTTPMCPHandlerOptions extends MCPServerOptions {
246
+ /** Spread into the SDK's StreamableHTTPServerTransport options (e.g. enableDnsRebindingProtection, allowedHosts, allowedOrigins). */
247
+ transportOptions?: Record<string, unknown>;
248
+ /** Invoked when the handler fails; the handler then responds 500 (JSON-RPC internal error) if headers were not sent. */
249
+ onError?: (err: unknown, req: any, res: any) => void;
250
+ }
251
+
252
+ /** Result of {@link generateMCPTools}. */
253
+ export interface GeneratedMCPTools {
254
+ tools: MCPTool[];
255
+ /**
256
+ * Execute a tool by its published name. Returns a {@link CallToolResult}
257
+ * (GraphQL errors become `isError` results). Throws SimfinityError
258
+ * MCP_TOOL_NOT_FOUND for unknown names and MCP_CALL_CANCELLED when
259
+ * `extra.signal` is already aborted.
260
+ */
261
+ callTool: (
262
+ name: string,
263
+ args?: Record<string, unknown>,
264
+ extra?: MCPCallExtra,
265
+ ) => Promise<CallToolResult>;
266
+ /** Return the prebuilt GraphQL operation document for a tool; throws MCP_TOOL_NOT_FOUND for unknown names. */
267
+ getOperation: (name: string) => string;
268
+ }
269
+
270
+ /**
271
+ * An MCP SDK Server instance (call `server.connect(transport)`). Typed loosely
272
+ * to avoid a hard dependency on the optional `@modelcontextprotocol/sdk`.
273
+ */
274
+ export type MCPServer = any;
275
+
276
+ /** Express-style request handler serving the MCP over Streamable HTTP. */
277
+ export type HTTPMCPRequestHandler = (req: any, res: any) => Promise<void>;
278
+
279
+ /**
280
+ * Generate MCP tool definitions and an executor from a Simfinity-generated
281
+ * GraphQLSchema. Every root Query and Mutation field becomes a tool.
282
+ */
283
+ export function generateMCPTools(
284
+ schema: GraphQLSchema,
285
+ options?: GenerateMCPToolsOptions,
286
+ ): GeneratedMCPTools;
287
+
288
+ /** Build the MCP `inputSchema` (JSON Schema) for a single GraphQL field's arguments. */
289
+ export function graphqlArgsToJSONSchema(field: GraphQLField<any, any>): JSONSchema;
290
+
291
+ /**
292
+ * Create a transport-agnostic MCP Server exposing every GraphQL operation as a
293
+ * tool. Requires the optional `@modelcontextprotocol/sdk` dependency (throws
294
+ * SimfinityError MCP_SDK_NOT_INSTALLED / MCP_SDK_INCOMPATIBLE / MCP_SDK_LOAD_FAILED).
295
+ */
296
+ export function createMCPServer(
297
+ schema: GraphQLSchema,
298
+ options?: MCPServerOptions,
299
+ ): Promise<MCPServer>;
300
+
301
+ /** Create an MCP Server and connect it over stdio (for a standalone MCP executable). */
302
+ export function startStdioMCPServer(
303
+ schema: GraphQLSchema,
304
+ options?: MCPServerOptions,
305
+ ): Promise<MCPServer>;
306
+
307
+ /**
308
+ * Create an Express-style request handler serving the MCP over Streamable
309
+ * HTTP. Tool definitions are built once; a fresh server + transport pair is
310
+ * created per request, and a function `context` is invoked `(req, extra)` per
311
+ * request.
312
+ */
313
+ export function createHTTPMCPHandler(
314
+ schema: GraphQLSchema,
315
+ options?: HTTPMCPHandlerOptions,
316
+ ): Promise<HTTPMCPRequestHandler>;
317
+
318
+ /** Namespace object bundling the MCP surface (default export of src/mcp.js). */
319
+ export const mcp: {
320
+ generateMCPTools: typeof generateMCPTools;
321
+ graphqlArgsToJSONSchema: typeof graphqlArgsToJSONSchema;
322
+ createMCPServer: typeof createMCPServer;
323
+ startStdioMCPServer: typeof startStdioMCPServer;
324
+ createHTTPMCPHandler: typeof createHTTPMCPHandler;
325
+ };
326
+
327
+ /* ========================================================================== *
328
+ * Core schema-building API (src/index.js)
329
+ * ========================================================================== */
330
+
331
+ /** Lifecycle hooks invoked around create / update / delete of an entity. */
332
+ export interface EntityController {
333
+ onSaving?(doc: any, args: any, session: any, context: any): void | Promise<void>;
334
+ onSaved?(result: any, args: any, session: any, context: any): void | Promise<void>;
335
+ onUpdating?(id: any, args: any, session: any, context: any): void | Promise<void>;
336
+ onUpdated?(result: any, session: any, context: any): void | Promise<void>;
337
+ onDelete?(doc: any, session: any, context: any): void | Promise<void>;
338
+ }
339
+
340
+ /** State machine attached to an entity (initial state plus named action transitions). */
341
+ export interface StateMachine {
342
+ initialState: any;
343
+ actions: Record<string, any>;
344
+ [key: string]: any;
345
+ }
346
+
347
+ /** Register a Mongoose model + GraphQL type pair, exposing single and list endpoints. */
348
+ export function connect(
349
+ model: any,
350
+ gqltype: GraphQLObjectType,
351
+ simpleEntityEndpointName: string,
352
+ listEntitiesEndpointName: string,
353
+ controller?: EntityController | null,
354
+ onModelCreated?: ((model: any) => void) | null,
355
+ stateMachine?: StateMachine | null,
356
+ ): void;
357
+
358
+ /** Register a GraphQL type without exposing root endpoints (e.g. embedded/related types). */
359
+ export function addNoEndpointType(gqltype: GraphQLObjectType): void;
360
+
361
+ /**
362
+ * Build the executable GraphQLSchema from every connected type. The first two
363
+ * allowlists are matched against the GraphQLObjectType INSTANCES passed to
364
+ * connect(); only custom mutations are matched by name.
365
+ */
366
+ export function createSchema(
367
+ includedQueryTypes?: GraphQLObjectType[] | null,
368
+ includedMutationTypes?: GraphQLObjectType[] | null,
369
+ includedCustomMutations?: string[] | null,
370
+ ): GraphQLSchema;
371
+
372
+ /** Register a custom mutation executed inside a transaction. */
373
+ export function registerMutation(
374
+ name: string,
375
+ description: string,
376
+ inputModel: GraphQLInputObjectType | null | undefined,
377
+ outputModel: GraphQLOutputType,
378
+ callback: (input: any, session: any, context: any) => any,
379
+ ): void;
380
+
381
+ /** Operation context passed to Simfinity middlewares registered via {@link use}. */
382
+ export interface SimfinityMiddlewareContext {
383
+ args: any;
384
+ operation: string;
385
+ entry?: string;
386
+ type?: any;
387
+ context?: any;
388
+ [key: string]: any;
389
+ }
390
+
391
+ /** Register a koa-style middleware run around every Simfinity operation. */
392
+ export function use(
393
+ middleware: (
394
+ context: SimfinityMiddlewareContext,
395
+ next: () => Promise<void>,
396
+ ) => void | Promise<void>,
397
+ ): void;
398
+
399
+ /** Build a GraphQL error formatter that normalizes unexpected errors to {@link InternalServerError}. */
400
+ export function buildErrorFormatter(
401
+ callback?: (error: SimfinityError) => Error | void,
402
+ ): (err: Error) => Error;
403
+
404
+ /** Globally prevent Mongoose collection creation for generated models. */
405
+ export function preventCreatingCollection(prevent: boolean): void;
406
+
407
+ /** Get the generated GraphQL input type registered for an object type. */
408
+ export function getInputType(type: GraphQLObjectType | { name: string }): GraphQLInputObjectType;
409
+
410
+ /** Persist an object of a connected type inside a transaction (runs controllers/validators). */
411
+ export function saveObject(
412
+ typeName: string,
413
+ args: Record<string, any>,
414
+ session?: any,
415
+ context?: any,
416
+ ): Promise<any>;
417
+
418
+ /** Get the Mongoose model registered for a connected GraphQL type. */
419
+ export function getModel(gqltype: GraphQLObjectType | { name: string }): any;
420
+
421
+ /** Look up a connected GraphQL type by name (or by another type's name). */
422
+ export function getType(
423
+ typeName: string | { name: string },
424
+ ): GraphQLObjectType | null | undefined;
425
+
426
+ /**
427
+ * Create a custom scalar that validates values against `validate` while
428
+ * (de)serializing via `baseScalarType`. The resulting scalar is named
429
+ * `${name}_${baseScalarType.name}` and exposes `baseScalarType`.
430
+ */
431
+ export function createValidatedScalar(
432
+ name: string,
433
+ description: string,
434
+ baseScalarType: GraphQLScalarType,
435
+ validate: (value: any) => void,
436
+ ): GraphQLScalarType & { baseScalarType: GraphQLScalarType };
437
+
438
+ /* ========================================================================== *
439
+ * Query building (src/index.js)
440
+ * ========================================================================== */
441
+
442
+ /** A QLFilterGroup input value (recursive AND/OR groups plus flat conditions). */
443
+ export interface FilterGroupInput {
444
+ AND?: FilterGroupInput[];
445
+ OR?: FilterGroupInput[];
446
+ conditions?: Array<{
447
+ field: string;
448
+ operator?: string;
449
+ value?: any;
450
+ path?: string;
451
+ }>;
452
+ [key: string]: any;
453
+ }
454
+
455
+ /** Translate list-query arguments (filters, AND/OR, sort, pagination) into a MongoDB aggregation pipeline. */
456
+ export function buildQuery(
457
+ input: Record<string, any>,
458
+ gqltype: GraphQLObjectType,
459
+ isCount?: boolean,
460
+ ): Promise<Array<Record<string, any>>>;
461
+
462
+ /** Translate a QLFilterGroup into a MongoDB `$match` expression, collecting required lookups. */
463
+ export function buildFilterGroupMatch(
464
+ filterGroup: FilterGroupInput,
465
+ gqltype: GraphQLObjectType,
466
+ aggregateClauses: any[],
467
+ aggregationsIncluded: Record<string, any>,
468
+ depth?: number,
469
+ ): Promise<any>;
470
+
471
+ /* ========================================================================== *
472
+ * Validators (src/validators.js default export)
473
+ * ========================================================================== */
474
+
475
+ /** A single field validator (throws SimfinityError VALIDATION_ERROR on failure). */
476
+ export interface FieldValidator {
477
+ validate(typeName: string, fieldName: string, value: unknown, session?: unknown): Promise<void>;
478
+ }
479
+
480
+ /** Validators grouped by operation, as expected by field `extensions.validations`. */
481
+ export interface FieldValidations {
482
+ CREATE: FieldValidator[];
483
+ UPDATE: FieldValidator[];
484
+ /** Backward-compatible alias of CREATE. */
485
+ save: FieldValidator[];
486
+ /** Backward-compatible alias of UPDATE. */
487
+ update: FieldValidator[];
488
+ }
489
+
490
+ /** Built-in field validator factories. */
491
+ export const validators: {
492
+ stringLength(name: string, min?: number, max?: number): FieldValidations;
493
+ maxLength(name: string, max: number): FieldValidations;
494
+ pattern(name: string, regex: RegExp | string, message?: string): FieldValidations;
495
+ email(): FieldValidations;
496
+ url(): FieldValidations;
497
+ numberRange(name: string, min?: number, max?: number): FieldValidations;
498
+ positive(name: string): FieldValidations;
499
+ arrayLength(name: string, maxItems?: number, itemValidator?: FieldValidator[]): FieldValidations;
500
+ dateFormat(name: string, format?: string): FieldValidations;
501
+ futureDate(name: string): FieldValidations;
502
+ };
503
+
504
+ /* ========================================================================== *
505
+ * Scalars (src/scalars.js default export)
506
+ * ========================================================================== */
507
+
508
+ /** Pre-built validated scalars and factory functions. */
509
+ export const scalars: {
510
+ EmailScalar: GraphQLScalarType;
511
+ URLScalar: GraphQLScalarType;
512
+ PositiveIntScalar: GraphQLScalarType;
513
+ PositiveFloatScalar: GraphQLScalarType;
514
+ createBoundedStringScalar(name: string, min?: number, max?: number): GraphQLScalarType;
515
+ createBoundedIntScalar(name: string, min?: number, max?: number): GraphQLScalarType;
516
+ createBoundedFloatScalar(name: string, min?: number, max?: number): GraphQLScalarType;
517
+ createPatternStringScalar(name: string, pattern: RegExp | string, message?: string): GraphQLScalarType;
518
+ };
519
+
520
+ /* ========================================================================== *
521
+ * Auth (src/auth/index.js default export)
522
+ * ========================================================================== */
523
+
524
+ /** A rule function: return true/void to allow, false to deny (or throw). */
525
+ export type AuthRuleFunction = (
526
+ parent: any,
527
+ args: any,
528
+ ctx: any,
529
+ info: any,
530
+ ) => boolean | void | Promise<boolean | void>;
531
+
532
+ /** Declarative policy expression (JSON AST). */
533
+ export type PolicyExpression = Record<string, unknown>;
534
+
535
+ /** A rule: function, array of functions (AND), or a policy expression. */
536
+ export type AuthRule = AuthRuleFunction | AuthRuleFunction[] | PolicyExpression;
537
+
538
+ /** Field-name (or '*') to rule mapping for one GraphQL type. */
539
+ export type TypePermissions = Record<string, AuthRule>;
540
+
541
+ /** Type-name to {@link TypePermissions} mapping. */
542
+ export type PermissionSchema = Record<string, TypePermissions>;
543
+
544
+ /** Options for the auth plugin / middleware factories. */
545
+ export interface AuthPluginOptions {
546
+ /** Policy applied when no rule matches. Default 'DENY'. */
547
+ defaultPolicy?: 'ALLOW' | 'DENY';
548
+ debug?: boolean;
549
+ }
550
+
551
+ declare class UnauthenticatedError extends SimfinityError {
552
+ constructor(message?: string);
553
+ }
554
+
555
+ declare class ForbiddenError extends SimfinityError {
556
+ constructor(message?: string);
557
+ }
558
+
559
+ /** Authorization utilities (RBAC/ABAC rules, plugin factories and auth errors). */
560
+ export const auth: {
561
+ /** Envelop-compatible plugin that wraps schema resolvers in-place via `onSchemaChange`. */
562
+ createAuthPlugin(permissions: PermissionSchema, options?: AuthPluginOptions): EnvelopSchemaPlugin;
563
+ /** @deprecated Use createAuthPlugin instead. graphql-middleware compatible middleware. */
564
+ createAuthMiddleware(
565
+ permissions: PermissionSchema,
566
+ options?: AuthPluginOptions,
567
+ ): (resolve: any, parent: any, args: any, ctx: any, info: any) => Promise<any>;
568
+ /** @deprecated Use createAuthPlugin instead. Field middleware object for graphql-middleware. */
569
+ createFieldMiddleware(
570
+ permissions: PermissionSchema,
571
+ options?: AuthPluginOptions,
572
+ ): Record<string, Record<string, any>>;
573
+ resolvePath(obj: any, pathOrFn: string | ((obj: any) => any)): any;
574
+ requireAuth(userPath?: string): AuthRuleFunction;
575
+ requireRole(role: string | string[], options?: { userPath?: string; rolePath?: string }): AuthRuleFunction;
576
+ requirePermission(
577
+ permission: string | string[],
578
+ options?: { userPath?: string; permissionsPath?: string },
579
+ ): AuthRuleFunction;
580
+ composeRules(...rules: AuthRuleFunction[]): AuthRuleFunction;
581
+ anyRule(...rules: AuthRuleFunction[]): AuthRuleFunction;
582
+ isOwner(ownerField?: string, userIdField?: string, options?: { userPath?: string }): AuthRuleFunction;
583
+ createRule(predicate: AuthRuleFunction, errorMessage?: string, errorCode?: string): AuthRuleFunction;
584
+ allow(): AuthRuleFunction;
585
+ deny(message?: string): AuthRuleFunction;
586
+ evaluateExpression(expression: PolicyExpression, context: any): boolean;
587
+ isPolicyExpression(value: unknown): boolean;
588
+ createRuleFromExpression(expression: PolicyExpression): AuthRuleFunction;
589
+ UnauthenticatedError: typeof UnauthenticatedError;
590
+ ForbiddenError: typeof ForbiddenError;
591
+ createAuthError(message: string, code?: string): SimfinityError;
592
+ };
593
+
594
+ /* ========================================================================== *
595
+ * Plugins (src/plugins.js default export)
596
+ * ========================================================================== */
597
+
598
+ /** GraphQL server plugins: auth plugin factory plus count-extension plugins. */
599
+ export const plugins: {
600
+ createAuthPlugin(permissions: PermissionSchema, options?: AuthPluginOptions): EnvelopSchemaPlugin;
601
+ /** Apollo Server plugin that copies `contextValue.count` into `extensions.count`. */
602
+ apolloCountPlugin(): {
603
+ requestDidStart(): Promise<{
604
+ willSendResponse(payload: any): Promise<void>;
605
+ }>;
606
+ };
607
+ /** Envelop plugin that copies `contextValue.count` into `extensions.count`. */
608
+ envelopCountPlugin(): {
609
+ onExecute(): {
610
+ onExecuteDone(payload: any): void;
611
+ };
612
+ };
613
+ };