@svadmin/core 0.69.2 → 0.70.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,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 generateCode(resource: ResourceDefinition): string {
297
- const esc = (s: string) => s.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
298
- const fieldsCode = resource.fields.map((f: FieldDefinition) => {
299
- const lines = [
300
- ` { key: '${esc(f.key)}', label: '${esc(f.label)}', type: '${f.type}'`,
301
- ];
302
- if (f.sortable) lines.push(` sortable: true`);
303
- if (f.searchable) lines.push(` searchable: true`);
304
- if (f.showInList === false) lines.push(` showInList: false`);
305
- if (f.showInForm === false) lines.push(` showInForm: false`);
306
- if (f.resource) {
307
- lines.push(` resource: '${f.resource}'`);
308
- lines.push(` optionLabel: '${f.optionLabel}'`);
309
- lines.push(` optionValue: '${f.optionValue}'`);
310
- }
311
- if (f.options) {
312
- lines.push(` options: ${JSON.stringify(f.options)}`);
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
- return lines.join(',\n') + ' }';
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
- return `import type { ResourceDefinition } from '@svadmin/core';
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
- export const ${resource.name}Resource: ResourceDefinition = {
321
- name: '${resource.name}',
322
- label: '${resource.label}',
323
- primaryKey: '${resource.primaryKey ?? 'id'}',
324
- canCreate: true,
325
- canEdit: true,
326
- canDelete: true,
327
- canShow: true,
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
- ${fieldsCode}
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="${resource.name}">
344
- <AutoTable resourceName="${resource.name}" />
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="${resource.name}">
358
- <AutoForm resourceName="${resource.name}" mode="create" />
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="${resource.name}" {id}>
378
- <AutoForm resourceName="${resource.name}" {id} mode="edit" />
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="${resource.name}" {id}>
398
- <AutoForm resourceName="${resource.name}" {id} mode="show" />
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
  `;
@@ -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 interface UseInfiniteListOptions extends ContractOptions {
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?: { staleTime?: number; enabled?: boolean };
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> = InfiniteData<GetListResult<T>, number>;
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<Pages<T>, unknown>, keyof InfiniteOutcome<Pages<T>> | 'refetch' | 'fetchNextPage' | 'fetchPreviousPage'>
68
- & InfiniteOutcome<Pages<T>> & {
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: options.queryOptions?.enabled ?? true,
114
- staleTime: options.queryOptions?.staleTime ?? adminOptions.reactQuery?.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({ staleTime: origin.staleTime }),
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 = decodeInfiniteResult(rawData, origin.decode);
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 = decodeInfiniteResult(rawData, origin.decode);
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,
@@ -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>;