@svadmin/core 0.67.0 → 0.69.3
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 +6 -2
- package/src/adapters/ably.ts +58 -0
- package/src/adapters/cerbos.ts +92 -0
- package/src/adapters/firebase.ts +46 -0
- package/src/adapters/graphql-subscription.ts +45 -0
- package/src/adapters/live-event.ts +21 -0
- package/src/adapters/permit.ts +78 -0
- package/src/audit-hooks.svelte.ts +119 -0
- package/src/contract-form.svelte.ts +96 -6
- package/src/contracts.ts +11 -0
- package/src/crud-operator-schema.ts +20 -0
- package/src/editable-table.svelte.ts +90 -0
- package/src/editable-table.ts +314 -0
- package/src/hooks.svelte.ts +34 -0
- package/src/i18n.svelte.ts +7 -4
- package/src/index.ts +29 -8
- package/src/inferencer-contract.ts +114 -0
- package/src/inferencer.ts +219 -42
- package/src/query-hooks.svelte.ts +16 -6
- package/src/query-options.ts +50 -0
- package/src/query-snapshot.ts +3 -4
- package/src/resource-contract.ts +6 -3
- package/src/resource-schemas.ts +3 -6
- package/src/router-provider.ts +11 -0
- package/src/routing-hooks.svelte.ts +84 -3
- package/src/select-options.ts +35 -1
- package/src/select-query.svelte.ts +20 -5
- package/src/session-query.svelte.ts +6 -1
- package/src/strict-hooks.svelte.ts +9 -5
- package/src/table-hooks.svelte.ts +12 -0
- package/src/task-hooks.svelte.ts +1 -0
- package/src/theme.svelte.ts +8 -6
- package/src/types.ts +22 -7
- package/src/url-sync.ts +37 -17
- package/src/utility-hooks.svelte.ts +68 -5
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import type { FieldDefinition } from './types';
|
|
2
|
+
|
|
3
|
+
const contractExpressions = new WeakMap<FieldDefinition, string>();
|
|
4
|
+
const JSON_SCHEMA_DEPTH = 6;
|
|
5
|
+
|
|
6
|
+
export function propertyKey(key: string): string {
|
|
7
|
+
// 对象字面量里的 __proto__ 会改原型,必须写成字符串键。
|
|
8
|
+
if (key === '__proto__' || key === 'constructor' || key === 'prototype') return JSON.stringify(key);
|
|
9
|
+
return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(key) ? key : JSON.stringify(key);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function unionExpressions(expressions: string[]): string | null {
|
|
13
|
+
const unique = [...new Set(expressions)];
|
|
14
|
+
if (unique.length === 0) return null;
|
|
15
|
+
if (unique.length === 1) return unique[0] ?? null;
|
|
16
|
+
return `Type.Union([${unique.join(', ')}])`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function valueKind(value: unknown): 'string' | 'boolean' | 'number' | 'array' | 'object' | 'other' {
|
|
20
|
+
if (typeof value === 'string') return 'string';
|
|
21
|
+
if (typeof value === 'boolean') return 'boolean';
|
|
22
|
+
if (typeof value === 'number') return 'number';
|
|
23
|
+
if (Array.isArray(value)) return 'array';
|
|
24
|
+
if (typeof value === 'object' && value !== null) return 'object';
|
|
25
|
+
return 'other';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** 从样本值生成 closeContractSchema 接受的封闭 TypeBox 表达式。无法封闭时返回 null。 */
|
|
29
|
+
export function closedValueExpression(values: unknown[], depth: number, seen: WeakSet<object>): string | null {
|
|
30
|
+
if (depth > JSON_SCHEMA_DEPTH) return null;
|
|
31
|
+
const defined = values.filter((value) => value !== undefined);
|
|
32
|
+
if (defined.length === 0) return null;
|
|
33
|
+
const nonNull = defined.filter((value) => value !== null);
|
|
34
|
+
const expression = nonNull.length === 0
|
|
35
|
+
? 'Type.Null()'
|
|
36
|
+
: closedNonNullExpression(nonNull, depth, seen);
|
|
37
|
+
if (!expression) return null;
|
|
38
|
+
if (nonNull.length !== defined.length && expression !== 'Type.Null()') {
|
|
39
|
+
return `Type.Union([${expression}, Type.Null()])`;
|
|
40
|
+
}
|
|
41
|
+
return expression;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function closedNonNullExpression(values: unknown[], depth: number, seen: WeakSet<object>): string | null {
|
|
45
|
+
const kinds = [...new Set(values.map(valueKind))];
|
|
46
|
+
if (kinds.length !== 1) {
|
|
47
|
+
const parts: string[] = [];
|
|
48
|
+
for (const kind of kinds) {
|
|
49
|
+
const expression = closedNonNullExpression(values.filter((value) => valueKind(value) === kind), depth, seen);
|
|
50
|
+
if (!expression) return null;
|
|
51
|
+
parts.push(expression);
|
|
52
|
+
}
|
|
53
|
+
return unionExpressions(parts);
|
|
54
|
+
}
|
|
55
|
+
switch (kinds[0]) {
|
|
56
|
+
case 'string':
|
|
57
|
+
return 'Type.String()';
|
|
58
|
+
case 'boolean':
|
|
59
|
+
return 'Type.Boolean()';
|
|
60
|
+
case 'number':
|
|
61
|
+
return values.every((value) => typeof value === 'number' && Number.isFinite(value)) ? 'Type.Number()' : null;
|
|
62
|
+
case 'array':
|
|
63
|
+
return closedArrayExpression(values.filter(Array.isArray), depth, seen);
|
|
64
|
+
case 'object':
|
|
65
|
+
return closedObjectExpression(values.filter((value): value is Record<string, unknown> => valueKind(value) === 'object'), depth, seen);
|
|
66
|
+
default:
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function closedArrayExpression(values: unknown[][], depth: number, seen: WeakSet<object>): string | null {
|
|
72
|
+
for (const value of values) {
|
|
73
|
+
if (seen.has(value)) return null;
|
|
74
|
+
}
|
|
75
|
+
for (const value of values) seen.add(value);
|
|
76
|
+
try {
|
|
77
|
+
const items = values.flat();
|
|
78
|
+
if (items.length === 0) return null;
|
|
79
|
+
const item = closedValueExpression(items, depth + 1, seen);
|
|
80
|
+
return item ? `Type.Array(${item})` : null;
|
|
81
|
+
} finally {
|
|
82
|
+
for (const value of values) seen.delete(value);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function closedObjectExpression(objects: Record<string, unknown>[], depth: number, seen: WeakSet<object>): string | null {
|
|
87
|
+
for (const value of objects) {
|
|
88
|
+
if (seen.has(value)) return null;
|
|
89
|
+
}
|
|
90
|
+
for (const value of objects) seen.add(value);
|
|
91
|
+
try {
|
|
92
|
+
const keys = [...new Set(objects.flatMap((value) => Object.keys(value)))].sort();
|
|
93
|
+
const properties: string[] = [];
|
|
94
|
+
for (const key of keys) {
|
|
95
|
+
const present = objects.filter((value) => Object.prototype.hasOwnProperty.call(value, key));
|
|
96
|
+
const expression = closedValueExpression(present.map((value) => value[key]), depth + 1, seen);
|
|
97
|
+
if (!expression) return null;
|
|
98
|
+
const rendered = present.length === objects.length ? expression : `Type.Optional(${expression})`;
|
|
99
|
+
properties.push(`${propertyKey(key)}: ${rendered}`);
|
|
100
|
+
}
|
|
101
|
+
const body = properties.length > 0 ? ` ${properties.join(', ')} ` : ' ';
|
|
102
|
+
return `Type.Object({${body}}, { additionalProperties: false })`;
|
|
103
|
+
} finally {
|
|
104
|
+
for (const value of objects) seen.delete(value);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function rememberContractExpression(field: FieldDefinition, expression: string | null): void {
|
|
109
|
+
if (expression) contractExpressions.set(field, expression);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function getContractExpression(field: FieldDefinition): string | undefined {
|
|
113
|
+
return contractExpressions.get(field);
|
|
114
|
+
}
|
package/src/inferencer.ts
CHANGED
|
@@ -5,6 +5,12 @@
|
|
|
5
5
|
* Can also generate copy-paste-ready Svelte component code.
|
|
6
6
|
*/
|
|
7
7
|
import type { FieldDefinition, ResourceDefinition } from './types';
|
|
8
|
+
import {
|
|
9
|
+
closedValueExpression,
|
|
10
|
+
getContractExpression,
|
|
11
|
+
propertyKey,
|
|
12
|
+
rememberContractExpression,
|
|
13
|
+
} from './inferencer-contract';
|
|
8
14
|
|
|
9
15
|
// ─── Field Type Inference ────────────────────────────────────
|
|
10
16
|
|
|
@@ -98,7 +104,8 @@ export type InferReviewWarningCode =
|
|
|
98
104
|
| 'nullable-field'
|
|
99
105
|
| 'mixed-types'
|
|
100
106
|
| 'heuristic-relation'
|
|
101
|
-
| 'heuristic-select'
|
|
107
|
+
| 'heuristic-select'
|
|
108
|
+
| 'unconstrained-field';
|
|
102
109
|
|
|
103
110
|
export interface InferReviewWarning {
|
|
104
111
|
code: InferReviewWarningCode;
|
|
@@ -135,7 +142,7 @@ export function inferResource(
|
|
|
135
142
|
return {
|
|
136
143
|
fields: [],
|
|
137
144
|
resource: emptyResource,
|
|
138
|
-
code: `// No data available to infer fields for "${resourceName}"
|
|
145
|
+
code: `// No data available to infer fields for "${resourceName}".\n${generateCode(emptyResource)}`,
|
|
139
146
|
typeboxCode: generateTypeBoxSchemaCode(emptyResource),
|
|
140
147
|
review: {
|
|
141
148
|
needsReview: true,
|
|
@@ -242,6 +249,24 @@ export function inferResource(
|
|
|
242
249
|
field.options = [...uniqueStrings].map(v => ({ label: capitalize(v), value: v }));
|
|
243
250
|
}
|
|
244
251
|
|
|
252
|
+
if (field.type === 'json' || field.type === 'richtext') {
|
|
253
|
+
const observed = sampleData.flatMap((row) => (
|
|
254
|
+
Object.prototype.hasOwnProperty.call(row, key) ? [row[key]] : []
|
|
255
|
+
));
|
|
256
|
+
const expression = closedValueExpression(observed, 0, new WeakSet());
|
|
257
|
+
if (expression) {
|
|
258
|
+
rememberContractExpression(field, expression);
|
|
259
|
+
} else if (field.type === 'richtext') {
|
|
260
|
+
rememberContractExpression(field, 'Type.String()');
|
|
261
|
+
} else {
|
|
262
|
+
warnings.push({
|
|
263
|
+
code: 'unconstrained-field',
|
|
264
|
+
field: key,
|
|
265
|
+
message: `Field "${key}" is omitted from the strict ResourceContract because its sample shape is not a closed JSON value. Author the contract by hand.`,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
245
270
|
fields.push(field);
|
|
246
271
|
}
|
|
247
272
|
|
|
@@ -293,40 +318,171 @@ export function inferResource(
|
|
|
293
318
|
|
|
294
319
|
// ─── Code Generation ─────────────────────────────────────────
|
|
295
320
|
|
|
296
|
-
function
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
321
|
+
function moduleName(resource: ResourceDefinition): string {
|
|
322
|
+
const safe = resource.name.replace(/[^A-Za-z0-9_$]/g, '_');
|
|
323
|
+
return /^[A-Za-z_$]/.test(safe) ? safe : `resource_${safe}`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Closed TypeBox expression, or null when the value cannot be a strict contract field. */
|
|
327
|
+
function contractTypeExpression(field: FieldDefinition): string | null {
|
|
328
|
+
const esc = (value: string) => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
329
|
+
switch (field.type) {
|
|
330
|
+
case 'number':
|
|
331
|
+
return 'Type.Number()';
|
|
332
|
+
case 'boolean':
|
|
333
|
+
return 'Type.Boolean()';
|
|
334
|
+
case 'date':
|
|
335
|
+
return "Type.String({ format: 'date-time' })";
|
|
336
|
+
case 'email':
|
|
337
|
+
return "Type.String({ format: 'email' })";
|
|
338
|
+
case 'url':
|
|
339
|
+
case 'image':
|
|
340
|
+
return "Type.String({ format: 'uri' })";
|
|
341
|
+
case 'phone':
|
|
342
|
+
return "Type.String({ pattern: '^\\\\+?[\\\\d\\\\s\\\\-()]{7,}$' })";
|
|
343
|
+
case 'tags':
|
|
344
|
+
return 'Type.Array(Type.String())';
|
|
345
|
+
case 'images':
|
|
346
|
+
return "Type.Array(Type.String({ format: 'uri' }))";
|
|
347
|
+
case 'select':
|
|
348
|
+
if (field.options && field.options.length > 0) {
|
|
349
|
+
const literals = field.options.map((option) => `Type.Literal('${esc(String(option.value))}')`).join(', ');
|
|
350
|
+
return `Type.Union([${literals}])`;
|
|
351
|
+
}
|
|
352
|
+
return 'Type.String()';
|
|
353
|
+
case 'relation':
|
|
354
|
+
return 'Type.Union([Type.String(), Type.Number()])';
|
|
355
|
+
case 'daterange':
|
|
356
|
+
return 'Type.Union([Type.Object({ start: Type.Union([Type.String(), Type.Null()]), end: Type.Union([Type.String(), Type.Null()]) }, { additionalProperties: false }), Type.Null()])';
|
|
357
|
+
case 'json':
|
|
358
|
+
return getContractExpression(field) ?? null;
|
|
359
|
+
case 'richtext':
|
|
360
|
+
return getContractExpression(field) ?? 'Type.String()';
|
|
361
|
+
case 'datetime':
|
|
362
|
+
case 'time':
|
|
363
|
+
case 'textarea':
|
|
364
|
+
case 'text':
|
|
365
|
+
case 'color':
|
|
366
|
+
default:
|
|
367
|
+
return 'Type.String()';
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function idTypeExpression(field: FieldDefinition | undefined): string {
|
|
372
|
+
if (!field) return 'Type.String()';
|
|
373
|
+
if (field.type === 'number') return 'Type.Number()';
|
|
374
|
+
if (field.type === 'relation') return 'Type.Union([Type.String(), Type.Number()])';
|
|
375
|
+
return 'Type.String()';
|
|
376
|
+
}
|
|
314
377
|
|
|
315
|
-
|
|
378
|
+
function schemaProperty(key: string, expression: string, optional: boolean): string {
|
|
379
|
+
const value = optional ? `Type.Optional(${expression})` : expression;
|
|
380
|
+
return ` ${propertyKey(key)}: ${value},`;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function objectConst(name: string, properties: string[]): string {
|
|
384
|
+
const body = properties.length > 0 ? `\n${properties.join('\n')}\n` : '\n';
|
|
385
|
+
return `const ${name} = Type.Object({${body}}, { additionalProperties: false });`;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function definitionFieldLines(fields: FieldDefinition[]): string {
|
|
389
|
+
const esc = (value: string) => value.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
390
|
+
return fields.map((field) => {
|
|
391
|
+
const lines = [` { key: '${esc(field.key)}', label: '${esc(field.label)}', type: '${field.type}'`];
|
|
392
|
+
if (field.sortable) lines.push(' sortable: true');
|
|
393
|
+
if (field.searchable) lines.push(' searchable: true');
|
|
394
|
+
if (field.showInList === false) lines.push(' showInList: false');
|
|
395
|
+
if (field.showInForm === false) lines.push(' showInForm: false');
|
|
396
|
+
if (field.resource) {
|
|
397
|
+
lines.push(` resource: '${esc(field.resource)}'`);
|
|
398
|
+
lines.push(` optionLabel: '${esc(field.optionLabel ?? 'name')}'`);
|
|
399
|
+
lines.push(` optionValue: '${esc(field.optionValue ?? 'id')}'`);
|
|
400
|
+
}
|
|
401
|
+
if (field.options) lines.push(` options: ${JSON.stringify(field.options)}`);
|
|
402
|
+
return `${lines.join(',\n')} }`;
|
|
316
403
|
}).join(',\n');
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
function contractParts(resource: ResourceDefinition): { idField: FieldDefinition | undefined; writable: FieldDefinition[] } {
|
|
407
|
+
const sourceKey = resource.primaryKey ?? 'id';
|
|
408
|
+
const idField = resource.fields.find((field) => field.key === sourceKey) ?? resource.fields.find((field) => field.key === 'id');
|
|
409
|
+
const writable = resource.fields.filter((field) => (
|
|
410
|
+
field.key !== sourceKey
|
|
411
|
+
&& field.key !== 'id'
|
|
412
|
+
&& field.showInForm !== false
|
|
413
|
+
&& contractTypeExpression(field) !== null
|
|
414
|
+
));
|
|
415
|
+
return { idField, writable };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
function definitionFields(resource: ResourceDefinition): FieldDefinition[] {
|
|
419
|
+
const sourceKey = resource.primaryKey ?? 'id';
|
|
420
|
+
const idField = resource.fields.find((field) => field.key === sourceKey) ?? resource.fields.find((field) => field.key === 'id');
|
|
421
|
+
const rest = resource.fields.filter((field) => field.key !== sourceKey && field.key !== 'id');
|
|
422
|
+
const idDefinition: FieldDefinition = idField
|
|
423
|
+
? { ...idField, key: 'id', showInForm: false }
|
|
424
|
+
: { key: 'id', label: 'ID', type: 'text', showInForm: false, showInList: false };
|
|
425
|
+
return [idDefinition, ...rest];
|
|
426
|
+
}
|
|
317
427
|
|
|
318
|
-
|
|
428
|
+
function handAuthoredContractNotes(resource: ResourceDefinition): string {
|
|
429
|
+
const notes = resource.fields.flatMap((field) => {
|
|
430
|
+
if (field.type !== 'json' && field.type !== 'richtext') return [];
|
|
431
|
+
if (contractTypeExpression(field) !== null) return [];
|
|
432
|
+
return [
|
|
433
|
+
`// @svadmin hand-authored-contract ${JSON.stringify(field.key)}: ${field.type} is omitted from the strict contract because its sample shape is not a closed JSON value. Author a closed Type.Object schema before records containing this field can pass validation.`,
|
|
434
|
+
];
|
|
435
|
+
});
|
|
436
|
+
return notes.length > 0 ? `${notes.join('\n')}\n` : '';
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function generateCode(resource: ResourceDefinition): string {
|
|
440
|
+
const name = moduleName(resource);
|
|
441
|
+
const literalName = resource.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
442
|
+
const literalLabel = resource.label.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
443
|
+
const { idField, writable } = contractParts(resource);
|
|
444
|
+
const idType = idTypeExpression(idField);
|
|
445
|
+
const recordProps = [
|
|
446
|
+
schemaProperty('id', idType, false),
|
|
447
|
+
...writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', field.required !== true)),
|
|
448
|
+
];
|
|
449
|
+
const createProps = writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', field.required !== true));
|
|
450
|
+
const updateProps = writable.map((field) => schemaProperty(field.key, contractTypeExpression(field) ?? 'Type.String()', true));
|
|
451
|
+
const sourceKey = resource.primaryKey ?? 'id';
|
|
452
|
+
const projection = sourceKey === 'id'
|
|
453
|
+
? ''
|
|
454
|
+
: `// Source primary key "${sourceKey.replace(/"/g, '\\"')}" is projected onto the contract id.\n`;
|
|
455
|
+
return `import { Type } from 'typebox';
|
|
456
|
+
import { defineResource, type AdminResourceDefinition } from '@svadmin/core';
|
|
457
|
+
|
|
458
|
+
${projection}${handAuthoredContractNotes(resource)}${objectConst(`${name}RecordSchema`, recordProps)}
|
|
459
|
+
|
|
460
|
+
${objectConst(`${name}CreateSchema`, createProps)}
|
|
461
|
+
|
|
462
|
+
${objectConst(`${name}UpdateSchema`, updateProps)}
|
|
463
|
+
|
|
464
|
+
${objectConst(`${name}DeleteSchema`, [schemaProperty('id', idType, false)])}
|
|
465
|
+
|
|
466
|
+
/** Runtime contract consumed by AutoTable and AutoForm through resolveResourceContract(). */
|
|
467
|
+
export const ${name}Resource = defineResource('${literalName}', {
|
|
468
|
+
record: ${name}RecordSchema,
|
|
469
|
+
create: ${name}CreateSchema,
|
|
470
|
+
update: ${name}UpdateSchema,
|
|
471
|
+
delete: ${name}DeleteSchema,
|
|
472
|
+
});
|
|
319
473
|
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
474
|
+
/** Register this definition on the admin config resources array. */
|
|
475
|
+
export const ${name}Definition: AdminResourceDefinition = {
|
|
476
|
+
name: '${literalName}',
|
|
477
|
+
label: '${literalLabel}',
|
|
478
|
+
primaryKey: 'id',
|
|
479
|
+
canCreate: ${resource.canCreate ?? true},
|
|
480
|
+
canEdit: ${resource.canEdit ?? true},
|
|
481
|
+
canDelete: ${resource.canDelete ?? true},
|
|
482
|
+
canShow: ${resource.canShow ?? true},
|
|
483
|
+
contract: ${name}Resource,
|
|
328
484
|
fields: [
|
|
329
|
-
${
|
|
485
|
+
${definitionFieldLines(definitionFields(resource))}
|
|
330
486
|
],
|
|
331
487
|
};
|
|
332
488
|
`;
|
|
@@ -336,12 +492,16 @@ ${fieldsCode}
|
|
|
336
492
|
* Generate Svelte 5 ListPage component code for a resource.
|
|
337
493
|
*/
|
|
338
494
|
export function generateListPageCode(resource: ResourceDefinition): string {
|
|
495
|
+
const name = moduleName(resource);
|
|
339
496
|
return `<script lang="ts">
|
|
340
497
|
import { ListPage, AutoTable } from '@svadmin/ui';
|
|
498
|
+
import { ${name}Definition } from '../${resource.name}.resource';
|
|
499
|
+
|
|
500
|
+
const resourceName = ${name}Definition.name;
|
|
341
501
|
</script>
|
|
342
502
|
|
|
343
|
-
<ListPage resourceName
|
|
344
|
-
<AutoTable resourceName
|
|
503
|
+
<ListPage {resourceName}>
|
|
504
|
+
<AutoTable {resourceName} />
|
|
345
505
|
</ListPage>
|
|
346
506
|
`;
|
|
347
507
|
}
|
|
@@ -350,12 +510,16 @@ export function generateListPageCode(resource: ResourceDefinition): string {
|
|
|
350
510
|
* Generate Svelte 5 CreatePage component code for a resource.
|
|
351
511
|
*/
|
|
352
512
|
export function generateCreatePageCode(resource: ResourceDefinition): string {
|
|
513
|
+
const name = moduleName(resource);
|
|
353
514
|
return `<script lang="ts">
|
|
354
515
|
import { CreatePage, AutoForm } from '@svadmin/ui';
|
|
516
|
+
import { ${name}Definition } from '../${resource.name}.resource';
|
|
517
|
+
|
|
518
|
+
const resourceName = ${name}Definition.name;
|
|
355
519
|
</script>
|
|
356
520
|
|
|
357
|
-
<CreatePage resourceName
|
|
358
|
-
<AutoForm resourceName
|
|
521
|
+
<CreatePage {resourceName}>
|
|
522
|
+
<AutoForm {resourceName} mode="create" />
|
|
359
523
|
</CreatePage>
|
|
360
524
|
`;
|
|
361
525
|
}
|
|
@@ -364,18 +528,21 @@ export function generateCreatePageCode(resource: ResourceDefinition): string {
|
|
|
364
528
|
* Generate Svelte 5 EditPage component code for a resource.
|
|
365
529
|
*/
|
|
366
530
|
export function generateEditPageCode(resource: ResourceDefinition): string {
|
|
531
|
+
const name = moduleName(resource);
|
|
367
532
|
return `<script lang="ts">
|
|
368
533
|
import { EditPage, AutoForm } from '@svadmin/ui';
|
|
534
|
+
import { ${name}Definition } from '../${resource.name}.resource';
|
|
369
535
|
|
|
370
536
|
interface Props {
|
|
371
537
|
id?: string | number;
|
|
372
538
|
}
|
|
373
539
|
|
|
374
540
|
let { id }: Props = $props();
|
|
541
|
+
const resourceName = ${name}Definition.name;
|
|
375
542
|
</script>
|
|
376
543
|
|
|
377
|
-
<EditPage resourceName
|
|
378
|
-
<AutoForm resourceName
|
|
544
|
+
<EditPage {resourceName} {id}>
|
|
545
|
+
<AutoForm {resourceName} {id} mode="edit" />
|
|
379
546
|
</EditPage>
|
|
380
547
|
`;
|
|
381
548
|
}
|
|
@@ -384,18 +551,21 @@ export function generateEditPageCode(resource: ResourceDefinition): string {
|
|
|
384
551
|
* Generate Svelte 5 ShowPage component code for a resource.
|
|
385
552
|
*/
|
|
386
553
|
export function generateShowPageCode(resource: ResourceDefinition): string {
|
|
554
|
+
const name = moduleName(resource);
|
|
387
555
|
return `<script lang="ts">
|
|
388
556
|
import { ShowPage, AutoForm } from '@svadmin/ui';
|
|
557
|
+
import { ${name}Definition } from '../${resource.name}.resource';
|
|
389
558
|
|
|
390
559
|
interface Props {
|
|
391
560
|
id?: string | number;
|
|
392
561
|
}
|
|
393
562
|
|
|
394
563
|
let { id }: Props = $props();
|
|
564
|
+
const resourceName = ${name}Definition.name;
|
|
395
565
|
</script>
|
|
396
566
|
|
|
397
|
-
<ShowPage resourceName
|
|
398
|
-
<AutoForm resourceName
|
|
567
|
+
<ShowPage {resourceName} {id}>
|
|
568
|
+
<AutoForm {resourceName} {id} mode="show" />
|
|
399
569
|
</ShowPage>
|
|
400
570
|
`;
|
|
401
571
|
}
|
|
@@ -407,6 +577,11 @@ export function generateResourceCode(resource: ResourceDefinition): string {
|
|
|
407
577
|
return generateCode(resource);
|
|
408
578
|
}
|
|
409
579
|
|
|
580
|
+
/** Alias that makes the ResourceContract output explicit for callers. */
|
|
581
|
+
export function generateResourceContractCode(resource: ResourceDefinition): string {
|
|
582
|
+
return generateCode(resource);
|
|
583
|
+
}
|
|
584
|
+
|
|
410
585
|
/**
|
|
411
586
|
* Generate TypeScript code for TypeBox schema definition.
|
|
412
587
|
*/
|
|
@@ -451,7 +626,7 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
|
|
|
451
626
|
typeDef = "Type.Array(Type.String({ format: 'uri' }))";
|
|
452
627
|
break;
|
|
453
628
|
case 'json':
|
|
454
|
-
typeDef = 'Type.Record(Type.String(), Type.Unknown())';
|
|
629
|
+
typeDef = getContractExpression(f) ?? 'Type.Record(Type.String(), Type.Unknown())';
|
|
455
630
|
break;
|
|
456
631
|
case 'select':
|
|
457
632
|
if (f.options && f.options.length > 0) {
|
|
@@ -464,8 +639,10 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
|
|
|
464
639
|
case 'relation':
|
|
465
640
|
typeDef = 'Type.Union([Type.String(), Type.Number()])';
|
|
466
641
|
break;
|
|
467
|
-
case 'textarea':
|
|
468
642
|
case 'richtext':
|
|
643
|
+
typeDef = getContractExpression(f) ?? 'Type.String()';
|
|
644
|
+
break;
|
|
645
|
+
case 'textarea':
|
|
469
646
|
case 'text':
|
|
470
647
|
default:
|
|
471
648
|
typeDef = 'Type.String()';
|
|
@@ -486,7 +663,7 @@ export function generateTypeBoxSchemaCode(resource: ResourceDefinition): string
|
|
|
486
663
|
|
|
487
664
|
export const ${typeName}Schema = Type.Object({
|
|
488
665
|
${schemaProps}
|
|
489
|
-
});
|
|
666
|
+
}, { additionalProperties: false });
|
|
490
667
|
|
|
491
668
|
export type ${typeName} = Static<typeof ${typeName}Schema>;
|
|
492
669
|
`;
|
|
@@ -19,6 +19,7 @@ import { decodeBaseRecord, decodeListResult, decodeOneResult, decodeManyResult,
|
|
|
19
19
|
import { HttpError } from './types';
|
|
20
20
|
import { extendReactiveMembers } from './reactive-projection';
|
|
21
21
|
import { captureQueryProvider, snapshotListParams, snapshotOneParams, snapshotManyParams } from './query-snapshot';
|
|
22
|
+
import { applyListSelect, listQuerySettings, type ResourceQueryOptions } from './query-options';
|
|
22
23
|
|
|
23
24
|
// ─── useList ───────────────────────────────────────────────────
|
|
24
25
|
|
|
@@ -31,7 +32,7 @@ export interface UseListOptions<_TData extends BaseRecord=BaseRecord,_TError=Htt
|
|
|
31
32
|
filters?: Filter[];
|
|
32
33
|
meta?: Record<string,unknown>;
|
|
33
34
|
dataProviderName?: string;
|
|
34
|
-
queryOptions?:
|
|
35
|
+
queryOptions?: ResourceQueryOptions<GetListResult<_TData>>;
|
|
35
36
|
successNotification?: NotificationConfig;
|
|
36
37
|
errorNotification?: NotificationConfig;
|
|
37
38
|
liveMode?: LiveMode;
|
|
@@ -63,6 +64,7 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
63
64
|
resource,...definedOptions({ dataProviderName: opts.dataProviderName,contract: opts.contract,meta: opts.meta }),
|
|
64
65
|
});
|
|
65
66
|
const queryOptions=opts.queryOptions;
|
|
67
|
+
const settings=listQuerySettings(queryOptions);
|
|
66
68
|
|
|
67
69
|
// Inject a parent filter for nested resources.
|
|
68
70
|
// Consume only parentParams parsed from the path, such as teamId in /teams/123/users,
|
|
@@ -94,7 +96,6 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
94
96
|
|
|
95
97
|
return {
|
|
96
98
|
resource, successNotification: opts.successNotification, errorNotification: opts.errorNotification,
|
|
97
|
-
decode: decodeResult,
|
|
98
99
|
queryKey: adminContext.queryKeys(resource,opts.dataProviderName).data.list(resource,{
|
|
99
100
|
...definedOptions({
|
|
100
101
|
pagination: params.pagination,sorters: params.sorters,filters: params.filters,meta: params.meta,
|
|
@@ -107,11 +108,20 @@ export function createListQuery<TData extends BaseRecord>(
|
|
|
107
108
|
});
|
|
108
109
|
return decodeResult(await current.provider.getList(snapshotListParams({ ...params, ...definedOptions({ signal }) })));
|
|
109
110
|
},
|
|
110
|
-
|
|
111
|
+
decode: (value): GetListResult<TData> => applyListSelect(
|
|
112
|
+
decodeResult(value),
|
|
113
|
+
queryOptions?.select as ((data: GetListResult<TData>) => GetListResult<TData>) | undefined,
|
|
114
|
+
),
|
|
115
|
+
enabled: settings.enabled,
|
|
111
116
|
...definedOptions({
|
|
112
|
-
staleTime:
|
|
113
|
-
gcTime:
|
|
114
|
-
refetchOnWindowFocus:
|
|
117
|
+
staleTime: settings.staleTime??adminOptions.reactQuery?.staleTime,
|
|
118
|
+
gcTime: settings.gcTime??adminOptions.reactQuery?.gcTime,
|
|
119
|
+
refetchOnWindowFocus: settings.refetchOnWindowFocus??adminOptions.reactQuery?.refetchOnWindowFocus,
|
|
120
|
+
retry: settings.retry,
|
|
121
|
+
retryDelay: settings.retryDelay,
|
|
122
|
+
refetchInterval: settings.refetchInterval,
|
|
123
|
+
refetchIntervalInBackground: settings.refetchIntervalInBackground,
|
|
124
|
+
placeholderData: settings.placeholderData as GetListResult<TData> | ((previousData: GetListResult<TData> | undefined) => GetListResult<TData> | undefined) | undefined,
|
|
115
125
|
}),
|
|
116
126
|
};
|
|
117
127
|
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { definedOptions } from './defined-options';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* useList / useTable 可以安全转发的 TanStack Query 选项。
|
|
5
|
+
* `select` 在解码之后执行,避免改掉缓存里的原始响应。
|
|
6
|
+
*/
|
|
7
|
+
export interface ResourceQueryOptions<TData = unknown> {
|
|
8
|
+
staleTime?: number;
|
|
9
|
+
enabled?: boolean;
|
|
10
|
+
gcTime?: number;
|
|
11
|
+
refetchOnWindowFocus?: boolean | 'always';
|
|
12
|
+
retry?: boolean | number;
|
|
13
|
+
retryDelay?: number | ((failureCount: number, error: unknown) => number);
|
|
14
|
+
refetchInterval?: number | false;
|
|
15
|
+
refetchIntervalInBackground?: boolean;
|
|
16
|
+
placeholderData?: TData | ((previousData: TData | undefined) => TData | undefined);
|
|
17
|
+
select?: (data: TData) => TData;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface ListQuerySettings<TData = unknown> {
|
|
21
|
+
enabled: boolean;
|
|
22
|
+
staleTime?: number;
|
|
23
|
+
gcTime?: number;
|
|
24
|
+
refetchOnWindowFocus?: boolean | 'always';
|
|
25
|
+
retry?: boolean | number;
|
|
26
|
+
retryDelay?: ResourceQueryOptions<TData>['retryDelay'];
|
|
27
|
+
refetchInterval?: number | false;
|
|
28
|
+
refetchIntervalInBackground?: boolean;
|
|
29
|
+
placeholderData?: ResourceQueryOptions<TData>['placeholderData'];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function listQuerySettings<TData>(options: ResourceQueryOptions<TData> | undefined): ListQuerySettings<TData> {
|
|
33
|
+
return {
|
|
34
|
+
enabled: options?.enabled ?? true,
|
|
35
|
+
...definedOptions({
|
|
36
|
+
staleTime: options?.staleTime,
|
|
37
|
+
gcTime: options?.gcTime,
|
|
38
|
+
refetchOnWindowFocus: options?.refetchOnWindowFocus,
|
|
39
|
+
retry: options?.retry,
|
|
40
|
+
retryDelay: options?.retryDelay,
|
|
41
|
+
refetchInterval: options?.refetchInterval,
|
|
42
|
+
refetchIntervalInBackground: options?.refetchIntervalInBackground,
|
|
43
|
+
placeholderData: options?.placeholderData,
|
|
44
|
+
}),
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function applyListSelect<TData>(data: TData, select?: (data: TData) => TData): TData {
|
|
49
|
+
return select ? select(data) : data;
|
|
50
|
+
}
|
package/src/query-snapshot.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { Type, type Static, type TSchema } from 'typebox';
|
|
2
2
|
import type { AdminContextAccessor } from './context.svelte';
|
|
3
3
|
import type { DataProvider, GetListParams, GetOneParams, GetManyParams } from './types';
|
|
4
|
+
import { crudFieldOperatorSchema } from './crud-operator-schema';
|
|
4
5
|
import { HttpError } from './types';
|
|
5
6
|
import { contractProvider, type ResourceContract } from './resource-contract';
|
|
6
7
|
import { definedOptions } from './defined-options';
|
|
@@ -12,13 +13,11 @@ const filters = Type.Cyclic({
|
|
|
12
13
|
Filters: Type.Union([
|
|
13
14
|
Type.Object({
|
|
14
15
|
field: Type.String(),
|
|
15
|
-
operator:
|
|
16
|
-
'eq', 'ne', 'lt', 'gt', 'lte', 'gte', 'in', 'nin', 'contains', 'ncontains',
|
|
17
|
-
'startswith', 'endswith', 'null', 'nnull', 'between', 'nbetween',
|
|
18
|
-
] as const).map(value => Type.Literal(value))),
|
|
16
|
+
operator: crudFieldOperatorSchema,
|
|
19
17
|
value: Type.Unknown(),
|
|
20
18
|
}, { additionalProperties: false }),
|
|
21
19
|
Type.Object({
|
|
20
|
+
key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
22
21
|
operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
|
|
23
22
|
value: Type.Array(Type.Ref('Filters')),
|
|
24
23
|
}, { additionalProperties: false }),
|
package/src/resource-contract.ts
CHANGED
|
@@ -500,6 +500,7 @@ export function validateContractMutationParams(contract: ResourceContract | unde
|
|
|
500
500
|
}
|
|
501
501
|
|
|
502
502
|
const filterGroup = Type.Object({
|
|
503
|
+
key: Type.Optional(Type.String({ minLength: 1, maxLength: 128 })),
|
|
503
504
|
operator: Type.Union([Type.Literal('and'), Type.Literal('or')]),
|
|
504
505
|
value: Type.Array(Type.Unknown()),
|
|
505
506
|
}, { additionalProperties: false });
|
|
@@ -532,10 +533,12 @@ function checkFilters(filters: unknown, record: TObject, depth = 0): void {
|
|
|
532
533
|
}
|
|
533
534
|
const scalar = Type.Exclude(field, Type.Null());
|
|
534
535
|
switch (filter.operator) {
|
|
535
|
-
case 'eq': case 'ne': check(field, filter.value, filter.field); break;
|
|
536
|
-
case 'in': case 'nin': check(Type.Array(field), filter.value, filter.field); break;
|
|
536
|
+
case 'eq': case 'ne': case 'eqs': case 'nes': check(field, filter.value, filter.field); break;
|
|
537
|
+
case 'in': case 'nin': case 'ina': case 'nina': check(Type.Array(field), filter.value, filter.field); break;
|
|
537
538
|
case 'null': case 'nnull': check(Type.Null(), filter.value, filter.field); break;
|
|
538
|
-
case 'contains': case 'ncontains': case '
|
|
539
|
+
case 'contains': case 'ncontains': case 'containss': case 'ncontainss':
|
|
540
|
+
case 'startswith': case 'nstartswith': case 'startswiths': case 'nstartswiths':
|
|
541
|
+
case 'endswith': case 'nendswith': case 'endswiths': case 'nendswiths':
|
|
539
542
|
check(Type.Intersect([scalar, Type.String()]), filter.value, filter.field); break;
|
|
540
543
|
case 'lt': case 'lte': case 'gt': case 'gte':
|
|
541
544
|
check(Type.Intersect([scalar, Type.Union([Type.String(), Type.Number()])]), filter.value, filter.field); break;
|