@contello/store 1.5.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -31,16 +31,18 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  Store: () => Store,
34
- createStore: () => createStore
34
+ createStore: () => createStore,
35
+ maybeCatch: () => import_projected7.maybeCatch,
36
+ maybeThen: () => import_projected7.maybeThen
35
37
  });
36
38
  module.exports = __toCommonJS(index_exports);
37
39
 
38
40
  // src/store.ts
39
- var import_client = require("@contello/client");
41
+ var import_client9 = require("@contello/client");
40
42
 
41
43
  // src/assets.ts
44
+ var import_client2 = require("@contello/client");
42
45
  var import_projected = require("projected");
43
- var import_rxjs2 = require("rxjs");
44
46
 
45
47
  // src/diagnostics.ts
46
48
  var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
@@ -85,7 +87,26 @@ function wrap(name, fn) {
85
87
  }
86
88
 
87
89
  // src/generated/graphql.ts
88
- var storeGetAssetsDocument = `fragment StoreFile on ContelloFile {
90
+ var MediaAssetFragmentSchema = `fragment MediaAsset on ContelloAsset {
91
+ id
92
+ original {
93
+ ...MediaFile
94
+ }
95
+ preview {
96
+ ...MediaFile
97
+ }
98
+ optimized {
99
+ ...MediaFile
100
+ ... on ContelloOptimizedFile {
101
+ optimizationConfig {
102
+ ... on ContelloImageOptimizationConfig {
103
+ name
104
+ }
105
+ }
106
+ }
107
+ }
108
+ }`;
109
+ var MediaFileFragmentSchema = `fragment MediaFile on ContelloFile {
89
110
  uid
90
111
  mimeType
91
112
  metadata {
@@ -98,44 +119,21 @@ var storeGetAssetsDocument = `fragment StoreFile on ContelloFile {
98
119
  height
99
120
  }
100
121
  }
101
- }
102
- fragment StoreAsset on ContelloAsset {
103
- id
104
- original {
105
- ...StoreFile
106
- }
107
- preview {
108
- ...StoreFile
109
- }
110
- optimized {
111
- ...StoreFile
112
- }
113
- }
114
- query StoreGetAssets($filter: ContelloAssetsFilterInput!) {
115
- contelloAssets(filter: $filter) {
116
- ...StoreAsset
117
- }
118
122
  }`;
119
- var storeGetI18nMessagesDocument = `subscription StoreGetI18nMessages($collection: String!) {
120
- contelloI18nMessagesBatch(collectionReferenceName: $collection) {
121
- id
122
- token
123
- translations {
124
- language
125
- value
126
- }
127
- }
123
+ var StoreAssetFragmentSchema = `fragment StoreAsset on ContelloAsset {
124
+ ...MediaAsset
128
125
  }`;
129
- var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
130
- registerContelloI18nMessages(
131
- collectionReferenceName: $collection
132
- messages: $messages
133
- deprecateUnmentioned: true
134
- ) {
135
- ids
126
+ var StoreI18nMessageFragmentSchema = `fragment StoreI18nMessage on ContelloI18nMessage {
127
+ id
128
+ token
129
+ description
130
+ example
131
+ translations {
132
+ language
133
+ value
136
134
  }
137
135
  }`;
138
- var storeGetRoutesDocument = `fragment StoreRoute on ContelloRoute {
136
+ var StoreRouteFragmentSchema = `fragment StoreRoute on ContelloRoute {
139
137
  id
140
138
  path
141
139
  target {
@@ -171,49 +169,37 @@ var storeGetRoutesDocument = `fragment StoreRoute on ContelloRoute {
171
169
  name
172
170
  value
173
171
  }
174
- }
172
+ }`;
173
+ var storeGetAssetsDocument = `${MediaFileFragmentSchema}
174
+ ${MediaAssetFragmentSchema}
175
+ ${StoreAssetFragmentSchema}
176
+ query StoreGetAssets($filter: ContelloAssetsFilterInput!) {
177
+ contelloAssets(filter: $filter) {
178
+ ...StoreAsset
179
+ }
180
+ }`;
181
+ var storeGetI18nMessagesDocument = `${StoreI18nMessageFragmentSchema}
182
+ subscription StoreGetI18nMessages($collection: String!) {
183
+ contelloI18nMessagesBatch(collectionReferenceName: $collection) {
184
+ ...StoreI18nMessage
185
+ }
186
+ }`;
187
+ var storeRegisterI18nMessagesDocument = `mutation StoreRegisterI18nMessages($collection: String!, $messages: [ContelloI18nMessageInput!]!) {
188
+ registerContelloI18nMessages(
189
+ collectionReferenceName: $collection
190
+ messages: $messages
191
+ deprecateUnmentioned: true
192
+ ) {
193
+ ids
194
+ }
195
+ }`;
196
+ var storeGetRoutesDocument = `${StoreRouteFragmentSchema}
175
197
  query StoreGetRoutes($request: ContelloRoutesRequestInput!) {
176
198
  contelloRoutes(request: $request) {
177
199
  ...StoreRoute
178
200
  }
179
201
  }`;
180
- var storeWatchUpdatesDocument = `fragment StoreRoute on ContelloRoute {
181
- id
182
- path
183
- target {
184
- __typename
185
- ... on ContelloRouteTargetEntity {
186
- entity {
187
- __typename
188
- ... on ContelloEntityBase {
189
- id
190
- }
191
- }
192
- }
193
- ... on ContelloRouteTargetAsset {
194
- asset {
195
- id
196
- original {
197
- uid
198
- mimeType
199
- }
200
- }
201
- contentDisposition
202
- }
203
- ... on ContelloRouteTargetRedirect {
204
- location
205
- responseCode
206
- }
207
- ... on ContelloRouteTargetText {
208
- content
209
- mimeType
210
- }
211
- }
212
- customHeaders {
213
- name
214
- value
215
- }
216
- }
202
+ var storeWatchUpdatesDocument = `${StoreRouteFragmentSchema}
217
203
  subscription StoreWatchUpdates {
218
204
  contelloUpdatesBatch {
219
205
  events {
@@ -245,6 +231,31 @@ subscription StoreWatchUpdates {
245
231
  }
246
232
  }
247
233
  }`;
234
+ var sources = {
235
+ storeAsset: {
236
+ document: `${MediaFileFragmentSchema}
237
+ ${MediaAssetFragmentSchema}
238
+ ${StoreAssetFragmentSchema}`,
239
+ fragment: "StoreAsset",
240
+ subscription: "contelloAssetsBatch",
241
+ __model: "storeAsset",
242
+ __cardinality: "asset"
243
+ },
244
+ storeI18nMessage: {
245
+ document: StoreI18nMessageFragmentSchema,
246
+ fragment: "StoreI18nMessage",
247
+ subscription: "contelloI18nMessagesBatch",
248
+ __model: "storeI18nMessage",
249
+ __cardinality: "i18nMessage"
250
+ },
251
+ storeRoute: {
252
+ document: StoreRouteFragmentSchema,
253
+ fragment: "StoreRoute",
254
+ subscription: "contelloRoutesBatch",
255
+ __model: "storeRoute",
256
+ __cardinality: "route"
257
+ }
258
+ };
248
259
 
249
260
  // src/lru.ts
250
261
  var import_lru_cache = require("lru-cache");
@@ -272,22 +283,7 @@ function createLruCache(options) {
272
283
  }
273
284
 
274
285
  // src/utils.ts
275
- var import_backoff_rxjs = require("backoff-rxjs");
276
- var import_rxjs = require("rxjs");
277
- var keepalive = (params) => (source) => source.pipe(
278
- (0, import_rxjs.catchError)((error) => {
279
- params?.onError?.(error);
280
- throw error;
281
- }),
282
- (0, import_backoff_rxjs.retryBackoff)({ initialInterval: 100, maxInterval: 5e3 }),
283
- (0, import_rxjs.repeat)({ delay: 0 })
284
- );
285
- function resolveFetchable(value) {
286
- if (value instanceof import_rxjs.Observable) {
287
- return collect(value);
288
- }
289
- return value;
290
- }
286
+ var import_client = require("@contello/client");
291
287
  function createRefresher(fn, onRefreshed, onStart2) {
292
288
  let refreshing = false;
293
289
  let pending = false;
@@ -298,29 +294,17 @@ function createRefresher(fn, onRefreshed, onStart2) {
298
294
  }
299
295
  refreshing = true;
300
296
  onStart2?.();
301
- (0, import_rxjs.defer)(() => fn()).pipe((0, import_backoff_rxjs.retryBackoff)({ initialInterval: 100, maxInterval: 1e4 })).subscribe({
302
- complete: () => {
303
- refreshing = false;
304
- onRefreshed();
305
- if (pending) {
306
- pending = false;
307
- scheduleRefresh();
308
- }
297
+ void (0, import_client.runWithBackoff)(fn).then(() => {
298
+ refreshing = false;
299
+ onRefreshed();
300
+ if (pending) {
301
+ pending = false;
302
+ scheduleRefresh();
309
303
  }
310
304
  });
311
305
  }
312
306
  return scheduleRefresh;
313
307
  }
314
- function collect(observable) {
315
- return new Promise((resolve, reject) => {
316
- const collected = [];
317
- observable.subscribe({
318
- error: reject,
319
- next: (chunk) => collected.push(...chunk),
320
- complete: () => resolve(collected)
321
- });
322
- });
323
- }
324
308
 
325
309
  // src/assets.ts
326
310
  function mapFile(raw) {
@@ -359,10 +343,9 @@ function createAssetsCollection(def, client, updates$) {
359
343
  }, [])
360
344
  )
361
345
  ),
362
- cache,
363
- protection: "freeze"
346
+ cache
364
347
  });
365
- const refresh$ = new import_rxjs2.Subject();
348
+ const refresh$ = (0, import_client2.createAsyncIterableSubject)();
366
349
  let lastRefreshKeys = [];
367
350
  const scheduleRefresh = createRefresher(
368
351
  async () => {
@@ -380,7 +363,7 @@ function createAssetsCollection(def, client, updates$) {
380
363
  () => {
381
364
  }
382
365
  );
383
- updates$.subscribe((batch) => {
366
+ const unsubUpdates = updates$.subscribe((batch) => {
384
367
  if (batch.asset.length === 0) return;
385
368
  for (const event of batch.asset) {
386
369
  projected.delete(event.id);
@@ -388,31 +371,37 @@ function createAssetsCollection(def, client, updates$) {
388
371
  refresh$.next(batch.asset.map((e) => e.id));
389
372
  });
390
373
  return {
391
- refresh$: refresh$.asObservable(),
392
- get(idOrIds) {
393
- return projected.get(idOrIds);
394
- },
395
- upload(data, meta, options) {
396
- return client.upload(data, meta, options);
397
- },
398
- download(fileId) {
399
- return client.download(fileId);
400
- },
401
- proxyHls(path, signal) {
402
- return client.proxyHls(path, signal);
403
- },
404
- refresh() {
405
- scheduleRefresh();
374
+ instance: {
375
+ refresh$,
376
+ get(idOrIds) {
377
+ return projected.get(idOrIds);
378
+ },
379
+ upload(data, meta, options) {
380
+ return client.upload(data, meta, options);
381
+ },
382
+ download(fileId) {
383
+ return client.download(fileId);
384
+ },
385
+ proxyHls(path, signal) {
386
+ return client.proxyHls(path, signal);
387
+ },
388
+ refresh() {
389
+ scheduleRefresh();
390
+ },
391
+ clear() {
392
+ projected.clear();
393
+ }
406
394
  },
407
- clear() {
408
- projected.clear();
395
+ destroy() {
396
+ unsubUpdates();
397
+ refresh$.complete();
409
398
  }
410
399
  };
411
400
  }
412
401
 
413
402
  // src/collection.ts
403
+ var import_client3 = require("@contello/client");
414
404
  var import_projected2 = require("projected");
415
- var import_rxjs3 = require("rxjs");
416
405
 
417
406
  // src/dependency-collector.ts
418
407
  function createDependencyKey(target, id) {
@@ -567,66 +556,115 @@ var DependencyCollector = class {
567
556
  };
568
557
 
569
558
  // src/collection.ts
570
- function createCollection(def, client, updates$, resolver) {
559
+ function fetchCollection(source, client, ids) {
560
+ return (0, import_client3.firstAsync)(
561
+ (0, import_client3.mapAsync)(
562
+ client.subscribe((0, import_client3.createSourceSubscription)(source), { ids }),
563
+ (r) => r.source
564
+ )
565
+ );
566
+ }
567
+ function createCollection(source, options, client, updates$, resolver) {
568
+ const opts = options ?? {};
569
+ const mapFn = opts.map ?? ((item) => item);
571
570
  const _def = {
572
- name: def.name ?? def.model,
573
- model: def.model,
571
+ name: opts.name ?? source.__model,
572
+ model: source.__model,
574
573
  cache: {
575
- ttl: def.cache?.ttl,
576
- eviction: def.cache?.eviction ?? "refresh"
574
+ ttl: opts.cache?.ttl,
575
+ eviction: opts.cache?.eviction ?? "refresh"
577
576
  }
578
577
  };
579
578
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
580
- let timer;
579
+ let ttlTimer;
581
580
  const projected = new import_projected2.ProjectedMap({
582
581
  key: (item) => item.id,
583
- values: () => wrap(
582
+ values: (ids) => wrap(
584
583
  `collection:${_def.name}`,
585
584
  () => (0, import_projected2.maybeThen)(
586
- resolveFetchable(def.fetch(client)),
587
- (rawItems) => (
588
- // maybeAll one day?
589
- Promise.all(
590
- rawItems.map(
591
- (item) => dependencyCollector.createContext(
592
- (ref, register) => (0, import_projected2.maybeThen)(def.map(item, ref), (mapped) => {
593
- register(mapped.id);
594
- return mapped;
595
- })
596
- )
585
+ fetchCollection(source, client, ids),
586
+ (rawItems) => Promise.all(
587
+ rawItems.map(
588
+ (item) => dependencyCollector.createContext(
589
+ (ref, register) => (0, import_projected2.maybeThen)(mapFn(item, ref), (mapped) => {
590
+ register(mapped.id);
591
+ return mapped;
592
+ })
597
593
  )
598
- ).then((items) => {
594
+ )
595
+ ).then((items) => {
596
+ if (ids === void 0) {
599
597
  dependencyCollector.retainOnly(new Set(items.map((item) => item.id)));
600
- return items;
601
- })
602
- )
598
+ } else {
599
+ const returnedIds = new Set(items.map((item) => item.id));
600
+ for (const id of ids) {
601
+ if (!returnedIds.has(id)) {
602
+ dependencyCollector.removeItem(id);
603
+ }
604
+ }
605
+ }
606
+ return items;
607
+ })
603
608
  )
604
609
  ),
605
- protection: "freeze"
610
+ sort: opts.sort
606
611
  });
607
- const refresh$ = new import_rxjs3.Subject();
608
- const scheduleRefresh = createRefresher(
609
- () => projected.refresh(),
610
- () => {
611
- (0, import_projected2.maybeThen)(projected.getAll(), (items) => {
612
- const ids = items.map((item) => item.id);
613
- refresh$.next(ids);
614
- def.onRefresh?.(ids);
615
- if (_def.cache.ttl !== void 0) {
616
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
617
- }
618
- });
619
- },
620
- () => clearTimeout(timer)
621
- );
612
+ const refresh$ = (0, import_client3.createAsyncIterableSubject)();
622
613
  let loaded = false;
623
- updates$.subscribe((batch) => {
614
+ function scheduleTtl() {
615
+ if (_def.cache.ttl === void 0) {
616
+ return;
617
+ }
618
+ clearTimeout(ttlTimer);
619
+ ttlTimer = setTimeout(() => {
620
+ runFullRefresh();
621
+ }, _def.cache.ttl);
622
+ }
623
+ function runFullRefresh() {
624
+ void (0, import_client3.runWithBackoff)(
625
+ () => projected.refresh().then((map) => {
626
+ const ids = [...map.keys()];
627
+ refresh$.next(ids);
628
+ opts.onRefresh?.(ids);
629
+ scheduleTtl();
630
+ })
631
+ );
632
+ }
633
+ function runPartialRefresh(refreshIds, deletedIds) {
634
+ const changedIds = [.../* @__PURE__ */ new Set([...refreshIds, ...deletedIds])];
635
+ if (refreshIds.length === 0) {
636
+ refresh$.next(changedIds);
637
+ opts.onRefresh?.(changedIds);
638
+ return;
639
+ }
640
+ void (0, import_client3.runWithBackoff)(
641
+ () => projected.refresh(refreshIds).then(() => {
642
+ refresh$.next(changedIds);
643
+ opts.onRefresh?.(changedIds);
644
+ })
645
+ );
646
+ }
647
+ const unsubUpdates = updates$.subscribe((batch) => {
624
648
  if (!loaded) {
625
649
  return;
626
650
  }
627
- const hasOwnModel = batch.entity.has(_def.model);
628
- const hasAffectedRefs = batch.events.some((event) => dependencyCollector.getAffectedKeys(event).size > 0);
629
- if (!hasOwnModel && !hasAffectedRefs) {
651
+ const ownEvents = batch.entity.get(_def.model) ?? [];
652
+ const deleted = [];
653
+ const upserted = /* @__PURE__ */ new Set();
654
+ for (const event of ownEvents) {
655
+ if (event.mutation === "delete") {
656
+ deleted.push(event.id);
657
+ } else {
658
+ upserted.add(event.id);
659
+ }
660
+ }
661
+ const depAffected = /* @__PURE__ */ new Set();
662
+ for (const event of batch.events) {
663
+ for (const id of dependencyCollector.getAffectedKeys(event)) {
664
+ depAffected.add(id);
665
+ }
666
+ }
667
+ if (deleted.length === 0 && upserted.size === 0 && depAffected.size === 0) {
630
668
  return;
631
669
  }
632
670
  if (_def.cache.eviction === "clear") {
@@ -634,11 +672,21 @@ function createCollection(def, client, updates$, resolver) {
634
672
  projected.clear();
635
673
  return;
636
674
  }
637
- scheduleRefresh();
675
+ for (const id of deleted) {
676
+ dependencyCollector.removeItem(id);
677
+ }
678
+ if (deleted.length > 0) {
679
+ projected.delete(deleted);
680
+ }
681
+ const refreshIds = /* @__PURE__ */ new Set([...upserted, ...depAffected]);
682
+ for (const id of deleted) {
683
+ refreshIds.delete(id);
684
+ }
685
+ runPartialRefresh([...refreshIds], deleted);
638
686
  });
639
687
  const instance = {
640
688
  name: _def.name,
641
- refresh$: refresh$.asObservable(),
689
+ refresh$,
642
690
  get(idOrIds) {
643
691
  return projected.get(idOrIds);
644
692
  },
@@ -646,21 +694,32 @@ function createCollection(def, client, updates$, resolver) {
646
694
  return projected.getAll();
647
695
  },
648
696
  refresh() {
649
- scheduleRefresh();
697
+ runFullRefresh();
650
698
  },
651
699
  async load() {
652
- const items = await projected.getAll();
700
+ const map = await projected.refresh();
653
701
  loaded = true;
654
- if (_def.cache.ttl !== void 0) {
655
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
656
- }
657
- def.onLoad?.(items.map((item) => item.id));
702
+ scheduleTtl();
703
+ opts.onLoad?.([...map.keys()]);
704
+ }
705
+ };
706
+ return {
707
+ instance,
708
+ destroy() {
709
+ unsubUpdates();
710
+ clearTimeout(ttlTimer);
711
+ refresh$.complete();
658
712
  }
659
713
  };
660
- return instance;
661
714
  }
662
- function createCollectionSync(def, client, updates$, resolver) {
663
- const base = createCollection(def, client, updates$, resolver);
715
+ function createCollectionSync(source, options, client, updates$, resolver) {
716
+ const { instance: base, destroy } = createCollection(
717
+ source,
718
+ options,
719
+ client,
720
+ updates$,
721
+ resolver
722
+ );
664
723
  function assertSync(value, method) {
665
724
  if (value instanceof Promise) {
666
725
  throw new Error(`collection "${base.name}".${method}() is not initialized yet \u2014 call collection.load() first`);
@@ -668,19 +727,22 @@ function createCollectionSync(def, client, updates$, resolver) {
668
727
  return value;
669
728
  }
670
729
  return {
671
- ...base,
672
- get(idOrIds) {
673
- return assertSync(base.get(idOrIds), "get");
730
+ instance: {
731
+ ...base,
732
+ get(idOrIds) {
733
+ return assertSync(base.get(idOrIds), "get");
734
+ },
735
+ getAll() {
736
+ return assertSync(base.getAll(), "getAll");
737
+ }
674
738
  },
675
- getAll() {
676
- return assertSync(base.getAll(), "getAll");
677
- }
739
+ destroy
678
740
  };
679
741
  }
680
742
 
681
743
  // src/i18n.ts
744
+ var import_client4 = require("@contello/client");
682
745
  var import_projected3 = require("projected");
683
- var import_rxjs4 = require("rxjs");
684
746
  function toGqlMessageInput(msg) {
685
747
  return {
686
748
  token: msg.token,
@@ -696,8 +758,13 @@ function createI18nMessagesCollection(def, client, updates$) {
696
758
  key: (msg) => msg.id,
697
759
  values: () => wrap(
698
760
  `i18n:${def.collection}`,
699
- () => collect(
700
- client.subscribe(storeGetI18nMessagesDocument, { collection: def.collection }).pipe((0, import_rxjs4.map)((data) => data.contelloI18nMessagesBatch))
761
+ () => (0, import_client4.collectAsync)(
762
+ (0, import_client4.mapAsync)(
763
+ client.subscribe(storeGetI18nMessagesDocument, {
764
+ collection: def.collection
765
+ }),
766
+ (data) => data.contelloI18nMessagesBatch
767
+ )
701
768
  ).then(
702
769
  (msgs) => msgs.map((msg) => ({
703
770
  id: msg.id,
@@ -705,10 +772,9 @@ function createI18nMessagesCollection(def, client, updates$) {
705
772
  translations: new Map(msg.translations.map((t) => [t.language, t.value]))
706
773
  }))
707
774
  )
708
- ),
709
- protection: "freeze"
775
+ )
710
776
  });
711
- const refresh$ = new import_rxjs4.Subject();
777
+ const refresh$ = (0, import_client4.createAsyncIterableSubject)();
712
778
  const scheduleRefresh = createRefresher(
713
779
  () => projected.refresh(),
714
780
  () => {
@@ -719,13 +785,13 @@ function createI18nMessagesCollection(def, client, updates$) {
719
785
  () => {
720
786
  }
721
787
  );
722
- updates$.subscribe((batch) => {
788
+ const unsubUpdates = updates$.subscribe((batch) => {
723
789
  if (batch.i18nMessage.length > 0) {
724
790
  scheduleRefresh();
725
791
  }
726
792
  });
727
793
  return {
728
- refresh$: refresh$.asObservable(),
794
+ refresh$,
729
795
  get(idOrIds) {
730
796
  return projected.get(idOrIds);
731
797
  },
@@ -741,20 +807,26 @@ function createI18nMessagesCollection(def, client, updates$) {
741
807
  }).then(() => {
742
808
  })
743
809
  );
810
+ },
811
+ destroy() {
812
+ unsubUpdates();
813
+ refresh$.complete();
744
814
  }
745
815
  };
746
816
  }
747
817
 
748
818
  // src/lazy-collection.ts
819
+ var import_client5 = require("@contello/client");
749
820
  var import_projected4 = require("projected");
750
- var import_rxjs5 = require("rxjs");
751
- function createLazyCollection(def, client, updates$, resolver) {
821
+ function createLazyCollection(source, options, client, updates$, resolver) {
822
+ const opts = options ?? {};
823
+ const mapFn = opts.map ?? ((item) => item);
752
824
  const _def = {
753
- name: def.name ?? def.model,
754
- model: def.model,
825
+ name: opts.name ?? source.__model,
826
+ model: source.__model,
755
827
  cache: {
756
- max: def.cache?.max ?? 1e3,
757
- ttl: def.cache?.ttl
828
+ max: opts.cache?.max ?? 1e3,
829
+ ttl: opts.cache?.ttl
758
830
  }
759
831
  };
760
832
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
@@ -768,11 +840,18 @@ function createLazyCollection(def, client, updates$, resolver) {
768
840
  values: (keys) => wrap(
769
841
  `lazy-collection:${_def.name}`,
770
842
  () => (0, import_projected4.maybeThen)(
771
- resolveFetchable(def.fetch(keys, client)),
843
+ (0, import_client5.firstAsync)(
844
+ (0, import_client5.mapAsync)(
845
+ client.subscribe((0, import_client5.createSourceSubscription)(source), {
846
+ ids: keys
847
+ }),
848
+ (r) => r.source
849
+ )
850
+ ),
772
851
  (rawItems) => Promise.all(
773
852
  rawItems.map(
774
853
  (item) => dependencyCollector.createContext(
775
- (ref, register) => (0, import_projected4.maybeThen)(def.map(item, ref), (mapped) => {
854
+ (ref, register) => (0, import_projected4.maybeThen)(mapFn(item, ref), (mapped) => {
776
855
  register(mapped.id);
777
856
  return mapped;
778
857
  })
@@ -781,10 +860,9 @@ function createLazyCollection(def, client, updates$, resolver) {
781
860
  )
782
861
  )
783
862
  ),
784
- cache,
785
- protection: "freeze"
863
+ cache
786
864
  });
787
- const refresh$ = new import_rxjs5.Subject();
865
+ const refresh$ = (0, import_client5.createAsyncIterableSubject)();
788
866
  let lastRefreshKeys = [];
789
867
  const scheduleRefresh = createRefresher(
790
868
  async () => {
@@ -797,13 +875,13 @@ function createLazyCollection(def, client, updates$, resolver) {
797
875
  () => {
798
876
  if (lastRefreshKeys.length > 0) {
799
877
  refresh$.next(lastRefreshKeys);
800
- def.onRefresh?.(lastRefreshKeys);
878
+ opts.onRefresh?.(lastRefreshKeys);
801
879
  }
802
880
  },
803
881
  () => {
804
882
  }
805
883
  );
806
- updates$.subscribe((batch) => {
884
+ const unsubUpdates = updates$.subscribe((batch) => {
807
885
  const evicted = /* @__PURE__ */ new Set();
808
886
  const ownModelEvents = batch.entity.get(_def.model);
809
887
  if (ownModelEvents) {
@@ -823,21 +901,28 @@ function createLazyCollection(def, client, updates$, resolver) {
823
901
  }
824
902
  const ids = [...evicted];
825
903
  refresh$.next(ids);
826
- def.onRefresh?.(ids);
904
+ opts.onRefresh?.(ids);
827
905
  }
828
906
  });
907
+ void scheduleRefresh;
829
908
  return {
830
- name: _def.name,
831
- refresh$: refresh$.asObservable(),
832
- get(idOrIds) {
833
- return projected.get(idOrIds);
834
- },
835
- refresh() {
836
- scheduleRefresh();
909
+ instance: {
910
+ name: _def.name,
911
+ refresh$,
912
+ get(idOrIds) {
913
+ return projected.get(idOrIds);
914
+ },
915
+ refresh() {
916
+ scheduleRefresh();
917
+ },
918
+ clear() {
919
+ dependencyCollector.clear();
920
+ projected.clear();
921
+ }
837
922
  },
838
- clear() {
839
- dependencyCollector.clear();
840
- projected.clear();
923
+ destroy() {
924
+ unsubUpdates();
925
+ refresh$.complete();
841
926
  }
842
927
  };
843
928
  }
@@ -881,8 +966,8 @@ var ModelResolver = class {
881
966
  };
882
967
 
883
968
  // src/routes.ts
969
+ var import_client6 = require("@contello/client");
884
970
  var import_projected5 = require("projected");
885
- var import_rxjs6 = require("rxjs");
886
971
 
887
972
  // src/routes-mapping.ts
888
973
  function mapRoute(raw, resolver) {
@@ -1017,10 +1102,9 @@ function createRoutesCollection(def, client, updates$, resolver) {
1017
1102
  paths.length > 0 ? client.execute(storeGetRoutesDocument, { request: { paths } }).then((data) => collectRoutes(data, (r) => PATH_PREFIX + r.path, resolver)) : Promise.resolve([])
1018
1103
  ]).then(([byIds, byPaths]) => [...byIds, ...byPaths]);
1019
1104
  }),
1020
- cache,
1021
- protection: "freeze"
1105
+ cache
1022
1106
  });
1023
- const refresh$ = new import_rxjs6.Subject();
1107
+ const refresh$ = (0, import_client6.createAsyncIterableSubject)();
1024
1108
  let lastRefreshKeys = [];
1025
1109
  const scheduleRefresh = createRefresher(
1026
1110
  async () => {
@@ -1038,7 +1122,7 @@ function createRoutesCollection(def, client, updates$, resolver) {
1038
1122
  () => {
1039
1123
  }
1040
1124
  );
1041
- updates$.subscribe((batch) => {
1125
+ const unsubUpdates = updates$.subscribe((batch) => {
1042
1126
  const evicted = [];
1043
1127
  for (const event of batch.route) {
1044
1128
  const idKey = ID_PREFIX + event.id;
@@ -1047,7 +1131,7 @@ function createRoutesCollection(def, client, updates$, resolver) {
1047
1131
  evicted.push(event.id);
1048
1132
  } else {
1049
1133
  if (cache.has(idKey)) {
1050
- cache.set(idKey, Object.freeze(event.after));
1134
+ cache.set(idKey, event.after);
1051
1135
  }
1052
1136
  evicted.push(event.after.path);
1053
1137
  }
@@ -1057,38 +1141,46 @@ function createRoutesCollection(def, client, updates$, resolver) {
1057
1141
  }
1058
1142
  });
1059
1143
  return {
1060
- refresh$: refresh$.asObservable(),
1061
- get(idOrIds) {
1062
- if (Array.isArray(idOrIds)) {
1063
- return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1064
- }
1065
- return projected.get(ID_PREFIX + idOrIds);
1066
- },
1067
- getByPath(pathOrPaths) {
1068
- if (Array.isArray(pathOrPaths)) {
1069
- return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1144
+ instance: {
1145
+ refresh$,
1146
+ get(idOrIds) {
1147
+ if (Array.isArray(idOrIds)) {
1148
+ return projected.get(idOrIds.map((id) => ID_PREFIX + id));
1149
+ }
1150
+ return projected.get(ID_PREFIX + idOrIds);
1151
+ },
1152
+ getByPath(pathOrPaths) {
1153
+ if (Array.isArray(pathOrPaths)) {
1154
+ return projected.get(pathOrPaths.map((p) => PATH_PREFIX + p));
1155
+ }
1156
+ return projected.get(PATH_PREFIX + pathOrPaths);
1157
+ },
1158
+ refresh() {
1159
+ scheduleRefresh();
1160
+ },
1161
+ clear() {
1162
+ projected.clear();
1070
1163
  }
1071
- return projected.get(PATH_PREFIX + pathOrPaths);
1072
1164
  },
1073
- refresh() {
1074
- scheduleRefresh();
1075
- },
1076
- clear() {
1077
- projected.clear();
1165
+ destroy() {
1166
+ unsubUpdates();
1167
+ refresh$.complete();
1078
1168
  }
1079
1169
  };
1080
1170
  }
1081
1171
 
1082
1172
  // src/singleton.ts
1173
+ var import_client7 = require("@contello/client");
1083
1174
  var import_projected6 = require("projected");
1084
- var import_rxjs7 = require("rxjs");
1085
- function createSingleton(def, client, updates$, resolver) {
1175
+ function createSingleton(source, options, client, updates$, resolver) {
1176
+ const opts = options ?? {};
1177
+ const mapFn = opts.map ?? ((item) => item);
1086
1178
  const _def = {
1087
- name: def.name ?? def.model,
1088
- model: def.model,
1179
+ name: opts.name ?? source.__model,
1180
+ model: source.__model,
1089
1181
  cache: {
1090
- ttl: def.cache?.ttl,
1091
- eviction: def.cache?.eviction ?? "refresh"
1182
+ ttl: opts.cache?.ttl,
1183
+ eviction: opts.cache?.eviction ?? "refresh"
1092
1184
  }
1093
1185
  };
1094
1186
  const dependencyCollector = new DependencyCollector(_def.model, resolver);
@@ -1098,23 +1190,27 @@ function createSingleton(def, client, updates$, resolver) {
1098
1190
  value: () => wrap(
1099
1191
  `singleton:${_def.name}`,
1100
1192
  () => (0, import_projected6.maybeThen)(
1101
- def.fetch(client),
1193
+ (0, import_client7.firstAsync)(
1194
+ (0, import_client7.mapAsync)(
1195
+ client.subscribe((0, import_client7.createSourceSubscription)(source)),
1196
+ (r) => r.source
1197
+ )
1198
+ ),
1102
1199
  (raw) => dependencyCollector.createContext(
1103
- (ref, register) => (0, import_projected6.maybeThen)(def.map(raw, ref), (mapped) => {
1200
+ (ref, register) => (0, import_projected6.maybeThen)(mapFn(raw, ref), (mapped) => {
1104
1201
  register(itemKey);
1105
1202
  return mapped;
1106
1203
  })
1107
1204
  )
1108
1205
  )
1109
- ),
1110
- protection: "freeze"
1206
+ )
1111
1207
  });
1112
- const refresh$ = new import_rxjs7.Subject();
1208
+ const refresh$ = (0, import_client7.createAsyncIterableSubject)();
1113
1209
  const scheduleRefresh = createRefresher(
1114
1210
  () => projected.refresh(),
1115
1211
  () => {
1116
1212
  refresh$.next();
1117
- def.onRefresh?.();
1213
+ opts.onRefresh?.();
1118
1214
  if (_def.cache.ttl !== void 0) {
1119
1215
  timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1120
1216
  }
@@ -1122,7 +1218,7 @@ function createSingleton(def, client, updates$, resolver) {
1122
1218
  () => clearTimeout(timer)
1123
1219
  );
1124
1220
  let loaded = false;
1125
- updates$.subscribe((batch) => {
1221
+ const unsubUpdates = updates$.subscribe((batch) => {
1126
1222
  if (!loaded) {
1127
1223
  return;
1128
1224
  }
@@ -1139,45 +1235,61 @@ function createSingleton(def, client, updates$, resolver) {
1139
1235
  scheduleRefresh();
1140
1236
  });
1141
1237
  return {
1142
- name: _def.name,
1143
- refresh$: refresh$.asObservable(),
1144
- get() {
1145
- return projected.get();
1146
- },
1147
- refresh() {
1148
- scheduleRefresh();
1149
- },
1150
- async load() {
1151
- await projected.get();
1152
- loaded = true;
1153
- if (_def.cache.ttl !== void 0) {
1154
- timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1238
+ instance: {
1239
+ name: _def.name,
1240
+ refresh$,
1241
+ get() {
1242
+ return projected.get();
1243
+ },
1244
+ refresh() {
1245
+ scheduleRefresh();
1246
+ },
1247
+ async load() {
1248
+ await projected.get();
1249
+ loaded = true;
1250
+ if (_def.cache.ttl !== void 0) {
1251
+ timer = setTimeout(scheduleRefresh, _def.cache.ttl);
1252
+ }
1253
+ opts.onLoad?.();
1155
1254
  }
1156
- def.onLoad?.();
1255
+ },
1256
+ destroy() {
1257
+ unsubUpdates();
1258
+ clearTimeout(timer);
1259
+ refresh$.complete();
1157
1260
  }
1158
1261
  };
1159
1262
  }
1160
- function createSingletonSync(def, client, updates$, resolver) {
1161
- const base = createSingleton(def, client, updates$, resolver);
1263
+ function createSingletonSync(source, options, client, updates$, resolver) {
1264
+ const { instance: base, destroy } = createSingleton(
1265
+ source,
1266
+ options,
1267
+ client,
1268
+ updates$,
1269
+ resolver
1270
+ );
1162
1271
  return {
1163
- ...base,
1164
- get() {
1165
- const result = base.get();
1166
- if (result instanceof Promise) {
1167
- throw new Error(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1272
+ instance: {
1273
+ ...base,
1274
+ get() {
1275
+ const result = base.get();
1276
+ if (result instanceof Promise) {
1277
+ throw new Error(`singleton "${base.name}" is not initialized yet \u2014 call singleton.load() first`);
1278
+ }
1279
+ return result;
1168
1280
  }
1169
- return result;
1170
- }
1281
+ },
1282
+ destroy
1171
1283
  };
1172
1284
  }
1173
1285
 
1174
1286
  // src/watcher.ts
1175
- var import_rxjs8 = require("rxjs");
1176
- function addRouteByModel(map3, entityType, event) {
1177
- let list = map3.get(entityType);
1287
+ var import_client8 = require("@contello/client");
1288
+ function addRouteByModel(map, entityType, event) {
1289
+ let list = map.get(entityType);
1178
1290
  if (!list) {
1179
1291
  list = [];
1180
- map3.set(entityType, list);
1292
+ map.set(entityType, list);
1181
1293
  }
1182
1294
  list.push(event);
1183
1295
  }
@@ -1262,33 +1374,42 @@ function mapEvent(raw, resolver) {
1262
1374
  }
1263
1375
  }
1264
1376
  function createInternalWatcher(client, resolver) {
1265
- const subject = new import_rxjs8.Subject();
1266
- let subscription;
1267
- const updates$ = subject.asObservable().pipe((0, import_rxjs8.share)());
1377
+ const updates$ = (0, import_client8.createAsyncIterableSubject)();
1378
+ let controller;
1268
1379
  return {
1269
1380
  updates$,
1270
1381
  start() {
1271
- if (subscription) {
1382
+ if (controller) {
1272
1383
  return;
1273
1384
  }
1274
- const source$ = client.subscribe(storeWatchUpdatesDocument).pipe(
1275
- keepalive(),
1276
- (0, import_rxjs8.map)(
1277
- (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => mapEvent(e, resolver)).filter((e) => e !== void 0)
1278
- ),
1279
- (0, import_rxjs8.filter)((events) => events.length > 0),
1280
- (0, import_rxjs8.map)(createUpdateBatch)
1281
- );
1385
+ controller = new AbortController();
1386
+ const signal = controller.signal;
1282
1387
  wrap("watcher:start", () => {
1283
- subscription = source$.subscribe({
1284
- next: (batch) => subject.next(batch),
1285
- error: (err) => subject.error(err)
1286
- });
1388
+ void (async () => {
1389
+ const source = (0, import_client8.asyncKeepalive)(
1390
+ () => client.subscribe(storeWatchUpdatesDocument),
1391
+ signal
1392
+ );
1393
+ const events = (0, import_client8.mapAsync)(
1394
+ source,
1395
+ (data) => (data.contelloUpdatesBatch?.events ?? []).map((e) => mapEvent(e, resolver)).filter((e) => e !== void 0)
1396
+ );
1397
+ for await (const list of events) {
1398
+ if (signal.aborted) {
1399
+ return;
1400
+ }
1401
+ if (list.length === 0) {
1402
+ continue;
1403
+ }
1404
+ updates$.next(createUpdateBatch(list));
1405
+ }
1406
+ })();
1287
1407
  });
1288
1408
  },
1289
1409
  stop() {
1290
- subscription?.unsubscribe();
1291
- subscription = void 0;
1410
+ controller?.abort();
1411
+ controller = void 0;
1412
+ updates$.complete();
1292
1413
  }
1293
1414
  };
1294
1415
  }
@@ -1298,64 +1419,152 @@ var Store = class {
1298
1419
  _client;
1299
1420
  _resolver;
1300
1421
  _watcher;
1422
+ _schema;
1423
+ _cleanups = [];
1424
+ /**
1425
+ * Multicast update-batch stream from the watcher. Consume with `for await (const batch of updates$)`;
1426
+ * each iteration starts an independent fan-out from the shared source.
1427
+ */
1301
1428
  updates$;
1302
1429
  constructor(options) {
1303
- const { url, project, token, operations } = options;
1304
- this._client = (0, import_client.createContelloClient)({
1430
+ const { url, project, token, schema } = options;
1431
+ this._schema = schema;
1432
+ this._client = (0, import_client9.createContelloClient)({
1305
1433
  url,
1306
1434
  project,
1307
1435
  token,
1308
- operations,
1436
+ schema,
1309
1437
  connections: options.connections,
1310
1438
  onConnected: options.onConnected,
1311
1439
  onReconnecting: options.onReconnecting,
1312
1440
  onError: options.onError,
1313
1441
  connectionEvents: options.connectionEvents
1314
1442
  });
1315
- this._resolver = new ModelResolver(options.models);
1443
+ this._resolver = new ModelResolver(schema?.models);
1316
1444
  this._watcher = createInternalWatcher(this._client, this._resolver);
1317
1445
  this.updates$ = this._watcher.updates$;
1318
1446
  this.ping = () => this._client.ping();
1319
1447
  }
1448
+ get client() {
1449
+ return this._client;
1450
+ }
1320
1451
  async init() {
1321
1452
  await wrap("store:init", () => this._client.init());
1322
1453
  this._watcher.start();
1323
1454
  }
1324
1455
  async destroy() {
1456
+ for (const fn of this._cleanups.splice(0)) {
1457
+ try {
1458
+ fn();
1459
+ } catch {
1460
+ }
1461
+ }
1325
1462
  this._watcher.stop();
1326
1463
  await wrap("store:destroy", () => this._client.destroy());
1327
1464
  }
1328
- defineSingleton(def) {
1329
- return createSingleton(def, this._client, this._watcher.updates$, this._resolver);
1465
+ /** Resolve a string key (looked up via `schema.sources`) or a SourceDef directly to a SourceDef. */
1466
+ _resolveSource(sourceOrKey) {
1467
+ if (typeof sourceOrKey !== "string") {
1468
+ return sourceOrKey;
1469
+ }
1470
+ const sources2 = this._schema?.sources;
1471
+ const source = sources2?.[sourceOrKey];
1472
+ if (!source) {
1473
+ throw new Error(`@contello/store: no source named "${sourceOrKey}" in schema.sources`);
1474
+ }
1475
+ return source;
1330
1476
  }
1331
- defineSingletonSync(def) {
1332
- return createSingletonSync(def, this._client, this._watcher.updates$, this._resolver);
1477
+ // --- singleton ---
1478
+ defineSingleton(sourceOrKey, options) {
1479
+ const source = this._resolveSource(sourceOrKey);
1480
+ const { instance, destroy } = createSingleton(
1481
+ source,
1482
+ options,
1483
+ this._client,
1484
+ this._watcher.updates$,
1485
+ this._resolver
1486
+ );
1487
+ this._cleanups.push(destroy);
1488
+ return instance;
1333
1489
  }
1334
- defineCollection(def) {
1335
- return createCollection(def, this._client, this._watcher.updates$, this._resolver);
1490
+ defineSingletonSync(sourceOrKey, options) {
1491
+ const source = this._resolveSource(sourceOrKey);
1492
+ const { instance, destroy } = createSingletonSync(
1493
+ source,
1494
+ options,
1495
+ this._client,
1496
+ this._watcher.updates$,
1497
+ this._resolver
1498
+ );
1499
+ this._cleanups.push(destroy);
1500
+ return instance;
1336
1501
  }
1337
- defineCollectionSync(def) {
1338
- return createCollectionSync(def, this._client, this._watcher.updates$, this._resolver);
1502
+ // --- collection ---
1503
+ defineCollection(sourceOrKey, options) {
1504
+ const source = this._resolveSource(sourceOrKey);
1505
+ const { instance, destroy } = createCollection(
1506
+ source,
1507
+ options,
1508
+ this._client,
1509
+ this._watcher.updates$,
1510
+ this._resolver
1511
+ );
1512
+ this._cleanups.push(destroy);
1513
+ return instance;
1339
1514
  }
1340
- defineLazyCollection(def) {
1341
- return createLazyCollection(def, this._client, this._watcher.updates$, this._resolver);
1515
+ defineCollectionSync(sourceOrKey, options) {
1516
+ const source = this._resolveSource(sourceOrKey);
1517
+ const { instance, destroy } = createCollectionSync(
1518
+ source,
1519
+ options,
1520
+ this._client,
1521
+ this._watcher.updates$,
1522
+ this._resolver
1523
+ );
1524
+ this._cleanups.push(destroy);
1525
+ return instance;
1342
1526
  }
1527
+ // --- lazy collection ---
1528
+ defineLazyCollection(sourceOrKey, options) {
1529
+ const source = this._resolveSource(sourceOrKey);
1530
+ const { instance, destroy } = createLazyCollection(
1531
+ source,
1532
+ options,
1533
+ this._client,
1534
+ this._watcher.updates$,
1535
+ this._resolver
1536
+ );
1537
+ this._cleanups.push(destroy);
1538
+ return instance;
1539
+ }
1540
+ // --- assets / routes / i18n (no source — built-ins) ---
1343
1541
  defineAssets(options) {
1344
- return createAssetsCollection(options, this._client, this._watcher.updates$);
1542
+ const { instance, destroy } = createAssetsCollection(options, this._client, this._watcher.updates$);
1543
+ this._cleanups.push(destroy);
1544
+ return instance;
1345
1545
  }
1346
1546
  defineRoutes(options) {
1347
- return createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
1547
+ const { instance, destroy } = createRoutesCollection(options, this._client, this._watcher.updates$, this._resolver);
1548
+ this._cleanups.push(destroy);
1549
+ return instance;
1348
1550
  }
1349
1551
  defineI18nMessages(def) {
1350
- return createI18nMessagesCollection(def, this._client, this._watcher.updates$);
1552
+ const result = createI18nMessagesCollection(def, this._client, this._watcher.updates$);
1553
+ this._cleanups.push(result.destroy);
1554
+ return result;
1351
1555
  }
1352
1556
  ping;
1353
1557
  };
1354
1558
  function createStore(options) {
1355
1559
  return new Store(options);
1356
1560
  }
1561
+
1562
+ // src/index.ts
1563
+ var import_projected7 = require("projected");
1357
1564
  // Annotate the CommonJS export names for ESM import in node:
1358
1565
  0 && (module.exports = {
1359
1566
  Store,
1360
- createStore
1567
+ createStore,
1568
+ maybeCatch,
1569
+ maybeThen
1361
1570
  });