Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 31 additions & 11 deletions src/mock/generator.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getOperationAST, Kind, parse } from 'graphql';
import { unwrapType } from '../operations/variables.js';
import { GraphQLExecutor } from '../mcp/executor.js';
import type { ParsedSchema, SchemaField, TypeReference } from '../types/index.js';
Expand All @@ -11,6 +12,18 @@ export interface MockConfig {
const DEFAULT_ARRAY_LENGTH = 3;
const DEFAULT_MAX_DEPTH = 3;

const validateConfig = (config?: MockConfig): void => {
const limits = [
config?.arrayLength ?? DEFAULT_ARRAY_LENGTH,
config?.maxDepth ?? DEFAULT_MAX_DEPTH,
];
for (const value of limits) {
if (!Number.isSafeInteger(value) || value < 0) {
throw new RangeError('Mock arrayLength and maxDepth must be non-negative safe integers');
}
}
};

/**
* Simple deterministic hash from a string.
* Returns a positive integer.
Expand Down Expand Up @@ -223,6 +236,7 @@ export const generateMockData = (
typeName: string,
config?: MockConfig,
): Record<string, unknown> => {
validateConfig(config);
const seed = config?.seed ?? 0;
const arrayLength = config?.arrayLength ?? DEFAULT_ARRAY_LENGTH;
const maxDepth = config?.maxDepth ?? DEFAULT_MAX_DEPTH;
Expand All @@ -244,11 +258,14 @@ export const generateMockData = (
/**
* Extract the root field name from a GraphQL operation string.
*/
const extractRootFieldName = (operation: string): string | null => {
// Match the first field after the opening brace of the operation
// e.g., "query UserQuery($id: ID!) {\n user(id: $id) {\n..."
const match = operation.match(/\{\s*(?<fieldName>\w+)/u);
return match?.groups?.fieldName ?? null;
const extractRootFieldName = (operation: string): { name: string; responseName: string } | null => {
const definition = getOperationAST(parse(operation));
const field = definition?.selectionSet.selections.find(
(selection) => selection.kind === Kind.FIELD,
);
return field
? { name: field.name.value, responseName: field.alias?.value ?? field.name.value }
: null;
};

/**
Expand Down Expand Up @@ -320,22 +337,25 @@ const isListField = (schema: ParsedSchema, fieldName: string): boolean => {
* Implements the same interface as GraphQLExecutor.
*/
export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): GraphQLExecutor => {
validateConfig(config);
const mockExecutor = Object.create(GraphQLExecutor.prototype) as GraphQLExecutor;

// Override the execute method
(mockExecutor as unknown as Record<string, unknown>).execute = async (
operation: string,
): Promise<string> => {
// Parse the operation to find the root field name and its return type
const rootFieldName = extractRootFieldName(operation);
if (!rootFieldName) {
const rootField = extractRootFieldName(operation);
if (!rootField) {
return JSON.stringify({ data: null });
}

const { name: rootFieldName, responseName } = rootField;

// Find the return type from the schema
const returnTypeName = findReturnTypeName(schema, rootFieldName);
if (!returnTypeName) {
return JSON.stringify({ data: { [rootFieldName]: null } });
return JSON.stringify({ data: { [responseName]: null } });
}

// Check if it's a scalar return type
Expand All @@ -345,7 +365,7 @@ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): G
index: 0,
seed: config?.seed ?? 0,
});
return JSON.stringify({ data: { [rootFieldName]: scalarValue } }, null, 2);
return JSON.stringify({ data: { [responseName]: scalarValue } }, null, 2);
}

// Check if the field returns a list
Expand All @@ -361,11 +381,11 @@ export const createMockExecutor = (schema: ParsedSchema, config?: MockConfig): G
}),
);
}
return JSON.stringify({ data: { [rootFieldName]: items } }, null, 2);
return JSON.stringify({ data: { [responseName]: items } }, null, 2);
}

const mockData = generateMockData(schema, returnTypeName, config);
return JSON.stringify({ data: { [rootFieldName]: mockData } }, null, 2);
return JSON.stringify({ data: { [responseName]: mockData } }, null, 2);
};

return mockExecutor;
Expand Down
22 changes: 18 additions & 4 deletions src/pagination/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,12 +176,15 @@ const executeRelayPaginated = async ({
variables,
}: PaginationExecutionContext): Promise<PaginatedResult> => {
const allItems: unknown[] = [];
let cursor: string | null = null;
let cursor: string | null = typeof variables.after === 'string' ? variables.after : null;
const requestedCursors = new Set<string | null>();
let canFetchMore = true;
let startCursor: string | null = null;
let hasMore = true;
let pageCount = 0;

while (hasMore && (pageCount === 0 || Boolean(cursor)) && pageCount < maxPages) {
while (hasMore && canFetchMore && pageCount < maxPages) {
requestedCursors.add(cursor);
const pageVariables: Record<string, unknown> = {
...variables,
first: pageSize,
Expand Down Expand Up @@ -219,8 +222,9 @@ const executeRelayPaginated = async ({
}

hasMore = hasNextPage;
canFetchMore = Boolean(endCursor) && !requestedCursors.has(endCursor);
// The cursor is loop-carried state and is also returned to the caller.
// eslint-disable-next-line sonarjs/no-redundant-assignments

cursor = endCursor;
pageCount += 1;
}
Expand Down Expand Up @@ -249,12 +253,12 @@ const executeOffsetPaginated = async ({
variables,
}: PaginationExecutionContext): Promise<PaginatedResult> => {
const allItems: unknown[] = [];
let currentOffset = 0;
let hasMore = true;
let pageCount = 0;

// Detect whether to use limit/offset or skip/take
const useSkipTake = operation.includes('$skip') && operation.includes('$take');
let currentOffset = Number((useSkipTake ? variables.skip : variables.offset) ?? 0);

while (hasMore && pageCount < maxPages) {
const pageVariables: Record<string, unknown> = { ...variables };
Expand Down Expand Up @@ -304,6 +308,16 @@ export const executePaginated = async (
const style = config?.style ?? 'auto';
const pageSize = config?.pageSize ?? DEFAULT_PAGE_SIZE;
const maxPages = config?.maxPages ?? DEFAULT_MAX_PAGES;
if (
!Number.isSafeInteger(pageSize) ||
pageSize <= 0 ||
!Number.isSafeInteger(maxPages) ||
maxPages < 0
) {
throw new RangeError(
'pageSize must be a positive safe integer and maxPages a non-negative safe integer',
);
}

if (style === 'relay' || (style === 'auto' && isRelayOperation(operation))) {
return executeRelayPaginated({ executor, maxPages, operation, pageSize, variables });
Expand Down
7 changes: 6 additions & 1 deletion src/summarizer/summarizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,12 @@ export const summarizeResponse = (

const result: Record<string, unknown> = {};
for (const [key, currentValue] of Object.entries(value as Record<string, unknown>)) {
result[key] = summarize(currentValue, depth + 1);
Object.defineProperty(result, key, {
configurable: true,
enumerable: true,
value: summarize(currentValue, depth + 1),
writable: true,
});
}
return result;
}
Expand Down
73 changes: 73 additions & 0 deletions tests/maintenance-regression.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { expect, it, vi } from 'vitest';
import { buildSchema, introspectionFromSchema } from 'graphql';
import { parseSchema } from '../src/introspection/parser.js';
import { executePaginated } from '../src/pagination/handler.js';
import { createMockExecutor, generateMockData } from '../src/mock/generator.js';
import { summarizeResponse } from '../src/summarizer/summarizer.js';
import type { GraphQLExecutor } from '../src/mcp/executor.js';

const schema = parseSchema(
introspectionFromSchema(
buildSchema('type Query { users: [User] user: User } type User { name: String }'),
),
);

it.each(['offset', 'skip'])('starts pagination at the supplied %s', async (key) => {
const execute = vi.fn().mockResolvedValue('{"users":[]}');
const operation =
key === 'skip' ? 'query($skip:Int,$take:Int){users}' : 'query($offset:Int,$limit:Int){users}';
await executePaginated(
{ execute } as unknown as GraphQLExecutor,
operation,
{ [key]: 40 },
{ pageSize: 20, style: 'offset' },
);
expect(execute.mock.calls[0][1][key]).toBe(40);
});

it('rejects invalid pagination bounds before making a request', async () => {
const execute = vi.fn().mockResolvedValue('{"users":[]}');
const executor = { execute } as unknown as GraphQLExecutor;
await expect(
executePaginated(executor, '{users}', {}, { pageSize: 0, style: 'offset' }),
).rejects.toThrow(RangeError);
await expect(
executePaginated(executor, '{users}', {}, { maxPages: NaN, pageSize: 20, style: 'offset' }),
).rejects.toThrow(RangeError);
expect(execute).not.toHaveBeenCalled();
});

it('stops when a Relay server repeats a cursor', async () => {
const execute = vi
.fn()
.mockResolvedValue(
'{"users":{"edges":[{"node":{"name":"A"}}],"pageInfo":{"hasNextPage":true,"endCursor":"same"}}}',
);
const result = await executePaginated(
{ execute } as unknown as GraphQLExecutor,
'{users}',
{},
{ maxPages: 5, pageSize: 1, style: 'relay' },
);
expect(execute).toHaveBeenCalledTimes(2);
expect(result.hasMore).toBe(true);
});

it('uses the actual root field and the response alias in mock operations', async () => {
const executor = createMockExecutor(schema);
const result = JSON.parse(await executor.execute('{ alias: user { name } }'));
expect(result.data.alias).toEqual({ name: 'mock_name' });
});

it('rejects mock sizes that can overrun or skip generation', () => {
expect(() => generateMockData(schema, 'User', { arrayLength: 1.5 })).toThrow(RangeError);
expect(() => createMockExecutor(schema, { arrayLength: -1 })).toThrow(RangeError);
});

it('preserves own prototype-named JSON fields when summarizing', () => {
const data = JSON.parse('{"__proto__":{"name":"kept"},"name":"other"}');
const { summary } = summarizeResponse(data);
expect(Object.getPrototypeOf(summary)).toBe(Object.prototype);
expect(Object.hasOwn(summary as object, '__proto__')).toBe(true);
expect(JSON.stringify(summary)).toBe(JSON.stringify(data));
});
6 changes: 5 additions & 1 deletion tests/pagination/handler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,11 @@ describe('executePaginated - Relay', () => {
});

const mockExecutor = {
execute: vi.fn().mockResolvedValue(pageResponse),
execute: vi
.fn()
.mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor1'))
.mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor2'))
.mockResolvedValueOnce(pageResponse.replace('cursorN', 'cursor3')),
} as unknown as GraphQLExecutor;

const operation = `query Users($first: Int, $after: String) {
Expand Down
Loading