yaxa-svelte 2.5.0 → 2.7.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.
@@ -0,0 +1,242 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import { hashQueryKey, QueryClient, createQuery, createMutation, setQueryClient } from './index';
3
+ describe('Runes Query Engine - hashQueryKey', () => {
4
+ it('returns string keys as-is', () => {
5
+ expect(hashQueryKey('projects')).toBe('projects');
6
+ expect(hashQueryKey('/api/items')).toBe('/api/items');
7
+ });
8
+ it('deterministically hashes arrays and nested objects regardless of key order', () => {
9
+ const keyA = ['projects', { orgId: '123', status: 'active' }];
10
+ const keyB = ['projects', { status: 'active', orgId: '123' }];
11
+ expect(hashQueryKey(keyA)).toBe(hashQueryKey(keyB));
12
+ });
13
+ });
14
+ describe('Runes Query Engine - QueryClient', () => {
15
+ let client;
16
+ beforeEach(() => {
17
+ client = new QueryClient();
18
+ setQueryClient(client);
19
+ });
20
+ it('creates, retrieves, and updates query cache entries', () => {
21
+ expect(client.getQueryData('users')).toBeNull();
22
+ client.setQueryData('users', [{ id: '1', name: 'Alice' }]);
23
+ expect(client.getQueryData('users')).toEqual([{ id: '1', name: 'Alice' }]);
24
+ // Functional updater
25
+ client.setQueryData('users', (prev) => [
26
+ ...(prev ?? []),
27
+ { id: '2', name: 'Bob' }
28
+ ]);
29
+ expect(client.getQueryData('users')).toHaveLength(2);
30
+ });
31
+ it('invalidates matching queries with exact and prefix filters', async () => {
32
+ const entry1 = client.getOrCreateEntry('projects-list');
33
+ const entry2 = client.getOrCreateEntry('projects-detail-1');
34
+ const entry3 = client.getOrCreateEntry('users');
35
+ const listener1 = vi.fn();
36
+ const listener2 = vi.fn();
37
+ const listener3 = vi.fn();
38
+ entry1.subscribers.add(listener1);
39
+ entry2.subscribers.add(listener2);
40
+ entry3.subscribers.add(listener3);
41
+ // Invalidate all projects
42
+ await client.invalidateQueries('projects');
43
+ expect(listener1).toHaveBeenCalledTimes(1);
44
+ expect(listener2).toHaveBeenCalledTimes(1);
45
+ expect(listener3).not.toHaveBeenCalled();
46
+ // Exact invalidation
47
+ await client.invalidateQueries({ key: 'projects-list', exact: true });
48
+ expect(listener1).toHaveBeenCalledTimes(2);
49
+ expect(listener2).toHaveBeenCalledTimes(1);
50
+ });
51
+ });
52
+ describe('Runes Query Engine - createQuery', () => {
53
+ let client;
54
+ beforeEach(() => {
55
+ client = new QueryClient();
56
+ setQueryClient(client);
57
+ });
58
+ it('fetches data and unwraps ClientResponse successfully', async () => {
59
+ const fetchMock = vi.fn().mockResolvedValue({
60
+ ok: true,
61
+ status: 200,
62
+ data: [{ id: 'proj_1', name: 'Alpha' }],
63
+ error: null,
64
+ response: new Response()
65
+ });
66
+ const query = createQuery('test-projects', fetchMock, { client });
67
+ expect(query.isLoading).toBe(true);
68
+ expect(query.data).toBeNull();
69
+ const result = await query.refetch();
70
+ expect(result).toEqual([{ id: 'proj_1', name: 'Alpha' }]);
71
+ expect(query.data).toEqual([{ id: 'proj_1', name: 'Alpha' }]);
72
+ expect(query.isSuccess).toBe(true);
73
+ expect(query.isLoading).toBe(false);
74
+ expect(query.isError).toBe(false);
75
+ });
76
+ it('handles ClientResponse errors and RFC 7807 problem details', async () => {
77
+ const errorResponse = {
78
+ ok: false,
79
+ status: 404,
80
+ data: null,
81
+ error: {
82
+ type: 'https://yaxa.dev/errors/not-found',
83
+ title: 'Project Not Found',
84
+ status: 404,
85
+ detail: 'No project with ID 999 exists'
86
+ },
87
+ response: new Response(null, { status: 404 })
88
+ };
89
+ const fetchMock = vi.fn().mockResolvedValue(errorResponse);
90
+ const onError = vi.fn();
91
+ const query = createQuery('not-found-query', fetchMock, { client, onError });
92
+ await query.refetch();
93
+ expect(query.data).toBeNull();
94
+ expect(query.isError).toBe(true);
95
+ expect(query.error).toEqual(errorResponse.error);
96
+ expect(onError).toHaveBeenCalledWith(errorResponse.error);
97
+ });
98
+ it('coalesces multiple in-flight concurrent requests to the same key', async () => {
99
+ let resolveCall = () => { };
100
+ const fetchMock = vi.fn().mockImplementation(() => new Promise((res) => {
101
+ resolveCall = res;
102
+ }));
103
+ const query1 = createQuery('shared-key', fetchMock, { client });
104
+ const query2 = createQuery('shared-key', fetchMock, { client });
105
+ // Trigger both simultaneously
106
+ const p1 = query1.refetch();
107
+ const p2 = query2.refetch();
108
+ expect(fetchMock).toHaveBeenCalledTimes(1);
109
+ resolveCall({
110
+ ok: true,
111
+ status: 200,
112
+ data: { result: 'shared' },
113
+ error: null,
114
+ response: new Response()
115
+ });
116
+ const [res1, res2] = await Promise.all([p1, p2]);
117
+ expect(res1).toEqual({ result: 'shared' });
118
+ expect(res2).toEqual({ result: 'shared' });
119
+ });
120
+ it('respects staleTimeMs and avoids refetching when cache is fresh', async () => {
121
+ const fetchMock = vi.fn().mockResolvedValue('data-1');
122
+ const query = createQuery('stale-key', fetchMock, {
123
+ client,
124
+ staleTimeMs: 10_000
125
+ });
126
+ await query.refetch();
127
+ expect(fetchMock).toHaveBeenCalledTimes(1);
128
+ // Non-forced fetch should return cached data because staleTimeMs hasn't elapsed
129
+ client.getOrCreateEntry('stale-key').updatedAt = Date.now();
130
+ const entry = client.getOrCreateEntry('stale-key');
131
+ expect(entry.data).toBe('data-1');
132
+ });
133
+ it('hydrates with initialData with zero loading state', () => {
134
+ const query = createQuery('ssr-key', async () => 'fetched', {
135
+ client,
136
+ initialData: 'preloaded'
137
+ });
138
+ expect(query.data).toBe('preloaded');
139
+ expect(query.isLoading).toBe(false);
140
+ expect(query.isSuccess).toBe(true);
141
+ });
142
+ it('supports optimisticUpdate and setData', () => {
143
+ const query = createQuery('list-key', async () => ['item1'], {
144
+ client,
145
+ initialData: ['item1']
146
+ });
147
+ query.optimisticUpdate((prev) => [...(prev ?? []), 'item2']);
148
+ expect(query.data).toEqual(['item1', 'item2']);
149
+ query.setData(['item-override']);
150
+ expect(query.data).toEqual(['item-override']);
151
+ });
152
+ it('respects enabled: false and skips automatic fetching', async () => {
153
+ const fetchMock = vi.fn().mockResolvedValue('data');
154
+ const query = createQuery('disabled-key', fetchMock, {
155
+ client,
156
+ enabled: false
157
+ });
158
+ const res = await query.refetch();
159
+ expect(res).toBeNull();
160
+ expect(fetchMock).not.toHaveBeenCalled();
161
+ });
162
+ it('supports live invalidation via subscribeToSse', async () => {
163
+ const mockSse = {
164
+ on: vi.fn((_event, handler) => {
165
+ // Save handler
166
+ mockSse.trigger = handler;
167
+ return () => { };
168
+ })
169
+ };
170
+ const fetchMock = vi.fn().mockResolvedValue('sse-data');
171
+ createQuery('sse-query', fetchMock, {
172
+ client,
173
+ subscribeToSse: {
174
+ sse: mockSse,
175
+ event: 'project.updated'
176
+ }
177
+ });
178
+ expect(mockSse.on).toBeDefined();
179
+ });
180
+ });
181
+ describe('Runes Query Engine - createMutation', () => {
182
+ it('executes successful mutation and runs lifecycle hooks', async () => {
183
+ const onMutate = vi.fn().mockReturnValue({ tempId: 'temp_123' });
184
+ const onSuccess = vi.fn();
185
+ const onSettled = vi.fn();
186
+ const mutationFn = vi.fn().mockResolvedValue({
187
+ ok: true,
188
+ status: 201,
189
+ data: { id: 'real_123', name: 'Created' },
190
+ error: null,
191
+ response: new Response(null, { status: 201 })
192
+ });
193
+ const mutation = createMutation(mutationFn, {
194
+ onMutate,
195
+ onSuccess,
196
+ onSettled
197
+ });
198
+ expect(mutation.isIdle).toBe(true);
199
+ const promise = mutation.mutate({ name: 'Created' });
200
+ expect(mutation.isPending).toBe(true);
201
+ const result = await promise;
202
+ expect(result).toEqual({ id: 'real_123', name: 'Created' });
203
+ expect(mutation.data).toEqual({ id: 'real_123', name: 'Created' });
204
+ expect(mutation.isSuccess).toBe(true);
205
+ expect(mutation.isPending).toBe(false);
206
+ expect(onMutate).toHaveBeenCalledWith({ name: 'Created' });
207
+ expect(onSuccess).toHaveBeenCalledWith({ id: 'real_123', name: 'Created' }, { name: 'Created' }, { tempId: 'temp_123' });
208
+ expect(onSettled).toHaveBeenCalledWith({ id: 'real_123', name: 'Created' }, null, { name: 'Created' }, { tempId: 'temp_123' });
209
+ });
210
+ it('handles mutation errors, passes context for rollback, and re-throws', async () => {
211
+ const rollbackContext = { previousList: ['item1'] };
212
+ const onMutate = vi.fn().mockReturnValue(rollbackContext);
213
+ const onError = vi.fn();
214
+ const onSettled = vi.fn();
215
+ const errorResponse = {
216
+ ok: false,
217
+ status: 400,
218
+ data: null,
219
+ error: {
220
+ type: 'https://yaxa.dev/errors/validation',
221
+ title: 'Bad Request',
222
+ status: 400,
223
+ detail: 'Name must be at least 3 characters'
224
+ },
225
+ response: new Response(null, { status: 400 })
226
+ };
227
+ const mutation = createMutation(async () => errorResponse, {
228
+ onMutate,
229
+ onError,
230
+ onSettled
231
+ });
232
+ await expect(mutation.mutate(undefined)).rejects.toEqual(errorResponse.error);
233
+ expect(mutation.isError).toBe(true);
234
+ expect(mutation.error).toEqual(errorResponse.error);
235
+ expect(onError).toHaveBeenCalledWith(errorResponse.error, undefined, rollbackContext);
236
+ expect(onSettled).toHaveBeenCalledWith(null, errorResponse.error, undefined, rollbackContext);
237
+ mutation.reset();
238
+ expect(mutation.isIdle).toBe(true);
239
+ expect(mutation.error).toBeNull();
240
+ expect(mutation.data).toBeNull();
241
+ });
242
+ });
@@ -0,0 +1,222 @@
1
+ /**
2
+ * Standard RFC 7807 Problem Details representation.
3
+ * @see https://datatracker.ietf.org/doc/html/rfc7807
4
+ */
5
+ export interface ProblemDetails {
6
+ type: string;
7
+ title: string;
8
+ status: number;
9
+ detail?: string;
10
+ instance?: string;
11
+ invalidParams?: Array<{
12
+ name: string;
13
+ reason: string;
14
+ }>;
15
+ [key: string]: unknown;
16
+ }
17
+ /**
18
+ * Standard Schema or validator representation.
19
+ */
20
+ export type AnyValidator<T = any> = {
21
+ '~standard': {
22
+ validate: (value: unknown) => Promise<{
23
+ value?: T;
24
+ issues?: ReadonlyArray<any>;
25
+ }> | {
26
+ value?: T;
27
+ issues?: ReadonlyArray<any>;
28
+ };
29
+ };
30
+ } | {
31
+ safeParse: (value: unknown) => {
32
+ success: true;
33
+ data: T;
34
+ } | {
35
+ success: false;
36
+ error: any;
37
+ };
38
+ } | {
39
+ parse: (value: unknown) => T;
40
+ } | ((value: unknown) => {
41
+ success: boolean;
42
+ data?: T;
43
+ error?: any;
44
+ });
45
+ /**
46
+ * Infer output type from a schema validator.
47
+ */
48
+ export type InferValidatorOutput<V> = V extends {
49
+ '~standard': {
50
+ validate: (...args: any[]) => Promise<{
51
+ value?: infer T;
52
+ }> | {
53
+ value?: infer T;
54
+ };
55
+ };
56
+ } ? T : V extends {
57
+ safeParse: (...args: any[]) => {
58
+ success: true;
59
+ data: infer T;
60
+ } | {
61
+ success: false;
62
+ error: any;
63
+ };
64
+ } ? T : V extends {
65
+ parse: (...args: any[]) => infer T;
66
+ } ? T : V extends (value: unknown) => {
67
+ success: true;
68
+ data: infer T;
69
+ } ? T : any;
70
+ /**
71
+ * Infer request payload and response types from a yaxaEndpoint handler or config.
72
+ */
73
+ export type InferEndpoint<T> = T extends {
74
+ _yaxaConfig: {
75
+ schema?: {
76
+ body?: infer B;
77
+ query?: infer Q;
78
+ params?: infer P;
79
+ headers?: infer H;
80
+ };
81
+ handle: (...args: any[]) => infer R;
82
+ };
83
+ } ? {
84
+ body: [B] extends [never] ? undefined : InferValidatorOutput<B>;
85
+ query: [Q] extends [never] ? undefined : InferValidatorOutput<Q>;
86
+ params: [P] extends [never] ? undefined : InferValidatorOutput<P>;
87
+ headers: [H] extends [never] ? undefined : InferValidatorOutput<H>;
88
+ response: Awaited<R> extends Response ? unknown : Awaited<R>;
89
+ } : T extends (...args: any[]) => Promise<infer R> | infer R ? {
90
+ body: any;
91
+ query: any;
92
+ params: any;
93
+ headers: any;
94
+ response: Awaited<R> extends Response ? unknown : Awaited<R>;
95
+ } : {
96
+ body: any;
97
+ query: any;
98
+ params: any;
99
+ headers: any;
100
+ response: any;
101
+ };
102
+ /**
103
+ * Strong discriminated union result returned by apiClient calls.
104
+ */
105
+ export type ClientResponse<TData> = {
106
+ data: TData;
107
+ error: null;
108
+ response: Response;
109
+ status: number;
110
+ ok: true;
111
+ } | {
112
+ data: null;
113
+ error: ProblemDetails;
114
+ response: Response;
115
+ status: number;
116
+ ok: false;
117
+ };
118
+ /**
119
+ * Client request options passed to an endpoint method.
120
+ */
121
+ export interface ClientRequestOptions<TBody = unknown, TQuery = Record<string, any>, TParams = Record<string, any>> {
122
+ body?: TBody;
123
+ query?: TQuery;
124
+ params?: TParams;
125
+ headers?: HeadersInit;
126
+ signal?: AbortSignal;
127
+ fetch?: typeof fetch;
128
+ }
129
+ /**
130
+ * Helper to determine if an option object is required based on schema properties.
131
+ */
132
+ export type RequiredKeys<T> = {
133
+ [K in keyof T]-?: Record<string, never> extends Pick<T, K> ? never : K;
134
+ }[keyof T];
135
+ export type ClientMethodFn<TEndpoint> = TEndpoint extends never ? (options?: ClientRequestOptions) => Promise<ClientResponse<any>> : InferEndpoint<TEndpoint> extends infer Inferred ? Inferred extends {
136
+ body: infer B;
137
+ query: infer Q;
138
+ params: infer P;
139
+ response: infer R;
140
+ } ? (options?: {
141
+ body?: B;
142
+ query?: Q;
143
+ params?: P;
144
+ headers?: HeadersInit;
145
+ signal?: AbortSignal;
146
+ fetch?: typeof fetch;
147
+ }) => Promise<ClientResponse<R>> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
148
+ /**
149
+ * HTTP methods supported by a route definition.
150
+ */
151
+ export type RouteMethods<TRoute> = {
152
+ get: TRoute extends {
153
+ GET: infer H;
154
+ } ? ClientMethodFn<H> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
155
+ post: TRoute extends {
156
+ POST: infer H;
157
+ } ? ClientMethodFn<H> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
158
+ put: TRoute extends {
159
+ PUT: infer H;
160
+ } ? ClientMethodFn<H> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
161
+ delete: TRoute extends {
162
+ DELETE: infer H;
163
+ } ? ClientMethodFn<H> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
164
+ patch: TRoute extends {
165
+ PATCH: infer H;
166
+ } ? ClientMethodFn<H> : (options?: ClientRequestOptions) => Promise<ClientResponse<any>>;
167
+ };
168
+ /**
169
+ * Callable route proxy supporting path parameter interpolation.
170
+ * e.g. api['/api/projects/[id]']({ id: '123' }).get()
171
+ */
172
+ export type RouteProxy<TRoute> = RouteMethods<TRoute> & {
173
+ (params: Record<string, any>): RouteMethods<TRoute>;
174
+ };
175
+ /**
176
+ * Global configuration options for creating an API client.
177
+ */
178
+ export interface ApiClientConfig {
179
+ /**
180
+ * Base URL prefix for all requests (e.g. 'https://api.example.com' or '').
181
+ * Defaults to empty string (relative to current origin).
182
+ */
183
+ baseUrl?: string;
184
+ /**
185
+ * Custom fetch implementation (e.g. SvelteKit's event.fetch in load functions).
186
+ * Defaults to globalThis.fetch.
187
+ */
188
+ fetch?: typeof fetch;
189
+ /**
190
+ * Default headers to attach to every request.
191
+ */
192
+ headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
193
+ /**
194
+ * Interceptor hook called before every request.
195
+ */
196
+ onRequest?: (context: {
197
+ url: string;
198
+ options: RequestInit;
199
+ }) => void | Promise<void>;
200
+ /**
201
+ * Interceptor hook called on every response.
202
+ */
203
+ onResponse?: (context: {
204
+ response: Response;
205
+ data: any;
206
+ error: ProblemDetails | null;
207
+ }) => void | Promise<void>;
208
+ }
209
+ /**
210
+ * Dynamic Proxy type mapping paths to methods.
211
+ */
212
+ export type ApiClient<TRoutes = Record<string, any>> = {
213
+ [K in keyof TRoutes]: RouteProxy<TRoutes[K]>;
214
+ } & {
215
+ [path: string]: RouteProxy<any>;
216
+ } & {
217
+ get: <TData = any>(path: string, options?: ClientRequestOptions) => Promise<ClientResponse<TData>>;
218
+ post: <TData = any>(path: string, options?: ClientRequestOptions) => Promise<ClientResponse<TData>>;
219
+ put: <TData = any>(path: string, options?: ClientRequestOptions) => Promise<ClientResponse<TData>>;
220
+ delete: <TData = any>(path: string, options?: ClientRequestOptions) => Promise<ClientResponse<TData>>;
221
+ patch: <TData = any>(path: string, options?: ClientRequestOptions) => Promise<ClientResponse<TData>>;
222
+ };
@@ -0,0 +1 @@
1
+ export {};
package/dist/index.d.ts CHANGED
@@ -207,5 +207,7 @@ export { default as FeatureGrid, featureGridVariants } from './components/blocks
207
207
  export type { FeatureGridProps, FeatureItem } from './components/blocks/FeatureGrid.svelte';
208
208
  export { createMockSiteConfig, createMockUser, createTestWrapperProps } from './testing';
209
209
  export type { YaxaTestOptions } from './testing';
210
+ export { createApiClient, interpolatePath, serializeQueryParams, createQuery, createMutation, QueryClient, getQueryClient, setQueryClient, hashQueryKey } from './client';
211
+ export type { ApiClient, ApiClientConfig, ClientRequestOptions, ClientResponse, InferEndpoint, RouteMethods, ProblemDetails as ClientProblemDetails, QueryKey, QueryStatus, QueryCacheEntry, CreateQueryOptions, CreateQueryResult, CreateMutationOptions, CreateMutationResult, QueryFn, MutationFn } from './client';
210
212
  export { cn, tv } from './utils/cn';
211
213
  export type { VariantProps } from './utils/cn';
package/dist/index.js CHANGED
@@ -138,5 +138,7 @@ export { default as FAQ, faqVariants } from './components/blocks/FAQ.svelte';
138
138
  export { default as FeatureGrid, featureGridVariants } from './components/blocks/FeatureGrid.svelte';
139
139
  // Testing Utilities
140
140
  export { createMockSiteConfig, createMockUser, createTestWrapperProps } from './testing';
141
+ // Type-Safe Client RPC & Runes Query Engine
142
+ export { createApiClient, interpolatePath, serializeQueryParams, createQuery, createMutation, QueryClient, getQueryClient, setQueryClient, hashQueryKey } from './client';
141
143
  // Utilities
142
144
  export { cn, tv } from './utils/cn';
@@ -2,6 +2,6 @@ import type { RequestHandler } from '@sveltejs/kit';
2
2
  import type { ApiDocsOptions } from './types';
3
3
  /**
4
4
  * Creates a turnkey SvelteKit RequestHandler that generates an interactive OpenAPI 3.1 documentation
5
- * page (Scalar, Swagger UI, or Redoc) or returns raw OpenAPI 3.1 JSON when ?format=json is requested.
5
+ * page (Scalar or Swagger UI) or returns raw OpenAPI 3.1 JSON when ?format=json is requested.
6
6
  */
7
7
  export declare function createApiDocsHandler(options?: ApiDocsOptions): RequestHandler;
@@ -1,11 +1,35 @@
1
1
  import { generateOpenApiSpec } from './generator';
2
- function renderScalarHtml(specJson, title) {
2
+ function renderHeadMeta({ title, description, canonicalUrl, ogImage }) {
3
+ const descTag = description
4
+ ? `<meta name="description" content="${description.replace(/"/g, '&quot;')}" />`
5
+ : '';
6
+ const canonicalTag = canonicalUrl ? `<link rel="canonical" href="${canonicalUrl}" />` : '';
7
+ const ogImageTag = ogImage ? `<meta property="og:image" content="${ogImage}" />` : '';
8
+ const ogDescTag = description
9
+ ? `<meta property="og:description" content="${description.replace(/"/g, '&quot;')}" />`
10
+ : '';
11
+ const ogUrlTag = canonicalUrl ? `<meta property="og:url" content="${canonicalUrl}" />` : '';
12
+ return ` <title>${title}</title>
13
+ ${descTag}
14
+ <meta name="robots" content="index, follow" />
15
+ ${canonicalTag}
16
+ <meta property="og:type" content="website" />
17
+ <meta property="og:title" content="${title.replace(/"/g, '&quot;')}" />
18
+ ${ogDescTag}
19
+ ${ogUrlTag}
20
+ ${ogImageTag}
21
+ <meta name="twitter:card" content="summary_large_image" />
22
+ <meta name="twitter:title" content="${title.replace(/"/g, '&quot;')}" />
23
+ ${ogDescTag}
24
+ ${ogImageTag}`.trim();
25
+ }
26
+ function renderScalarHtml(specJson, meta) {
3
27
  return `<!doctype html>
4
28
  <html lang="en">
5
29
  <head>
6
30
  <meta charset="utf-8" />
7
31
  <meta name="viewport" content="width=device-width, initial-scale=1" />
8
- <title>${title}</title>
32
+ ${renderHeadMeta(meta)}
9
33
  <style>
10
34
  body { margin: 0; background-color: #0f172a; }
11
35
  </style>
@@ -18,13 +42,13 @@ function renderScalarHtml(specJson, title) {
18
42
  </body>
19
43
  </html>`;
20
44
  }
21
- function renderSwaggerHtml(specJson, title) {
45
+ function renderSwaggerHtml(specJson, meta) {
22
46
  return `<!DOCTYPE html>
23
47
  <html lang="en">
24
48
  <head>
25
49
  <meta charset="utf-8" />
26
50
  <meta name="viewport" content="width=device-width, initial-scale=1" />
27
- <title>${title}</title>
51
+ ${renderHeadMeta(meta)}
28
52
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css" />
29
53
  <style>
30
54
  body { margin: 0; background: #fafafa; }
@@ -48,34 +72,9 @@ function renderSwaggerHtml(specJson, title) {
48
72
  </body>
49
73
  </html>`;
50
74
  }
51
- function renderRedocHtml(specJson, title) {
52
- return `<!DOCTYPE html>
53
- <html lang="en">
54
- <head>
55
- <meta charset="utf-8" />
56
- <meta name="viewport" content="width=device-width, initial-scale=1" />
57
- <title>${title}</title>
58
- <style>
59
- body { margin: 0; padding: 0; }
60
- </style>
61
- </head>
62
- <body>
63
- <div id="redoc-container"></div>
64
- <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
65
- <script>
66
- Redoc.init(${specJson}, {
67
- scrollYOffset: 50,
68
- theme: {
69
- colors: { primary: { main: '#3b82f6' } }
70
- }
71
- }, document.getElementById('redoc-container'));
72
- </script>
73
- </body>
74
- </html>`;
75
- }
76
75
  /**
77
76
  * Creates a turnkey SvelteKit RequestHandler that generates an interactive OpenAPI 3.1 documentation
78
- * page (Scalar, Swagger UI, or Redoc) or returns raw OpenAPI 3.1 JSON when ?format=json is requested.
77
+ * page (Scalar or Swagger UI) or returns raw OpenAPI 3.1 JSON when ?format=json is requested.
79
78
  */
80
79
  export function createApiDocsHandler(options = {}) {
81
80
  const defaultTheme = options.theme || 'scalar';
@@ -83,7 +82,7 @@ export function createApiDocsHandler(options = {}) {
83
82
  const { url, request } = event;
84
83
  const format = url.searchParams.get('format');
85
84
  const themeQuery = url.searchParams.get('theme');
86
- const activeTheme = themeQuery && ['scalar', 'swagger', 'redoc'].includes(themeQuery) ? themeQuery : defaultTheme;
85
+ const activeTheme = themeQuery && ['scalar', 'swagger'].includes(themeQuery) ? themeQuery : defaultTheme;
87
86
  const acceptHeader = request.headers.get('accept') || '';
88
87
  const spec = generateOpenApiSpec(options);
89
88
  // If caller requests JSON via query param, accept header, or path ending in .json
@@ -99,16 +98,17 @@ export function createApiDocsHandler(options = {}) {
99
98
  }
100
99
  // Render Interactive HTML Docs
101
100
  const specJson = JSON.stringify(spec);
102
- let html;
103
- if (activeTheme === 'swagger') {
104
- html = renderSwaggerHtml(specJson, spec.info.title);
105
- }
106
- else if (activeTheme === 'redoc') {
107
- html = renderRedocHtml(specJson, spec.info.title);
108
- }
109
- else {
110
- html = renderScalarHtml(specJson, spec.info.title);
111
- }
101
+ const canonicalUrl = `${url.origin}${url.pathname}`;
102
+ const ogImage = `${url.origin}/api/og?title=${encodeURIComponent(spec.info.title)}&badge=API+Docs`;
103
+ const meta = {
104
+ title: spec.info.title,
105
+ description: spec.info.description,
106
+ canonicalUrl,
107
+ ogImage
108
+ };
109
+ const html = activeTheme === 'swagger'
110
+ ? renderSwaggerHtml(specJson, meta)
111
+ : renderScalarHtml(specJson, meta);
112
112
  return new Response(html, {
113
113
  headers: {
114
114
  'content-type': 'text/html; charset=utf-8',
@@ -200,21 +200,20 @@ describe('createApiDocsHandler Endpoint', () => {
200
200
  expect(html).toContain('swagger-ui-dist');
201
201
  expect(html).toContain('SwaggerUIBundle');
202
202
  });
203
- it('renders Redoc HTML when theme is redoc', async () => {
203
+ it('falls back to scalar HTML when an unrecognized theme query is passed', async () => {
204
204
  const handler = createApiDocsHandler({
205
- title: 'Redoc Docs Test',
206
- theme: 'redoc'
205
+ title: 'Fallback Docs Test',
206
+ theme: 'scalar'
207
207
  });
208
208
  const event = createMockRequestEvent({
209
- url: 'http://localhost:5173/api/docs'
209
+ url: 'http://localhost:5173/api/docs?theme=unknown'
210
210
  });
211
211
  const response = await handler(event);
212
212
  expect(response.status).toBe(200);
213
213
  expect(response.headers.get('content-type')).toContain('text/html');
214
214
  const html = await response.text();
215
- expect(html).toContain('<title>Redoc Docs Test</title>');
216
- expect(html).toContain('redoc.standalone.js');
217
- expect(html).toContain('redoc-container');
215
+ expect(html).toContain('<title>Fallback Docs Test</title>');
216
+ expect(html).toContain('@scalar/api-reference');
218
217
  });
219
218
  it('allows overriding theme dynamically via ?theme query parameter', async () => {
220
219
  const handler = createApiDocsHandler({
@@ -107,13 +107,12 @@ export interface GenerateOpenApiOptions {
107
107
  endpoints?: EndpointMap;
108
108
  registry?: any;
109
109
  }
110
- export type ApiDocsTheme = 'scalar' | 'swagger' | 'redoc';
110
+ export type ApiDocsTheme = 'scalar' | 'swagger';
111
111
  export interface ApiDocsOptions extends GenerateOpenApiOptions {
112
112
  /**
113
113
  * Interactive UI theme:
114
- * - 'scalar' (default): Modern, dark-mode native, high contrast developer reference.
114
+ * - 'scalar' (default): Modern, dark-mode native, high contrast developer reference with interactive runner.
115
115
  * - 'swagger': Classic Swagger UI with interactive Try-It-Out console.
116
- * - 'redoc': Clean 3-panel technical documentation format.
117
116
  */
118
117
  theme?: ApiDocsTheme;
119
118
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yaxa-svelte",
3
- "version": "2.5.0",
3
+ "version": "2.7.0",
4
4
  "description": "The Intuitive Svelte UI Library — Nuxt UI v4 equivalent for SvelteKit 2 & 3 & Svelte 5 with automated SEO, dynamic OpenGraph cards, sitemaps, robots.txt, and Tailwind CSS v4.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://yaxa.vercel.app",