@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.
@@ -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
+ }
@@ -127,31 +127,6 @@ export function isTenantCacheKey(value: unknown): value is TenantCacheKey {
127
127
  );
128
128
  }
129
129
 
130
- /**
131
- * @deprecated 0.36 — Query Key v2 replaces positional tenant cache-key appending.
132
- * Use `keys({ tenant })` instead. Removed in 0.39.
133
- */
134
- export function appendTenantCacheKey(
135
- queryKey: readonly unknown[],
136
- tenantCacheKey: TenantCacheKey|undefined,
137
- ): readonly unknown[] {
138
- return tenantCacheKey? [...queryKey,tenantCacheKey]:queryKey;
139
- }
140
-
141
- /**
142
- * @deprecated 0.36 — Query Key v2 replaces positional tenant cache-key matching.
143
- * Use `queryKeyMatches(queryKey, { tenant })` instead. Removed in 0.39.
144
- */
145
- export function queryKeyMatchesTenant(
146
- queryKey: readonly unknown[],
147
- tenantCacheKey: TenantCacheKey|undefined,
148
- ): boolean {
149
- const candidate=queryKey.at(-1);
150
- const keyTenant=isTenantCacheKey(candidate)? candidate:undefined;
151
- if(!tenantCacheKey) return keyTenant===undefined;
152
- return keyTenant?.__svadminTenant===tenantCacheKey.__svadminTenant;
153
- }
154
-
155
130
  export interface ProviderMetaInput {
156
131
  readonly resource?: string;
157
132
  readonly meta?: Record<string,unknown>;
@@ -0,0 +1,111 @@
1
+ import { isCrudFieldOperator, type CrudOperator, type Filter, CRUD_FIELD_OPERATORS } from './types';
2
+
3
+ /**
4
+ * 各一手数据源实际执行的筛选协议。
5
+ * 未声明的运算符或逻辑组合必须失败关闭,不能改写成相等或丢掉条件组。
6
+ */
7
+ export const FILTER_PROVIDER_IDS = [
8
+ 'pocketbase',
9
+ 'directus',
10
+ 'sanity',
11
+ 'elysia',
12
+ 'supabase-table',
13
+ 'scaffold-memory',
14
+ ] as const;
15
+
16
+ export type FilterProviderId = (typeof FILTER_PROVIDER_IDS)[number];
17
+
18
+ export interface ProviderFilterCapability {
19
+ id: FilterProviderId;
20
+ /** 语义等价、会被真正下推的字段运算符。 */
21
+ operators: readonly CrudOperator[];
22
+ /** 是否执行嵌套 and/or。key 只是条件组身份,不是查询谓词。 */
23
+ logical: boolean;
24
+ }
25
+
26
+ function operators(values: readonly CrudOperator[]): readonly CrudOperator[] {
27
+ return values;
28
+ }
29
+
30
+ export const PROVIDER_FILTER_CAPABILITIES: Record<FilterProviderId, ProviderFilterCapability> = {
31
+ pocketbase: {
32
+ id: 'pocketbase',
33
+ logical: true,
34
+ operators: operators([
35
+ 'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
36
+ 'contains', 'ncontains', 'startswith', 'nstartswith', 'endswith', 'nendswith',
37
+ 'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
38
+ ]),
39
+ },
40
+ directus: {
41
+ id: 'directus',
42
+ logical: true,
43
+ operators: operators([
44
+ 'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
45
+ 'contains', 'ncontains', 'containss', 'ncontainss',
46
+ 'startswith', 'nstartswith', 'startswiths', 'nstartswiths',
47
+ 'endswith', 'nendswith', 'endswiths', 'nendswiths',
48
+ 'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
49
+ ]),
50
+ },
51
+ sanity: {
52
+ id: 'sanity',
53
+ logical: true,
54
+ operators: operators([
55
+ 'eq', 'ne', 'lt', 'gt', 'lte', 'gte',
56
+ 'contains', 'ncontains', 'startswith', 'endswith',
57
+ 'in', 'nin', 'null', 'nnull', 'between', 'nbetween',
58
+ ]),
59
+ },
60
+ elysia: {
61
+ id: 'elysia',
62
+ logical: true,
63
+ operators: CRUD_FIELD_OPERATORS,
64
+ },
65
+ 'supabase-table': {
66
+ id: 'supabase-table',
67
+ logical: false,
68
+ operators: operators(['eq']),
69
+ },
70
+ 'scaffold-memory': {
71
+ id: 'scaffold-memory',
72
+ logical: true,
73
+ operators: operators(['eq', 'ne', 'contains', 'in', 'null', 'nnull']),
74
+ },
75
+ };
76
+
77
+ const supportedOperators = new Map<FilterProviderId, ReadonlySet<string>>(
78
+ FILTER_PROVIDER_IDS.map((id) => [id, new Set(PROVIDER_FILTER_CAPABILITIES[id].operators)]),
79
+ );
80
+
81
+ export function providerSupportsOperator(provider: FilterProviderId, operator: CrudOperator): boolean {
82
+ return supportedOperators.get(provider)?.has(operator) ?? false;
83
+ }
84
+
85
+ function visitFilter(provider: FilterProviderId, filter: Filter, depth: number, seen: Set<object>): void {
86
+ const capability = PROVIDER_FILTER_CAPABILITIES[provider];
87
+ const allowed = supportedOperators.get(provider);
88
+ if (!capability || !allowed) throw new Error(`Unknown filter provider: ${provider}`);
89
+ if (depth > 32) throw new Error(`Unsupported ${provider} filter: nesting is too deep`);
90
+ if (typeof filter !== 'object' || filter === null || seen.has(filter)) {
91
+ throw new Error(`Unsupported ${provider} filter: expected an object`);
92
+ }
93
+ seen.add(filter);
94
+ if ('field' in filter) {
95
+ if (!isCrudFieldOperator(filter.operator) || !allowed.has(filter.operator)) {
96
+ throw new Error(`Unsupported ${provider} filter operator: ${String(filter.operator)}`);
97
+ }
98
+ return;
99
+ }
100
+ if (!capability.logical || (filter.operator !== 'and' && filter.operator !== 'or') || !Array.isArray(filter.value)) {
101
+ throw new Error(`Unsupported ${provider} logical operator: ${String(filter.operator)}`);
102
+ }
103
+ for (const child of filter.value) visitFilter(provider, child, depth + 1, seen);
104
+ }
105
+
106
+ /** 在翻译之前拒绝能力矩阵之外的运算符和逻辑组合。 */
107
+ export function assertFiltersExecutable(provider: FilterProviderId, filters: readonly Filter[] | undefined): void {
108
+ if (!FILTER_PROVIDER_IDS.includes(provider)) throw new Error(`Unknown filter provider: ${String(provider)}`);
109
+ const seen = new Set<object>();
110
+ for (const filter of filters ?? []) visitFilter(provider, filter, 0, seen);
111
+ }