-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcard-api.gts
More file actions
5017 lines (4734 loc) · 162 KB
/
Copy pathcard-api.gts
File metadata and controls
5017 lines (4734 loc) · 162 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Modifier from 'ember-modifier';
import GlimmerComponent from '@glimmer/component';
import { isEqual } from 'lodash-es';
import { WatchedArray, rawArrayValues } from './watched-array';
import {
BoxelInput,
BrokenLinkTemplate,
CopyButton,
type BrokenLinkFormat,
} from '@cardstack/boxel-ui/components';
import {
markdownEscape,
type MenuItemOptions,
not,
} from '@cardstack/boxel-ui/helpers';
import {
getBoxComponent,
type BoxComponent,
CardCrudFunctionsConsumer,
DefaultFormatsConsumer,
} from './field-component';
import { getContainsManyComponent } from './contains-many-component';
import { LinksToEditor } from './links-to-editor';
import { getLinksToManyComponent } from './links-to-many-component';
import {
assertIsSerializerName,
baseRef,
CardContextName,
CardError,
CodeRef,
ToolContext,
Deferred,
byteStreamToUint8Array,
fields,
fieldSerializer,
fieldsUntracked,
formats,
getAncestor,
getMenuItems,
getField,
getSerializer,
humanReadable,
identifyCard,
inferContentType,
isBaseInstance,
isCardError,
isCardInstance as _isCardInstance,
isCardResource,
isFileMetaResource,
isFileDef,
isField,
isFieldInstance,
isRelationship,
loadCardDef,
loadCardDocument,
Loader,
localId,
LocalPath,
meta,
primitive,
realmURL,
relativeTo,
SingleCardDocument,
uuidv4,
NumberSerializer,
type Format,
type Meta,
type CardFields,
type Relationship,
type ResourceID,
type LooseCardResource,
type LooseSingleCardDocument,
type CardDocument,
type CardResourceMeta,
type ResolvedCodeRef,
type getCard,
type getCards,
type getCardCollection,
type Store,
type SearchResultsComponentSignature,
type ErrorEntry,
type Query,
type QueryWithInterpolations,
type QueryResultsMeta,
type SerializedError,
FileMetaResourceType,
CardResourceType,
loadFileMetaDocument,
CardResource,
LooseLinkableResource,
LooseSingleResourceDocument,
shouldTrackRuntimeModuleGraph,
shouldTrackRuntimeRelationship,
trackRuntimeFileDependency,
trackRuntimeInstanceDependency,
trackRuntimeModuleDependency,
runtimeNonQueryDependencyContext,
runtimeQueryDependencyContext,
type RuntimeDependencyTrackingContext,
rri,
resolveRRIReference,
type RealmResourceIdentifier,
type VirtualNetwork,
isDirectIndexedFieldKey,
cardTypeName,
} from '@cardstack/runtime-common';
import {
captureQueryFieldSeedData,
ensureQueryFieldSearchResource,
peekQueryFieldSearchResource,
validateRelationshipQuery,
} from './query-field-support';
import { isSavedInstance } from './-private';
import type { ComponentLike } from '@glint/template';
import { initSharedState } from './shared-state';
import DefaultFittedTemplate from './default-templates/fitted';
import DefaultEmbeddedTemplate from './default-templates/embedded';
import DefaultCardDefTemplate from './default-templates/isolated-and-edit';
import DefaultAtomViewTemplate from './default-templates/atom';
import DefaultHeadTemplate from './default-templates/head';
import MissingTemplate from './default-templates/missing-template';
import FieldDefEditTemplate from './default-templates/field-edit';
import MarkdownTemplate from './default-templates/markdown';
import DefaultMarkdownFallbackTemplate from './default-templates/markdown-fallback';
import { markdownImage } from './markdown-helpers';
import FileDefEditTemplate from './default-templates/file-def-edit';
import FileDefAtomTemplate from './default-templates/file-def-atom';
import FileDefEmbeddedTemplate from './default-templates/file-def-embedded';
import FileDefFittedTemplate from './default-templates/file-def-fitted';
import FileDefIsolatedTemplate from './default-templates/file-def-isolated';
import ImageDefAtomTemplate from './default-templates/image-def-atom';
import ImageDefEmbeddedTemplate from './default-templates/image-def-embedded';
import ImageDefFittedTemplate from './default-templates/image-def-fitted';
import ImageDefIsolatedTemplate from './default-templates/image-def-isolated';
import CaptionsIcon from '@cardstack/boxel-icons/captions';
import FileIcon from '@cardstack/boxel-icons/file';
import ImageIcon from '@cardstack/boxel-icons/image';
import LetterCaseIcon from '@cardstack/boxel-icons/letter-case';
import MarkdownIcon from '@cardstack/boxel-icons/align-box-left-middle';
import RectangleEllipsisIcon from '@cardstack/boxel-icons/rectangle-ellipsis';
import TextAreaIcon from '@cardstack/boxel-icons/align-left';
import ThemeIcon from '@cardstack/boxel-icons/palette';
import ImportIcon from '@cardstack/boxel-icons/import';
import FilePencilIcon from '@cardstack/boxel-icons/file-pencil';
import WandIcon from '@cardstack/boxel-icons/wand';
import HashIcon from '@cardstack/boxel-icons/hash';
// normalizeEnumOptions used by enum moved to packages/base/enum.gts
import PatchThemeTool from '@cardstack/boxel-host/commands/patch-theme';
import CopyAndEditTool from '@cardstack/boxel-host/commands/copy-and-edit';
import { md5 } from 'super-fast-md5';
import {
callSerializeHook,
cardClassFromResource,
deserialize,
makeMetaForField,
makeRelativeURL,
serialize,
serializeCard,
serializeCardResource,
serializeFileDef,
resourceFrom,
type DeserializeOpts,
type JSONAPIResource,
type JSONAPISingleResourceDocument,
type SerializeOpts,
getCardMeta,
} from './card-serialization';
import {
assertScalar,
beginComputePass,
endComputePass,
entangleWithCardTracking,
getBrokenLinks,
getDataBucket,
getFieldDescription,
getFieldOverrides,
getFields,
getRelationshipMembershipState,
getter,
registerRelationshipProbe,
relationshipStateForEntry,
readFieldLoadingSignal,
bumpFieldLoadingSignal,
isArrayOfCardOrField,
isCard,
isCardOrField,
isLinkError,
isLinkNotFound,
isNonPresentLink,
isNotLoadedValue,
markAuthoredEmptyLink,
notifyCardTracking,
peekAtField,
propagateRealmContext,
realmContext,
setFieldDescription,
setRealmContextOnField,
type BrokenLinkFinding,
type ComputePassSnapshot,
type LinkErrorValue,
type LinkNotFoundValue,
type NotLoadedValue,
type RelationshipStatus,
type RelationshipState,
} from './field-support';
import { TextInputValidator } from './text-input-validator';
import { type GetMenuItemParams, getDefaultCardMenuItems } from './menu-items';
import { getDefaultFileMenuItems } from './file-menu-items';
import {
LinkableDocument,
SingleFileMetaDocument,
} from '@cardstack/runtime-common/document-types';
import type { MarkdownEmbedChooser } from '@cardstack/runtime-common/bfm-card-references';
import type { FileMetaResource } from '@cardstack/runtime-common';
export const BULK_GENERATED_ITEM_COUNT = 3;
interface CardOrFieldTypeIconSignature {
Element: SVGSVGElement;
}
export type CardOrFieldTypeIcon = ComponentLike<CardOrFieldTypeIconSignature>;
export {
beginComputePass,
endComputePass,
deserialize,
getBrokenLinks,
getCardMeta,
getDataBucket,
getFieldDescription,
getFields,
getRelationshipMembershipState,
isNonPresentLink,
peekAtField,
isCard,
isField,
isFileDef,
localId,
meta,
primitive,
realmURL,
relativeTo,
serialize,
serializeCard,
serializeFileDef,
ensureQueryFieldSearchResource,
getStore,
type BoxComponent,
type BrokenLinkFinding,
type ComputePassSnapshot,
type DeserializeOpts,
type GetMenuItemParams,
type JSONAPISingleResourceDocument,
type RelationshipStatus,
type RelationshipState,
type ResourceID,
type SerializeOpts,
};
export const useIndexBasedKey = Symbol.for('cardstack-use-index-based-key');
export const fieldDecorator = Symbol.for('cardstack-field-decorator');
export const queryableValue = Symbol.for('cardstack-queryable-value');
export const formatQuery = Symbol.for('cardstack-format-query');
export const realmInfo = Symbol.for('cardstack-realm-info');
export const emptyValue = Symbol.for('cardstack-empty-value');
export type BaseInstanceType<T extends BaseDefConstructor> = T extends {
[primitive]: infer P;
}
? P
: InstanceType<T>;
// this is expressing the idea that the fields of a
// card may contain undefined, but even when that's
// true all the symbols and the `constructor` property
// can still be relied on.
type PartialFields<T> = {
[Property in keyof T]: Property extends symbol
? T[Property]
: Property extends 'constructor'
? T[Property]
: T[Property] | undefined;
};
export type PartialBaseInstanceType<T extends BaseDefConstructor> = T extends {
[primitive]: infer P;
}
? P | null
: PartialFields<InstanceType<T>> & {
[fields]: Record<string, BaseDefConstructor>;
[fieldsUntracked]: Record<string, BaseDefConstructor>;
};
export type FieldsTypeFor<T extends BaseDef> = {
[Field in keyof T]: BoxComponent &
(T[Field] extends ArrayLike<unknown>
? BoxComponent[]
: T[Field] extends BaseDef
? FieldsTypeFor<T[Field]>
: unknown);
};
export { formats, type Format };
export type FieldType = 'contains' | 'containsMany' | 'linksTo' | 'linksToMany';
// Opaque configuration passed to field format components and validators
export type FieldConfiguration = Record<string, any>;
// Configuration may be provided as a static object or a function of the parent instance
export type ConfigurationInput<T> =
| FieldConfiguration
| ((this: Readonly<T>) => FieldConfiguration | undefined);
export type FieldFormats = {
['fieldDef']: Format;
['cardDef']: Format;
};
type Setter = (value: any) => void;
export type SerializedFile<Extra extends object = {}> = {
sourceUrl: string;
url: string;
name: string;
contentType: string;
contentHash?: string;
contentSize?: number;
} & Extra;
export type ByteStream = ReadableStream<Uint8Array> | Uint8Array;
// Declares which links a field makes searchable — i.e. which linked cards are
// pulled into the search doc rather than left as a bare `{ id }` reference.
// `searchable` only ever governs links: a contained value is always included
// once its owner is in the doc, so `searchable` never decides whether a
// contained field appears. `true` makes the immediate ("self") link
// searchable; a dotted path makes a deeper (n+1) link searchable, routed from
// this field's target through its links — naming intermediate contained
// fields as segments to reach a link beneath them; an array combines routes.
// Omitted leaves the link as `{ id }` only. On a `contains`/`containsMany`
// field (whose value is always present) a path is therefore only meaningful to
// make a link reached *through* that contained value searchable.
export type Searchable = true | string | string[];
interface Options {
computeVia?: () => unknown;
description?: string;
// Names which links this field makes searchable. See `Searchable`.
searchable?: Searchable;
// Optional: per-usage configuration provider merged with FieldDef-level configuration
configuration?: ConfigurationInput<any>;
}
interface RelationshipOptions extends Options {
query?: QueryWithInterpolations;
}
export interface CardContext<T extends CardDef = CardDef> {
toolContext?: ToolContext;
// Pre-rename spelling of `toolContext`. Realm content reads
// `@context.commandContext`; populated with the same value until no
// deployed content references it.
commandContext?: ToolContext;
cardComponentModifier?: typeof Modifier<{
Args: {
Named: {
card?: CardDef;
cardId?: string;
format: Format | 'data';
fieldType: FieldType | undefined;
fieldName: string | undefined;
};
};
}>;
// The search rendering surface: renders the heterogeneous `entry`
// stream for an `entry`-rooted query — prerendered HTML inert (hydrated
// lazily) or a live card — so a card author renders results without ever
// branching on prerendered-vs-live. Supersedes `prerenderedCardSearchComponent`.
searchResultsComponent: typeof GlimmerComponent<SearchResultsComponentSignature>;
getCard: getCard<T>;
getCards: getCards;
getCardCollection: getCardCollection;
store: Store;
// Host bridge for the markdown editor's embed chooser. Provided by
// operator-mode; absent in contexts with no chooser modal (prerender,
// freestyle), so consumers guard on it.
markdownEmbedChooser?: MarkdownEmbedChooser;
// Optional runtime mode/submode hints used by cards that render differently per context.
mode?: 'host' | 'operator';
submode?: 'interact' | 'code' | 'host';
}
export interface FieldConstructor<T> {
cardThunk: () => T;
computeVia: undefined | (() => unknown);
declaredCardThunk?: () => T;
isPolymorphic?: true;
searchable?: Searchable;
name: string;
queryDefinition?: QueryWithInterpolations;
}
type CardChangeSubscriber = (
instance: BaseDef,
fieldName: string,
fieldValue: any,
) => void;
const stores = initSharedState(
'stores',
() => new WeakMap<BaseDef, CardStore>(),
);
const subscribers = initSharedState(
'subscribers',
() => new WeakMap<BaseDef, Set<CardChangeSubscriber>>(),
);
const subscriberConsumer = initSharedState(
'subscriberConsumer',
() => new WeakMap<BaseDef, { fieldOrCard: BaseDef; fieldName: string }>(),
);
const inflightLinkLoads = initSharedState(
'inflightLinkLoads',
() => new WeakMap<CardDef, Map<string, Promise<unknown>>>(),
);
export function instanceOf(instance: BaseDef, clazz: typeof BaseDef): boolean {
let instanceClazz: typeof BaseDef | null = instance.constructor;
let codeRefInstance: CodeRef | undefined;
let codeRefClazz = identifyCard(clazz);
if (!codeRefClazz) {
return instance instanceof (clazz as any);
}
do {
codeRefInstance = instanceClazz ? identifyCard(instanceClazz) : undefined;
if (isEqual(codeRefInstance, codeRefClazz)) {
return true;
}
instanceClazz = instanceClazz ? (getAncestor(instanceClazz) ?? null) : null;
} while (codeRefInstance && !isEqual(codeRefInstance, baseRef));
return false;
}
class Logger {
private promises: Promise<any>[] = [];
// TODO this doesn't look like it's used anymore. in the past this was used to
// keep track of async when eagerly running computes after a property had been set.
// consider removing this.
log(promise: Promise<any>) {
this.promises.push(promise);
// make an effort to resolve the promise at the time it is logged
(async () => {
try {
await promise;
} catch (e: any) {
console.error(`encountered error performing recompute on card`, e);
}
})();
}
async flush() {
let results = await Promise.allSettled(this.promises);
for (let result of results) {
if (result.status === 'rejected') {
console.error(`Promise rejected`, result.reason);
if (result.reason instanceof Error) {
console.error(result.reason.stack);
}
}
}
}
}
let logger = new Logger();
export async function flushLogs() {
await logger.flush();
}
export interface StoreSearchResource<T extends CardDef | FileDef = CardDef> {
readonly instances: T[];
readonly instancesByRealm: { realm: string; cards: T[] }[];
readonly isLoading: boolean;
readonly meta: QueryResultsMeta;
readonly errors?: ErrorEntry[];
}
export type GetSearchResourceFuncOpts = {
isLive?: boolean;
doWhileRefreshing?: (() => void) | undefined;
dependencyTracking?: RuntimeDependencyTrackingContext;
seed?: {
cards: CardDef[];
searchURL?: string;
realms?: string[];
queryErrors?: Array<{
realm: string;
type: string;
message: string;
status?: number;
}>;
// IDs the parent doc named in `relationships.{field}.data`. Used
// by the SearchResource when `cards` is empty and the parent
// skipped query-backed expansion — the resource loads each ID by
// URL instead of running a live re-query.
cardURLs?: string[];
};
};
export type GetSearchResourceFunc<T extends CardDef | FileDef = CardDef> = (
parent: object,
getQuery: () => Query | undefined,
getRealms?: () => string[] | undefined,
opts?: GetSearchResourceFuncOpts,
) => StoreSearchResource<T>;
export interface CardStore {
// Resolve a (possibly relative or RRI) reference to a real, fetchable URL.
// Stores expose URL-resolution capability — never the VirtualNetwork object
// itself — so card code can satisfy boundaries that require a real URL (an
// `<img src>`, `new URL(...)`) without holding the network. Returns
// undefined when the reference can't be resolved (no network available, or
// an unresolvable reference) so callers can degrade to URL math.
resolveURL(reference: string, base?: string): URL | undefined;
getCard(url: string): CardDef | undefined;
getFileMeta(url: string): FileDef | undefined;
setCard(url: string, instance: CardDef): void;
setFileMeta(url: string, instance: FileDef): void;
setCardNonTracked(id: string, instance: CardDef): void;
setFileMetaNonTracked(id: string, instance: FileDef): void;
makeTracked(id: string): void;
// `untracked` opts out of the store's load-generation tracking: safe only
// for a caller that awaits this promise inline and folds the resolved
// document into its own output, so the load-settle machinery (which exists
// to catch loads fired and abandoned by field getters) has nothing to wait
// for. The searchable generator's targeted link loads use this — it lets a
// walk whose targets all resolve immediately read as settled without a
// confirmation pass. Stores that don't implement the option simply keep
// tracking, which costs an extra settle pass and nothing else.
loadCardDocument(
url: string,
opts?: {
dependencyTrackingContext?: RuntimeDependencyTrackingContext;
untracked?: true;
},
): Promise<SingleCardDocument | CardError>;
loadFileMetaDocument(
url: string,
opts?: {
dependencyTrackingContext?: RuntimeDependencyTrackingContext;
untracked?: true;
},
): Promise<SingleFileMetaDocument | CardError>;
trackLoad(load: Promise<unknown>): void;
loaded(): Promise<void>;
// CS-10872: optional diagnostic hooks used by the prerenderer's
// render-timeout error path to populate "what the render was
// waiting on". Stores that don't implement them (e.g. older test
// doubles) simply won't contribute a queryLoadsInFlight section.
trackQueryLoad?(
load: Promise<unknown>,
meta: QueryLoadMeta,
): (() => void) | void;
queryLoadsInFlight?(): QueryLoadInfo[];
// Per-URL ageMs for currently-in-flight linked-field / file-meta
// loads. Mirrors the `cardDocsInFlight` string getter but carries
// "how long has this URL been loading".
cardDocLoadsInFlight?(): Array<{ url: string; ageMs: number }>;
fileMetaDocLoadsInFlight?(): Array<{ url: string; ageMs: number }>;
// Bounded top-N history of completed slow loads. Survives beyond
// the in-flight window so the post-timeout capture can see which
// individual queries / linked fields dominated wall time even if
// they completed just before the timer fired.
recentCardDocLoads?(): Array<{ url: string; ms: number }>;
recentFileMetaLoads?(): Array<{ url: string; ms: number }>;
recentQueryLoads?(): Array<{ meta: QueryLoadMeta; ms: number }>;
getSearchResource: GetSearchResourceFunc;
}
export interface QueryLoadMeta {
// Free-form label so operators can tell "a query-field resolution"
// apart from "a standalone search". See SearchResource.
source: string;
query?: unknown;
realms?: string[];
cardId?: string;
fieldName?: string;
}
export interface QueryLoadInfo extends QueryLoadMeta {
ageMs: number;
}
export interface Field<
CardT extends BaseDefConstructor = BaseDefConstructor,
SearchT = any,
> {
card: CardT;
name: string;
fieldType: FieldType;
computeVia: undefined | (() => unknown);
// Optional per-usage configuration stored on the field descriptor
configuration?: ConfigurationInput<any>;
// Declarative relationship query definition, if provided
queryDefinition?: QueryWithInterpolations;
captureQueryFieldSeedData?(
instance: BaseDef,
value: any,
resource: LooseCardResource,
): void;
isPolymorphic?: true;
// The links this field makes searchable. This descriptor is the source of
// truth; `getFieldDefinitions` mirrors it (raw) into the cached
// `FieldDefinition` for the loaderless query compiler and definition-build
// validation. See `Searchable`.
searchable?: Searchable;
serialize(
value: any,
doc: JSONAPISingleResourceDocument,
visited: Set<string>,
opts?: SerializeOpts,
): JSONAPIResource;
deserialize(
value: any,
doc: LooseSingleCardDocument | CardDocument,
relationships: JSONAPIResource['relationships'] | undefined,
fieldMeta: CardFields[string] | undefined,
store: CardStore | undefined,
instancePromise: Promise<BaseDef>,
loadedValue: any,
relativeTo: RealmResourceIdentifier | URL | undefined,
opts?: DeserializeOpts,
): Promise<any>;
emptyValue(instance: BaseDef): any;
validate(instance: BaseDef, value: any): void;
component(model: Box<BaseDef>): BoxComponent;
getter(instance: BaseDef): BaseInstanceType<CardT> | undefined;
queryableValue(value: any, stack: BaseDef[]): SearchT;
}
function cardTypeFor(
field: Field<typeof BaseDef>,
boxedElement?: Box<BaseDef>,
overrides?: () => Map<string, typeof BaseDef> | undefined,
): typeof BaseDef {
let override: typeof BaseDef | undefined;
if (overrides) {
let valueKey = `${field.name}${
boxedElement ? '.' + boxedElement.name : ''
}`;
override = boxedElement?.value ? overrides()?.get(valueKey) : undefined;
} else {
override =
boxedElement?.value && typeof boxedElement.value === 'object'
? getFieldOverrides(boxedElement.value)?.get(field.name)
: undefined;
}
if (primitive in field.card) {
return override ?? field.card;
}
if (boxedElement === undefined || boxedElement.value == null) {
return field.card;
}
return Reflect.getPrototypeOf(boxedElement.value)!
.constructor as typeof BaseDef;
}
function assertNoDeserializeOverride(cardClass: typeof BaseDef) {
if (
!(primitive in cardClass) &&
Object.prototype.hasOwnProperty.call(cardClass, deserialize)
) {
throw new Error(
`${cardClass.name} overrides [deserialize] directly. Composite fields must use a registered fieldSerializer instead.`,
);
}
}
class ContainsMany<FieldT extends FieldDefConstructor> implements Field<
FieldT,
any[] | null
> {
readonly fieldType = 'containsMany';
private cardThunk: () => FieldT;
readonly computeVia: undefined | (() => unknown);
readonly name: string;
readonly description: string | undefined;
readonly isPolymorphic: undefined | true;
readonly searchable: Searchable | undefined;
configuration: ConfigurationInput<any> | undefined;
constructor({
cardThunk,
computeVia,
name,
isPolymorphic,
searchable,
}: FieldConstructor<FieldT>) {
this.cardThunk = cardThunk;
this.computeVia = computeVia;
this.name = name;
this.isPolymorphic = isPolymorphic;
this.searchable = searchable;
}
get card(): FieldT {
return this.cardThunk();
}
getter(instance: BaseDef): BaseInstanceType<FieldT> | undefined {
let deserialized = getDataBucket(instance);
entangleWithCardTracking(instance);
let maybeNotLoaded = deserialized.get(this.name);
// a not loaded error can blow up thru a computed containsMany field that consumes a link
if (isNotLoadedValue(maybeNotLoaded)) {
lazilyLoadLink(instance as CardDef, this, maybeNotLoaded.reference);
return this.emptyValue(instance) as BaseInstanceType<FieldT>;
}
let results = getter(instance, this);
propagateRealmContext(results, instance);
return results;
}
queryableValue(instances: any[] | null, stack: BaseDef[]): any[] | null {
if (instances === null || instances.length === 0) {
// we intentionally use a "null" to represent an empty plural field as
// this is a limitation to SQLite's json_tree() function when trying to match
// plural fields that are empty
return null;
}
// Need to replace the WatchedArray proxy with an actual array because the
// WatchedArray proxy is not structuredClone-able, and hence cannot be
// communicated over the postMessage boundary between worker and DOM.
// TODO: can this be simplified since we don't have the worker anymore?
let results = [...instances]
.map((instance) => {
return this.card[queryableValue](instance, stack);
})
.filter((i) => i != null);
return results.length === 0 ? null : results;
}
serialize(
values: BaseInstanceType<FieldT>[] | NotLoadedValue,
doc: JSONAPISingleResourceDocument,
_visited: Set<string>,
opts?: SerializeOpts,
): JSONAPIResource {
// this can be a not loaded value happen when the containsMany is a
// computed that consumes a linkTo field that is not loaded
if (isNotLoadedValue(values)) {
return { attributes: {} };
}
let serialized =
values === null
? null
: values.map((value) =>
callSerializeHook(this.card, value, doc, undefined, opts),
);
if (primitive in this.card) {
if (opts?.overrides) {
let meta: Partial<Meta> = {};
if (Array.isArray(serialized)) {
for (let [index] of serialized.entries()) {
let fieldName = `${this.name}.${index}`;
let override = opts.overrides.get(fieldName);
if (!override) {
continue;
}
meta.fields = meta.fields ?? {};
meta.fields[fieldName] = {
adoptsFrom: identifyCard(
override,
opts?.useAbsoluteURL ? undefined : opts?.maybeRelativeReference,
),
};
}
}
return {
attributes: {
[this.name]: serialized,
},
meta,
};
} else {
return {
attributes: {
[this.name]: serialized,
},
};
}
} else {
let relationships: Record<string, Relationship> = {};
let serialized =
values === null
? null
: values.map((value, index) => {
let resource: JSONAPISingleResourceDocument['data'] =
callSerializeHook(this.card, value, doc, undefined, opts);
if (resource.relationships) {
for (let [fieldName, relationship] of Object.entries(
resource.relationships as Record<string, Relationship>,
)) {
relationships[`${this.name}.${index}.${fieldName}`] =
relationship; // warning side-effect
}
}
if (this.card === Reflect.getPrototypeOf(value)!.constructor) {
// when our implementation matches the default we don't need to include
// meta.adoptsFrom
delete resource.meta?.adoptsFrom;
}
if (resource.meta && Object.keys(resource.meta).length === 0) {
delete resource.meta;
}
return resource;
});
let result: JSONAPIResource = {
attributes: {
[this.name]:
serialized === null
? null
: serialized.map((resource) => resource.attributes),
},
};
if (Object.keys(relationships).length > 0) {
result.relationships = relationships;
}
if (serialized && serialized.some((resource) => resource.meta)) {
result.meta = {
fields: {
[this.name]: serialized.map((resource) => resource.meta ?? {}),
},
};
}
return result;
}
}
async deserialize(
value: any[],
doc: CardDocument,
relationships: JSONAPIResource['relationships'] | undefined,
fieldMeta: CardFields[string] | undefined,
store: CardStore,
instancePromise: Promise<BaseDef>,
_loadedValue: any,
relativeTo: RealmResourceIdentifier | URL | undefined,
opts: DeserializeOpts,
): Promise<BaseInstanceType<FieldT>[] | null> {
if (value == null) {
return null;
}
if (!Array.isArray(value)) {
throw new Error(`Expected array for field value ${this.name}`);
}
if (fieldMeta && !Array.isArray(fieldMeta)) {
throw new Error(
`fieldMeta for contains-many field '${
this.name
}' is not an array: ${JSON.stringify(fieldMeta, null, 2)}`,
);
}
let metas: Partial<Meta>[] = fieldMeta ?? [];
return new WatchedArray(
(prevArrayValue, arrayValue) =>
instancePromise.then((instance) => {
applySubscribersToInstanceValue(
instance,
this,
prevArrayValue,
arrayValue,
);
notifySubscribers(instance, field.name, arrayValue);
notifyCardTracking(instance);
}),
await Promise.all(
value.map(async (entry, index) => {
if (primitive in this.card) {
if (fieldSerializer in this.card) {
assertIsSerializerName(this.card[fieldSerializer]);
let serializer = getSerializer(this.card[fieldSerializer]);
return serializer.deserialize<FieldT>(
entry,
relativeTo,
doc,
store,
opts,
);
}
return entry;
} else {
if (fieldSerializer in this.card) {
assertIsSerializerName(this.card[fieldSerializer]);
let serializer = getSerializer(this.card[fieldSerializer]);
entry = await serializer.deserialize(
entry,
relativeTo,
doc,
store,
opts,
);
}
let meta = metas[index];
let resource: LooseCardResource = {
attributes: entry,
meta: makeMetaForField(meta, this.name, this.card),
};
if (relationships) {
resource.relationships = Object.fromEntries(
Object.entries(relationships)
.filter(([fieldName]) =>
fieldName.startsWith(`${this.name}.`),
)
.map(([fieldName, relationship]) => {
let relName = `${this.name}.${index}`;
return [
fieldName.startsWith(`${relName}.`)
? fieldName.substring(relName.length + 1)
: fieldName,
relationship,
];
}),
);
}
let cardClass = await cardClassFromResource(
resource,
this.card,
relativeTo,
);
assertNoDeserializeOverride(cardClass);
return cardClass[deserialize](
resource,
relativeTo,
doc,
store,
opts,
);
}
}),
),
);
}
emptyValue(instance: BaseDef) {
return new WatchedArray((oldValue, value) => {
applySubscribersToInstanceValue(
instance,
this,
oldValue as BaseDef[],
value as BaseDef[],
);
notifySubscribers(instance, this.name, value);
notifyCardTracking(instance);
});
}
validate(instance: BaseDef, values: any[] | null) {
if (values && !Array.isArray(values)) {
throw new Error(
`field validation error: Expected array for field value of field '${this.name}'`,
);
}
if (values == null) {
return values;
}
if (!(primitive in this.card)) {
for (let [index, item] of values.entries()) {
if (item != null && !instanceOf(item, this.card)) {
throw new Error(
`field validation error: tried set instance of ${values.constructor.name} at index ${index} of field '${this.name}' but it is not an instance of ${this.card.name}`,
);
}
}
}
return new WatchedArray((oldValue, value) => {
applySubscribersToInstanceValue(
instance,
this,
oldValue as BaseDef[],
value as BaseDef[],
);
notifySubscribers(instance, this.name, value);
notifyCardTracking(instance);
}, values);
}
component(model: Box<BaseDef>): BoxComponent {
let fieldName = this.name as keyof BaseDef;
let arrayField = model.field(
fieldName,
useIndexBasedKey in this.card,
) as unknown as Box<BaseDef[]>;
return getContainsManyComponent({
model,
arrayField,
field: this,
cardTypeFor,
});
}