@svadmin/core 0.69.3 → 0.71.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 +13 -1
- package/src/client-filter.ts +77 -0
- package/src/editable-table.ts +28 -3
- package/src/index.ts +11 -2
- package/src/inferencer-schema.ts +325 -0
- package/src/infinite-query.svelte.ts +45 -17
- package/src/mock-provider.ts +307 -0
- package/src/provider-bundle.ts +0 -25
- package/src/provider-filter-capabilities.ts +111 -0
- package/src/query-hooks.svelte.ts +68 -37
- package/src/query-options.ts +36 -7
- package/src/select-options.ts +14 -2
- package/src/select-query.svelte.ts +48 -12
- package/src/strict-hooks.svelte.ts +46 -17
- package/src/table-hooks.svelte.ts +22 -72
- package/src/table-state.svelte.ts +4 -3
- package/src/url-sync.ts +71 -14
- package/src/utility-hooks.svelte.ts +1 -19
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@svadmin/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.71.0",
|
|
4
4
|
"author": "zuohuadong",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -59,6 +59,10 @@
|
|
|
59
59
|
"types": "./src/defined-options.ts",
|
|
60
60
|
"default": "./src/defined-options.ts"
|
|
61
61
|
},
|
|
62
|
+
"./provider-filters": {
|
|
63
|
+
"types": "./src/provider-filter-capabilities.ts",
|
|
64
|
+
"default": "./src/provider-filter-capabilities.ts"
|
|
65
|
+
},
|
|
62
66
|
"./resource-contract": {
|
|
63
67
|
"types": "./src/resource-contract.ts",
|
|
64
68
|
"default": "./src/resource-contract.ts"
|
|
@@ -103,6 +107,14 @@
|
|
|
103
107
|
"types": "./src/inferencer.ts",
|
|
104
108
|
"default": "./src/inferencer.ts"
|
|
105
109
|
},
|
|
110
|
+
"./inferencer-schema": {
|
|
111
|
+
"types": "./src/inferencer-schema.ts",
|
|
112
|
+
"default": "./src/inferencer-schema.ts"
|
|
113
|
+
},
|
|
114
|
+
"./mock-provider": {
|
|
115
|
+
"types": "./src/mock-provider.ts",
|
|
116
|
+
"default": "./src/mock-provider.ts"
|
|
117
|
+
},
|
|
106
118
|
"./inferencer-openapi": {
|
|
107
119
|
"types": "./src/inferencer-openapi.ts",
|
|
108
120
|
"default": "./src/inferencer-openapi.ts"
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { Filter } from './types';
|
|
2
|
+
|
|
3
|
+
function textHit(value: string, expected: string, mode: 'includes' | 'starts' | 'ends', sensitive: boolean): boolean {
|
|
4
|
+
const left = sensitive ? value : value.toLowerCase();
|
|
5
|
+
const right = sensitive ? expected : expected.toLowerCase();
|
|
6
|
+
if (mode === 'includes') return left.includes(right);
|
|
7
|
+
if (mode === 'starts') return left.startsWith(right);
|
|
8
|
+
return left.endsWith(right);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function textOperator(
|
|
12
|
+
value: unknown,
|
|
13
|
+
expected: unknown,
|
|
14
|
+
mode: 'includes' | 'starts' | 'ends',
|
|
15
|
+
sensitive: boolean,
|
|
16
|
+
negate: boolean,
|
|
17
|
+
): boolean {
|
|
18
|
+
if (typeof value !== 'string' || typeof expected !== 'string') return false;
|
|
19
|
+
const hit = textHit(value, expected, mode, sensitive);
|
|
20
|
+
return negate ? !hit : hit;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** 客户端表格筛选。带 s 的字符串运算符区分大小写,不带 s 的不区分。 */
|
|
24
|
+
export function matchClientFilter(item: Record<string, unknown>, filter: Filter): boolean {
|
|
25
|
+
if (!('field' in filter)) {
|
|
26
|
+
if (filter.operator === 'and') return filter.value.every((child) => matchClientFilter(item, child));
|
|
27
|
+
if (filter.operator === 'or') return filter.value.length === 0 || filter.value.some((child) => matchClientFilter(item, child));
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
const value = item[filter.field];
|
|
31
|
+
const expected = filter.value;
|
|
32
|
+
switch (filter.operator) {
|
|
33
|
+
case 'null': return value == null;
|
|
34
|
+
case 'nnull': return value != null;
|
|
35
|
+
default: break;
|
|
36
|
+
}
|
|
37
|
+
if (expected == null || expected === '') return true;
|
|
38
|
+
switch (filter.operator) {
|
|
39
|
+
case 'eq': return value == expected;
|
|
40
|
+
case 'ne': return value != expected;
|
|
41
|
+
case 'eqs': return Object.is(value, expected);
|
|
42
|
+
case 'nes': return !Object.is(value, expected);
|
|
43
|
+
case 'lt': return typeof value === 'number' && typeof expected === 'number' && value < expected;
|
|
44
|
+
case 'gt': return typeof value === 'number' && typeof expected === 'number' && value > expected;
|
|
45
|
+
case 'lte': return typeof value === 'number' && typeof expected === 'number' && value <= expected;
|
|
46
|
+
case 'gte': return typeof value === 'number' && typeof expected === 'number' && value >= expected;
|
|
47
|
+
case 'in': return !Array.isArray(expected) || expected.length === 0 || expected.includes(value);
|
|
48
|
+
case 'nin': return !Array.isArray(expected) || expected.length === 0 || !expected.includes(value);
|
|
49
|
+
case 'ina': return Array.isArray(value) && Array.isArray(expected) && expected.every((entry) => value.includes(entry));
|
|
50
|
+
case 'nina': return Array.isArray(value) && Array.isArray(expected) && expected.some((entry) => !value.includes(entry));
|
|
51
|
+
case 'contains': return textOperator(value, expected, 'includes', false, false);
|
|
52
|
+
case 'ncontains': return textOperator(value, expected, 'includes', false, true);
|
|
53
|
+
case 'containss': return textOperator(value, expected, 'includes', true, false);
|
|
54
|
+
case 'ncontainss': return textOperator(value, expected, 'includes', true, true);
|
|
55
|
+
case 'startswith': return textOperator(value, expected, 'starts', false, false);
|
|
56
|
+
case 'nstartswith': return textOperator(value, expected, 'starts', false, true);
|
|
57
|
+
case 'startswiths': return textOperator(value, expected, 'starts', true, false);
|
|
58
|
+
case 'nstartswiths': return textOperator(value, expected, 'starts', true, true);
|
|
59
|
+
case 'endswith': return textOperator(value, expected, 'ends', false, false);
|
|
60
|
+
case 'nendswith': return textOperator(value, expected, 'ends', false, true);
|
|
61
|
+
case 'endswiths': return textOperator(value, expected, 'ends', true, false);
|
|
62
|
+
case 'nendswiths': return textOperator(value, expected, 'ends', true, true);
|
|
63
|
+
case 'between': {
|
|
64
|
+
if (!Array.isArray(expected) || expected.length !== 2) return true;
|
|
65
|
+
const [min, max] = expected;
|
|
66
|
+
return typeof value === 'number' && typeof min === 'number' && typeof max === 'number'
|
|
67
|
+
&& value >= min && value <= max;
|
|
68
|
+
}
|
|
69
|
+
case 'nbetween': {
|
|
70
|
+
if (!Array.isArray(expected) || expected.length !== 2) return true;
|
|
71
|
+
const [min, max] = expected;
|
|
72
|
+
return typeof value === 'number' && typeof min === 'number' && typeof max === 'number'
|
|
73
|
+
&& (value < min || value > max);
|
|
74
|
+
}
|
|
75
|
+
default: return true;
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/editable-table.ts
CHANGED
|
@@ -28,20 +28,26 @@ export function resolveEditableTableQuery(
|
|
|
28
28
|
url?: {
|
|
29
29
|
page?: number;
|
|
30
30
|
pageSize?: number;
|
|
31
|
+
sorters?: Sort[];
|
|
31
32
|
sortField?: string;
|
|
32
33
|
sortOrder?: 'asc' | 'desc';
|
|
33
34
|
filters?: Filter[];
|
|
34
35
|
},
|
|
35
36
|
): Pick<EditableTableQuery, 'pagination' | 'sorters' | 'filters'> {
|
|
36
37
|
const synced = options.syncWithLocation === true;
|
|
38
|
+
const syncedSorters = url?.sorters?.length
|
|
39
|
+
? url.sorters
|
|
40
|
+
: url?.sortField
|
|
41
|
+
? [{ field: url.sortField, order: url.sortOrder ?? 'asc' }]
|
|
42
|
+
: undefined;
|
|
37
43
|
return {
|
|
38
44
|
pagination: {
|
|
39
45
|
...options.pagination,
|
|
40
46
|
current: synced ? url?.page ?? options.pagination?.current ?? 1 : options.pagination?.current ?? 1,
|
|
41
47
|
pageSize: synced ? url?.pageSize ?? options.pagination?.pageSize ?? 50 : options.pagination?.pageSize ?? 50,
|
|
42
48
|
},
|
|
43
|
-
...(synced &&
|
|
44
|
-
? { sorters:
|
|
49
|
+
...(synced && syncedSorters
|
|
50
|
+
? { sorters: syncedSorters }
|
|
45
51
|
: options.sorters ? { sorters: options.sorters } : {}),
|
|
46
52
|
...((synced ? url?.filters ?? options.filters : options.filters) ? {
|
|
47
53
|
filters: synced ? url?.filters ?? options.filters : options.filters,
|
|
@@ -49,6 +55,22 @@ export function resolveEditableTableQuery(
|
|
|
49
55
|
};
|
|
50
56
|
}
|
|
51
57
|
|
|
58
|
+
function assertBatchReceipt(ids: readonly (string | number)[], records: readonly Record<string, unknown>[]): void {
|
|
59
|
+
const expected = new Set(ids.map((id) => String(id)));
|
|
60
|
+
if (expected.size !== ids.length || records.length !== ids.length) {
|
|
61
|
+
throw new Error('Batch update response did not match the requested records');
|
|
62
|
+
}
|
|
63
|
+
const seen = new Set<string>();
|
|
64
|
+
for (const record of records) {
|
|
65
|
+
const id = record['id'];
|
|
66
|
+
const key = typeof id === 'string' || typeof id === 'number' ? String(id) : '';
|
|
67
|
+
if (!key || !expected.has(key) || seen.has(key)) {
|
|
68
|
+
throw new Error('Batch update response did not match the requested records');
|
|
69
|
+
}
|
|
70
|
+
seen.add(key);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
52
74
|
function retryAttempts(retry: boolean | number | undefined): number {
|
|
53
75
|
if (retry === true) return 4;
|
|
54
76
|
if (typeof retry === 'number' && Number.isInteger(retry) && retry > 0 && retry <= 10) return retry + 1;
|
|
@@ -282,7 +304,10 @@ export function createEditableTableController(
|
|
|
282
304
|
try {
|
|
283
305
|
if (provider.updateMany) {
|
|
284
306
|
const result = await provider.updateMany({ resource: contract.name, ids, variables });
|
|
285
|
-
|
|
307
|
+
const records = Array.isArray(result?.data) ? result.data : undefined;
|
|
308
|
+
if (!records) throw new Error('Batch update response did not match the requested records');
|
|
309
|
+
const parsed = records.map((record) => parseContractRecord(contract, record));
|
|
310
|
+
assertBatchReceipt(ids, parsed);
|
|
286
311
|
} else {
|
|
287
312
|
for (const id of ids) {
|
|
288
313
|
const result = await provider.update({ resource: contract.name, id, variables });
|
package/src/index.ts
CHANGED
|
@@ -18,9 +18,7 @@ export {
|
|
|
18
18
|
createProviderBundle,
|
|
19
19
|
createTenantCacheKey,
|
|
20
20
|
defaultTenantAdapter,
|
|
21
|
-
appendTenantCacheKey,
|
|
22
21
|
isTenantCacheKey,
|
|
23
|
-
queryKeyMatchesTenant,
|
|
24
22
|
resolveTenantProviderMeta,
|
|
25
23
|
withProviderMeta,
|
|
26
24
|
withTenantDataProvider,
|
|
@@ -226,6 +224,13 @@ export { checkError } from './hook-utils.svelte';
|
|
|
226
224
|
export type { NotificationConfig, OvertimeOptions, OvertimeResult, LiveSubscriptionParams } from './hook-utils.svelte';
|
|
227
225
|
|
|
228
226
|
export { CRUD_FIELD_OPERATORS, DeleteManyPartialError, HttpError, UndoError, isCrudFieldOperator } from './types';
|
|
227
|
+
export {
|
|
228
|
+
FILTER_PROVIDER_IDS,
|
|
229
|
+
PROVIDER_FILTER_CAPABILITIES,
|
|
230
|
+
assertFiltersExecutable,
|
|
231
|
+
providerSupportsOperator,
|
|
232
|
+
} from './provider-filter-capabilities';
|
|
233
|
+
export type { FilterProviderId, ProviderFilterCapability } from './provider-filter-capabilities';
|
|
229
234
|
export { withResourceSchemas } from './resource-schemas';
|
|
230
235
|
export type { ResourceSchemas, ResourceSchemaMap, InferSchemaResourceMap, InferSchemaInputMap } from './resource-schemas';
|
|
231
236
|
export type {
|
|
@@ -328,12 +333,16 @@ export {
|
|
|
328
333
|
generateResourceBundle,
|
|
329
334
|
} from './inferencer';
|
|
330
335
|
export type { InferResult, InferReview, InferReviewWarning, InferReviewWarningCode } from './inferencer';
|
|
336
|
+
export { createMockDataProvider } from './mock-provider';
|
|
337
|
+
export type { MockDataProviderOptions, MockDataProviderInstance } from './mock-provider';
|
|
331
338
|
export { createWebSocketLiveProvider } from './live-websocket';
|
|
332
339
|
export type { WebSocketLiveProviderOptions } from './live-websocket';
|
|
333
340
|
export { createSSELiveProvider } from './live-sse';
|
|
334
341
|
export type { SSELiveProviderOptions } from './live-sse';
|
|
335
342
|
export { inferFromOpenAPI } from './inferencer-openapi';
|
|
336
343
|
export type { InferFromOpenAPIOptions } from './inferencer-openapi';
|
|
344
|
+
export { inferFromDatabaseColumns, inferFromJSONSchema } from './inferencer-schema';
|
|
345
|
+
export type { DatabaseColumnMeta, InferFromDatabaseOptions, JSONSchemaInput, JSONSchemaProperty } from './inferencer-schema';
|
|
337
346
|
export { inferFromGraphQL, GRAPHQL_INTROSPECTION_QUERY } from './inferencer-graphql';
|
|
338
347
|
export type { InferFromGraphQLOptions, GraphQLIntrospectionSchema, GraphQLTypeDescriptor } from './inferencer-graphql';
|
|
339
348
|
export {
|
|
@@ -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
|
+
}
|
|
@@ -10,6 +10,7 @@ import { createOvertimeTracker, createLiveSubscription, type NotificationConfig,
|
|
|
10
10
|
type LiveSubscriptionParams } from './hook-utils.svelte';
|
|
11
11
|
import { HttpError, type BaseRecord, type GetListResult, type Pagination, type Sort, type Filter, type KnownResources } from './types';
|
|
12
12
|
import { decodeBaseRecord, decodeListResult, rejectProviderResponse, type RecordDecoder } from './record-decoder';
|
|
13
|
+
import { listQuerySettings, type ResourceQueryOptions } from './query-options';
|
|
13
14
|
import { captureQueryProvider, snapshotListParams } from './query-snapshot';
|
|
14
15
|
import type { LiveMode, LiveEvent } from './live.svelte';
|
|
15
16
|
import type { QueryKey } from './query-keys';
|
|
@@ -19,14 +20,19 @@ import {
|
|
|
19
20
|
createQuerySession, createQueryResultView, pendingQueryResult, querySessionError, supersededQuerySession,
|
|
20
21
|
} from './query-session.svelte';
|
|
21
22
|
|
|
22
|
-
export
|
|
23
|
+
export type InfinitePages<T extends BaseRecord> = InfiniteData<GetListResult<T>, number>;
|
|
24
|
+
|
|
25
|
+
export interface UseInfiniteListOptions<
|
|
26
|
+
TData extends BaseRecord = BaseRecord,
|
|
27
|
+
TSelected = InfinitePages<TData>,
|
|
28
|
+
> extends ContractOptions {
|
|
23
29
|
resource?: KnownResources;
|
|
24
30
|
pagination?: Pagination;
|
|
25
31
|
sorters?: Sort[];
|
|
26
32
|
filters?: Filter[];
|
|
27
33
|
meta?: Record<string, unknown>;
|
|
28
34
|
dataProviderName?: string;
|
|
29
|
-
queryOptions?:
|
|
35
|
+
queryOptions?: ResourceQueryOptions<InfinitePages<TData>, TSelected>;
|
|
30
36
|
successNotification?: NotificationConfig;
|
|
31
37
|
errorNotification?: NotificationConfig;
|
|
32
38
|
liveMode?: LiveMode;
|
|
@@ -44,7 +50,7 @@ const flagsSchema = Type.Object({
|
|
|
44
50
|
isFetchPreviousPageError: Type.Boolean(), isFetchingPreviousPage: Type.Boolean(),
|
|
45
51
|
}, { additionalProperties: false });
|
|
46
52
|
|
|
47
|
-
type Pages<T extends BaseRecord> =
|
|
53
|
+
type Pages<T extends BaseRecord> = InfinitePages<T>;
|
|
48
54
|
type InfiniteOutcome<T> =
|
|
49
55
|
| { status: 'pending'; data: undefined; error: null; isPending: true; isError: false; isSuccess: false;
|
|
50
56
|
isLoading: boolean; isLoadingError: false; isRefetchError: false; isPlaceholderData: false;
|
|
@@ -63,12 +69,12 @@ type InfiniteOutcome<T> =
|
|
|
63
69
|
));
|
|
64
70
|
|
|
65
71
|
/** The installed observer retains data on paging errors without setting isRefetchError. */
|
|
66
|
-
export type InfiniteListResult<T extends BaseRecord
|
|
67
|
-
Omit<InfiniteQueryObserverBaseResult<
|
|
68
|
-
& InfiniteOutcome<
|
|
69
|
-
refetch: (settings?: RefetchOptions) => Promise<InfiniteListResult<T>>;
|
|
70
|
-
fetchNextPage: (settings?: FetchNextPageOptions) => Promise<InfiniteListResult<T>>;
|
|
71
|
-
fetchPreviousPage: (settings?: FetchPreviousPageOptions) => Promise<InfiniteListResult<T>>;
|
|
72
|
+
export type InfiniteListResult<T extends BaseRecord, TData = Pages<T>> =
|
|
73
|
+
Omit<InfiniteQueryObserverBaseResult<TData, unknown>, keyof InfiniteOutcome<TData> | 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>
|
|
74
|
+
& InfiniteOutcome<TData> & {
|
|
75
|
+
refetch: (settings?: RefetchOptions) => Promise<InfiniteListResult<T, TData>>;
|
|
76
|
+
fetchNextPage: (settings?: FetchNextPageOptions) => Promise<InfiniteListResult<T, TData>>;
|
|
77
|
+
fetchPreviousPage: (settings?: FetchPreviousPageOptions) => Promise<InfiniteListResult<T, TData>>;
|
|
72
78
|
};
|
|
73
79
|
|
|
74
80
|
export function decodeInfiniteResult<T extends BaseRecord>(input: unknown, decode: RecordDecoder<T>): InfiniteData<GetListResult<T>, number> {
|
|
@@ -88,15 +94,16 @@ export function useInfiniteList(options: UseInfiniteListOptions = {}) {
|
|
|
88
94
|
return createInfiniteListQuery(options, () => decodeBaseRecord);
|
|
89
95
|
}
|
|
90
96
|
|
|
91
|
-
export function createInfiniteListQuery<TData extends BaseRecord
|
|
92
|
-
options: UseInfiniteListOptions, getDecoder: () => RecordDecoder<TData>,
|
|
97
|
+
export function createInfiniteListQuery<TData extends BaseRecord, TSelected = Pages<TData>>(
|
|
98
|
+
options: UseInfiniteListOptions<TData, TSelected>, getDecoder: () => RecordDecoder<TData>,
|
|
93
99
|
) {
|
|
94
100
|
const context = captureContractContext(options);
|
|
95
101
|
const parsed = useParsed();
|
|
96
102
|
const adminOptions = getAdminOptions();
|
|
97
103
|
type Data = Pages<TData>;
|
|
98
|
-
type Result = InfiniteListResult<TData>;
|
|
104
|
+
type Result = InfiniteListResult<TData, TSelected>;
|
|
99
105
|
const session = createQuerySession(context, () => {
|
|
106
|
+
const querySettings = listQuerySettings(options.queryOptions);
|
|
100
107
|
const resource = options.resource ?? parsed.resource ?? '';
|
|
101
108
|
const captured = captureQueryProvider(context, {
|
|
102
109
|
resource, ...definedOptions({ dataProviderName: options.dataProviderName, contract: options.contract, meta: options.meta }),
|
|
@@ -110,8 +117,16 @@ export function createInfiniteListQuery<TData extends BaseRecord>(
|
|
|
110
117
|
return {
|
|
111
118
|
resource, captured, params, decode: getDecoder(),
|
|
112
119
|
queryKey: context.queryKeys(resource, options.dataProviderName).data.infiniteList(resource, { ...params, source: captured.source }),
|
|
113
|
-
enabled:
|
|
114
|
-
staleTime:
|
|
120
|
+
enabled: querySettings.enabled,
|
|
121
|
+
staleTime: querySettings.staleTime ?? adminOptions.reactQuery?.staleTime,
|
|
122
|
+
gcTime: querySettings.gcTime ?? adminOptions.reactQuery?.gcTime,
|
|
123
|
+
refetchOnWindowFocus: querySettings.refetchOnWindowFocus ?? adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
124
|
+
retry: querySettings.retry,
|
|
125
|
+
retryDelay: querySettings.retryDelay,
|
|
126
|
+
refetchInterval: querySettings.refetchInterval,
|
|
127
|
+
refetchIntervalInBackground: querySettings.refetchIntervalInBackground,
|
|
128
|
+
placeholderData: querySettings.placeholderData as Data | ((previousData: Data | undefined) => Data | undefined) | undefined,
|
|
129
|
+
select: options.queryOptions?.select,
|
|
115
130
|
successNotification: options.successNotification, errorNotification: options.errorNotification,
|
|
116
131
|
};
|
|
117
132
|
});
|
|
@@ -142,7 +157,16 @@ export function createInfiniteListQuery<TData extends BaseRecord>(
|
|
|
142
157
|
}
|
|
143
158
|
},
|
|
144
159
|
enabled: origin.enabled && origin.auth.available,
|
|
145
|
-
...definedOptions({
|
|
160
|
+
...definedOptions({
|
|
161
|
+
staleTime: origin.staleTime,
|
|
162
|
+
gcTime: origin.gcTime,
|
|
163
|
+
refetchOnWindowFocus: origin.refetchOnWindowFocus,
|
|
164
|
+
retry: origin.retry,
|
|
165
|
+
retryDelay: origin.retryDelay,
|
|
166
|
+
refetchInterval: origin.refetchInterval,
|
|
167
|
+
refetchIntervalInBackground: origin.refetchIntervalInBackground,
|
|
168
|
+
placeholderData: origin.placeholderData,
|
|
169
|
+
}),
|
|
146
170
|
};
|
|
147
171
|
});
|
|
148
172
|
|
|
@@ -184,15 +208,19 @@ export function createInfiniteListQuery<TData extends BaseRecord>(
|
|
|
184
208
|
if (!checkExact(flagsSchema, flags)) return rejectProviderResponse();
|
|
185
209
|
const failureReason = result.failureReason === null ? null : querySessionError(result.failureReason);
|
|
186
210
|
const rawData: unknown = result.data;
|
|
211
|
+
const projectData = (value: unknown): TSelected => {
|
|
212
|
+
const pages = decodeInfiniteResult(value, origin.decode);
|
|
213
|
+
return origin.select ? origin.select(pages) : pages as TSelected;
|
|
214
|
+
};
|
|
187
215
|
if (result.status === 'success') {
|
|
188
|
-
const data =
|
|
216
|
+
const data = projectData(rawData);
|
|
189
217
|
if (!session.current(origin)) return pending(operations);
|
|
190
218
|
return { ...result, ...flags, ...operations, data, failureReason, isFetchNextPageError: false, isFetchPreviousPageError: false };
|
|
191
219
|
}
|
|
192
220
|
if (result.status === 'error') {
|
|
193
221
|
const base = { ...result, ...flags, ...operations, error: querySessionError(result.error), failureReason };
|
|
194
222
|
if (rawData === undefined) return { ...base, data: undefined, isLoadingError: true, isRefetchError: false };
|
|
195
|
-
const data =
|
|
223
|
+
const data = projectData(rawData);
|
|
196
224
|
if (!session.current(origin)) return pending(operations);
|
|
197
225
|
if (flags.isFetchNextPageError) return {
|
|
198
226
|
...base, data, isLoadingError: false, isRefetchError: false, isFetchNextPageError: true, isFetchPreviousPageError: false,
|