@svadmin/core 0.70.0 → 0.72.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +21 -1
- package/src/create-hooks.svelte.ts +11 -1
- package/src/create-many-hooks.svelte.ts +11 -1
- package/src/delete-hooks.svelte.ts +11 -1
- package/src/delete-many-hooks.svelte.ts +11 -1
- package/src/domain-errors.ts +418 -0
- package/src/index.ts +53 -0
- package/src/inferencer-schema.ts +325 -0
- package/src/mock-provider.ts +307 -0
- package/src/resilience.ts +185 -0
- package/src/result.ts +99 -0
- package/src/update-hooks.svelte.ts +11 -1
- package/src/update-many-hooks.svelte.ts +11 -1
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @svadmin/inferencer-schema
|
|
3
|
+
*
|
|
4
|
+
* Infers ResourceDefinition + FieldDefinition[] from database column metadata
|
|
5
|
+
* (e.g. Supabase, PostgreSQL information_schema, Drizzle, Prisma)
|
|
6
|
+
* or JSON Schema / OpenAPI component definitions.
|
|
7
|
+
*/
|
|
8
|
+
import type { FieldDefinition, ResourceDefinition } from './types';
|
|
9
|
+
import type { InferResult, InferReviewWarning } from './inferencer';
|
|
10
|
+
import { generateResourceBundle } from './inferencer';
|
|
11
|
+
|
|
12
|
+
// ─── Database Column Types ───────────────────────────────────
|
|
13
|
+
|
|
14
|
+
export interface DatabaseColumnMeta {
|
|
15
|
+
name: string;
|
|
16
|
+
type: string;
|
|
17
|
+
nullable?: boolean;
|
|
18
|
+
isPrimary?: boolean;
|
|
19
|
+
defaultValue?: unknown;
|
|
20
|
+
isForeignKey?: boolean;
|
|
21
|
+
referencesResource?: string;
|
|
22
|
+
description?: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface InferFromDatabaseOptions {
|
|
26
|
+
primaryKey?: string;
|
|
27
|
+
label?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// ─── JSON Schema Types ───────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
export interface JSONSchemaProperty {
|
|
33
|
+
type?: string | string[];
|
|
34
|
+
format?: string;
|
|
35
|
+
title?: string;
|
|
36
|
+
description?: string;
|
|
37
|
+
enum?: unknown[];
|
|
38
|
+
items?: Record<string, unknown>;
|
|
39
|
+
default?: unknown;
|
|
40
|
+
properties?: Record<string, JSONSchemaProperty>;
|
|
41
|
+
required?: string[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface JSONSchemaInput {
|
|
45
|
+
title?: string;
|
|
46
|
+
description?: string;
|
|
47
|
+
type?: string;
|
|
48
|
+
properties?: Record<string, JSONSchemaProperty>;
|
|
49
|
+
required?: string[];
|
|
50
|
+
[key: string]: unknown;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ─── Helpers ─────────────────────────────────────────────────
|
|
54
|
+
|
|
55
|
+
function capitalize(s: string): string {
|
|
56
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function humanize(key: string): string {
|
|
60
|
+
return key
|
|
61
|
+
.replace(/_/g, ' ')
|
|
62
|
+
.replace(/([a-z])([A-Z])/g, '$1 $2')
|
|
63
|
+
.replace(/\b\w/g, c => c.toUpperCase());
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const RELATION_SUFFIXES = ['_id', 'Id', '_ID'];
|
|
67
|
+
|
|
68
|
+
/** SQL type families we can map without falling back to name heuristics. */
|
|
69
|
+
const RECOGNIZED_SQL_TYPES =
|
|
70
|
+
/(?:^|[\s_])(?:bool|boolean|int|integer|smallint|bigint|serial|bigserial|numeric|decimal|real|float|double|money|timestamp|timestamptz|date|time|json|jsonb|char|character|varchar|text|uuid|enum|string)(?=$|[\s_(])/;
|
|
71
|
+
|
|
72
|
+
function reviewConfidence(warnings: readonly InferReviewWarning[]): 'high' | 'medium' | 'low' {
|
|
73
|
+
if (warnings.length === 0) return 'high';
|
|
74
|
+
return warnings.some(warning => warning.code === 'mixed-types' || warning.code === 'nullable-field')
|
|
75
|
+
? 'low'
|
|
76
|
+
: 'medium';
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function isLikelyRelation(key: string): string | null {
|
|
80
|
+
for (const suffix of RELATION_SUFFIXES) {
|
|
81
|
+
if (key.endsWith(suffix)) {
|
|
82
|
+
const resource = key.slice(0, -suffix.length);
|
|
83
|
+
return resource.endsWith('s') ? resource : resource + 's';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ─── Database Column Inferencer ──────────────────────────────
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Infer ResourceDefinition and code bundle from database column metadata.
|
|
93
|
+
*/
|
|
94
|
+
export function inferFromDatabaseColumns(
|
|
95
|
+
resourceName: string,
|
|
96
|
+
columns: DatabaseColumnMeta[],
|
|
97
|
+
options: InferFromDatabaseOptions = {},
|
|
98
|
+
): InferResult {
|
|
99
|
+
const primaryKey = options.primaryKey ?? columns.find(c => c.isPrimary)?.name ?? 'id';
|
|
100
|
+
const label = options.label ?? capitalize(resourceName);
|
|
101
|
+
const fields: FieldDefinition[] = [];
|
|
102
|
+
const warnings: InferReviewWarning[] = [];
|
|
103
|
+
|
|
104
|
+
if (options.primaryKey === undefined && !columns.some(c => c.isPrimary)) {
|
|
105
|
+
warnings.push({
|
|
106
|
+
code: 'unconstrained-field',
|
|
107
|
+
message: `No primary key column detected; defaulted to "${primaryKey}". Verify the column list before shipping.`,
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
for (const col of columns) {
|
|
112
|
+
const rawType = (col.type ?? '').toLowerCase().replace(/\(.*\)/, '').trim();
|
|
113
|
+
let type: FieldDefinition['type'];
|
|
114
|
+
|
|
115
|
+
if (rawType !== '' && !RECOGNIZED_SQL_TYPES.test(rawType)) {
|
|
116
|
+
warnings.push({
|
|
117
|
+
code: 'unconstrained-field',
|
|
118
|
+
field: col.name,
|
|
119
|
+
message: `Column "${col.name}" has unrecognized SQL type "${col.type}"; field type was inferred from its name.`,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
if (col.isPrimary || col.name === primaryKey) {
|
|
124
|
+
type = /int|serial|numeric|decimal|float|bigint/.test(rawType) ? 'number' : 'text';
|
|
125
|
+
} else if (col.isForeignKey || col.referencesResource || isLikelyRelation(col.name)) {
|
|
126
|
+
type = 'relation';
|
|
127
|
+
} else if (/bool|boolean/.test(rawType)) {
|
|
128
|
+
type = 'boolean';
|
|
129
|
+
} else if (/int|integer|numeric|decimal|real|float|double|serial|bigint|smallint|money/.test(rawType)) {
|
|
130
|
+
type = 'number';
|
|
131
|
+
} else if (/timestamptz|timestamp|date|time/.test(rawType)) {
|
|
132
|
+
type = 'date';
|
|
133
|
+
} else if (/json|jsonb/.test(rawType)) {
|
|
134
|
+
type = 'json';
|
|
135
|
+
} else {
|
|
136
|
+
const lk = col.name.toLowerCase();
|
|
137
|
+
if (lk.includes('email')) type = 'email';
|
|
138
|
+
else if (lk.includes('phone') || lk.includes('tel') || lk.includes('mobile')) type = 'phone';
|
|
139
|
+
else if (lk.includes('url') || lk.includes('link') || lk.includes('website')) type = 'url';
|
|
140
|
+
else if (lk.includes('avatar') || lk.includes('image') || lk.includes('photo') || lk.includes('logo')) type = 'image';
|
|
141
|
+
else if (lk.includes('description') || lk.includes('content') || lk.includes('body') || lk.includes('summary') || /text|longtext/.test(rawType)) type = 'textarea';
|
|
142
|
+
else if (col.isForeignKey || isLikelyRelation(col.name)) type = 'relation';
|
|
143
|
+
else type = 'text';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const field: FieldDefinition = {
|
|
147
|
+
key: col.name,
|
|
148
|
+
label: humanize(col.name),
|
|
149
|
+
type,
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
if (col.description) {
|
|
153
|
+
field.description = col.description;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (col.isPrimary || col.name === primaryKey) {
|
|
157
|
+
field.showInCreate = false;
|
|
158
|
+
field.sortable = true;
|
|
159
|
+
field.filterable = true;
|
|
160
|
+
} else {
|
|
161
|
+
if (col.nullable === false && col.defaultValue === undefined) {
|
|
162
|
+
field.required = true;
|
|
163
|
+
}
|
|
164
|
+
if (col.defaultValue !== undefined) {
|
|
165
|
+
field.defaultValue = col.defaultValue;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (type === 'relation') {
|
|
170
|
+
const relTarget = col.referencesResource ?? isLikelyRelation(col.name);
|
|
171
|
+
if (relTarget) {
|
|
172
|
+
field.resource = relTarget;
|
|
173
|
+
}
|
|
174
|
+
if (!col.referencesResource) {
|
|
175
|
+
warnings.push({
|
|
176
|
+
code: 'heuristic-relation',
|
|
177
|
+
field: col.name,
|
|
178
|
+
message: `Relation target for "${col.name}" was inferred from its column name; confirm it points at the right resource.`,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
field.optionLabel = 'title';
|
|
182
|
+
field.sortable = true;
|
|
183
|
+
field.filterable = true;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
fields.push(field);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const resource: ResourceDefinition = {
|
|
190
|
+
name: resourceName,
|
|
191
|
+
label,
|
|
192
|
+
primaryKey,
|
|
193
|
+
fields,
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
const bundle = generateResourceBundle(resource);
|
|
197
|
+
bundle.review = {
|
|
198
|
+
needsReview: warnings.length > 0,
|
|
199
|
+
confidence: reviewConfidence(warnings),
|
|
200
|
+
sampleSize: columns.length,
|
|
201
|
+
warnings,
|
|
202
|
+
};
|
|
203
|
+
return bundle;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// ─── JSON Schema Inferencer ──────────────────────────────────
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Infer ResourceDefinition and code bundle from a JSON Schema / OpenAPI schema object.
|
|
210
|
+
*/
|
|
211
|
+
export function inferFromJSONSchema(
|
|
212
|
+
resourceName: string,
|
|
213
|
+
schema: JSONSchemaInput,
|
|
214
|
+
options: { primaryKey?: string; label?: string } = {},
|
|
215
|
+
): InferResult {
|
|
216
|
+
const primaryKey = options.primaryKey ?? 'id';
|
|
217
|
+
const label = options.label ?? schema.title ?? capitalize(resourceName);
|
|
218
|
+
const fields: FieldDefinition[] = [];
|
|
219
|
+
const warnings: InferReviewWarning[] = [];
|
|
220
|
+
const requiredSet = new Set(schema.required ?? []);
|
|
221
|
+
const properties = schema.properties ?? {};
|
|
222
|
+
|
|
223
|
+
if (Object.keys(properties).length === 0) {
|
|
224
|
+
warnings.push({
|
|
225
|
+
code: 'empty-sample',
|
|
226
|
+
message: 'Schema declares no properties; the generated resource has no fields.',
|
|
227
|
+
});
|
|
228
|
+
} else if (!Object.hasOwn(properties, primaryKey)) {
|
|
229
|
+
warnings.push({
|
|
230
|
+
code: 'unconstrained-field',
|
|
231
|
+
message: `Primary key "${primaryKey}" is not declared in the schema properties. Verify the identifier field before shipping.`,
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
for (const [key, prop] of Object.entries(properties)) {
|
|
236
|
+
const rawType = Array.isArray(prop.type) ? prop.type[0] : prop.type;
|
|
237
|
+
let type: FieldDefinition['type'];
|
|
238
|
+
let fieldOptions: { label: string; value: string | number }[] | undefined;
|
|
239
|
+
|
|
240
|
+
if (prop.enum && Array.isArray(prop.enum) && prop.enum.length > 0) {
|
|
241
|
+
type = 'select';
|
|
242
|
+
fieldOptions = prop.enum.map(val => ({ label: humanize(String(val)), value: val as string | number }));
|
|
243
|
+
} else if (rawType === 'boolean') {
|
|
244
|
+
type = 'boolean';
|
|
245
|
+
} else if (rawType === 'number' || rawType === 'integer') {
|
|
246
|
+
type = 'number';
|
|
247
|
+
} else if (rawType === 'array') {
|
|
248
|
+
const items = prop.items as { type?: string; format?: string } | undefined;
|
|
249
|
+
if (items?.type === 'string' && items.format === 'uri') {
|
|
250
|
+
type = 'images';
|
|
251
|
+
} else {
|
|
252
|
+
type = 'tags';
|
|
253
|
+
}
|
|
254
|
+
} else if (rawType === 'object') {
|
|
255
|
+
type = 'json';
|
|
256
|
+
} else {
|
|
257
|
+
if (prop.format === 'date-time' || prop.format === 'date') {
|
|
258
|
+
type = 'date';
|
|
259
|
+
} else if (prop.format === 'email') {
|
|
260
|
+
type = 'email';
|
|
261
|
+
} else if (prop.format === 'uri' || prop.format === 'url') {
|
|
262
|
+
type = 'url';
|
|
263
|
+
} else {
|
|
264
|
+
const lk = key.toLowerCase();
|
|
265
|
+
if (lk.includes('email')) type = 'email';
|
|
266
|
+
else if (lk.includes('phone') || lk.includes('tel') || lk.includes('mobile')) type = 'phone';
|
|
267
|
+
else if (lk.includes('url') || lk.includes('link') || lk.includes('website')) type = 'url';
|
|
268
|
+
else if (lk.includes('avatar') || lk.includes('image') || lk.includes('photo') || lk.includes('logo')) type = 'image';
|
|
269
|
+
else if (lk.includes('description') || lk.includes('content') || lk.includes('body') || lk.includes('summary')) type = 'textarea';
|
|
270
|
+
else if (isLikelyRelation(key)) type = 'relation';
|
|
271
|
+
else type = 'text';
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
const field: FieldDefinition = {
|
|
276
|
+
key,
|
|
277
|
+
label: prop.title || humanize(key),
|
|
278
|
+
type,
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
if (prop.description) field.description = prop.description;
|
|
282
|
+
if (requiredSet.has(key)) field.required = true;
|
|
283
|
+
if (prop.default !== undefined) field.defaultValue = prop.default;
|
|
284
|
+
if (fieldOptions) field.options = fieldOptions;
|
|
285
|
+
|
|
286
|
+
if (key === primaryKey) {
|
|
287
|
+
field.showInCreate = false;
|
|
288
|
+
field.sortable = true;
|
|
289
|
+
field.filterable = true;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
if (type === 'relation') {
|
|
293
|
+
const relTarget = isLikelyRelation(key);
|
|
294
|
+
if (relTarget) {
|
|
295
|
+
field.resource = relTarget;
|
|
296
|
+
}
|
|
297
|
+
warnings.push({
|
|
298
|
+
code: 'heuristic-relation',
|
|
299
|
+
field: key,
|
|
300
|
+
message: `Relation target for "${key}" was inferred from its property name; confirm it points at the right resource.`,
|
|
301
|
+
});
|
|
302
|
+
field.optionLabel = 'title';
|
|
303
|
+
field.sortable = true;
|
|
304
|
+
field.filterable = true;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
fields.push(field);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const resource: ResourceDefinition = {
|
|
311
|
+
name: resourceName,
|
|
312
|
+
label,
|
|
313
|
+
primaryKey,
|
|
314
|
+
fields,
|
|
315
|
+
};
|
|
316
|
+
|
|
317
|
+
const bundle = generateResourceBundle(resource);
|
|
318
|
+
bundle.review = {
|
|
319
|
+
needsReview: warnings.length > 0,
|
|
320
|
+
confidence: reviewConfidence(warnings),
|
|
321
|
+
sampleSize: Object.keys(properties).length,
|
|
322
|
+
warnings,
|
|
323
|
+
};
|
|
324
|
+
return bundle;
|
|
325
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @svadmin/mock-provider
|
|
3
|
+
*
|
|
4
|
+
* In-memory zero-configuration DataProvider for rapid prototyping,
|
|
5
|
+
* local testing, and offline Vibe Coding workflows.
|
|
6
|
+
*/
|
|
7
|
+
import type {
|
|
8
|
+
BaseRecord,
|
|
9
|
+
CreateParams,
|
|
10
|
+
CreateResult,
|
|
11
|
+
CreateManyParams,
|
|
12
|
+
CreateManyResult,
|
|
13
|
+
CustomParams,
|
|
14
|
+
CustomResult,
|
|
15
|
+
DataProvider,
|
|
16
|
+
DeleteManyParams,
|
|
17
|
+
DeleteManyResult,
|
|
18
|
+
DeleteParams,
|
|
19
|
+
DeleteResult,
|
|
20
|
+
GetListParams,
|
|
21
|
+
GetListResult,
|
|
22
|
+
GetManyParams,
|
|
23
|
+
GetManyResult,
|
|
24
|
+
GetOneParams,
|
|
25
|
+
GetOneResult,
|
|
26
|
+
UpdateManyParams,
|
|
27
|
+
UpdateManyResult,
|
|
28
|
+
UpdateParams,
|
|
29
|
+
UpdateResult,
|
|
30
|
+
} from './types';
|
|
31
|
+
import { HttpError } from './types';
|
|
32
|
+
import { matchClientFilter } from './client-filter';
|
|
33
|
+
|
|
34
|
+
export interface MockDataProviderOptions {
|
|
35
|
+
/** Optional initial data set by resource name */
|
|
36
|
+
initialData?: Record<string, BaseRecord[]>;
|
|
37
|
+
/** Primary key field name (default: 'id') */
|
|
38
|
+
idKey?: string;
|
|
39
|
+
/** Artificial latency in milliseconds (default: 0) */
|
|
40
|
+
latencyMs?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface MockDataProviderInstance extends DataProvider {
|
|
44
|
+
resetData(): void;
|
|
45
|
+
setData(resource: string, records: BaseRecord[]): void;
|
|
46
|
+
getData(resource: string): BaseRecord[];
|
|
47
|
+
getAllData(): Record<string, BaseRecord[]>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const DEFAULT_ENTERPRISE_DATA: Record<string, BaseRecord[]> = {
|
|
51
|
+
users: [
|
|
52
|
+
{ id: 1, name: 'Alice Chen', email: 'alice@example.com', role: 'admin', active: true, createdAt: '2026-01-15T08:00:00Z' },
|
|
53
|
+
{ id: 2, name: 'Bob Smith', email: 'bob@example.com', role: 'editor', active: true, createdAt: '2026-02-10T09:30:00Z' },
|
|
54
|
+
{ id: 3, name: 'Carol Danvers', email: 'carol@example.com', role: 'viewer', active: false, createdAt: '2026-03-01T14:15:00Z' },
|
|
55
|
+
{ id: 4, name: 'David Miller', email: 'david@example.com', role: 'editor', active: true, createdAt: '2026-04-12T11:00:00Z' },
|
|
56
|
+
],
|
|
57
|
+
posts: [
|
|
58
|
+
{ id: 1, title: 'Getting Started with svadmin', status: 'published', authorId: 1, views: 1250, createdAt: '2026-02-01T10:00:00Z' },
|
|
59
|
+
{ id: 2, title: 'Vibe Coding with AI Agents', status: 'published', authorId: 2, views: 3420, createdAt: '2026-02-15T15:20:00Z' },
|
|
60
|
+
{ id: 3, title: 'Architectural Guardrails in Production', status: 'draft', authorId: 1, views: 0, createdAt: '2026-03-05T08:45:00Z' },
|
|
61
|
+
{ id: 4, title: 'Building Self-Healing Admin Systems', status: 'published', authorId: 4, views: 890, createdAt: '2026-03-20T16:10:00Z' },
|
|
62
|
+
{ id: 5, title: 'Declarative UI Patterns for 2026', status: 'draft', authorId: 2, views: 0, createdAt: '2026-04-02T13:00:00Z' },
|
|
63
|
+
],
|
|
64
|
+
orders: [
|
|
65
|
+
{ id: 'ORD-1001', customer: 'Acme Corp', amount: 4999.00, status: 'completed', createdAt: '2026-03-10T12:00:00Z' },
|
|
66
|
+
{ id: 'ORD-1002', customer: 'Global Tech', amount: 1250.50, status: 'pending', createdAt: '2026-03-12T09:15:00Z' },
|
|
67
|
+
{ id: 'ORD-1003', customer: 'Nexus Ltd', amount: 890.00, status: 'completed', createdAt: '2026-03-14T14:30:00Z' },
|
|
68
|
+
{ id: 'ORD-1004', customer: 'Starlight Inc', amount: 15400.00, status: 'processing', createdAt: '2026-03-18T17:45:00Z' },
|
|
69
|
+
],
|
|
70
|
+
audit_logs: [
|
|
71
|
+
{ id: 1, action: 'LOGIN', userId: 1, ip: '192.168.1.10', timestamp: '2026-04-01T08:00:00Z' },
|
|
72
|
+
{ id: 2, action: 'UPDATE_POST', userId: 2, ip: '192.168.1.15', timestamp: '2026-04-01T08:30:00Z' },
|
|
73
|
+
{ id: 3, action: 'EXPORT_ORDERS', userId: 1, ip: '192.168.1.10', timestamp: '2026-04-01T09:15:00Z' },
|
|
74
|
+
],
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
function deepClone<T>(obj: T): T {
|
|
78
|
+
return JSON.parse(JSON.stringify(obj));
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Creates an in-memory mock data provider with enterprise defaults and zero backend dependencies.
|
|
83
|
+
*/
|
|
84
|
+
export function createMockDataProvider(options: MockDataProviderOptions = {}): MockDataProviderInstance {
|
|
85
|
+
const idKey = options.idKey ?? 'id';
|
|
86
|
+
const latencyMs = options.latencyMs ?? 0;
|
|
87
|
+
const initial = options.initialData
|
|
88
|
+
? deepClone(options.initialData)
|
|
89
|
+
: deepClone(DEFAULT_ENTERPRISE_DATA);
|
|
90
|
+
|
|
91
|
+
let store: Record<string, BaseRecord[]> = deepClone(initial);
|
|
92
|
+
|
|
93
|
+
const delay = async () => {
|
|
94
|
+
if (latencyMs > 0) {
|
|
95
|
+
await new Promise(resolve => setTimeout(resolve, latencyMs));
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const getCollection = (resource: string): BaseRecord[] => {
|
|
100
|
+
if (!store[resource]) {
|
|
101
|
+
store[resource] = [];
|
|
102
|
+
}
|
|
103
|
+
return store[resource];
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
getApiUrl: () => 'mock://local',
|
|
108
|
+
|
|
109
|
+
getList: async <TData extends BaseRecord = BaseRecord>(params: GetListParams): Promise<GetListResult<TData>> => {
|
|
110
|
+
await delay();
|
|
111
|
+
let records = [...getCollection(params.resource)];
|
|
112
|
+
|
|
113
|
+
// 1. Filters
|
|
114
|
+
if (params.filters && params.filters.length > 0) {
|
|
115
|
+
for (const filter of params.filters) {
|
|
116
|
+
records = records.filter(item => matchClientFilter(item, filter));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// 2. Sorters
|
|
121
|
+
const sorters = params.sorters ?? [];
|
|
122
|
+
if (sorters.length > 0) {
|
|
123
|
+
records.sort((a, b) => {
|
|
124
|
+
for (const sorter of sorters) {
|
|
125
|
+
const valA = a[sorter.field];
|
|
126
|
+
const valB = b[sorter.field];
|
|
127
|
+
if (valA === valB) continue;
|
|
128
|
+
if (valA === undefined || valA === null) return 1;
|
|
129
|
+
if (valB === undefined || valB === null) return -1;
|
|
130
|
+
|
|
131
|
+
const order = sorter.order === 'desc' ? -1 : 1;
|
|
132
|
+
if (typeof valA === 'number' && typeof valB === 'number') {
|
|
133
|
+
return (valA - valB) * order;
|
|
134
|
+
}
|
|
135
|
+
return String(valA).localeCompare(String(valB)) * order;
|
|
136
|
+
}
|
|
137
|
+
return 0;
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const total = records.length;
|
|
142
|
+
|
|
143
|
+
// 3. Pagination
|
|
144
|
+
const current = params.pagination?.current ?? 1;
|
|
145
|
+
const pageSize = params.pagination?.pageSize ?? 10;
|
|
146
|
+
const start = (current - 1) * pageSize;
|
|
147
|
+
const paginated = records.slice(start, start + pageSize);
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
data: deepClone(paginated) as TData[],
|
|
151
|
+
total,
|
|
152
|
+
};
|
|
153
|
+
},
|
|
154
|
+
|
|
155
|
+
getOne: async <TData extends BaseRecord = BaseRecord>(params: GetOneParams): Promise<GetOneResult<TData>> => {
|
|
156
|
+
await delay();
|
|
157
|
+
const records = getCollection(params.resource);
|
|
158
|
+
const record = records.find(r => String(r[idKey]) === String(params.id));
|
|
159
|
+
if (!record) {
|
|
160
|
+
throw new HttpError(`Record ${params.id} not found in ${params.resource}`, 404);
|
|
161
|
+
}
|
|
162
|
+
return { data: deepClone(record) as TData };
|
|
163
|
+
},
|
|
164
|
+
|
|
165
|
+
getMany: async <TData extends BaseRecord = BaseRecord>(params: GetManyParams): Promise<GetManyResult<TData>> => {
|
|
166
|
+
await delay();
|
|
167
|
+
const records = getCollection(params.resource);
|
|
168
|
+
const idSet = new Set(params.ids.map(id => String(id)));
|
|
169
|
+
const matching = records.filter(r => idSet.has(String(r[idKey])));
|
|
170
|
+
return { data: deepClone(matching) as TData[] };
|
|
171
|
+
},
|
|
172
|
+
|
|
173
|
+
create: async <TData extends BaseRecord = BaseRecord>(params: CreateParams): Promise<CreateResult<TData>> => {
|
|
174
|
+
await delay();
|
|
175
|
+
const records = getCollection(params.resource);
|
|
176
|
+
const payload = { ...(params.variables as BaseRecord) };
|
|
177
|
+
|
|
178
|
+
if (payload[idKey] === undefined) {
|
|
179
|
+
// Auto assign ID
|
|
180
|
+
const numericIds = records
|
|
181
|
+
.map(r => Number(r[idKey]))
|
|
182
|
+
.filter(id => !isNaN(id));
|
|
183
|
+
payload[idKey] = numericIds.length > 0 ? Math.max(...numericIds) + 1 : records.length + 1;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
records.push(payload);
|
|
187
|
+
return { data: deepClone(payload) as TData };
|
|
188
|
+
},
|
|
189
|
+
|
|
190
|
+
createMany: async <TData extends BaseRecord = BaseRecord>(params: CreateManyParams): Promise<CreateManyResult<TData>> => {
|
|
191
|
+
await delay();
|
|
192
|
+
const records = getCollection(params.resource);
|
|
193
|
+
const created: BaseRecord[] = [];
|
|
194
|
+
|
|
195
|
+
for (const raw of params.variables) {
|
|
196
|
+
const payload = { ...(raw as BaseRecord) };
|
|
197
|
+
if (payload[idKey] === undefined) {
|
|
198
|
+
const numericIds = [...records, ...created]
|
|
199
|
+
.map(r => Number(r[idKey]))
|
|
200
|
+
.filter(id => !isNaN(id));
|
|
201
|
+
payload[idKey] = numericIds.length > 0 ? Math.max(...numericIds) + 1 : records.length + created.length + 1;
|
|
202
|
+
}
|
|
203
|
+
created.push(payload);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
records.push(...created);
|
|
207
|
+
return { data: deepClone(created) as TData[] };
|
|
208
|
+
},
|
|
209
|
+
|
|
210
|
+
update: async <TData extends BaseRecord = BaseRecord>(params: UpdateParams): Promise<UpdateResult<TData>> => {
|
|
211
|
+
await delay();
|
|
212
|
+
const records = getCollection(params.resource);
|
|
213
|
+
const index = records.findIndex(r => String(r[idKey]) === String(params.id));
|
|
214
|
+
const existing = records[index];
|
|
215
|
+
if (index === -1 || !existing) {
|
|
216
|
+
throw new HttpError(`Record ${params.id} not found in ${params.resource}`, 404);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const updatedRecord = {
|
|
220
|
+
...existing,
|
|
221
|
+
...(params.variables as BaseRecord),
|
|
222
|
+
[idKey]: existing[idKey], // Preserve original id
|
|
223
|
+
};
|
|
224
|
+
records[index] = updatedRecord;
|
|
225
|
+
|
|
226
|
+
return { data: deepClone(updatedRecord) as TData };
|
|
227
|
+
},
|
|
228
|
+
|
|
229
|
+
updateMany: async <TData extends BaseRecord = BaseRecord>(params: UpdateManyParams): Promise<UpdateManyResult<TData>> => {
|
|
230
|
+
await delay();
|
|
231
|
+
const records = getCollection(params.resource);
|
|
232
|
+
const idSet = new Set(params.ids.map(id => String(id)));
|
|
233
|
+
const updated: BaseRecord[] = [];
|
|
234
|
+
|
|
235
|
+
for (let i = 0; i < records.length; i++) {
|
|
236
|
+
const item = records[i];
|
|
237
|
+
if (item && idSet.has(String(item[idKey]))) {
|
|
238
|
+
const updatedItem = {
|
|
239
|
+
...item,
|
|
240
|
+
...(params.variables as BaseRecord),
|
|
241
|
+
[idKey]: item[idKey],
|
|
242
|
+
};
|
|
243
|
+
records[i] = updatedItem;
|
|
244
|
+
updated.push(updatedItem);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return { data: deepClone(updated) as TData[] };
|
|
249
|
+
},
|
|
250
|
+
|
|
251
|
+
deleteOne: async <TData extends BaseRecord = BaseRecord>(params: DeleteParams): Promise<DeleteResult<TData>> => {
|
|
252
|
+
await delay();
|
|
253
|
+
const records = getCollection(params.resource);
|
|
254
|
+
const index = records.findIndex(r => String(r[idKey]) === String(params.id));
|
|
255
|
+
if (index === -1) {
|
|
256
|
+
throw new HttpError(`Record ${params.id} not found in ${params.resource}`, 404);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const [deleted] = records.splice(index, 1);
|
|
260
|
+
return { data: deepClone(deleted) as TData };
|
|
261
|
+
},
|
|
262
|
+
|
|
263
|
+
deleteMany: async <TData extends BaseRecord = BaseRecord>(params: DeleteManyParams): Promise<DeleteManyResult<TData>> => {
|
|
264
|
+
await delay();
|
|
265
|
+
const records = getCollection(params.resource);
|
|
266
|
+
const idSet = new Set(params.ids.map(id => String(id)));
|
|
267
|
+
const deleted: BaseRecord[] = [];
|
|
268
|
+
|
|
269
|
+
store[params.resource] = records.filter(r => {
|
|
270
|
+
if (idSet.has(String(r[idKey]))) {
|
|
271
|
+
deleted.push(r);
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
274
|
+
return true;
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
return { data: deepClone(deleted) as TData[] };
|
|
278
|
+
},
|
|
279
|
+
|
|
280
|
+
custom: async <TData = unknown>(params: CustomParams): Promise<CustomResult<TData>> => {
|
|
281
|
+
await delay();
|
|
282
|
+
return {
|
|
283
|
+
data: {
|
|
284
|
+
url: params.url,
|
|
285
|
+
method: params.method,
|
|
286
|
+
ok: true,
|
|
287
|
+
} as unknown as TData,
|
|
288
|
+
};
|
|
289
|
+
},
|
|
290
|
+
|
|
291
|
+
resetData: () => {
|
|
292
|
+
store = deepClone(initial);
|
|
293
|
+
},
|
|
294
|
+
|
|
295
|
+
setData: (resource: string, records: BaseRecord[]) => {
|
|
296
|
+
store[resource] = deepClone(records);
|
|
297
|
+
},
|
|
298
|
+
|
|
299
|
+
getData: (resource: string) => {
|
|
300
|
+
return deepClone(store[resource] ?? []);
|
|
301
|
+
},
|
|
302
|
+
|
|
303
|
+
getAllData: () => {
|
|
304
|
+
return deepClone(store);
|
|
305
|
+
},
|
|
306
|
+
};
|
|
307
|
+
}
|