@simtlix/simfinity-js 3.0.1 → 3.3.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.
package/types/index.d.ts CHANGED
@@ -1,10 +1,9 @@
1
1
  /**
2
2
  * Type declarations for @simtlix/simfinity-js.
3
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.
4
+ * Mirrors the MongoDB facade in src/index.js. Shared helper and MCP types are
5
+ * re-exported from their canonical packages; MongoDB model and session values
6
+ * remain deliberately typed loosely (`any`).
8
7
  */
9
8
 
10
9
  import type {
@@ -12,327 +11,49 @@ import type {
12
11
  GraphQLObjectType,
13
12
  GraphQLInputObjectType,
14
13
  GraphQLOutputType,
15
- GraphQLScalarType,
16
- GraphQLField,
17
14
  } 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
- };
15
+ import type {
16
+ DatabaseAdapter,
17
+ RuntimeRegistration,
18
+ SimfinityError,
19
+ } from '@simtlix/simfinity-core';
20
+ export {
21
+ auth,
22
+ buildErrorFormatter,
23
+ createRuntime,
24
+ createValidatedScalar,
25
+ InternalServerError,
26
+ plugins,
27
+ scalars,
28
+ SimfinityError,
29
+ validators,
30
+ } from '@simtlix/simfinity-core';
31
+ export type {
32
+ AuthPluginOptions,
33
+ AuthRule,
34
+ AuthRuleFunction,
35
+ EnvelopSchemaPlugin,
36
+ FieldValidations,
37
+ FieldValidator,
38
+ PermissionSchema,
39
+ PolicyExpression,
40
+ TypePermissions,
41
+ } from '@simtlix/simfinity-core';
42
+ export * from '@simtlix/simfinity-mcp';
43
+ export { default as mcp } from '@simtlix/simfinity-mcp';
44
+ export function createMongoAdapter(): DatabaseAdapter;
45
+ export function getRegistrations(): RuntimeRegistration[];
326
46
 
327
47
  /* ========================================================================== *
328
48
  * Core schema-building API (src/index.js)
329
49
  * ========================================================================== */
330
50
 
331
- /** Lifecycle hooks invoked around create / update / delete of an entity. */
51
+ /** Lifecycle hooks run before commit and may repeat on a transient transaction retry. */
332
52
  export interface EntityController {
333
53
  onSaving?(doc: any, args: any, session: any, context: any): void | Promise<void>;
334
54
  onSaved?(result: any, args: any, session: any, context: any): void | Promise<void>;
335
55
  onUpdating?(id: any, args: any, session: any, context: any): void | Promise<void>;
56
+ /** Receives the updated Mongoose document after parent and nested writes complete. */
336
57
  onUpdated?(result: any, session: any, context: any): void | Promise<void>;
337
58
  onDelete?(doc: any, session: any, context: any): void | Promise<void>;
338
59
  }
@@ -378,7 +99,7 @@ export function registerMutation(
378
99
  callback: (input: any, session: any, context: any) => any,
379
100
  ): void;
380
101
 
381
- /** Operation context passed to Simfinity middlewares registered via {@link use}. */
102
+ /** Operation context for root operations, generated non-embedded relation reads, and nested collection writes. */
382
103
  export interface SimfinityMiddlewareContext {
383
104
  args: any;
384
105
  operation: string;
@@ -388,7 +109,11 @@ export interface SimfinityMiddlewareContext {
388
109
  [key: string]: any;
389
110
  }
390
111
 
391
- /** Register a koa-style middleware run around every Simfinity operation. */
112
+ /**
113
+ * Register middleware before generated operations, including related-type reads and nested child writes.
114
+ * Nested operations keep root argument shapes and the GraphQL request context.
115
+ * Await next() to advance the middleware chain; throw to reject before the operation executes.
116
+ */
392
117
  export function use(
393
118
  middleware: (
394
119
  context: SimfinityMiddlewareContext,
@@ -396,18 +121,34 @@ export function use(
396
121
  ) => void | Promise<void>,
397
122
  ): void;
398
123
 
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
124
  /** Globally prevent Mongoose collection creation for generated models. */
405
125
  export function preventCreatingCollection(prevent: boolean): void;
406
126
 
407
- /** Get the generated GraphQL input type registered for an object type. */
127
+ /** Process-wide limits for generated list and paginated aggregate queries. */
128
+ export interface QueryLimitsOptions {
129
+ /** Positive safe integer; defaults to 1000. Unpaged lists use min(100, maxPageSize). */
130
+ maxPageSize?: number;
131
+ }
132
+
133
+ /** Configure at startup. Invalid configuration throws INVALID_QUERY_LIMITS (400). */
134
+ export function configureQueryLimits(options?: QueryLimitsOptions): void;
135
+
136
+ /**
137
+ * Get the generated create input type, preserving field and list-item non-null
138
+ * wrappers. Update inputs remove only the outer wrapper (except entity id).
139
+ * References use IdInputType; embedded lists use nested inputs; referenced
140
+ * collections use added/updated/deleted operation inputs.
141
+ */
408
142
  export function getInputType(type: GraphQLObjectType | { name: string }): GraphQLInputObjectType;
409
143
 
410
- /** Persist an object of a connected type inside a transaction (runs controllers/validators). */
144
+ /**
145
+ * Persist an object and its nested writes inside a transaction (runs controllers/validators).
146
+ * Without a session, owns a transaction on the model's connection and awaits cleanup.
147
+ * A supplied session must have an active transaction and belong to the model's MongoDB client.
148
+ * The caller then owns retries, commit, abort, and cleanup; inactive sessions are rejected.
149
+ * Owned transactions retry transient failures and uncertain commits separately, up to five times each.
150
+ */
151
+
411
152
  export function saveObject(
412
153
  typeName: string,
413
154
  args: Record<string, any>,
@@ -423,18 +164,6 @@ export function getType(
423
164
  typeName: string | { name: string },
424
165
  ): GraphQLObjectType | null | undefined;
425
166
 
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
167
  /* ========================================================================== *
439
168
  * Query building (src/index.js)
440
169
  * ========================================================================== */
@@ -467,147 +196,3 @@ export function buildFilterGroupMatch(
467
196
  aggregationsIncluded: Record<string, any>,
468
197
  depth?: number,
469
198
  ): 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
- };