@carlonicora/nextjs-jsonapi 1.73.0 → 1.74.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 (95) hide show
  1. package/dist/{ApiDataInterface-DPP8s46n.d.mts → ApiDataInterface-BcZeXy5X.d.mts} +1 -0
  2. package/dist/{ApiDataInterface-DPP8s46n.d.ts → ApiDataInterface-BcZeXy5X.d.ts} +1 -0
  3. package/dist/{ApiResponseInterface-CAIAeP5d.d.ts → ApiResponseInterface-CWLvSCvS.d.ts} +1 -1
  4. package/dist/{ApiResponseInterface-zeewugD7.d.mts → ApiResponseInterface-rsXRL_Hn.d.mts} +1 -1
  5. package/dist/{AuthComponent-Di8DsZ2I.d.ts → AuthComponent-Blbs06ud.d.ts} +2 -2
  6. package/dist/{AuthComponent-DXe3kPzb.d.mts → AuthComponent-huIaK5rm.d.mts} +2 -2
  7. package/dist/{BlockNoteEditor-ETTYTXDX.js → BlockNoteEditor-A37P3FA7.js} +14 -14
  8. package/dist/{BlockNoteEditor-ETTYTXDX.js.map → BlockNoteEditor-A37P3FA7.js.map} +1 -1
  9. package/dist/{BlockNoteEditor-MZ6G4XN4.mjs → BlockNoteEditor-KJZ7FGBA.mjs} +4 -4
  10. package/dist/{HowToInterface-NaqSG9sE.d.ts → HowToInterface-BKhnkzBp.d.ts} +1 -1
  11. package/dist/{HowToInterface-DtVWAE1s.d.mts → HowToInterface-Cj8OuQFf.d.mts} +1 -1
  12. package/dist/{ModulePathsInterface-49EWvbWy.d.mts → ModulePathsInterface-BrdqgteS.d.mts} +1 -1
  13. package/dist/{ModulePathsInterface-wVS5Raa4.d.ts → ModulePathsInterface-DJKs7s_s.d.ts} +1 -1
  14. package/dist/{auth.interface-C4uJzBec.d.mts → auth.interface-Bdq7-8iV.d.mts} +2 -2
  15. package/dist/{auth.interface-BTco8PWs.d.ts → auth.interface-CQJ6A2Cj.d.ts} +2 -2
  16. package/dist/billing/index.d.mts +3 -3
  17. package/dist/billing/index.d.ts +3 -3
  18. package/dist/billing/index.js +346 -346
  19. package/dist/billing/index.mjs +3 -3
  20. package/dist/{chunk-QLICTZL7.js → chunk-FKLP4NED.js} +134 -129
  21. package/dist/chunk-FKLP4NED.js.map +1 -0
  22. package/dist/{chunk-HP6AJBWE.mjs → chunk-JOJZRGZL.mjs} +2 -2
  23. package/dist/{chunk-5QTDS6V7.js → chunk-OTZEXASK.js} +11 -11
  24. package/dist/{chunk-5QTDS6V7.js.map → chunk-OTZEXASK.js.map} +1 -1
  25. package/dist/{chunk-73ANSE3J.mjs → chunk-XI35ALWY.mjs} +6 -1
  26. package/dist/chunk-XI35ALWY.mjs.map +1 -0
  27. package/dist/{chunk-OPUWDWFH.js → chunk-XUTMY6K5.js} +651 -651
  28. package/dist/{chunk-OPUWDWFH.js.map → chunk-XUTMY6K5.js.map} +1 -1
  29. package/dist/{chunk-6O3YOOQM.mjs → chunk-ZNODEBMI.mjs} +6 -6
  30. package/dist/chunk-ZNODEBMI.mjs.map +1 -0
  31. package/dist/client/index.d.mts +10 -10
  32. package/dist/client/index.d.ts +10 -10
  33. package/dist/client/index.js +4 -4
  34. package/dist/client/index.mjs +3 -3
  35. package/dist/components/index.d.mts +10 -10
  36. package/dist/components/index.d.ts +10 -10
  37. package/dist/components/index.js +4 -4
  38. package/dist/components/index.mjs +3 -3
  39. package/dist/{config-n0lfSf27.d.ts → config-B3jKt9P7.d.ts} +1 -1
  40. package/dist/{config-Bmr_0qTn.d.mts → config-DkHF61xA.d.mts} +1 -1
  41. package/dist/contexts/index.d.mts +5 -5
  42. package/dist/contexts/index.d.ts +5 -5
  43. package/dist/contexts/index.js +4 -4
  44. package/dist/contexts/index.mjs +3 -3
  45. package/dist/core/index.d.mts +19 -17
  46. package/dist/core/index.d.ts +19 -17
  47. package/dist/core/index.js +2 -2
  48. package/dist/core/index.mjs +1 -1
  49. package/dist/{feature.interface-CIWxo8NP.d.ts → feature.interface-BO25VLlx.d.ts} +1 -1
  50. package/dist/{feature.interface-BxFFOPNq.d.mts → feature.interface-CXb1-vNq.d.mts} +1 -1
  51. package/dist/index.d.mts +17 -17
  52. package/dist/index.d.ts +17 -17
  53. package/dist/index.js +3 -3
  54. package/dist/index.mjs +2 -2
  55. package/dist/{notification.interface-DrHu_1MM.d.mts → notification.interface-DG6obXUH.d.mts} +3 -2
  56. package/dist/{notification.interface-DYDZENx2.d.ts → notification.interface-DcSuc9CL.d.ts} +3 -2
  57. package/dist/{oauth.interface-vL7za9Bz.d.ts → oauth.interface-B6xmfDzK.d.ts} +1 -1
  58. package/dist/{oauth.interface-DsZ5ecSX.d.mts → oauth.interface-o5FLpiN7.d.mts} +1 -1
  59. package/dist/{s3.service-TsN2unZr.d.mts → s3.service-DGilbikH.d.mts} +4 -4
  60. package/dist/{s3.service-DK2KKXbR.d.ts → s3.service-DjwEQJPe.d.ts} +4 -4
  61. package/dist/server/index.d.mts +6 -6
  62. package/dist/server/index.d.ts +6 -6
  63. package/dist/server/index.js +3 -3
  64. package/dist/server/index.mjs +1 -1
  65. package/dist/{stripe-promotion-code.interface-BcJty0rv.d.ts → stripe-promotion-code.interface-C3qqh3mi.d.ts} +2 -2
  66. package/dist/{stripe-promotion-code.interface-Dnm2DJKQ.d.mts → stripe-promotion-code.interface-ClZ7DxS9.d.mts} +2 -2
  67. package/dist/testing/index.d.mts +2 -2
  68. package/dist/testing/index.d.ts +2 -2
  69. package/dist/testing/index.js +5 -1
  70. package/dist/testing/index.js.map +1 -1
  71. package/dist/testing/index.mjs +5 -1
  72. package/dist/testing/index.mjs.map +1 -1
  73. package/dist/{useRbacState-BYaSdA78.d.ts → useRbacState-C88O-5L8.d.ts} +3 -3
  74. package/dist/{useRbacState-CQEJ_ysV.d.mts → useRbacState-mqYiRp3J.d.mts} +3 -3
  75. package/dist/{useSocket-Cjt_qvkI.d.ts → useSocket-8eUtnL7J.d.ts} +1 -1
  76. package/dist/{useSocket-VAGetcT3.d.mts → useSocket-CmzVtg32.d.mts} +1 -1
  77. package/package.json +1 -1
  78. package/src/client/hooks/__tests__/useRehydration.test.ts +3 -0
  79. package/src/components/navigations/RecentPagesNavigator.tsx +16 -13
  80. package/src/core/abstracts/AbstractApiData.ts +10 -0
  81. package/src/core/abstracts/__tests__/identifier.spec.ts +117 -0
  82. package/src/core/factories/__tests__/JsonApiDataFactory.test.ts +3 -0
  83. package/src/core/factories/__tests__/RehydrationFactory.test.ts +3 -0
  84. package/src/core/interfaces/ApiDataInterface.ts +1 -0
  85. package/src/core/registry/__tests__/DataClassRegistry.getByJsonApiType.spec.ts +6 -0
  86. package/src/core/registry/__tests__/DataClassRegistry.test.ts +3 -0
  87. package/src/core/registry/__tests__/ModuleRegistrar.test.ts +6 -0
  88. package/src/features/rbac/hooks/useRbacState.test.ts +2 -0
  89. package/src/permissions/types.ts +1 -0
  90. package/src/testing/factories/createMockApiData.ts +7 -0
  91. package/dist/chunk-6O3YOOQM.mjs.map +0 -1
  92. package/dist/chunk-73ANSE3J.mjs.map +0 -1
  93. package/dist/chunk-QLICTZL7.js.map +0 -1
  94. /package/dist/{BlockNoteEditor-MZ6G4XN4.mjs.map → BlockNoteEditor-KJZ7FGBA.mjs.map} +0 -0
  95. /package/dist/{chunk-HP6AJBWE.mjs.map → chunk-JOJZRGZL.mjs.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/testing/index.js","../../src/testing/providers/MockJsonApiProvider.tsx","../../src/testing/factories/createMockModule.ts","../../src/testing/factories/createMockResponse.ts","../../src/testing/factories/createMockService.ts","../../src/testing/factories/createMockApiData.ts","../../src/testing/matchers/jsonApiMatchers.ts","../../src/testing/utils/renderWithProviders.tsx"],"names":[],"mappings":"AAAA;AACE;AACF,uDAA6B;AAC7B;AACE;AACF,uDAA6B;AAC7B;AACA;AC2CS,+CAAA;AAxCT,IAAM,kBAAA,EAAmC;AAAA,EACvC,MAAA,EAAQ,sBAAA;AAAA,EACR,WAAA,kBAAa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A;AACd,IAAA;AAChB,MAAA;AACgB,MAAA;AAC2B,MAAA;AAC5C,IAAA;AACH,EAAA;AACF;AAZgB;ALyEiD;AACA;AM5M1C;AAmCQ;AAAA;AAAA;AAAA;AAIe,EAAA;AACkB,IAAA;AACA,IAAA;AACN,IAAA;AAC3B,IAAA;AAEpB,IAAA;AACC,MAAA;AAGA,MAAA;AAER,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAKmE,EAAA;AACL,IAAA;AACnC,IAAA;AACG,IAAA;AAErB,IAAA;AACL,MAAA;AAGM,MAAA;AAER,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAK8F,EAAA;AAChC,IAAA;AACpB,IAAA;AACF,IAAA;AACM,IAAA;AAEX,IAAA;AAExB,MAAA;AACC,QAAA;AAGA,QAAA;AAER,MAAA;AACF,IAAA;AAEoC,IAAA;AAC7B,IAAA;AACiB,MAAA;AAEJ,MAAA;AAKpB,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAK+E,EAAA;AACjB,IAAA;AACd,IAAA;AACF,IAAA;AAErC,IAAA;AACC,MAAA;AAGA,MAAA;AAER,IAAA;AACF,EAAA;AAAA;AAAA;AAAA;AAKuE,EAAA;AAC9C,IAAA;AACW,IAAA;AACsB,IAAA;AAC1B,IAAA;AAEvB,IAAA;AACL,MAAA;AAGM,MAAA;AAER,IAAA;AACF,EAAA;AACF;AAgCwD;AACzB,EAAA;AAC/B;AAFgB;ANiHiD;AACA;AOxRb;AAmEP;AACnB;AAhBN;AAJ0F;AACtD,EAAA;AAEa,EAAA;AAC5B,IAAA;AAEd,IAAA;AACM,MAAA;AAC7B,IAAA;AAEO,IAAA;AACT,EAAA;AARS,EAAA;AAUoD,EAAA;AAC/D;AAdgB;AP0PiD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/testing/index.js","sourcesContent":[null,"\"use client\";\n\nimport React from \"react\";\nimport { JsonApiConfig, JsonApiContext } from \"../../client/context/JsonApiContext\";\n\nexport interface MockJsonApiProviderProps {\n children: React.ReactNode;\n config?: Partial<JsonApiConfig>;\n}\n\nconst defaultMockConfig: JsonApiConfig = {\n apiUrl: \"https://api.test.com\",\n tokenGetter: async () => \"mock-token-for-testing\",\n languageGetter: async () => \"en\",\n defaultHeaders: {},\n onError: () => {},\n cacheConfig: {\n defaultProfile: \"default\",\n },\n};\n\n/**\n * A test-friendly provider that wraps components with mock JSON:API context.\n *\n * @example\n * ```tsx\n * import { MockJsonApiProvider } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * render(\n * <MockJsonApiProvider>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n *\n * @example With custom config\n * ```tsx\n * render(\n * <MockJsonApiProvider config={{ apiUrl: 'https://custom.api.com' }}>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n */\nexport function MockJsonApiProvider({ children, config }: MockJsonApiProviderProps) {\n const mergedConfig: JsonApiConfig = {\n ...defaultMockConfig,\n ...config,\n };\n\n return <JsonApiContext.Provider value={mergedConfig}>{children}</JsonApiContext.Provider>;\n}\n\nexport { defaultMockConfig };\n","import { ApiRequestDataTypeInterface } from \"../../core/interfaces/ApiRequestDataTypeInterface\";\n\nexport interface CreateMockModuleOptions {\n name: string;\n cache?: string;\n inclusions?: ApiRequestDataTypeInterface[\"inclusions\"];\n}\n\n/**\n * Creates a mock module definition for testing.\n *\n * @example\n * ```ts\n * import { createMockModule } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticleModule = createMockModule({ name: 'articles' });\n * ```\n */\nexport function createMockModule(options: CreateMockModuleOptions): ApiRequestDataTypeInterface {\n // Create a mock model class\n class MockModel {\n id = \"mock-id\";\n type = options.name;\n }\n\n return {\n name: options.name,\n cache: options.cache,\n inclusions: options.inclusions,\n model: MockModel,\n };\n}\n","import { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockResponseOptions {\n data?: ApiDataInterface | ApiDataInterface[] | null;\n ok?: boolean;\n response?: number;\n error?: string;\n meta?: Record<string, any>;\n self?: string;\n next?: string;\n prev?: string;\n}\n\n/**\n * Creates a mock API response for testing.\n *\n * @example\n * ```ts\n * import { createMockResponse, createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockData = createMockApiData({ type: 'articles', id: '1' });\n * const response = createMockResponse({ data: mockData, ok: true });\n * ```\n *\n * @example With pagination\n * ```ts\n * const response = createMockResponse({\n * data: [mockData],\n * ok: true,\n * next: '/articles?page=2',\n * prev: '/articles?page=0',\n * });\n * ```\n */\nexport function createMockResponse(options: CreateMockResponseOptions = {}): ApiResponseInterface {\n const {\n data = null,\n ok = true,\n response = ok ? 200 : 500,\n error = ok ? \"\" : \"Error\",\n meta,\n self,\n next,\n prev,\n } = options;\n\n const mockResponse: ApiResponseInterface = {\n ok,\n response,\n data: data as ApiDataInterface | ApiDataInterface[],\n error,\n meta,\n self,\n next,\n prev,\n };\n\n // Add pagination methods if next/prev provided\n if (next) {\n mockResponse.nextPage = async () => createMockResponse({ ...options, next: undefined, prev: self });\n }\n\n if (prev) {\n mockResponse.prevPage = async () => createMockResponse({ ...options, prev: undefined, next: self });\n }\n\n return mockResponse;\n}\n\n/**\n * Creates a mock error response for testing error scenarios.\n *\n * @example\n * ```ts\n * import { createMockErrorResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorResponse = createMockErrorResponse(404, 'Not Found');\n * ```\n */\nexport function createMockErrorResponse(statusCode: number, errorMessage: string): ApiResponseInterface {\n return createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n data: null,\n });\n}\n","import { vi, type Mock } from \"vitest\";\nimport { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { createMockResponse } from \"./createMockResponse\";\n\nexport type MockApiMethod = Mock<(...args: any[]) => Promise<ApiResponseInterface>>;\n\nexport interface MockService {\n get: MockApiMethod;\n post: MockApiMethod;\n put: MockApiMethod;\n patch: MockApiMethod;\n delete: MockApiMethod;\n}\n\nexport interface CreateMockServiceOptions {\n defaultResponse?: ApiResponseInterface;\n}\n\n/**\n * Creates a mock service with Vitest mock functions for all HTTP methods.\n *\n * @example\n * ```ts\n * import { createMockService, createMockResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockService = createMockService();\n * mockService.get.mockResolvedValue(createMockResponse({ data: mockData }));\n *\n * // Use in test\n * expect(mockService.get).toHaveBeenCalled();\n * ```\n *\n * @example With default response\n * ```ts\n * const mockService = createMockService({\n * defaultResponse: createMockResponse({ ok: true, data: [] }),\n * });\n * ```\n */\nexport function createMockService(options: CreateMockServiceOptions = {}): MockService {\n const defaultResponse = options.defaultResponse ?? createMockResponse({ ok: true });\n\n return {\n get: vi.fn().mockResolvedValue(defaultResponse),\n post: vi.fn().mockResolvedValue(defaultResponse),\n put: vi.fn().mockResolvedValue(defaultResponse),\n patch: vi.fn().mockResolvedValue(defaultResponse),\n delete: vi.fn().mockResolvedValue(defaultResponse),\n };\n}\n\n/**\n * Creates a mock service that returns errors for all methods.\n *\n * @example\n * ```ts\n * import { createMockErrorService } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorService = createMockErrorService(500, 'Internal Server Error');\n * ```\n */\nexport function createMockErrorService(statusCode: number = 500, errorMessage: string = \"Error\"): MockService {\n const errorResponse = createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n });\n\n return {\n get: vi.fn().mockResolvedValue(errorResponse),\n post: vi.fn().mockResolvedValue(errorResponse),\n put: vi.fn().mockResolvedValue(errorResponse),\n patch: vi.fn().mockResolvedValue(errorResponse),\n delete: vi.fn().mockResolvedValue(errorResponse),\n };\n}\n","import { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockApiDataOptions {\n type: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n included?: any[];\n createdAt?: Date;\n updatedAt?: Date;\n self?: string;\n}\n\n/**\n * Creates a mock ApiDataInterface object for testing.\n *\n * @example\n * ```ts\n * import { createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test Article', body: 'Content here' },\n * });\n * ```\n *\n * @example With relationships\n * ```ts\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test' },\n * relationships: {\n * author: { data: { type: 'users', id: '42' } },\n * },\n * });\n * ```\n */\nexport function createMockApiData(options: CreateMockApiDataOptions): ApiDataInterface {\n const {\n type,\n id = `mock-${type}-${Math.random().toString(36).substring(7)}`,\n attributes = {},\n relationships = {},\n included = [],\n createdAt = new Date(),\n updatedAt = new Date(),\n self,\n } = options;\n\n const jsonApiData = {\n type,\n id,\n attributes: {\n ...attributes,\n createdAt: createdAt.toISOString(),\n updatedAt: updatedAt.toISOString(),\n },\n relationships,\n };\n\n const mockData: ApiDataInterface = {\n get included() {\n return included;\n },\n get type() {\n return type;\n },\n get id() {\n return id;\n },\n get createdAt() {\n return createdAt;\n },\n get updatedAt() {\n return updatedAt;\n },\n get self() {\n return self;\n },\n get jsonApi() {\n return jsonApiData;\n },\n generateApiUrl: (params?: any) => {\n const baseUrl = `/${type}/${id}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n return `${baseUrl}?${searchParams.toString()}`;\n }\n return baseUrl;\n },\n dehydrate: () => ({\n jsonApi: jsonApiData,\n included,\n allData: [jsonApiData],\n }),\n rehydrate: function (_data: any) {\n return this;\n },\n createJsonApi: (data: any) => ({\n type,\n id,\n attributes: data,\n }),\n };\n\n // Add attribute accessors to the mock object\n Object.keys(attributes).forEach((key) => {\n Object.defineProperty(mockData, key, {\n get: () => attributes[key],\n enumerable: true,\n });\n });\n\n return mockData;\n}\n\n/**\n * Creates an array of mock ApiDataInterface objects.\n *\n * @example\n * ```ts\n * import { createMockApiDataList } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticles = createMockApiDataList('articles', 5, (index) => ({\n * title: `Article ${index + 1}`,\n * }));\n * ```\n */\nexport function createMockApiDataList(\n type: string,\n count: number,\n attributesFactory?: (index: number) => Record<string, any>,\n): ApiDataInterface[] {\n return Array.from({ length: count }, (_, index) =>\n createMockApiData({\n type,\n id: `${index + 1}`,\n attributes: attributesFactory?.(index) ?? {},\n }),\n );\n}\n","import { expect } from \"vitest\";\n\ninterface JsonApiResponse {\n data?:\n | {\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }\n | Array<{\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }>;\n}\n\n/**\n * Custom Vitest matchers for JSON:API assertions.\n *\n * @example\n * ```ts\n * import { jsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n * import { expect } from 'vitest';\n *\n * expect.extend(jsonApiMatchers);\n *\n * // Then use in tests:\n * expect(response).toBeValidJsonApi();\n * expect(response).toHaveJsonApiType('articles');\n * expect(response).toHaveJsonApiAttribute('title', 'My Article');\n * expect(response).toHaveJsonApiRelationship('author');\n * ```\n */\nexport const jsonApiMatchers = {\n /**\n * Asserts that the response has a valid JSON:API structure with type and id.\n */\n toBeValidJsonApi(received: JsonApiResponse) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const hasType = typeof data?.type === \"string\" && data.type.length > 0;\n const hasId = typeof data?.id === \"string\" && data.id.length > 0;\n const isValid = hasType && hasId;\n\n return {\n pass: isValid,\n message: () =>\n isValid\n ? `Expected response not to be valid JSON:API, but it has type \"${data?.type}\" and id \"${data?.id}\"`\n : `Expected response to be valid JSON:API with type and id, but got type: ${JSON.stringify(data?.type)}, id: ${JSON.stringify(data?.id)}`,\n };\n },\n\n /**\n * Asserts that the response data has the expected JSON:API type.\n */\n toHaveJsonApiType(received: JsonApiResponse, expectedType: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const actualType = data?.type;\n const pass = actualType === expectedType;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have JSON:API type \"${expectedType}\"`\n : `Expected response to have JSON:API type \"${expectedType}\", but got \"${actualType}\"`,\n };\n },\n\n /**\n * Asserts that the response data has an attribute with the expected value.\n */\n toHaveJsonApiAttribute(received: JsonApiResponse, attributeName: string, expectedValue?: any) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const attributes = data?.attributes ?? {};\n const hasAttribute = attributeName in attributes;\n const actualValue = attributes[attributeName];\n\n if (expectedValue === undefined) {\n // Just check existence\n return {\n pass: hasAttribute,\n message: () =>\n hasAttribute\n ? `Expected response not to have JSON:API attribute \"${attributeName}\"`\n : `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found. Available attributes: ${Object.keys(attributes).join(\", \") || \"none\"}`,\n };\n }\n\n const valuesMatch = actualValue === expectedValue;\n return {\n pass: hasAttribute && valuesMatch,\n message: () =>\n hasAttribute && valuesMatch\n ? `Expected response not to have JSON:API attribute \"${attributeName}\" with value \"${expectedValue}\"`\n : !hasAttribute\n ? `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found`\n : `Expected JSON:API attribute \"${attributeName}\" to be \"${expectedValue}\", but got \"${actualValue}\"`,\n };\n },\n\n /**\n * Asserts that the response data has the specified relationship.\n */\n toHaveJsonApiRelationship(received: JsonApiResponse, relationshipName: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const relationships = data?.relationships ?? {};\n const hasRelationship = relationshipName in relationships;\n\n return {\n pass: hasRelationship,\n message: () =>\n hasRelationship\n ? `Expected response not to have JSON:API relationship \"${relationshipName}\"`\n : `Expected response to have JSON:API relationship \"${relationshipName}\", but it was not found. Available relationships: ${Object.keys(relationships).join(\", \") || \"none\"}`,\n };\n },\n\n /**\n * Asserts that the response data array has the expected length.\n */\n toHaveJsonApiLength(received: JsonApiResponse, expectedLength: number) {\n const data = received?.data;\n const isArray = Array.isArray(data);\n const actualLength = isArray ? data.length : data ? 1 : 0;\n const pass = actualLength === expectedLength;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have ${expectedLength} items`\n : `Expected response to have ${expectedLength} items, but got ${actualLength}`,\n };\n },\n};\n\n// Type declarations for the custom matchers\ndeclare module \"vitest\" {\n interface Assertion<T = any> {\n toBeValidJsonApi(): T;\n toHaveJsonApiType(expectedType: string): T;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): T;\n toHaveJsonApiRelationship(relationshipName: string): T;\n toHaveJsonApiLength(expectedLength: number): T;\n }\n interface AsymmetricMatchersContaining {\n toBeValidJsonApi(): any;\n toHaveJsonApiType(expectedType: string): any;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): any;\n toHaveJsonApiRelationship(relationshipName: string): any;\n toHaveJsonApiLength(expectedLength: number): any;\n }\n}\n\n/**\n * Extends Vitest's expect with JSON:API matchers.\n * Call this in your test setup file.\n *\n * @example\n * ```ts\n * // vitest.setup.ts\n * import { extendExpectWithJsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * extendExpectWithJsonApiMatchers();\n * ```\n */\nexport function extendExpectWithJsonApiMatchers(): void {\n expect.extend(jsonApiMatchers);\n}\n","\"use client\";\n\nimport React, { ReactElement } from \"react\";\nimport { render, RenderOptions, RenderResult } from \"@testing-library/react\";\nimport {\n MockJsonApiProvider,\n MockJsonApiProviderProps as _MockJsonApiProviderProps,\n} from \"../providers/MockJsonApiProvider\";\nimport { JsonApiConfig } from \"../../client/context/JsonApiContext\";\n\nexport interface RenderWithProvidersOptions extends Omit<RenderOptions, \"wrapper\"> {\n /**\n * Custom JSON:API configuration to pass to the mock provider.\n */\n jsonApiConfig?: Partial<JsonApiConfig>;\n\n /**\n * Additional wrapper component to wrap around the providers.\n */\n wrapper?: React.ComponentType<{ children: React.ReactNode }>;\n}\n\n/**\n * Renders a component wrapped with all necessary providers for testing.\n *\n * @example\n * ```tsx\n * import { renderWithProviders } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const { getByText } = renderWithProviders(<MyComponent />);\n * expect(getByText('Hello')).toBeInTheDocument();\n * ```\n *\n * @example With custom config\n * ```tsx\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * jsonApiConfig: { apiUrl: 'https://custom.api.com' },\n * });\n * ```\n *\n * @example With additional wrapper\n * ```tsx\n * const CustomWrapper = ({ children }) => (\n * <ThemeProvider>{children}</ThemeProvider>\n * );\n *\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * wrapper: CustomWrapper,\n * });\n * ```\n */\nexport function renderWithProviders(ui: ReactElement, options: RenderWithProvidersOptions = {}): RenderResult {\n const { jsonApiConfig, wrapper: AdditionalWrapper, ...renderOptions } = options;\n\n function AllProviders({ children }: { children: React.ReactNode }) {\n const content = <MockJsonApiProvider config={jsonApiConfig}>{children}</MockJsonApiProvider>;\n\n if (AdditionalWrapper) {\n return <AdditionalWrapper>{content}</AdditionalWrapper>;\n }\n\n return content;\n }\n\n return render(ui, { wrapper: AllProviders, ...renderOptions });\n}\n\n/**\n * Re-export render utilities from Testing Library for convenience.\n */\nexport { render, screen, waitFor, fireEvent, within } from \"@testing-library/react\";\nexport { userEvent } from \"@testing-library/user-event\";\n"]}
1
+ {"version":3,"sources":["/home/runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/testing/index.js","../../src/testing/providers/MockJsonApiProvider.tsx","../../src/testing/factories/createMockModule.ts","../../src/testing/factories/createMockResponse.ts","../../src/testing/factories/createMockService.ts","../../src/testing/factories/createMockApiData.ts","../../src/testing/matchers/jsonApiMatchers.ts","../../src/testing/utils/renderWithProviders.tsx"],"names":[],"mappings":"AAAA;AACE;AACF,uDAA6B;AAC7B;AACE;AACF,uDAA6B;AAC7B;AACA;AC2CS,+CAAA;AAxCT,IAAM,kBAAA,EAAmC;AAAA,EACvC,MAAA,EAAQ,sBAAA;AAAA,EACR,WAAA,kBAAa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runner/work/nextjs-jsonapi/nextjs-jsonapi/dist/testing/index.js","sourcesContent":[null,"\"use client\";\n\nimport React from \"react\";\nimport { JsonApiConfig, JsonApiContext } from \"../../client/context/JsonApiContext\";\n\nexport interface MockJsonApiProviderProps {\n children: React.ReactNode;\n config?: Partial<JsonApiConfig>;\n}\n\nconst defaultMockConfig: JsonApiConfig = {\n apiUrl: \"https://api.test.com\",\n tokenGetter: async () => \"mock-token-for-testing\",\n languageGetter: async () => \"en\",\n defaultHeaders: {},\n onError: () => {},\n cacheConfig: {\n defaultProfile: \"default\",\n },\n};\n\n/**\n * A test-friendly provider that wraps components with mock JSON:API context.\n *\n * @example\n * ```tsx\n * import { MockJsonApiProvider } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * render(\n * <MockJsonApiProvider>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n *\n * @example With custom config\n * ```tsx\n * render(\n * <MockJsonApiProvider config={{ apiUrl: 'https://custom.api.com' }}>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n */\nexport function MockJsonApiProvider({ children, config }: MockJsonApiProviderProps) {\n const mergedConfig: JsonApiConfig = {\n ...defaultMockConfig,\n ...config,\n };\n\n return <JsonApiContext.Provider value={mergedConfig}>{children}</JsonApiContext.Provider>;\n}\n\nexport { defaultMockConfig };\n","import { ApiRequestDataTypeInterface } from \"../../core/interfaces/ApiRequestDataTypeInterface\";\n\nexport interface CreateMockModuleOptions {\n name: string;\n cache?: string;\n inclusions?: ApiRequestDataTypeInterface[\"inclusions\"];\n}\n\n/**\n * Creates a mock module definition for testing.\n *\n * @example\n * ```ts\n * import { createMockModule } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticleModule = createMockModule({ name: 'articles' });\n * ```\n */\nexport function createMockModule(options: CreateMockModuleOptions): ApiRequestDataTypeInterface {\n // Create a mock model class\n class MockModel {\n id = \"mock-id\";\n type = options.name;\n }\n\n return {\n name: options.name,\n cache: options.cache,\n inclusions: options.inclusions,\n model: MockModel,\n };\n}\n","import { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockResponseOptions {\n data?: ApiDataInterface | ApiDataInterface[] | null;\n ok?: boolean;\n response?: number;\n error?: string;\n meta?: Record<string, any>;\n self?: string;\n next?: string;\n prev?: string;\n}\n\n/**\n * Creates a mock API response for testing.\n *\n * @example\n * ```ts\n * import { createMockResponse, createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockData = createMockApiData({ type: 'articles', id: '1' });\n * const response = createMockResponse({ data: mockData, ok: true });\n * ```\n *\n * @example With pagination\n * ```ts\n * const response = createMockResponse({\n * data: [mockData],\n * ok: true,\n * next: '/articles?page=2',\n * prev: '/articles?page=0',\n * });\n * ```\n */\nexport function createMockResponse(options: CreateMockResponseOptions = {}): ApiResponseInterface {\n const {\n data = null,\n ok = true,\n response = ok ? 200 : 500,\n error = ok ? \"\" : \"Error\",\n meta,\n self,\n next,\n prev,\n } = options;\n\n const mockResponse: ApiResponseInterface = {\n ok,\n response,\n data: data as ApiDataInterface | ApiDataInterface[],\n error,\n meta,\n self,\n next,\n prev,\n };\n\n // Add pagination methods if next/prev provided\n if (next) {\n mockResponse.nextPage = async () => createMockResponse({ ...options, next: undefined, prev: self });\n }\n\n if (prev) {\n mockResponse.prevPage = async () => createMockResponse({ ...options, prev: undefined, next: self });\n }\n\n return mockResponse;\n}\n\n/**\n * Creates a mock error response for testing error scenarios.\n *\n * @example\n * ```ts\n * import { createMockErrorResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorResponse = createMockErrorResponse(404, 'Not Found');\n * ```\n */\nexport function createMockErrorResponse(statusCode: number, errorMessage: string): ApiResponseInterface {\n return createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n data: null,\n });\n}\n","import { vi, type Mock } from \"vitest\";\nimport { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { createMockResponse } from \"./createMockResponse\";\n\nexport type MockApiMethod = Mock<(...args: any[]) => Promise<ApiResponseInterface>>;\n\nexport interface MockService {\n get: MockApiMethod;\n post: MockApiMethod;\n put: MockApiMethod;\n patch: MockApiMethod;\n delete: MockApiMethod;\n}\n\nexport interface CreateMockServiceOptions {\n defaultResponse?: ApiResponseInterface;\n}\n\n/**\n * Creates a mock service with Vitest mock functions for all HTTP methods.\n *\n * @example\n * ```ts\n * import { createMockService, createMockResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockService = createMockService();\n * mockService.get.mockResolvedValue(createMockResponse({ data: mockData }));\n *\n * // Use in test\n * expect(mockService.get).toHaveBeenCalled();\n * ```\n *\n * @example With default response\n * ```ts\n * const mockService = createMockService({\n * defaultResponse: createMockResponse({ ok: true, data: [] }),\n * });\n * ```\n */\nexport function createMockService(options: CreateMockServiceOptions = {}): MockService {\n const defaultResponse = options.defaultResponse ?? createMockResponse({ ok: true });\n\n return {\n get: vi.fn().mockResolvedValue(defaultResponse),\n post: vi.fn().mockResolvedValue(defaultResponse),\n put: vi.fn().mockResolvedValue(defaultResponse),\n patch: vi.fn().mockResolvedValue(defaultResponse),\n delete: vi.fn().mockResolvedValue(defaultResponse),\n };\n}\n\n/**\n * Creates a mock service that returns errors for all methods.\n *\n * @example\n * ```ts\n * import { createMockErrorService } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorService = createMockErrorService(500, 'Internal Server Error');\n * ```\n */\nexport function createMockErrorService(statusCode: number = 500, errorMessage: string = \"Error\"): MockService {\n const errorResponse = createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n });\n\n return {\n get: vi.fn().mockResolvedValue(errorResponse),\n post: vi.fn().mockResolvedValue(errorResponse),\n put: vi.fn().mockResolvedValue(errorResponse),\n patch: vi.fn().mockResolvedValue(errorResponse),\n delete: vi.fn().mockResolvedValue(errorResponse),\n };\n}\n","import { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockApiDataOptions {\n type: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n included?: any[];\n createdAt?: Date;\n updatedAt?: Date;\n self?: string;\n}\n\n/**\n * Creates a mock ApiDataInterface object for testing.\n *\n * @example\n * ```ts\n * import { createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test Article', body: 'Content here' },\n * });\n * ```\n *\n * @example With relationships\n * ```ts\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test' },\n * relationships: {\n * author: { data: { type: 'users', id: '42' } },\n * },\n * });\n * ```\n */\nexport function createMockApiData(options: CreateMockApiDataOptions): ApiDataInterface {\n const {\n type,\n id = `mock-${type}-${Math.random().toString(36).substring(7)}`,\n attributes = {},\n relationships = {},\n included = [],\n createdAt = new Date(),\n updatedAt = new Date(),\n self,\n } = options;\n\n const jsonApiData = {\n type,\n id,\n attributes: {\n ...attributes,\n createdAt: createdAt.toISOString(),\n updatedAt: updatedAt.toISOString(),\n },\n relationships,\n };\n\n const mockData: ApiDataInterface = {\n get included() {\n return included;\n },\n get type() {\n return type;\n },\n get id() {\n return id;\n },\n get createdAt() {\n return createdAt;\n },\n get updatedAt() {\n return updatedAt;\n },\n get self() {\n return self;\n },\n get jsonApi() {\n return jsonApiData;\n },\n generateApiUrl: (params?: any) => {\n const baseUrl = `/${type}/${id}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n return `${baseUrl}?${searchParams.toString()}`;\n }\n return baseUrl;\n },\n dehydrate: () => ({\n jsonApi: jsonApiData,\n included,\n allData: [jsonApiData],\n }),\n rehydrate: function (_data: any) {\n return this;\n },\n createJsonApi: (data: any) => ({\n type,\n id,\n attributes: data,\n }),\n get identifier() {\n const identifierFields = [\"name\"];\n return identifierFields\n .map((field) => attributes[field])\n .filter((v) => v != null && v !== \"\")\n .join(\" \");\n },\n };\n\n // Add attribute accessors to the mock object\n Object.keys(attributes).forEach((key) => {\n Object.defineProperty(mockData, key, {\n get: () => attributes[key],\n enumerable: true,\n });\n });\n\n return mockData;\n}\n\n/**\n * Creates an array of mock ApiDataInterface objects.\n *\n * @example\n * ```ts\n * import { createMockApiDataList } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticles = createMockApiDataList('articles', 5, (index) => ({\n * title: `Article ${index + 1}`,\n * }));\n * ```\n */\nexport function createMockApiDataList(\n type: string,\n count: number,\n attributesFactory?: (index: number) => Record<string, any>,\n): ApiDataInterface[] {\n return Array.from({ length: count }, (_, index) =>\n createMockApiData({\n type,\n id: `${index + 1}`,\n attributes: attributesFactory?.(index) ?? {},\n }),\n );\n}\n","import { expect } from \"vitest\";\n\ninterface JsonApiResponse {\n data?:\n | {\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }\n | Array<{\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }>;\n}\n\n/**\n * Custom Vitest matchers for JSON:API assertions.\n *\n * @example\n * ```ts\n * import { jsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n * import { expect } from 'vitest';\n *\n * expect.extend(jsonApiMatchers);\n *\n * // Then use in tests:\n * expect(response).toBeValidJsonApi();\n * expect(response).toHaveJsonApiType('articles');\n * expect(response).toHaveJsonApiAttribute('title', 'My Article');\n * expect(response).toHaveJsonApiRelationship('author');\n * ```\n */\nexport const jsonApiMatchers = {\n /**\n * Asserts that the response has a valid JSON:API structure with type and id.\n */\n toBeValidJsonApi(received: JsonApiResponse) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const hasType = typeof data?.type === \"string\" && data.type.length > 0;\n const hasId = typeof data?.id === \"string\" && data.id.length > 0;\n const isValid = hasType && hasId;\n\n return {\n pass: isValid,\n message: () =>\n isValid\n ? `Expected response not to be valid JSON:API, but it has type \"${data?.type}\" and id \"${data?.id}\"`\n : `Expected response to be valid JSON:API with type and id, but got type: ${JSON.stringify(data?.type)}, id: ${JSON.stringify(data?.id)}`,\n };\n },\n\n /**\n * Asserts that the response data has the expected JSON:API type.\n */\n toHaveJsonApiType(received: JsonApiResponse, expectedType: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const actualType = data?.type;\n const pass = actualType === expectedType;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have JSON:API type \"${expectedType}\"`\n : `Expected response to have JSON:API type \"${expectedType}\", but got \"${actualType}\"`,\n };\n },\n\n /**\n * Asserts that the response data has an attribute with the expected value.\n */\n toHaveJsonApiAttribute(received: JsonApiResponse, attributeName: string, expectedValue?: any) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const attributes = data?.attributes ?? {};\n const hasAttribute = attributeName in attributes;\n const actualValue = attributes[attributeName];\n\n if (expectedValue === undefined) {\n // Just check existence\n return {\n pass: hasAttribute,\n message: () =>\n hasAttribute\n ? `Expected response not to have JSON:API attribute \"${attributeName}\"`\n : `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found. Available attributes: ${Object.keys(attributes).join(\", \") || \"none\"}`,\n };\n }\n\n const valuesMatch = actualValue === expectedValue;\n return {\n pass: hasAttribute && valuesMatch,\n message: () =>\n hasAttribute && valuesMatch\n ? `Expected response not to have JSON:API attribute \"${attributeName}\" with value \"${expectedValue}\"`\n : !hasAttribute\n ? `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found`\n : `Expected JSON:API attribute \"${attributeName}\" to be \"${expectedValue}\", but got \"${actualValue}\"`,\n };\n },\n\n /**\n * Asserts that the response data has the specified relationship.\n */\n toHaveJsonApiRelationship(received: JsonApiResponse, relationshipName: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const relationships = data?.relationships ?? {};\n const hasRelationship = relationshipName in relationships;\n\n return {\n pass: hasRelationship,\n message: () =>\n hasRelationship\n ? `Expected response not to have JSON:API relationship \"${relationshipName}\"`\n : `Expected response to have JSON:API relationship \"${relationshipName}\", but it was not found. Available relationships: ${Object.keys(relationships).join(\", \") || \"none\"}`,\n };\n },\n\n /**\n * Asserts that the response data array has the expected length.\n */\n toHaveJsonApiLength(received: JsonApiResponse, expectedLength: number) {\n const data = received?.data;\n const isArray = Array.isArray(data);\n const actualLength = isArray ? data.length : data ? 1 : 0;\n const pass = actualLength === expectedLength;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have ${expectedLength} items`\n : `Expected response to have ${expectedLength} items, but got ${actualLength}`,\n };\n },\n};\n\n// Type declarations for the custom matchers\ndeclare module \"vitest\" {\n interface Assertion<T = any> {\n toBeValidJsonApi(): T;\n toHaveJsonApiType(expectedType: string): T;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): T;\n toHaveJsonApiRelationship(relationshipName: string): T;\n toHaveJsonApiLength(expectedLength: number): T;\n }\n interface AsymmetricMatchersContaining {\n toBeValidJsonApi(): any;\n toHaveJsonApiType(expectedType: string): any;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): any;\n toHaveJsonApiRelationship(relationshipName: string): any;\n toHaveJsonApiLength(expectedLength: number): any;\n }\n}\n\n/**\n * Extends Vitest's expect with JSON:API matchers.\n * Call this in your test setup file.\n *\n * @example\n * ```ts\n * // vitest.setup.ts\n * import { extendExpectWithJsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * extendExpectWithJsonApiMatchers();\n * ```\n */\nexport function extendExpectWithJsonApiMatchers(): void {\n expect.extend(jsonApiMatchers);\n}\n","\"use client\";\n\nimport React, { ReactElement } from \"react\";\nimport { render, RenderOptions, RenderResult } from \"@testing-library/react\";\nimport {\n MockJsonApiProvider,\n MockJsonApiProviderProps as _MockJsonApiProviderProps,\n} from \"../providers/MockJsonApiProvider\";\nimport { JsonApiConfig } from \"../../client/context/JsonApiContext\";\n\nexport interface RenderWithProvidersOptions extends Omit<RenderOptions, \"wrapper\"> {\n /**\n * Custom JSON:API configuration to pass to the mock provider.\n */\n jsonApiConfig?: Partial<JsonApiConfig>;\n\n /**\n * Additional wrapper component to wrap around the providers.\n */\n wrapper?: React.ComponentType<{ children: React.ReactNode }>;\n}\n\n/**\n * Renders a component wrapped with all necessary providers for testing.\n *\n * @example\n * ```tsx\n * import { renderWithProviders } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const { getByText } = renderWithProviders(<MyComponent />);\n * expect(getByText('Hello')).toBeInTheDocument();\n * ```\n *\n * @example With custom config\n * ```tsx\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * jsonApiConfig: { apiUrl: 'https://custom.api.com' },\n * });\n * ```\n *\n * @example With additional wrapper\n * ```tsx\n * const CustomWrapper = ({ children }) => (\n * <ThemeProvider>{children}</ThemeProvider>\n * );\n *\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * wrapper: CustomWrapper,\n * });\n * ```\n */\nexport function renderWithProviders(ui: ReactElement, options: RenderWithProvidersOptions = {}): RenderResult {\n const { jsonApiConfig, wrapper: AdditionalWrapper, ...renderOptions } = options;\n\n function AllProviders({ children }: { children: React.ReactNode }) {\n const content = <MockJsonApiProvider config={jsonApiConfig}>{children}</MockJsonApiProvider>;\n\n if (AdditionalWrapper) {\n return <AdditionalWrapper>{content}</AdditionalWrapper>;\n }\n\n return content;\n }\n\n return render(ui, { wrapper: AllProviders, ...renderOptions });\n}\n\n/**\n * Re-export render utilities from Testing Library for convenience.\n */\nexport { render, screen, waitFor, fireEvent, within } from \"@testing-library/react\";\nexport { userEvent } from \"@testing-library/user-event\";\n"]}
@@ -180,7 +180,11 @@ function createMockApiData(options) {
180
180
  type,
181
181
  id,
182
182
  attributes: data
183
- }), "createJsonApi")
183
+ }), "createJsonApi"),
184
+ get identifier() {
185
+ const identifierFields = ["name"];
186
+ return identifierFields.map((field) => attributes[field]).filter((v) => v != null && v !== "").join(" ");
187
+ }
184
188
  };
185
189
  Object.keys(attributes).forEach((key) => {
186
190
  Object.defineProperty(mockData, key, {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/testing/providers/MockJsonApiProvider.tsx","../../src/testing/factories/createMockModule.ts","../../src/testing/factories/createMockResponse.ts","../../src/testing/factories/createMockService.ts","../../src/testing/factories/createMockApiData.ts","../../src/testing/matchers/jsonApiMatchers.ts","../../src/testing/utils/renderWithProviders.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\nimport { JsonApiConfig, JsonApiContext } from \"../../client/context/JsonApiContext\";\n\nexport interface MockJsonApiProviderProps {\n children: React.ReactNode;\n config?: Partial<JsonApiConfig>;\n}\n\nconst defaultMockConfig: JsonApiConfig = {\n apiUrl: \"https://api.test.com\",\n tokenGetter: async () => \"mock-token-for-testing\",\n languageGetter: async () => \"en\",\n defaultHeaders: {},\n onError: () => {},\n cacheConfig: {\n defaultProfile: \"default\",\n },\n};\n\n/**\n * A test-friendly provider that wraps components with mock JSON:API context.\n *\n * @example\n * ```tsx\n * import { MockJsonApiProvider } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * render(\n * <MockJsonApiProvider>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n *\n * @example With custom config\n * ```tsx\n * render(\n * <MockJsonApiProvider config={{ apiUrl: 'https://custom.api.com' }}>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n */\nexport function MockJsonApiProvider({ children, config }: MockJsonApiProviderProps) {\n const mergedConfig: JsonApiConfig = {\n ...defaultMockConfig,\n ...config,\n };\n\n return <JsonApiContext.Provider value={mergedConfig}>{children}</JsonApiContext.Provider>;\n}\n\nexport { defaultMockConfig };\n","import { ApiRequestDataTypeInterface } from \"../../core/interfaces/ApiRequestDataTypeInterface\";\n\nexport interface CreateMockModuleOptions {\n name: string;\n cache?: string;\n inclusions?: ApiRequestDataTypeInterface[\"inclusions\"];\n}\n\n/**\n * Creates a mock module definition for testing.\n *\n * @example\n * ```ts\n * import { createMockModule } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticleModule = createMockModule({ name: 'articles' });\n * ```\n */\nexport function createMockModule(options: CreateMockModuleOptions): ApiRequestDataTypeInterface {\n // Create a mock model class\n class MockModel {\n id = \"mock-id\";\n type = options.name;\n }\n\n return {\n name: options.name,\n cache: options.cache,\n inclusions: options.inclusions,\n model: MockModel,\n };\n}\n","import { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockResponseOptions {\n data?: ApiDataInterface | ApiDataInterface[] | null;\n ok?: boolean;\n response?: number;\n error?: string;\n meta?: Record<string, any>;\n self?: string;\n next?: string;\n prev?: string;\n}\n\n/**\n * Creates a mock API response for testing.\n *\n * @example\n * ```ts\n * import { createMockResponse, createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockData = createMockApiData({ type: 'articles', id: '1' });\n * const response = createMockResponse({ data: mockData, ok: true });\n * ```\n *\n * @example With pagination\n * ```ts\n * const response = createMockResponse({\n * data: [mockData],\n * ok: true,\n * next: '/articles?page=2',\n * prev: '/articles?page=0',\n * });\n * ```\n */\nexport function createMockResponse(options: CreateMockResponseOptions = {}): ApiResponseInterface {\n const {\n data = null,\n ok = true,\n response = ok ? 200 : 500,\n error = ok ? \"\" : \"Error\",\n meta,\n self,\n next,\n prev,\n } = options;\n\n const mockResponse: ApiResponseInterface = {\n ok,\n response,\n data: data as ApiDataInterface | ApiDataInterface[],\n error,\n meta,\n self,\n next,\n prev,\n };\n\n // Add pagination methods if next/prev provided\n if (next) {\n mockResponse.nextPage = async () => createMockResponse({ ...options, next: undefined, prev: self });\n }\n\n if (prev) {\n mockResponse.prevPage = async () => createMockResponse({ ...options, prev: undefined, next: self });\n }\n\n return mockResponse;\n}\n\n/**\n * Creates a mock error response for testing error scenarios.\n *\n * @example\n * ```ts\n * import { createMockErrorResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorResponse = createMockErrorResponse(404, 'Not Found');\n * ```\n */\nexport function createMockErrorResponse(statusCode: number, errorMessage: string): ApiResponseInterface {\n return createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n data: null,\n });\n}\n","import { vi, type Mock } from \"vitest\";\nimport { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { createMockResponse } from \"./createMockResponse\";\n\nexport type MockApiMethod = Mock<(...args: any[]) => Promise<ApiResponseInterface>>;\n\nexport interface MockService {\n get: MockApiMethod;\n post: MockApiMethod;\n put: MockApiMethod;\n patch: MockApiMethod;\n delete: MockApiMethod;\n}\n\nexport interface CreateMockServiceOptions {\n defaultResponse?: ApiResponseInterface;\n}\n\n/**\n * Creates a mock service with Vitest mock functions for all HTTP methods.\n *\n * @example\n * ```ts\n * import { createMockService, createMockResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockService = createMockService();\n * mockService.get.mockResolvedValue(createMockResponse({ data: mockData }));\n *\n * // Use in test\n * expect(mockService.get).toHaveBeenCalled();\n * ```\n *\n * @example With default response\n * ```ts\n * const mockService = createMockService({\n * defaultResponse: createMockResponse({ ok: true, data: [] }),\n * });\n * ```\n */\nexport function createMockService(options: CreateMockServiceOptions = {}): MockService {\n const defaultResponse = options.defaultResponse ?? createMockResponse({ ok: true });\n\n return {\n get: vi.fn().mockResolvedValue(defaultResponse),\n post: vi.fn().mockResolvedValue(defaultResponse),\n put: vi.fn().mockResolvedValue(defaultResponse),\n patch: vi.fn().mockResolvedValue(defaultResponse),\n delete: vi.fn().mockResolvedValue(defaultResponse),\n };\n}\n\n/**\n * Creates a mock service that returns errors for all methods.\n *\n * @example\n * ```ts\n * import { createMockErrorService } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorService = createMockErrorService(500, 'Internal Server Error');\n * ```\n */\nexport function createMockErrorService(statusCode: number = 500, errorMessage: string = \"Error\"): MockService {\n const errorResponse = createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n });\n\n return {\n get: vi.fn().mockResolvedValue(errorResponse),\n post: vi.fn().mockResolvedValue(errorResponse),\n put: vi.fn().mockResolvedValue(errorResponse),\n patch: vi.fn().mockResolvedValue(errorResponse),\n delete: vi.fn().mockResolvedValue(errorResponse),\n };\n}\n","import { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockApiDataOptions {\n type: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n included?: any[];\n createdAt?: Date;\n updatedAt?: Date;\n self?: string;\n}\n\n/**\n * Creates a mock ApiDataInterface object for testing.\n *\n * @example\n * ```ts\n * import { createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test Article', body: 'Content here' },\n * });\n * ```\n *\n * @example With relationships\n * ```ts\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test' },\n * relationships: {\n * author: { data: { type: 'users', id: '42' } },\n * },\n * });\n * ```\n */\nexport function createMockApiData(options: CreateMockApiDataOptions): ApiDataInterface {\n const {\n type,\n id = `mock-${type}-${Math.random().toString(36).substring(7)}`,\n attributes = {},\n relationships = {},\n included = [],\n createdAt = new Date(),\n updatedAt = new Date(),\n self,\n } = options;\n\n const jsonApiData = {\n type,\n id,\n attributes: {\n ...attributes,\n createdAt: createdAt.toISOString(),\n updatedAt: updatedAt.toISOString(),\n },\n relationships,\n };\n\n const mockData: ApiDataInterface = {\n get included() {\n return included;\n },\n get type() {\n return type;\n },\n get id() {\n return id;\n },\n get createdAt() {\n return createdAt;\n },\n get updatedAt() {\n return updatedAt;\n },\n get self() {\n return self;\n },\n get jsonApi() {\n return jsonApiData;\n },\n generateApiUrl: (params?: any) => {\n const baseUrl = `/${type}/${id}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n return `${baseUrl}?${searchParams.toString()}`;\n }\n return baseUrl;\n },\n dehydrate: () => ({\n jsonApi: jsonApiData,\n included,\n allData: [jsonApiData],\n }),\n rehydrate: function (_data: any) {\n return this;\n },\n createJsonApi: (data: any) => ({\n type,\n id,\n attributes: data,\n }),\n };\n\n // Add attribute accessors to the mock object\n Object.keys(attributes).forEach((key) => {\n Object.defineProperty(mockData, key, {\n get: () => attributes[key],\n enumerable: true,\n });\n });\n\n return mockData;\n}\n\n/**\n * Creates an array of mock ApiDataInterface objects.\n *\n * @example\n * ```ts\n * import { createMockApiDataList } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticles = createMockApiDataList('articles', 5, (index) => ({\n * title: `Article ${index + 1}`,\n * }));\n * ```\n */\nexport function createMockApiDataList(\n type: string,\n count: number,\n attributesFactory?: (index: number) => Record<string, any>,\n): ApiDataInterface[] {\n return Array.from({ length: count }, (_, index) =>\n createMockApiData({\n type,\n id: `${index + 1}`,\n attributes: attributesFactory?.(index) ?? {},\n }),\n );\n}\n","import { expect } from \"vitest\";\n\ninterface JsonApiResponse {\n data?:\n | {\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }\n | Array<{\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }>;\n}\n\n/**\n * Custom Vitest matchers for JSON:API assertions.\n *\n * @example\n * ```ts\n * import { jsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n * import { expect } from 'vitest';\n *\n * expect.extend(jsonApiMatchers);\n *\n * // Then use in tests:\n * expect(response).toBeValidJsonApi();\n * expect(response).toHaveJsonApiType('articles');\n * expect(response).toHaveJsonApiAttribute('title', 'My Article');\n * expect(response).toHaveJsonApiRelationship('author');\n * ```\n */\nexport const jsonApiMatchers = {\n /**\n * Asserts that the response has a valid JSON:API structure with type and id.\n */\n toBeValidJsonApi(received: JsonApiResponse) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const hasType = typeof data?.type === \"string\" && data.type.length > 0;\n const hasId = typeof data?.id === \"string\" && data.id.length > 0;\n const isValid = hasType && hasId;\n\n return {\n pass: isValid,\n message: () =>\n isValid\n ? `Expected response not to be valid JSON:API, but it has type \"${data?.type}\" and id \"${data?.id}\"`\n : `Expected response to be valid JSON:API with type and id, but got type: ${JSON.stringify(data?.type)}, id: ${JSON.stringify(data?.id)}`,\n };\n },\n\n /**\n * Asserts that the response data has the expected JSON:API type.\n */\n toHaveJsonApiType(received: JsonApiResponse, expectedType: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const actualType = data?.type;\n const pass = actualType === expectedType;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have JSON:API type \"${expectedType}\"`\n : `Expected response to have JSON:API type \"${expectedType}\", but got \"${actualType}\"`,\n };\n },\n\n /**\n * Asserts that the response data has an attribute with the expected value.\n */\n toHaveJsonApiAttribute(received: JsonApiResponse, attributeName: string, expectedValue?: any) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const attributes = data?.attributes ?? {};\n const hasAttribute = attributeName in attributes;\n const actualValue = attributes[attributeName];\n\n if (expectedValue === undefined) {\n // Just check existence\n return {\n pass: hasAttribute,\n message: () =>\n hasAttribute\n ? `Expected response not to have JSON:API attribute \"${attributeName}\"`\n : `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found. Available attributes: ${Object.keys(attributes).join(\", \") || \"none\"}`,\n };\n }\n\n const valuesMatch = actualValue === expectedValue;\n return {\n pass: hasAttribute && valuesMatch,\n message: () =>\n hasAttribute && valuesMatch\n ? `Expected response not to have JSON:API attribute \"${attributeName}\" with value \"${expectedValue}\"`\n : !hasAttribute\n ? `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found`\n : `Expected JSON:API attribute \"${attributeName}\" to be \"${expectedValue}\", but got \"${actualValue}\"`,\n };\n },\n\n /**\n * Asserts that the response data has the specified relationship.\n */\n toHaveJsonApiRelationship(received: JsonApiResponse, relationshipName: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const relationships = data?.relationships ?? {};\n const hasRelationship = relationshipName in relationships;\n\n return {\n pass: hasRelationship,\n message: () =>\n hasRelationship\n ? `Expected response not to have JSON:API relationship \"${relationshipName}\"`\n : `Expected response to have JSON:API relationship \"${relationshipName}\", but it was not found. Available relationships: ${Object.keys(relationships).join(\", \") || \"none\"}`,\n };\n },\n\n /**\n * Asserts that the response data array has the expected length.\n */\n toHaveJsonApiLength(received: JsonApiResponse, expectedLength: number) {\n const data = received?.data;\n const isArray = Array.isArray(data);\n const actualLength = isArray ? data.length : data ? 1 : 0;\n const pass = actualLength === expectedLength;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have ${expectedLength} items`\n : `Expected response to have ${expectedLength} items, but got ${actualLength}`,\n };\n },\n};\n\n// Type declarations for the custom matchers\ndeclare module \"vitest\" {\n interface Assertion<T = any> {\n toBeValidJsonApi(): T;\n toHaveJsonApiType(expectedType: string): T;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): T;\n toHaveJsonApiRelationship(relationshipName: string): T;\n toHaveJsonApiLength(expectedLength: number): T;\n }\n interface AsymmetricMatchersContaining {\n toBeValidJsonApi(): any;\n toHaveJsonApiType(expectedType: string): any;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): any;\n toHaveJsonApiRelationship(relationshipName: string): any;\n toHaveJsonApiLength(expectedLength: number): any;\n }\n}\n\n/**\n * Extends Vitest's expect with JSON:API matchers.\n * Call this in your test setup file.\n *\n * @example\n * ```ts\n * // vitest.setup.ts\n * import { extendExpectWithJsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * extendExpectWithJsonApiMatchers();\n * ```\n */\nexport function extendExpectWithJsonApiMatchers(): void {\n expect.extend(jsonApiMatchers);\n}\n","\"use client\";\n\nimport React, { ReactElement } from \"react\";\nimport { render, RenderOptions, RenderResult } from \"@testing-library/react\";\nimport {\n MockJsonApiProvider,\n MockJsonApiProviderProps as _MockJsonApiProviderProps,\n} from \"../providers/MockJsonApiProvider\";\nimport { JsonApiConfig } from \"../../client/context/JsonApiContext\";\n\nexport interface RenderWithProvidersOptions extends Omit<RenderOptions, \"wrapper\"> {\n /**\n * Custom JSON:API configuration to pass to the mock provider.\n */\n jsonApiConfig?: Partial<JsonApiConfig>;\n\n /**\n * Additional wrapper component to wrap around the providers.\n */\n wrapper?: React.ComponentType<{ children: React.ReactNode }>;\n}\n\n/**\n * Renders a component wrapped with all necessary providers for testing.\n *\n * @example\n * ```tsx\n * import { renderWithProviders } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const { getByText } = renderWithProviders(<MyComponent />);\n * expect(getByText('Hello')).toBeInTheDocument();\n * ```\n *\n * @example With custom config\n * ```tsx\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * jsonApiConfig: { apiUrl: 'https://custom.api.com' },\n * });\n * ```\n *\n * @example With additional wrapper\n * ```tsx\n * const CustomWrapper = ({ children }) => (\n * <ThemeProvider>{children}</ThemeProvider>\n * );\n *\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * wrapper: CustomWrapper,\n * });\n * ```\n */\nexport function renderWithProviders(ui: ReactElement, options: RenderWithProvidersOptions = {}): RenderResult {\n const { jsonApiConfig, wrapper: AdditionalWrapper, ...renderOptions } = options;\n\n function AllProviders({ children }: { children: React.ReactNode }) {\n const content = <MockJsonApiProvider config={jsonApiConfig}>{children}</MockJsonApiProvider>;\n\n if (AdditionalWrapper) {\n return <AdditionalWrapper>{content}</AdditionalWrapper>;\n }\n\n return content;\n }\n\n return render(ui, { wrapper: AllProviders, ...renderOptions });\n}\n\n/**\n * Re-export render utilities from Testing Library for convenience.\n */\nexport { render, screen, waitFor, fireEvent, within } from \"@testing-library/react\";\nexport { userEvent } from \"@testing-library/user-event\";\n"],"mappings":";;;;;;;;AAkDS;AAxCT,IAAM,oBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,aAAa,mCAAY,0BAAZ;AAAA,EACb,gBAAgB,mCAAY,MAAZ;AAAA,EAChB,gBAAgB,CAAC;AAAA,EACjB,SAAS,6BAAM;AAAA,EAAC,GAAP;AAAA,EACT,aAAa;AAAA,IACX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A2C;AAmEpD,SAAS,UAAAA,SAAQ,QAAQ,SAAS,WAAW,cAAc;AAC3D,SAAS,iBAAiB;AAhBN,gBAAAC,YAAA;AAJb,SAAS,oBAAoB,IAAkB,UAAsC,CAAC,GAAiB;AAC5G,QAAM,EAAE,eAAe,SAAS,mBAAmB,GAAG,cAAc,IAAI;AAExE,WAAS,aAAa,EAAE,SAAS,GAAkC;AACjE,UAAM,UAAU,gBAAAA,KAAC,uBAAoB,QAAQ,eAAgB,UAAS;AAEtE,QAAI,mBAAmB;AACrB,aAAO,gBAAAA,KAAC,qBAAmB,mBAAQ;AAAA,IACrC;AAEA,WAAO;AAAA,EACT;AARS;AAUT,SAAO,OAAO,IAAI,EAAE,SAAS,cAAc,GAAG,cAAc,CAAC;AAC/D;AAdgB;","names":["render","jsx"]}
1
+ {"version":3,"sources":["../../src/testing/providers/MockJsonApiProvider.tsx","../../src/testing/factories/createMockModule.ts","../../src/testing/factories/createMockResponse.ts","../../src/testing/factories/createMockService.ts","../../src/testing/factories/createMockApiData.ts","../../src/testing/matchers/jsonApiMatchers.ts","../../src/testing/utils/renderWithProviders.tsx"],"sourcesContent":["\"use client\";\n\nimport React from \"react\";\nimport { JsonApiConfig, JsonApiContext } from \"../../client/context/JsonApiContext\";\n\nexport interface MockJsonApiProviderProps {\n children: React.ReactNode;\n config?: Partial<JsonApiConfig>;\n}\n\nconst defaultMockConfig: JsonApiConfig = {\n apiUrl: \"https://api.test.com\",\n tokenGetter: async () => \"mock-token-for-testing\",\n languageGetter: async () => \"en\",\n defaultHeaders: {},\n onError: () => {},\n cacheConfig: {\n defaultProfile: \"default\",\n },\n};\n\n/**\n * A test-friendly provider that wraps components with mock JSON:API context.\n *\n * @example\n * ```tsx\n * import { MockJsonApiProvider } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * render(\n * <MockJsonApiProvider>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n *\n * @example With custom config\n * ```tsx\n * render(\n * <MockJsonApiProvider config={{ apiUrl: 'https://custom.api.com' }}>\n * <MyComponent />\n * </MockJsonApiProvider>\n * );\n * ```\n */\nexport function MockJsonApiProvider({ children, config }: MockJsonApiProviderProps) {\n const mergedConfig: JsonApiConfig = {\n ...defaultMockConfig,\n ...config,\n };\n\n return <JsonApiContext.Provider value={mergedConfig}>{children}</JsonApiContext.Provider>;\n}\n\nexport { defaultMockConfig };\n","import { ApiRequestDataTypeInterface } from \"../../core/interfaces/ApiRequestDataTypeInterface\";\n\nexport interface CreateMockModuleOptions {\n name: string;\n cache?: string;\n inclusions?: ApiRequestDataTypeInterface[\"inclusions\"];\n}\n\n/**\n * Creates a mock module definition for testing.\n *\n * @example\n * ```ts\n * import { createMockModule } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticleModule = createMockModule({ name: 'articles' });\n * ```\n */\nexport function createMockModule(options: CreateMockModuleOptions): ApiRequestDataTypeInterface {\n // Create a mock model class\n class MockModel {\n id = \"mock-id\";\n type = options.name;\n }\n\n return {\n name: options.name,\n cache: options.cache,\n inclusions: options.inclusions,\n model: MockModel,\n };\n}\n","import { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockResponseOptions {\n data?: ApiDataInterface | ApiDataInterface[] | null;\n ok?: boolean;\n response?: number;\n error?: string;\n meta?: Record<string, any>;\n self?: string;\n next?: string;\n prev?: string;\n}\n\n/**\n * Creates a mock API response for testing.\n *\n * @example\n * ```ts\n * import { createMockResponse, createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockData = createMockApiData({ type: 'articles', id: '1' });\n * const response = createMockResponse({ data: mockData, ok: true });\n * ```\n *\n * @example With pagination\n * ```ts\n * const response = createMockResponse({\n * data: [mockData],\n * ok: true,\n * next: '/articles?page=2',\n * prev: '/articles?page=0',\n * });\n * ```\n */\nexport function createMockResponse(options: CreateMockResponseOptions = {}): ApiResponseInterface {\n const {\n data = null,\n ok = true,\n response = ok ? 200 : 500,\n error = ok ? \"\" : \"Error\",\n meta,\n self,\n next,\n prev,\n } = options;\n\n const mockResponse: ApiResponseInterface = {\n ok,\n response,\n data: data as ApiDataInterface | ApiDataInterface[],\n error,\n meta,\n self,\n next,\n prev,\n };\n\n // Add pagination methods if next/prev provided\n if (next) {\n mockResponse.nextPage = async () => createMockResponse({ ...options, next: undefined, prev: self });\n }\n\n if (prev) {\n mockResponse.prevPage = async () => createMockResponse({ ...options, prev: undefined, next: self });\n }\n\n return mockResponse;\n}\n\n/**\n * Creates a mock error response for testing error scenarios.\n *\n * @example\n * ```ts\n * import { createMockErrorResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorResponse = createMockErrorResponse(404, 'Not Found');\n * ```\n */\nexport function createMockErrorResponse(statusCode: number, errorMessage: string): ApiResponseInterface {\n return createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n data: null,\n });\n}\n","import { vi, type Mock } from \"vitest\";\nimport { ApiResponseInterface } from \"../../core/interfaces/ApiResponseInterface\";\nimport { createMockResponse } from \"./createMockResponse\";\n\nexport type MockApiMethod = Mock<(...args: any[]) => Promise<ApiResponseInterface>>;\n\nexport interface MockService {\n get: MockApiMethod;\n post: MockApiMethod;\n put: MockApiMethod;\n patch: MockApiMethod;\n delete: MockApiMethod;\n}\n\nexport interface CreateMockServiceOptions {\n defaultResponse?: ApiResponseInterface;\n}\n\n/**\n * Creates a mock service with Vitest mock functions for all HTTP methods.\n *\n * @example\n * ```ts\n * import { createMockService, createMockResponse } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockService = createMockService();\n * mockService.get.mockResolvedValue(createMockResponse({ data: mockData }));\n *\n * // Use in test\n * expect(mockService.get).toHaveBeenCalled();\n * ```\n *\n * @example With default response\n * ```ts\n * const mockService = createMockService({\n * defaultResponse: createMockResponse({ ok: true, data: [] }),\n * });\n * ```\n */\nexport function createMockService(options: CreateMockServiceOptions = {}): MockService {\n const defaultResponse = options.defaultResponse ?? createMockResponse({ ok: true });\n\n return {\n get: vi.fn().mockResolvedValue(defaultResponse),\n post: vi.fn().mockResolvedValue(defaultResponse),\n put: vi.fn().mockResolvedValue(defaultResponse),\n patch: vi.fn().mockResolvedValue(defaultResponse),\n delete: vi.fn().mockResolvedValue(defaultResponse),\n };\n}\n\n/**\n * Creates a mock service that returns errors for all methods.\n *\n * @example\n * ```ts\n * import { createMockErrorService } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const errorService = createMockErrorService(500, 'Internal Server Error');\n * ```\n */\nexport function createMockErrorService(statusCode: number = 500, errorMessage: string = \"Error\"): MockService {\n const errorResponse = createMockResponse({\n ok: false,\n response: statusCode,\n error: errorMessage,\n });\n\n return {\n get: vi.fn().mockResolvedValue(errorResponse),\n post: vi.fn().mockResolvedValue(errorResponse),\n put: vi.fn().mockResolvedValue(errorResponse),\n patch: vi.fn().mockResolvedValue(errorResponse),\n delete: vi.fn().mockResolvedValue(errorResponse),\n };\n}\n","import { ApiDataInterface } from \"../../core/interfaces/ApiDataInterface\";\n\nexport interface CreateMockApiDataOptions {\n type: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n included?: any[];\n createdAt?: Date;\n updatedAt?: Date;\n self?: string;\n}\n\n/**\n * Creates a mock ApiDataInterface object for testing.\n *\n * @example\n * ```ts\n * import { createMockApiData } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test Article', body: 'Content here' },\n * });\n * ```\n *\n * @example With relationships\n * ```ts\n * const mockArticle = createMockApiData({\n * type: 'articles',\n * id: '1',\n * attributes: { title: 'Test' },\n * relationships: {\n * author: { data: { type: 'users', id: '42' } },\n * },\n * });\n * ```\n */\nexport function createMockApiData(options: CreateMockApiDataOptions): ApiDataInterface {\n const {\n type,\n id = `mock-${type}-${Math.random().toString(36).substring(7)}`,\n attributes = {},\n relationships = {},\n included = [],\n createdAt = new Date(),\n updatedAt = new Date(),\n self,\n } = options;\n\n const jsonApiData = {\n type,\n id,\n attributes: {\n ...attributes,\n createdAt: createdAt.toISOString(),\n updatedAt: updatedAt.toISOString(),\n },\n relationships,\n };\n\n const mockData: ApiDataInterface = {\n get included() {\n return included;\n },\n get type() {\n return type;\n },\n get id() {\n return id;\n },\n get createdAt() {\n return createdAt;\n },\n get updatedAt() {\n return updatedAt;\n },\n get self() {\n return self;\n },\n get jsonApi() {\n return jsonApiData;\n },\n generateApiUrl: (params?: any) => {\n const baseUrl = `/${type}/${id}`;\n if (params) {\n const searchParams = new URLSearchParams(params);\n return `${baseUrl}?${searchParams.toString()}`;\n }\n return baseUrl;\n },\n dehydrate: () => ({\n jsonApi: jsonApiData,\n included,\n allData: [jsonApiData],\n }),\n rehydrate: function (_data: any) {\n return this;\n },\n createJsonApi: (data: any) => ({\n type,\n id,\n attributes: data,\n }),\n get identifier() {\n const identifierFields = [\"name\"];\n return identifierFields\n .map((field) => attributes[field])\n .filter((v) => v != null && v !== \"\")\n .join(\" \");\n },\n };\n\n // Add attribute accessors to the mock object\n Object.keys(attributes).forEach((key) => {\n Object.defineProperty(mockData, key, {\n get: () => attributes[key],\n enumerable: true,\n });\n });\n\n return mockData;\n}\n\n/**\n * Creates an array of mock ApiDataInterface objects.\n *\n * @example\n * ```ts\n * import { createMockApiDataList } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const mockArticles = createMockApiDataList('articles', 5, (index) => ({\n * title: `Article ${index + 1}`,\n * }));\n * ```\n */\nexport function createMockApiDataList(\n type: string,\n count: number,\n attributesFactory?: (index: number) => Record<string, any>,\n): ApiDataInterface[] {\n return Array.from({ length: count }, (_, index) =>\n createMockApiData({\n type,\n id: `${index + 1}`,\n attributes: attributesFactory?.(index) ?? {},\n }),\n );\n}\n","import { expect } from \"vitest\";\n\ninterface JsonApiResponse {\n data?:\n | {\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }\n | Array<{\n type?: string;\n id?: string;\n attributes?: Record<string, any>;\n relationships?: Record<string, any>;\n }>;\n}\n\n/**\n * Custom Vitest matchers for JSON:API assertions.\n *\n * @example\n * ```ts\n * import { jsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n * import { expect } from 'vitest';\n *\n * expect.extend(jsonApiMatchers);\n *\n * // Then use in tests:\n * expect(response).toBeValidJsonApi();\n * expect(response).toHaveJsonApiType('articles');\n * expect(response).toHaveJsonApiAttribute('title', 'My Article');\n * expect(response).toHaveJsonApiRelationship('author');\n * ```\n */\nexport const jsonApiMatchers = {\n /**\n * Asserts that the response has a valid JSON:API structure with type and id.\n */\n toBeValidJsonApi(received: JsonApiResponse) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const hasType = typeof data?.type === \"string\" && data.type.length > 0;\n const hasId = typeof data?.id === \"string\" && data.id.length > 0;\n const isValid = hasType && hasId;\n\n return {\n pass: isValid,\n message: () =>\n isValid\n ? `Expected response not to be valid JSON:API, but it has type \"${data?.type}\" and id \"${data?.id}\"`\n : `Expected response to be valid JSON:API with type and id, but got type: ${JSON.stringify(data?.type)}, id: ${JSON.stringify(data?.id)}`,\n };\n },\n\n /**\n * Asserts that the response data has the expected JSON:API type.\n */\n toHaveJsonApiType(received: JsonApiResponse, expectedType: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const actualType = data?.type;\n const pass = actualType === expectedType;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have JSON:API type \"${expectedType}\"`\n : `Expected response to have JSON:API type \"${expectedType}\", but got \"${actualType}\"`,\n };\n },\n\n /**\n * Asserts that the response data has an attribute with the expected value.\n */\n toHaveJsonApiAttribute(received: JsonApiResponse, attributeName: string, expectedValue?: any) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const attributes = data?.attributes ?? {};\n const hasAttribute = attributeName in attributes;\n const actualValue = attributes[attributeName];\n\n if (expectedValue === undefined) {\n // Just check existence\n return {\n pass: hasAttribute,\n message: () =>\n hasAttribute\n ? `Expected response not to have JSON:API attribute \"${attributeName}\"`\n : `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found. Available attributes: ${Object.keys(attributes).join(\", \") || \"none\"}`,\n };\n }\n\n const valuesMatch = actualValue === expectedValue;\n return {\n pass: hasAttribute && valuesMatch,\n message: () =>\n hasAttribute && valuesMatch\n ? `Expected response not to have JSON:API attribute \"${attributeName}\" with value \"${expectedValue}\"`\n : !hasAttribute\n ? `Expected response to have JSON:API attribute \"${attributeName}\", but it was not found`\n : `Expected JSON:API attribute \"${attributeName}\" to be \"${expectedValue}\", but got \"${actualValue}\"`,\n };\n },\n\n /**\n * Asserts that the response data has the specified relationship.\n */\n toHaveJsonApiRelationship(received: JsonApiResponse, relationshipName: string) {\n const data = Array.isArray(received?.data) ? received.data[0] : received?.data;\n const relationships = data?.relationships ?? {};\n const hasRelationship = relationshipName in relationships;\n\n return {\n pass: hasRelationship,\n message: () =>\n hasRelationship\n ? `Expected response not to have JSON:API relationship \"${relationshipName}\"`\n : `Expected response to have JSON:API relationship \"${relationshipName}\", but it was not found. Available relationships: ${Object.keys(relationships).join(\", \") || \"none\"}`,\n };\n },\n\n /**\n * Asserts that the response data array has the expected length.\n */\n toHaveJsonApiLength(received: JsonApiResponse, expectedLength: number) {\n const data = received?.data;\n const isArray = Array.isArray(data);\n const actualLength = isArray ? data.length : data ? 1 : 0;\n const pass = actualLength === expectedLength;\n\n return {\n pass,\n message: () =>\n pass\n ? `Expected response not to have ${expectedLength} items`\n : `Expected response to have ${expectedLength} items, but got ${actualLength}`,\n };\n },\n};\n\n// Type declarations for the custom matchers\ndeclare module \"vitest\" {\n interface Assertion<T = any> {\n toBeValidJsonApi(): T;\n toHaveJsonApiType(expectedType: string): T;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): T;\n toHaveJsonApiRelationship(relationshipName: string): T;\n toHaveJsonApiLength(expectedLength: number): T;\n }\n interface AsymmetricMatchersContaining {\n toBeValidJsonApi(): any;\n toHaveJsonApiType(expectedType: string): any;\n toHaveJsonApiAttribute(attributeName: string, expectedValue?: any): any;\n toHaveJsonApiRelationship(relationshipName: string): any;\n toHaveJsonApiLength(expectedLength: number): any;\n }\n}\n\n/**\n * Extends Vitest's expect with JSON:API matchers.\n * Call this in your test setup file.\n *\n * @example\n * ```ts\n * // vitest.setup.ts\n * import { extendExpectWithJsonApiMatchers } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * extendExpectWithJsonApiMatchers();\n * ```\n */\nexport function extendExpectWithJsonApiMatchers(): void {\n expect.extend(jsonApiMatchers);\n}\n","\"use client\";\n\nimport React, { ReactElement } from \"react\";\nimport { render, RenderOptions, RenderResult } from \"@testing-library/react\";\nimport {\n MockJsonApiProvider,\n MockJsonApiProviderProps as _MockJsonApiProviderProps,\n} from \"../providers/MockJsonApiProvider\";\nimport { JsonApiConfig } from \"../../client/context/JsonApiContext\";\n\nexport interface RenderWithProvidersOptions extends Omit<RenderOptions, \"wrapper\"> {\n /**\n * Custom JSON:API configuration to pass to the mock provider.\n */\n jsonApiConfig?: Partial<JsonApiConfig>;\n\n /**\n * Additional wrapper component to wrap around the providers.\n */\n wrapper?: React.ComponentType<{ children: React.ReactNode }>;\n}\n\n/**\n * Renders a component wrapped with all necessary providers for testing.\n *\n * @example\n * ```tsx\n * import { renderWithProviders } from '@carlonicora/nextjs-jsonapi/testing';\n *\n * const { getByText } = renderWithProviders(<MyComponent />);\n * expect(getByText('Hello')).toBeInTheDocument();\n * ```\n *\n * @example With custom config\n * ```tsx\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * jsonApiConfig: { apiUrl: 'https://custom.api.com' },\n * });\n * ```\n *\n * @example With additional wrapper\n * ```tsx\n * const CustomWrapper = ({ children }) => (\n * <ThemeProvider>{children}</ThemeProvider>\n * );\n *\n * const { getByText } = renderWithProviders(<MyComponent />, {\n * wrapper: CustomWrapper,\n * });\n * ```\n */\nexport function renderWithProviders(ui: ReactElement, options: RenderWithProvidersOptions = {}): RenderResult {\n const { jsonApiConfig, wrapper: AdditionalWrapper, ...renderOptions } = options;\n\n function AllProviders({ children }: { children: React.ReactNode }) {\n const content = <MockJsonApiProvider config={jsonApiConfig}>{children}</MockJsonApiProvider>;\n\n if (AdditionalWrapper) {\n return <AdditionalWrapper>{content}</AdditionalWrapper>;\n }\n\n return content;\n }\n\n return render(ui, { wrapper: AllProviders, ...renderOptions });\n}\n\n/**\n * Re-export render utilities from Testing Library for convenience.\n */\nexport { render, screen, waitFor, fireEvent, within } from \"@testing-library/react\";\nexport { userEvent } from \"@testing-library/user-event\";\n"],"mappings":";;;;;;;;AAkDS;AAxCT,IAAM,oBAAmC;AAAA,EACvC,QAAQ;AAAA,EACR,aAAa,mCAAY,0BAAZ;AAAA,EACb,gBAAgB,mCAAY,MAAZ;AAAA,EAChB,gBAAgB,CAAC;AAAA,EACjB,SAAS,6BAAM;AAAA,EAAC,GAAP;AAAA,EACT,aAAa;AAAA,IACX,gBAAgB;AAAA,EAClB;AACF;AAyBO,SAAS,oBAAoB,EAAE,UAAU,OAAO,GAA6B;AAClF,QAAM,eAA8B;AAAA,IAClC,GAAG;AAAA,IACH,GAAG;AAAA,EACL;AAEA,SAAO,oBAAC,eAAe,UAAf,EAAwB,OAAO,cAAe,UAAS;AACjE;AAPgB;;;AC1BT,SAAS,iBAAiB,SAA+D;AAAA,EAE9F,MAAM,UAAU;AAAA,IApBlB,OAoBkB;AAAA;AAAA;AAAA,IACd,KAAK;AAAA,IACL,OAAO,QAAQ;AAAA,EACjB;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ;AAAA,IACd,OAAO,QAAQ;AAAA,IACf,YAAY,QAAQ;AAAA,IACpB,OAAO;AAAA,EACT;AACF;AAbgB;;;ACiBT,SAAS,mBAAmB,UAAqC,CAAC,GAAyB;AAChG,QAAM;AAAA,IACJ,OAAO;AAAA,IACP,KAAK;AAAA,IACL,WAAW,KAAK,MAAM;AAAA,IACtB,QAAQ,KAAK,KAAK;AAAA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,cAAc,GAAG,cAAc,CAAC;AAC/D;AAdgB;","names":["render","jsx"]}
@@ -1,6 +1,6 @@
1
- import { F as FeatureInterface } from './feature.interface-CIWxo8NP.js';
2
- import { R as RoleInterface } from './notification.interface-DYDZENx2.js';
3
- import { P as PermissionMappingInterface, M as ModulePathsInterface, A as ActionType, a as PermissionValue, b as PermissionsMap } from './ModulePathsInterface-wVS5Raa4.js';
1
+ import { F as FeatureInterface } from './feature.interface-BO25VLlx.js';
2
+ import { R as RoleInterface } from './notification.interface-DcSuc9CL.js';
3
+ import { P as PermissionMappingInterface, M as ModulePathsInterface, A as ActionType, a as PermissionValue, b as PermissionsMap } from './ModulePathsInterface-DJKs7s_s.js';
4
4
 
5
5
  type PageInfo = {
6
6
  startItem: number;
@@ -1,6 +1,6 @@
1
- import { F as FeatureInterface } from './feature.interface-BxFFOPNq.mjs';
2
- import { R as RoleInterface } from './notification.interface-DrHu_1MM.mjs';
3
- import { P as PermissionMappingInterface, M as ModulePathsInterface, A as ActionType, a as PermissionValue, b as PermissionsMap } from './ModulePathsInterface-49EWvbWy.mjs';
1
+ import { F as FeatureInterface } from './feature.interface-CXb1-vNq.mjs';
2
+ import { R as RoleInterface } from './notification.interface-DG6obXUH.mjs';
3
+ import { P as PermissionMappingInterface, M as ModulePathsInterface, A as ActionType, a as PermissionValue, b as PermissionsMap } from './ModulePathsInterface-BrdqgteS.mjs';
4
4
 
5
5
  type PageInfo = {
6
6
  startItem: number;
@@ -1,4 +1,4 @@
1
- import { N as NotificationInterface } from './notification.interface-DYDZENx2.js';
1
+ import { N as NotificationInterface } from './notification.interface-DcSuc9CL.js';
2
2
 
3
3
  interface UseSocketOptions {
4
4
  token: string;
@@ -1,4 +1,4 @@
1
- import { N as NotificationInterface } from './notification.interface-DrHu_1MM.mjs';
1
+ import { N as NotificationInterface } from './notification.interface-DG6obXUH.mjs';
2
2
 
3
3
  interface UseSocketOptions {
4
4
  token: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@carlonicora/nextjs-jsonapi",
3
- "version": "1.73.0",
3
+ "version": "1.74.0",
4
4
  "description": "Next.js JSON:API client with server/client support and caching",
5
5
  "author": "Carlo Nicora",
6
6
  "license": "GPL-3.0-or-later",
@@ -40,6 +40,9 @@ class MockArticle implements Partial<ApiDataInterface> {
40
40
  createJsonApi(data: any) {
41
41
  return { type: this.type, attributes: data };
42
42
  }
43
+ get identifier() {
44
+ return "MockArticle";
45
+ }
43
46
  }
44
47
 
45
48
  const mockModule = { name: "articles", model: MockArticle };
@@ -7,6 +7,7 @@ import { recentPagesAtom } from "../../atoms";
7
7
  import {
8
8
  DropdownMenu,
9
9
  DropdownMenuContent,
10
+ DropdownMenuGroup,
10
11
  DropdownMenuItem,
11
12
  DropdownMenuLabel,
12
13
  DropdownMenuSeparator,
@@ -32,20 +33,22 @@ export function RecentPagesNavigator() {
32
33
  </span>
33
34
  </DropdownMenuTrigger>
34
35
  <DropdownMenuContent align="start" className="w-96">
35
- <DropdownMenuLabel>{t(`common.recent_pages`)}</DropdownMenuLabel>
36
- <DropdownMenuSeparator />
37
- {recentPages.map((page, index) => (
38
- <DropdownMenuItem key={`${page.url}-${index}`}>
39
- <Link href={page.url} className="flex items-center gap-2">
40
- <div className="flex flex-col">
41
- <div className="truncate text-sm">{page.title}</div>
42
- <div className="text-muted-foreground text-xs font-normal">
43
- {t(`entities.${page.moduleType}`, { count: 1 })}
36
+ <DropdownMenuGroup>
37
+ <DropdownMenuLabel>{t(`common.recent_pages`)}</DropdownMenuLabel>
38
+ <DropdownMenuSeparator />
39
+ {recentPages.map((page, index) => (
40
+ <DropdownMenuItem key={`${page.url}-${index}`}>
41
+ <Link href={page.url} className="flex items-center gap-2">
42
+ <div className="flex flex-col">
43
+ <div className="truncate text-sm">{page.title}</div>
44
+ <div className="text-muted-foreground text-xs font-normal">
45
+ {t(`entities.${page.moduleType}`, { count: 1 })}
46
+ </div>
44
47
  </div>
45
- </div>
46
- </Link>
47
- </DropdownMenuItem>
48
- ))}
48
+ </Link>
49
+ </DropdownMenuItem>
50
+ ))}
51
+ </DropdownMenuGroup>
49
52
  </DropdownMenuContent>
50
53
  </DropdownMenu>
51
54
  );
@@ -4,6 +4,16 @@ import { ApiRequestDataTypeInterface } from "../interfaces/ApiRequestDataTypeInt
4
4
  import { JsonApiHydratedDataInterface } from "../interfaces/JsonApiHydratedDataInterface";
5
5
 
6
6
  export abstract class AbstractApiData implements ApiDataInterface {
7
+ static identifierFields: string[] = ["name"];
8
+
9
+ get identifier(): string {
10
+ const fields = (this.constructor as typeof AbstractApiData).identifierFields;
11
+ return fields
12
+ .map((field) => this._jsonApi?.attributes?.[field])
13
+ .filter((v) => v != null && v !== "")
14
+ .join(" ");
15
+ }
16
+
7
17
  protected _jsonApi?: any;
8
18
  protected _included?: any[];
9
19
 
@@ -0,0 +1,117 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { AbstractApiData } from "../AbstractApiData";
3
+ import { JsonApiHydratedDataInterface } from "../../interfaces/JsonApiHydratedDataInterface";
4
+
5
+ // Concrete test subclass — uses default identifierFields ["name"]
6
+ class DefaultModel extends AbstractApiData {
7
+ rehydrate(data: JsonApiHydratedDataInterface): this {
8
+ super.rehydrate(data);
9
+ return this;
10
+ }
11
+ }
12
+
13
+ // Subclass with custom identifierFields
14
+ class PersonModel extends AbstractApiData {
15
+ rehydrate(data: JsonApiHydratedDataInterface): this {
16
+ super.rehydrate(data);
17
+ return this;
18
+ }
19
+ }
20
+ // Simulate what ModuleFactory does at registration time
21
+ (PersonModel as any).identifierFields = ["first_name", "last_name"];
22
+
23
+ // Subclass with single non-name field
24
+ class OrderModel extends AbstractApiData {
25
+ rehydrate(data: JsonApiHydratedDataInterface): this {
26
+ super.rehydrate(data);
27
+ return this;
28
+ }
29
+ }
30
+ (OrderModel as any).identifierFields = ["number"];
31
+
32
+ function makeHydratedData(attributes: Record<string, any>): JsonApiHydratedDataInterface {
33
+ return {
34
+ jsonApi: {
35
+ type: "test",
36
+ id: "1",
37
+ attributes,
38
+ },
39
+ included: [],
40
+ };
41
+ }
42
+
43
+ describe("AbstractApiData.identifier", () => {
44
+ it("returns name attribute by default", () => {
45
+ const model = new DefaultModel();
46
+ model.rehydrate(makeHydratedData({ name: "Acme Corp" }));
47
+ expect(model.identifier).toBe("Acme Corp");
48
+ });
49
+
50
+ it("joins multiple fields with a space", () => {
51
+ const model = new PersonModel();
52
+ model.rehydrate(makeHydratedData({ first_name: "John", last_name: "Doe" }));
53
+ expect(model.identifier).toBe("John Doe");
54
+ });
55
+
56
+ it("filters out null fields", () => {
57
+ const model = new PersonModel();
58
+ model.rehydrate(makeHydratedData({ first_name: null, last_name: "Doe" }));
59
+ expect(model.identifier).toBe("Doe");
60
+ });
61
+
62
+ it("filters out undefined fields", () => {
63
+ const model = new PersonModel();
64
+ model.rehydrate(makeHydratedData({ last_name: "Doe" }));
65
+ expect(model.identifier).toBe("Doe");
66
+ });
67
+
68
+ it("filters out empty string fields", () => {
69
+ const model = new PersonModel();
70
+ model.rehydrate(makeHydratedData({ first_name: "", last_name: "Doe" }));
71
+ expect(model.identifier).toBe("Doe");
72
+ });
73
+
74
+ it("preserves numeric zero values", () => {
75
+ class ZeroModel extends AbstractApiData {
76
+ rehydrate(data: JsonApiHydratedDataInterface): this {
77
+ super.rehydrate(data);
78
+ return this;
79
+ }
80
+ }
81
+ (ZeroModel as any).identifierFields = ["quantity"];
82
+ const model = new ZeroModel();
83
+ model.rehydrate(makeHydratedData({ quantity: 0 }));
84
+ expect(model.identifier).toBe("0");
85
+ });
86
+
87
+ it("returns single non-name field", () => {
88
+ const model = new OrderModel();
89
+ model.rehydrate(makeHydratedData({ number: "ORD-001" }));
90
+ expect(model.identifier).toBe("ORD-001");
91
+ });
92
+
93
+ it("returns empty string when not rehydrated", () => {
94
+ const model = new DefaultModel();
95
+ expect(model.identifier).toBe("");
96
+ });
97
+
98
+ it("returns empty string when attribute is missing", () => {
99
+ const model = new DefaultModel();
100
+ model.rehydrate(makeHydratedData({}));
101
+ expect(model.identifier).toBe("");
102
+ });
103
+
104
+ it("does not share identifierFields between subclasses", () => {
105
+ const defaultModel = new DefaultModel();
106
+ const personModel = new PersonModel();
107
+ const orderModel = new OrderModel();
108
+
109
+ defaultModel.rehydrate(makeHydratedData({ name: "Test" }));
110
+ personModel.rehydrate(makeHydratedData({ first_name: "John", last_name: "Doe" }));
111
+ orderModel.rehydrate(makeHydratedData({ number: "ORD-001" }));
112
+
113
+ expect(defaultModel.identifier).toBe("Test");
114
+ expect(personModel.identifier).toBe("John Doe");
115
+ expect(orderModel.identifier).toBe("ORD-001");
116
+ });
117
+ });
@@ -37,6 +37,9 @@ class MockDataClass implements Partial<ApiDataInterface> {
37
37
  rehydrate(data: any) {
38
38
  return this;
39
39
  }
40
+ get identifier() {
41
+ return "MockDataClass";
42
+ }
40
43
  }
41
44
 
42
45
  describe("JsonApiDataFactory", () => {
@@ -39,6 +39,9 @@ class MockDataClass implements Partial<ApiDataInterface> {
39
39
  createJsonApi(data: any) {
40
40
  return { type: this.type, attributes: data };
41
41
  }
42
+ get identifier() {
43
+ return "MockDataClass";
44
+ }
42
45
  }
43
46
 
44
47
  describe("RehydrationFactory", () => {
@@ -8,6 +8,7 @@ export interface ApiDataInterface {
8
8
  get updatedAt(): Date;
9
9
  get self(): string | undefined;
10
10
  get jsonApi(): any;
11
+ get identifier(): string;
11
12
  generateApiUrl(params?: any): string;
12
13
  dehydrate(): JsonApiHydratedDataInterface;
13
14
  rehydrate(data: JsonApiHydratedDataInterface): this;
@@ -40,6 +40,9 @@ class MockTaxonomy implements ApiDataInterface {
40
40
  dehydrate(): any {
41
41
  return {};
42
42
  }
43
+ get identifier(): string {
44
+ return "MockTaxonomy";
45
+ }
43
46
  }
44
47
 
45
48
  class MockLeafTaxonomy implements ApiDataInterface {
@@ -79,6 +82,9 @@ class MockLeafTaxonomy implements ApiDataInterface {
79
82
  dehydrate(): any {
80
83
  return {};
81
84
  }
85
+ get identifier(): string {
86
+ return "MockLeafTaxonomy";
87
+ }
82
88
  }
83
89
 
84
90
  describe("DataClassRegistry.getByJsonApiType", () => {
@@ -34,6 +34,9 @@ class MockArticle implements Partial<ApiDataInterface> {
34
34
  createJsonApi(data: any) {
35
35
  return { type: this.type, attributes: data };
36
36
  }
37
+ get identifier() {
38
+ return "MockArticle";
39
+ }
37
40
  }
38
41
 
39
42
  describe("DataClassRegistry", () => {
@@ -34,6 +34,9 @@ class MockUser implements Partial<ApiDataInterface> {
34
34
  createJsonApi(data: any) {
35
35
  return { type: this.type, attributes: data };
36
36
  }
37
+ get identifier() {
38
+ return "MockUser";
39
+ }
37
40
  }
38
41
 
39
42
  class MockArticle implements Partial<ApiDataInterface> {
@@ -66,6 +69,9 @@ class MockArticle implements Partial<ApiDataInterface> {
66
69
  createJsonApi(data: any) {
67
70
  return { type: this.type, attributes: data };
68
71
  }
72
+ get identifier() {
73
+ return "MockArticle";
74
+ }
69
75
  }
70
76
 
71
77
  // Mock Modules class with static getters
@@ -13,6 +13,7 @@ const mockModule: ModuleInterface = {
13
13
  included: [],
14
14
  createdAt: new Date(),
15
15
  updatedAt: new Date(),
16
+ identifier: "pipelines",
16
17
  name: "pipelines",
17
18
  permissions: { create: true, read: true, update: true, delete: false },
18
19
  } as ModuleInterface;
@@ -24,6 +25,7 @@ const mockFeatures: FeatureInterface[] = [
24
25
  included: [],
25
26
  createdAt: new Date(),
26
27
  updatedAt: new Date(),
28
+ identifier: "CRM",
27
29
  name: "CRM",
28
30
  isCore: false,
29
31
  modules: [mockModule],
@@ -103,6 +103,7 @@ export type ModuleFactory = (params: {
103
103
  feature?: string;
104
104
  moduleId?: string;
105
105
  icon?: LucideIcon;
106
+ identifier?: string[];
106
107
  inclusions?: Record<
107
108
  string,
108
109
  {
@@ -103,6 +103,13 @@ export function createMockApiData(options: CreateMockApiDataOptions): ApiDataInt
103
103
  id,
104
104
  attributes: data,
105
105
  }),
106
+ get identifier() {
107
+ const identifierFields = ["name"];
108
+ return identifierFields
109
+ .map((field) => attributes[field])
110
+ .filter((v) => v != null && v !== "")
111
+ .join(" ");
112
+ },
106
113
  };
107
114
 
108
115
  // Add attribute accessors to the mock object